77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
"""The same transactional store contract on PostgreSQL and local SQLite."""
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import zlib
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
|
|
def pack(obj):
|
|
return zlib.compress(
|
|
json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode(), 3
|
|
)
|
|
|
|
|
|
def unpack(blob):
|
|
return json.loads(zlib.decompress(blob))
|
|
|
|
|
|
class Database:
|
|
def __init__(self):
|
|
self.dsn = os.getenv("DATABASE_URL")
|
|
if not self.dsn and os.getenv("DB_PASSWORD_FILE"):
|
|
from urllib.parse import quote
|
|
|
|
password = Path(os.environ["DB_PASSWORD_FILE"]).read_text().strip()
|
|
user = quote(os.environ["POSTGRES_USER"], safe="")
|
|
dbname = quote(os.environ["POSTGRES_DB"], safe="")
|
|
self.dsn = f"postgresql://{user}:{quote(password, safe='')}@db/{dbname}"
|
|
self.path = os.getenv("SQLITE_PATH", "dispatch.sqlite3")
|
|
|
|
@contextmanager
|
|
def transaction(self, write=False):
|
|
if self.dsn:
|
|
import psycopg
|
|
|
|
con = psycopg.connect(self.dsn)
|
|
if not write:
|
|
con.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
|
else:
|
|
con = sqlite3.connect(self.path, timeout=30)
|
|
con.execute("PRAGMA foreign_keys=ON")
|
|
con.execute("BEGIN IMMEDIATE" if write else "BEGIN")
|
|
|
|
def run(sql, args=()):
|
|
return con.execute(sql.replace("?", "%s") if self.dsn else sql, args)
|
|
|
|
try:
|
|
yield run
|
|
con.commit()
|
|
except BaseException:
|
|
con.rollback()
|
|
raise
|
|
finally:
|
|
con.close()
|
|
|
|
def init(self):
|
|
if not self.dsn:
|
|
with sqlite3.connect(self.path) as c:
|
|
c.execute("PRAGMA journal_mode=WAL")
|
|
sql = Path(__file__).with_name("001_initial.sql").read_text()
|
|
with self.transaction(True) as run:
|
|
for stmt in sql.split(";"):
|
|
if stmt.strip():
|
|
run(stmt)
|
|
|
|
def row(self, run, gid, owner=None, lock=False):
|
|
sql = "SELECT owner,version,state,seq FROM games WHERE id=?"
|
|
args = [gid]
|
|
if owner is not None:
|
|
sql += " AND owner=?"
|
|
args.append(owner)
|
|
if lock and self.dsn:
|
|
sql += " FOR UPDATE"
|
|
return run(sql, args).fetchone()
|