159 lines
7.2 KiB
Python
159 lines
7.2 KiB
Python
"""Connect and materialize registered snippets before accepting calls."""
|
|
|
|
from contextlib import contextmanager
|
|
from os import PathLike
|
|
|
|
from alembic.autogenerate import compare_metadata
|
|
from alembic.migration import MigrationContext
|
|
from alembic.operations import Operations
|
|
from sqlalchemy import JSON, Column, Integer, MetaData, String, Table, create_engine, event, inspect, select, text
|
|
from sqlalchemy.engine import URL, make_url
|
|
|
|
|
|
def connect(database):
|
|
if isinstance(database, PathLike) or "://" not in database:
|
|
url = URL.create("sqlite+pysqlite", database=str(database))
|
|
else:
|
|
url = make_url(database)
|
|
drivers = {"postgresql": "psycopg", "mysql": "pymysql", "sqlite": "pysqlite"}
|
|
backend = url.get_backend_name()
|
|
if backend not in drivers:
|
|
raise ValueError(f"unsupported database: {backend}")
|
|
engine = create_engine(url.set(drivername=f"{backend}+{drivers[backend]}"), pool_pre_ping=True)
|
|
if backend == "sqlite":
|
|
@event.listens_for(engine, "connect")
|
|
def enable_foreign_keys(dbapi, record):
|
|
dbapi.execute("PRAGMA foreign_keys=ON")
|
|
return engine
|
|
|
|
|
|
@contextmanager
|
|
def startup_transaction(engine):
|
|
# Serialize inspection and DDL across workers. MySQL DDL commits implicitly,
|
|
# so its session lock has to outlive the SQL transaction.
|
|
with engine.connect() as db:
|
|
mysql_locked = False
|
|
try:
|
|
with db.begin():
|
|
if db.dialect.name == "postgresql":
|
|
db.execute(text("SELECT pg_advisory_xact_lock(1296646977)"))
|
|
elif db.dialect.name == "sqlite":
|
|
db.exec_driver_sql("BEGIN IMMEDIATE")
|
|
else:
|
|
mysql_locked = db.scalar(text("SELECT GET_LOCK('mica.core.startup', 30)")) == 1
|
|
if not mysql_locked:
|
|
raise RuntimeError("timed out waiting for the MICA startup lock")
|
|
yield db
|
|
finally:
|
|
if mysql_locked:
|
|
db.execute(text("SELECT RELEASE_LOCK('mica.core.startup')"))
|
|
|
|
|
|
system = MetaData()
|
|
site_binding = Table("mica_site", system, Column("slot", Integer, primary_key=True),
|
|
Column("site", String(63), nullable=False))
|
|
receipts = Table("mica_receipts", system, Column("subject", String(128), primary_key=True),
|
|
Column("key_hash", String(64), primary_key=True),
|
|
Column("digest", String(64), nullable=False), Column("result", JSON))
|
|
revisions = Table("mica_plugin_revisions", system, Column("plugin", String(63), primary_key=True),
|
|
Column("version", Integer, primary_key=True))
|
|
|
|
|
|
def bind_site(db, site):
|
|
if site is None and not inspect(db).has_table(site_binding.name):
|
|
return
|
|
site_binding.create(db, checkfirst=True)
|
|
bound = db.scalar(select(site_binding.c.site))
|
|
if bound is None and site is not None:
|
|
db.execute(site_binding.insert().values(slot=1, site=site))
|
|
elif bound != site:
|
|
raise ValueError("database is bound to another site")
|
|
|
|
|
|
def migrate_plugins(db, catalog, registry):
|
|
catalog.create(db, checkfirst=True)
|
|
revisions.create(db, checkfirst=True)
|
|
known = set(db.scalars(select(catalog.c.name)))
|
|
for plugin in registry.plugins.values():
|
|
applied = db.scalars(select(revisions.c.version).where(revisions.c.plugin == plugin.name)).all()
|
|
# Pre-versioned catalog rows correspond to revision 1. New installs use current models.
|
|
current = max(applied) if applied else (1 if plugin.name in known else plugin.version)
|
|
if current > plugin.version:
|
|
raise ValueError(f"plugin downgrade: {plugin.name} {current} -> {plugin.version}")
|
|
if not applied:
|
|
db.execute(revisions.insert().values(plugin=plugin.name, version=current))
|
|
for revision in range(current + 1, plugin.version + 1):
|
|
migrate = plugin.migrations.get(revision)
|
|
if not callable(migrate):
|
|
raise ValueError(f"{plugin.name} missing migration to {revision}")
|
|
migrate(db)
|
|
db.execute(revisions.insert().values(plugin=plugin.name, version=revision))
|
|
|
|
|
|
def materialize(engine, registry, *, site=None):
|
|
metadata = MetaData()
|
|
for table in registry.metadata.tables.values():
|
|
table.to_metadata(metadata)
|
|
catalog = Table("mica_plugins", metadata, Column("name", String(63), primary_key=True),
|
|
Column("description", JSON, nullable=False))
|
|
|
|
revisions.to_metadata(metadata)
|
|
if site is not None:
|
|
site_binding.to_metadata(metadata)
|
|
receipts.to_metadata(metadata)
|
|
|
|
def include_name(name, kind, parents):
|
|
return kind != "table" or name in metadata.tables
|
|
|
|
with startup_transaction(engine) as db:
|
|
bind_site(db, site)
|
|
migrate_plugins(db, catalog, registry)
|
|
context = MigrationContext.configure(db, opts={"include_name": include_name})
|
|
inspector = inspect(db)
|
|
for table in metadata.tables.values():
|
|
if inspector.has_table(table.name):
|
|
pk = inspector.get_pk_constraint(table.name)["constrained_columns"]
|
|
if pk != list(table.primary_key.columns.keys()):
|
|
raise ValueError(f"explicit schema migration required: {table.name} primary key")
|
|
changes = compare_metadata(context, metadata)
|
|
additions = []
|
|
for change in changes:
|
|
if change[0] in ("add_table", "add_index"):
|
|
continue
|
|
if change[0] == "add_column":
|
|
column = change[3]
|
|
if column.nullable and not column.foreign_keys and not column.unique:
|
|
additions.append(change)
|
|
continue
|
|
# Legacy SQLite TEXT PRIMARY KEY columns can reflect as nullable.
|
|
# Allow only this opted-in difference; keep all other checks active.
|
|
if db.dialect.name == "sqlite" and isinstance(change, list) and len(change) == 1:
|
|
diff = change[0]
|
|
if diff[0] == "modify_nullable" and diff[-2:] == (True, False):
|
|
column = metadata.tables[diff[2]].c[diff[3]]
|
|
if column.primary_key and column.info.get("sqlite_legacy_nullable_pk"):
|
|
continue
|
|
raise ValueError(f"explicit schema migration required: {change}")
|
|
|
|
ops = Operations(context)
|
|
for _, schema, table_name, column in additions:
|
|
ops.add_column(table_name, column, schema=schema)
|
|
metadata.create_all(db)
|
|
for change in changes:
|
|
if change[0] == "add_index":
|
|
change[1].create(db, checkfirst=True)
|
|
|
|
existing = set(db.scalars(select(catalog.c.name)))
|
|
for plugin in registry.plugins.values():
|
|
description = {
|
|
"version": plugin.version,
|
|
"requires": list(plugin.requires),
|
|
"snippets": {s.name: {"operations": sorted(s.operations),
|
|
"tables": [t.name for t in s.tables]} for s in plugin.snippets},
|
|
}
|
|
if plugin.name in existing:
|
|
stmt = catalog.update().where(catalog.c.name == plugin.name)
|
|
else:
|
|
stmt = catalog.insert().values(name=plugin.name)
|
|
db.execute(stmt.values(description=description))
|