dbsql.html


001| '''SQLite Database Table classes.
001| 
001| classes:
001|     dbQuery (object)    - query base class
001|     dbTable (dbQuery)   - table base class
001| 
001| Developer@Sonnack.com
001| June 2017
001| '''

002| ####################################################################################################
003| from sys import stdout
004| from os import path
005| import sqlite3
006| from logger import logger
007| from files import tabfile
008| ####################################################################################################
009| 
010| 
011| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
012| class dbQuery (object):
013|     '''SQLite Database Query class.
013| 
013| properties:
013|     dbname      - database name
013|     name        - table name (or query name)
013|     is_open     - database flag
013| 
013| methods:
013|     dbopen      ()
013|     dbclose     ()
013|     db_query    (sql, params)
013| 
013| '''

014| 
015|     Log = logger('dbsql')
016| 
017|     def __init__ (self, db_name, name):
018|         self.dbname = db_name
019|         self.name = name # Just a Query name, but used as TableName in dbTable!
020|         self.is_open = False
021| 
022|     def __str__ (self):
023|         return 'dbQuery[%s] (DB:%s)' % (self.name, self.dbname)
024| 
025|     def db_query (self, query, params=None):
026|         '''Query the Database.'''
027|         self.Log.debug('dbQuery[%s]' % self.name)
028|         self.Log.debug('sql={%s}' % query.replace('\n',' '))
029|         if params: self.Log.trace('ps=%s' % str(params))
030|         self.dbopen()
031|         try:
032|             result = self.crsr.execute(query,params) if params else self.crsr.execute(query)
033|             return list(result)
034|         except Exception as e:
035|             self.Log.error(e)
036|             raise
037|         finally:
038|             self.dbclose()
039| 
040|     def dbopen (self):
041|         '''Open the Database and create a Cursor.'''
042|         self.Log.debug('db[%s] OPEN' % self.name)
043|         if self.is_open:
044|             self.Log.warn('Database was already open! (Closed it!)')
045|             self.dbclose()
046|         self.conn = sqlite3.connect(self.dbname)
047|         self.crsr = self.conn.cursor()
048|         self.is_open = True
049| 
050|     def dbclose (self):
051|         '''Close the Database.'''
052|         self.Log.debug('db[%s] CLOSE' % self.name)
053|         if not self.is_open:
054|             self.Log.warn('Database already closed! (Nothing done.)')
055|             return
056|         self.conn.commit()
057|         self.conn.close()
058|         self.is_open = False
059| 
060| 
061| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
062| class dbTable (dbQuery):
063|     '''SQLite Database Table class.
063| 
063| properties:
063|     cols            - original list of column names
063|     col_names       - list of just the column names
063|     col_types       - list of just the column data types
063| 
063| methods:
063|     create_table                    (notice)
063|     create_and_insert_table         (notice, recd)
063|     create_and_insert_many_table    (notice, recds)
063|     create_and_load_table           (notice, filename)
063| 
063|     destroy_table                   (notice)
063| 
063|     list_to_file    (...)
063|     print_records   (fp)
063| 
063|     find_record     (search_col_ix, search_value)
063|     db_insert       (record)
063|     db_insert_many  (records)
063| 
063|     db_create       ()
063|     db_destroy      ()
063|     db_load         (filename)
063| 
063| '''

