database.py 87 KB

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