]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/TSN/XML/News.hs
Remove two unnecessary XML representations of teams/locations.
[dead/htsn-import.git] / src / TSN / XML / News.hs
1 {-# LANGUAGE DeriveDataTypeable #-}
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 \"newsxml.dtd\". Each document contains
10 -- a root element \<message\> that contains an entire news item.
11 --
12 module TSN.XML.News (
13 dtd,
14 pickle_message,
15 -- * Tests
16 news_tests,
17 -- * WARNING: these are private but exported to silence warnings
18 News_LocationConstructor(..),
19 News_NewsTeamConstructor(..),
20 NewsConstructor(..),
21 NewsTeamConstructor(..) )
22 where
23
24 -- System imports.
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 (
31 countAll,
32 deleteAll,
33 insert_,
34 migrate,
35 runMigration,
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 (
41 defaultCodegenConfig,
42 groundhog,
43 mkPersist )
44 import Test.Tasty ( TestTree, testGroup )
45 import Test.Tasty.HUnit ( (@?=), testCase )
46 import Text.XML.HXT.Core (
47 PU,
48 xp13Tuple,
49 xpAttr,
50 xpElem,
51 xpInt,
52 xpList,
53 xpOption,
54 xpPair,
55 xpText,
56 xpTriple,
57 xpWrap )
58
59 -- Local imports.
60 import TSN.Codegen (
61 tsn_codegen_config,
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(..) )
68 import Xml (
69 FromXml(..),
70 ToDb(..),
71 pickle_unpickle,
72 unpickleable,
73 unsafe_unpickle )
74
75
76 -- | The DTD to which this module corresponds. Used to invoke dbimport.
77 --
78 dtd :: String
79 dtd = "newsxml.dtd"
80
81
82 --
83 -- DB/XML Data types
84 --
85
86 -- * News/Message
87
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.
92 --
93 data MsgId =
94 MsgId {
95 db_msg_id :: Int,
96 db_event_id :: Maybe Int }
97 deriving (Data, Eq, Show, Typeable)
98
99
100 -- | The XML representation of a news item (\<message\>).
101 --
102 data Message =
103 Message {
104 xml_xml_file_id :: Int,
105 xml_heading :: String,
106 xml_mid :: MsgId,
107 xml_category :: String,
108 xml_sport :: String,
109 xml_url :: Maybe String,
110 xml_teams :: [NewsTeam],
111 xml_locations :: [Location],
112 xml_sms :: String,
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 }
117 deriving (Eq, Show)
118
119
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.
123 --
124 data News =
125 News {
126 db_xml_file_id :: Int,
127 db_mid :: MsgId,
128 db_sport :: String,
129 db_url :: Maybe String,
130 db_sms :: 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)
136
137
138
139 instance ToDb Message where
140 -- | The database representation of 'Message' is 'News'.
141 type Db Message = News
142
143 -- | Convert the XML representation 'Message' to the database
144 -- representation 'News'.
145 --
146 instance FromXml Message where
147 -- | We use a record wildcard so GHC doesn't complain that we never
148 -- used the field names.
149 --
150 from_xml Message{..} = News { db_xml_file_id = xml_xml_file_id,
151 db_mid = xml_mid,
152 db_sport = xml_sport,
153 db_url = xml_url,
154 db_sms = xml_sms,
155 db_editor = xml_editor,
156 db_text = xml_text,
157 db_continue = xml_continue,
158 db_time_stamp = xml_time_stamp }
159
160 -- | This lets us insert the XML representation 'Message' directly.
161 --
162 instance XmlImport Message
163
164
165 -- * NewsTeam
166
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
173 -- worth.)
174 --
175 data NewsTeam =
176 NewsTeam { team_name :: String }
177 deriving (Eq, Show)
178
179
180
181 -- * News_NewsTeam
182
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
186 -- via groundhog.
187 --
188 data News_NewsTeam = News_NewsTeam
189 (DefaultKey News)
190 (DefaultKey NewsTeam)
191
192
193 -- * News_Location
194
195 -- | Mapping between 'News' records and 'Location' records in the
196 -- database. We don't name the fields because we don't use the names
197 -- explicitly; that means we have to give them nice database names
198 -- via groundhog.
199 --
200 data News_Location = News_Location
201 (DefaultKey News)
202 (DefaultKey Location)
203
204
205
206 --
207 -- Database code
208 --
209
210 -- | Define 'dbmigrate' and 'dbimport' for 'Message's. The import is
211 -- slightly non-generic because of our 'News_NewsTeam' and
212 -- 'News_Location' join tables.
213 --
214 instance DbImport Message where
215 dbmigrate _ =
216 run_dbmigrate $ do
217 migrate (undefined :: Location)
218 migrate (undefined :: News)
219 migrate (undefined :: NewsTeam)
220 migrate (undefined :: News_NewsTeam)
221 migrate (undefined :: News_Location)
222
223 dbimport message = do
224 -- Insert the message and acquire its primary key (unique ID)
225 news_id <- insert_xml message
226
227 -- Now insert the teams. We use insert_or_select because we know
228 -- that most teams will already exist, and we want to get back the
229 -- id for the existing team when there's a collision.
230 nt_ids <- mapM insert_or_select (xml_teams message)
231
232 -- Now that the teams have been inserted, create
233 -- news__news_team records mapping beween the two.
234 let news_news_teams = map (News_NewsTeam news_id) nt_ids
235 mapM_ insert_ news_news_teams
236
237 -- Do all of that over again for the Locations.
238 loc_ids <- mapM insert_or_select (xml_locations message)
239 let news_news_locations = map (News_Location news_id) loc_ids
240 mapM_ insert_ news_news_locations
241
242 return ImportSucceeded
243
244
245 -- These types don't have special XML representations or field name
246 -- collisions so we use the defaultCodegenConfig and give their
247 -- fields nice simple names.
248 mkPersist defaultCodegenConfig [groundhog|
249 - entity: NewsTeam
250 dbName: news_teams
251 constructors:
252 - name: NewsTeam
253 uniques:
254 - name: unique_news_team
255 type: constraint
256 fields: [team_name]
257
258 |]
259
260
261 -- These types have fields with e.g. db_ and xml_ prefixes, so we
262 -- use our own codegen to peel those off before naming the columns.
263 mkPersist tsn_codegen_config [groundhog|
264 - entity: News
265 constructors:
266 - name: News
267 uniques:
268 - name: unique_news
269 type: constraint
270 # Prevent multiple imports of the same message.
271 fields: [db_xml_file_id]
272 fields:
273 - name: db_mid
274 embeddedType:
275 - {name: msg_id, dbName: msg_id}
276 - {name: event_id, dbName: event_id}
277
278 - embedded: MsgId
279 fields:
280 - name: db_msg_id
281 dbName: msg_id
282 - name: db_event_id
283 dbName: event_id
284
285 - entity: News_NewsTeam
286 dbName: news__news_teams
287 constructors:
288 - name: News_NewsTeam
289 fields:
290 - name: news_NewsTeam0 # Default created by mkNormalFieldName
291 dbName: news_id
292 reference:
293 onDelete: cascade
294 - name: news_NewsTeam1 # Default created by mkNormalFieldName
295 dbName: news_teams_id
296 reference:
297 onDelete: cascade
298
299 - entity: News_Location
300 dbName: news__locations
301 constructors:
302 - name: News_Location
303 fields:
304 - name: news_Location0 # Default created by mkNormalFieldName
305 dbName: news_id
306 reference:
307 onDelete: cascade
308 - name: news_Location1 # Default created by mkNormalFieldName
309 dbName: locations_id
310 reference:
311 onDelete: cascade
312 |]
313
314
315 --
316 -- XML Picklers
317 --
318
319 -- | Convert a 'NewsTeam' to/from XML.
320 --
321 pickle_news_team :: PU NewsTeam
322 pickle_news_team =
323 xpElem "team" $
324 xpWrap (from_string, to_string) xpText
325 where
326 to_string :: NewsTeam -> String
327 to_string = team_name
328
329 from_string :: String -> NewsTeam
330 from_string = NewsTeam
331
332
333 -- | Convert a 'MsgId' to/from XML.
334 --
335 pickle_msg_id :: PU MsgId
336 pickle_msg_id =
337 xpElem "msg_id" $
338 xpWrap (from_tuple, to_tuple) $
339 xpPair xpInt (xpAttr "EventId" (xpOption xpInt))
340 where
341 from_tuple = uncurryN MsgId
342 to_tuple m = (db_msg_id m, db_event_id m)
343
344
345 -- | Convert a 'Location' to/from XML.
346 --
347 pickle_location :: PU Location
348 pickle_location =
349 xpElem "location" $
350 xpWrap (from_tuple, to_tuple) $
351 xpTriple (xpOption (xpElem "city" xpText))
352 (xpOption (xpElem "state" xpText))
353 (xpElem "country" xpText)
354 where
355 from_tuple =
356 uncurryN Location
357 to_tuple l = (city l, state l, country l)
358
359
360 -- | Convert a 'Message' to/from XML.
361 --
362 pickle_message :: PU Message
363 pickle_message =
364 xpElem "message" $
365 xpWrap (from_tuple, to_tuple) $
366 xp13Tuple (xpElem "XML_File_ID" xpInt)
367 (xpElem "heading" xpText)
368 pickle_msg_id
369 (xpElem "category" xpText)
370 (xpElem "sport" xpText)
371 (xpElem "url" $ xpOption xpText)
372 (xpList pickle_news_team)
373 (xpList pickle_location)
374 (xpElem "SMS" xpText)
375 (xpOption (xpElem "Editor" xpText))
376 (xpOption (xpElem "text" xpText))
377 pickle_continue
378 (xpElem "time_stamp" xp_time_stamp)
379 where
380 from_tuple = uncurryN Message
381 to_tuple m = (xml_xml_file_id m, -- Verbose,
382 xml_heading m, -- but
383 xml_mid m, -- eliminates
384 xml_category m, -- GHC
385 xml_sport m, -- warnings
386 xml_url m, -- .
387 xml_teams m, -- .
388 xml_locations m, -- .
389 xml_sms m,
390 xml_editor m,
391 xml_text m,
392 xml_continue m,
393 xml_time_stamp m)
394
395 -- | We combine all of the \<continue\> elements into one 'String'
396 -- while unpickling and do the reverse while pickling.
397 --
398 pickle_continue :: PU (Maybe String)
399 pickle_continue =
400 xpOption $
401 xpWrap (to_string, from_string) $
402 xpElem "continue" $
403 xpList (xpElem "P" xpText)
404 where
405 from_string :: String -> [String]
406 from_string = split "\n"
407
408 to_string :: [String] -> String
409 to_string = join "\n"
410
411
412 --
413 -- Tasty Tests
414 --
415
416 -- | A list of all tests for this module.
417 --
418 news_tests :: TestTree
419 news_tests =
420 testGroup
421 "News tests"
422 [ test_news_fields_have_correct_names,
423 test_on_delete_cascade,
424 test_pickle_of_unpickle_is_identity,
425 test_unpickle_succeeds ]
426
427
428 -- | Make sure our codegen is producing the correct database names.
429 --
430 test_news_fields_have_correct_names :: TestTree
431 test_news_fields_have_correct_names =
432 testCase "news fields get correct database names" $
433 mapM_ check (zip actual expected)
434 where
435 -- This is cool, it uses the (derived) Data instance of
436 -- News.News to get its constructor names.
437 field_names :: [String]
438 field_names =
439 constrFields . head $ dataTypeConstrs $ dataTypeOf (undefined :: News)
440
441 expected :: [String]
442 expected =
443 map (\x -> tsn_db_field_namer "herp" "derp" 8675309 x 90210) field_names
444
445 actual :: [String]
446 actual = ["xml_file_id",
447 "mid",
448 "sport",
449 "url",
450 "sms",
451 "editor",
452 "text",
453 "continue"]
454
455 check (x,y) = (x @?= y)
456
457
458 -- | If we unpickle something and then pickle it, we should wind up
459 -- with the same thing we started with. WARNING: success of this
460 -- test does not mean that unpickling succeeded.
461 --
462 test_pickle_of_unpickle_is_identity :: TestTree
463 test_pickle_of_unpickle_is_identity = testGroup "pickle-unpickle tests"
464 [ check "pickle composed with unpickle is the identity"
465 "test/xml/newsxml.xml",
466
467 check "pickle composed with unpickle is the identity (with Editor)"
468 "test/xml/newsxml-with-editor.xml" ]
469 where
470 check desc path = testCase desc $ do
471 (expected, actual) <- pickle_unpickle pickle_message path
472 actual @?= expected
473
474
475 -- | Make sure we can actually unpickle these things.
476 --
477 test_unpickle_succeeds :: TestTree
478 test_unpickle_succeeds = testGroup "unpickle tests"
479 [ check "unpickling succeeds"
480 "test/xml/newsxml.xml",
481
482 check "unpickling succeeds (with Editor)"
483 "test/xml/newsxml-with-editor.xml" ]
484 where
485 check desc path = testCase desc $ do
486 actual <- unpickleable path pickle_message
487 let expected = True
488 actual @?= expected
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 = testGroup "cascading delete tests"
496 [ check "deleting news deletes its children"
497 "test/xml/newsxml.xml"
498 4 -- 2 news_teams and 2 news_locations that should remain.
499 ]
500 where
501 check desc path expected = testCase desc $ do
502 news <- unsafe_unpickle path pickle_message
503 let a = undefined :: Location
504 let b = undefined :: News
505 let c = undefined :: NewsTeam
506 let d = undefined :: News_NewsTeam
507 let e = undefined :: News_Location
508 actual <- withSqliteConn ":memory:" $ runDbConn $ do
509 runMigration silentMigrationLogger $ do
510 migrate a
511 migrate b
512 migrate c
513 migrate d
514 migrate e
515 _ <- dbimport news
516 deleteAll b
517 count_a <- countAll a
518 count_b <- countAll b
519 count_c <- countAll c
520 count_d <- countAll d
521 count_e <- countAll e
522 return $ count_a + count_b + count_c + count_d + count_e
523 actual @?= expected