Notes/src/sql.py

94 lines
2.3 KiB
Python
Raw Normal View History

import base64
import sqlite3
import utils
2017-09-09 13:53:58 -04:00
conn = None
2017-10-09 19:48:10 -04:00
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
if isinstance(row[idx], buffer):
d[col[0]] = base64.b64encode(row[idx])
else:
d[col[0]] = row[idx]
return d
2017-10-09 19:48:10 -04:00
def connect(document_path):
global conn
2017-10-09 19:48:10 -04:00
conn = sqlite3.connect(document_path)
conn.row_factory = dict_factory
2017-10-09 19:48:10 -04:00
def insert(table_name, rec):
2017-08-27 14:39:26 -04:00
# FIXME: SQL injection!
keys = ','.join(rec.keys())
2017-10-09 19:48:10 -04:00
question_marks = ','.join(list('?' * len(rec)))
values = tuple(rec.values())
2017-10-09 19:48:10 -04:00
cursor = execute('INSERT INTO ' + table_name + ' (' + keys + ') VALUES (' + question_marks + ')', values)
return cursor.lastrowid
2017-10-09 19:48:10 -04:00
def set_option(name, value):
execute("UPDATE options SET opt_value = ? WHERE opt_name = ?", [value, name])
2017-10-09 19:48:10 -04:00
def get_option(name):
return getSingleResult("SELECT opt_value FROM options WHERE opt_name = ?", [name])['opt_value']
2017-10-09 19:48:10 -04:00
def add_audit(category, request=None, note_id=None, change_from=None, change_to=None, comment=None):
now = utils.now_timestamp()
2017-09-28 23:16:36 -04:00
browser_id = None
if request:
browser_id = request.headers['x-browser-id']
execute("INSERT INTO audit_log (date_modified, category, browser_id, note_id, change_from, change_to, comment)"
" VALUES (?, ?, ?, ?, ?, ?, ?)", [now, category, browser_id, note_id, change_from, change_to, comment])
2017-10-09 19:48:10 -04:00
def deleteRecentAudits(category, request, note_id):
browser_id = request.headers['x-browser-id']
2017-10-09 19:48:10 -04:00
delete_cutoff = utils.now_timestamp() - 10 * 60;
execute("DELETE FROM audit_log WHERE category = ? AND browser_id = ? AND note_id = ? AND date_modified > ?",
[category, browser_id, note_id, delete_cutoff])
2017-10-09 19:48:10 -04:00
def delete(tablename, note_id):
execute("DELETE FROM " + tablename + " WHERE note_id = ?", [note_id])
2017-10-09 19:48:10 -04:00
def execute(sql, params=[]):
cursor = conn.cursor()
cursor.execute(sql, params)
return cursor
2017-10-09 19:48:10 -04:00
2017-10-09 16:50:36 -04:00
def execute_script(sql):
cursor = conn.cursor()
cursor.executescript(sql)
return cursor
2017-10-09 19:48:10 -04:00
def getResults(sql, params=[]):
cursor = conn.cursor()
query = cursor.execute(sql, params)
return query.fetchall()
2017-10-09 19:48:10 -04:00
def getSingleResult(sql, params=()):
cursor = conn.cursor()
query = cursor.execute(sql, params)
return query.fetchone()
2017-10-09 19:48:10 -04:00
def commit():
conn.commit()