OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
ancDB.py
Go to the documentation of this file.
1 
2 import sqlite3
3 import re
4 
5 class ancDB:
6  def __init__(self, dbfile=None, local=False):
7  """A small set of functions to generate, update, and read from a local SQLite database of ancillary
8  file information"""
9  self.dbfile = dbfile
10  self.local = local
11  self.conn = None
12  self.cursor = None
13 
14  def openDB(self):
15  """
16  Open connection to the ancillary DB and initiate a cursor
17  """
18  conn = sqlite3.connect(self.dbfile, timeout=30)
19  self.conn = conn
20  c = conn.cursor()
21  c.execute('''PRAGMA foreign_keys = ON''')
22  self.cursor = c
23  return
24 
25  def closeDB(self):
26  """
27  Close the DB connection, committing changes.
28  """
29  conn = self.conn
30  cursor = self.cursor
31  conn.commit()
32  cursor.close()
33 
34  def create_db(self):
35  """
36  Create the ancillary DB
37  """
38  if self.conn is None:
39  print("No connection to database!")
40  return 110
41 
42  c = self.cursor
43  # Create satfiles table
44  c.execute('''CREATE TABLE IF NOT EXISTS satfiles
45  (satid INTEGER PRIMARY KEY,
46  filename TEXT ,
47  starttime TEXT,
48  stoptime TEXT,
49  status INTEGER,
50  attephstat INTEGER)''')
51 
52  # Create ancfiles table
53  c.execute('''CREATE TABLE IF NOT EXISTS ancfiles
54  (ancid INTEGER PRIMARY KEY,
55  filename TEXT ,
56  path TEXT ,
57  type TEXT)''')
58 
59  # Create satancinfo table
60  c.execute('''CREATE TABLE IF NOT EXISTS satancinfo
61  (satid INTEGER ,
62  ancid INTEGER ,
63  optimal INTEGER,
64  FOREIGN KEY(satID) REFERENCES satfiles(satid),
65  FOREIGN KEY(ancID) REFERENCES ancfiles(ancid))''')
66 
67  def insert_record(self, satfile=None, starttime=None, stoptime=None, dbstat=0,
68  ancfile=None, ancpath=None, anctype=None, atteph=False):
69  """
70  Insert record into ancillary DB
71  """
72  if self.conn is None:
73  print("No connection to database!")
74  return 110
75 
76  c = self.cursor
77  satid = self.check_file(satfile, starttime=starttime)
78  ancid = self.check_file(ancfile, anctype=anctype)
79 
80  if satid is None:
81  inputdbstat = dbstat
82  attephstat = -1
83  if atteph:
84  attephstat = dbstat
85  inputdbstat = -1
86 
87  c.execute('INSERT INTO satfiles VALUES (NULL,?,?,?,?,?)',
88  [satfile, starttime, stoptime, inputdbstat, attephstat])
89  self.conn.commit()
90  satid = ancDB.check_file(self, satfile, starttime=starttime)
91 
92  else:
93  if atteph:
94  c.execute('''UPDATE satfiles SET attephstat = ?
95  WHERE satid = ?''', [dbstat, satid])
96  else:
97  c.execute('''UPDATE satfiles SET status = ?
98  WHERE satid = ?''', [dbstat, satid])
99 
100  self.conn.commit()
101 
102  if ancid is None:
103  c.execute('INSERT INTO ancfiles VALUES (NULL,?,?,?)', [ancfile, ancpath, anctype])
104  self.conn.commit()
105  ancid = ancDB.check_file(self, ancfile, anctype=anctype)
106 
107  opt = self.check_dbrtn_status(dbstat, anctype)
108 
109  result = c.execute('SELECT * from satancinfo where satid = ? and ancid = ?', [satid, ancid])
110  r = result.fetchone()
111 
112  if r is None:
113  c.execute('INSERT INTO satancinfo VALUES (?,?,?)', [satid, ancid, opt])
114 
115 
116  def delete_record(self, filename, anctype=None, starttime=None):
117  """
118  Deletes records from ancillary DB
119  If given a satellite filename, deletes all records associated with it
120  If given an ancillary filename and keyword anc is set true, deletes only that ancillary record
121  """
122  if self.conn is None:
123  print("No connection to database!")
124  return 110
125 
126  c = self.cursor
127  conn = self.conn
128 
129  if anctype:
130  ancid = self.check_file(filename, anctype=anctype)
131  c.execute('DELETE from satancinfo where ancid = ?', [ancid])
132  c.execute('DELETE from ancfiles where ancid = ?', [ancid])
133 
134  else:
135  satid = self.check_file(filename, starttime=starttime)
136  ancids = conn.execute('select ancid from satancinfo where satid = ?', [satid])
137  for a in ancids:
138  c.execute('DELETE from satancinfo where ancid = ?', [a[0]])
139  c.execute('DELETE from ancfiles where ancid = ?', [a[0]])
140 
141  c.execute('DELETE from satfiles where satid = ?', [satid])
142 
143  conn.commit()
144 
145  def check_dbrtn_status(self, dbstat, anctype):
146  """
147  Check the database return status.
148  DB return status bitwise values:
149  all bits off means all is well in the world
150  value of -1 means have not checked for ancfiles yet
151  Ancillary:
152  bit 0 - missing one or more MET
153  bit 1 - missing one or more OZONE
154  bit 2 - missing SST
155  bit 3 - missing NO2
156  bit 4 - missing ICE
157  Attitude-Ephemeris
158  bit 0 - predicted attitude selected
159  bit 1 - predicted ephemeris selected
160  bit 2 - no attitude found
161  bit 3 - no ephemeris found
162  bit 4 - invalid mission
163  """
164 
165  statchk = {'atm': 1, 'met': 1, # bit 0
166  'ozone': 2,
167  'sstfile': 4,
168  'no2file': 8,
169  'icefile': 16, # bit 4
170  'geo': 32,
171  # atteph
172  'att': 1,
173  'eph': 2,
174  # aquarius
175  'sssfile': 32,
176  'xrayfile': 64,
177  'scat': 128,
178  'tecfile': 256,
179  'swhfile': 512,
180  'frozenfile': 1024,
181  'geosfile': 2048,
182  'argosfile': 4096,
183  'sif': 8192, # sif_file
184  'pert': 16384, # l2_uncertainties_file
185  'sssmatchup': 32768, # sss_matchup_file
186  'rim_file': 65536 }
187 
188  if re.search("\d$", anctype):
189  anctype = anctype[0:len(anctype) - 1]
190  if dbstat & statchk[anctype]:
191  return 0
192  else:
193  return 1
194 
195 
196  def check_file(self, filename, anctype=None, starttime=None):
197  """
198  Check database for existing file, return ID if exists
199  """
200  if self.conn is None:
201  print("No connection to database!")
202  return 110
203 
204  c = self.cursor
205 
206  table = 'satfiles'
207  id = 'satid'
208  if anctype is None:
209  if filename:
210  query = ' '.join(['select', id, 'from', table, 'where filename =', '"' + filename + '"'])
211  else:
212  query = ' '.join(['select', id, 'from', table, 'where starttime =', '"' + starttime + '"'])
213 
214  else:
215  table = 'ancfiles'
216  id = 'ancid'
217  if filename:
218  query = ' '.join(['select', id, 'from', table, 'where filename =', '"' + filename + '"', " and type = ",
219  '"' + anctype + '"'])
220  else:
221  return None
222 
223  result = c.execute(query)
224  r = result.fetchone()
225 
226  if r is None:
227  return None
228  else:
229  if len(r) > 1:
230  print('more than one entry for this starttime - this may be a problem.?')
231  return r[0]
232 
233  def get_status(self, filename, atteph=False, starttime=None):
234  """
235  Check the stored database return status
236  """
237  if self.conn is None:
238  print("No connection to database!")
239  return 110
240 
241  c = self.cursor
242  if atteph:
243  if filename:
244  query = ' '.join(['select attephstat from satfiles where filename =', '"' + filename + '"'])
245  else:
246  query = ' '.join(['select attephstat from satfiles where starttime =', '"' + starttime + '"'])
247  else:
248  if filename:
249  query = ' '.join(['select status from satfiles where filename =', '"' + filename + '"'])
250  else:
251  query = ' '.join(['select status from satfiles where starttime =', '"' + starttime + '"'])
252 
253  result = c.execute(query)
254  r = result.fetchone()
255 
256  if r is None:
257  return None
258  else:
259  return r[0]
260 
261  def get_filetime(self, filename, starttime=None):
262  """
263  return the stored file start and stop times
264  """
265  if self.conn is None:
266  print("No connection to database!")
267  return 110
268 
269  c = self.cursor
270  if filename:
271  query = ' '.join(['select starttime,stoptime from satfiles where filename =', '"' + filename + '"'])
272  else:
273  query = ' '.join(['select starttime,stoptime from satfiles where starttime =', '"' + starttime + '"'])
274 
275  result = c.execute(query)
276  r = result.fetchone()
277  return [r[0],r[1]]
278 
279  def get_ancfiles(self, filename, atteph=False, starttime=None):
280  """
281  Return the ancillary files associated with a given input file
282  """
283  import os
284  if self.conn is None:
285  print("No connection to database!")
286  return None
287 
288  c = self.cursor
289 
290  satID = self.check_file(filename, starttime=starttime)
291  if satID is None:
292  return None
293 
294  filehash = {}
295  result = c.execute(
296  'SELECT a.type, a.path, a.filename from ancfiles a, satancinfo s where a.ancid = s.ancid and s.satid = ?',
297  [satID])
298  for row in result:
299  anctype = row[0]
300  if atteph and not re.search('(att|eph)', anctype, re.IGNORECASE):
301  continue
302  elif not atteph and re.search('(att|eph)', anctype, re.IGNORECASE):
303  continue
304 
305  filehash[row[0]] = os.path.join(row[1], row[2])
306 
307  return filehash
308 
309 if __name__ == "__main__":
310  db = ancDB(dbfile='/tmp/testDB.sqlite.db')
311 
312  db.openDB()
313  db.create_db()
314  db.insert_record(satfile='A2002365234500.L1A_LAC', starttime='2002365234500', stoptime='2002365235000',
315  ancfile='N200236518_MET_NCEPN_6h.hdf', ancpath='/Users/Shared/python/OCSSW_Scripts',
316  anctype='met1')
317  db.insert_record(satfile='A2002365234500.L1A_LAC', starttime='2002365234500', stoptime='2002365235000',
318  ancfile='N200300100_MET_NCEPN_6h.hdf', ancpath='/Users/Shared/python/OCSSW_Scripts',
319  anctype='att1', atteph=True)
320  print(db.check_file('A2002365234500.L1A_LAC'))
321  print(db.check_file('N200236518_MET_NCEPN_6h.hdf', anctype='met1'))
322  files = db.get_ancfiles('A2002365234500.L1A_LAC', atteph=True)
323  print(files)
324  db.delete_record(filename='A2002365234500.L1A_LAC')
325  print(db.check_file('N200236518_MET_NCEPN_6h.hdf', anctype='met1'))
326  db.closeDB()
def closeDB(self)
Definition: ancDB.py:25
def __init__(self, dbfile=None, local=False)
Definition: ancDB.py:6
def check_file(self, filename, anctype=None, starttime=None)
Definition: ancDB.py:196
def check_dbrtn_status(self, dbstat, anctype)
Definition: ancDB.py:145
def get_status(self, filename, atteph=False, starttime=None)
Definition: ancDB.py:233
def get_ancfiles(self, filename, atteph=False, starttime=None)
Definition: ancDB.py:279
def create_db(self)
Definition: ancDB.py:34
def insert_record(self, satfile=None, starttime=None, stoptime=None, dbstat=0, ancfile=None, ancpath=None, anctype=None, atteph=False)
Definition: ancDB.py:67
def delete_record(self, filename, anctype=None, starttime=None)
Definition: ancDB.py:116
def openDB(self)
Definition: ancDB.py:14
def get_filetime(self, filename, starttime=None)
Definition: ancDB.py:261