3 # Copyright (C) 2007--2014,2016,2017 Kipp Cannon
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 3 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 # =============================================================================
25 # =============================================================================
30 Transfer table data between LIGO Light Weight XML files and SQLite
35 from __future__
import print_function
36 from optparse
import OptionParser
42 from lal.utils.cache
import CacheEntry
43 from ligo.lw
import __date__, __version__
44 from ligo.lw
import ligolw
45 from ligo.lw
import dbtables
46 from ligo.lw.utils
import local_path_from_url
47 from ligo.lw.utils
import ligolw_sqlite
51 # so they can be inserted into a database
52 dbtables.ligolwtypes.ToPyType[
"ilwd:char"] = six.text_type
55 __author__ =
"Kipp Cannon <kipp.cannon@ligo.org>"
59 # =============================================================================
63 # =============================================================================
67 def parse_command_line():
69 Parse the command line, return an options object and a list of file
72 parser = OptionParser(
73 version =
"Name: %%prog\n%s" % __version__,
74 usage =
"%prog -d|--database filename [options] [url ...]",
75 description =
"merge database files applying the sql in --sql-file as you go"
77 parser.add_option(
"-d",
"--database", metavar =
"filename", help =
"Set the name of the SQLite3 database file (required).")
78 parser.add_option(
"--ilwdchar-compat", action =
"store_true", help =
"Use obsolete ilwd:char based table definitions and ID reassignment algorithm (default = use new int_8s based table definitions and ID reassignment algorithm).")
79 parser.add_option(
"-i",
"--input-cache", metavar =
"filename", action =
"append", default = [], help =
"Get the names of XML documents to insert into the database from this LAL cache. This option can be given multiple times, and all files from all caches will be loaded.")
80 parser.add_option(
"-p",
"--preserve-ids", action =
"store_true", help =
"Preserve row IDs from the XML in the database. The default is to assign new IDs to prevent collisisions. Inserts will fail if collisions occur.")
81 parser.add_option(
"-r",
"--replace", action =
"store_true", help =
"If the database file already exists, over-write it instead of inserting into it.")
82 parser.add_option(
"-t",
"--tmp-space", metavar =
"path", help =
"Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
83 parser.add_option(
"-s",
"--sql-file", metavar =
"filename", help =
"Execute this SQL file (required).")
84 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose.")
85 options, urls = parser.parse_args()
87 urls = [CacheEntry(line).url for cache in options.input_cache for line in open(cache)] + urls
89 if not options.database:
90 raise ValueError(
"missing required argument --database")
92 return options, (urls or [None])
96 # =============================================================================
100 # =============================================================================
109 options, urls = parse_command_line()
111 will_replace_file = options.replace
112 will_use_tmp_space = options.tmp_space is not None
114 if options.ilwdchar_compat:
115 from glue.ligolw import ligolw
116 from glue.ligolw import dbtables
117 from glue.ligolw.utils import local_path_from_url
118 from glue.ligolw.utils import ligolw_sqlite
124 # Parse the sql file into something that can be executed in sequence
125 sql = [line.strip() for line in open(options.sql_file)]
126 # Remove comments and pragmas
127 sql = [s for s in sql if not s.startswith(
"--") and not s.startswith(
"PRAGMA")]
129 sql = [statement.strip() for statement in sql.split(
";\n")]
130 sql = [statement for statement in sql if statement]
139 class ContentHandler(ligolw.LIGOLWContentHandler):
143 with dbtables.workingcopy(options.database, tmp_path = options.tmp_space if will_use_tmp_space else None, replace_file = will_replace_file, verbose = options.verbose) as target:
144 ContentHandler.connection = sqlite3.connect(str(target))
145 cursor = ContentHandler.connection.cursor()
153 for n, url in enumerate(urls, 1):
155 print(
"%d/%d:" % (n, len(urls)), end=
' ', file=sys.stderr)
156 if url.endswith(
".sqlite"):
157 with dbtables.workingcopy(local_path_from_url(url), tmp_path = options.tmp_space, discard = True, verbose = options.verbose) as source_filename:
159 print(
"reading '%s' ..." % source_filename, file=sys.stderr)
160 xmldoc = dbtables.get_xml(sqlite3.connect(str(source_filename)))
161 ligolw_sqlite.insert_from_xmldoc(ContentHandler.connection, xmldoc, preserve_ids = options.preserve_ids, verbose = options.verbose)
164 ligolw_sqlite.insert_from_url(url, contenthandler = ContentHandler, preserve_ids = options.preserve_ids, verbose = options.verbose)
167 print(
"Executing SQL ...", file=sys.stderr)
169 for statement in sql:
171 print(statement, file=sys.stderr)
172 cursor.execute(statement)
173 ContentHandler.connection.commit()
176 print(
"... Done.", file=sys.stderr)
179 dbtables.build_indexes(ContentHandler.connection, options.verbose)
183 # Close database, and move to final location
187 ContentHandler.connection.close()
196 print(
"done.", file=sys.stderr)