Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stupid SQLite3 handler
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