]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/TSN/XML/EarlyLine.hs
796418f716b865c66afa38b1ab6b38e4f1bbf2bc
[dead/htsn-import.git] / src / TSN / XML / EarlyLine.hs
1 {-# LANGUAGE DeriveGeneric #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# LANGUAGE GADTs #-}
4 {-# LANGUAGE QuasiQuotes #-}
5 {-# LANGUAGE RecordWildCards #-}
6 {-# LANGUAGE TemplateHaskell #-}
7 {-# LANGUAGE TypeFamilies #-}
8
9 -- | Parse TSN XML for the DTD \"earlylineXML.dtd\". For that DTD,
10 -- each \<message\> element contains a bunch of \<date\>s, and those
11 -- \<date\>s contain a single \<game\>. In the database, we merge
12 -- the date info into the games, and key the games to the messages.
13 --
14 -- Real life is not so simple, however. There is another module,
15 -- "TSN.XML.MLBEarlyLine" that is something of a subclass of this
16 -- one. It contains early lines, but only for MLB games. The data
17 -- types and XML schema are /almost/ the same, but TSN like to make
18 -- things difficult.
19 --
20 -- A full list of the differences is given in that module. In this
21 -- one, we mention where data types have been twerked a little to
22 -- support the second document type.
23 --
24 module TSN.XML.EarlyLine (
25 EarlyLine, -- Used in TSN.XML.MLBEarlyLine
26 EarlyLineGame, -- Used in TSN.XML.MLBEarlyLine
27 dtd,
28 pickle_message,
29 -- * Tests
30 early_line_tests,
31 -- * WARNING: these are private but exported to silence warnings
32 EarlyLineConstructor(..),
33 EarlyLineGameConstructor(..) )
34 where
35
36 -- System imports.
37 import Control.Monad ( join )
38 import Data.Time ( UTCTime(..) )
39 import Data.Tuple.Curry ( uncurryN )
40 import qualified Data.Vector.HFixed as H ( HVector, convert )
41 import Database.Groundhog (
42 countAll,
43 deleteAll,
44 insert_,
45 migrate )
46 import Database.Groundhog.Core ( DefaultKey )
47 import Database.Groundhog.Generic ( runDbConn, runMigrationSilent )
48 import Database.Groundhog.Sqlite ( withSqliteConn )
49 import Database.Groundhog.TH (
50 groundhog,
51 mkPersist )
52 import qualified GHC.Generics as GHC ( Generic )
53 import Test.Tasty ( TestTree, testGroup )
54 import Test.Tasty.HUnit ( (@?=), testCase )
55 import Text.XML.HXT.Core (
56 PU,
57 xp4Tuple,
58 xp6Tuple,
59 xp7Tuple,
60 xpAttr,
61 xpElem,
62 xpInt,
63 xpList,
64 xpOption,
65 xpPair,
66 xpText,
67 xpWrap )
68
69 -- Local imports.
70 import TSN.Codegen ( tsn_codegen_config )
71 import TSN.DbImport ( DbImport(..), ImportResult(..), run_dbmigrate )
72 import TSN.Picklers (
73 xp_ambiguous_time,
74 xp_early_line_date,
75 xp_time_stamp )
76 import TSN.XmlImport ( XmlImport(..) )
77 import Xml (
78 FromXml(..),
79 ToDb(..),
80 pickle_unpickle,
81 unpickleable,
82 unsafe_unpickle )
83
84
85 -- | The DTD to which this module corresponds. Used to invoke dbimport.
86 --
87 dtd :: String
88 dtd = "earlylineXML.dtd"
89
90 --
91 -- * DB/XML data types
92 --
93
94 -- * EarlyLine/Message
95
96 -- | Database representation of a 'Message'. It lacks the \<date\>
97 -- elements since they're really properties of the games that they
98 -- contain.
99 --
100 data EarlyLine =
101 EarlyLine {
102 db_xml_file_id :: Int,
103 db_heading :: String,
104 db_category :: String,
105 db_sport :: String,
106 db_title :: String,
107 db_time_stamp :: UTCTime }
108 deriving (Eq, Show)
109
110
111
112 -- | XML Representation of an 'EarlyLine'. It has the same
113 -- fields, but in addition contains the 'xml_dates'.
114 --
115 data Message =
116 Message {
117 xml_xml_file_id :: Int,
118 xml_heading :: String,
119 xml_category :: String,
120 xml_sport :: String,
121 xml_title :: String,
122 xml_dates :: [EarlyLineDate],
123 xml_time_stamp :: UTCTime }
124 deriving (Eq, GHC.Generic, Show)
125
126 -- | For 'H.convert'.
127 --
128 instance H.HVector Message
129
130
131 instance ToDb Message where
132 -- | The database analogue of a 'Message' is an 'EarlyLine'.
133 --
134 type Db Message = EarlyLine
135
136
137 -- | The 'FromXml' instance for 'Message' is required for the
138 -- 'XmlImport' instance.
139 --
140 instance FromXml Message where
141 -- | To convert a 'Message' to an 'EarlyLine', we just drop
142 -- the 'xml_dates'.
143 --
144 from_xml Message{..} =
145 EarlyLine {
146 db_xml_file_id = xml_xml_file_id,
147 db_heading = xml_heading,
148 db_category = xml_category,
149 db_sport = xml_sport,
150 db_title = xml_title,
151 db_time_stamp = xml_time_stamp }
152
153
154 -- | This allows us to insert the XML representation 'Message'
155 -- directly.
156 --
157 instance XmlImport Message
158
159
160
161 -- * EarlyLineDate / EarlyLineGameWithNote
162
163 -- | This is a very sad data type. It exists so that we can
164 -- successfully unpickle/pickle the MLB_earlylineXML.dtd documents
165 -- and get back what we started with. In that document type, the
166 -- dates all have multiple \<game\>s associated with them (as
167 -- children). But the dates also have multiple \<note\>s as
168 -- children, and we're supposed to figure out which notes go with
169 -- which games based on the order that they appear in the XML
170 -- file. Yeah, right.
171 --
172 -- In any case, instead of expecting the games and notes in some
173 -- nice order, we use this data type to expect \"a game and maybe a
174 -- note\" multiple times. This will pair the notes with only one
175 -- game, rather than all of the games that TSN think it should go
176 -- with. But it allows us to pickle and unpickle correctly at least.
177 --
178 data EarlyLineGameWithNote =
179 EarlyLineGameWithNote
180 (Maybe String) -- date_note, unused
181 EarlyLineGameXml -- date_game
182 deriving (Eq, GHC.Generic, Show)
183
184 -- | Accessor for the game within a 'EarlyLineGameWithNote'. We define
185 -- this ourselves to avoid an unused field warning for date_note.
186 --
187 date_game :: EarlyLineGameWithNote -> EarlyLineGameXml
188 date_game (EarlyLineGameWithNote _ g) = g
189
190 -- | For 'H.convert'.
191 --
192 instance H.HVector EarlyLineGameWithNote
193
194
195
196 -- | XML representation of a \<date\>. It has a \"value\" attribute
197 -- containing the actual date string. As children it contains a
198 -- (non-optional) note, and a game. The note and date value are
199 -- properties of the game as far as I can tell.
200 --
201 data EarlyLineDate =
202 EarlyLineDate {
203 date_value :: UTCTime,
204 date_games_with_notes :: [EarlyLineGameWithNote] }
205 deriving (Eq, GHC.Generic, Show)
206
207 -- | For 'H.convert'.
208 --
209 instance H.HVector EarlyLineDate
210
211
212
213 -- * EarlyLineGame / EarlyLineGameXml
214
215 -- | Database representation of a \<game\> in earlylineXML.dtd and
216 -- MLB_earlylineXML.dtd. We've had to make a sacrifice here to
217 -- support both document types. Since it's not possible to pair the
218 -- \<note\>s with \<game\>s reliably in MLB_earlylineXML.dtd, we
219 -- have omitted the notes entirely. This is sad, but totally not our
220 -- fault.
221 --
222 -- In earlylineXML.dtd, each \<date\> and thus each \<note\> is
223 -- paired with exactly one \<game\>, so if we only cared about that
224 -- document type, we could have retained the notes.
225 --
226 -- In earlylinexml.DTD, the over/under is required, but in
227 -- MLB_earlylinexml.DTD it is not. So another compromise is to have
228 -- it optional here.
229 --
230 -- The 'db_game_time' should be the combined date/time using the
231 -- date value from the \<game\> element's containing
232 -- \<date\>. That's why EarlyLineGame isn't an instance of
233 -- 'FromXmlFk': the foreign key isn't enough to construct one, we
234 -- also need the date.
235 --
236 data EarlyLineGame =
237 EarlyLineGame {
238 db_early_lines_id :: DefaultKey EarlyLine,
239 db_game_time :: UTCTime, -- ^ Combined date/time
240 db_away_team :: EarlyLineGameTeam,
241 db_home_team :: EarlyLineGameTeam,
242 db_over_under :: Maybe String }
243
244
245 -- | XML representation of a 'EarlyLineGame'. Comparatively, it lacks
246 -- only the foreign key to the parent message.
247 --
248 data EarlyLineGameXml =
249 EarlyLineGameXml {
250 xml_game_time :: Maybe UTCTime, -- ^ Only an ambiguous time string,
251 -- e.g. \"8:30\". Can be empty.
252 xml_away_team :: EarlyLineGameTeamXml,
253 xml_home_team :: EarlyLineGameTeamXml,
254 xml_over_under :: Maybe String }
255 deriving (Eq, GHC.Generic, Show)
256
257
258 -- | For 'H.convert'.
259 --
260 instance H.HVector EarlyLineGameXml
261
262
263 -- * EarlyLineGameTeam / EarlyLineGameTeamXml
264
265 -- | Database representation of an EarlyLine team, used in both
266 -- earlylineXML.dtd and MLB_earlylineXML.dtd. It doubles as an
267 -- embedded type within the DB representation 'EarlyLineGame'.
268 --
269 -- The team name is /not/ optional. However, since we're overloading
270 -- the XML representation, we're constructing 'db_team_name' name
271 -- from two Maybes, 'xml_team_name_attr' and
272 -- 'xml_team_name_text'. To ensure type safety (and avoid a runtime
273 -- crash), we allow the database field to be optional as well.
274 --
275 data EarlyLineGameTeam =
276 EarlyLineGameTeam {
277 db_rotation_number :: Maybe Int, -- ^ Usually there but sometimes empty.
278 db_line :: Maybe String, -- ^ Can be blank, a Double, or \"off\".
279 db_team_name :: Maybe String, -- ^ NOT optional, see the data type docs.
280 db_pitcher :: Maybe String -- ^ Optional in MLB_earlylineXML.dtd,
281 -- always absent in earlylineXML.dtd.
282 }
283
284
285 -- | This here is an abomination. What we've got is an XML
286 -- representation, not for either earlylineXML.dtd or
287 -- MLB_earlylineXML.dtd, but one that will work for /both/. Even
288 -- though they represent the teams totally differently! Argh!
289 --
290 -- The earlylineXML.dtd teams look like,
291 --
292 -- \<teamA rotation=\"709\" line=\"\">Miami\</teamA\>
293 --
294 -- While the MLB_earlylineXML.dtd teams look like,
295 --
296 -- <teamA rotation="901" name="LOS">
297 -- <pitcher>D.Haren</pitcher>
298 -- <line>-130</line>
299 -- </teamA>
300 --
301 -- So that's cool. This data type has placeholders that should allow
302 -- the name/line to appear either as an attribute or as a text
303 -- node. We'll sort it all out in the conversion to
304 -- EarlyLineGameTeam.
305 --
306 data EarlyLineGameTeamXml =
307 EarlyLineGameTeamXml {
308 xml_rotation_number :: Maybe Int,
309 xml_line_attr :: Maybe String,
310 xml_team_name_attr :: Maybe String,
311 xml_team_name_text :: Maybe String,
312 xml_pitcher :: Maybe String,
313 xml_line_elem :: Maybe String }
314 deriving (Eq, Show)
315
316
317
318 instance ToDb EarlyLineGameTeamXml where
319 -- | The database analogue of a 'EarlyLineGameTeamXml' is an
320 -- 'EarlyLineGameTeam', although the DB type is merely embedded
321 -- in another type.
322 --
323 type Db EarlyLineGameTeamXml = EarlyLineGameTeam
324
325
326 -- | The 'FromXml' instance for 'EarlyLineGameTeamXml' lets us convert
327 -- it to a 'EarlyLineGameTeam' easily.
328 --
329 instance FromXml EarlyLineGameTeamXml where
330 -- | To convert a 'EarlyLineGameTeamXml' to an 'EarlyLineGameTeam',
331 -- we figure how its fields were represented and choose the ones
332 -- that are populated. For example if the \"line\" attribute was
333 -- there, we'll use it, but if now, we'll use the \<line\>
334 -- element.
335 --
336 from_xml EarlyLineGameTeamXml{..} =
337 EarlyLineGameTeam {
338 db_rotation_number = xml_rotation_number,
339 db_line = merge xml_line_attr xml_line_elem,
340 db_team_name = merge xml_team_name_attr xml_team_name_text,
341 db_pitcher = xml_pitcher }
342 where
343 merge :: Maybe String -> Maybe String -> Maybe String
344 merge Nothing y = y
345 merge x Nothing = x
346 merge _ _ = Nothing
347
348
349
350
351 -- | Convert an 'EarlyLineDate' into a list of 'EarlyLineGame's. Each
352 -- date has one or more games, and the fields that belong to the date
353 -- should really be in the game anyway. So the database
354 -- representation of a game has the combined fields of the XML
355 -- date/game.
356 --
357 -- This function gets the games out of a date, and then sticks the
358 -- date value inside the games. It also adds the foreign key
359 -- reference to the games' parent message, and returns the result.
360 --
361 -- This would convert a single date to a single game if we only
362 -- needed to support earlylineXML.dtd and not MLB_earlylineXML.dtd.
363 --
364 date_to_games :: (DefaultKey EarlyLine) -> EarlyLineDate -> [EarlyLineGame]
365 date_to_games fk date =
366 map convert_game games_only
367 where
368 -- | Get the list of games out of a date (i.e. drop the notes).
369 --
370 games_only :: [EarlyLineGameXml]
371 games_only = (map date_game (date_games_with_notes date))
372
373 -- | Stick the date value into the given game. If our
374 -- 'EarlyLineGameXml' has an 'xml_game_time', then we combine it
375 -- with the day portion of the supplied @date@. If not, then we
376 -- just use @date as-is.
377 --
378 combine_date_time :: Maybe UTCTime -> UTCTime
379 combine_date_time (Just t) =
380 UTCTime (utctDay $ date_value date) (utctDayTime t)
381 combine_date_time Nothing = date_value date
382
383 -- | Convert an XML game to a database one.
384 --
385 convert_game :: EarlyLineGameXml -> EarlyLineGame
386 convert_game EarlyLineGameXml{..} =
387 EarlyLineGame {
388 db_early_lines_id = fk,
389 db_game_time = combine_date_time xml_game_time,
390 db_away_team = from_xml xml_away_team,
391 db_home_team = from_xml xml_home_team,
392 db_over_under = xml_over_under }
393
394
395 --
396 -- * Database stuff
397 --
398
399 instance DbImport Message where
400 dbmigrate _ =
401 run_dbmigrate $ do
402 migrate (undefined :: EarlyLine)
403 migrate (undefined :: EarlyLineGame)
404
405 dbimport m = do
406 -- Insert the message and obtain its ID.
407 msg_id <- insert_xml m
408
409 -- Create a function that will turn a list of dates into a list of
410 -- games by converting each date to its own list of games, and
411 -- then concatenating all of the game lists together.
412 let convert_dates_to_games = concatMap (date_to_games msg_id)
413
414 -- Now use it to make dem games.
415 let games = convert_dates_to_games (xml_dates m)
416
417 -- And insert all of them
418 mapM_ insert_ games
419
420 return ImportSucceeded
421
422
423 mkPersist tsn_codegen_config [groundhog|
424
425 - entity: EarlyLine
426 dbName: early_lines
427 constructors:
428 - name: EarlyLine
429 uniques:
430 - name: unique_early_lines
431 type: constraint
432 # Prevent multiple imports of the same message.
433 fields: [db_xml_file_id]
434
435
436 - entity: EarlyLineGame
437 dbName: early_lines_games
438 constructors:
439 - name: EarlyLineGame
440 fields:
441 - name: db_early_lines_id
442 reference:
443 onDelete: cascade
444 - name: db_away_team
445 embeddedType:
446 - {name: rotation_number, dbName: away_team_rotation_number}
447 - {name: line, dbName: away_team_line}
448 - {name: team_name, dbName: away_team_name}
449 - {name: pitcher, dbName: away_team_pitcher}
450 - name: db_home_team
451 embeddedType:
452 - {name: rotation_number, dbName: home_team_rotation_number}
453 - {name: line, dbName: home_team_line}
454 - {name: team_name, dbName: home_team_name}
455 - {name: pitcher, dbName: home_team_pitcher}
456
457 - embedded: EarlyLineGameTeam
458 fields:
459 - name: db_rotation_number
460 dbName: rotation_number
461 - name: db_line
462 dbName: line
463 - name: db_team_name
464 dbName: team_name
465 - name: db_pitcher
466 dbName: pitcher
467 |]
468
469
470
471 --
472 -- * Pickling
473 --
474
475
476 -- | Pickler for the top-level 'Message'.
477 --
478 pickle_message :: PU Message
479 pickle_message =
480 xpElem "message" $
481 xpWrap (from_tuple, H.convert) $
482 xp7Tuple (xpElem "XML_File_ID" xpInt)
483 (xpElem "heading" xpText)
484 (xpElem "category" xpText)
485 (xpElem "sport" xpText)
486 (xpElem "title" xpText)
487 (xpList pickle_date)
488 (xpElem "time_stamp" xp_time_stamp)
489 where
490 from_tuple = uncurryN Message
491
492
493
494 -- | Pickler for a '\<note\> followed by a \<game\>. We turn them into
495 -- a 'EarlyLineGameWithNote'.
496 --
497 pickle_game_with_note :: PU EarlyLineGameWithNote
498 pickle_game_with_note =
499 xpWrap (from_tuple, H.convert) $
500 xpPair (xpOption $ xpElem "note" xpText)
501 pickle_game
502 where
503 from_tuple = uncurry EarlyLineGameWithNote
504
505
506 -- | Pickler for the \<date\> elements within each \<message\>.
507 --
508 pickle_date :: PU EarlyLineDate
509 pickle_date =
510 xpElem "date" $
511 xpWrap (from_tuple, H.convert) $
512 xpPair (xpAttr "value" xp_early_line_date)
513 (xpList pickle_game_with_note)
514 where
515 from_tuple = uncurry EarlyLineDate
516
517
518
519 -- | Pickler for the \<game\> elements within each \<date\>.
520 --
521 pickle_game :: PU EarlyLineGameXml
522 pickle_game =
523 xpElem "game" $
524 xpWrap (from_tuple, H.convert) $
525 xp4Tuple (xpElem "time" (xpOption xp_ambiguous_time))
526 pickle_away_team
527 pickle_home_team
528 (xpElem "over_under" (xpOption xpText))
529 where
530 from_tuple = uncurryN EarlyLineGameXml
531
532
533
534 -- | Pickle an away team (\<teamA\>) element within a \<game\>. Most
535 -- of the work (common with the home team pickler) is done by
536 -- 'pickle_team'.
537 --
538 pickle_away_team :: PU EarlyLineGameTeamXml
539 pickle_away_team = xpElem "teamA" pickle_team
540
541
542 -- | Pickle a home team (\<teamH\>) element within a \<game\>. Most
543 -- of the work (common with theaway team pickler) is done by
544 -- 'pickle_team'.
545 --
546 pickle_home_team :: PU EarlyLineGameTeamXml
547 pickle_home_team = xpElem "teamH" pickle_team
548
549
550 -- | Team pickling common to both 'pickle_away_team' and
551 -- 'pickle_home_team'. Handles everything inside the \<teamA\> and
552 -- \<teamH\> elements. We try to parse the line/name as both an
553 -- attribute and an element in order to accomodate
554 -- MLB_earlylineXML.dtd.
555 --
556 -- The \"line\" and \"pitcher\" fields wind up being double-Maybes,
557 -- since they can be empty even if they exist.
558 --
559 pickle_team :: PU EarlyLineGameTeamXml
560 pickle_team =
561 xpWrap (from_tuple, to_tuple') $
562 xp6Tuple (xpAttr "rotation" (xpOption xpInt))
563 (xpOption $ xpAttr "line" (xpOption xpText))
564 (xpOption $ xpAttr "name" xpText)
565 (xpOption xpText)
566 (xpOption $ xpElem "pitcher" (xpOption xpText))
567 (xpOption $ xpElem "line" (xpOption xpText))
568 where
569 from_tuple (u,v,w,x,y,z) =
570 EarlyLineGameTeamXml u (join v) w x (join y) (join z)
571
572 to_tuple' (EarlyLineGameTeamXml u v w x y z) =
573 (u, double_just v, w, x, double_just y, double_just z)
574 where
575 double_just val = case val of
576 Nothing -> Nothing
577 just_something -> Just just_something
578
579
580
581
582 --
583 -- * Tasty Tests
584 --
585
586 -- | A list of all tests for this module.
587 --
588 early_line_tests :: TestTree
589 early_line_tests =
590 testGroup
591 "EarlyLine tests"
592 [ test_on_delete_cascade,
593 test_pickle_of_unpickle_is_identity,
594 test_unpickle_succeeds ]
595
596 -- | If we unpickle something and then pickle it, we should wind up
597 -- with the same thing we started with. WARNING: success of this
598 -- test does not mean that unpickling succeeded.
599 --
600 test_pickle_of_unpickle_is_identity :: TestTree
601 test_pickle_of_unpickle_is_identity = testGroup "pickle-unpickle tests"
602 [ check "pickle composed with unpickle is the identity"
603 "test/xml/earlylineXML.xml",
604
605 check "pickle composed with unpickle is the identity (empty game time)"
606 "test/xml/earlylineXML-empty-game-time.xml" ]
607 where
608 check desc path = testCase desc $ do
609 (expected, actual) <- pickle_unpickle pickle_message path
610 actual @?= expected
611
612
613
614 -- | Make sure we can actually unpickle these things.
615 --
616 test_unpickle_succeeds :: TestTree
617 test_unpickle_succeeds = testGroup "unpickle tests"
618 [ check "unpickling succeeds"
619 "test/xml/earlylineXML.xml",
620
621 check "unpickling succeeds (empty game time)"
622 "test/xml/earlylineXML-empty-game-time.xml" ]
623 where
624 check desc path = testCase desc $ do
625 actual <- unpickleable path pickle_message
626 let expected = True
627 actual @?= expected
628
629
630
631 -- | Make sure everything gets deleted when we delete the top-level
632 -- record.
633 --
634 test_on_delete_cascade :: TestTree
635 test_on_delete_cascade = testGroup "cascading delete tests"
636 [ check "deleting early_lines deletes its children"
637 "test/xml/earlylineXML.xml",
638
639 check "deleting early_lines deletes its children (empty game time)"
640 "test/xml/earlylineXML-empty-game-time.xml" ]
641 where
642 check desc path = testCase desc $ do
643 results <- unsafe_unpickle path pickle_message
644 let a = undefined :: EarlyLine
645 let b = undefined :: EarlyLineGame
646
647 actual <- withSqliteConn ":memory:" $ runDbConn $ do
648 runMigrationSilent $ do
649 migrate a
650 migrate b
651 _ <- dbimport results
652 deleteAll a
653 count_a <- countAll a
654 count_b <- countAll b
655 return $ sum [count_a, count_b]
656 let expected = 0
657 actual @?= expected