database.py 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. import asyncio
  2. import logging
  3. from sqlalchemy import event
  4. from sqlalchemy.exc import IntegrityError, OperationalError, ProgrammingError
  5. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  6. from sqlalchemy.orm import DeclarativeBase
  7. from backend.app.core.config import settings
  8. from backend.app.core.db_dialect import is_sqlite
  9. logger = logging.getLogger(__name__)
  10. def _set_sqlite_pragmas(dbapi_conn, connection_record):
  11. """Set SQLite pragmas on each new connection for concurrency and performance."""
  12. cursor = dbapi_conn.cursor()
  13. # WAL mode allows concurrent readers + one writer (vs default DELETE mode which locks entirely)
  14. cursor.execute("PRAGMA journal_mode = WAL")
  15. # Wait up to 15 seconds when the database is locked instead of failing immediately
  16. cursor.execute("PRAGMA busy_timeout = 15000")
  17. cursor.execute("PRAGMA synchronous = NORMAL")
  18. cursor.close()
  19. def _create_engine():
  20. """Create the async engine with dialect-appropriate settings."""
  21. if is_sqlite():
  22. kwargs = {"pool_size": 20, "max_overflow": 200}
  23. else:
  24. kwargs = {"pool_size": 10, "max_overflow": 20}
  25. eng = create_async_engine(
  26. settings.database_url,
  27. echo=settings.debug,
  28. **kwargs,
  29. )
  30. if is_sqlite():
  31. event.listen(eng.sync_engine, "connect", _set_sqlite_pragmas)
  32. else:
  33. # Strip timezone info from aware datetimes before they reach asyncpg.
  34. # asyncpg rejects timezone-aware values for TIMESTAMP WITHOUT TIME ZONE columns.
  35. # The codebase uses datetime.now(timezone.utc) in many places — this makes
  36. # Postgres behave like SQLite which ignores timezone info entirely.
  37. @event.listens_for(eng.sync_engine, "before_cursor_execute", retval=True)
  38. def _strip_tz_from_params(conn, cursor, statement, parameters, context, executemany):
  39. import datetime
  40. if parameters is None:
  41. return statement, parameters
  42. # Recursive strip that walks any nesting of dict/list/tuple. Needed
  43. # because SQLAlchemy passes parameters in several shapes depending
  44. # on the path: a dict for named binds, a tuple for positional, a
  45. # list of dicts/tuples for executemany, and for insertmanyvalues
  46. # sometimes a list of tuples inside an outer list. The simplest
  47. # correct answer is "strip datetimes at any depth".
  48. def _strip(val):
  49. if isinstance(val, datetime.datetime) and val.tzinfo is not None:
  50. return val.replace(tzinfo=None)
  51. if isinstance(val, dict):
  52. return {k: _strip(v) for k, v in val.items()}
  53. if isinstance(val, list):
  54. return [_strip(v) for v in val]
  55. if isinstance(val, tuple):
  56. return tuple(_strip(v) for v in val)
  57. return val
  58. return statement, _strip(parameters)
  59. return eng
  60. engine = _create_engine()
  61. async_session = async_sessionmaker(
  62. engine,
  63. class_=AsyncSession,
  64. expire_on_commit=False,
  65. )
  66. async def run_with_retry(fn, *, max_attempts: int = 3, label: str = ""):
  67. """Run an async DB operation with retry for SQLite 'database is locked' errors.
  68. ``fn`` is an async callable that receives an ``AsyncSession`` and performs
  69. the full query-mutate-commit cycle. On each retry a fresh session is used
  70. so there are no stale-object / expired-attribute issues after rollback.
  71. On PostgreSQL this calls ``fn`` once with no retry (Postgres uses row-level
  72. locking and doesn't suffer from single-writer contention).
  73. """
  74. if not is_sqlite():
  75. async with async_session() as db:
  76. return await fn(db)
  77. last_exc: OperationalError | None = None
  78. for attempt in range(1, max_attempts + 1):
  79. try:
  80. async with async_session() as db:
  81. return await fn(db)
  82. except OperationalError as exc:
  83. last_exc = exc
  84. if "database is locked" not in str(exc) or attempt == max_attempts:
  85. raise
  86. delay = 0.5 * attempt # 0.5s, 1.0s
  87. logger.warning(
  88. "SQLite locked%s (attempt %d/%d), retrying in %.1fs: %s",
  89. f" ({label})" if label else "",
  90. attempt,
  91. max_attempts,
  92. delay,
  93. exc,
  94. )
  95. await asyncio.sleep(delay)
  96. raise last_exc # unreachable, but keeps type checkers happy
  97. async def close_all_connections():
  98. """Close all database connections for backup/restore operations."""
  99. global engine
  100. await engine.dispose()
  101. async def reinitialize_database():
  102. """Reinitialize database connection after restore."""
  103. global engine, async_session
  104. engine = _create_engine()
  105. async_session = async_sessionmaker(
  106. engine,
  107. class_=AsyncSession,
  108. expire_on_commit=False,
  109. )
  110. class Base(DeclarativeBase):
  111. pass
  112. async def get_db() -> AsyncSession:
  113. async with async_session() as session:
  114. try:
  115. yield session
  116. await session.commit()
  117. except BaseException:
  118. # Catch BaseException (not just Exception) so CancelledError —
  119. # raised when Starlette's BaseHTTPMiddleware cancels the inner
  120. # task scope on client disconnect — also triggers rollback.
  121. # `asyncio.shield` keeps the rollback running to completion
  122. # even when the await itself gets cancelled, so the SQLite
  123. # write lock is released promptly instead of being held until
  124. # the connection is GC'd ages later (which was producing the
  125. # "database is locked" cascade in #1112's support package).
  126. try:
  127. await asyncio.shield(session.rollback())
  128. except BaseException: # noqa: BLE001 — rollback failure must not mask the original
  129. pass
  130. raise
  131. finally:
  132. try:
  133. await asyncio.shield(session.close())
  134. except BaseException: # noqa: BLE001 — close failure must not mask the original
  135. pass
  136. async def init_db():
  137. # Import models to register them with SQLAlchemy
  138. from backend.app.models import ( # noqa: F401
  139. active_print_spoolman,
  140. ams_history,
  141. ams_label,
  142. api_key,
  143. archive,
  144. auth_ephemeral,
  145. bug_report,
  146. color_catalog,
  147. external_link,
  148. filament,
  149. filament_sku_settings,
  150. github_backup,
  151. group,
  152. kprofile_note,
  153. library,
  154. local_preset,
  155. long_lived_token,
  156. maintenance,
  157. notification,
  158. notification_template,
  159. oidc_provider,
  160. orca_base_cache,
  161. pending_upload,
  162. print_batch,
  163. print_log,
  164. print_queue,
  165. printer,
  166. project,
  167. project_bom,
  168. settings,
  169. shopping_list,
  170. slot_preset,
  171. smart_plug,
  172. smart_plug_energy_snapshot,
  173. spool,
  174. spool_assignment,
  175. spool_catalog,
  176. spool_k_profile,
  177. spool_usage_history,
  178. spoolbuddy_device,
  179. user,
  180. user_email_pref,
  181. user_otp_code,
  182. user_totp,
  183. virtual_printer,
  184. )
  185. async with engine.begin() as conn:
  186. await conn.run_sync(Base.metadata.create_all)
  187. # Run migrations for new columns (SQLite doesn't auto-add columns)
  188. await run_migrations(conn)
  189. # Seed default notification templates
  190. await seed_notification_templates()
  191. # Seed default groups and migrate existing users
  192. await seed_default_groups()
  193. # Seed default catalog entries
  194. await seed_spool_catalog()
  195. await seed_color_catalog()
  196. async def _safe_execute(conn, sql):
  197. """Execute a DDL migration statement, silently ignoring idempotency errors.
  198. 'already exists', 'duplicate column name' (SQLite ADD COLUMN), 'no such column'
  199. (SQLite RENAME COLUMN), 'duplicate key', and the compound
  200. 'column … does not exist' (PostgreSQL RENAME COLUMN idempotency) are swallowed
  201. so that re-running DDL migrations is safe. The compound check additionally
  202. requires the SQL to be a RENAME COLUMN statement so that "does not exist" errors
  203. from ADD COLUMN or CREATE INDEX (which would indicate schema corruption, not
  204. idempotency) are never silently swallowed.
  205. Any other error is logged and re-raised — callers must not assume silent
  206. recovery, as a failure will abort the migration sequence and prevent
  207. application startup.
  208. Only use for DDL statements (ALTER TABLE, CREATE INDEX, etc.).
  209. For DML backfills (UPDATE, DELETE) use conn.execute() directly inside
  210. async with conn.begin_nested() so failures are never silently swallowed.
  211. Uses a savepoint so that a failed statement doesn't poison the surrounding
  212. transaction (required for PostgreSQL).
  213. """
  214. from sqlalchemy import text
  215. try:
  216. async with conn.begin_nested():
  217. await conn.execute(text(sql))
  218. except (OperationalError, ProgrammingError) as exc:
  219. msg = str(exc).lower()
  220. # Only swallow "column … does not exist" for RENAME COLUMN — not for ADD COLUMN
  221. # or CREATE INDEX where it would indicate schema corruption, not idempotency.
  222. column_not_exists = "rename column" in sql.lower() and "column" in msg and "does not exist" in msg
  223. if (
  224. not any(k in msg for k in ("already exists", "duplicate key", "duplicate column name", "no such column"))
  225. and not column_not_exists
  226. ):
  227. logger.error("Migration statement failed: %s | SQL: %.200s", exc, sql)
  228. raise
  229. async def _migrate_normalize_printer_ids(conn) -> None:
  230. from sqlalchemy import text
  231. async with conn.begin_nested():
  232. if is_sqlite():
  233. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids = '[]'"))
  234. else:
  235. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids::text = '[]'"))
  236. async def _migrate_update_auto_link_constraint(conn) -> None:
  237. """Update the auto_link CHECK constraint to allow Fall C (custom email claim).
  238. Old formula: auto_link = FALSE OR (require_ev = TRUE AND email_claim = 'email')
  239. New formula: auto_link = FALSE OR email_claim != 'email' OR require_ev = TRUE
  240. Only Fall B (email_claim='email' + require_ev=False) remains blocked.
  241. Fall C (custom claim, e.g. Azure preferred_username/upn) is now allowed.
  242. PostgreSQL: DROP CONSTRAINT IF EXISTS + ADD new formula via _safe_execute (idempotent).
  243. SQLite: table recreation when old formula is detected in sqlite_master (idempotent).
  244. """
  245. from sqlalchemy import text
  246. _NEW_FORMULA = "auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE"
  247. _CONSTRAINT_NAME = "ck_auto_link_requires_verified_email_claim"
  248. if not is_sqlite():
  249. await _safe_execute(conn, f"ALTER TABLE oidc_providers DROP CONSTRAINT IF EXISTS {_CONSTRAINT_NAME}")
  250. await _safe_execute(
  251. conn,
  252. f"ALTER TABLE oidc_providers ADD CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})",
  253. )
  254. else:
  255. row = (
  256. await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='oidc_providers'"))
  257. ).fetchone()
  258. # Only recreate if the old (more restrictive) formula is still present.
  259. # Fresh installs created with the new __table_args__ already have the correct formula.
  260. # Installs without any constraint (pre-SEC-1 upgrades) are skipped — app-level guards suffice.
  261. if row and "require_email_verified = TRUE AND email_claim = 'email'" in row[0]:
  262. try:
  263. async with conn.begin_nested():
  264. await conn.execute(text("DROP TABLE IF EXISTS oidc_providers_v2"))
  265. await conn.execute(
  266. text(
  267. "CREATE TABLE oidc_providers_v2 ("
  268. "id INTEGER NOT NULL, "
  269. "name VARCHAR(100) NOT NULL, "
  270. "issuer_url VARCHAR(500) NOT NULL, "
  271. "client_id VARCHAR(255) NOT NULL, "
  272. "client_secret VARCHAR(512) NOT NULL, "
  273. "scopes VARCHAR(500), "
  274. "is_enabled BOOLEAN, "
  275. "auto_create_users BOOLEAN, "
  276. "auto_link_existing_accounts BOOLEAN DEFAULT 0, "
  277. "email_claim VARCHAR(64) DEFAULT 'email', "
  278. "require_email_verified BOOLEAN DEFAULT 1, "
  279. "icon_url TEXT, "
  280. "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  281. "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  282. "PRIMARY KEY (id), "
  283. f"UNIQUE (name), "
  284. f"CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})"
  285. ")"
  286. )
  287. )
  288. await conn.execute(
  289. text(
  290. "INSERT INTO oidc_providers_v2 "
  291. "(id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  292. "auto_create_users, auto_link_existing_accounts, email_claim, "
  293. "require_email_verified, icon_url, created_at, updated_at) "
  294. "SELECT id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  295. "auto_create_users, auto_link_existing_accounts, email_claim, "
  296. "require_email_verified, icon_url, created_at, updated_at "
  297. "FROM oidc_providers"
  298. )
  299. )
  300. original = (await conn.execute(text("SELECT count(*) FROM oidc_providers"))).scalar_one()
  301. copied = (await conn.execute(text("SELECT count(*) FROM oidc_providers_v2"))).scalar_one()
  302. if copied != original:
  303. raise RuntimeError(
  304. f"auto_link constraint migration: row count mismatch after copy "
  305. f"({original} in source, {copied} in copy)"
  306. )
  307. await conn.execute(text("DROP TABLE oidc_providers"))
  308. await conn.execute(text("ALTER TABLE oidc_providers_v2 RENAME TO oidc_providers"))
  309. except Exception as exc:
  310. logger.error(
  311. "auto_link constraint update (SQLite table recreation) FAILED: %s",
  312. exc,
  313. exc_info=True,
  314. )
  315. raise
  316. async def run_migrations(conn):
  317. """Run all schema migrations and data backfills on startup.
  318. Includes ALTER TABLE (add columns, rename columns, add constraints),
  319. CREATE INDEX, CREATE TRIGGER, data UPDATE backfills, and table recreations
  320. for complex SQLite schema changes that ALTER TABLE cannot handle.
  321. DDL statements are wrapped in _safe_execute for idempotency.
  322. DML backfills (UPDATE/DELETE) are executed directly via conn.execute()
  323. inside begin_nested() so any failure is always fatal and never silently
  324. swallowed.
  325. """
  326. from sqlalchemy import text
  327. # Migration: Add is_favorite column to print_archives
  328. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0")
  329. # Migration: Add content_hash column to print_archives for duplicate detection
  330. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)")
  331. # Migration: Add auto_off_executed column to smart_plugs
  332. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0")
  333. # Migration: Add on_print_stopped column to notification_providers
  334. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1")
  335. # Migration: Add source_3mf_path column to print_archives
  336. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)")
  337. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  338. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)")
  339. # Migration: Add on_maintenance_due column to notification_providers
  340. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0")
  341. # Migration: Add location column to printers for grouping
  342. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN location VARCHAR(100)")
  343. # Migration: Add interval_type column to maintenance_types
  344. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'")
  345. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  346. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0")
  347. # Migration: Add custom_interval_type column to printer_maintenance
  348. await _safe_execute(conn, "ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)")
  349. # Migration: Add power alert columns to smart_plugs
  350. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0")
  351. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL")
  352. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL")
  353. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME")
  354. # Migration: Add schedule columns to smart_plugs
  355. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0")
  356. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)")
  357. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)")
  358. # Migration: Add daily digest columns to notification_providers
  359. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0")
  360. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)")
  361. # Migration: Add missing-spool-assignment print-start notification toggle
  362. try:
  363. async with conn.begin_nested():
  364. await conn.execute(
  365. text(
  366. "ALTER TABLE notification_providers ADD COLUMN on_print_missing_spool_assignment BOOLEAN DEFAULT 0"
  367. )
  368. )
  369. except (OperationalError, ProgrammingError):
  370. pass # Already applied
  371. # Migration: Add project_id column to print_archives
  372. try:
  373. async with conn.begin_nested():
  374. await conn.execute(
  375. text(
  376. "ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  377. )
  378. )
  379. except (OperationalError, ProgrammingError):
  380. pass # Already applied
  381. # Migration: Add project_id column to print_queue
  382. try:
  383. async with conn.begin_nested():
  384. await conn.execute(
  385. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  386. )
  387. except (OperationalError, ProgrammingError):
  388. pass # Already applied
  389. # Migration: Enforce uniqueness on user_oidc_links for existing rows.
  390. # create_all() is idempotent and does not add constraints to existing tables,
  391. # so we create covering unique indexes explicitly here.
  392. await _safe_execute(
  393. conn,
  394. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_provider_sub"
  395. " ON user_oidc_links (provider_id, provider_user_id)",
  396. )
  397. await _safe_execute(
  398. conn,
  399. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_user_provider ON user_oidc_links (user_id, provider_id)",
  400. )
  401. # Migration: Create FTS5 virtual table for archive full-text search (SQLite only)
  402. # PostgreSQL uses tsvector + GIN index instead (set up in archives.py search route)
  403. if is_sqlite():
  404. try:
  405. await conn.execute(
  406. text("""
  407. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  408. print_name,
  409. filename,
  410. tags,
  411. notes,
  412. designer,
  413. filament_type,
  414. content='print_archives',
  415. content_rowid='id'
  416. )
  417. """)
  418. )
  419. except (OperationalError, ProgrammingError):
  420. pass # Already applied
  421. # Migration: Create triggers to keep FTS index in sync
  422. try:
  423. await conn.execute(
  424. text("""
  425. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  426. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  427. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  428. END
  429. """)
  430. )
  431. except (OperationalError, ProgrammingError):
  432. pass # Already applied
  433. try:
  434. await conn.execute(
  435. text("""
  436. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  437. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  438. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  439. END
  440. """)
  441. )
  442. except (OperationalError, ProgrammingError):
  443. pass # Already applied
  444. try:
  445. await conn.execute(
  446. text("""
  447. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  448. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  449. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  450. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  451. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  452. END
  453. """)
  454. )
  455. except (OperationalError, ProgrammingError):
  456. pass # Already applied
  457. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  458. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0")
  459. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME")
  460. # Migration: Add auto_off_persistent column to smart_plugs (keep auto-off enabled between prints)
  461. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_persistent BOOLEAN DEFAULT 0")
  462. # Migration: Add AMS alarm notification columns to notification_providers
  463. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0")
  464. try:
  465. async with conn.begin_nested():
  466. await conn.execute(
  467. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  468. )
  469. except (OperationalError, ProgrammingError):
  470. pass # Already applied
  471. # Migration: Add AMS-HT alarm notification columns to notification_providers
  472. try:
  473. async with conn.begin_nested():
  474. await conn.execute(
  475. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  476. )
  477. except (OperationalError, ProgrammingError):
  478. pass # Already applied
  479. try:
  480. async with conn.begin_nested():
  481. await conn.execute(
  482. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  483. )
  484. except (OperationalError, ProgrammingError):
  485. pass # Already applied
  486. # Migration: Add plate not empty notification column to notification_providers
  487. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1")
  488. # Migration: Add notes column to projects (Phase 2)
  489. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN notes TEXT")
  490. # Migration: Add attachments column to projects (Phase 3)
  491. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN attachments JSON")
  492. # Migration: Add tags column to projects (Phase 4)
  493. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN tags TEXT")
  494. # Migration: Add due_date column to projects (Phase 5)
  495. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN due_date DATETIME")
  496. # Migration: Add priority column to projects (Phase 5)
  497. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'")
  498. # Migration: Add budget column to projects (Phase 6)
  499. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN budget REAL")
  500. # Migration: Add is_template column to projects (Phase 8)
  501. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0")
  502. # Migration: Add template_source_id column to projects (Phase 8)
  503. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN template_source_id INTEGER")
  504. # Migration: Add parent_id column to projects (Phase 10)
  505. try:
  506. async with conn.begin_nested():
  507. await conn.execute(
  508. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  509. )
  510. except (OperationalError, ProgrammingError):
  511. pass # Already applied
  512. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  513. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired")
  514. # Migration: Add unit_price column to project_bom_items
  515. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN unit_price REAL")
  516. # Migration: Add sourcing_url column to project_bom_items
  517. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)")
  518. # Migration: Rename notes to remarks in project_bom_items
  519. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks")
  520. # Migration: Add show_in_switchbar column to smart_plugs
  521. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0")
  522. # Migration: Add runtime tracking columns to printers
  523. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0")
  524. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME")
  525. # Migration: Add quantity column to print_archives for tracking item count
  526. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1")
  527. # Migration: Add manual_start column to print_queue for staged prints
  528. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0")
  529. # Migration: Add wiki_url column to maintenance_types for documentation links
  530. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)")
  531. # Migration: Add tailscale_disabled column to virtual_printers. Opt-in: default TRUE so
  532. # the auto-detect + fallback noise only runs for users who explicitly enable it.
  533. # Postgres rejects `DEFAULT 1` for BOOLEAN (#1070 round-2 review).
  534. if is_sqlite():
  535. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT 1")
  536. else:
  537. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT true")
  538. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  539. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT")
  540. # Migration: Add queue_force_color_match column to virtual_printers (#1188).
  541. # Opt-in flag: when true, VP queue-mode uploads pin the per-slot type+color
  542. # from the 3MF onto the queue item's filament_overrides so the scheduler
  543. # refuses to dispatch onto a printer with the wrong filament loaded.
  544. # Default false to preserve current behaviour for upgraders.
  545. if is_sqlite():
  546. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT 0")
  547. else:
  548. await _safe_execute(
  549. conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT FALSE"
  550. )
  551. # Migration: Add target_parts_count column to projects for tracking total parts needed
  552. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_parts_count INTEGER")
  553. # Migration: Add url + cover_image_filename columns to projects (#1155).
  554. # url: external link rendered next to the project name on the card.
  555. # cover_image_filename: filename of the project's hero image inside the
  556. # existing attachments dir; rendered as a thumbnail on the card.
  557. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN url VARCHAR(2048)")
  558. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN cover_image_filename VARCHAR(255)")
  559. # Migration: enhanced filament colour handling on color_catalog (#1154).
  560. # Mirrors the Spool columns added below; widens hex_color to VARCHAR(9)
  561. # so catalog entries can store an alpha component (#RRGGBBAA). SQLite
  562. # ignores VARCHAR length, so the widen only matters on PostgreSQL.
  563. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN extra_colors VARCHAR(255)")
  564. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN effect_type VARCHAR(20)")
  565. if not is_sqlite():
  566. await _safe_execute(conn, "ALTER TABLE color_catalog ALTER COLUMN hex_color TYPE VARCHAR(9)")
  567. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  568. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  569. # PostgreSQL gets the correct schema from create_all(), so skip this
  570. if is_sqlite():
  571. try:
  572. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  573. row = result.fetchone()
  574. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  575. await conn.execute(
  576. text("""
  577. CREATE TABLE print_queue_new (
  578. id INTEGER PRIMARY KEY,
  579. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  580. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  581. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  582. position INTEGER DEFAULT 0,
  583. scheduled_time DATETIME,
  584. manual_start BOOLEAN DEFAULT 0,
  585. require_previous_success BOOLEAN DEFAULT 0,
  586. auto_off_after BOOLEAN DEFAULT 0,
  587. ams_mapping TEXT,
  588. status VARCHAR(20) DEFAULT 'pending',
  589. started_at DATETIME,
  590. completed_at DATETIME,
  591. error_message TEXT,
  592. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  593. )
  594. """)
  595. )
  596. await conn.execute(
  597. text("""
  598. INSERT INTO print_queue_new
  599. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  600. manual_start, require_previous_success, auto_off_after, ams_mapping,
  601. status, started_at, completed_at, error_message, created_at
  602. FROM print_queue
  603. """)
  604. )
  605. await conn.execute(text("DROP TABLE print_queue"))
  606. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  607. except (OperationalError, ProgrammingError):
  608. pass # Already applied
  609. # Migration: Add plug_type column to smart_plugs for HA integration
  610. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'")
  611. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  612. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)")
  613. # Migration: Add project_id column to library_folders for linking folders to projects
  614. try:
  615. async with conn.begin_nested():
  616. await conn.execute(
  617. text(
  618. "ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  619. )
  620. )
  621. except (OperationalError, ProgrammingError):
  622. pass # Already applied
  623. # Migration: Add archive_id column to library_folders for linking folders to archives
  624. try:
  625. async with conn.begin_nested():
  626. await conn.execute(
  627. text(
  628. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  629. )
  630. )
  631. except (OperationalError, ProgrammingError):
  632. pass # Already applied
  633. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  634. # PostgreSQL gets the correct schema from create_all(), so skip this
  635. if is_sqlite():
  636. try:
  637. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  638. row = result.fetchone()
  639. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  640. await conn.execute(
  641. text("""
  642. CREATE TABLE smart_plugs_new (
  643. id INTEGER PRIMARY KEY,
  644. name VARCHAR(100) NOT NULL,
  645. ip_address VARCHAR(45),
  646. plug_type VARCHAR(20) DEFAULT 'tasmota',
  647. ha_entity_id VARCHAR(100),
  648. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  649. enabled BOOLEAN NOT NULL DEFAULT 1,
  650. auto_on BOOLEAN NOT NULL DEFAULT 1,
  651. auto_off BOOLEAN NOT NULL DEFAULT 1,
  652. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  653. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  654. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  655. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  656. username VARCHAR(50),
  657. password VARCHAR(100),
  658. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  659. power_alert_high FLOAT,
  660. power_alert_low FLOAT,
  661. power_alert_last_triggered DATETIME,
  662. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  663. schedule_on_time VARCHAR(5),
  664. schedule_off_time VARCHAR(5),
  665. show_in_switchbar BOOLEAN DEFAULT 0,
  666. last_state VARCHAR(10),
  667. last_checked DATETIME,
  668. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  669. auto_off_pending BOOLEAN DEFAULT 0,
  670. auto_off_pending_since DATETIME,
  671. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  672. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  673. )
  674. """)
  675. )
  676. await conn.execute(
  677. text("""
  678. INSERT INTO smart_plugs_new
  679. SELECT id, name, ip_address,
  680. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  681. enabled, auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  682. off_delay_mode, off_delay_minutes, off_temp_threshold,
  683. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  684. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  685. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  686. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  687. FROM smart_plugs
  688. """)
  689. )
  690. await conn.execute(text("DROP TABLE smart_plugs"))
  691. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  692. except (OperationalError, ProgrammingError):
  693. pass # Already applied
  694. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  695. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN plate_id INTEGER")
  696. # Migration: Add print options columns to print_queue
  697. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1")
  698. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0")
  699. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1")
  700. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0")
  701. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0")
  702. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1")
  703. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  704. # This allows queue items to reference library files directly (archive created at print start)
  705. try:
  706. async with conn.begin_nested():
  707. await conn.execute(
  708. text(
  709. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  710. )
  711. )
  712. except (OperationalError, ProgrammingError):
  713. pass # Already applied
  714. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  715. # PostgreSQL gets the correct schema from create_all(), so skip this
  716. if is_sqlite():
  717. try:
  718. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  719. row = result.fetchone()
  720. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  721. await conn.execute(
  722. text("""
  723. CREATE TABLE print_queue_new2 (
  724. id INTEGER PRIMARY KEY,
  725. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  726. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  727. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  728. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  729. position INTEGER DEFAULT 0,
  730. scheduled_time DATETIME,
  731. manual_start BOOLEAN DEFAULT 0,
  732. require_previous_success BOOLEAN DEFAULT 0,
  733. auto_off_after BOOLEAN DEFAULT 0,
  734. ams_mapping TEXT,
  735. plate_id INTEGER,
  736. bed_levelling BOOLEAN DEFAULT 1,
  737. flow_cali BOOLEAN DEFAULT 0,
  738. vibration_cali BOOLEAN DEFAULT 1,
  739. layer_inspect BOOLEAN DEFAULT 0,
  740. timelapse BOOLEAN DEFAULT 0,
  741. use_ams BOOLEAN DEFAULT 1,
  742. status VARCHAR(20) DEFAULT 'pending',
  743. started_at DATETIME,
  744. completed_at DATETIME,
  745. error_message TEXT,
  746. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  747. )
  748. """)
  749. )
  750. await conn.execute(
  751. text("""
  752. INSERT INTO print_queue_new2
  753. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  754. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  755. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  756. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  757. status, started_at, completed_at, error_message, created_at
  758. FROM print_queue
  759. """)
  760. )
  761. await conn.execute(text("DROP TABLE print_queue"))
  762. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  763. except (OperationalError, ProgrammingError):
  764. pass # Already applied
  765. # Migration: Add HA energy sensor entity columns to smart_plugs
  766. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)")
  767. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)")
  768. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)")
  769. # Migration: Create users table for authentication
  770. try:
  771. async with conn.begin_nested():
  772. await conn.execute(
  773. text("""
  774. CREATE TABLE IF NOT EXISTS users (
  775. id INTEGER PRIMARY KEY,
  776. username VARCHAR(100) NOT NULL UNIQUE,
  777. password_hash VARCHAR(255) NOT NULL,
  778. role VARCHAR(20) NOT NULL DEFAULT 'user',
  779. is_active BOOLEAN NOT NULL DEFAULT 1,
  780. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  781. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  782. )
  783. """)
  784. )
  785. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  786. except (OperationalError, ProgrammingError):
  787. pass # Already applied
  788. # Migration: Add external camera columns to printers
  789. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)")
  790. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)")
  791. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0")
  792. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_snapshot_url VARCHAR(500)")
  793. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  794. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)")
  795. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  796. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)")
  797. # Migration: Add is_external column to library_files for external cloud files
  798. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0")
  799. # Migration: Add project_id column to library_files
  800. try:
  801. async with conn.begin_nested():
  802. await conn.execute(
  803. text(
  804. "ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  805. )
  806. )
  807. except (OperationalError, ProgrammingError):
  808. pass # Already applied
  809. # Migration: Add is_external column to library_folders for external cloud folders
  810. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0")
  811. # Migration: Add external folder settings columns to library_folders
  812. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0")
  813. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0")
  814. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)")
  815. # Migration: Add plate_detection_enabled column to printers
  816. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0")
  817. # Migration: Add plate detection ROI columns to printers
  818. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL")
  819. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL")
  820. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL")
  821. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL")
  822. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  823. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  824. # SQLite requires table recreation to drop constraints
  825. # PostgreSQL gets the correct schema from create_all(), so skip this
  826. if is_sqlite():
  827. try:
  828. needs_migration = False
  829. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  830. row = result.fetchone()
  831. table_sql = (row[0] or "").upper() if row else ""
  832. if "PRINTER_ID" in table_sql and "UNIQUE" in table_sql:
  833. import re
  834. if re.search(r'"?PRINTER_ID"?\s+\w+\s+UNIQUE', table_sql) or re.search(
  835. r'UNIQUE\s*\([^)]*"?PRINTER_ID"?', table_sql
  836. ):
  837. needs_migration = True
  838. idx_result = await conn.execute(
  839. text("SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='smart_plugs' AND sql IS NOT NULL")
  840. )
  841. for idx_row in idx_result.fetchall():
  842. idx_sql = (idx_row[0] or "").upper()
  843. if "UNIQUE" in idx_sql and "PRINTER_ID" in idx_sql:
  844. needs_migration = True
  845. break
  846. if needs_migration:
  847. # Create new table without UNIQUE constraint on printer_id
  848. await conn.execute(
  849. text("""
  850. CREATE TABLE smart_plugs_temp (
  851. id INTEGER PRIMARY KEY,
  852. name VARCHAR(100) NOT NULL,
  853. ip_address VARCHAR(45),
  854. plug_type VARCHAR(20) DEFAULT 'tasmota',
  855. ha_entity_id VARCHAR(100),
  856. ha_power_entity VARCHAR(100),
  857. ha_energy_today_entity VARCHAR(100),
  858. ha_energy_total_entity VARCHAR(100),
  859. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  860. enabled BOOLEAN NOT NULL DEFAULT 1,
  861. auto_on BOOLEAN NOT NULL DEFAULT 1,
  862. auto_off BOOLEAN NOT NULL DEFAULT 1,
  863. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  864. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  865. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  866. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  867. username VARCHAR(50),
  868. password VARCHAR(100),
  869. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  870. power_alert_high FLOAT,
  871. power_alert_low FLOAT,
  872. power_alert_last_triggered DATETIME,
  873. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  874. schedule_on_time VARCHAR(5),
  875. schedule_off_time VARCHAR(5),
  876. show_in_switchbar BOOLEAN DEFAULT 0,
  877. last_state VARCHAR(10),
  878. last_checked DATETIME,
  879. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  880. auto_off_pending BOOLEAN DEFAULT 0,
  881. auto_off_pending_since DATETIME,
  882. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  883. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  884. )
  885. """)
  886. )
  887. # Copy data
  888. await conn.execute(
  889. text("""
  890. INSERT INTO smart_plugs_temp
  891. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  892. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  893. auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  894. off_delay_mode, off_delay_minutes, off_temp_threshold,
  895. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  896. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  897. show_in_switchbar, last_state, last_checked, auto_off_executed,
  898. auto_off_pending, auto_off_pending_since, created_at, updated_at
  899. FROM smart_plugs
  900. """)
  901. )
  902. # Drop old table and rename new one
  903. await conn.execute(text("DROP TABLE smart_plugs"))
  904. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  905. except (OperationalError, ProgrammingError):
  906. pass # Already applied
  907. # Migration: Add show_on_printer_card column to smart_plugs
  908. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1")
  909. # Migration: Add MQTT smart plug fields (legacy)
  910. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)")
  911. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)")
  912. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)")
  913. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)")
  914. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0")
  915. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  916. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)")
  917. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0")
  918. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)")
  919. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0")
  920. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)")
  921. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)")
  922. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  923. try:
  924. async with conn.begin_nested():
  925. await conn.execute(
  926. text("""
  927. UPDATE smart_plugs
  928. SET mqtt_power_topic = mqtt_topic,
  929. mqtt_power_multiplier = mqtt_multiplier
  930. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  931. """)
  932. )
  933. except (OperationalError, ProgrammingError):
  934. pass # Already applied
  935. # Migration: Create groups table for permission-based access control
  936. try:
  937. async with conn.begin_nested():
  938. await conn.execute(
  939. text("""
  940. CREATE TABLE IF NOT EXISTS groups (
  941. id INTEGER PRIMARY KEY,
  942. name VARCHAR(100) NOT NULL UNIQUE,
  943. description VARCHAR(500),
  944. permissions JSON,
  945. is_system BOOLEAN NOT NULL DEFAULT 0,
  946. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  947. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  948. )
  949. """)
  950. )
  951. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  952. except (OperationalError, ProgrammingError):
  953. pass # Already applied
  954. # Migration: Create user_groups association table
  955. try:
  956. async with conn.begin_nested():
  957. await conn.execute(
  958. text("""
  959. CREATE TABLE IF NOT EXISTS user_groups (
  960. user_id INTEGER NOT NULL,
  961. group_id INTEGER NOT NULL,
  962. PRIMARY KEY (user_id, group_id),
  963. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  964. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  965. )
  966. """)
  967. )
  968. except (OperationalError, ProgrammingError):
  969. pass # Already applied
  970. # Migration: Add model-based queue assignment columns to print_queue
  971. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)")
  972. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT")
  973. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT")
  974. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  975. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1")
  976. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  977. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0")
  978. # Migration: Add queue notification event columns to notification_providers
  979. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0")
  980. try:
  981. async with conn.begin_nested():
  982. await conn.execute(
  983. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  984. )
  985. except (OperationalError, ProgrammingError):
  986. pass # Already applied
  987. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0")
  988. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1")
  989. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1")
  990. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1")
  991. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0")
  992. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  993. try:
  994. async with conn.begin_nested():
  995. await conn.execute(
  996. text(
  997. "ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  998. )
  999. )
  1000. except (OperationalError, ProgrammingError):
  1001. pass # Already applied
  1002. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  1003. try:
  1004. async with conn.begin_nested():
  1005. await conn.execute(
  1006. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1007. )
  1008. except (OperationalError, ProgrammingError):
  1009. pass # Already applied
  1010. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  1011. try:
  1012. async with conn.begin_nested():
  1013. await conn.execute(
  1014. text(
  1015. "ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  1016. )
  1017. )
  1018. except (OperationalError, ProgrammingError):
  1019. pass # Already applied
  1020. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  1021. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)")
  1022. # Migration: Convert absolute paths to relative paths in library_files table
  1023. # This ensures backup/restore portability across different installations
  1024. try:
  1025. async with conn.begin_nested():
  1026. base_dir_str = str(settings.base_dir)
  1027. # Ensure we have a trailing slash for clean replacement
  1028. if not base_dir_str.endswith("/"):
  1029. base_dir_str += "/"
  1030. # Update file_path - remove base_dir prefix from absolute paths
  1031. await conn.execute(
  1032. text("""
  1033. UPDATE library_files
  1034. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  1035. WHERE file_path LIKE :pattern
  1036. """),
  1037. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1038. )
  1039. # Update thumbnail_path - remove base_dir prefix from absolute paths
  1040. await conn.execute(
  1041. text("""
  1042. UPDATE library_files
  1043. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  1044. WHERE thumbnail_path LIKE :pattern
  1045. """),
  1046. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1047. )
  1048. except (OperationalError, ProgrammingError):
  1049. pass # Already applied
  1050. # Create active_print_spoolman table for Spoolman per-filament tracking
  1051. try:
  1052. async with conn.begin_nested():
  1053. await conn.execute(
  1054. text("""
  1055. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1056. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1057. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1058. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1059. filament_usage TEXT NOT NULL,
  1060. ams_trays TEXT NOT NULL,
  1061. slot_to_tray TEXT,
  1062. layer_usage TEXT,
  1063. filament_properties TEXT,
  1064. UNIQUE(printer_id, archive_id)
  1065. )
  1066. """)
  1067. )
  1068. except (OperationalError, ProgrammingError):
  1069. pass # Already applied
  1070. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1071. try:
  1072. async with conn.begin_nested():
  1073. await conn.execute(
  1074. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1075. )
  1076. except (OperationalError, ProgrammingError):
  1077. pass # Already applied
  1078. # Migration: Add email column to users for Advanced Auth (PR #322)
  1079. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN email VARCHAR(255)")
  1080. # Migration: Add inventory spool tracking columns
  1081. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN added_full BOOLEAN")
  1082. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_used DATETIME")
  1083. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN encode_time DATETIME")
  1084. # Migration: Add RFID tag matching columns to spool
  1085. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)")
  1086. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)")
  1087. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)")
  1088. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)")
  1089. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  1090. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER")
  1091. # Migration: Create spool_usage_history table for filament consumption tracking
  1092. try:
  1093. async with conn.begin_nested():
  1094. await conn.execute(
  1095. text("""
  1096. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1097. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1098. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1099. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1100. print_name VARCHAR(500),
  1101. weight_used REAL NOT NULL DEFAULT 0,
  1102. percent_used INTEGER NOT NULL DEFAULT 0,
  1103. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1104. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1105. )
  1106. """)
  1107. )
  1108. except (OperationalError, ProgrammingError):
  1109. pass # Already applied
  1110. # Migration: Add open_in_new_tab column to external_links
  1111. await _safe_execute(conn, "ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0")
  1112. # Migration: Add bed cooled notification column to notification_providers
  1113. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0")
  1114. # Migration: Add first layer complete notification column to notification_providers
  1115. try:
  1116. async with conn.begin_nested():
  1117. await conn.execute(
  1118. text("ALTER TABLE notification_providers ADD COLUMN on_first_layer_complete BOOLEAN DEFAULT 0")
  1119. )
  1120. except (OperationalError, ProgrammingError):
  1121. pass # Already applied
  1122. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  1123. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0")
  1124. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  1125. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER")
  1126. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME")
  1127. # Migration: Add cost tracking fields to spool table
  1128. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN cost_per_kg REAL")
  1129. # Migration: Per-spool category + low-stock threshold override (#729). Both
  1130. # nullable — NULL category leaves the spool uncategorised, NULL threshold
  1131. # falls back to the global low_stock_threshold setting.
  1132. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN category VARCHAR(50)")
  1133. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN low_stock_threshold_pct INTEGER")
  1134. # Migration: enhanced filament colour handling (#1154). `extra_colors` is
  1135. # a comma-separated list of 6- or 8-char hex tokens (no `#`) for multi-
  1136. # colour gradients; `effect_type` is one of {sparkle, wood, marble, glow,
  1137. # matte} as a visual rendering hint. Both nullable — NULL keeps the
  1138. # current single-rgba/no-effect behaviour.
  1139. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN extra_colors VARCHAR(255)")
  1140. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN effect_type VARCHAR(20)")
  1141. # Migration: Add cost field to spool_usage_history table
  1142. await _safe_execute(conn, "ALTER TABLE spool_usage_history ADD COLUMN cost REAL")
  1143. # Migration: Add archive_id field to spool_usage_history table
  1144. try:
  1145. async with conn.begin_nested():
  1146. await conn.execute(
  1147. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  1148. )
  1149. except (OperationalError, ProgrammingError):
  1150. pass # Already applied
  1151. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  1152. try:
  1153. async with conn.begin_nested():
  1154. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  1155. count = result.scalar() or 0
  1156. if count == 0:
  1157. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  1158. row = result.fetchone()
  1159. if row:
  1160. # Old settings exist — migrate to first virtual printer row
  1161. old_enabled = row[0] == "true" if row[0] else False
  1162. result = await conn.execute(
  1163. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  1164. )
  1165. row = result.fetchone()
  1166. old_access_code = row[0] if row else None
  1167. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  1168. row = result.fetchone()
  1169. old_mode = row[0] if row else "immediate"
  1170. if old_mode == "queue":
  1171. old_mode = "review"
  1172. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  1173. row = result.fetchone()
  1174. old_model = row[0] if row else "BL-P001"
  1175. result = await conn.execute(
  1176. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1177. )
  1178. row = result.fetchone()
  1179. old_target_id = int(row[0]) if row and row[0] else None
  1180. result = await conn.execute(
  1181. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  1182. )
  1183. row = result.fetchone()
  1184. old_remote_iface = row[0] if row else None
  1185. await conn.execute(
  1186. text("""
  1187. INSERT INTO virtual_printers
  1188. (name, enabled, mode, model, access_code, target_printer_id,
  1189. bind_ip, remote_interface_ip, serial_suffix, position)
  1190. VALUES
  1191. (:name, :enabled, :mode, :model, :access_code, :target_id,
  1192. NULL, :remote_iface, '391800001', 0)
  1193. """),
  1194. {
  1195. "name": "Bambuddy",
  1196. "enabled": old_enabled,
  1197. "mode": old_mode or "immediate",
  1198. "model": old_model,
  1199. "access_code": old_access_code,
  1200. "target_id": old_target_id,
  1201. "remote_iface": old_remote_iface,
  1202. },
  1203. )
  1204. except (OperationalError, ProgrammingError, IntegrityError):
  1205. pass # Table may not exist yet on first run, or columns have different constraints
  1206. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  1207. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT")
  1208. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  1209. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)")
  1210. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)")
  1211. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100")
  1212. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0")
  1213. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0")
  1214. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME")
  1215. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  1216. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT")
  1217. # Migration: Add OTA update tracking columns to spoolbuddy_devices
  1218. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_status VARCHAR(20)")
  1219. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_message VARCHAR(255)")
  1220. # Migration: Persist SpoolBuddy backend URL and queued system payload
  1221. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN backend_url VARCHAR(255)")
  1222. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_system_payload TEXT")
  1223. # Migration: Add system_stats JSON blob column to spoolbuddy_devices
  1224. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN system_stats TEXT")
  1225. # Migration: Convert ams_labels table from (printer_id, ams_id) key to ams_serial_number key
  1226. # Labels are now keyed by AMS serial number so they persist when the AMS is moved to another printer.
  1227. # PostgreSQL gets the correct schema from create_all(), so skip this
  1228. if is_sqlite():
  1229. try:
  1230. await conn.execute(text("DROP TABLE IF EXISTS ams_labels_new"))
  1231. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='ams_labels'"))
  1232. row = result.fetchone()
  1233. if row and "printer_id" in (row[0] or ""):
  1234. # Old schema: rebuild the table with ams_serial_number as the unique key.
  1235. # Existing rows get a synthetic serial "p{printer_id}a{ams_id}" so data is preserved.
  1236. await conn.execute(
  1237. text("""
  1238. CREATE TABLE ams_labels_new (
  1239. id INTEGER PRIMARY KEY,
  1240. ams_serial_number VARCHAR(50) NOT NULL,
  1241. ams_id INTEGER,
  1242. label VARCHAR(100) NOT NULL,
  1243. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1244. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1245. CONSTRAINT uq_ams_label_serial UNIQUE (ams_serial_number)
  1246. )
  1247. """)
  1248. )
  1249. await conn.execute(
  1250. text("""
  1251. INSERT INTO ams_labels_new (id, ams_serial_number, ams_id, label, created_at, updated_at)
  1252. SELECT id,
  1253. 'p' || CAST(printer_id AS TEXT) || 'a' || CAST(ams_id AS TEXT),
  1254. ams_id,
  1255. label,
  1256. created_at,
  1257. updated_at
  1258. FROM ams_labels
  1259. """)
  1260. )
  1261. await conn.execute(text("DROP TABLE ams_labels"))
  1262. await conn.execute(text("ALTER TABLE ams_labels_new RENAME TO ams_labels"))
  1263. except (OperationalError, ProgrammingError):
  1264. pass # Already migrated or table does not exist yet
  1265. # Migration: Add auto_dispatch column to virtual_printers
  1266. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN auto_dispatch BOOLEAN DEFAULT 1")
  1267. # Migration: Fix VP model codes — convert legacy SSDP codes and display names to correct SSDP codes
  1268. # Legacy codes (from multi-VP refactor) and display names (from proxy auto-inherit)
  1269. vp_model_fixes = {
  1270. "3DPrinter-X1-Carbon": "BL-P001",
  1271. "3DPrinter-X1": "BL-P002",
  1272. "X1C": "BL-P001",
  1273. "X1": "BL-P002",
  1274. "X1E": "C13",
  1275. "X2D": "N6",
  1276. "P1P": "C11",
  1277. "P1S": "C12",
  1278. "P2S": "N7",
  1279. "A1": "N2S",
  1280. "A1 Mini": "N1",
  1281. "H2D": "O1D",
  1282. "H2C": "O1C",
  1283. "H2S": "O1S",
  1284. }
  1285. for old_val, new_val in vp_model_fixes.items():
  1286. await conn.execute(
  1287. text("UPDATE virtual_printers SET model = :new WHERE model = :old"),
  1288. {"old": old_val, "new": new_val},
  1289. )
  1290. await conn.execute(
  1291. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_model' AND value = :old"),
  1292. {"old": old_val, "new": new_val},
  1293. )
  1294. # Migration: Add per-user Bambu Cloud credential columns
  1295. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_token VARCHAR(500)")
  1296. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_email VARCHAR(255)")
  1297. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_region VARCHAR(10)")
  1298. # Cleanup: Remove obsolete settings keys that are no longer used
  1299. obsolete_keys = ["slicer_binary_path"]
  1300. for key in obsolete_keys:
  1301. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  1302. # Migration: Create user_email_preferences table for user-specific email notification settings
  1303. try:
  1304. async with conn.begin_nested():
  1305. await conn.execute(
  1306. text("""
  1307. CREATE TABLE IF NOT EXISTS user_email_preferences (
  1308. id INTEGER PRIMARY KEY,
  1309. user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  1310. notify_print_start BOOLEAN NOT NULL DEFAULT 1,
  1311. notify_print_complete BOOLEAN NOT NULL DEFAULT 1,
  1312. notify_print_failed BOOLEAN NOT NULL DEFAULT 1,
  1313. notify_print_stopped BOOLEAN NOT NULL DEFAULT 1,
  1314. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1315. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1316. )
  1317. """)
  1318. )
  1319. await conn.execute(
  1320. text("CREATE INDEX IF NOT EXISTS ix_user_email_preferences_user_id ON user_email_preferences(user_id)")
  1321. )
  1322. except (OperationalError, ProgrammingError):
  1323. pass # Already applied
  1324. # Legacy migration: Add notify_print_stopped column (for any existing partial tables)
  1325. try:
  1326. async with conn.begin_nested():
  1327. await conn.execute(
  1328. text("ALTER TABLE user_email_preferences ADD COLUMN notify_print_stopped BOOLEAN NOT NULL DEFAULT 1")
  1329. )
  1330. except (OperationalError, ProgrammingError):
  1331. pass # Column already exists or table created with full schema
  1332. # Migration: Add camera_rotation column to printers
  1333. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN camera_rotation INTEGER DEFAULT 0")
  1334. # Migration: Add awaiting_plate_clear column to printers (#961)
  1335. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN awaiting_plate_clear BOOLEAN DEFAULT FALSE NOT NULL")
  1336. # Migration: Add REST/Webhook smart plug fields
  1337. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_url VARCHAR(500)")
  1338. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_body TEXT")
  1339. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_url VARCHAR(500)")
  1340. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_body TEXT")
  1341. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_method VARCHAR(10)")
  1342. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_headers TEXT")
  1343. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_url VARCHAR(500)")
  1344. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_path VARCHAR(200)")
  1345. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_on_value VARCHAR(50)")
  1346. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_path VARCHAR(200)")
  1347. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_path VARCHAR(200)")
  1348. # Migration: Add separate REST power/energy URLs and multipliers
  1349. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_url VARCHAR(500)")
  1350. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_multiplier REAL DEFAULT 1.0")
  1351. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_url VARCHAR(500)")
  1352. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_multiplier REAL DEFAULT 1.0")
  1353. # Migration: Add batch_id column to print_queue for batch grouping
  1354. try:
  1355. async with conn.begin_nested():
  1356. await conn.execute(
  1357. text(
  1358. "ALTER TABLE print_queue ADD COLUMN batch_id INTEGER REFERENCES print_batches(id) ON DELETE SET NULL"
  1359. )
  1360. )
  1361. except (OperationalError, ProgrammingError):
  1362. pass
  1363. # Migration: Shortest-job-first scheduling columns on print_queue
  1364. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN print_time_seconds INTEGER")
  1365. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN been_jumped BOOLEAN DEFAULT FALSE NOT NULL")
  1366. # Migration: Auto-print G-code injection (#422)
  1367. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE NOT NULL")
  1368. # Migration: Add backup_spools and backup_archives columns to github_backup_config
  1369. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_spools BOOLEAN DEFAULT 0")
  1370. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_archives BOOLEAN DEFAULT 0")
  1371. # Migration: Widen columns where SQLite allowed data beyond the declared VARCHAR limit
  1372. if not is_sqlite():
  1373. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_hash TYPE VARCHAR(255)")
  1374. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_prefix TYPE VARCHAR(20)")
  1375. await _safe_execute(conn, "ALTER TABLE print_archives ALTER COLUMN filament_color TYPE VARCHAR(200)")
  1376. # Migration: Create GIN index for full-text search on PostgreSQL
  1377. # (SQLite uses FTS5 virtual table instead, set up above)
  1378. if not is_sqlite():
  1379. try:
  1380. await conn.execute(
  1381. text("""
  1382. CREATE INDEX IF NOT EXISTS idx_archives_fulltext
  1383. ON print_archives
  1384. USING GIN (to_tsvector('simple',
  1385. COALESCE(print_name, '') || ' ' ||
  1386. COALESCE(filename, '') || ' ' ||
  1387. COALESCE(tags, '') || ' ' ||
  1388. COALESCE(notes, '') || ' ' ||
  1389. COALESCE(designer, '') || ' ' ||
  1390. COALESCE(filament_type, '')
  1391. ))
  1392. """)
  1393. )
  1394. except (OperationalError, ProgrammingError):
  1395. pass # Already applied
  1396. # Migration: Normalize empty printer_ids [] to NULL (global access) on API keys
  1397. # Previously both None and [] meant "all printers"; now [] means "no printers"
  1398. # PostgreSQL stores printer_ids as JSONB; comparing JSONB to a string literal fails
  1399. # with "operator does not exist: jsonb = unknown" — cast the literal to jsonb explicitly.
  1400. await _migrate_normalize_printer_ids(conn)
  1401. # Migration: Add auth_source column to users for LDAP support (#794)
  1402. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN auth_source VARCHAR(20) DEFAULT 'local' NOT NULL")
  1403. # Migration: Make password_hash nullable for LDAP users (#794)
  1404. # LDAP users have no local password — the column must allow NULL so auto-provisioning
  1405. # doesn't hit a NOT NULL constraint failure on upgraded installs whose users table was
  1406. # originally created before LDAP support landed.
  1407. if is_sqlite():
  1408. # SQLite can't ALTER COLUMN; patch sqlite_master directly via writable_schema.
  1409. # Bump schema_version afterwards so SQLite reloads the table definition from disk —
  1410. # without that bump, the current connection keeps enforcing the old NOT NULL from
  1411. # its cached schema. Safe because row data is untouched and the replace() is a
  1412. # no-op if the constraint has already been removed.
  1413. try:
  1414. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='users'"))
  1415. users_sql = result.scalar()
  1416. if users_sql and "password_hash VARCHAR(255) NOT NULL" in users_sql:
  1417. version_result = await conn.execute(text("PRAGMA schema_version"))
  1418. schema_version = version_result.scalar() or 0
  1419. await conn.execute(text("PRAGMA writable_schema = ON"))
  1420. await conn.execute(
  1421. text(
  1422. "UPDATE sqlite_master "
  1423. "SET sql = replace(sql, 'password_hash VARCHAR(255) NOT NULL', 'password_hash VARCHAR(255)') "
  1424. "WHERE type = 'table' AND name = 'users'"
  1425. )
  1426. )
  1427. await conn.execute(text(f"PRAGMA schema_version = {schema_version + 1}"))
  1428. await conn.execute(text("PRAGMA writable_schema = OFF"))
  1429. except (OperationalError, ProgrammingError) as exc:
  1430. logger.error(
  1431. "Failed to remove NOT NULL from users.password_hash via writable_schema — "
  1432. "OIDC/LDAP user creation will fail on this install: %s",
  1433. exc,
  1434. exc_info=True,
  1435. )
  1436. else:
  1437. await _safe_execute(conn, "ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL")
  1438. # Migration: Add energy_start_kwh to print_archives (#941)
  1439. # Persists the smart plug lifetime counter captured at print start, so per-print
  1440. # energy tracking survives a backend restart mid-print.
  1441. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN energy_start_kwh REAL")
  1442. # Migration: Add subtask_id to print_archives (#972)
  1443. # MQTT-provided task identifier used to resume the same archive row across a
  1444. # backend restart mid-print. Without it, a long print (e.g. 13h) triggers
  1445. # stale-cancel + new-archive, losing started_at continuity.
  1446. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN subtask_id VARCHAR(64)")
  1447. # Migration: Create smart_plug_energy_snapshots table (#941)
  1448. # Hourly snapshots of each plug's lifetime counter, so date-range queries in
  1449. # "total consumption" energy mode can compute (last - first) deltas.
  1450. await _safe_execute(
  1451. conn,
  1452. """
  1453. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1454. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1455. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1456. recorded_at DATETIME NOT NULL,
  1457. lifetime_kwh REAL NOT NULL
  1458. )
  1459. """
  1460. if is_sqlite()
  1461. else """
  1462. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1463. id SERIAL PRIMARY KEY,
  1464. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1465. recorded_at TIMESTAMP NOT NULL,
  1466. lifetime_kwh REAL NOT NULL
  1467. )
  1468. """,
  1469. )
  1470. await _safe_execute(
  1471. conn,
  1472. "CREATE INDEX IF NOT EXISTS ix_plug_energy_snapshots_plug_time "
  1473. "ON smart_plug_energy_snapshots(plug_id, recorded_at)",
  1474. )
  1475. # Migration: Add PKCE code_verifier column to auth_ephemeral_tokens
  1476. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN code_verifier VARCHAR(128)")
  1477. # Migration: Add TOTP replay-protection counter to user_totp
  1478. await _safe_execute(conn, "ALTER TABLE user_totp ADD COLUMN last_totp_counter BIGINT")
  1479. # Migration: Add challenge_id for pre-auth token client binding (HttpOnly cookie)
  1480. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN challenge_id VARCHAR(128)")
  1481. # Migration: Add auto_link_existing_accounts column to oidc_providers (M-4)
  1482. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  1483. if is_sqlite():
  1484. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT 0")
  1485. else:
  1486. await _safe_execute(
  1487. conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT false"
  1488. )
  1489. # Migration: Azure Entra ID support — configurable email claim and verification requirement
  1490. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN email_claim VARCHAR(64) DEFAULT 'email'")
  1491. # Postgres rejects `DEFAULT 1` for BOOLEAN columns.
  1492. if is_sqlite():
  1493. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT 1")
  1494. else:
  1495. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT true")
  1496. # SEC-1 backfill: reset auto_link only for Fall B (email_claim='email' + require_email_verified=False).
  1497. # Fall C (custom claim) is now allowed to use auto_link — do NOT reset those rows.
  1498. # Runs BEFORE the CHECK constraint below so Fall B rows self-heal rather than failing
  1499. # PostgreSQL's "check constraint is violated by some row" on ADD CONSTRAINT.
  1500. # On fresh installs the column defaults guarantee this UPDATE matches zero rows.
  1501. # TRUE/FALSE literals are accepted by both SQLite (≥ 3.23) and PostgreSQL — no dialect branch needed.
  1502. try:
  1503. async with conn.begin_nested():
  1504. await conn.execute(
  1505. text(
  1506. "UPDATE oidc_providers SET auto_link_existing_accounts = FALSE "
  1507. "WHERE auto_link_existing_accounts = TRUE "
  1508. "AND email_claim = 'email' AND require_email_verified = FALSE"
  1509. )
  1510. )
  1511. except Exception as exc:
  1512. logger.error(
  1513. "SEC-1 safety backfill FAILED — auto_link_existing_accounts may remain enabled "
  1514. "on providers with unsafe email settings: %s",
  1515. exc,
  1516. exc_info=True,
  1517. )
  1518. raise
  1519. # SEC-1: Add DB-level CHECK constraint for existing PostgreSQL installs.
  1520. # SQLite does not support ALTER TABLE ADD CONSTRAINT — handled by __table_args__ at creation.
  1521. # Runs AFTER the backfill so Fall B rows don't fail constraint validation.
  1522. if not is_sqlite():
  1523. try:
  1524. async with conn.begin_nested():
  1525. await conn.execute(
  1526. text(
  1527. "ALTER TABLE oidc_providers ADD CONSTRAINT ck_auto_link_requires_verified_email_claim "
  1528. "CHECK (auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE)"
  1529. )
  1530. )
  1531. except (OperationalError, ProgrammingError) as exc:
  1532. msg = str(exc).lower()
  1533. if "already exists" not in msg:
  1534. logger.error(
  1535. "Security constraint migration FAILED — auto_link safety constraint may not be enforced: %s",
  1536. exc,
  1537. exc_info=True,
  1538. )
  1539. raise
  1540. # Migration: Update auto_link CHECK constraint formula (existing installs).
  1541. # Existing PostgreSQL installs that ran the ADD CONSTRAINT above with the old formula
  1542. # (or a previous version of this code) need an explicit DROP + ADD to update it.
  1543. # For SQLite, the table is recreated with the new constraint formula if the old formula
  1544. # is still present in sqlite_master (SQLite cannot ALTER TABLE DROP/ADD CONSTRAINT).
  1545. await _migrate_update_auto_link_constraint(conn)
  1546. # Migration: Add default_group_id to oidc_providers.
  1547. # Must run AFTER _migrate_update_auto_link_constraint to avoid being dropped during
  1548. # the SQLite table recreation that function performs on stale-formula databases.
  1549. await _safe_execute(
  1550. conn,
  1551. "ALTER TABLE oidc_providers ADD COLUMN default_group_id INTEGER REFERENCES groups(id) ON DELETE SET NULL",
  1552. )
  1553. # Migration: Add password_changed_at to users (M-R7-B)
  1554. # Tracks the last time a user's password was changed/reset. JWTs whose iat
  1555. # predates this timestamp are rejected in all six auth validation paths.
  1556. # R4 fix: TIMESTAMP is accepted by both SQLite and PostgreSQL; DATETIME
  1557. # is rejected by Postgres ("type 'datetime' does not exist"), which made
  1558. # _safe_execute swallow the error and leave existing Postgres installs
  1559. # without the column — causing UndefinedColumnError on every User query.
  1560. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP")
  1561. # Migration: Back-fill password_changed_at = created_at for existing users (I2).
  1562. # Users who never changed their password would have NULL here, meaning old
  1563. # tokens could never be invalidated via the freshness check. Setting it to
  1564. # created_at is conservative: any token issued before the account was created
  1565. # is always invalid, so this is a safe lower bound.
  1566. async with conn.begin_nested():
  1567. await conn.execute(text("UPDATE users SET password_changed_at = created_at WHERE password_changed_at IS NULL"))
  1568. # Migration: Provenance columns on library_files for MakerWorld imports.
  1569. # source_url is indexed so "already imported" dedupe lookups stay O(log N)
  1570. # as the library grows.
  1571. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_type VARCHAR(32)")
  1572. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_url VARCHAR(512)")
  1573. await _safe_execute(
  1574. conn,
  1575. "CREATE INDEX IF NOT EXISTS ix_library_files_source_url ON library_files(source_url)",
  1576. )
  1577. # Migration: Cache metadata title on pending uploads (#1152 follow-up).
  1578. # Without this column the review card always shows the FTP filename while
  1579. # the eventual archive's print_name comes from the 3MF metadata title,
  1580. # creating a confusing review→archive name mismatch. Captured at upload
  1581. # time so /pending-uploads/ list calls don't have to reopen each 3MF.
  1582. await _safe_execute(
  1583. conn,
  1584. "ALTER TABLE pending_uploads ADD COLUMN metadata_print_name VARCHAR(255)",
  1585. )
  1586. # Migration: Per-user API key ownership + cloud-access scope (#1182).
  1587. # user_id is nullable so legacy keys (created before #1182) survive the
  1588. # migration; cloud routes reject calls from keys without an owner so the
  1589. # operator is forced to recreate them. ON DELETE CASCADE so deleting a user
  1590. # takes their keys with them — orphan keys must never authenticate.
  1591. # SQLite ignores REFERENCES on ADD COLUMN (not enforced but not an error);
  1592. # PostgreSQL enforces the FK from this point forward. Indexed for the
  1593. # auth-gate's owner→keys lookup that runs on every API-keyed request.
  1594. await _safe_execute(
  1595. conn,
  1596. "ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE CASCADE",
  1597. )
  1598. await _safe_execute(
  1599. conn,
  1600. "CREATE INDEX IF NOT EXISTS ix_api_keys_user_id ON api_keys(user_id)",
  1601. )
  1602. # ``DEFAULT 0`` works on SQLite (boolean is just integer-coerced) but
  1603. # asyncpg's strict type-check rejects it: "column is of type boolean but
  1604. # default expression is of type integer". Use ``DEFAULT FALSE`` so both
  1605. # dialects accept the same statement — same pattern as the print_queue
  1606. # gcode_injection migration above.
  1607. await _safe_execute(
  1608. conn,
  1609. "ALTER TABLE api_keys ADD COLUMN can_access_cloud BOOLEAN DEFAULT FALSE",
  1610. )
  1611. # Migration: Soft-delete column for trash bin (Issue #1008). Indexed so the
  1612. # sweeper's "SELECT ... WHERE deleted_at < cutoff" and the trash list's
  1613. # "WHERE deleted_at IS NOT NULL" stay cheap as the table grows.
  1614. #
  1615. # ``DATETIME`` is a SQLite-only type alias — PostgreSQL rejects it as
  1616. # invalid syntax, _safe_execute swallows the error, and the column is
  1617. # never added (breaking every query that references it). Emit
  1618. # dialect-appropriate SQL so both backends get the column.
  1619. if is_sqlite():
  1620. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at DATETIME")
  1621. else:
  1622. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at TIMESTAMP")
  1623. await _safe_execute(
  1624. conn,
  1625. "CREATE INDEX IF NOT EXISTS ix_library_files_deleted_at ON library_files(deleted_at)",
  1626. )
  1627. # Legacy SQLite installs created `settings` without a UNIQUE constraint on `key`,
  1628. # so `INSERT OR IGNORE` below silently degrades to a plain INSERT and dupes rows on
  1629. # every restart. Dedupe (keep lowest id per key) and add the missing unique index
  1630. # before seeding. Safe/idempotent on both dialects — fresh installs already have
  1631. # no dupes and `create_all` already emits the index.
  1632. async with conn.begin_nested():
  1633. await conn.execute(text("DELETE FROM settings WHERE id NOT IN (SELECT MIN(id) FROM settings GROUP BY key)"))
  1634. await _safe_execute(conn, "CREATE UNIQUE INDEX IF NOT EXISTS ix_settings_key ON settings(key)")
  1635. # Migration: Normalise provider_email to lowercase (SEC-3).
  1636. # Required for Entra ID where UPN/email claims may arrive in mixed case.
  1637. # LOWER() is supported by both SQLite and PostgreSQL; the UPDATE is idempotent.
  1638. # Executed directly (not via _safe_execute) so any column-reference failure
  1639. # is always fatal and never silently swallowed.
  1640. async with conn.begin_nested():
  1641. await conn.execute(
  1642. text(
  1643. "UPDATE user_oidc_links SET provider_email = LOWER(provider_email) "
  1644. "WHERE provider_email IS NOT NULL AND provider_email != LOWER(provider_email)"
  1645. )
  1646. )
  1647. # Migration: Add provider column to github_backup_config for multi-provider support
  1648. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN provider VARCHAR(30) DEFAULT 'github'")
  1649. # Migration: Add allow_insecure_http column to github_backup_config for self-hosted HTTP instances
  1650. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN allow_insecure_http BOOLEAN DEFAULT FALSE")
  1651. # Seed default settings keys that must exist on fresh install
  1652. default_settings = [
  1653. ("advanced_auth_enabled", "false"),
  1654. ("smtp_auth_enabled", "true"),
  1655. ]
  1656. for key, value in default_settings:
  1657. try:
  1658. if is_sqlite():
  1659. await conn.execute(
  1660. text("INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)"),
  1661. {"key": key, "value": value},
  1662. )
  1663. else:
  1664. await conn.execute(
  1665. text("INSERT INTO settings (key, value) VALUES (:key, :value) ON CONFLICT (key) DO NOTHING"),
  1666. {"key": key, "value": value},
  1667. )
  1668. except (OperationalError, ProgrammingError):
  1669. pass
  1670. # Migration: Create filament_sku_settings table for reorder forecasting
  1671. if is_sqlite():
  1672. await _safe_execute(
  1673. conn,
  1674. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  1675. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1676. material VARCHAR(50) NOT NULL,
  1677. subtype VARCHAR(50),
  1678. brand VARCHAR(100),
  1679. lead_time_days INTEGER NOT NULL DEFAULT 0,
  1680. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  1681. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  1682. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1683. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1684. UNIQUE (material, subtype, brand)
  1685. )""",
  1686. )
  1687. async with conn.begin_nested():
  1688. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  1689. await _safe_execute(
  1690. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_value INTEGER NOT NULL DEFAULT 14"
  1691. )
  1692. await _safe_execute(
  1693. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'"
  1694. )
  1695. await _safe_execute(
  1696. conn, "ALTER TABLE filament_sku_settings ADD COLUMN alerts_snoozed BOOLEAN NOT NULL DEFAULT 0"
  1697. )
  1698. # Backfill and drop legacy safety_margin_days column — SQLite requires a table rebuild.
  1699. # Only run if the stale column still exists.
  1700. cols_result = await conn.execute(text("PRAGMA table_info(filament_sku_settings)"))
  1701. col_names = [row[1] for row in cols_result.fetchall()]
  1702. if "safety_margin_days" in col_names:
  1703. async with conn.begin_nested():
  1704. # Defensive: a previous startup may have crashed mid-rebuild leaving
  1705. # filament_sku_settings_new behind, which would break the CREATE below.
  1706. await conn.execute(text("DROP TABLE IF EXISTS filament_sku_settings_new"))
  1707. await conn.execute(
  1708. text(
  1709. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  1710. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  1711. )
  1712. )
  1713. await conn.execute(
  1714. text(
  1715. """CREATE TABLE filament_sku_settings_new (
  1716. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1717. material VARCHAR(50) NOT NULL,
  1718. subtype VARCHAR(50),
  1719. brand VARCHAR(100),
  1720. lead_time_days INTEGER NOT NULL DEFAULT 0,
  1721. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  1722. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  1723. alerts_snoozed BOOLEAN NOT NULL DEFAULT 0,
  1724. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1725. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1726. UNIQUE (material, subtype, brand)
  1727. )"""
  1728. )
  1729. )
  1730. await conn.execute(
  1731. text(
  1732. """INSERT INTO filament_sku_settings_new
  1733. (id, material, subtype, brand, lead_time_days, safety_margin_value,
  1734. safety_margin_unit, alerts_snoozed, created_at, updated_at)
  1735. SELECT id, material, subtype, brand, lead_time_days, safety_margin_value,
  1736. safety_margin_unit, COALESCE(alerts_snoozed, 0), created_at, updated_at
  1737. FROM filament_sku_settings"""
  1738. )
  1739. )
  1740. await conn.execute(text("DROP TABLE filament_sku_settings"))
  1741. await conn.execute(text("ALTER TABLE filament_sku_settings_new RENAME TO filament_sku_settings"))
  1742. await _safe_execute(
  1743. conn,
  1744. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  1745. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1746. material VARCHAR(50) NOT NULL,
  1747. subtype VARCHAR(50),
  1748. brand VARCHAR(100),
  1749. quantity_spools INTEGER NOT NULL DEFAULT 1,
  1750. note VARCHAR(500),
  1751. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  1752. purchased_at DATETIME,
  1753. added_at DATETIME DEFAULT CURRENT_TIMESTAMP
  1754. )""",
  1755. )
  1756. # SQLite has no implicit updated_at trigger — add one so the column stays current.
  1757. await _safe_execute(
  1758. conn,
  1759. """CREATE TRIGGER IF NOT EXISTS trg_filament_sku_settings_updated_at
  1760. AFTER UPDATE ON filament_sku_settings FOR EACH ROW
  1761. BEGIN
  1762. UPDATE filament_sku_settings SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
  1763. END""",
  1764. )
  1765. else:
  1766. await _safe_execute(
  1767. conn,
  1768. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  1769. id SERIAL PRIMARY KEY,
  1770. material VARCHAR(50) NOT NULL,
  1771. subtype VARCHAR(50),
  1772. brand VARCHAR(100),
  1773. lead_time_days INTEGER NOT NULL DEFAULT 0,
  1774. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  1775. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  1776. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  1777. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  1778. UNIQUE (material, subtype, brand)
  1779. )""",
  1780. )
  1781. async with conn.begin_nested():
  1782. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  1783. await _safe_execute(
  1784. conn,
  1785. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_value INTEGER NOT NULL DEFAULT 14",
  1786. )
  1787. await _safe_execute(
  1788. conn,
  1789. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'",
  1790. )
  1791. await _safe_execute(
  1792. conn,
  1793. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS alerts_snoozed BOOLEAN NOT NULL DEFAULT FALSE",
  1794. )
  1795. # Only backfill from safety_margin_days if that column still exists (PostgreSQL).
  1796. col_check = await conn.execute(
  1797. text(
  1798. "SELECT 1 FROM information_schema.columns "
  1799. "WHERE table_name = 'filament_sku_settings' AND column_name = 'safety_margin_days'"
  1800. )
  1801. )
  1802. if col_check.fetchone():
  1803. async with conn.begin_nested():
  1804. await conn.execute(
  1805. text(
  1806. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  1807. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  1808. )
  1809. )
  1810. await _safe_execute(
  1811. conn,
  1812. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  1813. id SERIAL PRIMARY KEY,
  1814. material VARCHAR(50) NOT NULL,
  1815. subtype VARCHAR(50),
  1816. brand VARCHAR(100),
  1817. quantity_spools INTEGER NOT NULL DEFAULT 1,
  1818. note VARCHAR(500),
  1819. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  1820. purchased_at TIMESTAMP,
  1821. added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  1822. )""",
  1823. )
  1824. await _safe_execute(
  1825. conn,
  1826. "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'pending'",
  1827. )
  1828. await _safe_execute(conn, "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS purchased_at TIMESTAMP")
  1829. # Migration: Add inventory stock alert columns to notification_providers.
  1830. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  1831. if is_sqlite():
  1832. await _safe_execute(
  1833. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT 0"
  1834. )
  1835. await _safe_execute(
  1836. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT 0"
  1837. )
  1838. else:
  1839. await _safe_execute(
  1840. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT false"
  1841. )
  1842. await _safe_execute(
  1843. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT false"
  1844. )
  1845. async def seed_notification_templates():
  1846. """Seed default notification templates if they don't exist."""
  1847. from sqlalchemy import select
  1848. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  1849. async with async_session() as session:
  1850. # Get existing template event types
  1851. result = await session.execute(select(NotificationTemplate.event_type))
  1852. existing_types = {row[0] for row in result.fetchall()}
  1853. if not existing_types:
  1854. # No templates exist - insert all defaults
  1855. for template_data in DEFAULT_TEMPLATES:
  1856. template = NotificationTemplate(
  1857. event_type=template_data["event_type"],
  1858. name=template_data["name"],
  1859. title_template=template_data["title_template"],
  1860. body_template=template_data["body_template"],
  1861. is_default=True,
  1862. )
  1863. session.add(template)
  1864. else:
  1865. # Templates exist - only add missing ones
  1866. for template_data in DEFAULT_TEMPLATES:
  1867. if template_data["event_type"] not in existing_types:
  1868. template = NotificationTemplate(
  1869. event_type=template_data["event_type"],
  1870. name=template_data["name"],
  1871. title_template=template_data["title_template"],
  1872. body_template=template_data["body_template"],
  1873. is_default=True,
  1874. )
  1875. session.add(template)
  1876. await session.commit()
  1877. async def seed_default_groups():
  1878. """Seed default groups and migrate existing users to appropriate groups.
  1879. Creates the default system groups (Administrators, Operators, Viewers) if they
  1880. don't exist, then migrates existing users:
  1881. - Users with role='admin' -> Administrators group
  1882. - Users with role='user' -> Operators group
  1883. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1884. """
  1885. import logging
  1886. from sqlalchemy import select
  1887. from backend.app.core.permissions import DEFAULT_GROUPS
  1888. from backend.app.models.group import Group
  1889. from backend.app.models.user import User
  1890. logger = logging.getLogger(__name__)
  1891. # Map old permissions to new ones for migration
  1892. # Administrators get *_all permissions, Operators get *_own permissions
  1893. PERMISSION_MIGRATION_ALL = {
  1894. "queue:update": "queue:update_all",
  1895. "queue:delete": "queue:delete_all",
  1896. "archives:update": "archives:update_all",
  1897. "archives:delete": "archives:delete_all",
  1898. "archives:reprint": "archives:reprint_all",
  1899. "library:update": "library:update_all",
  1900. "library:delete": "library:delete_all",
  1901. }
  1902. PERMISSION_MIGRATION_OWN = {
  1903. "queue:update": "queue:update_own",
  1904. "queue:delete": "queue:delete_own",
  1905. "archives:update": "archives:update_own",
  1906. "archives:delete": "archives:delete_own",
  1907. "archives:reprint": "archives:reprint_own",
  1908. "library:update": "library:update_own",
  1909. "library:delete": "library:delete_own",
  1910. }
  1911. async with async_session() as session:
  1912. # Get existing groups
  1913. result = await session.execute(select(Group))
  1914. existing_groups = {group.name: group for group in result.scalars().all()}
  1915. # Create default groups if they don't exist
  1916. groups_created = []
  1917. for group_name, group_config in DEFAULT_GROUPS.items():
  1918. if group_name not in existing_groups:
  1919. group = Group(
  1920. name=group_name,
  1921. description=group_config["description"],
  1922. permissions=group_config["permissions"],
  1923. is_system=group_config["is_system"],
  1924. )
  1925. session.add(group)
  1926. groups_created.append(group_name)
  1927. logger.info("Created default group: %s", group_name)
  1928. else:
  1929. # Migrate existing group's permissions from old to new format
  1930. group = existing_groups[group_name]
  1931. if group.permissions:
  1932. updated = False
  1933. new_permissions = list(group.permissions)
  1934. # Determine which migration map to use based on group
  1935. migration_map = (
  1936. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1937. )
  1938. for old_perm, new_perm in migration_map.items():
  1939. if old_perm in new_permissions:
  1940. new_permissions.remove(old_perm)
  1941. if new_perm not in new_permissions:
  1942. new_permissions.append(new_perm)
  1943. updated = True
  1944. logger.info(
  1945. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  1946. )
  1947. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1948. if group_name == "Administrators":
  1949. for _own_perm, all_perm in [
  1950. ("queue:update_own", "queue:update_all"),
  1951. ("queue:delete_own", "queue:delete_all"),
  1952. ("archives:update_own", "archives:update_all"),
  1953. ("archives:delete_own", "archives:delete_all"),
  1954. ("archives:reprint_own", "archives:reprint_all"),
  1955. ("library:update_own", "library:update_all"),
  1956. ("library:delete_own", "library:delete_all"),
  1957. ]:
  1958. # Add *_all if not present
  1959. if all_perm not in new_permissions:
  1960. new_permissions.append(all_perm)
  1961. updated = True
  1962. if updated:
  1963. group.permissions = new_permissions
  1964. await session.commit()
  1965. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  1966. result = await session.execute(select(Group))
  1967. all_groups = result.scalars().all()
  1968. for group in all_groups:
  1969. if (
  1970. group.permissions
  1971. and "printers:control" in group.permissions
  1972. and "printers:clear_plate" not in group.permissions
  1973. ):
  1974. group.permissions = [*group.permissions, "printers:clear_plate"]
  1975. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  1976. await session.commit()
  1977. # Migrate new permissions for MakerWorld integration: groups that
  1978. # already have library:upload (i.e. can write to the library) are
  1979. # the correct audience for makerworld:view + makerworld:import, and
  1980. # groups that only have library:read get makerworld:view (browse
  1981. # only). Matches the intent of DEFAULT_GROUPS without clobbering
  1982. # any user-customised permission lists.
  1983. result = await session.execute(select(Group))
  1984. for group in result.scalars().all():
  1985. if not group.permissions:
  1986. continue
  1987. perms = list(group.permissions)
  1988. changed = False
  1989. if "library:upload" in perms:
  1990. for new_perm in ("makerworld:view", "makerworld:import"):
  1991. if new_perm not in perms:
  1992. perms.append(new_perm)
  1993. changed = True
  1994. logger.info("Added %s to group '%s' (has library:upload)", new_perm, group.name)
  1995. elif "library:read" in perms and "makerworld:view" not in perms:
  1996. perms.append("makerworld:view")
  1997. changed = True
  1998. logger.info("Added makerworld:view to group '%s' (has library:read)", group.name)
  1999. if changed:
  2000. group.permissions = perms
  2001. await session.commit()
  2002. # Backfill library:purge + archives:purge for the Administrators group
  2003. # on existing installs. Both permissions were added after Administrators
  2004. # was first seeded, so upgrading users miss them even though the default
  2005. # config (ALL_PERMISSIONS) includes them for fresh installs.
  2006. result = await session.execute(select(Group).where(Group.name == "Administrators"))
  2007. admin_group = result.scalar_one_or_none()
  2008. if admin_group and admin_group.permissions is not None:
  2009. perms = list(admin_group.permissions)
  2010. added = False
  2011. for new_perm in ("library:purge", "archives:purge"):
  2012. if new_perm not in perms:
  2013. perms.append(new_perm)
  2014. added = True
  2015. logger.info("Added %s to Administrators group (backfill)", new_perm)
  2016. if added:
  2017. admin_group.permissions = perms
  2018. await session.commit()
  2019. # Backfill inventory forecast permissions for existing groups.
  2020. # inventory:forecast_read was added after initial seeding, so groups
  2021. # that already have inventory:read (or inventory:update) need it added.
  2022. # inventory:forecast_write goes to any group with inventory:update.
  2023. result = await session.execute(select(Group))
  2024. for group in result.scalars().all():
  2025. if not group.permissions:
  2026. continue
  2027. perms = list(group.permissions)
  2028. changed = False
  2029. if "inventory:read" in perms and "inventory:forecast_read" not in perms:
  2030. perms.append("inventory:forecast_read")
  2031. changed = True
  2032. logger.info("Added inventory:forecast_read to group '%s' (backfill)", group.name)
  2033. if "inventory:update" in perms and "inventory:forecast_write" not in perms:
  2034. perms.append("inventory:forecast_write")
  2035. changed = True
  2036. logger.info("Added inventory:forecast_write to group '%s' (backfill)", group.name)
  2037. if changed:
  2038. group.permissions = perms
  2039. await session.commit()
  2040. # Migrate existing users to groups if they're not already in any group
  2041. if groups_created:
  2042. # Refresh to get newly created groups
  2043. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  2044. admin_group = admin_result.scalar_one_or_none()
  2045. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  2046. operators_group = operators_result.scalar_one_or_none()
  2047. # Get all users
  2048. users_result = await session.execute(select(User))
  2049. users = users_result.scalars().all()
  2050. for user in users:
  2051. # Skip if user already has groups
  2052. if user.groups:
  2053. continue
  2054. if user.role == "admin" and admin_group:
  2055. user.groups.append(admin_group)
  2056. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  2057. elif operators_group:
  2058. user.groups.append(operators_group)
  2059. logger.info("Migrated user '%s' to Operators group", user.username)
  2060. await session.commit()
  2061. async def seed_spool_catalog():
  2062. """Seed the spool catalog with default entries if empty."""
  2063. import logging
  2064. from sqlalchemy import func, select
  2065. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  2066. from backend.app.models.spool_catalog import SpoolCatalogEntry
  2067. logger = logging.getLogger(__name__)
  2068. async with async_session() as session:
  2069. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  2070. count = result.scalar() or 0
  2071. if count > 0:
  2072. return # Already seeded
  2073. for name, weight in DEFAULT_SPOOL_CATALOG:
  2074. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  2075. await session.commit()
  2076. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  2077. async def seed_color_catalog():
  2078. """Seed the color catalog with default entries if empty."""
  2079. import logging
  2080. from sqlalchemy import func, select
  2081. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  2082. from backend.app.models.color_catalog import ColorCatalogEntry
  2083. logger = logging.getLogger(__name__)
  2084. async with async_session() as session:
  2085. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  2086. count = result.scalar() or 0
  2087. if count > 0:
  2088. return # Already seeded
  2089. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  2090. session.add(
  2091. ColorCatalogEntry(
  2092. manufacturer=manufacturer,
  2093. color_name=color_name,
  2094. hex_color=hex_color,
  2095. material=material,
  2096. is_default=True,
  2097. )
  2098. )
  2099. await session.commit()
  2100. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))