database.py 94 KB

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