database.py 94 KB

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