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