database.py 76 KB

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