database.py 88 KB

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