]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/TSN/XML/ScheduleChanges.hs
Whitespace.
[dead/htsn-import.git] / src / TSN / XML / ScheduleChanges.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 \"Schedule_Changes_XML.dtd\". Each
10 -- \<message\> element contains zero or more \<Schedule_Change\>
11 -- which are just a wrapper around zero or more \<SC_Listing\>s.
12 --
13 -- The teams appear to use the shared "TSN.Team" representation.
14 --
15 module TSN.XML.ScheduleChanges (
16 dtd,
17 pickle_message,
18 -- * Tests
19 schedule_changes_tests,
20 -- * WARNING: these are private but exported to silence warnings
21 ScheduleChangesConstructor(..),
22 ScheduleChangesListingConstructor(..) )
23 where
24
25 -- System imports.
26 import Control.Monad ( forM_ )
27 import Data.Time ( UTCTime(..) )
28 import Data.Tuple.Curry ( uncurryN )
29 import Database.Groundhog (
30 countAll,
31 deleteAll,
32 insert_,
33 migrate,
34 runMigration,
35 silentMigrationLogger )
36 import Database.Groundhog.Core ( DefaultKey )
37 import Database.Groundhog.Generic ( runDbConn )
38 import Database.Groundhog.Sqlite ( withSqliteConn )
39 import Database.Groundhog.TH (
40 groundhog,
41 mkPersist )
42 import qualified GHC.Generics as GHC ( Generic )
43 import Test.Tasty ( TestTree, testGroup )
44 import Test.Tasty.HUnit ( (@?=), testCase )
45 import Text.XML.HXT.Core (
46 PU,
47 xp6Tuple,
48 xp11Tuple,
49 xpAttr,
50 xpElem,
51 xpInt,
52 xpList,
53 xpOption,
54 xpPair,
55 xpText,
56 xpWrap )
57
58 -- Local imports.
59 import Generics ( Generic(..), to_tuple )
60 import TSN.Codegen ( tsn_codegen_config )
61 import TSN.Database ( insert_or_select )
62 import TSN.DbImport ( DbImport(..), ImportResult(..), run_dbmigrate )
63 import TSN.Picklers ( xp_date_padded, xp_tba_time, xp_time_stamp )
64 import TSN.Team ( Team(..), HTeam(..), VTeam(..) )
65 import TSN.XmlImport ( XmlImport(..) )
66 import Xml (
67 FromXml(..),
68 ToDb(..),
69 pickle_unpickle,
70 unpickleable,
71 unsafe_unpickle )
72
73
74
75 -- | The DTD to which this module corresponds. Used to invoke
76 -- 'dbimport'.
77 --
78 dtd :: String
79 dtd = "Schedule_Changes_XML.dtd"
80
81
82 --
83 -- DB/XML data types
84 --
85
86 -- * ScheduleChanges/Message
87
88 -- | Database representation of a 'Message'. Comparatively, it lacks
89 -- the listings since they are linked via a foreign key.
90 --
91 data ScheduleChanges =
92 ScheduleChanges {
93 db_xml_file_id :: Int,
94 db_heading :: String,
95 db_category :: String,
96 db_sport :: String,
97 db_time_stamp :: UTCTime }
98 deriving (Eq, Show)
99
100
101 -- | XML representation of a \<Schedule_Change\> within a
102 -- \<message\>. These are wrappers around a bunch of
103 -- \<SC_Listing\>s, but they also contain the sport name for all of
104 -- the contained listings.
105 --
106 data ScheduleChangeXml =
107 ScheduleChangeXml {
108 xml_sc_sport :: String,
109 xml_sc_listings :: [ScheduleChangesListingXml] }
110 deriving (Eq, GHC.Generic, Show)
111
112
113 -- | For 'Generics.to_tuple'.
114 --
115 instance Generic ScheduleChangeXml
116
117
118 -- | XML representation of a 'ScheduleChanges'. It has the same
119 -- fields, but in addition contains the 'xml_listings'.
120 --
121 data Message =
122 Message {
123 xml_xml_file_id :: Int,
124 xml_heading :: String,
125 xml_category :: String,
126 xml_sport :: String,
127 xml_schedule_changes :: [ScheduleChangeXml],
128 xml_time_stamp :: UTCTime }
129 deriving (Eq, GHC.Generic, Show)
130
131
132 -- | For 'Generics.to_tuple'.
133 --
134 instance Generic Message
135
136
137 instance ToDb Message where
138 -- | The database analogue of a 'Message' is a 'ScheduleChanges'.
139 --
140 type Db Message = ScheduleChanges
141
142
143 -- | The 'FromXml' instance for 'Message' is required for the
144 -- 'XmlImport' instance.
145 --
146 instance FromXml Message where
147 -- | To convert a 'Message' to an 'ScheduleChanges', we just drop
148 -- the 'xml_schedule_changes'.
149 --
150 from_xml Message{..} =
151 ScheduleChanges {
152 db_xml_file_id = xml_xml_file_id,
153 db_heading = xml_heading,
154 db_category = xml_category,
155 db_sport = xml_sport,
156 db_time_stamp = xml_time_stamp }
157
158
159 -- | This allows us to insert the XML representation 'Message'
160 -- directly.
161 --
162 instance XmlImport Message
163
164
165
166 -- * ScheduleChangesListing/ScheduleChangesListingXml
167
168 -- | An embedded type within 'ScheduleChangesListing'. These look
169 -- like, \<status numeral=\"4\"\>FINAL\</status\> within the XML,
170 -- but they're in one-to-one correspondence with the listings.
171 --
172 data ScheduleChangesListingStatus =
173 ScheduleChangesListingStatus {
174 db_status_numeral :: Int,
175 db_status :: Maybe String } -- Yes, they can be empty.
176 deriving (Eq, Show)
177
178
179
180 -- | Database representation of a \<SC_Listing\> contained within a
181 -- \<Schedule_Change\>, within a \<message\>. During the transition
182 -- to the database, we drop the intermediate \<Schedule_Change\>
183 -- leaving the listing keyed to the 'ScheduleChanges' itself.
184 --
185 -- The home/away teams reuse the 'Team' representation.
186 --
187 -- The sport name (sc_sport) is pulled out of the containing
188 -- \<Schedule_Change\> and embedded into the listings themselves.
189 --
190 data ScheduleChangesListing =
191 ScheduleChangesListing {
192 db_schedule_changes_id :: DefaultKey ScheduleChanges,
193 db_away_team_id :: DefaultKey Team,
194 db_home_team_id ::DefaultKey Team,
195 db_type :: String,
196 db_sc_sport :: String,
197 db_schedule_id :: Int,
198 db_game_time :: UTCTime,
199 db_location :: Maybe String,
200 db_vscore :: Int,
201 db_hscore :: Int,
202 db_listing_status :: ScheduleChangesListingStatus,
203 db_notes :: Maybe String }
204
205
206 -- | XML representation of a \<SC_Listing\> contained within a
207 -- \<Schedule_Change\>, within a \<message\>.
208 --
209 data ScheduleChangesListingXml =
210 ScheduleChangesListingXml {
211 xml_type :: String,
212 xml_schedule_id :: Int,
213 xml_game_date :: UTCTime,
214 xml_game_time :: Maybe UTCTime,
215 xml_location :: Maybe String,
216 xml_away_team :: VTeam,
217 xml_home_team :: HTeam,
218 xml_vscore :: Int,
219 xml_hscore :: Int,
220 xml_listing_status :: ScheduleChangesListingStatus,
221 xml_notes :: Maybe String }
222 deriving (Eq, GHC.Generic, Show)
223
224
225 -- | For 'Generics.to_tuple'.
226 --
227 instance Generic ScheduleChangesListingXml
228
229
230 instance ToDb ScheduleChangesListingXml where
231 -- | The database analogue of an 'ScheduleChangesListingXml' is
232 -- an 'ScheduleChangesListing'.
233 --
234 type Db ScheduleChangesListingXml = ScheduleChangesListing
235
236
237
238 -- | We don't make 'ScheduleChangesListingXml' an instance of
239 -- 'FromXmlFkTeams' because it needs some additional information,
240 -- namely the sport name from its containing \<Schedule_Change\>.
241 -- But essentially we'll need to do the same thing as
242 -- 'from_xml_fk_teams'. This function accomplishes the same thing,
243 -- with the addition of the sport that's passed in.
244 --
245 -- The parameter order is for convenience later (see dbimport).
246 --
247 from_xml_fk_sport :: (DefaultKey ScheduleChanges)
248 -> String -- ^ The sport from our containing schedule change
249 -> (DefaultKey Team) -- ^ Away team FK
250 -> (DefaultKey Team) -- ^ Home team FK
251 -> ScheduleChangesListingXml
252 -> ScheduleChangesListing
253 from_xml_fk_sport fk sport fk_away fk_home ScheduleChangesListingXml{..} =
254 ScheduleChangesListing {
255 db_schedule_changes_id = fk,
256 db_away_team_id = fk_away,
257 db_home_team_id = fk_home,
258 db_type = xml_type,
259 db_sc_sport = sport,
260 db_schedule_id = xml_schedule_id,
261 db_game_time = make_game_time xml_game_date xml_game_time,
262 db_location = xml_location,
263 db_vscore = xml_vscore,
264 db_hscore = xml_hscore,
265 db_listing_status = xml_listing_status,
266 db_notes = xml_notes }
267 where
268 -- | Make the database \"game time\" from the XML
269 -- date/time. Simply take the day part from one and the time
270 -- from the other.
271 --
272 make_game_time d Nothing = d
273 make_game_time d (Just t) = UTCTime (utctDay d) (utctDayTime t)
274
275
276
277 --
278 -- * Database stuff.
279 --
280
281 instance DbImport Message where
282 dbmigrate _ =
283 run_dbmigrate $ do
284 migrate (undefined :: Team)
285 migrate (undefined :: ScheduleChanges)
286 migrate (undefined :: ScheduleChangesListing)
287
288 dbimport m = do
289 -- Insert the top-level message
290 msg_id <- insert_xml m
291
292 -- Now loop through the message's schedule changes
293 forM_ (xml_schedule_changes m) $ \sc -> do
294 -- Construct the function that will turn an XML listing into a DB one.
295 -- This is only partially applied without the away/home team IDs.
296 let listing_xml_to_db = from_xml_fk_sport msg_id (xml_sc_sport sc)
297
298 -- Now loop through the listings so that we can handle the teams
299 -- one listing at a time.
300 forM_ (xml_sc_listings sc) $ \listing -> do
301 away_team_id <- insert_or_select (vteam $ xml_away_team listing)
302 home_team_id <- insert_or_select (hteam $ xml_home_team listing)
303
304 -- Finish constructing the xml -> db function.
305 let listing_xml_to_db' = listing_xml_to_db away_team_id home_team_id
306 let db_listing = listing_xml_to_db' listing
307
308 insert_ db_listing
309
310 return ImportSucceeded
311
312
313 mkPersist tsn_codegen_config [groundhog|
314 - entity: ScheduleChanges
315 dbName: schedule_changes
316 constructors:
317 - name: ScheduleChanges
318 uniques:
319 - name: unique_schedule_changes
320 type: constraint
321 # Prevent multiple imports of the same message.
322 fields: [db_xml_file_id]
323
324 # Note: we drop the "sc" prefix from the db_sc_sport field.
325 - entity: ScheduleChangesListing
326 dbName: schedule_changes_listings
327 constructors:
328 - name: ScheduleChangesListing
329 fields:
330 - name: db_schedule_changes_id
331 reference:
332 onDelete: cascade
333 - name: db_away_team_id
334 reference:
335 onDelete: cascade
336 - name: db_home_team_id
337 reference:
338 onDelete: cascade
339 - name: db_sc_sport
340 dbName: sport
341 - name: db_listing_status
342 embeddedType:
343 - {name: status_numeral, dbName: status_numeral}
344 - {name: status, dbName: status}
345
346 - embedded: ScheduleChangesListingStatus
347 fields:
348 - name: db_status_numeral
349 dbName: status_numeral
350 - name: db_status
351 dbName: status
352
353 |]
354
355
356
357 --
358 -- * Pickling
359 --
360
361 -- | An (un)pickler for the \<Away_Team\> elements.
362 --
363 pickle_away_team :: PU VTeam
364 pickle_away_team =
365 xpElem "Away_Team" $
366 xpWrap (from_tuple, to_tuple') $
367 xpPair (xpAttr "AT_ID" xpText)
368 (xpOption xpText)
369 where
370 from_tuple (x,y) = VTeam (Team x Nothing y)
371 to_tuple' (VTeam t) = (team_id t, name t)
372
373
374 -- | An (un)pickler for the \<Away_Team\> elements.
375 --
376 pickle_home_team :: PU HTeam
377 pickle_home_team =
378 xpElem "Home_Team" $
379 xpWrap (from_tuple, to_tuple') $
380 xpPair (xpAttr "HT_ID" xpText)
381 (xpOption xpText)
382 where
383 from_tuple (x,y) = HTeam (Team x Nothing y)
384 to_tuple' (HTeam t) = (team_id t, name t)
385
386
387 -- | An (un)pickler for the \<status\> elements.
388 --
389 pickle_status :: PU ScheduleChangesListingStatus
390 pickle_status =
391 xpElem "status" $
392 xpWrap (from_tuple, to_tuple') $
393 xpPair (xpAttr "numeral" xpInt)
394 (xpOption xpText)
395 where
396 from_tuple = uncurry ScheduleChangesListingStatus
397
398 -- Avouid unused field warnings.
399 to_tuple' ScheduleChangesListingStatus{..} =
400 (db_status_numeral, db_status)
401
402 -- | An (un)pickler for the \<SC_Listing\> elements.
403 --
404 pickle_listing :: PU ScheduleChangesListingXml
405 pickle_listing =
406 xpElem "SC_Listing" $
407 xpWrap (from_tuple, to_tuple) $
408 xp11Tuple (xpAttr "type" xpText)
409 (xpElem "Schedule_ID" xpInt)
410 (xpElem "Game_Date" xp_date_padded)
411 (xpElem "Game_Time" xp_tba_time)
412 (xpElem "Location" (xpOption xpText))
413 pickle_away_team
414 pickle_home_team
415 (xpElem "vscore" xpInt)
416 (xpElem "hscore" xpInt)
417 pickle_status
418 (xpElem "notes" (xpOption xpText))
419 where
420 from_tuple = uncurryN ScheduleChangesListingXml
421
422
423 -- | An (un)pickler for the \<Schedule_Change\> elements.
424 --
425 pickle_schedule_change :: PU ScheduleChangeXml
426 pickle_schedule_change =
427 xpElem "Schedule_Change" $
428 xpWrap (from_tuple, to_tuple) $
429 xpPair (xpAttr "Sport" xpText)
430 (xpList pickle_listing)
431 where
432 from_tuple = uncurry ScheduleChangeXml
433
434
435 -- | Pickler for the top-level 'Message'.
436 --
437 pickle_message :: PU Message
438 pickle_message =
439 xpElem "message" $
440 xpWrap (from_tuple, to_tuple) $
441 xp6Tuple (xpElem "XML_File_ID" xpInt)
442 (xpElem "heading" xpText)
443 (xpElem "category" xpText)
444 (xpElem "sport" xpText)
445 (xpList pickle_schedule_change)
446 (xpElem "time_stamp" xp_time_stamp)
447 where
448 from_tuple = uncurryN Message
449
450
451
452 --
453 -- * Tests
454 --
455 -- | A list of all tests for this module.
456 --
457 schedule_changes_tests :: TestTree
458 schedule_changes_tests =
459 testGroup
460 "ScheduleChanges tests"
461 [ test_on_delete_cascade,
462 test_pickle_of_unpickle_is_identity,
463 test_unpickle_succeeds ]
464
465 -- | If we unpickle something and then pickle it, we should wind up
466 -- with the same thing we started with. WARNING: success of this
467 -- test does not mean that unpickling succeeded.
468 --
469 test_pickle_of_unpickle_is_identity :: TestTree
470 test_pickle_of_unpickle_is_identity =
471 testCase "pickle composed with unpickle is the identity" $ do
472 let path = "test/xml/Schedule_Changes_XML.xml"
473 (expected, actual) <- pickle_unpickle pickle_message path
474 actual @?= expected
475
476
477
478 -- | Make sure we can actually unpickle these things.
479 --
480 test_unpickle_succeeds :: TestTree
481 test_unpickle_succeeds =
482 testCase "unpickling succeeds" $ do
483 let path = "test/xml/Schedule_Changes_XML.xml"
484 actual <- unpickleable path pickle_message
485
486 let expected = True
487 actual @?= expected
488
489
490
491 -- | Make sure everything gets deleted when we delete the top-level
492 -- record.
493 --
494 test_on_delete_cascade :: TestTree
495 test_on_delete_cascade =
496 testCase "deleting auto_racing_results deletes its children" $ do
497 let path = "test/xml/Schedule_Changes_XML.xml"
498 results <- unsafe_unpickle path pickle_message
499 let a = undefined :: Team
500 let b = undefined :: ScheduleChanges
501 let c = undefined :: ScheduleChangesListing
502
503 actual <- withSqliteConn ":memory:" $ runDbConn $ do
504 runMigration silentMigrationLogger $ do
505 migrate a
506 migrate b
507 migrate c
508 _ <- dbimport results
509 deleteAll b
510 count_a <- countAll a
511 count_b <- countAll b
512 count_c <- countAll c
513 return $ sum [count_a, count_b, count_c]
514 let expected = 12 -- There are 16 team elements, but 4 are dupes,
515 -- so 12 unique teams should be left over.
516 actual @?= expected