1 {-# LANGUAGE NoMonomorphismRestriction #-}
5 import Control.Arrow ( (&&&), arr, returnA )
6 import Control.Monad ( when )
7 import Control.Monad.IO.Class ( liftIO )
8 import Database.Groundhog (
9 defaultMigrationLogger,
13 import Database.Groundhog.Core ( PersistEntity )
14 import Database.Groundhog.Generic ( runDbConn )
15 import Database.Groundhog.Sqlite (
17 import Database.Groundhog.Postgresql (
19 import Data.Monoid ( (<>) )
20 import System.Console.CmdArgs ( def )
21 import System.Exit ( exitWith, ExitCode (ExitFailure) )
22 import System.IO.Error ( catchIOError )
23 import Text.XML.HXT.Core (
45 import Backend ( Backend(..) )
46 import CommandLine ( get_args )
47 import Configuration ( Configuration(..), merge_optional )
48 import ConnectionString ( ConnectionString(..) )
49 import ExitCodes ( exit_no_xml_files )
50 import Network.Services.TSN.Logging ( init_logging )
51 import qualified OptionalConfiguration as OC (
52 OptionalConfiguration ( xml_files ),
54 import Network.Services.TSN.Report (
57 import qualified TSN.Injuries as Injuries (
59 Message ( listings ) )
60 import qualified TSN.InjuriesDetail as InjuriesDetail (
61 Listing ( player_listings ),
67 -- | A list of options passed to 'readDocument' when we parse an XML
68 -- document. We don't validate because the DTDs from TSN are
69 -- wrong. As a result, we don't want to keep useless DTDs
70 -- areound. Thus we disable 'withSubstDTDEntities' which, when
71 -- combined with "withValidate no", prevents HXT from trying to read
74 parse_opts :: SysConfigList
76 [ withPreserveComment no,
78 withSubstDTDEntities no,
82 -- | We put the 'Configuration' and 'XmlTree' arguments last so that
83 -- it's easy to eta reduce all of the import_foo functions that call
86 import_generic :: (XmlPickler a, PersistEntity b)
87 => b -- ^ Dummy Listing instance needed for 'migrate'
88 -> (a -> [b]) -- ^ listings getter
91 -> IO (Maybe Int) -- ^ Return the number of records inserted.
92 import_generic dummy g cfg xml
93 | backend cfg == Postgres = withPostgresqlConn cs go
94 | otherwise = withSqliteConn cs go
96 -- | Pull the real connection String out of the configuration.
98 cs = get_connection_string $ connection_string cfg
100 -- Needs NoMonomorphismRestriction to be allowed to return
101 -- different types in the two cases above.
103 runMigration defaultMigrationLogger $ migrate dummy
104 let root_element = unpickleDoc xpickle xml
107 let msg = "Could not unpickle document in import_generic."
108 liftIO $ report_error msg
111 ids <- mapM insert (g elt)
112 return $ Just (length ids)
116 -- | Import TSN.Injuries from an 'XmlTree'.
117 import_injuries :: Configuration -> XmlTree -> IO (Maybe Int)
120 (undefined :: Injuries.Listing)
123 -- | Import TSN.InjuriesDetail from an 'XmlTree'.
124 import_injuries_detail :: Configuration -> XmlTree -> IO (Maybe Int)
125 import_injuries_detail =
127 (undefined :: InjuriesDetail.PlayerListing)
128 ( (concatMap InjuriesDetail.player_listings) . InjuriesDetail.listings)
130 import_file :: Configuration -> FilePath -> IO ()
131 import_file cfg path = do
132 results <- catchIOError
135 report_error (show e)
136 report_error $ "Failed to import file " ++ path ++ "."
137 -- Return a nonempty list so we don't claim incorrectly that
138 -- we couldn't parse the DTD.
142 -- If results' is empty, one of the arrows return "nothing."
143 [] -> report_error $ "Unable to determine DTD for file " ++ path ++ "."
147 Just cnt -> report_info $ "Successfully imported " ++
149 " records from " ++ path ++ "."
151 -- | An arrow that reads a document into an 'XmlTree'.
152 readA :: IOStateArrow s a XmlTree
153 readA = readDocument parse_opts path
155 -- | An arrow which parses the doctype "SYSTEM" of an 'XmlTree'.
156 -- We use these to determine the parser to use.
157 doctypeA :: ArrowXml a => a XmlTree String
158 doctypeA = getAttrl >>> hasName "doctype-SYSTEM" /> getText
160 -- | Combine the arrows above as well as the function below
161 -- (arrowized with 'arr') into an IO action that does everything
162 -- (parses and then runs the import on what was parsed).
164 -- The result of runX has type IO [IO (Maybe Int)]. We thus use
165 -- bind (>>=) and sequence to combine all of the IOs into one
166 -- big one outside of the list.
167 parse_and_import :: IO [Maybe Int]
169 runX (readA >>> (doctypeA &&& returnA) >>> (arr import_with_dtd))
173 -- | Takes a 'Doctype', 'XmlTree' pair and uses the 'Doctype' to
174 -- determine which function to call on the 'XmlTree'.
175 import_with_dtd :: (String, XmlTree) -> IO (Maybe Int)
176 import_with_dtd (dtd,xml)
177 | dtd == "injuriesxml.dtd" = import_injuries cfg xml
178 | dtd == "Injuries_Detail_XML.dtd" = import_injuries_detail cfg xml
180 report_info $ "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
188 -- Merge the config file options with the command-line ones,
189 -- prefering the command-line ones.
190 let opt_config = rc_cfg <> cmd_cfg
192 -- Update a default config with any options that have been set in
193 -- either the config file or on the command-line. We initialize
194 -- logging before the missing parameter checks below so that we can
196 let cfg = (def :: Configuration) `merge_optional` opt_config
197 init_logging (log_file cfg) (log_level cfg) (syslog cfg)
199 -- Check the optional config for missing required options.
200 when (null $ OC.xml_files opt_config) $ do
201 report_error "No XML files given."
202 exitWith (ExitFailure exit_no_xml_files)
204 -- We don't do this in parallel (for now?) to keep the error
205 -- messages nice and linear.
206 mapM_ (import_file cfg) (OC.xml_files opt_config)