064| 
065|     def __init__ (self, db_name, table_name, column_names):
066|         dbQuery.__init__(self, db_name, table_name)
067|         self.cols = column_names
068|         self.col_names = []
069|         self.col_types = []
070|         for c in self.cols:
071|             t = c.split()
072|             self.col_names.append(t[0])
073|             self.col_types.append(t[1] if 1 < len(t) else '')
074| 
075|     def __len__ (self):
076|         return len(self.cols)
077| 
078|     def __str__ (self):
079|         return 'dbTable[%s] (%s)' % (self.name, self.dbname)
080| 
081|     def create_table (self, notice):
082|         '''Create Table. (notice is posted to Log)'''
083|         self.Log.info(notice)
084|         self.db_create()
085| 
086|     def create_and_insert_table (self, notice, recd):
087|         '''Create Table and Insert a Record.'''
088|         self.Log.info(notice)
089|         self.db_create()
090|         self.db_insert(recd)
091| 
092|     def create_and_insert_many_table (self, notice, recds):
093|         '''Create Table and Insert Records.'''
094|         self.Log.info(notice)
095|         self.db_create()
096|         self.db_insert_many(recds)
097| 
098|     def create_and_load_table (self, notice, filename):
099|         '''Create Table and Load From Data. (filename assumed in dataPath)'''
100|         self.Log.info(notice)
101|         self.db_create()
102|         self.db_load(path.join(self.dataPath,filename))
103| 
104|     def destroy_table (self, notice):
105|         '''Destroy Table. (notice is posted to Log)'''
106|         self.Log.info(notice)
107|         self.db_destroy()
108| 
109|     def list_to_file (self, records, fmt, filename, h1=None, h2=None, sql=None, ps=None):
110|         '''Print (formatted) records to a file stream.'''
111|         fp = open(filename, mode='w', encoding='utf-8')
112|         try:
113|             if h1: print(h1, file=fp)
114|             if h2: print(h2, file=fp)
115|             for rcd in records:
116|                 print(fmt % rcd, file=fp)
117|             if h2: print(h2, file=fp)
118|             print(file=fp)
119|             if sql: print('{%s}' % sql, file=fp)
120|             if ps: print('%s' % ps, file=fp)
121|             print(file=fp)
122|             self.Log.info('wrote: %s' % filename)
123|         except:
124|             raise
125|         finally:
126|             fp.close()
127| 
128|     def print_records (self, fp=stdout):
129|         '''Dump the records to a file stream. Order by first column.'''
130|         sql = 'SELECT * FROM "%s" ORDER BY %s' % (self.name, self.col_names[0])
131|         self.Log.trace(sql)
132|         rs = self.db_query(sql)
133|         for r in rs:
134|             print(r, file=fp)
135| 
136|     def find_record (self, srch_col, srch_val):
137|         '''Find a record given a colum index and a search value for that column.'''
138|         sql = 'SELECT * FROM "%s" WHERE (%s = ?)' % (self.name, self.col_names[srch_col])
139|         self.Log.trace(sql)
140|         rs = self.db_query(sql, [srch_val])
141|         self.Log.trace(rs)
142|         return rs
143| 
144|     def db_insert (self, recd):
145|         '''INSERT a single record into the table.'''
146|         self.Log.debug('dbTable[%s] Insert: {%s}' % (self.name,str(recd)))
147|         self.dbopen()
148|         try:
149|             t = ','.join('?'*len(self.cols))
150|             s = 'INSERT INTO "%s" VALUES (%s)' % (self.name,t)
151|             self.Log.trace(s)
152|             self.crsr.execute(s,recd)
153|         except Exception as e:
154|             self.Log.error(e)
155|             raise
156|         finally:
157|             self.dbclose()
158| 
159|     def db_insert_many (self, recds):
160|         '''INSERT multiple records into the table.'''
161|         self.Log.debug('dbTable[%s] Insert: {records: %d}' % (self.name,len(recds)))
162|         self.dbopen()
163|         try:
164|             t = ','.join('?'*len(self.cols))
165|             s = 'INSERT INTO "%s" VALUES (%s)' % (self.name,t)
166|             self.Log.trace(s)
167|             self.crsr.executemany(s,recds)
168|         except Exception as e:
169|             self.Log.error(e)
170|             raise
171|         finally:
172|             self.dbclose()
173| 
174|     def db_create (self):
175|         '''Create the table in the database. (Table must already not exist.)'''
176|         self.Log.debug('dbTable[%s] Create' % self.name)
177|         self.dbopen()
178|         try:
179|             t = ','.join(self.cols)
180|             s = 'CREATE TABLE "%s" (%s)' % (self.name, t)
181|             self.Log.trace(s)
182|             self.crsr.execute(s)
183|         except Exception as e:
184|             self.Log.error(e)
185|             raise
186|         finally:
187|             self.dbclose()
188| 
189|     def db_destroy (self):
190|         '''Remove the table from the database. (Table must exist. (Duh.))'''
191|         self.Log.debug('dbTable[%s] Destroy' % self.name)
192|         self.dbopen()
193|         try:
194|             s = 'DROP TABLE "%s"' % self.name
195|             self.Log.trace(s)
196|             self.crsr.execute(s)
197|         except Exception as e:
198|             self.Log.error(e)
199|             raise
200|         finally:
201|             self.dbclose()
202| 
203|     def db_load (self, filename):
204|         '''Assumes a TAB file with first row of headers (which are ignored).'''
205|         self.Log.debug('dbTable[%s] LoadRecords: %s' % (self.name, filename))
206|         ftab = tabfile(filename)
207|         ftab.load()
208|         self.db_insert_many(ftab.data)
209| 
210| 
211| ####################################################################################################
212| '''eof'''
213|