1 {-# LANGUAGE DeriveDataTypeable #-}
2 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE QuasiQuotes #-}
5 {-# LANGUAGE RecordWildCards #-}
6 {-# LANGUAGE TemplateHaskell #-}
7 {-# LANGUAGE TypeFamilies #-}
9 -- | Parse TSN XML for the DTD \"newsxml.dtd\". Each document contains
10 -- a root element \<message\> that contains an entire news item.
17 -- * WARNING: these are private but exported to silence warnings
18 News_LocationConstructor(..),
19 News_NewsTeamConstructor(..),
21 NewsTeamConstructor(..) )
25 import Data.Data ( Data, constrFields, dataTypeConstrs, dataTypeOf )
26 import Data.Time.Clock ( UTCTime )
27 import Data.List.Utils ( join, split )
28 import Data.Tuple.Curry ( uncurryN )
29 import Data.Typeable ( Typeable )
30 import Database.Groundhog (
36 silentMigrationLogger )
37 import Database.Groundhog.Core ( DefaultKey )
38 import Database.Groundhog.Generic ( runDbConn )
39 import Database.Groundhog.Sqlite ( withSqliteConn )
40 import Database.Groundhog.TH (
44 import Test.Tasty ( TestTree, testGroup )
45 import Test.Tasty.HUnit ( (@?=), testCase )
46 import Text.XML.HXT.Core (
62 tsn_db_field_namer ) -- Used in a test
63 import TSN.Database ( insert_or_select )
64 import TSN.DbImport ( DbImport(..), ImportResult(..), run_dbmigrate )
65 import TSN.Picklers ( xp_time_stamp )
66 import TSN.Location ( Location(..) )
67 import TSN.XmlImport ( XmlImport(..) )
76 -- | The DTD to which this module corresponds. Used to invoke dbimport.
88 -- | The msg_id child of \<message\> contains an event_id attribute; we
89 -- embed it into the 'News' type. We (pointlessly) use the \"db_\"
90 -- prefix here so that the two names don't collide on \"id\" when
91 -- Groundhog is creating its fields using our field namer.
96 db_event_id :: Maybe Int }
97 deriving (Data, Eq, Show, Typeable)
100 -- | The XML representation of a news item (\<message\>).
104 xml_xml_file_id :: Int,
105 xml_heading :: String,
107 xml_category :: String,
109 xml_url :: Maybe String,
110 xml_teams :: [NewsTeam],
111 xml_locations :: [NewsLocationXml],
113 xml_editor :: Maybe String,
114 xml_text :: Maybe String, -- Text and continue seem to show up in pairs,
115 xml_continue :: Maybe String, -- either both present or both missing.
116 xml_time_stamp :: UTCTime }
120 -- | The database representation of a news item. We drop several
121 -- uninteresting fields from 'Message', and omit the list fields which
122 -- will be represented as join tables.
126 db_xml_file_id :: Int,
129 db_url :: Maybe String,
131 db_editor :: Maybe String,
132 db_text :: Maybe String,
133 db_continue :: Maybe String,
134 db_time_stamp :: UTCTime }
135 deriving (Data, Eq, Show, Typeable)
139 instance ToDb Message where
140 -- | The database representation of 'Message' is 'News'.
141 type Db Message = News
143 -- | Convert the XML representation 'Message' to the database
144 -- representation 'News'.
146 instance FromXml Message where
147 -- | We use a record wildcard so GHC doesn't complain that we never
148 -- used the field names.
150 from_xml Message{..} = News { db_xml_file_id = xml_xml_file_id,
152 db_sport = xml_sport,
155 db_editor = xml_editor,
157 db_continue = xml_continue,
158 db_time_stamp = xml_time_stamp }
160 -- | This lets us insert the XML representation 'Message' directly.
162 instance XmlImport Message
167 -- | The database/XML type for teams as they show up in the news. We
168 -- can't reuse the representation from "TSN.Team" because they
169 -- require a team id. We wouldn't want to make the team ID optional
170 -- and then insert a team with no id, only to find the same team
171 -- later with an id and be unable to update the record. (We could
172 -- add the update logic, but it would be more trouble than it's
176 NewsTeam { team_name :: String }
183 -- | Mapping between News records and NewsTeam records in the
184 -- database. We don't name the fields because we don't use the names
185 -- explicitly; that means we have to give them nice database names
188 data News_NewsTeam = News_NewsTeam
190 (DefaultKey NewsTeam)
195 -- | The XML type for locations as they show up in the news. The
196 -- associated database type comes from "TSN.Location".
198 data NewsLocationXml =
200 xml_city :: Maybe String,
201 xml_state :: Maybe String,
202 xml_country :: String }
206 instance ToDb NewsLocationXml where
207 -- | The database analogue of a NewsLocationXml is a Location.
208 type Db NewsLocationXml = Location
211 instance FromXml NewsLocationXml where
212 -- | To convert from the XML representation to the database one, we
213 -- don't have to do anything. Just copy the fields.
215 from_xml NewsLocationXml{..} =
216 Location xml_city xml_state xml_country
219 -- | Allow us to import the XML representation directly into the
220 -- database, without having to perform the conversion manually first.
222 instance XmlImport NewsLocationXml
227 -- | Mapping between 'News' records and 'Location' records in the
228 -- database. We don't name the fields because we don't use the names
229 -- explicitly; that means we have to give them nice database names
232 data News_Location = News_Location
234 (DefaultKey Location)
242 -- | Define 'dbmigrate' and 'dbimport' for 'Message's. The import is
243 -- slightly non-generic because of our 'News_NewsTeam' and
244 -- 'News_Location' join tables.
246 instance DbImport Message where
249 migrate (undefined :: Location)
250 migrate (undefined :: News)
251 migrate (undefined :: NewsTeam)
252 migrate (undefined :: News_NewsTeam)
253 migrate (undefined :: News_Location)
255 dbimport message = do
256 -- Insert the message and acquire its primary key (unique ID)
257 news_id <- insert_xml message
259 -- Now insert the teams. We use insert_or_select because we know
260 -- that most teams will already exist, and we want to get back the
261 -- id for the existing team when there's a collision.
262 nt_ids <- mapM insert_or_select (xml_teams message)
264 -- Now that the teams have been inserted, create
265 -- news__news_team records mapping beween the two.
266 let news_news_teams = map (News_NewsTeam news_id) nt_ids
267 mapM_ insert_ news_news_teams
269 -- Do all of that over again for the Locations.
270 loc_ids <- mapM insert_xml_or_select (xml_locations message)
271 let news_news_locations = map (News_Location news_id) loc_ids
272 mapM_ insert_ news_news_locations
274 return ImportSucceeded
277 -- These types don't have special XML representations or field name
278 -- collisions so we use the defaultCodegenConfig and give their
279 -- fields nice simple names.
280 mkPersist defaultCodegenConfig [groundhog|
286 - name: unique_news_team
293 -- These types have fields with e.g. db_ and xml_ prefixes, so we
294 -- use our own codegen to peel those off before naming the columns.
295 mkPersist tsn_codegen_config [groundhog|
302 # Prevent multiple imports of the same message.
303 fields: [db_xml_file_id]
307 - {name: msg_id, dbName: msg_id}
308 - {name: event_id, dbName: event_id}
317 - entity: News_NewsTeam
318 dbName: news__news_teams
320 - name: News_NewsTeam
322 - name: news_NewsTeam0 # Default created by mkNormalFieldName
326 - name: news_NewsTeam1 # Default created by mkNormalFieldName
327 dbName: news_teams_id
331 - entity: News_Location
332 dbName: news__locations
334 - name: News_Location
336 - name: news_Location0 # Default created by mkNormalFieldName
340 - name: news_Location1 # Default created by mkNormalFieldName
351 -- | Convert a 'NewsTeam' to/from XML.
353 pickle_news_team :: PU NewsTeam
356 xpWrap (from_string, to_string) xpText
358 to_string :: NewsTeam -> String
359 to_string = team_name
361 from_string :: String -> NewsTeam
362 from_string = NewsTeam
365 -- | Convert a 'MsgId' to/from XML.
367 pickle_msg_id :: PU MsgId
370 xpWrap (from_tuple, to_tuple) $
371 xpPair xpInt (xpAttr "EventId" (xpOption xpInt))
373 from_tuple = uncurryN MsgId
374 to_tuple m = (db_msg_id m, db_event_id m)
377 -- | Convert a 'NewsLocationXml' to/from XML.
379 pickle_location :: PU NewsLocationXml
382 xpWrap (from_tuple, to_tuple) $
383 xpTriple (xpOption (xpElem "city" xpText))
384 (xpOption (xpElem "state" xpText))
385 (xpElem "country" xpText)
388 uncurryN NewsLocationXml
389 to_tuple l = (xml_city l, xml_state l, xml_country l)
392 -- | Convert a 'Message' to/from XML.
394 pickle_message :: PU Message
397 xpWrap (from_tuple, to_tuple) $
398 xp13Tuple (xpElem "XML_File_ID" xpInt)
399 (xpElem "heading" xpText)
401 (xpElem "category" xpText)
402 (xpElem "sport" xpText)
403 (xpElem "url" $ xpOption xpText)
404 (xpList pickle_news_team)
405 (xpList pickle_location)
406 (xpElem "SMS" xpText)
407 (xpOption (xpElem "Editor" xpText))
408 (xpOption (xpElem "text" xpText))
410 (xpElem "time_stamp" xp_time_stamp)
412 from_tuple = uncurryN Message
413 to_tuple m = (xml_xml_file_id m, -- Verbose,
414 xml_heading m, -- but
415 xml_mid m, -- eliminates
416 xml_category m, -- GHC
417 xml_sport m, -- warnings
420 xml_locations m, -- .
427 -- | We combine all of the \<continue\> elements into one 'String'
428 -- while unpickling and do the reverse while pickling.
430 pickle_continue :: PU (Maybe String)
433 xpWrap (to_string, from_string) $
435 xpList (xpElem "P" xpText)
437 from_string :: String -> [String]
438 from_string = split "\n"
440 to_string :: [String] -> String
441 to_string = join "\n"
448 -- | A list of all tests for this module.
450 news_tests :: TestTree
454 [ test_news_fields_have_correct_names,
455 test_on_delete_cascade,
456 test_pickle_of_unpickle_is_identity,
457 test_unpickle_succeeds ]
460 -- | Make sure our codegen is producing the correct database names.
462 test_news_fields_have_correct_names :: TestTree
463 test_news_fields_have_correct_names =
464 testCase "news fields get correct database names" $
465 mapM_ check (zip actual expected)
467 -- This is cool, it uses the (derived) Data instance of
468 -- News.News to get its constructor names.
469 field_names :: [String]
471 constrFields . head $ dataTypeConstrs $ dataTypeOf (undefined :: News)
475 map (\x -> tsn_db_field_namer "herp" "derp" 8675309 x 90210) field_names
478 actual = ["xml_file_id",
487 check (x,y) = (x @?= y)
490 -- | If we unpickle something and then pickle it, we should wind up
491 -- with the same thing we started with. WARNING: success of this
492 -- test does not mean that unpickling succeeded.
494 test_pickle_of_unpickle_is_identity :: TestTree
495 test_pickle_of_unpickle_is_identity = testGroup "pickle-unpickle tests"
496 [ check "pickle composed with unpickle is the identity"
497 "test/xml/newsxml.xml",
499 check "pickle composed with unpickle is the identity (with Editor)"
500 "test/xml/newsxml-with-editor.xml" ]
502 check desc path = testCase desc $ do
503 (expected, actual) <- pickle_unpickle pickle_message path
507 -- | Make sure we can actually unpickle these things.
509 test_unpickle_succeeds :: TestTree
510 test_unpickle_succeeds = testGroup "unpickle tests"
511 [ check "unpickling succeeds"
512 "test/xml/newsxml.xml",
514 check "unpickling succeeds (with Editor)"
515 "test/xml/newsxml-with-editor.xml" ]
517 check desc path = testCase desc $ do
518 actual <- unpickleable path pickle_message
523 -- | Make sure everything gets deleted when we delete the top-level
526 test_on_delete_cascade :: TestTree
527 test_on_delete_cascade = testGroup "cascading delete tests"
528 [ check "deleting news deletes its children"
529 "test/xml/newsxml.xml"
530 4 -- 2 news_teams and 2 news_locations that should remain.
533 check desc path expected = testCase desc $ do
534 news <- unsafe_unpickle path pickle_message
535 let a = undefined :: Location
536 let b = undefined :: News
537 let c = undefined :: NewsTeam
538 let d = undefined :: News_NewsTeam
539 let e = undefined :: News_Location
540 actual <- withSqliteConn ":memory:" $ runDbConn $ do
541 runMigration silentMigrationLogger $ do
549 count_a <- countAll a
550 count_b <- countAll b
551 count_c <- countAll c
552 count_d <- countAll d
553 count_e <- countAll e
554 return $ count_a + count_b + count_c + count_d + count_e