database.py 80 KB

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