All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
channelDBConverter.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 #---------------------------------------------------------------
3 #
4 # Name: siov_extracter.py
5 #
6 # Purpose: Extract data from conditions database into sqlite databases.
7 #
8 # Created: 9-Dec-2019, H. Greenlee
9 #
10 # Usage:
11 #
12 # $ iov_extracter.py [-d|--devel]
13 #
14 # Options:
15 #
16 # -d - Use development database.
17 #
18 # Notes:
19 #
20 # 1. Source ~uboonepro/.sqlaccess/prod_access.sh to define environment variables
21 # for database access.
22 #
23 #---------------------------------------------------------------
24 
25 from __future__ import print_function
26 import sys, os, datetime
27 import psycopg2
28 import sqlite3
29 
30 # Calibration database names.
31 
32 calibs = ['crt_channelstatus_data',
33  'detpedestals_data',
34  'detpmtgains_data',
35  'dqdx_xnorm_data',
36  'dqdx_xshape_plane0_data',
37  'dqdx_xshape_plane0_mc',
38  'dqdx_xshape_plane1_data',
39  'dqdx_xshape_plane1_mc',
40  'dqdx_xshape_plane2_data',
41  'dqdx_xshape_plane2_mc',
42  'dqdx_yz_plane0_data',
43  'dqdx_yz_plane0_mc',
44  'dqdx_yz_plane1_data',
45  'dqdx_yz_plane1_mc',
46  'dqdx_yz_plane2_data',
47  'dqdx_yz_plane2_mc',
48  'electronicscalib_data',
49  'elifetime_data',
50  'lightyieldscale_data']
51 
52 calibs_dev = ['crt_channelstatus_data',
53  'detpedestals_data',
54  'detpmtgains_data',
55  'dqdx_xnorm_data',
56  'dqdx_xshape_plane0_data',
57  'dqdx_xshape_plane1_data',
58  'dqdx_xshape_plane2_data',
59  'dqdx_yz_plane0_data',
60  'dqdx_yz_plane0_mc',
61  'dqdx_yz_plane1_data',
62  'dqdx_yz_plane1_mc',
63  'dqdx_yz_plane2_data',
64  'dqdx_yz_plane2_mc',
65  'electronicscalib_data',
66  'elifetime_data',
67  'lightyieldscale_data']
68 
69 # Table suffixes.
70 
71 suffixes = ['tags', 'iovs', 'tag_iovs', 'data']
72 
73 # Parse command line.
74 
75 devel = 0
76 dev = ''
77 args = sys.argv[1:]
78 while len(args) > 0:
79  if args[0] == '-d' or args[0] == '--devel' :
80  devel = 1
81  dev = '_dev'
82  del args[0]
83  else:
84  print('Unknown option %s' % args[0])
85  del args[0]
86  sys.exit(1)
87 
88 
89 # Open connection to conditions database (postgres).
90 
91 try:
92  host = os.environ['PUB_PSQL_READER_HOST']
93  port = int(os.environ['PUB_PSQL_READER_PORT'])
94  user = os.environ['PUB_PSQL_READER_USER']
95  db = os.environ['PUB_PSQL_READER_DB']
96  pw = os.environ['PUB_PSQL_READER_PASS']
97 except:
98  print("Source ~/.sqlaccess/prod_access.sh first.")
99 
100 
101 if devel:
102  host = 'ifdb04.fnal.gov'
103  db = 'microboone_dev'
104  calibs = calibs_dev
105 
106 conn = psycopg2.connect(host=host, port=port, dbname=db, user=user, password=pw)
107 cur = conn.cursor()
108 
109 # Loop over calibration databases.
110 
111 for calib in calibs:
112 
113  print('Calibration database %s.' % calib)
114 
115  # Create sqlite3 database for thie calibration.
116 
117  sqlite_database = '%s.db' % calib
118  if os.path.exists(sqlite_database):
119  os.remove(sqlite_database)
120  sqlite_conn = sqlite3.connect(sqlite_database)
121  sqlite_cur = sqlite_conn.cursor()
122 
123  # Dictionary of columns.
124 
125  schema = {} # schema[table] = list of columns.
126 
127  # Loop over tables.
128 
129  for suffix in suffixes:
130 
131  # Handle data table separately.
132 
133  table_name = '%s_%s' % (calib, suffix)
134  schema[table_name] = []
135  print('Processing table %s.' % table_name)
136 
137  # Construct sqlite query to create corresponding table.
138 
139  qtbl = 'CREATE TABLE IF NOT EXISTS %s (' % table_name
140 
141  # Get schema of this table.
142 
143  q = 'select column_name, data_type, is_nullable from information_schema.columns where table_name=%s'
144  cur.execute(q, (table_name,))
145  rows = cur.fetchall()
146  first = True
147  for row in rows:
148  column_name = row[0]
149  data_type = row[1]
150  null = row[2]
151 
152  schema[table_name].append(column_name)
153 
154  if not first:
155  qtbl += ', '
156 
157  # Convert postgres data type to sqlite data type.
158 
159  sqlite_type = ''
160  if data_type == 'integer':
161  sqlite_type = 'integer'
162  elif data_type == 'bigint':
163  sqlite_type = 'integer'
164  elif data_type == 'text':
165  sqlite_type = 'text'
166  elif data_type == 'timestamp without time zone':
167  sqlite_type = 'integer'
168  elif data_type == 'boolean':
169  sqlite_type = 'integer'
170  elif data_type == 'real':
171  sqlite_type = 'real'
172  if sqlite_type == '':
173  print('Unknown type %s' % data_type)
174  sys.exit(1)
175 
176  #print column_name, data_type, sqlite_type
177 
178  qtbl += '%s %s' % (column_name, sqlite_type)
179 
180  # Add primary keys and constraints.
181 
182  if first and (suffix == 'tags' or suffix == 'iovs'):
183  qtbl += ' PRIMARY KEY'
184  elif null == 'NO':
185  qtbl += ' NOT NULL'
186  first = False
187 
188  # Add foreign keys.
189 
190  if suffix == 'tag_iovs':
191  qtbl += ', FOREIGN KEY (iov_id) REFERENCES %s_iovs(iov_id)' % calib
192  qtbl += ', FOREIGN KEY (tag) REFERENCES %s_tags(tag)' % calib
193  elif suffix == 'data':
194  qtbl += ', FOREIGN KEY (__iov_id) REFERENCES %s_iovs(iov_id)' % calib
195 
196  # Complete query.
197 
198  qtbl += ');'
199  #print qtbl
200  sqlite_cur.execute(qtbl)
201 
202  # Done creating table.
203 
204  # For data table, query max __iov_id.
205 
206  max_iov_id = 0
207  if suffix == 'data':
208  q = 'SELECT MAX(__iov_id) FROM %s' % table_name
209  cur.execute(q)
210  row = cur.fetchone()
211  max_iov_id = row[0]
212  print('Maximum iov_id = %d' % max_iov_id)
213 
214  # Loop over iov ids.
215 
216  for iov_id in range(max_iov_id + 1):
217 
218  # Query contents of table from postgres database.
219 
220  first = True
221  q = 'SELECT '
222  for column in schema[table_name]:
223  if not first:
224  q += ','
225  q += column
226  first = False
227 
228  q += ' FROM %s' % table_name
229 
230  # For data table, append iov_id constraint.
231 
232  if suffix == 'data':
233  print('iov id = %d' % iov_id)
234  q += ' WHERE __iov_id = %d' % iov_id
235  q += ';'
236 
237  #print q
238  cur.execute(q)
239  rows = cur.fetchall()
240  print('%d rows fetched.' % len(rows))
241  now = datetime.datetime.now()
242  for row in rows:
243 
244  # Insert row into sqlite database.
245 
246  q = 'INSERT INTO %s (' % table_name
247  qval = 'VALUES('
248  values = []
249  n = 0
250  for column in schema[table_name]:
251  element = row[n]
252  if n > 0:
253  q += ','
254  qval += ','
255  q += column
256  qval += '?'
257  if type(element) == type(now):
258  values.append(int(element.strftime('%s')))
259  else:
260  values.append(element)
261  n += 1
262  qval += ')'
263  q += ') %s;' % qval
264  #print q
265  #print values
266  sqlite_cur.execute(q, tuple(values))
267 
268 
269  # Done looping over tables for thie calibration database.
270 
271  # Close sqlite database.
272 
273  sqlite_conn.commit()
274  sqlite_conn.close()
275 
276 # Done looping over calibration databases.
277 
278 sys.exit(0)
279 
do one_file $F done echo for F in find $TOP name CMakeLists txt print