@@ -15,70 +15,33 @@ import System.Random (randomRIO)
1515
1616getRandomParagraph :: Text -> Text -> Int -> Handler (Entity TextParagraph )
1717getRandomParagraph era source book = do
18- res <-
19- runDB $
20- rawSql
21- " SELECT MIN(id), MAX(id) \
22- \FROM text_paragraph \
23- \WHERE era = ? \
24- \ AND source = ? \
25- \ AND book = ?"
26- [ toPersistValue era,
27- toPersistValue source,
28- toPersistValue book
29- ]
30- pair <- case res of
31- [(Single mMinId, Single mMaxId)] ->
32- let minId = fromMaybe (error " no rows" ) mMinId
33- maxId = fromMaybe minId mMaxId
34- in return (minId, maxId)
35- _ -> notFound
36- let (minId, maxId) = pair
37- rnd <- liftIO $ randomRIO (minId, maxId)
38- let baseFilters =
18+ let filters =
3919 [ TextParagraphEra ==. era,
4020 TextParagraphSource ==. source,
4121 TextParagraphBook ==. book
4222 ]
43- mEnt <-
44- runDB $
45- selectFirst
46- (baseFilters ++ [TextParagraphId >=. toSqlKey rnd])
47- [Asc TextParagraphId ]
48- case mEnt of
49- Just ent -> return ent
50- Nothing -> do
51- mEnt2 <-
52- runDB $
53- selectFirst
54- baseFilters
55- [Asc TextParagraphId ]
56- maybe notFound return mEnt2
23+ total <- runDB $ count filters
24+ when (total == 0 ) notFound
25+
26+ idx <- liftIO $ randomRIO (0 , total - 1 )
27+
28+ results <- runDB $ selectList filters [OffsetBy idx, LimitTo 1 ]
29+ case results of
30+ [ent] -> return ent
31+ _ -> error " No paragraph found for this era."
5732
5833getRandomNewText :: Text -> Handler (Entity TextParagraph )
5934getRandomNewText era = do
60- App {appMinMaxByEra = cacheRef} <- getYesod
61- cache <- liftIO $ readIORef cacheRef
62- case Map. lookup era cache of
63- Nothing -> notFound
64- Just (minId, maxId) -> do
65- rnd <- liftIO $ randomRIO (minId, maxId)
66- mEnt <-
67- runDB $
68- selectFirst
69- [ TextParagraphEra ==. era,
70- TextParagraphId >=. toSqlKey rnd
71- ]
72- [Asc TextParagraphId ]
73- case mEnt of
74- Just ent -> return ent
75- Nothing -> do
76- mEnt2 <-
77- runDB $
78- selectFirst
79- [TextParagraphEra ==. era]
80- [Asc TextParagraphId ]
81- maybe notFound return mEnt2
35+ let filters = [TextParagraphEra ==. era]
36+ total <- runDB $ count filters
37+ when (total == 0 ) notFound
38+
39+ idx <- liftIO $ randomRIO (0 , total - 1 )
40+
41+ results <- runDB $ selectList filters [OffsetBy idx, LimitTo 1 ]
42+ case results of
43+ [ent] -> return ent
44+ _ -> error " No paragraph found for this era."
8245
8346getCustomText :: UserId -> Text -> Handler ByteString
8447getCustomText userId filename = do
0 commit comments