@@ -56,7 +56,8 @@ module Data.Query (
5656 createUser,
5757 tryActivateToken,
5858 deactivateToken,
59− searchUsers
59+ searchUsers,
60+ searchTags
6061 ) where
6162
6263import Squeal.PostgreSQL
@@ -353,7 +354,7 @@ getChannelPostsQ lim dir uIds tags = getLastPostsQ
353354 Just uIdsQ -> (`in_` uIdsQ)
354355 Nothing -> const $ false
355356
356−getTagsQ :: Query Schema '[] (RowPG (Only String))
357+getTagsQ :: Query Schema params (RowPG (Only String))
357358getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
358359 from (table #posts)
359360
@@ -555,6 +556,29 @@ searchUsersQ = select (
555556 ])
556557 query = tsQuery' (param @1)
557558
559+tagsByFrquencyQ :: Query Schema params '["tag" ::: 'NotNull (PG Text), "count" ::: 'NotNull 'PGint8]
560+tagsByFrquencyQ = select
561+ (#fromOnly `as` #tag :* count #fromOnly `as` #count)
562+ (from (subquery $ getTagsQ `As` #tt) &
563+ groupBy #fromOnly)
564+
565+getNpopularTagsQ :: Limit -> Query Schema param (RowPG (Only Text))
566+getNpopularTagsQ lim = select (#tag `as` #fromOnly)
567+ (from (subquery $ tagsByFrquencyQ `As` #tt) &
568+ orderBy [#count & Desc] &
569+ limit lim)
570+
571+
572+searchTagsQ :: Query Schema (TuplePG (Only Text)) (RowPG (Only Text))
573+searchTagsQ = select (#tag `as` #fromOnly) $
574+ from (subquery (tagsByFrquencyQ `As` #tt)) &
575+ where_ (vector @@ query) &
576+ orderBy [#count & Desc] &
577+ limit 100
578+ where
579+ query = tsQuery' (param @1)
580+ vector = tsVector' #tag
581+
558582tsRankCd
559583 :: Expression schema from grouping params ('NotNull 'PGtext)
560584 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -876,8 +900,9 @@ deleteNamedChannel uId cId = commitedTransactionallyUpdate $ do
876900 _ <- manipulateParams deleteNamedChannelQ (Only cId)
877901 return ()
878902
879−getTags :: StaticPQ [String]
880−getTags = map fromOnly <$> (runQuery getTagsQ >>= getRows)
903+-- Returns n most popular
904+getTags :: Limit -> StaticPQ [String]
905+getTags lim = map fromOnly <$> (runQuery (getNpopularTagsQ lim) >>= getRows)
881906
882907getDialogs
883908 :: UserId
@@ -964,6 +989,11 @@ searchUsers :: T.Text -> StaticPQ [User Faculty]
964989searchUsers query =
965990 map rowToUser <$> (runQueryParams searchUsersQ (Only . queryFromText $ query) >>= getRows)
966991
992+searchTags :: T.Text -> StaticPQ [Text]
993+searchTags query = map fromOnly <$>
994+ (runQueryParams searchTagsQ
995+ (Only . (<> ":*") . T.strip $ query) >>= getRows)
996+
967997createToken :: Token -> StaticPQ ()
968998createToken token = void $ manipulateParams createTokenQ token
969999