1 {-# LANGUAGE BangPatterns #-}
2 {-# LANGUAGE DeriveDataTypeable #-}
3 {-# LANGUAGE FlexibleInstances #-}
5 {-# LANGUAGE QuasiQuotes #-}
6 {-# LANGUAGE RecordWildCards #-}
7 {-# LANGUAGE ScopedTypeVariables #-}
8 {-# LANGUAGE StandaloneDeriving #-}
9 {-# LANGUAGE TemplateHaskell #-}
10 {-# LANGUAGE TypeFamilies #-}
12 -- | Parse TSN XML for the DTD "newsxml.dtd". Each document contains a
13 -- root element \<message\> that contains an entire news item.
20 import Data.Data ( Data, constrFields, dataTypeConstrs, dataTypeOf )
21 import Data.List.Utils ( join, split )
22 import Data.Tuple.Curry ( uncurryN )
23 import Data.Typeable ( Typeable )
24 import Database.Groundhog (
25 defaultMigrationLogger,
30 import Database.Groundhog.Core ( DefaultKey )
31 import Database.Groundhog.TH (
35 import System.Console.CmdArgs.Default ( Default(..) )
36 import Test.Tasty ( TestTree, testGroup )
37 import Test.Tasty.HUnit ( (@?=), testCase )
38 import Text.XML.HXT.Core (
55 tsn_db_field_namer ) -- Used in a test
56 import TSN.DbImport ( DbImport(..), ImportResult(..) )
57 import Xml ( ToFromXml(..), pickle_unpickle, unpickleable )
61 -- | The database type for teams as they show up in the news.
63 NewsTeam { team_name :: String }
66 -- | Mapping between News records and NewsTeam records in the
67 -- database. We name the fields (even though they're never used) for
68 -- Groundhog's benefit.
71 nnt_news_id :: DefaultKey News,
72 nnt_news_team_id :: DefaultKey NewsTeam }
74 -- | The database type for locations as they show up in the news.
78 state :: Maybe String,
82 -- | Mapping between News records and NewsLocation records in the
83 -- database. We name the fields (even though they're never used) for
84 -- Groundhog's benefit.
85 data News_NewsLocation =
87 nnl_news_id :: DefaultKey News,
88 nnl_news_location_id :: DefaultKey NewsLocation }
91 -- | The msg_id child of <message> contains an event_id attribute; we
92 -- embed it into the 'News' type. We (pointlessly) use the "db_"
93 -- prefix here so that the two names collide on "id" when Groundhog
94 -- is creating its fields using our field namer.
98 db_event_id :: Maybe Int }
99 deriving (Data, Eq, Show, Typeable)
104 xml_xml_file_id :: Int,
105 xml_heading :: String,
107 xml_category :: String,
110 xml_teams :: [NewsTeam],
111 xml_locations :: [NewsLocation],
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 :: String }
125 db_editor :: Maybe String,
126 db_text :: Maybe String,
127 db_continue :: Maybe String }
128 deriving (Data, Eq, Show, Typeable)
130 instance ToFromXml News where
131 type Xml News = Message
132 type Container News = ()
134 -- Use a record wildcard here so GHC doesn't complain that we never
135 -- used our named fields.
152 -- We don't need the key argument (from_xml_fk) since the XML type
153 -- contains more information in this case.
154 from_xml (Message _ _ c _ e f _ _ i j k l _) =
158 -- These types don't have special XML representations or field name
159 -- collisions so we use the defaultCodegenConfig and give their fields
160 -- nice simple names.
161 mkPersist defaultCodegenConfig [groundhog|
167 - name: unique_news_team
171 - entity: NewsLocation
172 dbName: news_locations
176 - name: unique_news_location
178 fields: [city, state, country]
182 mkPersist tsn_codegen_config [groundhog|
190 - {name: msg_id, dbName: msg_id}
191 - {name: event_id, dbName: event_id}
200 - entity: News_NewsTeam
201 dbName: news__news_teams
203 - entity: News_NewsLocation
204 dbName: news__news_locations
207 pickle_news_team :: PU NewsTeam
210 xpWrap (from_string, to_string) xpText
212 to_string :: NewsTeam -> String
213 to_string = team_name
215 from_string :: String -> NewsTeam
216 from_string = NewsTeam
218 instance XmlPickler NewsTeam where
219 xpickle = pickle_news_team
221 pickle_msg_id :: PU MsgId
224 xpWrap (from_tuple, to_tuple) $
225 xpPair xpInt (xpAttr "EventId" (xpOption xpInt))
227 from_tuple = uncurryN MsgId
228 to_tuple m = (db_msg_id m, db_event_id m)
230 instance XmlPickler MsgId where
231 xpickle = pickle_msg_id
233 pickle_location :: PU NewsLocation
236 xpWrap (from_tuple, to_tuple) $
237 xpTriple (xpOption (xpElem "city" xpText))
238 (xpOption (xpElem "state" xpText))
239 (xpElem "country" xpText)
242 uncurryN NewsLocation
243 to_tuple l = (city l, state l, country l)
245 instance XmlPickler NewsLocation where
246 xpickle = pickle_location
249 pickle_message :: PU Message
252 xpWrap (from_tuple, to_tuple) $
253 xp13Tuple (xpElem "XML_File_ID" xpInt)
254 (xpElem "heading" xpText)
256 (xpElem "category" xpText)
257 (xpElem "sport" xpText)
258 (xpElem "url" xpText)
259 (xpList pickle_news_team)
260 (xpList pickle_location)
261 (xpElem "SMS" xpText)
262 (xpOption (xpElem "Editor" xpText))
263 (xpOption (xpElem "text" xpText))
265 (xpElem "time_stamp" xpText)
267 from_tuple = uncurryN Message
268 to_tuple m = (xml_xml_file_id m,
282 pickle_continue :: PU (Maybe String)
285 xpWrap (to_string, from_string) $
287 xpList (xpElem "P" xpText)
289 from_string :: String -> [String]
290 from_string = split "\n"
292 to_string :: [String] -> String
293 to_string = join "\n"
295 instance XmlPickler Message where
296 xpickle = pickle_message
300 instance DbImport News where
302 runMigration defaultMigrationLogger $ do
303 migrate (undefined :: News)
304 migrate (undefined :: NewsTeam)
305 migrate (undefined :: NewsLocation)
306 migrate (undefined :: News_NewsTeam)
307 migrate (undefined :: News_NewsLocation)
308 let root_element = unpickleDoc xpickle xml :: Maybe Message
311 let errmsg = "Could not unpickle News message in dbimport."
312 return $ ImportFailed errmsg
314 -- Insert the message and acquire its primary key (unique ID)
315 news_id <- insert (from_xml message :: News)
317 -- And insert each one into its own table. We use insertByAll
318 -- because we know that most teams will already exist, and we
319 -- want to get back a Left (id) for the existing team when
320 -- there's a collision. In fact, if the insert succeeds, we'll
321 -- get a Right (id) back, so we can disregard the Either
322 -- constructor entirely. That's what the (either id id) does.
323 either_nt_ids <- mapM insertByAll (xml_teams message)
324 let nt_ids = map (either id id) either_nt_ids
326 -- Now that the teams have been inserted, create
327 -- news__news_team records mapping beween the two.
328 let news_news_teams = map (News_NewsTeam news_id) nt_ids
329 nnt_ids <- mapM insert news_news_teams
332 -- Do all of that over again for the NewsLocations.
333 either_loc_ids <- mapM insertByAll (xml_locations message)
334 let loc_ids = map (either id id) either_loc_ids
335 let news_news_locations = map (News_NewsLocation news_id) loc_ids
336 nnl_ids <- mapM insertByAll news_news_locations
338 return $ ImportSucceeded (1 + -- for the News
346 news_tests :: TestTree
350 [ test_news_fields_have_correct_names,
351 test_pickle_of_unpickle_is_identity,
352 test_unpickle_succeeds ]
355 test_news_fields_have_correct_names :: TestTree
356 test_news_fields_have_correct_names =
357 testCase "news fields get correct database names" $
358 mapM_ check (zip actual expected)
360 -- This is cool, it uses the (derived) Data instance of
361 -- News.News to get its constructor names.
362 field_names :: [String]
364 constrFields . head $ dataTypeConstrs $ dataTypeOf (undefined :: News)
368 map (\x -> tsn_db_field_namer "herp" "derp" 8675309 x 90210) field_names
371 actual = ["mid", "sport", "url", "sms", "editor", "text", "continue"]
373 check (x,y) = (x @?= y)
376 -- | Warning, succeess of this test does not mean that unpickling
378 test_pickle_of_unpickle_is_identity :: TestTree
379 test_pickle_of_unpickle_is_identity = testGroup "pickle-unpickle tests"
380 [ check "pickle composed with unpickle is the identity"
381 "test/xml/newsxml.xml",
383 check "pickle composed with unpickle is the identity (with Editor)"
384 "test/xml/newsxml-with-editor.xml" ]
386 check desc path = testCase desc $ do
387 (expected :: [Message], actual) <- pickle_unpickle "message" path
391 test_unpickle_succeeds :: TestTree
392 test_unpickle_succeeds = testGroup "unpickle tests"
393 [ check "unpickling succeeds"
394 "test/xml/newsxml.xml",
396 check "unpickling succeeds (with Editor)"
397 "test/xml/newsxml-with-editor.xml" ]
399 check desc path = testCase desc $ do
400 actual <- unpickleable path pickle_message