database.py 82 KB

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