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