database.py 183 KB

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