database.py 102 KB

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