database.py 169 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454
  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 BaseException:
  118. # Catch BaseException (not just Exception) so CancelledError —
  119. # raised when Starlette's BaseHTTPMiddleware cancels the inner
  120. # task scope on client disconnect — also triggers rollback.
  121. # `asyncio.shield` keeps the rollback running to completion
  122. # even when the await itself gets cancelled, so the SQLite
  123. # write lock is released promptly instead of being held until
  124. # the connection is GC'd ages later (which was producing the
  125. # "database is locked" cascade in #1112's support package).
  126. try:
  127. await asyncio.shield(session.rollback())
  128. except BaseException: # noqa: BLE001 — rollback failure must not mask the original
  129. pass
  130. raise
  131. finally:
  132. try:
  133. await asyncio.shield(session.close())
  134. except BaseException: # noqa: BLE001 — close failure must not mask the original
  135. pass
  136. async def init_db():
  137. # Import models to register them with SQLAlchemy
  138. from backend.app.models import ( # noqa: F401
  139. active_print_spoolman,
  140. ams_history,
  141. ams_label,
  142. api_key,
  143. archive,
  144. auth_ephemeral,
  145. bug_report,
  146. color_catalog,
  147. external_link,
  148. filament,
  149. filament_sku_settings,
  150. github_backup,
  151. group,
  152. kprofile_note,
  153. library,
  154. local_preset,
  155. location,
  156. long_lived_token,
  157. maintenance,
  158. notification,
  159. notification_template,
  160. oidc_provider,
  161. orca_base_cache,
  162. pending_upload,
  163. print_batch,
  164. print_log,
  165. print_queue,
  166. printer,
  167. project,
  168. project_bom,
  169. settings,
  170. shopping_list,
  171. slot_preset,
  172. smart_plug,
  173. smart_plug_energy_snapshot,
  174. spool,
  175. spool_assignment,
  176. spool_catalog,
  177. spool_k_profile,
  178. spool_usage_history,
  179. spoolbuddy_device,
  180. spoolman_k_profile,
  181. spoolman_slot_assignment,
  182. user,
  183. user_email_pref,
  184. user_otp_code,
  185. user_totp,
  186. virtual_printer,
  187. )
  188. async with engine.begin() as conn:
  189. await conn.run_sync(Base.metadata.create_all)
  190. # Run migrations for new columns (SQLite doesn't auto-add columns)
  191. await run_migrations(conn)
  192. # Re-encrypt any legacy plaintext OIDC client_secret / TOTP secret rows
  193. # that exist from before the encryption key was configured.
  194. # Runs on a fresh AsyncSession (NOT the run_migrations() connection) so it
  195. # doesn't share a transaction with the schema-DDL block above — required to
  196. # avoid SQLite "database is locked" contention on the WAL writer.
  197. await _migrate_encrypt_legacy_secrets()
  198. # Seed default notification templates
  199. await seed_notification_templates()
  200. # Seed default groups and migrate existing users
  201. await seed_default_groups()
  202. # Seed default catalog entries
  203. await seed_spool_catalog()
  204. await seed_color_catalog()
  205. # B2: Module-level counter exposing the number of rows skipped during the last
  206. # _migrate_encrypt_legacy_secrets() invocation. Surfaced via /encryption-status
  207. # (migration_error_count) so operators can spot poison rows that need attention.
  208. _migration_error_count: int = 0
  209. def get_migration_error_count() -> int:
  210. """Return the number of rows that failed to re-encrypt during the last
  211. _migrate_encrypt_legacy_secrets() run."""
  212. return _migration_error_count
  213. async def _migrate_encrypt_legacy_secrets() -> None:
  214. """Re-encrypt OIDC ``client_secret`` and TOTP ``secret`` rows that are still
  215. stored as plaintext (no ``fernet:`` prefix).
  216. Called from :func:`init_db` after :func:`run_migrations` finishes. No-ops
  217. when no encryption key is configured (so plaintext storage stays the
  218. legacy behaviour for installs without a key).
  219. B2: per-row strategy — each row is committed in its own AsyncSession so a
  220. single corrupt row does NOT block other successful re-encryptions on every
  221. startup forever. The skipped-row count is exposed via
  222. :func:`get_migration_error_count` and surfaced on /encryption-status.
  223. B3: unexpected (non-row) failures during the read phase are re-raised so
  224. operators see the problem instead of silent data corruption — startup
  225. fails loudly rather than running with half-migrated rows.
  226. Idempotent: rows that already start with ``fernet:`` are skipped, and the
  227. write-phase re-checks the prefix before encrypting (guards against double
  228. encryption from concurrent workers).
  229. """
  230. from sqlalchemy import not_, select
  231. from backend.app.core.encryption import is_encryption_active
  232. from backend.app.models.oidc_provider import OIDCProvider
  233. from backend.app.models.user_totp import UserTOTP
  234. global _migration_error_count
  235. if not is_encryption_active():
  236. # Reset stale counter from a previous active-key run — we no longer
  237. # have any rows to migrate, so the count must not leak across runs.
  238. _migration_error_count = 0
  239. return
  240. # Phase 1 (read): collect (id, stored_value) tuples for plaintext rows.
  241. # Read phase failures are startup-fatal — re-raise (B3).
  242. try:
  243. async with async_session() as ro:
  244. oidc_rows = await ro.execute(
  245. select(OIDCProvider.id, OIDCProvider._client_secret_enc).where(
  246. not_(OIDCProvider._client_secret_enc.like("fernet:%"))
  247. )
  248. )
  249. oidc_candidates = [(r[0], r[1]) for r in oidc_rows.all()]
  250. totp_rows = await ro.execute(
  251. select(UserTOTP.id, UserTOTP._secret_enc).where(not_(UserTOTP._secret_enc.like("fernet:%")))
  252. )
  253. totp_candidates = [(r[0], r[1]) for r in totp_rows.all()]
  254. except Exception:
  255. logger.error("_migrate_encrypt_legacy_secrets: phase 1 read failed", exc_info=True)
  256. raise # B3
  257. oidc_count = totp_count = error_count = 0
  258. # Phase 2 (write): each row in its own AsyncSession + transaction.
  259. # Failure of one row does NOT block the others.
  260. for oidc_id, stored in oidc_candidates:
  261. if not stored:
  262. continue # defensive: skip empty strings
  263. try:
  264. async with async_session() as wr:
  265. provider = await wr.get(OIDCProvider, oidc_id)
  266. if provider is None:
  267. continue # row deleted between phase 1 and phase 2
  268. # Idempotent guard: re-check inside the write session in case a
  269. # concurrent worker beat us to it.
  270. if not provider._client_secret_enc.startswith("fernet:"):
  271. provider.client_secret = stored # setter -> mfa_encrypt
  272. await wr.commit()
  273. oidc_count += 1
  274. except Exception:
  275. logger.error(
  276. "Failed to re-encrypt OIDCProvider id=%s — skipping",
  277. oidc_id,
  278. exc_info=True,
  279. )
  280. error_count += 1
  281. for totp_id, stored in totp_candidates:
  282. if not stored:
  283. continue
  284. try:
  285. async with async_session() as wr:
  286. totp = await wr.get(UserTOTP, totp_id)
  287. if totp is None:
  288. continue
  289. if not totp._secret_enc.startswith("fernet:"):
  290. totp.secret = stored
  291. await wr.commit()
  292. totp_count += 1
  293. except Exception:
  294. logger.error(
  295. "Failed to re-encrypt UserTOTP id=%s — skipping",
  296. totp_id,
  297. exc_info=True,
  298. )
  299. error_count += 1
  300. _migration_error_count = error_count
  301. if oidc_count or totp_count:
  302. logger.info(
  303. "Re-encrypted legacy plaintext secrets: %d OIDC client_secret(s), %d TOTP secret(s)",
  304. oidc_count,
  305. totp_count,
  306. )
  307. elif error_count == 0:
  308. logger.debug("_migrate_encrypt_legacy_secrets: no rows needed re-encryption")
  309. if error_count:
  310. logger.error(
  311. "_migrate_encrypt_legacy_secrets: %d row(s) skipped due to errors. "
  312. "See /api/v1/auth/encryption-status (migration_error_count).",
  313. error_count,
  314. )
  315. async def _safe_execute(conn, sql):
  316. """Execute a DDL migration statement, silently ignoring idempotency errors.
  317. 'already exists', 'duplicate column name' (SQLite ADD COLUMN), 'no such column'
  318. (SQLite RENAME COLUMN), 'duplicate key', and the compound
  319. 'column … does not exist' (PostgreSQL RENAME COLUMN idempotency) are swallowed
  320. so that re-running DDL migrations is safe. The compound check additionally
  321. requires the SQL to be a RENAME COLUMN statement so that "does not exist" errors
  322. from ADD COLUMN or CREATE INDEX (which would indicate schema corruption, not
  323. idempotency) are never silently swallowed.
  324. Any other error is logged and re-raised — callers must not assume silent
  325. recovery, as a failure will abort the migration sequence and prevent
  326. application startup.
  327. Only use for DDL statements (ALTER TABLE, CREATE INDEX, etc.).
  328. For DML backfills (UPDATE, DELETE) use conn.execute() directly inside
  329. async with conn.begin_nested() so failures are never silently swallowed.
  330. Uses a savepoint so that a failed statement doesn't poison the surrounding
  331. transaction (required for PostgreSQL).
  332. """
  333. from sqlalchemy import text
  334. try:
  335. async with conn.begin_nested():
  336. await conn.execute(text(sql))
  337. except (OperationalError, ProgrammingError) as exc:
  338. msg = str(exc).lower()
  339. # Only swallow "column … does not exist" for RENAME COLUMN — not for ADD COLUMN
  340. # or CREATE INDEX where it would indicate schema corruption, not idempotency.
  341. column_not_exists = "rename column" in sql.lower() and "column" in msg and "does not exist" in msg
  342. if (
  343. not any(k in msg for k in ("already exists", "duplicate key", "duplicate column name", "no such column"))
  344. and not column_not_exists
  345. ):
  346. logger.error("Migration statement failed: %s | SQL: %.200s", exc, sql)
  347. raise
  348. async def _api_keys_column_exists(conn, column_name: str) -> bool:
  349. """Return True if the named column exists on ``api_keys``.
  350. Used to gate one-shot data backfills that must run only on the migration
  351. that adds a column — without this, repeating the UPDATE on every startup
  352. would silently overwrite values the user later edited in the UI.
  353. Dialect-specific because SQLite has no information_schema.
  354. """
  355. from sqlalchemy import text
  356. if is_sqlite():
  357. result = await conn.execute(text("PRAGMA table_info(api_keys)"))
  358. return any(row[1] == column_name for row in result)
  359. result = await conn.execute(
  360. text("SELECT 1 FROM information_schema.columns WHERE table_name = 'api_keys' AND column_name = :col"),
  361. {"col": column_name},
  362. )
  363. return result.scalar_one_or_none() is not None
  364. async def _migrate_normalize_printer_ids(conn) -> None:
  365. from sqlalchemy import text
  366. async with conn.begin_nested():
  367. if is_sqlite():
  368. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids = '[]'"))
  369. else:
  370. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids::text = '[]'"))
  371. async def _migrate_drop_library_print_name(conn) -> None:
  372. """Strip the embedded 3MF Title (``print_name``) from library file metadata (#1489).
  373. Library files stored the 3MF's ``<metadata name="Title">`` as
  374. ``file_metadata.print_name`` — generic ("Exported 3D Model") for Bambu
  375. Studio exports, a marketing title for MakerWorld downloads — and the
  376. FileManager wrongly preferred it over the filename for the card label,
  377. search and sort. New imports no longer store it; this clears it from rows
  378. imported before the fix so existing libraries don't need a rename
  379. round-trip. Idempotent — rows without the key are untouched.
  380. """
  381. from sqlalchemy import text
  382. async with conn.begin_nested():
  383. if is_sqlite():
  384. await conn.execute(
  385. text(
  386. "UPDATE library_files SET file_metadata = json_remove(file_metadata, '$.print_name') "
  387. "WHERE json_extract(file_metadata, '$.print_name') IS NOT NULL"
  388. )
  389. )
  390. else:
  391. # file_metadata is a JSON (not JSONB) column — cast to jsonb for the
  392. # key-exists test (jsonb_exists, avoiding the `?` operator which
  393. # clashes with driver parameter syntax) and the `- key` removal.
  394. await conn.execute(
  395. text(
  396. "UPDATE library_files SET file_metadata = (file_metadata::jsonb - 'print_name')::json "
  397. "WHERE jsonb_exists(file_metadata::jsonb, 'print_name')"
  398. )
  399. )
  400. async def _migrate_update_auto_link_constraint(conn) -> None:
  401. """Update the auto_link CHECK constraint to allow Fall C (custom email claim).
  402. Old formula: auto_link = FALSE OR (require_ev = TRUE AND email_claim = 'email')
  403. New formula: auto_link = FALSE OR email_claim != 'email' OR require_ev = TRUE
  404. Only Fall B (email_claim='email' + require_ev=False) remains blocked.
  405. Fall C (custom claim, e.g. Azure preferred_username/upn) is now allowed.
  406. PostgreSQL: DROP CONSTRAINT IF EXISTS + ADD new formula via _safe_execute (idempotent).
  407. SQLite: table recreation when old formula is detected in sqlite_master (idempotent).
  408. """
  409. from sqlalchemy import text
  410. _NEW_FORMULA = "auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE"
  411. _CONSTRAINT_NAME = "ck_auto_link_requires_verified_email_claim"
  412. if not is_sqlite():
  413. await _safe_execute(conn, f"ALTER TABLE oidc_providers DROP CONSTRAINT IF EXISTS {_CONSTRAINT_NAME}")
  414. await _safe_execute(
  415. conn,
  416. f"ALTER TABLE oidc_providers ADD CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})",
  417. )
  418. else:
  419. row = (
  420. await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='oidc_providers'"))
  421. ).fetchone()
  422. # Only recreate if the old (more restrictive) formula is still present.
  423. # Fresh installs created with the new __table_args__ already have the correct formula.
  424. # Installs without any constraint (pre-SEC-1 upgrades) are skipped — app-level guards suffice.
  425. if row and "require_email_verified = TRUE AND email_claim = 'email'" in row[0]:
  426. try:
  427. async with conn.begin_nested():
  428. await conn.execute(text("DROP TABLE IF EXISTS oidc_providers_v2"))
  429. await conn.execute(
  430. text(
  431. "CREATE TABLE oidc_providers_v2 ("
  432. "id INTEGER NOT NULL, "
  433. "name VARCHAR(100) NOT NULL, "
  434. "issuer_url VARCHAR(500) NOT NULL, "
  435. "client_id VARCHAR(255) NOT NULL, "
  436. "client_secret VARCHAR(512) NOT NULL, "
  437. "scopes VARCHAR(500), "
  438. "is_enabled BOOLEAN, "
  439. "auto_create_users BOOLEAN, "
  440. "auto_link_existing_accounts BOOLEAN DEFAULT 0, "
  441. "email_claim VARCHAR(64) DEFAULT 'email', "
  442. "require_email_verified BOOLEAN DEFAULT 1, "
  443. "icon_url TEXT, "
  444. "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  445. "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  446. "PRIMARY KEY (id), "
  447. f"UNIQUE (name), "
  448. f"CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})"
  449. ")"
  450. )
  451. )
  452. await conn.execute(
  453. text(
  454. "INSERT INTO oidc_providers_v2 "
  455. "(id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  456. "auto_create_users, auto_link_existing_accounts, email_claim, "
  457. "require_email_verified, icon_url, created_at, updated_at) "
  458. "SELECT id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  459. "auto_create_users, auto_link_existing_accounts, email_claim, "
  460. "require_email_verified, icon_url, created_at, updated_at "
  461. "FROM oidc_providers"
  462. )
  463. )
  464. original = (await conn.execute(text("SELECT count(*) FROM oidc_providers"))).scalar_one()
  465. copied = (await conn.execute(text("SELECT count(*) FROM oidc_providers_v2"))).scalar_one()
  466. if copied != original:
  467. raise RuntimeError(
  468. f"auto_link constraint migration: row count mismatch after copy "
  469. f"({original} in source, {copied} in copy)"
  470. )
  471. await conn.execute(text("DROP TABLE oidc_providers"))
  472. await conn.execute(text("ALTER TABLE oidc_providers_v2 RENAME TO oidc_providers"))
  473. except Exception as exc:
  474. logger.error(
  475. "auto_link constraint update (SQLite table recreation) FAILED: %s",
  476. exc,
  477. exc_info=True,
  478. )
  479. raise
  480. async def _migrate_widen_spoolman_slot_ams_id_range(conn) -> None:
  481. """Widen ck_ams_id_range on spoolman_slot_assignments to admit AMS-HT (#1274).
  482. Old formula: (ams_id >= 0 AND ams_id <= 7) OR ams_id = 255
  483. New formula: (ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255
  484. The H2C/H2D AMS-HT reports ams_id 128+. The old constraint rejected every
  485. AMS-HT slot link with `IntegrityError: CHECK constraint failed: ck_ams_id_range`.
  486. PostgreSQL: DROP CONSTRAINT IF EXISTS + ADD new formula via _safe_execute.
  487. SQLite: table recreation when the old (narrower) formula is detected in
  488. sqlite_master. Fresh installs already have the widened constraint from
  489. the CREATE TABLE migration above.
  490. """
  491. from sqlalchemy import text
  492. _NEW_FORMULA = "(ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255"
  493. _CONSTRAINT_NAME = "ck_ams_id_range"
  494. if not is_sqlite():
  495. await _safe_execute(
  496. conn,
  497. f"ALTER TABLE spoolman_slot_assignments DROP CONSTRAINT IF EXISTS {_CONSTRAINT_NAME}",
  498. )
  499. await _safe_execute(
  500. conn,
  501. f"ALTER TABLE spoolman_slot_assignments ADD CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})",
  502. )
  503. return
  504. row = (
  505. await conn.execute(
  506. text("SELECT sql FROM sqlite_master WHERE type='table' AND name='spoolman_slot_assignments'")
  507. )
  508. ).fetchone()
  509. if not row:
  510. return
  511. sql = row[0] or ""
  512. # Already widened by an earlier run or by the fresh-install CREATE TABLE above.
  513. if "ams_id >= 128" in sql:
  514. return
  515. # Pre-migration table without any CHECK constraint at all → leave alone;
  516. # the app-level validation handles correctness and we don't risk a
  517. # destructive table rebuild for a constraint that isn't blocking anyone.
  518. if "ck_ams_id_range" not in sql and "ams_id <= 7" not in sql:
  519. return
  520. try:
  521. async with conn.begin_nested():
  522. await conn.execute(text("DROP TABLE IF EXISTS spoolman_slot_assignments_v2"))
  523. await conn.execute(
  524. text(
  525. "CREATE TABLE spoolman_slot_assignments_v2 ("
  526. "id INTEGER PRIMARY KEY AUTOINCREMENT, "
  527. "printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE, "
  528. f"ams_id INTEGER NOT NULL CHECK ({_NEW_FORMULA}), "
  529. "tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3), "
  530. "spoolman_spool_id INTEGER NOT NULL, "
  531. "assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "
  532. "CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)"
  533. ")"
  534. )
  535. )
  536. await conn.execute(
  537. text(
  538. "INSERT INTO spoolman_slot_assignments_v2 "
  539. "(id, printer_id, ams_id, tray_id, spoolman_spool_id, assigned_at) "
  540. "SELECT id, printer_id, ams_id, tray_id, spoolman_spool_id, assigned_at "
  541. "FROM spoolman_slot_assignments"
  542. )
  543. )
  544. original = (await conn.execute(text("SELECT count(*) FROM spoolman_slot_assignments"))).scalar_one()
  545. copied = (await conn.execute(text("SELECT count(*) FROM spoolman_slot_assignments_v2"))).scalar_one()
  546. if copied != original:
  547. raise RuntimeError(
  548. f"spoolman_slot_assignments migration: row count mismatch after copy "
  549. f"({original} in source, {copied} in copy)"
  550. )
  551. await conn.execute(text("DROP TABLE spoolman_slot_assignments"))
  552. await conn.execute(text("ALTER TABLE spoolman_slot_assignments_v2 RENAME TO spoolman_slot_assignments"))
  553. # The index sits on the renamed table; recreate it idempotently
  554. # to handle older sqlite versions that don't auto-rename indexes.
  555. await conn.execute(
  556. text(
  557. "CREATE INDEX IF NOT EXISTS ix_slot_assignment_spool "
  558. "ON spoolman_slot_assignments (spoolman_spool_id)"
  559. )
  560. )
  561. except Exception as exc:
  562. logger.error(
  563. "spoolman_slot_assignments ck_ams_id_range widening (SQLite table recreation) FAILED: %s",
  564. exc,
  565. exc_info=True,
  566. )
  567. raise
  568. async def run_migrations(conn):
  569. """Run all schema migrations and data backfills on startup.
  570. Includes ALTER TABLE (add columns, rename columns, add constraints),
  571. CREATE INDEX, CREATE TRIGGER, data UPDATE backfills, and table recreations
  572. for complex SQLite schema changes that ALTER TABLE cannot handle.
  573. DDL statements are wrapped in _safe_execute for idempotency.
  574. DML backfills (UPDATE/DELETE) are executed directly via conn.execute()
  575. inside begin_nested() so any failure is always fatal and never silently
  576. swallowed.
  577. """
  578. from sqlalchemy import text
  579. # Migration: Add is_favorite column to print_archives
  580. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0")
  581. # Migration: Add content_hash column to print_archives for duplicate detection
  582. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)")
  583. # Migration: Add auto_off_executed column to smart_plugs
  584. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0")
  585. # Migration: Add on_print_stopped column to notification_providers
  586. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1")
  587. # Migration: Add source_3mf_path column to print_archives
  588. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)")
  589. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  590. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)")
  591. # Migration: Add on_maintenance_due column to notification_providers
  592. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0")
  593. # Migration: Add location column to printers for grouping
  594. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN location VARCHAR(100)")
  595. # Migration: Add interval_type column to maintenance_types
  596. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'")
  597. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  598. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0")
  599. # Migration: Add custom_interval_type column to printer_maintenance
  600. await _safe_execute(conn, "ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)")
  601. # Migration: Add power alert columns to smart_plugs
  602. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0")
  603. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL")
  604. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL")
  605. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME")
  606. # Migration: Add schedule columns to smart_plugs
  607. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0")
  608. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)")
  609. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)")
  610. # Migration: Add daily digest columns to notification_providers
  611. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0")
  612. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)")
  613. # Migration: Add missing-spool-assignment print-start notification toggle
  614. try:
  615. async with conn.begin_nested():
  616. await conn.execute(
  617. text(
  618. "ALTER TABLE notification_providers ADD COLUMN on_print_missing_spool_assignment BOOLEAN DEFAULT 0"
  619. )
  620. )
  621. except (OperationalError, ProgrammingError):
  622. pass # Already applied
  623. # Migration: Add project_id column to print_archives
  624. try:
  625. async with conn.begin_nested():
  626. await conn.execute(
  627. text(
  628. "ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  629. )
  630. )
  631. except (OperationalError, ProgrammingError):
  632. pass # Already applied
  633. # Migration: Add project_id column to print_queue
  634. try:
  635. async with conn.begin_nested():
  636. await conn.execute(
  637. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  638. )
  639. except (OperationalError, ProgrammingError):
  640. pass # Already applied
  641. # Migration: Enforce uniqueness on user_oidc_links for existing rows.
  642. # create_all() is idempotent and does not add constraints to existing tables,
  643. # so we create covering unique indexes explicitly here.
  644. await _safe_execute(
  645. conn,
  646. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_provider_sub"
  647. " ON user_oidc_links (provider_id, provider_user_id)",
  648. )
  649. await _safe_execute(
  650. conn,
  651. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_user_provider ON user_oidc_links (user_id, provider_id)",
  652. )
  653. # Migration: Create FTS5 virtual table for archive full-text search (SQLite only)
  654. # PostgreSQL uses tsvector + GIN index instead (set up in archives.py search route)
  655. if is_sqlite():
  656. try:
  657. await conn.execute(
  658. text("""
  659. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  660. print_name,
  661. filename,
  662. tags,
  663. notes,
  664. designer,
  665. filament_type,
  666. content='print_archives',
  667. content_rowid='id'
  668. )
  669. """)
  670. )
  671. except (OperationalError, ProgrammingError):
  672. pass # Already applied
  673. # Migration: Create triggers to keep FTS index in sync
  674. try:
  675. await conn.execute(
  676. text("""
  677. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  678. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  679. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  680. END
  681. """)
  682. )
  683. except (OperationalError, ProgrammingError):
  684. pass # Already applied
  685. try:
  686. await conn.execute(
  687. text("""
  688. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  689. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  690. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  691. END
  692. """)
  693. )
  694. except (OperationalError, ProgrammingError):
  695. pass # Already applied
  696. try:
  697. await conn.execute(
  698. text("""
  699. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  700. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  701. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  702. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  703. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  704. END
  705. """)
  706. )
  707. except (OperationalError, ProgrammingError):
  708. pass # Already applied
  709. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  710. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0")
  711. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME")
  712. # Migration: Add auto_off_persistent column to smart_plugs (keep auto-off enabled between prints)
  713. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_persistent BOOLEAN DEFAULT 0")
  714. # Migration: Add AMS alarm notification columns to notification_providers
  715. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0")
  716. try:
  717. async with conn.begin_nested():
  718. await conn.execute(
  719. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  720. )
  721. except (OperationalError, ProgrammingError):
  722. pass # Already applied
  723. # Migration: Add AMS-HT alarm notification columns to notification_providers
  724. try:
  725. async with conn.begin_nested():
  726. await conn.execute(
  727. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  728. )
  729. except (OperationalError, ProgrammingError):
  730. pass # Already applied
  731. try:
  732. async with conn.begin_nested():
  733. await conn.execute(
  734. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  735. )
  736. except (OperationalError, ProgrammingError):
  737. pass # Already applied
  738. # Migration: Add plate not empty notification column to notification_providers
  739. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1")
  740. # Migration: Add notes column to projects (Phase 2)
  741. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN notes TEXT")
  742. # Migration: Add attachments column to projects (Phase 3)
  743. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN attachments JSON")
  744. # Migration: Add tags column to projects (Phase 4)
  745. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN tags TEXT")
  746. # Migration: Add due_date column to projects (Phase 5)
  747. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN due_date DATETIME")
  748. # Migration: Add priority column to projects (Phase 5)
  749. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'")
  750. # Migration: Add budget column to projects (Phase 6)
  751. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN budget REAL")
  752. # Migration: Add is_template column to projects (Phase 8)
  753. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0")
  754. # Migration: Add template_source_id column to projects (Phase 8)
  755. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN template_source_id INTEGER")
  756. # Migration: Add parent_id column to projects (Phase 10)
  757. try:
  758. async with conn.begin_nested():
  759. await conn.execute(
  760. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  761. )
  762. except (OperationalError, ProgrammingError):
  763. pass # Already applied
  764. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  765. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired")
  766. # Migration: Add unit_price column to project_bom_items
  767. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN unit_price REAL")
  768. # Migration: Add sourcing_url column to project_bom_items
  769. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)")
  770. # Migration: Rename notes to remarks in project_bom_items
  771. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks")
  772. # Migration: Add show_in_switchbar column to smart_plugs
  773. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0")
  774. # Migration: Add runtime tracking columns to printers
  775. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0")
  776. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME")
  777. # Migration: Add quantity column to print_archives for tracking item count
  778. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1")
  779. # Migration: Add manual_start column to print_queue for staged prints
  780. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0")
  781. # Migration: Add wiki_url column to maintenance_types for documentation links
  782. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)")
  783. # Migration: Add tailscale_disabled column to virtual_printers. Opt-in: default TRUE so
  784. # the auto-detect + fallback noise only runs for users who explicitly enable it.
  785. # Postgres rejects `DEFAULT 1` for BOOLEAN (#1070 round-2 review).
  786. if is_sqlite():
  787. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT 1")
  788. else:
  789. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT true")
  790. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  791. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT")
  792. # Migration: filament_short flag on print_queue (#1496). Set by the
  793. # dispatch scheduler when the assigned spool can't satisfy the print's
  794. # per-slot weight; surfaced as a "filament short" badge on the queue row.
  795. # Postgres rejects `DEFAULT 0` for BOOLEAN — branch on dialect.
  796. if is_sqlite():
  797. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_short BOOLEAN DEFAULT 0")
  798. else:
  799. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_short BOOLEAN DEFAULT false")
  800. # Migration: skip_filament_check flag on print_queue (#1698-followup).
  801. # Persists the user's "Print Anyway" acknowledgement so the scheduler
  802. # doesn't re-flag the item every tick after they've confirmed dispatch
  803. # despite the deficit warning. Set from the start route's skip_filament_check
  804. # query param and from PrintModal at queue-creation time. Postgres / SQLite
  805. # boolean default branch matches filament_short above.
  806. if is_sqlite():
  807. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN skip_filament_check BOOLEAN DEFAULT 0")
  808. else:
  809. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN skip_filament_check BOOLEAN DEFAULT false")
  810. # Migration: Add queue_force_color_match column to virtual_printers (#1188).
  811. # Opt-in flag: when true, VP queue-mode uploads pin the per-slot type+color
  812. # from the 3MF onto the queue item's filament_overrides so the scheduler
  813. # refuses to dispatch onto a printer with the wrong filament loaded.
  814. # Default false to preserve current behaviour for upgraders.
  815. if is_sqlite():
  816. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT 0")
  817. else:
  818. await _safe_execute(
  819. conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT FALSE"
  820. )
  821. # Per-VP opt-in for auto-print G-code injection (#1516). Default false so
  822. # existing gcode_snippets users don't silently start injecting on VP/Studio
  823. # Send jobs after upgrading.
  824. if is_sqlite():
  825. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN gcode_injection BOOLEAN DEFAULT 0")
  826. else:
  827. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE")
  828. # Migration: Add target_parts_count column to projects for tracking total parts needed
  829. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_parts_count INTEGER")
  830. # Migration: Add url + cover_image_filename columns to projects (#1155).
  831. # url: external link rendered next to the project name on the card.
  832. # cover_image_filename: filename of the project's hero image inside the
  833. # existing attachments dir; rendered as a thumbnail on the card.
  834. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN url VARCHAR(2048)")
  835. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN cover_image_filename VARCHAR(255)")
  836. # Migration: enhanced filament colour handling on color_catalog (#1154).
  837. # Mirrors the Spool columns added below; widens hex_color to VARCHAR(9)
  838. # so catalog entries can store an alpha component (#RRGGBBAA). SQLite
  839. # ignores VARCHAR length, so the widen only matters on PostgreSQL.
  840. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN extra_colors VARCHAR(255)")
  841. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN effect_type VARCHAR(20)")
  842. if not is_sqlite():
  843. await _safe_execute(conn, "ALTER TABLE color_catalog ALTER COLUMN hex_color TYPE VARCHAR(9)")
  844. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  845. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  846. # PostgreSQL gets the correct schema from create_all(), so skip this
  847. if is_sqlite():
  848. try:
  849. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  850. row = result.fetchone()
  851. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  852. await conn.execute(
  853. text("""
  854. CREATE TABLE print_queue_new (
  855. id INTEGER PRIMARY KEY,
  856. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  857. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  858. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  859. position INTEGER DEFAULT 0,
  860. scheduled_time DATETIME,
  861. manual_start BOOLEAN DEFAULT 0,
  862. require_previous_success BOOLEAN DEFAULT 0,
  863. auto_off_after BOOLEAN DEFAULT 0,
  864. ams_mapping TEXT,
  865. status VARCHAR(20) DEFAULT 'pending',
  866. started_at DATETIME,
  867. completed_at DATETIME,
  868. error_message TEXT,
  869. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  870. )
  871. """)
  872. )
  873. await conn.execute(
  874. text("""
  875. INSERT INTO print_queue_new
  876. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  877. manual_start, require_previous_success, auto_off_after, ams_mapping,
  878. status, started_at, completed_at, error_message, created_at
  879. FROM print_queue
  880. """)
  881. )
  882. await conn.execute(text("DROP TABLE print_queue"))
  883. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  884. except (OperationalError, ProgrammingError):
  885. pass # Already applied
  886. # Migration: Add plug_type column to smart_plugs for HA integration
  887. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'")
  888. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  889. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)")
  890. # Migration: Add project_id column to library_folders for linking folders to projects
  891. try:
  892. async with conn.begin_nested():
  893. await conn.execute(
  894. text(
  895. "ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  896. )
  897. )
  898. except (OperationalError, ProgrammingError):
  899. pass # Already applied
  900. # Migration: Add archive_id column to library_folders for linking folders to archives
  901. try:
  902. async with conn.begin_nested():
  903. await conn.execute(
  904. text(
  905. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  906. )
  907. )
  908. except (OperationalError, ProgrammingError):
  909. pass # Already applied
  910. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  911. # PostgreSQL gets the correct schema from create_all(), so skip this
  912. if is_sqlite():
  913. try:
  914. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  915. row = result.fetchone()
  916. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  917. await conn.execute(
  918. text("""
  919. CREATE TABLE smart_plugs_new (
  920. id INTEGER PRIMARY KEY,
  921. name VARCHAR(100) NOT NULL,
  922. ip_address VARCHAR(45),
  923. plug_type VARCHAR(20) DEFAULT 'tasmota',
  924. ha_entity_id VARCHAR(100),
  925. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  926. enabled BOOLEAN NOT NULL DEFAULT 1,
  927. auto_on BOOLEAN NOT NULL DEFAULT 1,
  928. auto_off BOOLEAN NOT NULL DEFAULT 1,
  929. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  930. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  931. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  932. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  933. username VARCHAR(50),
  934. password VARCHAR(100),
  935. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  936. power_alert_high FLOAT,
  937. power_alert_low FLOAT,
  938. power_alert_last_triggered DATETIME,
  939. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  940. schedule_on_time VARCHAR(5),
  941. schedule_off_time VARCHAR(5),
  942. show_in_switchbar BOOLEAN DEFAULT 0,
  943. last_state VARCHAR(10),
  944. last_checked DATETIME,
  945. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  946. auto_off_pending BOOLEAN DEFAULT 0,
  947. auto_off_pending_since DATETIME,
  948. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  949. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  950. )
  951. """)
  952. )
  953. await conn.execute(
  954. text("""
  955. INSERT INTO smart_plugs_new
  956. SELECT id, name, ip_address,
  957. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  958. enabled, auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  959. off_delay_mode, off_delay_minutes, off_temp_threshold,
  960. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  961. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  962. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  963. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  964. FROM smart_plugs
  965. """)
  966. )
  967. await conn.execute(text("DROP TABLE smart_plugs"))
  968. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  969. except (OperationalError, ProgrammingError):
  970. pass # Already applied
  971. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  972. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN plate_id INTEGER")
  973. # Migration: Add print options columns to print_queue
  974. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1")
  975. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0")
  976. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1")
  977. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0")
  978. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0")
  979. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1")
  980. # Migration: Add nozzle offset calibration option (dual-nozzle printers, #1682).
  981. # Postgres rejects `DEFAULT 1` on a BOOLEAN column — use TRUE / 1 per dialect.
  982. if is_sqlite():
  983. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_offset_cali BOOLEAN DEFAULT 1")
  984. else:
  985. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_offset_cali BOOLEAN DEFAULT TRUE")
  986. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  987. # This allows queue items to reference library files directly (archive created at print start)
  988. try:
  989. async with conn.begin_nested():
  990. await conn.execute(
  991. text(
  992. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  993. )
  994. )
  995. except (OperationalError, ProgrammingError):
  996. pass # Already applied
  997. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  998. # PostgreSQL gets the correct schema from create_all(), so skip this
  999. if is_sqlite():
  1000. try:
  1001. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  1002. row = result.fetchone()
  1003. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  1004. await conn.execute(
  1005. text("""
  1006. CREATE TABLE print_queue_new2 (
  1007. id INTEGER PRIMARY KEY,
  1008. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  1009. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  1010. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  1011. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  1012. position INTEGER DEFAULT 0,
  1013. scheduled_time DATETIME,
  1014. manual_start BOOLEAN DEFAULT 0,
  1015. require_previous_success BOOLEAN DEFAULT 0,
  1016. auto_off_after BOOLEAN DEFAULT 0,
  1017. ams_mapping TEXT,
  1018. plate_id INTEGER,
  1019. bed_levelling BOOLEAN DEFAULT 1,
  1020. flow_cali BOOLEAN DEFAULT 0,
  1021. vibration_cali BOOLEAN DEFAULT 1,
  1022. layer_inspect BOOLEAN DEFAULT 0,
  1023. timelapse BOOLEAN DEFAULT 0,
  1024. use_ams BOOLEAN DEFAULT 1,
  1025. status VARCHAR(20) DEFAULT 'pending',
  1026. started_at DATETIME,
  1027. completed_at DATETIME,
  1028. error_message TEXT,
  1029. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  1030. )
  1031. """)
  1032. )
  1033. await conn.execute(
  1034. text("""
  1035. INSERT INTO print_queue_new2
  1036. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  1037. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  1038. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  1039. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  1040. status, started_at, completed_at, error_message, created_at
  1041. FROM print_queue
  1042. """)
  1043. )
  1044. await conn.execute(text("DROP TABLE print_queue"))
  1045. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  1046. except (OperationalError, ProgrammingError):
  1047. pass # Already applied
  1048. # Migration: Add HA energy sensor entity columns to smart_plugs
  1049. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)")
  1050. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)")
  1051. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)")
  1052. # Migration: Create users table for authentication
  1053. try:
  1054. async with conn.begin_nested():
  1055. await conn.execute(
  1056. text("""
  1057. CREATE TABLE IF NOT EXISTS users (
  1058. id INTEGER PRIMARY KEY,
  1059. username VARCHAR(100) NOT NULL UNIQUE,
  1060. password_hash VARCHAR(255) NOT NULL,
  1061. role VARCHAR(20) NOT NULL DEFAULT 'user',
  1062. is_active BOOLEAN NOT NULL DEFAULT 1,
  1063. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1064. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1065. )
  1066. """)
  1067. )
  1068. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  1069. except (OperationalError, ProgrammingError):
  1070. pass # Already applied
  1071. # Migration: Add external camera columns to printers
  1072. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)")
  1073. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)")
  1074. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0")
  1075. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_snapshot_url VARCHAR(500)")
  1076. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  1077. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)")
  1078. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  1079. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)")
  1080. # Migration: Add is_external column to library_files for external cloud files
  1081. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0")
  1082. # Migration: Add project_id column to library_files
  1083. try:
  1084. async with conn.begin_nested():
  1085. await conn.execute(
  1086. text(
  1087. "ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  1088. )
  1089. )
  1090. except (OperationalError, ProgrammingError):
  1091. pass # Already applied
  1092. # Migration: Add is_external column to library_folders for external cloud folders
  1093. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0")
  1094. # Migration: Add external folder settings columns to library_folders
  1095. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0")
  1096. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0")
  1097. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)")
  1098. # Migration: Add plate_detection_enabled column to printers
  1099. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0")
  1100. # Migration: Add plate detection ROI columns to printers
  1101. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL")
  1102. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL")
  1103. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL")
  1104. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL")
  1105. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  1106. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  1107. # SQLite requires table recreation to drop constraints
  1108. # PostgreSQL gets the correct schema from create_all(), so skip this
  1109. if is_sqlite():
  1110. try:
  1111. needs_migration = False
  1112. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  1113. row = result.fetchone()
  1114. table_sql = (row[0] or "").upper() if row else ""
  1115. if "PRINTER_ID" in table_sql and "UNIQUE" in table_sql:
  1116. import re
  1117. if re.search(r'"?PRINTER_ID"?\s+\w+\s+UNIQUE', table_sql) or re.search(
  1118. r'UNIQUE\s*\([^)]*"?PRINTER_ID"?', table_sql
  1119. ):
  1120. needs_migration = True
  1121. idx_result = await conn.execute(
  1122. text("SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='smart_plugs' AND sql IS NOT NULL")
  1123. )
  1124. for idx_row in idx_result.fetchall():
  1125. idx_sql = (idx_row[0] or "").upper()
  1126. if "UNIQUE" in idx_sql and "PRINTER_ID" in idx_sql:
  1127. needs_migration = True
  1128. break
  1129. if needs_migration:
  1130. # Create new table without UNIQUE constraint on printer_id
  1131. await conn.execute(
  1132. text("""
  1133. CREATE TABLE smart_plugs_temp (
  1134. id INTEGER PRIMARY KEY,
  1135. name VARCHAR(100) NOT NULL,
  1136. ip_address VARCHAR(45),
  1137. plug_type VARCHAR(20) DEFAULT 'tasmota',
  1138. ha_entity_id VARCHAR(100),
  1139. ha_power_entity VARCHAR(100),
  1140. ha_energy_today_entity VARCHAR(100),
  1141. ha_energy_total_entity VARCHAR(100),
  1142. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1143. enabled BOOLEAN NOT NULL DEFAULT 1,
  1144. auto_on BOOLEAN NOT NULL DEFAULT 1,
  1145. auto_off BOOLEAN NOT NULL DEFAULT 1,
  1146. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  1147. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  1148. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  1149. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  1150. username VARCHAR(50),
  1151. password VARCHAR(100),
  1152. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  1153. power_alert_high FLOAT,
  1154. power_alert_low FLOAT,
  1155. power_alert_last_triggered DATETIME,
  1156. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  1157. schedule_on_time VARCHAR(5),
  1158. schedule_off_time VARCHAR(5),
  1159. show_in_switchbar BOOLEAN DEFAULT 0,
  1160. last_state VARCHAR(10),
  1161. last_checked DATETIME,
  1162. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  1163. auto_off_pending BOOLEAN DEFAULT 0,
  1164. auto_off_pending_since DATETIME,
  1165. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  1166. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  1167. )
  1168. """)
  1169. )
  1170. # Copy data
  1171. await conn.execute(
  1172. text("""
  1173. INSERT INTO smart_plugs_temp
  1174. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  1175. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  1176. auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  1177. off_delay_mode, off_delay_minutes, off_temp_threshold,
  1178. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  1179. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  1180. show_in_switchbar, last_state, last_checked, auto_off_executed,
  1181. auto_off_pending, auto_off_pending_since, created_at, updated_at
  1182. FROM smart_plugs
  1183. """)
  1184. )
  1185. # Drop old table and rename new one
  1186. await conn.execute(text("DROP TABLE smart_plugs"))
  1187. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  1188. except (OperationalError, ProgrammingError):
  1189. pass # Already applied
  1190. # Migration: Add show_on_printer_card column to smart_plugs
  1191. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1")
  1192. # Migration: Add MQTT smart plug fields (legacy)
  1193. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)")
  1194. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)")
  1195. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)")
  1196. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)")
  1197. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0")
  1198. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  1199. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)")
  1200. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0")
  1201. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)")
  1202. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0")
  1203. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)")
  1204. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)")
  1205. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  1206. try:
  1207. async with conn.begin_nested():
  1208. await conn.execute(
  1209. text("""
  1210. UPDATE smart_plugs
  1211. SET mqtt_power_topic = mqtt_topic,
  1212. mqtt_power_multiplier = mqtt_multiplier
  1213. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  1214. """)
  1215. )
  1216. except (OperationalError, ProgrammingError):
  1217. pass # Already applied
  1218. # Migration: Create groups table for permission-based access control
  1219. try:
  1220. async with conn.begin_nested():
  1221. await conn.execute(
  1222. text("""
  1223. CREATE TABLE IF NOT EXISTS groups (
  1224. id INTEGER PRIMARY KEY,
  1225. name VARCHAR(100) NOT NULL UNIQUE,
  1226. description VARCHAR(500),
  1227. permissions JSON,
  1228. is_system BOOLEAN NOT NULL DEFAULT 0,
  1229. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1230. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1231. )
  1232. """)
  1233. )
  1234. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  1235. except (OperationalError, ProgrammingError):
  1236. pass # Already applied
  1237. # Migration: Create user_groups association table
  1238. try:
  1239. async with conn.begin_nested():
  1240. await conn.execute(
  1241. text("""
  1242. CREATE TABLE IF NOT EXISTS user_groups (
  1243. user_id INTEGER NOT NULL,
  1244. group_id INTEGER NOT NULL,
  1245. PRIMARY KEY (user_id, group_id),
  1246. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  1247. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  1248. )
  1249. """)
  1250. )
  1251. except (OperationalError, ProgrammingError):
  1252. pass # Already applied
  1253. # Migration: Add model-based queue assignment columns to print_queue
  1254. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)")
  1255. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT")
  1256. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT")
  1257. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  1258. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1")
  1259. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  1260. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0")
  1261. # Migration: Add queue notification event columns to notification_providers
  1262. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0")
  1263. try:
  1264. async with conn.begin_nested():
  1265. await conn.execute(
  1266. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  1267. )
  1268. except (OperationalError, ProgrammingError):
  1269. pass # Already applied
  1270. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0")
  1271. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1")
  1272. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1")
  1273. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1")
  1274. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0")
  1275. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  1276. try:
  1277. async with conn.begin_nested():
  1278. await conn.execute(
  1279. text(
  1280. "ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  1281. )
  1282. )
  1283. except (OperationalError, ProgrammingError):
  1284. pass # Already applied
  1285. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  1286. try:
  1287. async with conn.begin_nested():
  1288. await conn.execute(
  1289. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1290. )
  1291. except (OperationalError, ProgrammingError):
  1292. pass # Already applied
  1293. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  1294. try:
  1295. async with conn.begin_nested():
  1296. await conn.execute(
  1297. text(
  1298. "ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  1299. )
  1300. )
  1301. except (OperationalError, ProgrammingError):
  1302. pass # Already applied
  1303. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  1304. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)")
  1305. # Migration: Convert absolute paths to relative paths in library_files table
  1306. # This ensures backup/restore portability across different installations
  1307. try:
  1308. async with conn.begin_nested():
  1309. base_dir_str = str(settings.base_dir)
  1310. # Ensure we have a trailing slash for clean replacement
  1311. if not base_dir_str.endswith("/"):
  1312. base_dir_str += "/"
  1313. # Update file_path - remove base_dir prefix from absolute paths
  1314. await conn.execute(
  1315. text("""
  1316. UPDATE library_files
  1317. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  1318. WHERE file_path LIKE :pattern
  1319. """),
  1320. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1321. )
  1322. # Update thumbnail_path - remove base_dir prefix from absolute paths
  1323. await conn.execute(
  1324. text("""
  1325. UPDATE library_files
  1326. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  1327. WHERE thumbnail_path LIKE :pattern
  1328. """),
  1329. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1330. )
  1331. except (OperationalError, ProgrammingError):
  1332. pass # Already applied
  1333. # Create active_print_spoolman table for Spoolman per-filament tracking
  1334. await _safe_execute(
  1335. conn,
  1336. """
  1337. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1338. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1339. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1340. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1341. filament_usage TEXT NOT NULL,
  1342. ams_trays TEXT NOT NULL,
  1343. slot_to_tray TEXT,
  1344. layer_usage TEXT,
  1345. filament_properties TEXT,
  1346. UNIQUE(printer_id, archive_id)
  1347. )
  1348. """
  1349. if is_sqlite()
  1350. else """
  1351. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1352. id SERIAL PRIMARY KEY,
  1353. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1354. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1355. filament_usage TEXT NOT NULL,
  1356. ams_trays TEXT NOT NULL,
  1357. slot_to_tray TEXT,
  1358. layer_usage TEXT,
  1359. filament_properties TEXT,
  1360. UNIQUE(printer_id, archive_id)
  1361. )
  1362. """,
  1363. )
  1364. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1365. try:
  1366. async with conn.begin_nested():
  1367. await conn.execute(
  1368. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1369. )
  1370. except (OperationalError, ProgrammingError):
  1371. pass # Already applied
  1372. # Migration: Add email column to users for Advanced Auth (PR #322)
  1373. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN email VARCHAR(255)")
  1374. # Migration: Add inventory spool tracking columns
  1375. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN added_full BOOLEAN")
  1376. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_used DATETIME")
  1377. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN encode_time DATETIME")
  1378. # Migration: Add RFID tag matching columns to spool
  1379. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)")
  1380. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)")
  1381. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)")
  1382. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)")
  1383. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  1384. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER")
  1385. # Migration: Create spool_usage_history table for filament consumption tracking
  1386. await _safe_execute(
  1387. conn,
  1388. """
  1389. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1390. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1391. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1392. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1393. print_name VARCHAR(500),
  1394. weight_used REAL NOT NULL DEFAULT 0,
  1395. percent_used INTEGER NOT NULL DEFAULT 0,
  1396. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1397. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1398. )
  1399. """
  1400. if is_sqlite()
  1401. else """
  1402. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1403. id SERIAL PRIMARY KEY,
  1404. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1405. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1406. print_name VARCHAR(500),
  1407. weight_used REAL NOT NULL DEFAULT 0,
  1408. percent_used INTEGER NOT NULL DEFAULT 0,
  1409. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1410. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  1411. )
  1412. """,
  1413. )
  1414. # Migration: Add open_in_new_tab column to external_links
  1415. await _safe_execute(conn, "ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0")
  1416. # Migration: Add bed cooled notification column to notification_providers
  1417. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0")
  1418. # Migration: Add first layer complete notification column to notification_providers
  1419. try:
  1420. async with conn.begin_nested():
  1421. await conn.execute(
  1422. text("ALTER TABLE notification_providers ADD COLUMN on_first_layer_complete BOOLEAN DEFAULT 0")
  1423. )
  1424. except (OperationalError, ProgrammingError):
  1425. pass # Already applied
  1426. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  1427. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0")
  1428. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  1429. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER")
  1430. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME")
  1431. # Migration: Add cost tracking fields to spool table
  1432. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN cost_per_kg REAL")
  1433. # Migration: Per-spool category + low-stock threshold override (#729). Both
  1434. # nullable — NULL category leaves the spool uncategorised, NULL threshold
  1435. # falls back to the global low_stock_threshold setting.
  1436. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN category VARCHAR(50)")
  1437. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN low_stock_threshold_pct INTEGER")
  1438. # Migration: Add user-editable storage location to spool table
  1439. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN storage_location VARCHAR(255)")
  1440. # Migration: Add weight_used_baseline anchor for the resettable "Total
  1441. # Consumed" stat (#1390). Existing spools default to 0 (no baseline),
  1442. # so the counter starts unaffected; pressing "Reset usage to 0" now
  1443. # stamps baseline = weight_used without touching remaining.
  1444. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_used_baseline REAL DEFAULT 0")
  1445. # Migration: Widen tag_uid column from VARCHAR(16) to VARCHAR(32) to accommodate 7-byte NFC
  1446. # UIDs (14 hex chars) in addition to 8-byte Bambu Lab UIDs (16 hex chars).
  1447. # ALTER COLUMN ... TYPE is PostgreSQL-only syntax; SQLite ignores VARCHAR sizes so no-op there.
  1448. if not is_sqlite():
  1449. await _safe_execute(conn, "ALTER TABLE spool ALTER COLUMN tag_uid TYPE VARCHAR(32)")
  1450. # Migration: enhanced filament colour handling (#1154). `extra_colors` is
  1451. # a comma-separated list of 6- or 8-char hex tokens (no `#`) for multi-
  1452. # colour gradients; `effect_type` is one of {sparkle, wood, marble, glow,
  1453. # matte} as a visual rendering hint. Both nullable — NULL keeps the
  1454. # current single-rgba/no-effect behaviour.
  1455. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN extra_colors VARCHAR(255)")
  1456. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN effect_type VARCHAR(20)")
  1457. # Migration: Add cost field to spool_usage_history table
  1458. await _safe_execute(conn, "ALTER TABLE spool_usage_history ADD COLUMN cost REAL")
  1459. # Migration: Add archive_id field to spool_usage_history table
  1460. try:
  1461. async with conn.begin_nested():
  1462. await conn.execute(
  1463. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  1464. )
  1465. except (OperationalError, ProgrammingError):
  1466. pass # Already applied
  1467. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  1468. try:
  1469. async with conn.begin_nested():
  1470. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  1471. count = result.scalar() or 0
  1472. if count == 0:
  1473. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  1474. row = result.fetchone()
  1475. if row:
  1476. # Old settings exist — migrate to first virtual printer row
  1477. old_enabled = row[0] == "true" if row[0] else False
  1478. result = await conn.execute(
  1479. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  1480. )
  1481. row = result.fetchone()
  1482. old_access_code = row[0] if row else None
  1483. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  1484. row = result.fetchone()
  1485. old_mode = row[0] if row else "archive"
  1486. # Translate to canonical wire values (#1429 mode-label
  1487. # discrepancy): legacy `immediate` → `archive`, legacy
  1488. # `print_queue` → `queue`. The historical `queue` alias
  1489. # for `review` predates the canonical rename and is
  1490. # preserved (existing user intent was "pending review").
  1491. if old_mode == "queue":
  1492. old_mode = "review"
  1493. elif old_mode == "immediate":
  1494. old_mode = "archive"
  1495. elif old_mode == "print_queue":
  1496. old_mode = "queue"
  1497. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  1498. row = result.fetchone()
  1499. old_model = row[0] if row else "BL-P001"
  1500. result = await conn.execute(
  1501. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1502. )
  1503. row = result.fetchone()
  1504. old_target_id = int(row[0]) if row and row[0] else None
  1505. result = await conn.execute(
  1506. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  1507. )
  1508. row = result.fetchone()
  1509. old_remote_iface = row[0] if row else None
  1510. await conn.execute(
  1511. text("""
  1512. INSERT INTO virtual_printers
  1513. (name, enabled, mode, model, access_code, target_printer_id,
  1514. bind_ip, remote_interface_ip, serial_suffix, position)
  1515. VALUES
  1516. (:name, :enabled, :mode, :model, :access_code, :target_id,
  1517. NULL, :remote_iface, '391800001', 0)
  1518. """),
  1519. {
  1520. "name": "Bambuddy",
  1521. "enabled": old_enabled,
  1522. "mode": old_mode or "archive",
  1523. "model": old_model,
  1524. "access_code": old_access_code,
  1525. "target_id": old_target_id,
  1526. "remote_iface": old_remote_iface,
  1527. },
  1528. )
  1529. except (OperationalError, ProgrammingError, IntegrityError):
  1530. pass # Table may not exist yet on first run, or columns have different constraints
  1531. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  1532. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT")
  1533. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  1534. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)")
  1535. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)")
  1536. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100")
  1537. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0")
  1538. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0")
  1539. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME")
  1540. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  1541. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT")
  1542. # Migration: Add OTA update tracking columns to spoolbuddy_devices
  1543. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_status VARCHAR(20)")
  1544. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_message VARCHAR(255)")
  1545. # Migration: Persist SpoolBuddy backend URL and queued system payload
  1546. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN backend_url VARCHAR(255)")
  1547. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_system_payload TEXT")
  1548. # Migration: Add system_stats JSON blob column to spoolbuddy_devices
  1549. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN system_stats TEXT")
  1550. # Migration: Add SSH host key for TOFU verification (H1 security fix)
  1551. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN ssh_host_key VARCHAR(500)")
  1552. # Migration: Widen ssh_host_key from VARCHAR(500) to TEXT — RSA-3072+ host keys
  1553. # in OpenSSH format exceed 500 chars (RSA-4096 ~720 chars). PostgreSQL enforces
  1554. # the limit and rejects the UPDATE; SQLite ignores VARCHAR length so no-op there.
  1555. if not is_sqlite():
  1556. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ALTER COLUMN ssh_host_key TYPE TEXT")
  1557. # Migration: Convert ams_labels table from (printer_id, ams_id) key to ams_serial_number key
  1558. # Labels are now keyed by AMS serial number so they persist when the AMS is moved to another printer.
  1559. # PostgreSQL gets the correct schema from create_all(), so skip this
  1560. if is_sqlite():
  1561. try:
  1562. await conn.execute(text("DROP TABLE IF EXISTS ams_labels_new"))
  1563. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='ams_labels'"))
  1564. row = result.fetchone()
  1565. if row and "printer_id" in (row[0] or ""):
  1566. # Old schema: rebuild the table with ams_serial_number as the unique key.
  1567. # Existing rows get a synthetic serial "p{printer_id}a{ams_id}" so data is preserved.
  1568. await conn.execute(
  1569. text("""
  1570. CREATE TABLE ams_labels_new (
  1571. id INTEGER PRIMARY KEY,
  1572. ams_serial_number VARCHAR(50) NOT NULL,
  1573. ams_id INTEGER,
  1574. label VARCHAR(100) NOT NULL,
  1575. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1576. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1577. CONSTRAINT uq_ams_label_serial UNIQUE (ams_serial_number)
  1578. )
  1579. """)
  1580. )
  1581. await conn.execute(
  1582. text("""
  1583. INSERT INTO ams_labels_new (id, ams_serial_number, ams_id, label, created_at, updated_at)
  1584. SELECT id,
  1585. 'p' || CAST(printer_id AS TEXT) || 'a' || CAST(ams_id AS TEXT),
  1586. ams_id,
  1587. label,
  1588. created_at,
  1589. updated_at
  1590. FROM ams_labels
  1591. """)
  1592. )
  1593. await conn.execute(text("DROP TABLE ams_labels"))
  1594. await conn.execute(text("ALTER TABLE ams_labels_new RENAME TO ams_labels"))
  1595. except (OperationalError, ProgrammingError):
  1596. pass # Already migrated or table does not exist yet
  1597. # Migration: Add auto_dispatch column to virtual_printers
  1598. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN auto_dispatch BOOLEAN DEFAULT 1")
  1599. # Migration: Fix VP model codes — convert legacy SSDP codes and display names to correct SSDP codes
  1600. # Legacy codes (from multi-VP refactor) and display names (from proxy auto-inherit)
  1601. vp_model_fixes = {
  1602. "3DPrinter-X1-Carbon": "BL-P001",
  1603. "3DPrinter-X1": "BL-P002",
  1604. "X1C": "BL-P001",
  1605. "X1": "BL-P002",
  1606. "X1E": "C13",
  1607. "X2D": "N6",
  1608. "P1P": "C11",
  1609. "P1S": "C12",
  1610. "P2S": "N7",
  1611. "A1": "N2S",
  1612. "A1 Mini": "N1",
  1613. "H2D": "O1D",
  1614. "H2C": "O1C",
  1615. "H2S": "O1S",
  1616. }
  1617. for old_val, new_val in vp_model_fixes.items():
  1618. await conn.execute(
  1619. text("UPDATE virtual_printers SET model = :new WHERE model = :old"),
  1620. {"old": old_val, "new": new_val},
  1621. )
  1622. await conn.execute(
  1623. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_model' AND value = :old"),
  1624. {"old": old_val, "new": new_val},
  1625. )
  1626. # Migration: Rename VP mode wire values to match the user-facing labels
  1627. # (#1429 follow-up). The UI button "Archive" had always saved `immediate`
  1628. # and "Queue" had always saved `print_queue` — a mismatch that showed up
  1629. # confusingly in every support bundle. The button labels stay; the wire
  1630. # value is what changes. Idempotent: re-running the UPDATE on canonical
  1631. # values is a no-op. SQLite and Postgres both accept this statement
  1632. # unchanged (string literal comparison, no driver-specific syntax).
  1633. vp_mode_renames = [("immediate", "archive"), ("print_queue", "queue")]
  1634. for old_val, new_val in vp_mode_renames:
  1635. await conn.execute(
  1636. text("UPDATE virtual_printers SET mode = :new WHERE mode = :old"),
  1637. {"old": old_val, "new": new_val},
  1638. )
  1639. await conn.execute(
  1640. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_mode' AND value = :old"),
  1641. {"old": old_val, "new": new_val},
  1642. )
  1643. # Migration: Auto-sync VP access codes from their target printer.
  1644. # Non-proxy VPs with a target printer (the live-mirror bridge) forward the
  1645. # slicer's MQTT/RTSPS auth bytes through to the real printer, so the VP's
  1646. # access code MUST equal the target's — earlier UIs let them diverge,
  1647. # producing a VP that the slicer could bind but whose bridge silently
  1648. # failed to authenticate against the real printer. The route layer now
  1649. # auto-inherits on every create/update; this backfill corrects any rows
  1650. # that pre-date that change. Idempotent (re-running on synced rows is a
  1651. # no-op because the WHERE clause excludes them). SQLite and Postgres both
  1652. # accept correlated subqueries in UPDATE — no driver-specific syntax.
  1653. mismatch_result = await conn.execute(
  1654. text(
  1655. "SELECT vp.id AS vp_id, vp.name AS vp_name, p.name AS target_name "
  1656. "FROM virtual_printers vp "
  1657. "JOIN printers p ON vp.target_printer_id = p.id "
  1658. "WHERE vp.mode != 'proxy' "
  1659. " AND (vp.access_code IS NULL OR vp.access_code != p.access_code)"
  1660. )
  1661. )
  1662. for row in mismatch_result.fetchall():
  1663. logger.info(
  1664. "VP %r (id=%d) access code synced from target printer %r",
  1665. row.vp_name,
  1666. row.vp_id,
  1667. row.target_name,
  1668. )
  1669. await conn.execute(
  1670. text(
  1671. "UPDATE virtual_printers "
  1672. "SET access_code = ("
  1673. " SELECT access_code FROM printers WHERE printers.id = virtual_printers.target_printer_id"
  1674. ") "
  1675. "WHERE virtual_printers.target_printer_id IS NOT NULL "
  1676. " AND virtual_printers.mode != 'proxy' "
  1677. " AND (virtual_printers.access_code IS NULL OR virtual_printers.access_code != ("
  1678. " SELECT access_code FROM printers WHERE printers.id = virtual_printers.target_printer_id"
  1679. " ))"
  1680. )
  1681. )
  1682. # Migration: Recover queue items that got stuck in `skipped` because of
  1683. # the cancellation-cascade bug (#1667). Pre-fix, the scheduler's
  1684. # `_check_previous_success` lookback excluded `cancelled` but included
  1685. # `skipped`, so a single user-cancelled print poisoned every downstream
  1686. # item with `require_previous_success=True` indefinitely. The reporter saw
  1687. # 18 items blocked over 3 days from one cancellation.
  1688. #
  1689. # Conservative reversal: ONLY reset rows whose immediate predecessor on
  1690. # the same printer (by completed_at desc, excluding the skipped-bug
  1691. # cascade) was `cancelled`. Skipped items whose true predecessor was a
  1692. # real `failed` or `aborted` print stay skipped — those were legitimate.
  1693. # Genuine failure-skips share the same status + error_message + completed_at
  1694. # fingerprint as bug-skips, so the predecessor check is what distinguishes
  1695. # them. Idempotent (post-reset rows no longer match the WHERE clause).
  1696. #
  1697. # Correlated subquery is portable across SQLite and Postgres. The
  1698. # `error_message` literal matches the exact string the buggy scheduler
  1699. # wrote — narrowing further on intent.
  1700. stuck_skipped_result = await conn.execute(
  1701. text(
  1702. "SELECT pq.id, pq.printer_id "
  1703. "FROM print_queue pq "
  1704. "WHERE pq.status = 'skipped' "
  1705. " AND pq.error_message = 'Previous print failed or was aborted' "
  1706. " AND pq.completed_at IS NOT NULL "
  1707. " AND ("
  1708. " SELECT prev.status FROM print_queue prev "
  1709. " WHERE prev.printer_id = pq.printer_id "
  1710. " AND prev.id != pq.id "
  1711. " AND prev.status IN ('completed', 'failed', 'cancelled', 'aborted') "
  1712. " AND prev.completed_at IS NOT NULL "
  1713. " AND prev.completed_at < pq.completed_at "
  1714. " ORDER BY prev.completed_at DESC LIMIT 1"
  1715. " ) = 'cancelled'"
  1716. )
  1717. )
  1718. stuck_ids = [row.id for row in stuck_skipped_result.fetchall()]
  1719. if stuck_ids:
  1720. logger.info(
  1721. "Queue cancellation-cascade migration (#1667): resetting %d skipped item(s) to pending",
  1722. len(stuck_ids),
  1723. )
  1724. await conn.execute(
  1725. text(
  1726. "UPDATE print_queue "
  1727. "SET status = 'pending', error_message = NULL, completed_at = NULL "
  1728. "WHERE id IN ("
  1729. " SELECT pq.id FROM print_queue pq "
  1730. " WHERE pq.status = 'skipped' "
  1731. " AND pq.error_message = 'Previous print failed or was aborted' "
  1732. " AND pq.completed_at IS NOT NULL "
  1733. " AND ("
  1734. " SELECT prev.status FROM print_queue prev "
  1735. " WHERE prev.printer_id = pq.printer_id "
  1736. " AND prev.id != pq.id "
  1737. " AND prev.status IN ('completed', 'failed', 'cancelled', 'aborted') "
  1738. " AND prev.completed_at IS NOT NULL "
  1739. " AND prev.completed_at < pq.completed_at "
  1740. " ORDER BY prev.completed_at DESC LIMIT 1"
  1741. " ) = 'cancelled'"
  1742. ")"
  1743. )
  1744. )
  1745. # Migration: Unify `LibraryFile.file_type` across ingest paths (#1600).
  1746. # Pre-#1600, only the external-folder scan path stored `gcode.3mf` for
  1747. # sliced outputs — the upload, ZIP-extract, and in-process paths all
  1748. # stripped to the trailing `.3mf` and stored `3mf`, so the same file
  1749. # family was split between two values depending on how it was ingested.
  1750. # Going forward `classify_file_type()` is canonical; this backfill flips
  1751. # existing legacy `3mf` rows whose filename ends in `.gcode.3mf` to the
  1752. # canonical compound name. Idempotent (post-update rows no longer match
  1753. # `file_type = '3mf'`) and dialect-neutral (`LOWER` + `LIKE` work the
  1754. # same under SQLite and Postgres).
  1755. await conn.execute(
  1756. text(
  1757. "UPDATE library_files SET file_type = 'gcode.3mf' "
  1758. "WHERE file_type = '3mf' AND LOWER(filename) LIKE '%.gcode.3mf'"
  1759. )
  1760. )
  1761. # Migration: Add per-user Bambu Cloud credential columns
  1762. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_token VARCHAR(500)")
  1763. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_email VARCHAR(255)")
  1764. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_region VARCHAR(10)")
  1765. # Cleanup: Remove obsolete settings keys that are no longer used
  1766. obsolete_keys = ["slicer_binary_path"]
  1767. for key in obsolete_keys:
  1768. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  1769. # Migration: Create user_email_preferences table for user-specific email notification settings
  1770. try:
  1771. async with conn.begin_nested():
  1772. await conn.execute(
  1773. text("""
  1774. CREATE TABLE IF NOT EXISTS user_email_preferences (
  1775. id INTEGER PRIMARY KEY,
  1776. user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  1777. notify_print_start BOOLEAN NOT NULL DEFAULT 1,
  1778. notify_print_complete BOOLEAN NOT NULL DEFAULT 1,
  1779. notify_print_failed BOOLEAN NOT NULL DEFAULT 1,
  1780. notify_print_stopped BOOLEAN NOT NULL DEFAULT 1,
  1781. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1782. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1783. )
  1784. """)
  1785. )
  1786. await conn.execute(
  1787. text("CREATE INDEX IF NOT EXISTS ix_user_email_preferences_user_id ON user_email_preferences(user_id)")
  1788. )
  1789. except (OperationalError, ProgrammingError):
  1790. pass # Already applied
  1791. # Legacy migration: Add notify_print_stopped column (for any existing partial tables)
  1792. try:
  1793. async with conn.begin_nested():
  1794. await conn.execute(
  1795. text("ALTER TABLE user_email_preferences ADD COLUMN notify_print_stopped BOOLEAN NOT NULL DEFAULT 1")
  1796. )
  1797. except (OperationalError, ProgrammingError):
  1798. pass # Column already exists or table created with full schema
  1799. # Migration: Add camera_rotation column to printers
  1800. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN camera_rotation INTEGER DEFAULT 0")
  1801. # Migration: Add awaiting_plate_clear column to printers (#961)
  1802. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN awaiting_plate_clear BOOLEAN DEFAULT FALSE NOT NULL")
  1803. # Migration: Add REST/Webhook smart plug fields
  1804. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_url VARCHAR(500)")
  1805. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_body TEXT")
  1806. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_url VARCHAR(500)")
  1807. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_body TEXT")
  1808. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_method VARCHAR(10)")
  1809. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_headers TEXT")
  1810. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_url VARCHAR(500)")
  1811. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_path VARCHAR(200)")
  1812. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_on_value VARCHAR(50)")
  1813. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_path VARCHAR(200)")
  1814. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_path VARCHAR(200)")
  1815. # Migration: Add separate REST power/energy URLs and multipliers
  1816. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_url VARCHAR(500)")
  1817. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_multiplier REAL DEFAULT 1.0")
  1818. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_url VARCHAR(500)")
  1819. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_multiplier REAL DEFAULT 1.0")
  1820. # Migration: Add batch_id column to print_queue for batch grouping
  1821. try:
  1822. async with conn.begin_nested():
  1823. await conn.execute(
  1824. text(
  1825. "ALTER TABLE print_queue ADD COLUMN batch_id INTEGER REFERENCES print_batches(id) ON DELETE SET NULL"
  1826. )
  1827. )
  1828. except (OperationalError, ProgrammingError):
  1829. pass
  1830. # Migration: Shortest-job-first scheduling columns on print_queue
  1831. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN print_time_seconds INTEGER")
  1832. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN been_jumped BOOLEAN DEFAULT FALSE NOT NULL")
  1833. # Migration: Auto-print G-code injection (#422)
  1834. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE NOT NULL")
  1835. # Migration: Add backup_spools and backup_archives columns to github_backup_config
  1836. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_spools BOOLEAN DEFAULT 0")
  1837. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_archives BOOLEAN DEFAULT 0")
  1838. # Migration: Widen columns where SQLite allowed data beyond the declared VARCHAR limit
  1839. if not is_sqlite():
  1840. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_hash TYPE VARCHAR(255)")
  1841. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_prefix TYPE VARCHAR(20)")
  1842. await _safe_execute(conn, "ALTER TABLE print_archives ALTER COLUMN filament_color TYPE VARCHAR(200)")
  1843. # Migration: Create GIN index for full-text search on PostgreSQL
  1844. # (SQLite uses FTS5 virtual table instead, set up above)
  1845. if not is_sqlite():
  1846. try:
  1847. await conn.execute(
  1848. text("""
  1849. CREATE INDEX IF NOT EXISTS idx_archives_fulltext
  1850. ON print_archives
  1851. USING GIN (to_tsvector('simple',
  1852. COALESCE(print_name, '') || ' ' ||
  1853. COALESCE(filename, '') || ' ' ||
  1854. COALESCE(tags, '') || ' ' ||
  1855. COALESCE(notes, '') || ' ' ||
  1856. COALESCE(designer, '') || ' ' ||
  1857. COALESCE(filament_type, '')
  1858. ))
  1859. """)
  1860. )
  1861. except (OperationalError, ProgrammingError):
  1862. pass # Already applied
  1863. # Migration: Normalize empty printer_ids [] to NULL (global access) on API keys
  1864. # Previously both None and [] meant "all printers"; now [] means "no printers"
  1865. # PostgreSQL stores printer_ids as JSONB; comparing JSONB to a string literal fails
  1866. # with "operator does not exist: jsonb = unknown" — cast the literal to jsonb explicitly.
  1867. await _migrate_normalize_printer_ids(conn)
  1868. # Migration: Add auth_source column to users for LDAP support (#794)
  1869. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN auth_source VARCHAR(20) DEFAULT 'local' NOT NULL")
  1870. # Migration: Make password_hash nullable for LDAP users (#794)
  1871. # LDAP users have no local password — the column must allow NULL so auto-provisioning
  1872. # doesn't hit a NOT NULL constraint failure on upgraded installs whose users table was
  1873. # originally created before LDAP support landed.
  1874. if is_sqlite():
  1875. # SQLite can't ALTER COLUMN; patch sqlite_master directly via writable_schema.
  1876. # Bump schema_version afterwards so SQLite reloads the table definition from disk —
  1877. # without that bump, the current connection keeps enforcing the old NOT NULL from
  1878. # its cached schema. Safe because row data is untouched and the replace() is a
  1879. # no-op if the constraint has already been removed.
  1880. try:
  1881. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='users'"))
  1882. users_sql = result.scalar()
  1883. if users_sql and "password_hash VARCHAR(255) NOT NULL" in users_sql:
  1884. version_result = await conn.execute(text("PRAGMA schema_version"))
  1885. schema_version = version_result.scalar() or 0
  1886. await conn.execute(text("PRAGMA writable_schema = ON"))
  1887. await conn.execute(
  1888. text(
  1889. "UPDATE sqlite_master "
  1890. "SET sql = replace(sql, 'password_hash VARCHAR(255) NOT NULL', 'password_hash VARCHAR(255)') "
  1891. "WHERE type = 'table' AND name = 'users'"
  1892. )
  1893. )
  1894. await conn.execute(text(f"PRAGMA schema_version = {schema_version + 1}"))
  1895. await conn.execute(text("PRAGMA writable_schema = OFF"))
  1896. except (OperationalError, ProgrammingError) as exc:
  1897. logger.error(
  1898. "Failed to remove NOT NULL from users.password_hash via writable_schema — "
  1899. "OIDC/LDAP user creation will fail on this install: %s",
  1900. exc,
  1901. exc_info=True,
  1902. )
  1903. else:
  1904. await _safe_execute(conn, "ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL")
  1905. # Migration: Add energy_start_kwh to print_archives (#941)
  1906. # Persists the smart plug lifetime counter captured at print start, so per-print
  1907. # energy tracking survives a backend restart mid-print.
  1908. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN energy_start_kwh REAL")
  1909. # Migration: Add subtask_id to print_archives (#972)
  1910. # MQTT-provided task identifier used to resume the same archive row across a
  1911. # backend restart mid-print. Without it, a long print (e.g. 13h) triggers
  1912. # stale-cancel + new-archive, losing started_at continuity.
  1913. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN subtask_id VARCHAR(64)")
  1914. # Migration: Add bed_type to print_archives (#1253)
  1915. # Build plate type extracted from 3MF (curr_bed_type), drives the bed icon
  1916. # rendered on archive cards.
  1917. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN bed_type VARCHAR(64)")
  1918. # Migration: Add deleted_at to print_archives (#1343)
  1919. # Soft-delete sentinel so deleting an archive entry from the UI no longer
  1920. # wipes its filament / time / cost contribution from Quick Stats. Listings
  1921. # hide rows where deleted_at IS NOT NULL; the stats endpoint counts them all.
  1922. # DATETIME on SQLite, TIMESTAMP on PostgreSQL (PG doesn't accept DATETIME on
  1923. # ALTER TABLE the same way it tolerates it inside CREATE TABLE).
  1924. _deleted_at_type = "DATETIME" if is_sqlite() else "TIMESTAMP"
  1925. await _safe_execute(conn, f"ALTER TABLE print_archives ADD COLUMN deleted_at {_deleted_at_type}")
  1926. await _safe_execute(
  1927. conn,
  1928. "CREATE INDEX IF NOT EXISTS ix_print_archives_deleted_at ON print_archives (deleted_at)",
  1929. )
  1930. # Migration: Add bambuddy_forced_timelapse to print_archives (#1397)
  1931. # Tracks prints where Bambuddy forced the firmware to record a timelapse
  1932. # so the finish-photo extractor could pull the post-park-pre-drop frame.
  1933. # The cleanup path uses this to delete the timelapse both locally and on
  1934. # the printer's SD after extraction — the user didn't opt in to a
  1935. # timelapse recording. Postgres rejects `DEFAULT 0` for BOOLEAN; SQLite
  1936. # accepts both 0/FALSE — branch the literal.
  1937. _bool_false_literal = "0" if is_sqlite() else "FALSE"
  1938. await _safe_execute(
  1939. conn,
  1940. f"ALTER TABLE print_archives ADD COLUMN bambuddy_forced_timelapse BOOLEAN DEFAULT {_bool_false_literal}",
  1941. )
  1942. # Migration: Create smart_plug_energy_snapshots table (#941)
  1943. # Hourly snapshots of each plug's lifetime counter, so date-range queries in
  1944. # "total consumption" energy mode can compute (last - first) deltas.
  1945. await _safe_execute(
  1946. conn,
  1947. """
  1948. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1949. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1950. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1951. recorded_at DATETIME NOT NULL,
  1952. lifetime_kwh REAL NOT NULL
  1953. )
  1954. """
  1955. if is_sqlite()
  1956. else """
  1957. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1958. id SERIAL PRIMARY KEY,
  1959. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1960. recorded_at TIMESTAMP NOT NULL,
  1961. lifetime_kwh REAL NOT NULL
  1962. )
  1963. """,
  1964. )
  1965. await _safe_execute(
  1966. conn,
  1967. "CREATE INDEX IF NOT EXISTS ix_plug_energy_snapshots_plug_time "
  1968. "ON smart_plug_energy_snapshots(plug_id, recorded_at)",
  1969. )
  1970. # Migration: Add PKCE code_verifier column to auth_ephemeral_tokens
  1971. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN code_verifier VARCHAR(128)")
  1972. # Migration: Add TOTP replay-protection counter to user_totp
  1973. await _safe_execute(conn, "ALTER TABLE user_totp ADD COLUMN last_totp_counter BIGINT")
  1974. # Migration: Add challenge_id for pre-auth token client binding (HttpOnly cookie)
  1975. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN challenge_id VARCHAR(128)")
  1976. # Migration: Add auto_link_existing_accounts column to oidc_providers (M-4)
  1977. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  1978. if is_sqlite():
  1979. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT 0")
  1980. else:
  1981. await _safe_execute(
  1982. conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT false"
  1983. )
  1984. # Migration: Azure Entra ID support — configurable email claim and verification requirement
  1985. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN email_claim VARCHAR(64) DEFAULT 'email'")
  1986. # Postgres rejects `DEFAULT 1` for BOOLEAN columns.
  1987. if is_sqlite():
  1988. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT 1")
  1989. else:
  1990. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT true")
  1991. # SEC-1 backfill: reset auto_link only for Fall B (email_claim='email' + require_email_verified=False).
  1992. # Fall C (custom claim) is now allowed to use auto_link — do NOT reset those rows.
  1993. # Runs BEFORE the CHECK constraint below so Fall B rows self-heal rather than failing
  1994. # PostgreSQL's "check constraint is violated by some row" on ADD CONSTRAINT.
  1995. # On fresh installs the column defaults guarantee this UPDATE matches zero rows.
  1996. # TRUE/FALSE literals are accepted by both SQLite (≥ 3.23) and PostgreSQL — no dialect branch needed.
  1997. try:
  1998. async with conn.begin_nested():
  1999. await conn.execute(
  2000. text(
  2001. "UPDATE oidc_providers SET auto_link_existing_accounts = FALSE "
  2002. "WHERE auto_link_existing_accounts = TRUE "
  2003. "AND email_claim = 'email' AND require_email_verified = FALSE"
  2004. )
  2005. )
  2006. except Exception as exc:
  2007. logger.error(
  2008. "SEC-1 safety backfill FAILED — auto_link_existing_accounts may remain enabled "
  2009. "on providers with unsafe email settings: %s",
  2010. exc,
  2011. exc_info=True,
  2012. )
  2013. raise
  2014. # SEC-1: Add DB-level CHECK constraint for existing PostgreSQL installs.
  2015. # SQLite does not support ALTER TABLE ADD CONSTRAINT — handled by __table_args__ at creation.
  2016. # Runs AFTER the backfill so Fall B rows don't fail constraint validation.
  2017. if not is_sqlite():
  2018. try:
  2019. async with conn.begin_nested():
  2020. await conn.execute(
  2021. text(
  2022. "ALTER TABLE oidc_providers ADD CONSTRAINT ck_auto_link_requires_verified_email_claim "
  2023. "CHECK (auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE)"
  2024. )
  2025. )
  2026. except (OperationalError, ProgrammingError) as exc:
  2027. msg = str(exc).lower()
  2028. if "already exists" not in msg:
  2029. logger.error(
  2030. "Security constraint migration FAILED — auto_link safety constraint may not be enforced: %s",
  2031. exc,
  2032. exc_info=True,
  2033. )
  2034. raise
  2035. # Migration: Update auto_link CHECK constraint formula (existing installs).
  2036. # Existing PostgreSQL installs that ran the ADD CONSTRAINT above with the old formula
  2037. # (or a previous version of this code) need an explicit DROP + ADD to update it.
  2038. # For SQLite, the table is recreated with the new constraint formula if the old formula
  2039. # is still present in sqlite_master (SQLite cannot ALTER TABLE DROP/ADD CONSTRAINT).
  2040. await _migrate_update_auto_link_constraint(conn)
  2041. # Migration: Add default_group_id to oidc_providers.
  2042. # Must run AFTER _migrate_update_auto_link_constraint to avoid being dropped during
  2043. # the SQLite table recreation that function performs on stale-formula databases.
  2044. await _safe_execute(
  2045. conn,
  2046. "ALTER TABLE oidc_providers ADD COLUMN default_group_id INTEGER REFERENCES groups(id) ON DELETE SET NULL",
  2047. )
  2048. # Migration: Add cached-icon columns to oidc_providers (#1333).
  2049. # SPA's strict CSP (img-src 'self' data: blob:) blocks hotlinking external
  2050. # icon hosts, so we proxy them: admin sets icon_url, backend fetches and
  2051. # caches the bytes here, the SPA renders <img src="/api/v1/auth/oidc/providers/{id}/icon">.
  2052. # Must run AFTER _migrate_update_auto_link_constraint for the same reason as
  2053. # default_group_id above (SQLite table recreation drops unknown columns).
  2054. # Dialect-conditional type: BLOB on SQLite, BYTEA on PostgreSQL.
  2055. _blob_type = "BLOB" if is_sqlite() else "BYTEA"
  2056. await _safe_execute(conn, f"ALTER TABLE oidc_providers ADD COLUMN icon_data {_blob_type}")
  2057. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN icon_content_type VARCHAR(20)")
  2058. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN icon_etag VARCHAR(64)")
  2059. # PostgreSQL-only: enforce the all-or-nothing triplet at the DB layer.
  2060. # SQLite cannot ADD CONSTRAINT to an existing table — fresh SQLite
  2061. # installs get the CHECK via metadata.create_all (model __table_args__);
  2062. # stale SQLite installs rely on the application layer, same trade-off
  2063. # as the default_group_id FK ON DELETE SET NULL above.
  2064. if not is_sqlite():
  2065. await _safe_execute(
  2066. conn,
  2067. "ALTER TABLE oidc_providers ADD CONSTRAINT ck_oidc_icon_triplet_co_null "
  2068. "CHECK ((icon_data IS NULL) = (icon_content_type IS NULL) "
  2069. "AND (icon_content_type IS NULL) = (icon_etag IS NULL))",
  2070. )
  2071. # Migration: Add password_changed_at to users (M-R7-B)
  2072. # Tracks the last time a user's password was changed/reset. JWTs whose iat
  2073. # predates this timestamp are rejected in all six auth validation paths.
  2074. # R4 fix: TIMESTAMP is accepted by both SQLite and PostgreSQL; DATETIME
  2075. # is rejected by Postgres ("type 'datetime' does not exist"), which made
  2076. # _safe_execute swallow the error and leave existing Postgres installs
  2077. # without the column — causing UndefinedColumnError on every User query.
  2078. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP")
  2079. # Migration: Back-fill password_changed_at = created_at for existing users (I2).
  2080. # Users who never changed their password would have NULL here, meaning old
  2081. # tokens could never be invalidated via the freshness check. Setting it to
  2082. # created_at is conservative: any token issued before the account was created
  2083. # is always invalid, so this is a safe lower bound.
  2084. async with conn.begin_nested():
  2085. await conn.execute(text("UPDATE users SET password_changed_at = created_at WHERE password_changed_at IS NULL"))
  2086. # Migration: Provenance columns on library_files for MakerWorld imports.
  2087. # source_url is indexed so "already imported" dedupe lookups stay O(log N)
  2088. # as the library grows.
  2089. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_type VARCHAR(32)")
  2090. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_url VARCHAR(512)")
  2091. await _safe_execute(
  2092. conn,
  2093. "CREATE INDEX IF NOT EXISTS ix_library_files_source_url ON library_files(source_url)",
  2094. )
  2095. # Migration: Cache metadata title on pending uploads (#1152 follow-up).
  2096. # Without this column the review card always shows the FTP filename while
  2097. # the eventual archive's print_name comes from the 3MF metadata title,
  2098. # creating a confusing review→archive name mismatch. Captured at upload
  2099. # time so /pending-uploads/ list calls don't have to reopen each 3MF.
  2100. await _safe_execute(
  2101. conn,
  2102. "ALTER TABLE pending_uploads ADD COLUMN metadata_print_name VARCHAR(255)",
  2103. )
  2104. # Migration: Per-user API key ownership + cloud-access scope (#1182).
  2105. # user_id is nullable so legacy keys (created before #1182) survive the
  2106. # migration; cloud routes reject calls from keys without an owner so the
  2107. # operator is forced to recreate them. ON DELETE CASCADE so deleting a user
  2108. # takes their keys with them — orphan keys must never authenticate.
  2109. # SQLite ignores REFERENCES on ADD COLUMN (not enforced but not an error);
  2110. # PostgreSQL enforces the FK from this point forward. Indexed for the
  2111. # auth-gate's owner→keys lookup that runs on every API-keyed request.
  2112. await _safe_execute(
  2113. conn,
  2114. "ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE CASCADE",
  2115. )
  2116. await _safe_execute(
  2117. conn,
  2118. "CREATE INDEX IF NOT EXISTS ix_api_keys_user_id ON api_keys(user_id)",
  2119. )
  2120. # ``DEFAULT 0`` works on SQLite (boolean is just integer-coerced) but
  2121. # asyncpg's strict type-check rejects it: "column is of type boolean but
  2122. # default expression is of type integer". Use ``DEFAULT FALSE`` so both
  2123. # dialects accept the same statement — same pattern as the print_queue
  2124. # gcode_injection migration above.
  2125. await _safe_execute(
  2126. conn,
  2127. "ALTER TABLE api_keys ADD COLUMN can_access_cloud BOOLEAN DEFAULT FALSE",
  2128. )
  2129. # Narrowly-scoped settings-write toggle for the dynamic-tariff push case
  2130. # documented in wiki/features/energy.md (#1356). Defaults FALSE so existing
  2131. # keys never silently gain settings-write capability on upgrade.
  2132. await _safe_execute(
  2133. conn,
  2134. "ALTER TABLE api_keys ADD COLUMN can_update_energy_cost BOOLEAN DEFAULT FALSE",
  2135. )
  2136. # GHSA-r2qv-8222-hqg3 (CVE-2026-pending, CVSS 9.9): split file-management out
  2137. # of the implicit "any API key" grant into an explicit scope flag. The
  2138. # allowlist-based ``_check_apikey_permissions`` (see ``core/auth.py``) routes
  2139. # LIBRARY_UPLOAD / LIBRARY_UPDATE_OWN / LIBRARY_DELETE_OWN / MAKERWORLD_IMPORT
  2140. # through this flag. DEFAULT TRUE matches the existing "queue + read" trust
  2141. # baseline; backfill mirrors can_queue so a key the user previously created as
  2142. # "queue-only" retains the file-upload step its queue workflow already used,
  2143. # while a hardened "read-only" key (can_queue=False) does not silently gain a
  2144. # new write capability on upgrade. Backfill is gated on column non-existence
  2145. # so user-edited values are never overwritten on subsequent startup.
  2146. column_existed = await _api_keys_column_exists(conn, "can_manage_library")
  2147. await _safe_execute(
  2148. conn,
  2149. "ALTER TABLE api_keys ADD COLUMN can_manage_library BOOLEAN DEFAULT TRUE",
  2150. )
  2151. if not column_existed:
  2152. async with conn.begin_nested():
  2153. await conn.execute(text("UPDATE api_keys SET can_manage_library = can_queue"))
  2154. # Same shape: SpoolBuddy NFC/scale/system endpoints plus manual inventory
  2155. # writes split out of the implicit "any API key" grant. Backfill mirrors
  2156. # ``can_queue`` so the bundled SpoolBuddy kiosk key (created via the CLI
  2157. # with can_queue=False) does NOT silently gain inventory writes — but
  2158. # the CLI override sets the new flag True explicitly, since the kiosk
  2159. # itself is the legitimate writer (see ``cli.py``).
  2160. column_existed = await _api_keys_column_exists(conn, "can_manage_inventory")
  2161. await _safe_execute(
  2162. conn,
  2163. "ALTER TABLE api_keys ADD COLUMN can_manage_inventory BOOLEAN DEFAULT TRUE",
  2164. )
  2165. if not column_existed:
  2166. async with conn.begin_nested():
  2167. await conn.execute(text("UPDATE api_keys SET can_manage_inventory = can_queue"))
  2168. # Migration: Soft-delete column for trash bin (Issue #1008). Indexed so the
  2169. # sweeper's "SELECT ... WHERE deleted_at < cutoff" and the trash list's
  2170. # "WHERE deleted_at IS NOT NULL" stay cheap as the table grows.
  2171. #
  2172. # ``DATETIME`` is a SQLite-only type alias — PostgreSQL rejects it as
  2173. # invalid syntax, _safe_execute swallows the error, and the column is
  2174. # never added (breaking every query that references it). Emit
  2175. # dialect-appropriate SQL so both backends get the column.
  2176. if is_sqlite():
  2177. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at DATETIME")
  2178. else:
  2179. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at TIMESTAMP")
  2180. await _safe_execute(
  2181. conn,
  2182. "CREATE INDEX IF NOT EXISTS ix_library_files_deleted_at ON library_files(deleted_at)",
  2183. )
  2184. # Legacy SQLite installs created `settings` without a UNIQUE constraint on `key`,
  2185. # so `INSERT OR IGNORE` below silently degrades to a plain INSERT and dupes rows on
  2186. # every restart. Dedupe (keep lowest id per key) and add the missing unique index
  2187. # before seeding. Safe/idempotent on both dialects — fresh installs already have
  2188. # no dupes and `create_all` already emits the index.
  2189. async with conn.begin_nested():
  2190. await conn.execute(text("DELETE FROM settings WHERE id NOT IN (SELECT MIN(id) FROM settings GROUP BY key)"))
  2191. await _safe_execute(conn, "CREATE UNIQUE INDEX IF NOT EXISTS ix_settings_key ON settings(key)")
  2192. # Migration: Normalise provider_email to lowercase (SEC-3).
  2193. # Required for Entra ID where UPN/email claims may arrive in mixed case.
  2194. # LOWER() is supported by both SQLite and PostgreSQL; the UPDATE is idempotent.
  2195. # Executed directly (not via _safe_execute) so any column-reference failure
  2196. # is always fatal and never silently swallowed.
  2197. async with conn.begin_nested():
  2198. await conn.execute(
  2199. text(
  2200. "UPDATE user_oidc_links SET provider_email = LOWER(provider_email) "
  2201. "WHERE provider_email IS NOT NULL AND provider_email != LOWER(provider_email)"
  2202. )
  2203. )
  2204. # Migration: Create spoolman_slot_assignments table for local AMS-slot→Spoolman-spool mapping.
  2205. # Replaces the pattern of writing spool.location in Spoolman (which polluted the
  2206. # user-editable storage_location field in the UI).
  2207. # ck_ams_id_range formula was widened in #1274 to admit AMS-HT (ams_id 128-191).
  2208. await _safe_execute(
  2209. conn,
  2210. """
  2211. CREATE TABLE IF NOT EXISTS spoolman_slot_assignments (
  2212. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2213. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2214. ams_id INTEGER NOT NULL CHECK ((ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255),
  2215. tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3),
  2216. spoolman_spool_id INTEGER NOT NULL,
  2217. assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2218. CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)
  2219. )
  2220. """
  2221. if is_sqlite()
  2222. else """
  2223. CREATE TABLE IF NOT EXISTS spoolman_slot_assignments (
  2224. id SERIAL PRIMARY KEY,
  2225. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2226. ams_id INTEGER NOT NULL CHECK ((ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255),
  2227. tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3),
  2228. spoolman_spool_id INTEGER NOT NULL,
  2229. assigned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2230. CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)
  2231. )
  2232. """,
  2233. )
  2234. await _safe_execute(
  2235. conn,
  2236. "CREATE INDEX IF NOT EXISTS ix_slot_assignment_spool ON spoolman_slot_assignments (spoolman_spool_id)",
  2237. )
  2238. # Migration: widen ck_ams_id_range on spoolman_slot_assignments to allow
  2239. # AMS-HT ids (128-191). Existing installs created before #1274 carry the
  2240. # stale formula which rejects every AMS-HT slot link with a CHECK violation.
  2241. await _migrate_widen_spoolman_slot_ams_id_range(conn)
  2242. # Migration: Create spoolman_k_profile table for K-value calibration profiles linked to Spoolman spools.
  2243. await _safe_execute(
  2244. conn,
  2245. """
  2246. CREATE TABLE IF NOT EXISTS spoolman_k_profile (
  2247. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2248. spoolman_spool_id INTEGER NOT NULL,
  2249. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2250. extruder INTEGER NOT NULL DEFAULT 0 CHECK (extruder >= 0 AND extruder <= 1),
  2251. nozzle_diameter VARCHAR(10) NOT NULL DEFAULT '0.4',
  2252. nozzle_type VARCHAR(50),
  2253. k_value REAL NOT NULL,
  2254. name VARCHAR(100),
  2255. cali_idx INTEGER,
  2256. setting_id VARCHAR(50),
  2257. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2258. CONSTRAINT uq_spoolman_k_profile UNIQUE(spoolman_spool_id, printer_id, extruder, nozzle_diameter)
  2259. )
  2260. """
  2261. if is_sqlite()
  2262. else """
  2263. CREATE TABLE IF NOT EXISTS spoolman_k_profile (
  2264. id SERIAL PRIMARY KEY,
  2265. spoolman_spool_id INTEGER NOT NULL,
  2266. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2267. extruder INTEGER NOT NULL DEFAULT 0 CHECK (extruder >= 0 AND extruder <= 1),
  2268. nozzle_diameter VARCHAR(10) NOT NULL DEFAULT '0.4',
  2269. nozzle_type VARCHAR(50),
  2270. k_value DOUBLE PRECISION NOT NULL,
  2271. name VARCHAR(100),
  2272. cali_idx INTEGER,
  2273. setting_id VARCHAR(50),
  2274. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2275. CONSTRAINT uq_spoolman_k_profile UNIQUE(spoolman_spool_id, printer_id, extruder, nozzle_diameter)
  2276. )
  2277. """,
  2278. )
  2279. await _safe_execute(
  2280. conn,
  2281. "CREATE INDEX IF NOT EXISTS ix_spoolman_k_profile_spool ON spoolman_k_profile (spoolman_spool_id)",
  2282. )
  2283. # Migration: Add provider column to github_backup_config for multi-provider support
  2284. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN provider VARCHAR(30) DEFAULT 'github'")
  2285. # Migration: Add allow_insecure_http column to github_backup_config for self-hosted HTTP instances
  2286. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN allow_insecure_http BOOLEAN DEFAULT FALSE")
  2287. # Seed default settings keys that must exist on fresh install
  2288. default_settings = [
  2289. ("advanced_auth_enabled", "false"),
  2290. ("smtp_auth_enabled", "true"),
  2291. ]
  2292. for key, value in default_settings:
  2293. try:
  2294. if is_sqlite():
  2295. await conn.execute(
  2296. text("INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)"),
  2297. {"key": key, "value": value},
  2298. )
  2299. else:
  2300. await conn.execute(
  2301. text("INSERT INTO settings (key, value) VALUES (:key, :value) ON CONFLICT (key) DO NOTHING"),
  2302. {"key": key, "value": value},
  2303. )
  2304. except (OperationalError, ProgrammingError):
  2305. pass
  2306. # Migration: Create filament_sku_settings table for reorder forecasting
  2307. if is_sqlite():
  2308. await _safe_execute(
  2309. conn,
  2310. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  2311. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2312. material VARCHAR(50) NOT NULL,
  2313. subtype VARCHAR(50),
  2314. brand VARCHAR(100),
  2315. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2316. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2317. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2318. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2319. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2320. UNIQUE (material, subtype, brand)
  2321. )""",
  2322. )
  2323. async with conn.begin_nested():
  2324. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  2325. await _safe_execute(
  2326. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_value INTEGER NOT NULL DEFAULT 14"
  2327. )
  2328. await _safe_execute(
  2329. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'"
  2330. )
  2331. await _safe_execute(
  2332. conn, "ALTER TABLE filament_sku_settings ADD COLUMN alerts_snoozed BOOLEAN NOT NULL DEFAULT 0"
  2333. )
  2334. # Backfill and drop legacy safety_margin_days column — SQLite requires a table rebuild.
  2335. # Only run if the stale column still exists.
  2336. cols_result = await conn.execute(text("PRAGMA table_info(filament_sku_settings)"))
  2337. col_names = [row[1] for row in cols_result.fetchall()]
  2338. if "safety_margin_days" in col_names:
  2339. async with conn.begin_nested():
  2340. # Defensive: a previous startup may have crashed mid-rebuild leaving
  2341. # filament_sku_settings_new behind, which would break the CREATE below.
  2342. await conn.execute(text("DROP TABLE IF EXISTS filament_sku_settings_new"))
  2343. await conn.execute(
  2344. text(
  2345. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  2346. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  2347. )
  2348. )
  2349. await conn.execute(
  2350. text(
  2351. """CREATE TABLE filament_sku_settings_new (
  2352. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2353. material VARCHAR(50) NOT NULL,
  2354. subtype VARCHAR(50),
  2355. brand VARCHAR(100),
  2356. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2357. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2358. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2359. alerts_snoozed BOOLEAN NOT NULL DEFAULT 0,
  2360. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2361. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2362. UNIQUE (material, subtype, brand)
  2363. )"""
  2364. )
  2365. )
  2366. await conn.execute(
  2367. text(
  2368. """INSERT INTO filament_sku_settings_new
  2369. (id, material, subtype, brand, lead_time_days, safety_margin_value,
  2370. safety_margin_unit, alerts_snoozed, created_at, updated_at)
  2371. SELECT id, material, subtype, brand, lead_time_days, safety_margin_value,
  2372. safety_margin_unit, COALESCE(alerts_snoozed, 0), created_at, updated_at
  2373. FROM filament_sku_settings"""
  2374. )
  2375. )
  2376. await conn.execute(text("DROP TABLE filament_sku_settings"))
  2377. await conn.execute(text("ALTER TABLE filament_sku_settings_new RENAME TO filament_sku_settings"))
  2378. await _safe_execute(
  2379. conn,
  2380. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  2381. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2382. material VARCHAR(50) NOT NULL,
  2383. subtype VARCHAR(50),
  2384. brand VARCHAR(100),
  2385. quantity_spools INTEGER NOT NULL DEFAULT 1,
  2386. note VARCHAR(500),
  2387. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  2388. purchased_at DATETIME,
  2389. added_at DATETIME DEFAULT CURRENT_TIMESTAMP
  2390. )""",
  2391. )
  2392. # SQLite has no implicit updated_at trigger — add one so the column stays current.
  2393. await _safe_execute(
  2394. conn,
  2395. """CREATE TRIGGER IF NOT EXISTS trg_filament_sku_settings_updated_at
  2396. AFTER UPDATE ON filament_sku_settings FOR EACH ROW
  2397. BEGIN
  2398. UPDATE filament_sku_settings SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
  2399. END""",
  2400. )
  2401. else:
  2402. await _safe_execute(
  2403. conn,
  2404. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  2405. id SERIAL PRIMARY KEY,
  2406. material VARCHAR(50) NOT NULL,
  2407. subtype VARCHAR(50),
  2408. brand VARCHAR(100),
  2409. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2410. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2411. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2412. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  2413. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  2414. UNIQUE (material, subtype, brand)
  2415. )""",
  2416. )
  2417. async with conn.begin_nested():
  2418. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  2419. await _safe_execute(
  2420. conn,
  2421. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_value INTEGER NOT NULL DEFAULT 14",
  2422. )
  2423. await _safe_execute(
  2424. conn,
  2425. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'",
  2426. )
  2427. await _safe_execute(
  2428. conn,
  2429. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS alerts_snoozed BOOLEAN NOT NULL DEFAULT FALSE",
  2430. )
  2431. # Only backfill from safety_margin_days if that column still exists (PostgreSQL).
  2432. col_check = await conn.execute(
  2433. text(
  2434. "SELECT 1 FROM information_schema.columns "
  2435. "WHERE table_name = 'filament_sku_settings' AND column_name = 'safety_margin_days'"
  2436. )
  2437. )
  2438. if col_check.fetchone():
  2439. async with conn.begin_nested():
  2440. await conn.execute(
  2441. text(
  2442. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  2443. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  2444. )
  2445. )
  2446. await _safe_execute(
  2447. conn,
  2448. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  2449. id SERIAL PRIMARY KEY,
  2450. material VARCHAR(50) NOT NULL,
  2451. subtype VARCHAR(50),
  2452. brand VARCHAR(100),
  2453. quantity_spools INTEGER NOT NULL DEFAULT 1,
  2454. note VARCHAR(500),
  2455. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  2456. purchased_at TIMESTAMP,
  2457. added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  2458. )""",
  2459. )
  2460. await _safe_execute(
  2461. conn,
  2462. "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'pending'",
  2463. )
  2464. await _safe_execute(conn, "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS purchased_at TIMESTAMP")
  2465. # Migration: Add inventory stock alert columns to notification_providers.
  2466. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  2467. if is_sqlite():
  2468. await _safe_execute(
  2469. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT 0"
  2470. )
  2471. await _safe_execute(
  2472. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT 0"
  2473. )
  2474. else:
  2475. await _safe_execute(
  2476. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT false"
  2477. )
  2478. await _safe_execute(
  2479. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT false"
  2480. )
  2481. # Migration: Heal orphan auth-related rows left behind by user-delete
  2482. # on SQLite. user_oidc_links, user_totp, user_otp_codes (introduced in
  2483. # PR #933) and long_lived_tokens (PR #1108) all declare ON DELETE
  2484. # CASCADE on user_id — both predate the explicit APIKey-cleanup
  2485. # pattern in PR #1182. PostgreSQL enforces the cascade, but SQLite
  2486. # ships with FK enforcement off, so rows pointing to a deleted user
  2487. # persisted — blocking SSO re-login (the OIDC callback finds the
  2488. # orphan link, fails to resolve the missing user, and falls through
  2489. # to "account_inactive" instead of triggering auto_create), leaking
  2490. # MFA secrets, and leaving camera-stream tokens whose secret_hash is
  2491. # still verify()-able by lookup_prefix. See issue #1285 (#1295 review
  2492. # extended the cleanup to long_lived_tokens). This migration is a
  2493. # no-op on PostgreSQL and idempotent on SQLite.
  2494. async with conn.begin_nested():
  2495. oidc_result = await conn.execute(
  2496. text("DELETE FROM user_oidc_links WHERE user_id NOT IN (SELECT id FROM users)")
  2497. )
  2498. totp_result = await conn.execute(text("DELETE FROM user_totp WHERE user_id NOT IN (SELECT id FROM users)"))
  2499. otp_result = await conn.execute(text("DELETE FROM user_otp_codes WHERE user_id NOT IN (SELECT id FROM users)"))
  2500. llt_result = await conn.execute(
  2501. text("DELETE FROM long_lived_tokens WHERE user_id NOT IN (SELECT id FROM users)")
  2502. )
  2503. oidc_n = oidc_result.rowcount or 0
  2504. totp_n = totp_result.rowcount or 0
  2505. otp_n = otp_result.rowcount or 0
  2506. llt_n = llt_result.rowcount or 0
  2507. if oidc_n or totp_n or otp_n or llt_n:
  2508. logger.info(
  2509. "Cleaned up orphan auth rows: %d OIDC links, %d TOTP, %d OTP codes, %d long-lived tokens",
  2510. oidc_n,
  2511. totp_n,
  2512. otp_n,
  2513. llt_n,
  2514. )
  2515. # Migration: extend print_log_entries with archive_id, cost, energy, failure_reason,
  2516. # created_by_id (#1378). Statistics queries shift from PrintArchive to PrintLogEntry
  2517. # so reprints contribute new rows instead of overwriting the source archive's data.
  2518. if is_sqlite():
  2519. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN archive_id INTEGER")
  2520. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN cost REAL")
  2521. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN energy_kwh REAL")
  2522. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN energy_cost REAL")
  2523. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN failure_reason VARCHAR(100)")
  2524. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN created_by_id INTEGER")
  2525. else:
  2526. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS archive_id INTEGER")
  2527. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS cost DOUBLE PRECISION")
  2528. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS energy_kwh DOUBLE PRECISION")
  2529. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS energy_cost DOUBLE PRECISION")
  2530. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS failure_reason VARCHAR(100)")
  2531. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS created_by_id INTEGER")
  2532. await _safe_execute(
  2533. conn, "CREATE INDEX IF NOT EXISTS ix_print_log_entries_archive_id ON print_log_entries (archive_id)"
  2534. )
  2535. # Backfill PrintLogEntry → PrintArchive linkage and per-event cost/energy
  2536. # for pre-#1378 rows the column-add migration left NULL (#1390).
  2537. #
  2538. # Without this backfill the user's Quick Stats show Filament Cost = 0 and
  2539. # Time Accuracy empty even though their archives carry both, because:
  2540. #
  2541. # - the new stats queries SUM PrintLogEntry.cost (NULL for old rows)
  2542. # - the time-accuracy query JOINs PrintArchive ON archive_id (NULL for
  2543. # old rows, so old runs get excluded from the average)
  2544. #
  2545. # Pre-#1378, archive.cost / energy_kwh / energy_cost were overwritten by
  2546. # each rerun, so the current archive values represent the *latest* run.
  2547. # Backfilling them onto the latest matching PrintLogEntry per archive
  2548. # reconstructs the pre-fix total exactly (sum across archives stays
  2549. # unchanged), and leaves earlier reprints with NULL cost so they
  2550. # contribute zero — matching the "first/latest writes, rest stay NULL"
  2551. # convention #1378 introduced for new prints.
  2552. #
  2553. # DML, not DDL — use conn.execute() inside a savepoint per _safe_execute's
  2554. # own docstring. SQL is plain ANSI (correlated UPDATE, MAX/GROUP BY/HAVING,
  2555. # CASE in HAVING) and runs unchanged on SQLite + PostgreSQL; verified
  2556. # against postgres:16-alpine + asyncpg.
  2557. #
  2558. # Step 1: link old log entries to their archive via print_name + printer_id.
  2559. # Picks the highest-id matching archive when multiple share the same key
  2560. # (newest archive wins — closest to the log's overwrite-then-leave shape).
  2561. from sqlalchemy import text as _text
  2562. async with conn.begin_nested():
  2563. await conn.execute(
  2564. _text("""
  2565. UPDATE print_log_entries
  2566. SET archive_id = (
  2567. SELECT a.id
  2568. FROM print_archives a
  2569. WHERE a.print_name = print_log_entries.print_name
  2570. AND (
  2571. a.printer_id = print_log_entries.printer_id
  2572. OR (a.printer_id IS NULL AND print_log_entries.printer_id IS NULL)
  2573. )
  2574. ORDER BY a.id DESC
  2575. LIMIT 1
  2576. )
  2577. WHERE archive_id IS NULL AND print_name IS NOT NULL
  2578. """)
  2579. )
  2580. # Step 2: backfill cost / energy_kwh / energy_cost onto the latest linked
  2581. # log entry per archive — the row whose creation time best matches the
  2582. # value currently stored on the archive (overwrite-on-reprint semantics
  2583. # under the old design). Only fires for archives where NO log entry has
  2584. # cost set yet, which gives the migration a clean idempotency property:
  2585. # the second pass sees the archive already has a cost-bearing run and
  2586. # leaves the rest of its history NULL (instead of marching up the
  2587. # ID-ordered list of NULL runs on every pass).
  2588. async with conn.begin_nested():
  2589. await conn.execute(
  2590. _text("""
  2591. UPDATE print_log_entries
  2592. SET cost = (SELECT cost FROM print_archives WHERE id = print_log_entries.archive_id),
  2593. energy_kwh = (SELECT energy_kwh FROM print_archives WHERE id = print_log_entries.archive_id),
  2594. energy_cost = (SELECT energy_cost FROM print_archives WHERE id = print_log_entries.archive_id)
  2595. WHERE id IN (
  2596. SELECT MAX(id)
  2597. FROM print_log_entries
  2598. WHERE archive_id IS NOT NULL
  2599. GROUP BY archive_id
  2600. HAVING SUM(CASE WHEN cost IS NOT NULL THEN 1 ELSE 0 END) = 0
  2601. )
  2602. """)
  2603. )
  2604. # Migration: smart_plugs gets per-plug auto-off-after-drying toggle and
  2605. # delay (#1349). Fires whenever any AMS attached to the linked printer
  2606. # finishes a dry cycle. Plain ANSI ALTER TABLE works on both SQLite and
  2607. # Postgres for INTEGER/BOOLEAN with simple defaults.
  2608. if is_sqlite():
  2609. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_after_drying BOOLEAN DEFAULT 0")
  2610. await _safe_execute(
  2611. conn, "ALTER TABLE smart_plugs ADD COLUMN off_delay_after_drying_minutes INTEGER DEFAULT 10"
  2612. )
  2613. else:
  2614. await _safe_execute(
  2615. conn,
  2616. "ALTER TABLE smart_plugs ADD COLUMN IF NOT EXISTS auto_off_after_drying BOOLEAN DEFAULT false",
  2617. )
  2618. await _safe_execute(
  2619. conn,
  2620. "ALTER TABLE smart_plugs ADD COLUMN IF NOT EXISTS off_delay_after_drying_minutes INTEGER DEFAULT 10",
  2621. )
  2622. # Migration: Add per-user Orca Cloud credential columns. Mirrors the Bambu
  2623. # Cloud columns but adds refresh_token + expires_at (Supabase PKCE issues
  2624. # short-lived access tokens with rotating refresh tokens), plus three
  2625. # transient PKCE state columns held during the auth handshake. DATETIME
  2626. # is SQLite-only — Postgres uses TIMESTAMP, so the datetime columns are
  2627. # dialect-branched per project convention.
  2628. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_token VARCHAR(2000)")
  2629. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_refresh_token VARCHAR(128)")
  2630. if is_sqlite():
  2631. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_expires_at DATETIME")
  2632. else:
  2633. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN IF NOT EXISTS orca_cloud_expires_at TIMESTAMP")
  2634. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_email VARCHAR(255)")
  2635. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_user_id VARCHAR(64)")
  2636. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_verifier VARCHAR(64)")
  2637. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_state VARCHAR(32)")
  2638. if is_sqlite():
  2639. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_at DATETIME")
  2640. else:
  2641. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN IF NOT EXISTS orca_cloud_pending_at TIMESTAMP")
  2642. # Data migration: drop the embedded 3MF Title (`print_name`) from library
  2643. # file metadata so the FileManager displays the filename, not the title (#1489).
  2644. await _migrate_drop_library_print_name(conn)
  2645. # Backfill NULL print_archives.created_at — older rows (and rows imported
  2646. # via the SQLite ↔ Postgres cross-DB restore path) can land with NULL
  2647. # because the column was originally created without a DEFAULT clause and
  2648. # server_default=func.now() only fires at table creation, not column
  2649. # population. The list_archives response model requires a datetime, so a
  2650. # single NULL row 500s the whole endpoint (#1732).
  2651. async with conn.begin_nested():
  2652. if is_sqlite():
  2653. await conn.execute(
  2654. text(
  2655. "UPDATE print_archives "
  2656. "SET created_at = COALESCE(completed_at, started_at, datetime('now')) "
  2657. "WHERE created_at IS NULL"
  2658. )
  2659. )
  2660. else:
  2661. await conn.execute(
  2662. text(
  2663. "UPDATE print_archives "
  2664. "SET created_at = COALESCE(completed_at, started_at, NOW()) "
  2665. "WHERE created_at IS NULL"
  2666. )
  2667. )
  2668. # Migration: structured storage locations (#1004). Flat catalog of physical
  2669. # shelves/drawers; spool.location_id FK with storage_location kept denormalized.
  2670. await _safe_execute(
  2671. conn,
  2672. """
  2673. CREATE TABLE IF NOT EXISTS locations (
  2674. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2675. name VARCHAR(255) NOT NULL UNIQUE,
  2676. name_key VARCHAR(255),
  2677. identifier VARCHAR(100),
  2678. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2679. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  2680. )
  2681. """
  2682. if is_sqlite()
  2683. else """
  2684. CREATE TABLE IF NOT EXISTS locations (
  2685. id SERIAL PRIMARY KEY,
  2686. name VARCHAR(255) NOT NULL UNIQUE,
  2687. name_key VARCHAR(255),
  2688. identifier VARCHAR(100),
  2689. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2690. updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  2691. )
  2692. """,
  2693. )
  2694. await _safe_execute(conn, "ALTER TABLE locations ADD COLUMN name_key VARCHAR(255)")
  2695. await _safe_execute(conn, "CREATE UNIQUE INDEX IF NOT EXISTS ix_locations_name_key ON locations (name_key)")
  2696. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN location_id INTEGER REFERENCES locations(id)")
  2697. await _safe_execute(conn, "CREATE INDEX IF NOT EXISTS ix_spool_location_id ON spool (location_id)")
  2698. # Backfill name_key on legacy rows FIRST. If a pre-existing locations
  2699. # row was manually inserted before this migration ran, its name_key is
  2700. # NULL. The dedup INSERT below would then be silently skipped by
  2701. # UNIQUE(name) (legacy row already has the name), AND the spool-link
  2702. # UPDATE that joins on name_key would miss it. Doing this backfill BEFORE
  2703. # the INSERT keeps the join consistent on both branches of the migration.
  2704. async with conn.begin_nested():
  2705. await conn.execute(
  2706. text(
  2707. """
  2708. UPDATE locations
  2709. SET name_key = LOWER(TRIM(name))
  2710. WHERE name_key IS NULL OR TRIM(name_key) = ''
  2711. """
  2712. )
  2713. )
  2714. # Backfill locations from existing free-text storage_location values.
  2715. # GROUP BY name_key so case variants ("Drybox 1" / "DRYBOX 1") collapse to
  2716. # one row; INSERT OR IGNORE / ON CONFLICT keeps the migration idempotent.
  2717. _location_backfill_sql = (
  2718. """
  2719. INSERT OR IGNORE INTO locations (name, name_key, created_at, updated_at)
  2720. SELECT MIN(TRIM(storage_location)), LOWER(TRIM(storage_location)), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
  2721. FROM spool
  2722. WHERE TRIM(COALESCE(storage_location, '')) != ''
  2723. GROUP BY LOWER(TRIM(storage_location))
  2724. """
  2725. if is_sqlite()
  2726. else """
  2727. INSERT INTO locations (name, name_key, created_at, updated_at)
  2728. SELECT MIN(TRIM(storage_location)), LOWER(TRIM(storage_location)), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
  2729. FROM spool
  2730. WHERE TRIM(COALESCE(storage_location, '')) != ''
  2731. GROUP BY LOWER(TRIM(storage_location))
  2732. ON CONFLICT (name_key) DO NOTHING
  2733. """
  2734. )
  2735. async with conn.begin_nested():
  2736. await conn.execute(text(_location_backfill_sql))
  2737. await conn.execute(
  2738. text(
  2739. """
  2740. UPDATE spool
  2741. SET location_id = (
  2742. SELECT l.id FROM locations l
  2743. WHERE l.name_key = LOWER(TRIM(spool.storage_location))
  2744. LIMIT 1
  2745. )
  2746. WHERE TRIM(COALESCE(storage_location, '')) != ''
  2747. AND location_id IS NULL
  2748. """
  2749. )
  2750. )
  2751. # Sanity check: any spools that still have a free-text storage_location
  2752. # but no location_id link mean a row slipped through the dedup INSERT
  2753. # (most likely a pre-existing manually-inserted locations row with a
  2754. # hostile name shape that the UNIQUE(name) check tripped on). Surface
  2755. # the count so ops can investigate — the user won't see those spools in
  2756. # location-filtered queries until they're manually linked or re-saved.
  2757. orphan_count_row = await conn.execute(
  2758. text("SELECT COUNT(*) FROM spool WHERE TRIM(COALESCE(storage_location, '')) != '' AND location_id IS NULL")
  2759. )
  2760. orphan_count = orphan_count_row.scalar() or 0
  2761. if orphan_count:
  2762. logger.warning(
  2763. "Storage-location migration left %d spool(s) with free-text storage_location "
  2764. "but no location_id link. Re-save those spools or merge the orphaned location "
  2765. "names manually.",
  2766. orphan_count,
  2767. )
  2768. async def seed_notification_templates():
  2769. """Seed default notification templates if they don't exist."""
  2770. from sqlalchemy import select
  2771. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  2772. async with async_session() as session:
  2773. # Get existing template event types
  2774. result = await session.execute(select(NotificationTemplate.event_type))
  2775. existing_types = {row[0] for row in result.fetchall()}
  2776. if not existing_types:
  2777. # No templates exist - insert all defaults
  2778. for template_data in DEFAULT_TEMPLATES:
  2779. template = NotificationTemplate(
  2780. event_type=template_data["event_type"],
  2781. name=template_data["name"],
  2782. title_template=template_data["title_template"],
  2783. body_template=template_data["body_template"],
  2784. is_default=True,
  2785. )
  2786. session.add(template)
  2787. else:
  2788. # Templates exist - only add missing ones
  2789. for template_data in DEFAULT_TEMPLATES:
  2790. if template_data["event_type"] not in existing_types:
  2791. template = NotificationTemplate(
  2792. event_type=template_data["event_type"],
  2793. name=template_data["name"],
  2794. title_template=template_data["title_template"],
  2795. body_template=template_data["body_template"],
  2796. is_default=True,
  2797. )
  2798. session.add(template)
  2799. await session.commit()
  2800. async def seed_default_groups():
  2801. """Seed default groups and migrate existing users to appropriate groups.
  2802. Creates the default system groups (Administrators, Operators, Viewers) if they
  2803. don't exist, then migrates existing users:
  2804. - Users with role='admin' -> Administrators group
  2805. - Users with role='user' -> Operators group
  2806. Also migrates old permissions to new ownership-based permissions (Issue #205).
  2807. """
  2808. import logging
  2809. from sqlalchemy import select
  2810. from backend.app.core.permissions import DEFAULT_GROUPS
  2811. from backend.app.models.group import Group
  2812. from backend.app.models.user import User
  2813. logger = logging.getLogger(__name__)
  2814. # Map old permissions to new ones for migration
  2815. # Administrators get *_all permissions, Operators get *_own permissions.
  2816. #
  2817. # NOTE on the read-flag asymmetry: write permissions (`update`, `delete`,
  2818. # `reprint`) are removed from the legacy flag and remapped to the OWN/ALL
  2819. # split — the legacy flag is dead on the API side. Read permissions are
  2820. # different: the frontend still gates UI actions (download buttons in
  2821. # ArchivesPage, preview button in FileManagerPage) on the LEGACY
  2822. # `archives:read` / `library:read` / `queue:read` strings. For admin we
  2823. # therefore keep the legacy flag (the `*_all` companion gets added via the
  2824. # backfill block below). For non-admin roles the legacy IS renamed to
  2825. # `_own` — that closes the IDOR (operators with a custom `archives:read`
  2826. # row can no longer read cross-user data) and the UI gates degrade to
  2827. # disabled-button state until the frontend is migrated to also accept
  2828. # `_own` (separate change). See maziggy/bambuddy-security #2.
  2829. PERMISSION_MIGRATION_ALL = {
  2830. "queue:update": "queue:update_all",
  2831. "queue:delete": "queue:delete_all",
  2832. "archives:update": "archives:update_all",
  2833. "archives:delete": "archives:delete_all",
  2834. "archives:reprint": "archives:reprint_all",
  2835. "library:update": "library:update_all",
  2836. "library:delete": "library:delete_all",
  2837. }
  2838. PERMISSION_MIGRATION_OWN = {
  2839. "queue:update": "queue:update_own",
  2840. "queue:delete": "queue:delete_own",
  2841. # Read permissions: any role NOT flagged as Administrator gets
  2842. # ownership-scoped reads. Pre-existing custom roles with the legacy
  2843. # `*:read` flag silently saw every user's items; the OWN variant
  2844. # closes that IDOR. Roles that genuinely need cross-user visibility
  2845. # must be re-granted `*:read_all` explicitly by an administrator
  2846. # after upgrade — fail-closed by default (per CWE-636).
  2847. "queue:read": "queue:read_own",
  2848. "archives:update": "archives:update_own",
  2849. "archives:delete": "archives:delete_own",
  2850. "archives:reprint": "archives:reprint_own",
  2851. "archives:read": "archives:read_own",
  2852. "library:update": "library:update_own",
  2853. "library:delete": "library:delete_own",
  2854. "library:read": "library:read_own",
  2855. }
  2856. async with async_session() as session:
  2857. # Get existing groups
  2858. result = await session.execute(select(Group))
  2859. existing_groups = {group.name: group for group in result.scalars().all()}
  2860. # Create default groups if they don't exist
  2861. groups_created = []
  2862. for group_name, group_config in DEFAULT_GROUPS.items():
  2863. if group_name not in existing_groups:
  2864. group = Group(
  2865. name=group_name,
  2866. description=group_config["description"],
  2867. permissions=group_config["permissions"],
  2868. is_system=group_config["is_system"],
  2869. )
  2870. session.add(group)
  2871. groups_created.append(group_name)
  2872. logger.info("Created default group: %s", group_name)
  2873. else:
  2874. # Migrate existing group's permissions from old to new format
  2875. group = existing_groups[group_name]
  2876. if group.permissions:
  2877. updated = False
  2878. new_permissions = list(group.permissions)
  2879. # Determine which migration map to use based on group
  2880. migration_map = (
  2881. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  2882. )
  2883. for old_perm, new_perm in migration_map.items():
  2884. if old_perm in new_permissions:
  2885. new_permissions.remove(old_perm)
  2886. if new_perm not in new_permissions:
  2887. new_permissions.append(new_perm)
  2888. updated = True
  2889. logger.info(
  2890. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  2891. )
  2892. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  2893. if group_name == "Administrators":
  2894. for _own_perm, all_perm in [
  2895. ("queue:update_own", "queue:update_all"),
  2896. ("queue:delete_own", "queue:delete_all"),
  2897. ("queue:read_own", "queue:read_all"),
  2898. ("archives:update_own", "archives:update_all"),
  2899. ("archives:delete_own", "archives:delete_all"),
  2900. ("archives:reprint_own", "archives:reprint_all"),
  2901. ("archives:read_own", "archives:read_all"),
  2902. ("library:update_own", "library:update_all"),
  2903. ("library:delete_own", "library:delete_all"),
  2904. ("library:read_own", "library:read_all"),
  2905. ]:
  2906. # Add *_all if not present
  2907. if all_perm not in new_permissions:
  2908. new_permissions.append(all_perm)
  2909. updated = True
  2910. if updated:
  2911. group.permissions = new_permissions
  2912. await session.commit()
  2913. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  2914. result = await session.execute(select(Group))
  2915. all_groups = result.scalars().all()
  2916. for group in all_groups:
  2917. if (
  2918. group.permissions
  2919. and "printers:control" in group.permissions
  2920. and "printers:clear_plate" not in group.permissions
  2921. ):
  2922. group.permissions = [*group.permissions, "printers:clear_plate"]
  2923. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  2924. await session.commit()
  2925. # Migrate new permissions for MakerWorld integration: groups that
  2926. # already have library:upload (i.e. can write to the library) are
  2927. # the correct audience for makerworld:view + makerworld:import, and
  2928. # groups that only have library:read get makerworld:view (browse
  2929. # only). Matches the intent of DEFAULT_GROUPS without clobbering
  2930. # any user-customised permission lists.
  2931. result = await session.execute(select(Group))
  2932. for group in result.scalars().all():
  2933. if not group.permissions:
  2934. continue
  2935. perms = list(group.permissions)
  2936. changed = False
  2937. if "library:upload" in perms:
  2938. for new_perm in ("makerworld:view", "makerworld:import"):
  2939. if new_perm not in perms:
  2940. perms.append(new_perm)
  2941. changed = True
  2942. logger.info("Added %s to group '%s' (has library:upload)", new_perm, group.name)
  2943. elif "library:read" in perms and "makerworld:view" not in perms:
  2944. perms.append("makerworld:view")
  2945. changed = True
  2946. logger.info("Added makerworld:view to group '%s' (has library:read)", group.name)
  2947. if changed:
  2948. group.permissions = perms
  2949. await session.commit()
  2950. # Backfill library:purge + archives:purge for the Administrators group
  2951. # on existing installs. Both permissions were added after Administrators
  2952. # was first seeded, so upgrading users miss them even though the default
  2953. # config (ALL_PERMISSIONS) includes them for fresh installs.
  2954. result = await session.execute(select(Group).where(Group.name == "Administrators"))
  2955. admin_group = result.scalar_one_or_none()
  2956. if admin_group and admin_group.permissions is not None:
  2957. perms = list(admin_group.permissions)
  2958. added = False
  2959. for new_perm in ("library:purge", "archives:purge"):
  2960. if new_perm not in perms:
  2961. perms.append(new_perm)
  2962. added = True
  2963. logger.info("Added %s to Administrators group (backfill)", new_perm)
  2964. if added:
  2965. admin_group.permissions = perms
  2966. await session.commit()
  2967. # Backfill the read flag set for the Administrators group on existing
  2968. # installs (maziggy/bambuddy-security #2). Two layers:
  2969. #
  2970. # (a) New OWN/ALL splits — `archives:read_own` etc. Fresh installs get
  2971. # these via ALL_PERMISSIONS; upgrades need the explicit backfill
  2972. # so admin's permission set matches a fresh install's.
  2973. #
  2974. # (b) Legacy `archives:read` / `library:read` / `queue:read`. The
  2975. # frontend still gates download / preview UI on these LEGACY
  2976. # strings (see ArchivesPage / FileManagerPage), so admin needs
  2977. # them retained even though the new API uses the OWN/ALL split.
  2978. # The PERMISSION_MIGRATION_ALL map deliberately doesn't rename
  2979. # read flags for admin — this backfill ensures they're present
  2980. # even if they were stripped by hand or by an older migration.
  2981. #
  2982. # Also includes orca_cloud:auth for parity with fresh-install
  2983. # behaviour (ALL_PERMISSIONS covers it; backfill makes sure an
  2984. # admin role that's been customised since seed still has it).
  2985. result = await session.execute(select(Group).where(Group.name == "Administrators"))
  2986. admin_group = result.scalar_one_or_none()
  2987. if admin_group and admin_group.permissions is not None:
  2988. perms = list(admin_group.permissions)
  2989. added = False
  2990. for new_perm in (
  2991. "archives:read",
  2992. "archives:read_own",
  2993. "archives:read_all",
  2994. "library:read",
  2995. "library:read_own",
  2996. "library:read_all",
  2997. "queue:read",
  2998. "queue:read_own",
  2999. "queue:read_all",
  3000. "orca_cloud:auth",
  3001. ):
  3002. if new_perm not in perms:
  3003. perms.append(new_perm)
  3004. added = True
  3005. logger.info("Added %s to Administrators group (backfill)", new_perm)
  3006. if added:
  3007. admin_group.permissions = perms
  3008. await session.commit()
  3009. # Same OWN-tier backfill for non-admin system groups. Operators and
  3010. # Viewers are seeded with _own on fresh installs (see DEFAULT_GROUPS),
  3011. # but the legacy-rename migration above won't run on a role that
  3012. # didn't carry the legacy `archives:read` flag. Without this block,
  3013. # an existing Operators row whose permissions list lacks the legacy
  3014. # flag would never get archives:read_own and operators would lose
  3015. # read access after upgrade. Re-check by group name so customised
  3016. # rows still get the correct OWN tier on next startup.
  3017. #
  3018. # Operators also get orca_cloud:auth backfilled — fresh installs now
  3019. # include it in the DEFAULT_GROUPS bootstrap, so this keeps upgrades
  3020. # consistent. Viewers do NOT get orca_cloud:auth (read-only role,
  3021. # not expected to author slicer presets / sync to Orca Cloud).
  3022. for non_admin_group_name in ("Operators", "Viewers"):
  3023. grp = (await session.execute(select(Group).where(Group.name == non_admin_group_name))).scalar_one_or_none()
  3024. if grp is None or grp.permissions is None:
  3025. continue
  3026. perms = list(grp.permissions)
  3027. changed = False
  3028. for own_perm in ("archives:read_own", "library:read_own", "queue:read_own"):
  3029. if own_perm not in perms:
  3030. perms.append(own_perm)
  3031. changed = True
  3032. logger.info("Added %s to %s group (backfill)", own_perm, non_admin_group_name)
  3033. if non_admin_group_name == "Operators" and "orca_cloud:auth" not in perms:
  3034. perms.append("orca_cloud:auth")
  3035. changed = True
  3036. logger.info("Added orca_cloud:auth to Operators group (backfill)")
  3037. if changed:
  3038. grp.permissions = perms
  3039. await session.commit()
  3040. # Backfill inventory forecast permissions for existing groups.
  3041. # inventory:forecast_read was added after initial seeding, so groups
  3042. # that already have inventory:read (or inventory:update) need it added.
  3043. # inventory:forecast_write goes to any group with inventory:update.
  3044. result = await session.execute(select(Group))
  3045. for group in result.scalars().all():
  3046. if not group.permissions:
  3047. continue
  3048. perms = list(group.permissions)
  3049. changed = False
  3050. if "inventory:read" in perms and "inventory:forecast_read" not in perms:
  3051. perms.append("inventory:forecast_read")
  3052. changed = True
  3053. logger.info("Added inventory:forecast_read to group '%s' (backfill)", group.name)
  3054. if "inventory:update" in perms and "inventory:forecast_write" not in perms:
  3055. perms.append("inventory:forecast_write")
  3056. changed = True
  3057. logger.info("Added inventory:forecast_write to group '%s' (backfill)", group.name)
  3058. if changed:
  3059. group.permissions = perms
  3060. await session.commit()
  3061. # Migrate existing users to groups if they're not already in any group
  3062. if groups_created:
  3063. # Refresh to get newly created groups
  3064. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  3065. admin_group = admin_result.scalar_one_or_none()
  3066. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  3067. operators_group = operators_result.scalar_one_or_none()
  3068. # Get all users
  3069. users_result = await session.execute(select(User))
  3070. users = users_result.scalars().all()
  3071. for user in users:
  3072. # Skip if user already has groups
  3073. if user.groups:
  3074. continue
  3075. if user.role == "admin" and admin_group:
  3076. user.groups.append(admin_group)
  3077. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  3078. elif operators_group:
  3079. user.groups.append(operators_group)
  3080. logger.info("Migrated user '%s' to Operators group", user.username)
  3081. await session.commit()
  3082. async def seed_spool_catalog():
  3083. """Seed the spool catalog with default entries if empty."""
  3084. import logging
  3085. from sqlalchemy import func, select
  3086. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  3087. from backend.app.models.spool_catalog import SpoolCatalogEntry
  3088. logger = logging.getLogger(__name__)
  3089. async with async_session() as session:
  3090. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  3091. count = result.scalar() or 0
  3092. if count > 0:
  3093. return # Already seeded
  3094. for name, weight in DEFAULT_SPOOL_CATALOG:
  3095. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  3096. await session.commit()
  3097. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  3098. async def seed_color_catalog():
  3099. """Seed the color catalog with default entries if empty."""
  3100. import logging
  3101. from sqlalchemy import func, select
  3102. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  3103. from backend.app.models.color_catalog import ColorCatalogEntry
  3104. logger = logging.getLogger(__name__)
  3105. async with async_session() as session:
  3106. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  3107. count = result.scalar() or 0
  3108. if count > 0:
  3109. return # Already seeded
  3110. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  3111. session.add(
  3112. ColorCatalogEntry(
  3113. manufacturer=manufacturer,
  3114. color_name=color_name,
  3115. hex_color=hex_color,
  3116. material=material,
  3117. is_default=True,
  3118. )
  3119. )
  3120. await session.commit()
  3121. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))