# 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 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('UnknownType', 0, '') 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 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