database.py 95 KB

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