All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
convertcalibPostGresToSQLite.py
Go to the documentation of this file.
1 from __future__ import print_function
2 import sys, os, datetime
3 import psycopg2
4 import sqlite3
5 
6 # Calibration database names.
7 
8 calibs = [
9 'crt_gain_reco_data',
10 ]
11 
12 # Table suffixes.
13 
14 suffixes = ['tags', 'iovs', 'tag_iovs', 'data']
15 
16 # Open connection to conditions database (postgres).
17 
18 host='Icarus-db'
19 db='icarus_online_prd'
20 user='calib_admin'
21 port='5434'
22 pw='calib4adm'
23 
24 conn = psycopg2.connect(host=host, port=port, dbname=db, user=user, password=pw)
25 cur = conn.cursor()
26 
27 # Loop over calibration databases.
28 
29 for calib in calibs:
30 
31  print('Calibration database %s.' % calib)
32 
33  # Create sqlite3 database for thie calibration.
34 
35  sqlite_database = '%s.db' % calib
36  if os.path.exists(sqlite_database):
37  os.remove(sqlite_database)
38  sqlite_conn = sqlite3.connect(sqlite_database)
39  sqlite_cur = sqlite_conn.cursor()
40 
41  # Dictionary of columns.
42 
43  schema = {} # schema[table] = list of columns.
44 
45  # Loop over tables.
46 
47  for suffix in suffixes:
48 
49  # Handle data table separately.
50 
51  table_name = '%s_%s' % (calib, suffix)
52  schema[table_name] = []
53  print('Processing table %s.' % table_name)
54 
55  # Construct sqlite query to create corresponding table.
56 
57  qtbl = 'CREATE TABLE IF NOT EXISTS %s (' % table_name
58 
59  # Get schema of this table.
60 
61  q = 'select column_name, data_type, is_nullable from information_schema.columns where table_name=%s'
62  cur.execute(q, (table_name,))
63  rows = cur.fetchall()
64  first = True
65  for row in rows:
66  column_name = row[0]
67  data_type = row[1]
68  null = row[2]
69 
70  schema[table_name].append(column_name)
71 
72  if not first:
73  qtbl += ', '
74 
75  # Convert postgres data type to sqlite data type.
76 
77  sqlite_type = ''
78  if data_type == 'integer':
79  sqlite_type = 'integer'
80  elif data_type == 'bigint':
81  sqlite_type = 'integer'
82  elif data_type == 'text':
83  sqlite_type = 'text'
84  elif data_type == 'timestamp without time zone':
85  sqlite_type = 'integer'
86  elif data_type == 'boolean':
87  sqlite_type = 'integer'
88  elif data_type == 'real':
89  sqlite_type = 'real'
90  if sqlite_type == '':
91  print('Unknown type %s' % data_type)
92  sys.exit(1)
93 
94  #print column_name, data_type, sqlite_type
95 
96  qtbl += '%s %s' % (column_name, sqlite_type)
97 
98  # Add primary keys and constraints.
99 
100  if first and (suffix == 'tags' or suffix == 'iovs'):
101  qtbl += ' PRIMARY KEY'
102  elif null == 'NO':
103  qtbl += ' NOT NULL'
104  first = False
105 
106  # Add foreign keys.
107 
108  if suffix == 'tag_iovs':
109  qtbl += ', FOREIGN KEY (iov_id) REFERENCES %s_iovs(iov_id)' % calib
110  qtbl += ', FOREIGN KEY (tag) REFERENCES %s_tags(tag)' % calib
111  elif suffix == 'data':
112  qtbl += ', FOREIGN KEY (__iov_id) REFERENCES %s_iovs(iov_id)' % calib
113 
114  # Complete query.
115 
116  qtbl += ');'
117  #print qtbl
118  sqlite_cur.execute(qtbl)
119 
120  # Done creating table.
121 
122  # For data table, query max __iov_id.
123 
124  max_iov_id = 0
125  if suffix == 'data':
126  q = 'SELECT MAX(__iov_id) FROM calib_prd.%s' % table_name
127  cur.execute(q)
128  row = cur.fetchone()
129  max_iov_id = row[0]
130  print('Maximum iov_id = %d' % max_iov_id)
131 
132  # Loop over iov ids.
133 
134  for iov_id in range(max_iov_id + 1):
135 
136  # Query contents of table from postgres database.
137 
138  first = True
139  q = 'SELECT '
140  for column in schema[table_name]:
141  if not first:
142  q += ','
143  q += column
144  first = False
145 
146  q += ' FROM calib_prd.%s' % table_name
147 
148  # For data table, append iov_id constraint.
149 
150  if suffix == 'data':
151  print('iov id = %d' % iov_id)
152  q += ' WHERE __iov_id = %d' % iov_id
153  q += ';'
154 
155  #print q
156  cur.execute(q)
157  rows = cur.fetchall()
158  print('%d rows fetched.' % len(rows))
159  now = datetime.datetime.now()
160  for row in rows:
161 
162  # Insert row into sqlite database.
163 
164  q = 'INSERT INTO %s (' % table_name
165  qval = 'VALUES('
166  values = []
167  n = 0
168  for column in schema[table_name]:
169  element = row[n]
170  if n > 0:
171  q += ','
172  qval += ','
173  q += column
174  qval += '?'
175  if type(element) == type(now):
176  values.append(int(element.strftime('%s')))
177  else:
178  values.append(element)
179  n += 1
180  qval += ')'
181  q += ') %s;' % qval
182  #print q
183  #print values
184  sqlite_cur.execute(q, tuple(values))
185 
186 
187  # Done looping over tables for thie calibration database.
188 
189  # Close sqlite database.
190 
191  sqlite_conn.commit()
192  sqlite_conn.close()
193 
194 # Done looping over calibration databases.
195 
196 sys.exit(0)
do one_file $F done echo for F in find $TOP name CMakeLists txt print