1 {-# LANGUAGE DeriveGeneric #-}
2 {-# LANGUAGE DeriveDataTypeable #-}
3 {-# LANGUAGE FlexibleInstances #-}
5 {-# LANGUAGE QuasiQuotes #-}
6 {-# LANGUAGE RecordWildCards #-}
7 {-# LANGUAGE TemplateHaskell #-}
8 {-# LANGUAGE TypeFamilies #-}
10 -- | Parse TSN XML for the DTD \"scoresxml.dtd\". Each document
11 -- contains a single \<game\> and some \<location\>s.
13 module TSN.XML.Scores (
18 -- * WARNING: these are private but exported to silence warnings
19 Score_LocationConstructor(..),
21 ScoreGameConstructor(..) )
25 import Control.Monad ( join )
26 import Data.Data ( Data )
27 import Data.Time ( UTCTime )
28 import Data.Tuple.Curry ( uncurryN )
29 import Data.Typeable ( Typeable )
30 import qualified Data.Vector.HFixed as H ( HVector, convert )
31 import Database.Groundhog (
37 silentMigrationLogger )
38 import Database.Groundhog.Core ( DefaultKey )
39 import Database.Groundhog.Generic ( runDbConn )
40 import Database.Groundhog.Sqlite ( withSqliteConn )
41 import Database.Groundhog.TH (
44 import qualified GHC.Generics as GHC ( Generic )
45 import Test.Tasty ( TestTree, testGroup )
46 import Test.Tasty.HUnit ( (@?=), testCase )
47 import Text.XML.HXT.Core (
62 import TSN.Codegen ( tsn_codegen_config )
63 import TSN.Database ( insert_or_select )
64 import TSN.DbImport ( DbImport(..), ImportResult(..), run_dbmigrate )
65 import TSN.Location ( Location(..), pickle_location )
66 import TSN.Picklers ( xp_time_stamp )
72 import TSN.XmlImport ( XmlImport(..), XmlImportFkTeams(..) )
82 -- | The DTD to which this module corresponds. Used to invoke dbimport.
89 -- * DB/XML Data types
95 -- | Database representation of a 'Message'. It lacks the
96 -- 'xml_locations' and 'xml_game' which are related via foreign keys
101 db_xml_file_id :: Int,
102 db_heading :: String,
103 db_game_id :: Maybe Int, -- ^ We've seen an empty one
104 db_schedule_id :: Maybe Int, -- ^ We've seen an empty one
105 db_tsnupdate :: Maybe Bool,
106 db_category :: String,
108 db_season_type :: Maybe String, -- ^ We've seen an empty one
109 db_time_stamp :: UTCTime }
112 -- | XML representation of the top level \<message\> element (i.e. a
117 xml_xml_file_id :: Int,
118 xml_heading :: String,
119 xml_game_id :: Maybe Int, -- ^ We've seen an empty one
120 xml_schedule_id :: Maybe Int, -- ^ We've seen an empty one
121 xml_tsnupdate :: Maybe Bool,
122 xml_category :: String,
124 xml_locations :: [Location],
125 xml_season_type :: Maybe String, -- ^ We've seen an empty one
126 xml_game :: ScoreGameXml,
127 xml_time_stamp :: UTCTime }
128 deriving (Eq, GHC.Generic, Show)
131 -- | For 'H.convert'.
133 instance H.HVector Message
136 instance ToDb Message where
137 -- | The database representation of a 'Message' is a 'Score'.
138 type Db Message = Score
140 instance FromXml Message where
141 -- | When converting from the XML representation to the database
142 -- one, we drop the list of locations which will be foreign-keyed to
144 from_xml Message{..} =
146 db_xml_file_id = xml_xml_file_id,
147 db_heading = xml_heading,
148 db_game_id = xml_game_id,
149 db_schedule_id = xml_schedule_id,
150 db_tsnupdate = xml_tsnupdate,
151 db_category = xml_category,
152 db_sport = xml_sport,
153 db_season_type = xml_season_type,
154 db_time_stamp = xml_time_stamp }
157 -- | This lets us insert the XML representation 'Message' directly.
159 instance XmlImport Message
162 -- * ScoreGame / ScoreGameXml
164 -- | This is an embedded field within 'SportsGame'. Each \<status\>
165 -- element has two attributes, a numeral and a type. It also
166 -- contains some text. Rather than put these in their own table, we
167 -- include them in the parent 'SportsGame'.
169 data ScoreGameStatus =
171 db_status_numeral :: Maybe Int,
172 db_status_type :: Maybe String, -- ^ These are probably only one-character,
173 -- long, but they all take the same
174 -- amount of space in Postgres.
175 db_status_text :: String }
176 deriving (Data, Eq, Show, Typeable)
179 -- | Database representation of a game.
183 db_scores_id :: DefaultKey Score,
184 db_away_team_id :: DefaultKey Team,
185 db_home_team_id :: DefaultKey Team,
186 db_away_team_score :: Int,
187 db_home_team_score :: Int,
188 db_away_team_pitcher :: Maybe String, -- ^ Found in the child \<vteam\>
189 db_home_team_pitcher :: Maybe String, -- ^ Found in the child \<hteam\>
190 db_time_r :: Maybe String, -- ^ Time remaining, the format is uncertain.
191 db_status :: ScoreGameStatus,
192 db_notes :: Maybe String }
195 -- | XML representation of a \<game\> element (i.e. a 'ScoreGame').
199 xml_vteam :: VTeamXml,
200 xml_hteam :: HTeamXml,
201 xml_away_team_score :: Int,
202 xml_home_team_score :: Int,
203 xml_time_r :: Maybe String, -- ^ Time remaining, the format is uncertain.
204 xml_status :: ScoreGameStatus,
205 xml_notes :: Maybe String }
206 deriving (Eq, GHC.Generic, Show)
209 -- | For 'H.convert'.
211 instance H.HVector ScoreGameXml
214 instance ToDb ScoreGameXml where
215 -- | The database representation of a 'ScoreGameXml' is a
218 type Db ScoreGameXml = ScoreGame
221 instance Child ScoreGameXml where
222 -- | Each 'ScoreGameXml' is contained in (i.e. has a foreign key to)
225 type Parent ScoreGameXml = Score
228 instance FromXmlFkTeams ScoreGameXml where
229 -- | To create a 'ScoreGame' from a 'ScoreGameXml', we need three
230 -- foreign keys: the parent message, and the away/home teams.
232 -- During conversion, we also get the pitchers out of the teams;
233 -- unfortunately this prevents us from making the conversion
236 from_xml_fk_teams fk fk_away fk_home ScoreGameXml{..} =
239 db_away_team_id = fk_away,
240 db_home_team_id = fk_home,
241 db_away_team_score = xml_away_team_score,
242 db_home_team_score = xml_home_team_score,
243 db_away_team_pitcher = xml_vpitcher xml_vteam,
244 db_home_team_pitcher = xml_hpitcher xml_hteam,
245 db_time_r = xml_time_r,
246 db_status = xml_status,
247 db_notes = xml_notes }
249 -- | This lets us import the database representation 'ScoreGameXml'
252 instance XmlImportFkTeams ScoreGameXml
258 -- | Join each 'Score' with its 'Location's. Database-only. We use a
259 -- join table because the locations are kept unique but there are
260 -- multiple locations per 'Score'.
262 data Score_Location =
265 (DefaultKey Location)
268 -- * HTeamXml / VTeamXml
270 -- | XML Representation of a home team. This document type is unusual
271 -- in that the \<hteam\> elements can have a pitcher attribute
272 -- attached to them. We still want to maintain the underlying 'Team'
273 -- representation, so we say that a home team is a 'Team' and
274 -- (maybe) a pitcher.
279 xml_hpitcher :: Maybe String }
282 instance ToDb HTeamXml where
283 -- | The database analogue of a 'HTeamXml' is its 'Team'.
284 type Db HTeamXml = Team
286 instance FromXml HTeamXml where
287 -- | The conversion from XML to database is simply the 'Team' accessor.
289 from_xml = hteam . xml_ht
291 -- | Allow import of the XML representation directly, without
292 -- requiring a manual conversion to the database type first.
294 instance XmlImport HTeamXml
298 -- | XML Representation of an away team. This document type is unusual
299 -- in that the \<hteam\> elements can have a pitcher attribute
300 -- attached to them. We still want to maintain the underlying 'Team'
301 -- representation, so we say that an away team is a 'Team' and
302 -- (maybe) a pitcher.
307 xml_vpitcher :: Maybe String }
310 instance ToDb VTeamXml where
311 -- | The database analogue of a 'VTeamXml' is its 'Team'.
312 type Db VTeamXml = Team
314 instance FromXml VTeamXml where
315 -- | The conversion from XML to database is simply the 'Team' accessor.
317 from_xml = vteam . xml_vt
319 -- | Allow import of the XML representation directly, without
320 -- requiring a manual conversion to the database type first.
322 instance XmlImport VTeamXml
326 instance DbImport Message where
329 migrate (undefined :: Location)
330 migrate (undefined :: Team)
331 migrate (undefined :: Score)
332 migrate (undefined :: ScoreGame)
333 migrate (undefined :: Score_Location)
336 -- Insert the message and get its ID.
337 msg_id <- insert_xml m
339 -- Insert all of the locations contained within this message and
340 -- collect their IDs in a list. We use insert_or_select because
341 -- most of the locations will already exist, and we just want to
342 -- get the ID of the existing location when there's a collision.
343 location_ids <- mapM insert_or_select (xml_locations m)
345 -- Now use that list to construct 'Score_ScoreLocation' objects,
347 mapM_ (insert_ . Score_Location msg_id) location_ids
349 -- Insert the hteam/vteams, noting the IDs.
350 vteam_id <- insert_xml_or_select (xml_vteam $ xml_game m)
351 hteam_id <- insert_xml_or_select (xml_hteam $ xml_game m)
353 -- Now use those along with the msg_id to construct the game.
354 insert_xml_fk_teams_ msg_id vteam_id hteam_id (xml_game m)
356 return ImportSucceeded
360 -- These types have fields with e.g. db_ and xml_ prefixes, so we
361 -- use our own codegen to peel those off before naming the columns.
362 mkPersist tsn_codegen_config [groundhog|
368 - name: unique_scores
370 # Prevent multiple imports of the same message.
371 fields: [db_xml_file_id]
373 - embedded: ScoreGameStatus
375 - name: db_status_numeral
376 dbName: status_numeral
377 - name: db_status_type
379 - name: db_status_text
393 - { name: status_numeral, dbName: status_numeral }
394 - { name: status_type, dbName: status_type }
395 - { name: status_text, dbName: status_text }
398 - entity: Score_Location
399 dbName: scores__locations
401 - name: Score_Location
403 - name: score_Location0 # Default created by mkNormalFieldName
407 - name: score_Location1 # Default created by mkNormalFieldName
418 -- | Convert a 'Message' to/from \<message\>.
420 pickle_message :: PU Message
423 xpWrap (from_tuple, H.convert) $
424 xp11Tuple (xpElem "XML_File_ID" xpInt)
425 (xpElem "heading" xpText)
426 (xpElem "game_id" (xpOption xpInt))
427 (xpElem "schedule_id" (xpOption xpInt))
428 (xpOption $ xpElem "tsnupdate" xpPrim)
429 (xpElem "category" xpText)
430 (xpElem "sport" xpText)
431 (xpList pickle_location)
432 (xpElem "seasontype" (xpOption xpText))
434 (xpElem "time_stamp" xp_time_stamp)
436 from_tuple = uncurryN Message
440 -- | Convert a 'ScoreGameStatus' to/from \<status\>. The \"type\"
441 -- attribute can be either missing or empty, so we're really parsing
442 -- a double-Maybe here. We use the monad join to collapse it into
443 -- one. See also: the hteam/vteam picklers.
445 pickle_status :: PU ScoreGameStatus
448 xpWrap (from_tuple, to_tuple') $
449 xpTriple (xpAttr "numeral" $ xpOption xpInt)
450 (xpOption $ xpAttr "type" $ xpOption xpText)
453 from_tuple (x,y,z) = ScoreGameStatus x (join y) z
454 to_tuple' ScoreGameStatus{..} =
455 (db_status_numeral, s, db_status_text)
457 s = case db_status_type of
459 Just _ -> Just db_status_type
462 -- | Convert a 'ScoreGameXml' to/from \<game\>.
464 pickle_game :: PU ScoreGameXml
467 xpWrap (from_tuple, H.convert) $
468 xp7Tuple pickle_vteam
470 (xpElem "vscore" xpInt)
471 (xpElem "hscore" xpInt)
472 (xpOption $ xpElem "time_r" xpText)
474 (xpOption $ xpElem "notes" xpText)
476 from_tuple = uncurryN ScoreGameXml
479 -- | Convert a 'VTeamXml' to/from \<vteam\>. The team names
480 -- always seem to be present here, but in the shared representation,
481 -- they're optional (because they show up blank elsewhere). So, we
482 -- pretend they're optional.
484 -- The \"pitcher\" attribute is a little bit funny. Usually, when
485 -- there's no pitcher, the attribute itself is missing. But once in
486 -- a blue moon, it will be present with no text. We want to treat
487 -- both cases the same, so what we really parse is a Maybe (Maybe
488 -- String), and then use the monad 'join' to collapse it into a single
491 pickle_vteam :: PU VTeamXml
494 xpWrap (from_tuple, to_tuple') $
495 xpTriple (xpAttr "id" xpText)
496 (xpOption $ xpAttr "pitcher" (xpOption xpText))
497 (xpOption xpText) -- Team name
499 from_tuple (x,y,z) = VTeamXml (VTeam (Team x Nothing z)) (join y)
501 to_tuple' (VTeamXml (VTeam t) Nothing) = (team_id t, Nothing, name t)
502 to_tuple' (VTeamXml (VTeam t) jvp) = (team_id t, Just jvp, name t)
505 -- | Convert a 'HTeamXml' to/from \<hteam\>. Identical to 'pickle_vteam'
506 -- modulo the \"h\" and \"v\". The team names always seem to be
507 -- present here, but in the shared representation, they're optional
508 -- (because they show up blank elsewhere). So, we pretend they're
511 -- The \"pitcher\" attribute is a little bit funny. Usually, when
512 -- there's no pitcher, the attribute itself is missing. But once in
513 -- a blue moon, it will be present with no text. We want to treat
514 -- both cases the same, so what we really parse is a Maybe (Maybe
515 -- String), and then use the monad 'join' to collapse it into a single
518 pickle_hteam :: PU HTeamXml
521 xpWrap (from_tuple, to_tuple') $
522 xpTriple (xpAttr "id" xpText)
523 (xpOption $ xpAttr "pitcher" (xpOption xpText))
524 (xpOption xpText) -- Team name
526 from_tuple (x,y,z)= HTeamXml (HTeam (Team x Nothing z)) (join y)
527 to_tuple' (HTeamXml (HTeam t) Nothing) = (team_id t, Nothing, name t)
528 to_tuple' (HTeamXml (HTeam t) jhp) = (team_id t, Just jhp, name t)
536 -- | A list of all tests for this module.
538 scores_tests :: TestTree
542 [ test_on_delete_cascade,
543 test_pickle_of_unpickle_is_identity,
544 test_unpickle_succeeds ]
547 -- | If we unpickle something and then pickle it, we should wind up
548 -- with the same thing we started with. WARNING: success of this
549 -- test does not mean that unpickling succeeded.
551 test_pickle_of_unpickle_is_identity :: TestTree
552 test_pickle_of_unpickle_is_identity = testGroup "pickle-unpickle tests"
553 [ check "pickle composed with unpickle is the identity"
554 "test/xml/scoresxml.xml",
556 check "pickle composed with unpickle is the identity (no locations)"
557 "test/xml/scoresxml-no-locations.xml",
559 check "pickle composed with unpickle is the identity (pitcher, no type)"
560 "test/xml/scoresxml-pitcher-no-type.xml",
562 check "pickle composed with unpickle is the identity (empty numeral)"
563 "test/xml/scoresxml-empty-numeral.xml",
565 check "pickle composed with unpickle is the identity (empty type)"
566 "test/xml/scoresxml-empty-type.xml" ]
568 check desc path = testCase desc $ do
569 (expected, actual) <- pickle_unpickle pickle_message path
573 -- | Make sure we can actually unpickle these things.
575 test_unpickle_succeeds :: TestTree
576 test_unpickle_succeeds = testGroup "unpickle tests"
577 [ check "unpickling succeeds"
578 "test/xml/scoresxml.xml",
580 check "unpickling succeeds (no locations)"
581 "test/xml/scoresxml-no-locations.xml",
583 check "unpickling succeeds (pitcher, no type)"
584 "test/xml/scoresxml-pitcher-no-type.xml",
586 check "unpickling succeeds (empty numeral)"
587 "test/xml/scoresxml-empty-numeral.xml",
589 check "unpickling succeeds (empty type)"
590 "test/xml/scoresxml-empty-type.xml" ]
592 check desc path = testCase desc $ do
593 actual <- unpickleable path pickle_message
598 -- | Make sure everything gets deleted when we delete the top-level
601 test_on_delete_cascade :: TestTree
602 test_on_delete_cascade = testGroup "cascading delete tests"
603 [ check "unpickling succeeds"
604 "test/xml/scoresxml.xml"
605 4, -- 2 teams, 2 locations
607 check "unpickling succeeds (no locations)"
608 "test/xml/scoresxml-no-locations.xml"
609 2, -- 2 teams, 0 locations
611 check "unpickling succeeds (pitcher, no type)"
612 "test/xml/scoresxml-pitcher-no-type.xml"
613 3, -- 2 teams, 1 location
615 check "unpickling succeeds (empty numeral)"
616 "test/xml/scoresxml-empty-numeral.xml"
617 3, -- 2 teams, 1 location
619 check "unpickling succeeds (empty type)"
620 "test/xml/scoresxml-empty-type.xml"
621 4 -- 2 teams, 2 locations
624 check desc path expected = testCase desc $ do
625 score <- unsafe_unpickle path pickle_message
626 let a = undefined :: Location
627 let b = undefined :: Team
628 let c = undefined :: Score
629 let d = undefined :: ScoreGame
630 let e = undefined :: Score_Location
631 actual <- withSqliteConn ":memory:" $ runDbConn $ do
632 runMigration silentMigrationLogger $ do
639 -- No idea how 'delete' works, so do this instead.
641 count_a <- countAll a
642 count_b <- countAll b
643 count_c <- countAll c
644 count_d <- countAll d
645 count_e <- countAll e
646 return $ sum [count_a, count_b, count_c,