Files
YMS/yms/database.py
T

205 lines
6.6 KiB
Python

# SPDX-License-Identifier: WTFPL
import MySQLdb
import secrets
from gettext import pgettext
class Database:
def __init__(self, hostname, dbname):
self.hostname = hostname
self.schema = dbname
self.conn = None
self.cur = None
self.dcur = None
self.error = None
self.last_sql = None
def connect(self, dbuser, dbpass):
if self.conn:
return True
MySQLdb.paramstyle = 'pyformat'
try:
self.conn = MySQLdb.connect(host=self.hostname, db=self.schema,
user=dbuser, passwd=dbpass, charset='utf8')
except MySQLdb.Error as e:
self.error = e
return False
self.conn.autocommit(False)
self.cur = self.conn.cursor()
self.dcur = self.conn.cursor(MySQLdb.cursors.DictCursor)
return True
def connect_local(self):
# connection via local unix socket
if self.conn:
return True
MySQLdb.paramstyle = 'pyformat'
try:
self.conn = MySQLdb.connect(host='localhost', db=self.schema,
unix_socket='/run/mysqld/mysqld.sock', charset='utf8')
except MySQLdb.Error as e:
self.error = e
return False
self.cur = self.conn.cursor()
self.dcur = self.conn.cursor(MySQLdb.cursors.DictCursor)
return True
def disconnect(self):
self.cur.close()
self.dcur.close()
self.conn.close()
def is_connected(self):
return self.conn.open
def is_encrypted(self):
self.cur.execute("SHOW SESSION STATUS LIKE 'Ssl_cipher'")
row = self.cur.fetchone()
return (row and row[1])
def get_timestamp(self):
self.cur.execute("SELECT CURRENT_TIMESTAMP")
return self.cur.fetchone()[0]
def last_error(self):
if not self.error:
return('NoError', 0, _('No error information available'))
etype = type(self.error).__name__
ecode = 0
etext = str(self.error)
if len(self.error.args) >= 2 and isinstance(self.error.args[0], int):
ecode = self.error.args[0]
etext = str(self.error.args[1])
self.error = None
return (etype, ecode, etext)
def load_enum(self, table, column):
"""
Load an enum or set directly from a database table and provide it as a
dictionary for use in, for example, selection lists.
"""
sql = (
"SELECT TRIM(TRAILING ')' FROM SUBSTRING(column_type,6)) "
"FROM information_schema.columns "
"WHERE table_schema=DATABASE() AND table_name=%s AND column_name=%s AND data_type IN ('enum','set')"
)
self.cur.execute(sql, (table, column))
row = self.cur.fetchone()
if not row:
return {}
enumvals = row[0].replace("'", "").split(",")
return {
value: pgettext(f"{table}.{column}", value)
for value in enumvals
}
def lock_acquire(self, table, key, userid):
token = secrets.token_hex(8)
# first try new lock
sql = (
"INSERT INTO recordlock (lock_table, lock_key, token, userid)"
"VALUES (%s, %s, %s, %s)"
)
try:
self.cur.execute(sql, (table, key, token, userid))
self.conn.commit()
return token
except self.conn.IntegrityError as e:
self.conn.rollback()
if e.args[0] != 1062:
raise
# lazy locking: lock exists but is old, so we use it
sql = (
"UPDATE recordlock "
"SET token=%s, userid=%s,"
" created_at=CURRENT_TIMESTAMP, last_seen=CURRENT_TIMESTAMP "
"WHERE lock_table=%s AND lock_key=%s AND last_seen<CURRENT_TIMESTAMP-INTERVAL 5 MINUTE"
)
self.cur.execute(sql, (token, userid, table, key))
self.conn.commit()
if self.cur.rowcount == 1:
return token
return None
def lock_refresh(self, token):
sql = (
"UPDATE recordlock "
"SET last_seen=CURRENT_TIMESTAMP "
"WHERE token=%s"
)
self.cur.execute(sql, (token,))
self.conn.commit()
return self.cur.rowcount == 1
def lock_release(self, token):
sql = "DELETE FROM recordlock WHERE token=%s"
self.cur.execute(sql, (token,))
self.conn.commit()
return self.cur.rowcount == 1
def load_setting(self, sno, autocreate=True):
sql = "SELECT valstr, valint FROM settings WHERE userid=0 AND sno=%s"
self.cur.execute(sql, (sno,))
row = self.cur.fetchone()
if not row:
if autocreate:
sql = "INSERT INTO settings (userid, sno) VALUES (0, %s)"
self.cur.execute(sql, (sno,))
self.conn.commit()
return (None, None)
return row
def save_setting(self, sno, valstr, valint):
sql = "UPDATE settings SET valstr=%s, valint=%s WHERE userid=0 AND sno=%s"
values = (valstr, valint, sno)
return self.execute_write(sql, values, 1)
def get_free_number(self, table, column):
"""
Get first free number from column, so gaps are filled
"""
sql = (
"SELECT MIN(n.{col}) AS nextval "
"FROM ("
"SELECT 1 AS {col} "
"UNION ALL "
"SELECT DISTINCT {col} + 1 "
"FROM {tbl} "
"WHERE {col} > 0"
") AS n "
"LEFT JOIN {tbl} AS m ON m.{col}=n.{col} "
"WHERE m.{col} IS NULL"
).format(tbl=table, col=column)
self.cur.execute(sql)
return self.cur.fetchone()[0] or 1
def execute_write(self, sql, values=(), expected_rows=None):
"""
Execute an INSERT, UPDATE, or DELETE statement.
expected_rows:
None = do not check the number of affected rows
1 = expect exactly one affected row
0 = expect no affected rows / no data changed
"""
try:
self.cur.execute(sql, values)
except MySQLdb.Error as e:
self.conn.rollback()
self.error = e
return False
if (expected_rows is not None and self.cur.rowcount != expected_rows):
self.conn.rollback()
self.error = RuntimeError(
"Expected {} affected rows, got {}".format(
expected_rows,
self.cur.rowcount
)
)
return False
self.error = None
return True