database.py 88 KB

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