Created
July 9, 2015 08:32
-
-
Save yubessy/1d76caf6aa273e2df13c to your computer and use it in GitHub Desktop.
Stupid SQLite3 handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import sqlite3 | |
class SQLite3DB: | |
_IDENTIFIER_RE = re.compile(r'^[a-zA-Z_]\w*$') | |
def __init__(self, filename): | |
self._con = sqlite3.connect(filename, isolation_level=None) | |
self._con.row_factory = sqlite3.Row | |
def _validate_args(self, *indentifiers): | |
for idfr in indentifiers: | |
if not self._IDENTIFIER_RE.match(idfr): | |
raise ValueError('Bad indentifier: ' + idfr) | |
def insert(self, table, **kwargs): | |
keys = kwargs.keys() | |
self._validate_args(table, *keys) | |
column_field = ', '.join(keys) | |
placeholder_field = ', '.join(':' + k for k in keys) | |
sql = ''' | |
INSERT INTO {table} ({column_field}) VALUES ({placeholder_field}) | |
'''.format( | |
table=table, | |
column_field=column_field, | |
placeholder_field=placeholder_field, | |
) | |
self._con.execute(sql, kwargs) | |
def select(self, table, columns, **kwargs): | |
keys = kwargs.keys() | |
args = columns + tuple(keys) | |
self._validate_args(table, *args) | |
column_field = ', '.join(columns) | |
sql = ''' | |
SELECT {column_field} FROM {table} | |
'''.format( | |
table=table, | |
column_field=column_field, | |
) | |
if keys: | |
cond_field = ' AND '.join('{0} == :{0}'.format(k) for k in keys) | |
sql += ''' | |
WHERE {cond_field} | |
'''.format( | |
cond_field=cond_field, | |
) | |
return self._con.execute(sql, kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment