4 htsn-import \- Import XML files from The Sports Network into an RDBMS.
8 \fBhtsn-import\fR [OPTIONS] [FILES]
12 The Sports Network <http://www.sportsnetwork.com/> offers an XML feed
13 containing various sports news and statistics. Our sister program
14 \fBhtsn\fR is capable of retrieving the feed and saving the individual
15 XML documents contained therein. But what to do with them?
17 The purpose of \fBhtsn-import\fR is to take these XML documents and
18 get them into something we can use, a relational database management
19 system (RDBMS), otherwise known as a SQL database. The structure of
20 relational database, is, well, relational, and the feed XML is not. So
21 there is some work to do before the data can be imported into the
24 First, we must parse the XML. Each supported document type (see below)
25 has a full pickle/unpickle implementation (\(dqpickle\(dq is simply a
26 synonym for \(dqserialize\(dq here). That means that we parse the
27 entire document into a data structure, and if we pickle (serialize)
28 that data structure, we get the exact same XML document tha we started
31 This is important for two reasons. First, it serves as a second level
32 of validation. The first validation is performed by the XML parser,
33 but if that succeeds and unpicking fails, we know that something is
34 fishy. Second, we don't ever want to be surprised by some new element
35 or attribute showing up in the XML. The fact that we can unpickle the
36 whole thing now means that we won't be surprised in the future.
38 The aforementioned feature is especially important because we
39 automatically migrate the database schema every time we import a
40 document. If you attempt to import a \(dqnewsxml.dtd\(dq document, all
41 database objects relating to the news will be created if they do not
42 exist. We don't want the schema to change out from under us without
43 warning, so it's important that no XML be parsed that would result in
44 a different schema than we had previously. Since we can
45 pickle/unpickle everything already, this should be impossible.
47 A list of supported document types is given in the appendix.
49 The GameInfo and SportInfo types do not have their own top-level
50 tables in the database. Instead, their raw XML is stored in either the
51 \(dqgame_info\(dq or \(dqsport_info\(dq table respectively.
55 At the top level (with two notable exceptions), we have one table for
56 each of the XML document types that we import. For example, the
57 documents corresponding to \fInewsxml.dtd\fR will have a table called
58 \(dqnews\(dq. All top-level tables contain two important fields,
59 \(dqxml_file_id\(dq and \(dqtime_stamp\(dq. The former is unique and
60 prevents us from inserting the same data twice. The time stamp on the
61 other hand lets us know when the data is old and can be removed. The
62 database schema make it possible to delete only the outdated top-level
63 records; all transient children should be removed by triggers.
65 These top-level tables will often have children. For example, each
66 news item has zero or more locations associated with it. The child
67 table will be named <parent>_<children>, which in this case
68 corresponds to \(dqnews_locations\(dq.
70 To relate the two, a third table may exist with name
71 <parent>__<child>. Note the two underscores. This prevents ambiguity
72 when the child table itself contains underscores. The table joining
73 \(dqnews\(dq with \(dqnews_locations\(dq is thus called
74 \(dqnews__news_locations\(dq. This is necessary when the child table
75 has a unique constraint; we don't want to blindly insert duplicate
76 records keyed to the parent. Instead we'd like to use the third table
77 to map an existing child to the new parent.
79 Where it makes sense, children are kept unique to prevent pointless
80 duplication. This slows down inserts, and speeds up reads (which are
81 much more frequent). There is a tradeoff to be made, however. For a
82 table with a small, fixed upper bound on the number of rows (like
83 \(dqodds_casinos\(dq), there is great benefit to de-duplication. The
84 total number of rows stays small, so inserts are still quick, and many
85 duplicate rows are eliminated.
87 But, with a table like \(dqodds_games\(dq, the number of games grows
88 quickly and without bound. It is therefore more beneficial to be able
89 to delete the old games (through an ON DELETE CASCADE, tied to
90 \(dqodds\(dq) than it is to eliminate duplication. A table like
91 \(dqnews_locations\(dq is somewhere in-between. It is hoped that the
92 unique constraint in the top-level table's \(dqxml_file_id\(dq will
93 prevent duplication in this case anyway.
95 The aforementioned exceptions are the \(dqgame_info\(dq and
96 \(dqsport_info\(dq tables. These tables contain the raw XML for a
97 number of DTDs that are not handled individually. This is partially
98 for backwards-compatibility with a legacy implementation, but is
99 mostly a stopgap due to a lack of resources at the moment. These two
100 tables (game_info and sport_info) still possess timestamps that allow
101 us to prune old data.
103 UML diagrams of the resulting database schema for each XML document
104 type are provided with the \fBhtsn-import\fR documentation, in the
105 \fIdoc/dbschema\fR directory. These are not authoritative, but it
106 should be considered a bug if they are incorrect. The diagrams are
107 created using the pgModeler <http://www.pgmodeler.com.br/> tool.
109 .SH XML SCHEMA GENERATION
111 In order to parse XML, you need to know the structure of your
112 documents. Usually this is given in the form of a DTD or schema. The
113 Sports Network does provide DTDs for their XML, but unfortunately many
114 of them do not match the XML found on the feed.
116 We need to construct a database into which to insert the XML. How do
117 we know if <game> should be a column, or if it should have its own
118 table? We need to know how many times it can appear in the
119 document. So we need some form of specification. Since the supplied
120 DTDs are incorrect, we would like to generate them automatically.
122 The process should go something like,
124 Generate a DTD from the first foo.xml file we see. Call it foo.dtd.
126 Validate future foo documents against foo.dtd. If they all validate,
127 great. If one fails, add it to the corpus and update foo.dtd so
128 that both the original and the new foo.xml validate.
130 Repeat until no more failures occur. This can never be perfect:
131 tomorrow we could get a foo.xml that's wildly different from what
132 we've seen in the past. But it's the best we can hope for under
135 Enter XML-Schema-learner
136 <https://github.com/kore/XML-Schema-learner>. This tool can infer a
137 DTD from a set of sample XML files. The top-level \(dqschemagen\(dq
138 folder (in this project) contains a number of subfolders\(emone for
139 each type of document that we want to parse. Contained therein are XML
140 samples for that particular document type. These were hand-picked one
141 at a time according to the procedure above, and the complete set of
142 XML is what we use to generate the DTDs used by htsn-import.
144 To generate them, run `make schema` at the project
145 root. XML-Schema-learner will be invoked on each subfolder of
146 \(dqschemagen\(dq and will output the corresponding DTDs to the
147 \(dqschemagen\(dq folder.
149 Most of the production schemas are generated this way; however, a few
150 needed manual tweaking. The final, believed-to-be-correct schemas for
151 all supported document types can be found in the \(dqschema\(dq folder in
152 the project root. Having the correct DTDs available means you
153 don't need XML-Schema-learner available to install \fBhtsn-import\fR.
155 .SH XML SCHEMA UPDATES
157 If a new tag is added to an XML document type, \fBhtsn-import\fR will
158 most likely refuse to parse it, since the new documents no longer
159 match the existing DTD.
161 The first thing to do in that case is add the unparseable document to
162 the \(dqschemagen\(dq directory, and generate a new DTD that matches
163 both the old and new samples. Once a new, correct DTD has been
164 generated, it should be added to the \(dqschema\(dq directory. Then,
165 the parser can be updated and \fBhtsn-import\fR rebuilt.
167 At this point, \fBhtsn-import\fR should be capable of importing the
168 new document. But the addition of the new tag will most require new
169 fields in the database. Fortunately, easy migrations like this are
170 handled automatically. As an example, at one point, \fIOdds_XML.dtd\fR
171 did not contain the \(dqHStarter\(dq and \(dqAStarter\(dq elements
172 associated with its games. Suppose we parse one of the old documents
173 (without \(dqHStarter\(dq and \(dqAStarter\(dq) using an old version
174 of \fBhtsn-import\fR:
177 .I $ htsn-import --connection-string='foo.sqlite3' \\\\
178 .I " schemagen/Odds_XML/19996433.xml"
179 Migration: CREATE TABLE \(dqodds\(dq ...
180 Successfully imported schemagen/Odds_XML/19996433.xml.
181 Processed 1 document(s) total.
184 At this point, the database schema matches the old documents, i.e. the
185 ones without \fIAStarter\fR and \fIHStarter\fR. If we use a new
186 version of \fBhtsn-import\fR, supporting the new fields, the migration
187 is handled gracefully:
190 .I $ htsn-import --connection-string='foo.sqlite3' \\\\
191 .I " schemagen/Odds_XML/21315768.xml"
192 Migration: ALTER TABLE \(dqodds_games\(dq
193 ADD COLUMN \(dqaway_team_starter_id\(dq INTEGER;
194 Migration: ALTER TABLE \(dqodds_games\(dq
195 ADD COLUMN \(dqaway_team_starter_name\(dq VARCHAR;
196 Migration: ALTER TABLE \(dqodds_games\(dq
197 ADD COLUMN \(dqhome_team_starter_id\(dq INTEGER;
198 Migration: ALTER TABLE \(dqodds_games\(dq
199 ADD COLUMN \(dqhome_team_starter_name\(dq VARCHAR;
200 Successfully imported schemagen/Odds_XML/21315768.xml.
201 Processed 1 document(s) total.
204 If fields are removed from the schema, then manual intervention may be
208 .I $ htsn-import -b Postgres -c 'dbname=htsn user=postgres' \\\\
209 .I " schemagen/Odds_XML/19996433.xml"
210 ERROR: Database migration: manual intervention required.
211 The following actions are considered unsafe:
212 ALTER TABLE \(dqodds_games\(dq DROP COLUMN \(dqaway_team_starter_id\(dq
213 ALTER TABLE \(dqodds_games\(dq DROP COLUMN \(dqaway_team_starter_name\(dq
214 ALTER TABLE \(dqodds_games\(dq DROP COLUMN \(dqhome_team_starter_id\(dq
215 ALTER TABLE \(dqodds_games\(dq DROP COLUMN \(dqhome_team_starter_name\(dq
217 ERROR: Failed to import file schemagen/Odds_XML/19996433.xml.
218 Processed 0 document(s) total.
221 To fix these errors, manually invoke the SQL commands that were
225 .I $ psql -U postgres -d htsn \\\\
226 .I " -c 'ALTER TABLE odds_games DROP COLUMN away_team_starter_id;'"
228 .I $ psql -U postgres -d htsn \\\\
229 .I " -c 'ALTER TABLE odds_games DROP COLUMN away_team_starter_name;'"
231 .I $ psql -U postgres -d htsn \\\\
232 .I " -c 'ALTER TABLE odds_games DROP COLUMN home_team_starter_id;'"
234 .I $ psql -U postgres -d htsn \\\\
235 .I " -c 'ALTER TABLE odds_games DROP COLUMN home_team_starter_name;'"
239 After manually adjusting the schema, the import should succeed.
241 .SH XML SCHEMA ODDITIES
243 There are a number of problems with the XML on the wire. Even if we
244 construct the DTDs ourselves, the results are sometimes
245 inconsistent. Here we document a few of them.
250 The <Notes> elements here are supposed to be associated with a set of
251 <Game> elements, but since the pair
252 (<Notes>...</Notes><Game>...</Game>) can appear zero or more times,
253 this leads to ambiguity in parsing. We therefore ignore the notes
254 entirely (although a hack is employed to facilitate parsing). The same
255 thing goes for the newer <League_Name> element.
260 There appear to be two types of weather documents; the first has
261 <listing> contained within <forecast> and the second has <forecast>
262 contained within <listing>. While it would be possible to parse both,
263 it would greatly complicate things. The first form is more common, so
264 that's all we support for now. An example is provided as
265 schemagen/weatherxml/20143655.xml.
269 .IP \fB\-\-backend\fR,\ \fB\-b\fR
270 The RDBMS backend to use. Valid choices are \fISqlite\fR and
271 \fIPostgres\fR. Capitalization is important, sorry.
275 .IP \fB\-\-connection-string\fR,\ \fB\-c\fR
276 The connection string used for connecting to the database backend
277 given by the \fB\-\-backend\fR option. The default is appropriate for
278 the \fISqlite\fR backend.
280 Default: \(dq:memory:\(dq
282 .IP \fB\-\-log-file\fR
283 If you specify a file here, logs will be written to it (possibly in
284 addition to syslog). Can be either a relative or absolute path. It
285 will not be auto-rotated; use something like logrotate for that.
289 .IP \fB\-\-log-level\fR
290 How verbose should the logs be? We log notifications at four levels:
291 DEBUG, INFO, WARN, and ERROR. Specify the \(dqmost boring\(dq level of
292 notifications you would like to receive (in all-caps); more
293 interesting notifications will be logged as well. The debug output is
294 extremely verbose and will not be written to syslog even if you try.
298 .IP \fB\-\-remove\fR,\ \fB\-r\fR
299 Remove successfully processed files. If you enable this, you can see
300 at a glance which XML files are not being processed, because they're
301 all that should be left.
305 .IP \fB\-\-syslog\fR,\ \fB\-s\fR
306 Enable logging to syslog. On Windows this will attempt to communicate
307 (over UDP) with a syslog daemon on localhost, which will most likely
312 .SH CONFIGURATION FILE
314 Any of the command-line options mentioned above can be specified in a
315 configuration file instead. We first look for \(dqhtsn-importrc\(dq in
316 the system configuration directory. We then look for a file named
317 \(dq.htsn-importrc\(dq in the user's home directory. The latter will
320 The user's home directory is simply $HOME on Unix; on Windows it's
321 wherever %APPDATA% points. The system configuration directory is
322 determined by Cabal; the \(dqsysconfdir\(dq parameter during the
323 \(dqconfigure\(dq step is used.
325 The file's syntax is given by examples in the htsn-importrc.example file
326 (included with \fBhtsn-import\fR).
328 Options specified on the command-line override those in either
333 Import newsxml.xml into a preexisting sqlite database named \(dqfoo.sqlite3\(dq:
336 .I $ htsn-import --connection-string='foo.sqlite3' \\\\
337 .I " test/xml/newsxml.xml"
338 Successfully imported test/xml/newsxml.xml.
339 Imported 1 document(s) total.
342 Repeat the previous example, but delete newsxml.xml afterwards:
345 .I $ htsn-import --connection-string='foo.sqlite3' \\\\
346 .I " --remove test/xml/newsxml.xml"
347 Successfully imported test/xml/newsxml.xml.
348 Imported 1 document(s) total.
349 Removed processed file test/xml/newsxml.xml.
352 Use a Postgres database instead of the default Sqlite. This assumes
353 that you have a database named \(dqhtsn\(dq accessible to user
354 \(dqpostgres\(dq locally:
357 .I $ htsn-import --connection-string='dbname=htsn user=postgres' \\\\
358 .I " --backend=Postgres test/xml/newsxml.xml"
359 Successfully imported test/xml/newsxml.xml.
360 Imported 1 document(s) total.
366 Send bugs to michael@orlitzky.com.
368 .SH APPENDIX: SUPPORTED DOCUMENT TYPES
370 The XML document types obtained from the feed are uniquely identified
371 by their DTDs. We currently support documents with the following DTDs:
373 AutoRacingResultsXML.dtd
375 Auto_Racing_Schedule_XML.dtd
379 Injuries_Detail_XML.dtd
389 Schedule_Changes_XML.dtd
404 Matchup_NBA_NHL_XML.dtd
408 MLB_Gaming_Matchup_XML.dtd
418 NBA_Gaming_Matchup_XML.dtd
420 NBA_Playoff_Matchup_XML.dtd
426 NCAA_FB_Preview_XML.dtd
428 NFL_NCAA_FB_Matchup_XML.dtd
436 WorldBaseballPreviewXML.dtd
444 Cbask_All_Tourn_Teams_XML.dtd
452 Cbask_Conf_Standings_XML.dtd
454 Cbask_DivII_III_Indv_Stats_XML.dtd
456 Cbask_DivII_Team_Stats_XML.dtd
458 Cbask_DivIII_Team_Stats_XML.dtd
466 Cbask_Indv_Scoring_XML.dtd
472 CBASK_ReboundsXML.dtd
474 CBASK_ScoringLeadersXML.dtd
476 Cbask_Team_ThreePT_Made_XML.dtd
478 Cbask_Team_ThreePT_PCT_XML.dtd
480 Cbask_Team_Win_Pct_XML.dtd
482 Cbask_Top_Twenty_Five_XML.dtd
484 CBASK_TopTwentyFiveResult_XML.dtd
486 Cbask_Tourn_Awards_XML.dtd
488 Cbask_Tourn_Champs_XML.dtd
490 Cbask_Tourn_Indiv_XML.dtd
492 Cbask_Tourn_Leaders_XML.dtd
494 Cbask_Tourn_MVP_XML.dtd
496 Cbask_Tourn_Records_XML.dtd
498 LeagueScheduleXML.dtd
502 Minor_Baseball_League_Leaders_XML.dtd
504 Minor_Baseball_Standings_XML.dtd
506 Minor_Baseball_Transactions_XML.dtd
510 mlbdoublesleadersxml.dtd
512 MLBGamesPlayedXML.dtd
518 mlbhitsleadersxml.dtd
536 mlbrunsleadersxml.dtd
544 mlbsluggingpctxml.dtd
548 mlbstandxml_preseason.dtd
552 mlbtotalbasesleadersxml.dtd
554 mlbtriplesleadersxml.dtd
558 mlbwalksleadersxml.dtd
560 MLBXtraBaseHitsXML.dtd
562 MLB_Pitching_Appearances_Leaders.dtd
566 MLB_Pitching_Balks_Leaders.dtd
568 MLB_Pitching_CG_Leaders.dtd
570 MLB_Pitching_ER_Allowed_Leaders.dtd
572 MLB_Pitching_Hits_Allowed_Leaders.dtd
574 MLB_Pitching_Hit_Batters_Leaders.dtd
576 MLB_Pitching_HR_Allowed_Leaders.dtd
578 MLB_Pitching_IP_Leaders.dtd
580 MLB_Pitching_Runs_Allowed_Leaders.dtd
582 MLB_Pitching_Saves_Leaders.dtd
584 MLB_Pitching_Shut_Outs_Leaders.dtd
586 MLB_Pitching_Starts_Leaders.dtd
588 MLB_Pitching_Strike_Outs_Leaders.dtd
590 MLB_Pitching_Walks_Leaders.dtd
592 MLB_Pitching_WHIP_Leaders.dtd
594 MLB_Pitching_Wild_Pitches_Leaders.dtd
596 MLB_Pitching_Win_Percentage_Leaders.dtd
598 MLB_Pitching_WL_Leaders.dtd
600 NBA_Team_Stats_XML.dtd
630 nbateamleadersxml.dtd
632 nbatripledoublexml.dtd
636 NCAA_Conference_Schedule_XML.dtd
640 NFLFumbleLeaderXML.dtd
648 NFLMondayNightXML.dtd
654 NFLSackLeadersXML.dtd
658 NFLTeamRankingsXML.dtd
660 NFLTopPerformanceXML.dtd
662 NFLTotalYardageXML.dtd
664 NFL_KickingLeaders_XML.dtd
666 NFL_NBA_Draft_XML.dtd
670 NFL_Team_Stats_XML.dtd
676 WNBA_Team_Leaders_XML.dtd