7 from TrigConfIO.TriggerConfigAccessBase
import ConfigDBLoader
8 from copy
import deepcopy
13 parser = argparse.ArgumentParser(prog =
"AtlTriggerDBCopy.py", description=
"Example: %(prog)s -d TRIGGERDBMC -c triggerDBMC_Run2.db")
14 parser.add_argument(
"-d",
"--dbalias", dest=
"dbalias", help=
"TriggerDB connection alias for the source DB")
15 parser.add_argument(
"-c",
"--create", dest=
"createfile", help=
"create sqlite db file")
16 parser.add_argument(
"-v", help=
"increase output verbosity", action=
"count", default=0)
17 args = parser.parse_args()
19 print(
"No source Trigger DB specified")
22 if not args.createfile:
23 print(
"No sqlite target file specified")
24 parser.print_help(parser)
37 credentials = ConfigDBLoader.getConnectionParameters(self.
dbalias)
39 print(f
"Opening connection to {self.dbalias}")
44 print(f
"Closing connection to {self.dbalias}" )
62 print(
"Not connected to an output file, will print the insert commands instead")
64 if filename
and os.path.exists(filename):
65 print(f
"Target file {filename} exists already, will abort in order to prevent overwriting")
66 raise RuntimeError(
"Target file already exists")
90 self.
cursor.executemany(statement, iter(data))
96 with open(creationFileName)
as fh:
97 print(
"Creating sqlite db %s from %s" % (self.
filename, creationFileName) )
98 self.
cursor.executescript( fh.read() )
110 self.
ignoreTablesCreate = [
'TT_WRITELOCK',
'HLT_SMT_TO_HRE',
'HLT_PARAMETER',
'HLT_RELEASE',
'TRIGGER_LOG',
111 'DBCOPY_SOURCE_DATABASE',
'HLT_RULE_SET',
'TEMP',
'HLT_RULE_PARAMETER',
'HLT_RULE_COMPONENT',
112 'HLT_SETUP',
'TT_USERS',
'HLT_RULE',
"HLT_HRC_TO_HRP",
"HLT_HRE_TO_HRS",
113 "HLT_HRS_TO_HRU",
"HLT_HRU_TO_HRC",
"HLT_PRESCALE_SET_ALIAS",
"HLT_PRESCALE_SET_COLL",
114 "PRESCALE_SET_ALIAS",
"TRIGGER_ALIAS",
"L1_PRESCALE_SET_ALIAS",
"L1_CALO_SIN_COS",
115 "L1_CI_TO_CSC",
"L1_JET_INPUT",
"L1_MUON_THRESHOLD_SET"]
123 query_ListAllTables =
"SELECT table_name FROM all_tables WHERE owner=:SCHEMA"
129 if exceptTables
is not None:
130 for x
in exceptTables:
137 cursor.arraysize = 1000
138 cursor.execute( query, **data )
142 query_TableSize =
"SELECT COUNT(*) FROM {schema}.{tableName}"
143 qdict = {
"schema" : self.
connection.schema,
"tableName" : tableName }
144 result = self.
executeQuery( query_TableSize.format(**qdict) )
145 row = result.fetchone()
149 query_ColumnNames =
"SELECT column_name, data_type FROM sys.all_tab_columns WHERE owner = :SCHEMA AND table_name = :TABLE_NAME ORDER BY column_id"
150 data = {
"SCHEMA" : self.
connection.schema,
"TABLE_NAME" : tableName }
151 result = self.
executeQuery( query = query_ColumnNames, data = data )
152 colNames, colTypes = zip(*result)
153 return colNames, colTypes
159 print(
"retrieving indexes from Oracle")
161 SELECT table_name, index_name, column_name FROM sys.all_ind_columns WHERE table_owner = :SCHEMA
164 result = self.
executeQuery( query = query_Indexes, data = data )
165 for table_name, index_name, column_name
in result:
166 if table_name
not in self.
indexes:
168 self.
indexes[table_name][index_name] = column_name
174 print(
"retrieving primary key constraints from Oracle")
175 query_PrimaryKeys =
"""
176 SELECT table_name, column_name, position FROM sys.all_cons_columns WHERE owner = :SCHEMA AND constraint_name in
177 (SELECT constraint_name FROM sys.all_constraints WHERE owner = :SCHEMA AND constraint_type='P')
178 ORDER BY table_name, position
182 result = self.
executeQuery( query = query_PrimaryKeys, data = data )
183 for table_name, column_name, _
in result:
184 if table_name
not in pk:
186 pk[table_name] += [ column_name ]
193 print(
"retrieving foreign key constraints from Oracle")
194 query_ForeignKeys =
"""
195 SELECT c.table_name, c.constraint_name, a.column_name, c.r_constraint_name, r.table_name, r.column_name
196 FROM sys.all_constraints c
198 sys.all_cons_columns a
199 on (c.constraint_type='R' and c.constraint_name = a.constraint_name and c.owner = :SCHEMA and a.owner = :SCHEMA)
201 sys.all_cons_columns r
202 on (c.r_constraint_name = r.constraint_name and r.owner = :SCHEMA)
206 result = self.
executeQuery( query = query_ForeignKeys, data = data )
207 for table, _, fkcol, _, rtable, rcol
in result:
210 fk[table] += [ {
"col" : fkcol,
"rtab" : rtable,
"rcol" : rcol } ]
215 if oraType.startswith(
"TIMESTAMP"):
217 d = {
"VARCHAR2" :
"TEXT",
219 "NUMBER" :
"INTEGER",
227 for colName, colType
in zip(colNames,colTypes):
228 lines.append(
"%s %s" % (colName, self.
sqliteType(colType)) )
229 lines.append(
"PRIMARY KEY (%s)" %
",".
join(primaryKeys) )
230 for fk
in foreignKeys:
231 lines.append(
"FOREIGN KEY (%s) REFERENCES %s (%s)" % (fk[
"col"], fk[
"rtab"], fk[
"rcol"]) )
232 creationCommand = f
"CREATE TABLE IF NOT EXISTS {tableName} (\n "
233 creationCommand +=
",\n ".
join(lines)
234 creationCommand +=
"\n);\n"
235 for index_name
in indexes:
236 creationCommand +=
"CREATE INDEX %s on %s(%s);\n" % (index_name, tableName, indexes[index_name])
237 return creationCommand
243 with open(creationFileName,
"w")
as fh:
244 print(
"Creating schema file for sqlite: %s" % creationFileName)
252 colNameList =
",".
join(colNames)
253 bindVarList =
",".
join(len(colNames)*[
"?"])
254 insertStatement = f
"INSERT INTO {tableName} ({colNameList}) VALUES ({bindVarList})"
256 selectQuery = f
"SELECT {colNameList} FROM {schema}.{tableName}"
261 sqliteInserter.insertBulk(insertStatement, result)
266 print(
"%i / %i" % (c, size))
268 sqliteInserter.insert(insertStatement, data)
271 sqliteInserter.commit()
287 tempTableCreationFileName =
"tmpCreateTablesSQLite.sql"
288 oraExp.extractSchema(tempTableCreationFileName)
289 sqliteInserter.createSchema(tempTableCreationFileName)
293 tablesToCreate = oraExp.getTables(exceptTables = oraExp.ignoreTablesCreate)
294 tablesToFill = oraExp.getTables(exceptTables = oraExp.ignoreTablesFill)
295 print(
"Tables to create: %i" % len(tablesToCreate))
296 print(
"Tables to fill: %i" % len(tablesToFill))
299 for tableName
in tablesToCreate:
300 entries[tableName] = oraExp.tableSize(tableName)
301 doNotCopy = tableName
not in tablesToFill
302 print(
" table %s has %i entries %s" % (tableName, entries[tableName], (
"(will not copy)" if doNotCopy
else "") ) )
303 totalEntries =
sum(entries.values())
304 print(
"\nTotal number of entries: %i" %totalEntries)
307 print(
"Start copying data")
309 for tableName
in tablesToFill:
310 print(
"Copying table %s" % tableName, end =
'', flush=
True)
311 oraExp.copyTable(tableName, sqliteInserter, entries[tableName])
312 copiedEntries += entries[tableName]
313 print(
" => done %i / %i (%f%%)" % (copiedEntries, totalEntries, 100 * copiedEntries/totalEntries))
315 sqliteInserter.connection.close()
318 if __name__ ==
"__main__":