database.py 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524
  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. # Resolved connection-pool configuration, captured at engine creation so
  20. # /system/db-pool can report it without re-deriving the dialect defaults.
  21. _pool_config: dict = {}
  22. # What the PostgreSQL server itself will allow, read once at startup. None on
  23. # SQLite, or when the probe could not run. Reported by get_pool_status() so a
  24. # support bundle carries both sides of the comparison.
  25. _server_connection_limits: dict | None = None
  26. def _resolve_pool_kwargs() -> dict:
  27. """Build the pool kwargs for ``create_async_engine`` (issue #2572).
  28. Dialect-aware defaults, each overridable via env (``DB_POOL_SIZE`` etc.):
  29. - PostgreSQL: pool_size 20 + max_overflow 80, ``pool_pre_ping`` (recover
  30. server-dropped connections instead of erroring the request) and
  31. ``pool_recycle`` 1800s. The old hard-coded 10 + 20 exhausted on large
  32. farms while printer callbacks held connections.
  33. - SQLite: pool_size 20 + max_overflow 200 (unchanged); no pre-ping /
  34. recycle — the connection is a local file, not a server socket.
  35. """
  36. if is_sqlite():
  37. pool_size = settings.db_pool_size if settings.db_pool_size is not None else 20
  38. max_overflow = settings.db_max_overflow if settings.db_max_overflow is not None else 200
  39. kwargs = {"pool_size": pool_size, "max_overflow": max_overflow}
  40. else:
  41. pool_size = settings.db_pool_size if settings.db_pool_size is not None else 20
  42. max_overflow = settings.db_max_overflow if settings.db_max_overflow is not None else 80
  43. kwargs = {
  44. "pool_size": pool_size,
  45. "max_overflow": max_overflow,
  46. "pool_pre_ping": True,
  47. "pool_recycle": settings.db_pool_recycle if settings.db_pool_recycle is not None else 1800,
  48. # LIFO checkout keeps a bursty farm on a small hot connection set and
  49. # lets overflow connections recycle out during quiet spells (#2572).
  50. "pool_use_lifo": settings.db_pool_use_lifo if settings.db_pool_use_lifo is not None else True,
  51. }
  52. if settings.db_pool_timeout is not None:
  53. kwargs["pool_timeout"] = settings.db_pool_timeout
  54. return kwargs
  55. def _create_engine():
  56. """Create the async engine with dialect-appropriate settings."""
  57. kwargs = _resolve_pool_kwargs()
  58. global _pool_config
  59. _pool_config = {
  60. "pool_size": kwargs["pool_size"],
  61. "max_overflow": kwargs["max_overflow"],
  62. # SQLAlchemy's own defaults when we don't pass the kwarg.
  63. "pool_timeout": kwargs.get("pool_timeout", 30),
  64. "pool_recycle": kwargs.get("pool_recycle", -1),
  65. "pool_pre_ping": kwargs.get("pool_pre_ping", False),
  66. "pool_use_lifo": kwargs.get("pool_use_lifo", False),
  67. }
  68. eng = create_async_engine(
  69. settings.database_url,
  70. echo=settings.debug,
  71. **kwargs,
  72. )
  73. if is_sqlite():
  74. event.listen(eng.sync_engine, "connect", _set_sqlite_pragmas)
  75. else:
  76. # Strip timezone info from aware datetimes before they reach asyncpg.
  77. # asyncpg rejects timezone-aware values for TIMESTAMP WITHOUT TIME ZONE columns.
  78. # The codebase uses datetime.now(timezone.utc) in many places — this makes
  79. # Postgres behave like SQLite which ignores timezone info entirely.
  80. @event.listens_for(eng.sync_engine, "before_cursor_execute", retval=True)
  81. def _strip_tz_from_params(conn, cursor, statement, parameters, context, executemany):
  82. import datetime
  83. if parameters is None:
  84. return statement, parameters
  85. # Recursive strip that walks any nesting of dict/list/tuple. Needed
  86. # because SQLAlchemy passes parameters in several shapes depending
  87. # on the path: a dict for named binds, a tuple for positional, a
  88. # list of dicts/tuples for executemany, and for insertmanyvalues
  89. # sometimes a list of tuples inside an outer list. The simplest
  90. # correct answer is "strip datetimes at any depth".
  91. def _strip(val):
  92. if isinstance(val, datetime.datetime) and val.tzinfo is not None:
  93. return val.replace(tzinfo=None)
  94. if isinstance(val, dict):
  95. return {k: _strip(v) for k, v in val.items()}
  96. if isinstance(val, list):
  97. return [_strip(v) for v in val]
  98. if isinstance(val, tuple):
  99. return tuple(_strip(v) for v in val)
  100. return val
  101. return statement, _strip(parameters)
  102. return eng
  103. engine = _create_engine()
  104. async_session = async_sessionmaker(
  105. engine,
  106. class_=AsyncSession,
  107. expire_on_commit=False,
  108. )
  109. def get_pool_status() -> dict:
  110. """Snapshot the DB connection pool for diagnostics (issue #2572).
  111. Returns the resolved configuration plus live gauges (checked-out /
  112. checked-in / overflow). Reads the pool's own counters — it does NOT
  113. check out a connection, so it stays truthful even when the pool is
  114. exhausted. Gauges a given pool implementation doesn't expose come back
  115. as ``None`` rather than raising.
  116. """
  117. pool = engine.sync_engine.pool
  118. gauges: dict = {}
  119. for key, method_name in (
  120. ("current_size", "size"),
  121. ("checked_out", "checkedout"),
  122. ("checked_in", "checkedin"),
  123. ("overflow", "overflow"),
  124. ):
  125. method = getattr(pool, method_name, None)
  126. try:
  127. gauges[key] = method() if callable(method) else None
  128. except Exception:
  129. # A gauge should never take down the diagnostics endpoint.
  130. gauges[key] = None
  131. return {
  132. "dialect": "sqlite" if is_sqlite() else "postgresql",
  133. "config": dict(_pool_config),
  134. # Both sides of the ceiling-vs-server comparison, so a support bundle
  135. # shows whether a TooManyConnectionsError was a misconfiguration or a
  136. # genuine leak. None on SQLite or if the startup probe couldn't run.
  137. "server_limits": dict(_server_connection_limits) if _server_connection_limits else None,
  138. **gauges,
  139. }
  140. async def run_with_retry(fn, *, max_attempts: int = 3, label: str = ""):
  141. """Run an async DB operation with retry for SQLite 'database is locked' errors.
  142. ``fn`` is an async callable that receives an ``AsyncSession`` and performs
  143. the full query-mutate-commit cycle. On each retry a fresh session is used
  144. so there are no stale-object / expired-attribute issues after rollback.
  145. On PostgreSQL this calls ``fn`` once with no retry (Postgres uses row-level
  146. locking and doesn't suffer from single-writer contention).
  147. """
  148. if not is_sqlite():
  149. async with async_session() as db:
  150. return await fn(db)
  151. last_exc: OperationalError | None = None
  152. for attempt in range(1, max_attempts + 1):
  153. try:
  154. async with async_session() as db:
  155. return await fn(db)
  156. except OperationalError as exc:
  157. last_exc = exc
  158. if "database is locked" not in str(exc) or attempt == max_attempts:
  159. raise
  160. delay = 0.5 * attempt # 0.5s, 1.0s
  161. logger.warning(
  162. "SQLite locked%s (attempt %d/%d), retrying in %.1fs: %s",
  163. f" ({label})" if label else "",
  164. attempt,
  165. max_attempts,
  166. delay,
  167. exc,
  168. )
  169. await asyncio.sleep(delay)
  170. raise last_exc # unreachable, but keeps type checkers happy
  171. async def close_all_connections():
  172. """Close all database connections for backup/restore operations."""
  173. global engine
  174. await engine.dispose()
  175. async def reinitialize_database():
  176. """Reinitialize database connection after restore."""
  177. global engine, async_session
  178. engine = _create_engine()
  179. async_session = async_sessionmaker(
  180. engine,
  181. class_=AsyncSession,
  182. expire_on_commit=False,
  183. )
  184. class Base(DeclarativeBase):
  185. pass
  186. async def get_db() -> AsyncSession:
  187. async with async_session() as session:
  188. try:
  189. yield session
  190. await session.commit()
  191. except BaseException:
  192. # Catch BaseException (not just Exception) so CancelledError —
  193. # raised when Starlette's BaseHTTPMiddleware cancels the inner
  194. # task scope on client disconnect — also triggers rollback.
  195. # `asyncio.shield` keeps the rollback running to completion
  196. # even when the await itself gets cancelled, so the SQLite
  197. # write lock is released promptly instead of being held until
  198. # the connection is GC'd ages later (which was producing the
  199. # "database is locked" cascade in #1112's support package).
  200. try:
  201. await asyncio.shield(session.rollback())
  202. except BaseException: # noqa: BLE001 — rollback failure must not mask the original
  203. pass
  204. raise
  205. finally:
  206. try:
  207. await asyncio.shield(session.close())
  208. except BaseException: # noqa: BLE001 — close failure must not mask the original
  209. pass
  210. async def init_db():
  211. # Import models to register them with SQLAlchemy
  212. from backend.app.models import ( # noqa: F401
  213. active_print_spoolman,
  214. ams_history,
  215. ams_label,
  216. api_key,
  217. archive,
  218. auth_ephemeral,
  219. bug_report,
  220. color_catalog,
  221. external_link,
  222. filament,
  223. filament_sku_settings,
  224. github_backup,
  225. group,
  226. kprofile_note,
  227. library,
  228. local_preset,
  229. location,
  230. long_lived_token,
  231. maintenance,
  232. notification,
  233. notification_template,
  234. oidc_provider,
  235. orca_base_cache,
  236. pending_upload,
  237. pipeline_run,
  238. print_batch,
  239. print_log,
  240. print_queue,
  241. printer,
  242. printer_ha_sensor,
  243. printer_sensor_history,
  244. project,
  245. project_bom,
  246. settings,
  247. shopping_list,
  248. slicer_pipeline,
  249. slot_preset,
  250. smart_plug,
  251. smart_plug_energy_snapshot,
  252. spool,
  253. spool_assignment,
  254. spool_catalog,
  255. spool_k_profile,
  256. spool_usage_history,
  257. spoolbuddy_device,
  258. spoolman_k_profile,
  259. spoolman_slot_assignment,
  260. user,
  261. user_email_pref,
  262. user_otp_code,
  263. user_totp,
  264. virtual_printer,
  265. )
  266. async with engine.begin() as conn:
  267. await conn.run_sync(Base.metadata.create_all)
  268. # Run migrations for new columns (SQLite doesn't auto-add columns)
  269. await run_migrations(conn)
  270. # Re-encrypt any legacy plaintext OIDC client_secret / TOTP secret rows
  271. # that exist from before the encryption key was configured.
  272. # Runs on a fresh AsyncSession (NOT the run_migrations() connection) so it
  273. # doesn't share a transaction with the schema-DDL block above — required to
  274. # avoid SQLite "database is locked" contention on the WAL writer.
  275. await _migrate_encrypt_legacy_secrets()
  276. # Seed default notification templates
  277. await seed_notification_templates()
  278. # Seed default groups and migrate existing users
  279. await seed_default_groups()
  280. # Seed default catalog entries
  281. await seed_spool_catalog()
  282. await seed_color_catalog()
  283. await check_pool_fits_server()
  284. async def check_pool_fits_server() -> None:
  285. """Warn when the pool may ask PostgreSQL for more connections than it allows.
  286. ``pool_size + max_overflow`` is the most connections one worker process will
  287. ever open. If that exceeds what the server permits, the pool never reaches
  288. its own limit and so never queues: it goes straight to the server, which
  289. refuses with ``TooManyConnectionsError``. That surfaces wherever the next
  290. connection happened to be needed — in the reported case, halfway through a
  291. queue dispatch, which then left an expected-print registration and a dispatch
  292. claim behind (#2702 follow-up).
  293. The distinction is worth knowing when reading a log: SQLAlchemy's own
  294. ``QueuePool limit ... timed out`` means the pool is the bottleneck (too much
  295. concurrency, or connections held too long), whereas asyncpg's
  296. ``TooManyConnectionsError`` means the pool's ceiling is above the server's.
  297. Not clamped, deliberately. Pool sizes are fixed when the engine is created,
  298. which happens at import — before any connection exists to ask the server
  299. with — and ``engine`` / ``async_session`` are imported by name in ~150 places,
  300. so swapping the engine afterwards would leave stale references. The correct
  301. ceiling also depends on the worker count and on anything else sharing the
  302. server, neither of which Bambuddy can see. So this reports the mismatch with
  303. both numbers and the knobs to fix it, and leaves the choice to the operator.
  304. """
  305. global _server_connection_limits
  306. if is_sqlite():
  307. return
  308. from sqlalchemy import text
  309. in_use: int | None = None
  310. try:
  311. async with engine.connect() as conn:
  312. max_conn = int((await conn.execute(text("SHOW max_connections"))).scalar_one())
  313. reserved = int((await conn.execute(text("SHOW superuser_reserved_connections"))).scalar_one())
  314. try:
  315. in_use = int(
  316. (
  317. await conn.execute(
  318. text("SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend'")
  319. )
  320. ).scalar_one()
  321. )
  322. except Exception as exc:
  323. # `pg_stat_activity.backend_type` is PostgreSQL 10+, and a
  324. # restricted role sees fewer rows. The count is a nice-to-have
  325. # for spotting other clients; the warning itself only needs the
  326. # two settings above, so losing it must not cost the warning.
  327. # Done last on purpose: a failed statement can abort the
  328. # transaction, and nothing else uses this connection after it.
  329. logger.debug("Could not count client backends: %s", exc)
  330. except Exception as exc:
  331. # A diagnostic must never be the reason startup fails. An older server
  332. # or a restricted role may refuse these.
  333. logger.debug("Could not read PostgreSQL connection limits: %s", exc)
  334. return
  335. available = max_conn - reserved
  336. ceiling = _pool_config.get("pool_size", 0) + _pool_config.get("max_overflow", 0)
  337. _server_connection_limits = {
  338. "max_connections": max_conn,
  339. "superuser_reserved_connections": reserved,
  340. "available_to_bambuddy": available,
  341. "client_backends_at_startup": in_use,
  342. "pool_ceiling_per_worker": ceiling,
  343. }
  344. if ceiling > available:
  345. in_use_note = (
  346. f" {in_use} client connection(s) are open on the server right now, including "
  347. "this one — a count well above 1 means something else shares it."
  348. if in_use is not None
  349. else ""
  350. )
  351. logger.warning(
  352. "DB pool may exceed what PostgreSQL allows: this worker can open up to %d "
  353. "connections (pool_size %d + max_overflow %d) but the server permits %d "
  354. "(max_connections %d minus %d reserved for superusers).%s Exhaustion surfaces "
  355. "as TooManyConnectionsError at whatever ran next, not as a pool timeout. "
  356. "Lower DB_POOL_SIZE / DB_MAX_OVERFLOW, or raise the server's "
  357. "max_connections — and account for every worker process and any other "
  358. "client sharing this server.",
  359. ceiling,
  360. _pool_config.get("pool_size", 0),
  361. _pool_config.get("max_overflow", 0),
  362. available,
  363. max_conn,
  364. reserved,
  365. in_use_note,
  366. )
  367. else:
  368. logger.info(
  369. "DB pool fits the server: up to %d connection(s) per worker, %d available (max_connections %d).",
  370. ceiling,
  371. available,
  372. max_conn,
  373. )
  374. # B2: Module-level counter exposing the number of rows skipped during the last
  375. # _migrate_encrypt_legacy_secrets() invocation. Surfaced via /encryption-status
  376. # (migration_error_count) so operators can spot poison rows that need attention.
  377. _migration_error_count: int = 0
  378. def get_migration_error_count() -> int:
  379. """Return the number of rows that failed to re-encrypt during the last
  380. _migrate_encrypt_legacy_secrets() run."""
  381. return _migration_error_count
  382. async def _migrate_encrypt_legacy_secrets() -> None:
  383. """Re-encrypt OIDC ``client_secret`` and TOTP ``secret`` rows that are still
  384. stored as plaintext (no ``fernet:`` prefix).
  385. Called from :func:`init_db` after :func:`run_migrations` finishes. No-ops
  386. when no encryption key is configured (so plaintext storage stays the
  387. legacy behaviour for installs without a key).
  388. B2: per-row strategy — each row is committed in its own AsyncSession so a
  389. single corrupt row does NOT block other successful re-encryptions on every
  390. startup forever. The skipped-row count is exposed via
  391. :func:`get_migration_error_count` and surfaced on /encryption-status.
  392. B3: unexpected (non-row) failures during the read phase are re-raised so
  393. operators see the problem instead of silent data corruption — startup
  394. fails loudly rather than running with half-migrated rows.
  395. Idempotent: rows that already start with ``fernet:`` are skipped, and the
  396. write-phase re-checks the prefix before encrypting (guards against double
  397. encryption from concurrent workers).
  398. """
  399. from sqlalchemy import not_, select
  400. from backend.app.core.encryption import is_encryption_active
  401. from backend.app.models.oidc_provider import OIDCProvider
  402. from backend.app.models.user_totp import UserTOTP
  403. global _migration_error_count
  404. if not is_encryption_active():
  405. # Reset stale counter from a previous active-key run — we no longer
  406. # have any rows to migrate, so the count must not leak across runs.
  407. _migration_error_count = 0
  408. return
  409. # Phase 1 (read): collect (id, stored_value) tuples for plaintext rows.
  410. # Read phase failures are startup-fatal — re-raise (B3).
  411. try:
  412. async with async_session() as ro:
  413. oidc_rows = await ro.execute(
  414. select(OIDCProvider.id, OIDCProvider._client_secret_enc).where(
  415. not_(OIDCProvider._client_secret_enc.like("fernet:%"))
  416. )
  417. )
  418. oidc_candidates = [(r[0], r[1]) for r in oidc_rows.all()]
  419. totp_rows = await ro.execute(
  420. select(UserTOTP.id, UserTOTP._secret_enc).where(not_(UserTOTP._secret_enc.like("fernet:%")))
  421. )
  422. totp_candidates = [(r[0], r[1]) for r in totp_rows.all()]
  423. except Exception:
  424. logger.error("_migrate_encrypt_legacy_secrets: phase 1 read failed", exc_info=True)
  425. raise # B3
  426. oidc_count = totp_count = error_count = 0
  427. # Phase 2 (write): each row in its own AsyncSession + transaction.
  428. # Failure of one row does NOT block the others.
  429. for oidc_id, stored in oidc_candidates:
  430. if not stored:
  431. continue # defensive: skip empty strings
  432. try:
  433. async with async_session() as wr:
  434. provider = await wr.get(OIDCProvider, oidc_id)
  435. if provider is None:
  436. continue # row deleted between phase 1 and phase 2
  437. # Idempotent guard: re-check inside the write session in case a
  438. # concurrent worker beat us to it.
  439. if not provider._client_secret_enc.startswith("fernet:"):
  440. provider.client_secret = stored # setter -> mfa_encrypt
  441. await wr.commit()
  442. oidc_count += 1
  443. except Exception:
  444. logger.error(
  445. "Failed to re-encrypt OIDCProvider id=%s — skipping",
  446. oidc_id,
  447. exc_info=True,
  448. )
  449. error_count += 1
  450. for totp_id, stored in totp_candidates:
  451. if not stored:
  452. continue
  453. try:
  454. async with async_session() as wr:
  455. totp = await wr.get(UserTOTP, totp_id)
  456. if totp is None:
  457. continue
  458. if not totp._secret_enc.startswith("fernet:"):
  459. totp.secret = stored
  460. await wr.commit()
  461. totp_count += 1
  462. except Exception:
  463. logger.error(
  464. "Failed to re-encrypt UserTOTP id=%s — skipping",
  465. totp_id,
  466. exc_info=True,
  467. )
  468. error_count += 1
  469. _migration_error_count = error_count
  470. if oidc_count or totp_count:
  471. logger.info(
  472. "Re-encrypted legacy plaintext secrets: %d OIDC client_secret(s), %d TOTP secret(s)",
  473. oidc_count,
  474. totp_count,
  475. )
  476. elif error_count == 0:
  477. logger.debug("_migrate_encrypt_legacy_secrets: no rows needed re-encryption")
  478. if error_count:
  479. logger.error(
  480. "_migrate_encrypt_legacy_secrets: %d row(s) skipped due to errors. "
  481. "See /api/v1/auth/encryption-status (migration_error_count).",
  482. error_count,
  483. )
  484. async def _safe_execute(conn, sql):
  485. """Execute a DDL migration statement, silently ignoring idempotency errors.
  486. 'already exists', 'duplicate column name' (SQLite ADD COLUMN), 'no such column'
  487. (SQLite RENAME COLUMN), 'duplicate key', and the compound
  488. 'column … does not exist' (PostgreSQL RENAME COLUMN idempotency) are swallowed
  489. so that re-running DDL migrations is safe. The compound check additionally
  490. requires the SQL to be a RENAME COLUMN statement so that "does not exist" errors
  491. from ADD COLUMN or CREATE INDEX (which would indicate schema corruption, not
  492. idempotency) are never silently swallowed.
  493. Any other error is logged and re-raised — callers must not assume silent
  494. recovery, as a failure will abort the migration sequence and prevent
  495. application startup.
  496. Only use for DDL statements (ALTER TABLE, CREATE INDEX, etc.).
  497. For DML backfills (UPDATE, DELETE) use conn.execute() directly inside
  498. async with conn.begin_nested() so failures are never silently swallowed.
  499. Uses a savepoint so that a failed statement doesn't poison the surrounding
  500. transaction (required for PostgreSQL).
  501. """
  502. from sqlalchemy import text
  503. try:
  504. async with conn.begin_nested():
  505. await conn.execute(text(sql))
  506. except (OperationalError, ProgrammingError) as exc:
  507. msg = str(exc).lower()
  508. # Only swallow "column … does not exist" for RENAME COLUMN — not for ADD COLUMN
  509. # or CREATE INDEX where it would indicate schema corruption, not idempotency.
  510. column_not_exists = "rename column" in sql.lower() and "column" in msg and "does not exist" in msg
  511. if (
  512. not any(k in msg for k in ("already exists", "duplicate key", "duplicate column name", "no such column"))
  513. and not column_not_exists
  514. ):
  515. logger.error("Migration statement failed: %s | SQL: %.200s", exc, sql)
  516. raise
  517. async def _api_keys_column_exists(conn, column_name: str) -> bool:
  518. """Return True if the named column exists on ``api_keys``.
  519. Used to gate one-shot data backfills that must run only on the migration
  520. that adds a column — without this, repeating the UPDATE on every startup
  521. would silently overwrite values the user later edited in the UI.
  522. Dialect-specific because SQLite has no information_schema.
  523. """
  524. from sqlalchemy import text
  525. if is_sqlite():
  526. result = await conn.execute(text("PRAGMA table_info(api_keys)"))
  527. return any(row[1] == column_name for row in result)
  528. result = await conn.execute(
  529. text("SELECT 1 FROM information_schema.columns WHERE table_name = 'api_keys' AND column_name = :col"),
  530. {"col": column_name},
  531. )
  532. return result.scalar_one_or_none() is not None
  533. async def _migrate_normalize_printer_ids(conn) -> None:
  534. from sqlalchemy import text
  535. async with conn.begin_nested():
  536. if is_sqlite():
  537. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids = '[]'"))
  538. else:
  539. await conn.execute(text("UPDATE api_keys SET printer_ids = NULL WHERE printer_ids::text = '[]'"))
  540. async def _migrate_scope_force_color_overrides_to_plate(conn) -> None:
  541. """Re-scope queue items that carry another plate's filament overrides (#2551).
  542. Queueing several plates of one 3MF used to store the union of every selected
  543. plate's overrides on each item, so a ``force_color_match`` plate printing one
  544. colour sat at Waiting until a printer had the whole batch's palette loaded.
  545. The write paths now narrow to the plate, but items queued before the fix would
  546. stay stuck until the user deleted and re-added them by hand — with a waiting
  547. reason that gives no hint as to why. Repair them here instead.
  548. Only pending items are touched: a printing or finished item's overrides are a
  549. record of what it dispatched with, not an instruction. An item whose plate we
  550. cannot read keeps every override, per ``overrides_for_plate``. Idempotent —
  551. an already-scoped item narrows to itself and is not rewritten.
  552. """
  553. import json
  554. from pathlib import Path
  555. from sqlalchemy import text
  556. from backend.app.services.filament_requirements import overrides_for_plate
  557. rows = (
  558. await conn.execute(
  559. text(
  560. "SELECT q.id, q.plate_id, q.filament_overrides, "
  561. "a.file_path AS archive_path, l.file_path AS library_path "
  562. "FROM print_queue q "
  563. "LEFT JOIN print_archives a ON a.id = q.archive_id "
  564. "LEFT JOIN library_files l ON l.id = q.library_file_id "
  565. "WHERE q.status = 'pending' "
  566. "AND q.plate_id IS NOT NULL "
  567. "AND q.filament_overrides IS NOT NULL"
  568. )
  569. )
  570. ).fetchall()
  571. repaired = 0
  572. for row in rows:
  573. try:
  574. overrides = json.loads(row.filament_overrides)
  575. except (json.JSONDecodeError, TypeError):
  576. continue
  577. if not isinstance(overrides, list) or not overrides:
  578. continue
  579. stored_path = row.archive_path or row.library_path
  580. if not stored_path:
  581. continue
  582. path = Path(stored_path)
  583. if not path.is_absolute():
  584. path = settings.base_dir / stored_path
  585. scoped = overrides_for_plate(overrides, path, row.plate_id)
  586. if len(scoped) == len(overrides):
  587. continue
  588. async with conn.begin_nested():
  589. await conn.execute(
  590. text("UPDATE print_queue SET filament_overrides = :overrides WHERE id = :id"),
  591. {"overrides": json.dumps(scoped) if scoped else None, "id": row.id},
  592. )
  593. repaired += 1
  594. if repaired:
  595. logger.info(
  596. "Re-scoped the filament overrides of %d queued item(s) to the plate they print (#2551)",
  597. repaired,
  598. )
  599. async def _migrate_scope_run_filament_to_plate(conn) -> None:
  600. """Repair completed print-log rows that stored a multi-plate 3MF's whole-file
  601. filament (and cost) instead of the printed plate's (#2614).
  602. When the AMS tracker measured nothing for a completed run, the per-run filament
  603. fell back to ``PrintArchive.filament_used_grams`` — the sum over EVERY plate of
  604. the source 3MF (right for the archive card / project rollup, wrong for one
  605. printed plate). So each printed plate of a 22-plate file logged the full ~12 kg,
  606. inflating lifetime / user / project / filament stats by the plate count. The
  607. forward fix scopes new rows; this repairs the rows already written.
  608. Only completed rows whose stored grams EXACTLY equal the archive's whole-file
  609. value are touched — that is the mis-copy signature. Tracker-measured rows (a
  610. rounded spool-delta sum) and partial-progress rows (scaled to progress) never
  611. match, so they are never clobbered. Cost is scaled by the plate's share of the
  612. whole so it stays consistent with the corrected grams. Runs AFTER the #2603
  613. archive plate_id backfill so ``print_archives.plate_id`` is populated.
  614. Gated to run **exactly once** via a settings flag. This is not merely for
  615. idempotency: a genuine single-plate print carries a ``plate_id`` too (the UI
  616. always sends one), and for it the plate estimate legitimately equals the
  617. whole-file value — so those rows match the signature on every boot. Without
  618. the one-shot gate we would re-parse every single-plate 3MF on the print log at
  619. each startup, a cost that grows without bound with print history. One pass is
  620. enough: the forward fix keeps all new rows correct.
  621. """
  622. from pathlib import Path
  623. from sqlalchemy import text
  624. from backend.app.utils.threemf_tools import extract_plate_metadata_from_3mf
  625. flag = "_backfill_2614_plate_filament_done"
  626. async with conn.begin_nested():
  627. already = (
  628. await conn.execute(text('SELECT value FROM settings WHERE "key" = :k'), {"k": flag})
  629. ).scalar_one_or_none()
  630. if already:
  631. return
  632. rows = (
  633. await conn.execute(
  634. text(
  635. "SELECT ple.id AS entry_id, ple.filament_used_grams AS grams, ple.cost AS cost, "
  636. "a.plate_id AS plate_id, a.filament_used_grams AS whole_grams, a.file_path AS file_path "
  637. "FROM print_log_entries ple "
  638. "JOIN print_archives a ON a.id = ple.archive_id "
  639. "WHERE ple.status = 'completed' "
  640. "AND a.plate_id IS NOT NULL "
  641. "AND a.file_path IS NOT NULL "
  642. "AND a.filament_used_grams IS NOT NULL "
  643. "AND ple.filament_used_grams IS NOT NULL "
  644. "AND ple.filament_used_grams = a.filament_used_grams"
  645. )
  646. )
  647. ).fetchall()
  648. corrected = 0
  649. grams_removed = 0.0
  650. for row in rows:
  651. path = Path(row.file_path)
  652. if not path.is_absolute():
  653. path = settings.base_dir / row.file_path
  654. if not path.exists():
  655. continue
  656. try:
  657. plate_grams = extract_plate_metadata_from_3mf(path, row.plate_id).filament_used_grams
  658. except Exception as exc:
  659. logger.warning(
  660. "[#2614] could not read plate %s of %s for log entry %s: %s",
  661. row.plate_id,
  662. row.file_path,
  663. row.entry_id,
  664. exc,
  665. )
  666. continue
  667. if not plate_grams or plate_grams <= 0:
  668. continue
  669. new_grams = round(plate_grams, 2)
  670. if abs(new_grams - (row.grams or 0)) < 0.01:
  671. continue # nothing to change (e.g. a genuine single-plate file)
  672. new_cost = row.cost
  673. whole = row.whole_grams or 0
  674. if row.cost and whole > 0:
  675. new_cost = round(row.cost * (plate_grams / whole), 2)
  676. await conn.execute(
  677. text("UPDATE print_log_entries SET filament_used_grams = :g, cost = :c WHERE id = :id"),
  678. {"g": new_grams, "c": new_cost, "id": row.entry_id},
  679. )
  680. corrected += 1
  681. grams_removed += (row.grams or 0) - new_grams
  682. if corrected:
  683. logger.info(
  684. "[#2614] Re-scoped %d completed print-log row(s) from whole-file to plate filament "
  685. "(removed %.0f g of over-counted usage from statistics)",
  686. corrected,
  687. grams_removed,
  688. )
  689. # Mark done unconditionally (even when nothing matched) so this one-shot
  690. # never re-scans the print log on subsequent boots. id/timestamps come
  691. # from the table's own defaults; "key" is quoted as it's a keyword.
  692. await conn.execute(
  693. text('INSERT INTO settings ("key", value) VALUES (:k, :v)'),
  694. {"k": flag, "v": "true"},
  695. )
  696. async def _migrate_drop_library_print_name(conn) -> None:
  697. """Strip the embedded 3MF Title (``print_name``) from library file metadata (#1489).
  698. Library files stored the 3MF's ``<metadata name="Title">`` as
  699. ``file_metadata.print_name`` — generic ("Exported 3D Model") for Bambu
  700. Studio exports, a marketing title for MakerWorld downloads — and the
  701. FileManager wrongly preferred it over the filename for the card label,
  702. search and sort. New imports no longer store it; this clears it from rows
  703. imported before the fix so existing libraries don't need a rename
  704. round-trip. Idempotent — rows without the key are untouched.
  705. """
  706. from sqlalchemy import text
  707. async with conn.begin_nested():
  708. if is_sqlite():
  709. await conn.execute(
  710. text(
  711. "UPDATE library_files SET file_metadata = json_remove(file_metadata, '$.print_name') "
  712. "WHERE json_extract(file_metadata, '$.print_name') IS NOT NULL"
  713. )
  714. )
  715. else:
  716. # file_metadata is a JSON (not JSONB) column — cast to jsonb for the
  717. # key-exists test (jsonb_exists, avoiding the `?` operator which
  718. # clashes with driver parameter syntax) and the `- key` removal.
  719. await conn.execute(
  720. text(
  721. "UPDATE library_files SET file_metadata = (file_metadata::jsonb - 'print_name')::json "
  722. "WHERE jsonb_exists(file_metadata::jsonb, 'print_name')"
  723. )
  724. )
  725. async def _migrate_update_auto_link_constraint(conn) -> None:
  726. """Update the auto_link CHECK constraint to allow Fall C (custom email claim).
  727. Old formula: auto_link = FALSE OR (require_ev = TRUE AND email_claim = 'email')
  728. New formula: auto_link = FALSE OR email_claim != 'email' OR require_ev = TRUE
  729. Only Fall B (email_claim='email' + require_ev=False) remains blocked.
  730. Fall C (custom claim, e.g. Azure preferred_username/upn) is now allowed.
  731. PostgreSQL: DROP CONSTRAINT IF EXISTS + ADD new formula via _safe_execute (idempotent).
  732. SQLite: table recreation when old formula is detected in sqlite_master (idempotent).
  733. """
  734. from sqlalchemy import text
  735. _NEW_FORMULA = "auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE"
  736. _CONSTRAINT_NAME = "ck_auto_link_requires_verified_email_claim"
  737. if not is_sqlite():
  738. await _safe_execute(conn, f"ALTER TABLE oidc_providers DROP CONSTRAINT IF EXISTS {_CONSTRAINT_NAME}")
  739. await _safe_execute(
  740. conn,
  741. f"ALTER TABLE oidc_providers ADD CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})",
  742. )
  743. else:
  744. row = (
  745. await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='oidc_providers'"))
  746. ).fetchone()
  747. # Only recreate if the old (more restrictive) formula is still present.
  748. # Fresh installs created with the new __table_args__ already have the correct formula.
  749. # Installs without any constraint (pre-SEC-1 upgrades) are skipped — app-level guards suffice.
  750. if row and "require_email_verified = TRUE AND email_claim = 'email'" in row[0]:
  751. try:
  752. async with conn.begin_nested():
  753. await conn.execute(text("DROP TABLE IF EXISTS oidc_providers_v2"))
  754. await conn.execute(
  755. text(
  756. "CREATE TABLE oidc_providers_v2 ("
  757. "id INTEGER NOT NULL, "
  758. "name VARCHAR(100) NOT NULL, "
  759. "issuer_url VARCHAR(500) NOT NULL, "
  760. "client_id VARCHAR(255) NOT NULL, "
  761. "client_secret VARCHAR(512) NOT NULL, "
  762. "scopes VARCHAR(500), "
  763. "is_enabled BOOLEAN, "
  764. "auto_create_users BOOLEAN, "
  765. "auto_link_existing_accounts BOOLEAN DEFAULT 0, "
  766. "email_claim VARCHAR(64) DEFAULT 'email', "
  767. "require_email_verified BOOLEAN DEFAULT 1, "
  768. "icon_url TEXT, "
  769. "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  770. "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
  771. "PRIMARY KEY (id), "
  772. f"UNIQUE (name), "
  773. f"CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})"
  774. ")"
  775. )
  776. )
  777. await conn.execute(
  778. text(
  779. "INSERT INTO oidc_providers_v2 "
  780. "(id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  781. "auto_create_users, auto_link_existing_accounts, email_claim, "
  782. "require_email_verified, icon_url, created_at, updated_at) "
  783. "SELECT id, name, issuer_url, client_id, client_secret, scopes, is_enabled, "
  784. "auto_create_users, auto_link_existing_accounts, email_claim, "
  785. "require_email_verified, icon_url, created_at, updated_at "
  786. "FROM oidc_providers"
  787. )
  788. )
  789. original = (await conn.execute(text("SELECT count(*) FROM oidc_providers"))).scalar_one()
  790. copied = (await conn.execute(text("SELECT count(*) FROM oidc_providers_v2"))).scalar_one()
  791. if copied != original:
  792. raise RuntimeError(
  793. f"auto_link constraint migration: row count mismatch after copy "
  794. f"({original} in source, {copied} in copy)"
  795. )
  796. await conn.execute(text("DROP TABLE oidc_providers"))
  797. await conn.execute(text("ALTER TABLE oidc_providers_v2 RENAME TO oidc_providers"))
  798. except Exception as exc:
  799. logger.error(
  800. "auto_link constraint update (SQLite table recreation) FAILED: %s",
  801. exc,
  802. exc_info=True,
  803. )
  804. raise
  805. async def _migrate_widen_spoolman_slot_ams_id_range(conn) -> None:
  806. """Widen ck_ams_id_range on spoolman_slot_assignments to admit AMS-HT (#1274).
  807. Old formula: (ams_id >= 0 AND ams_id <= 7) OR ams_id = 255
  808. New formula: (ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255
  809. The H2C/H2D AMS-HT reports ams_id 128+. The old constraint rejected every
  810. AMS-HT slot link with `IntegrityError: CHECK constraint failed: ck_ams_id_range`.
  811. PostgreSQL: DROP CONSTRAINT IF EXISTS + ADD new formula via _safe_execute.
  812. SQLite: table recreation when the old (narrower) formula is detected in
  813. sqlite_master. Fresh installs already have the widened constraint from
  814. the CREATE TABLE migration above.
  815. """
  816. from sqlalchemy import text
  817. _NEW_FORMULA = "(ams_id >= 0 AND ams_id <= 7) OR (ams_id >= 128 AND ams_id <= 191) OR ams_id = 255"
  818. _CONSTRAINT_NAME = "ck_ams_id_range"
  819. if not is_sqlite():
  820. await _safe_execute(
  821. conn,
  822. f"ALTER TABLE spoolman_slot_assignments DROP CONSTRAINT IF EXISTS {_CONSTRAINT_NAME}",
  823. )
  824. await _safe_execute(
  825. conn,
  826. f"ALTER TABLE spoolman_slot_assignments ADD CONSTRAINT {_CONSTRAINT_NAME} CHECK ({_NEW_FORMULA})",
  827. )
  828. return
  829. row = (
  830. await conn.execute(
  831. text("SELECT sql FROM sqlite_master WHERE type='table' AND name='spoolman_slot_assignments'")
  832. )
  833. ).fetchone()
  834. if not row:
  835. return
  836. sql = row[0] or ""
  837. # Already widened by an earlier run or by the fresh-install CREATE TABLE above.
  838. if "ams_id >= 128" in sql:
  839. return
  840. # Pre-migration table without any CHECK constraint at all → leave alone;
  841. # the app-level validation handles correctness and we don't risk a
  842. # destructive table rebuild for a constraint that isn't blocking anyone.
  843. if "ck_ams_id_range" not in sql and "ams_id <= 7" not in sql:
  844. return
  845. try:
  846. async with conn.begin_nested():
  847. await conn.execute(text("DROP TABLE IF EXISTS spoolman_slot_assignments_v2"))
  848. await conn.execute(
  849. text(
  850. "CREATE TABLE spoolman_slot_assignments_v2 ("
  851. "id INTEGER PRIMARY KEY AUTOINCREMENT, "
  852. "printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE, "
  853. f"ams_id INTEGER NOT NULL CHECK ({_NEW_FORMULA}), "
  854. "tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3), "
  855. "spoolman_spool_id INTEGER NOT NULL, "
  856. "assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "
  857. "CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)"
  858. ")"
  859. )
  860. )
  861. await conn.execute(
  862. text(
  863. "INSERT INTO spoolman_slot_assignments_v2 "
  864. "(id, printer_id, ams_id, tray_id, spoolman_spool_id, assigned_at) "
  865. "SELECT id, printer_id, ams_id, tray_id, spoolman_spool_id, assigned_at "
  866. "FROM spoolman_slot_assignments"
  867. )
  868. )
  869. original = (await conn.execute(text("SELECT count(*) FROM spoolman_slot_assignments"))).scalar_one()
  870. copied = (await conn.execute(text("SELECT count(*) FROM spoolman_slot_assignments_v2"))).scalar_one()
  871. if copied != original:
  872. raise RuntimeError(
  873. f"spoolman_slot_assignments migration: row count mismatch after copy "
  874. f"({original} in source, {copied} in copy)"
  875. )
  876. await conn.execute(text("DROP TABLE spoolman_slot_assignments"))
  877. await conn.execute(text("ALTER TABLE spoolman_slot_assignments_v2 RENAME TO spoolman_slot_assignments"))
  878. # The index sits on the renamed table; recreate it idempotently
  879. # to handle older sqlite versions that don't auto-rename indexes.
  880. await conn.execute(
  881. text(
  882. "CREATE INDEX IF NOT EXISTS ix_slot_assignment_spool "
  883. "ON spoolman_slot_assignments (spoolman_spool_id)"
  884. )
  885. )
  886. except Exception as exc:
  887. logger.error(
  888. "spoolman_slot_assignments ck_ams_id_range widening (SQLite table recreation) FAILED: %s",
  889. exc,
  890. exc_info=True,
  891. )
  892. raise
  893. async def run_migrations(conn):
  894. """Run all schema migrations and data backfills on startup.
  895. Includes ALTER TABLE (add columns, rename columns, add constraints),
  896. CREATE INDEX, CREATE TRIGGER, data UPDATE backfills, and table recreations
  897. for complex SQLite schema changes that ALTER TABLE cannot handle.
  898. DDL statements are wrapped in _safe_execute for idempotency.
  899. DML backfills (UPDATE/DELETE) are executed directly via conn.execute()
  900. inside begin_nested() so any failure is always fatal and never silently
  901. swallowed.
  902. """
  903. from sqlalchemy import text
  904. # Migration: Add parent_run_id column to pipeline_runs (#1425 PR C).
  905. # Links a retry-failed run back to its parent so the dashboard can show
  906. # "Retry of run #N" inline. Idempotent on both SQLite and Postgres.
  907. await _safe_execute(
  908. conn,
  909. "ALTER TABLE pipeline_runs ADD COLUMN parent_run_id INTEGER REFERENCES pipeline_runs(id) ON DELETE SET NULL",
  910. )
  911. # Migration: Add source_archive_id column to pipeline_runs (#1425 PR B follow-up).
  912. # Allows a pipeline run to source from an archive's source 3MF in addition
  913. # to a library file. Idempotent — _safe_execute swallows the "already exists"
  914. # case on both SQLite and Postgres.
  915. await _safe_execute(
  916. conn,
  917. "ALTER TABLE pipeline_runs ADD COLUMN source_archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL",
  918. )
  919. # Migration: Add is_favorite column to print_archives
  920. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0")
  921. # Migration: Add content_hash column to print_archives for duplicate detection
  922. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)")
  923. # Migration: Add auto_off_executed column to smart_plugs
  924. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0")
  925. # Migration: Add on_print_stopped column to notification_providers
  926. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1")
  927. # Migration: Add source_3mf_path column to print_archives
  928. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)")
  929. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  930. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)")
  931. # Migration: Add plate_id column to print_archives (#2603). The selected plate
  932. # of a multi-plate 3MF is copied from the queue item at dispatch so Print
  933. # History can show the actual plate instead of falling back to Plate 1.
  934. # Nullable, no default — identical DDL on SQLite and Postgres. Backfilled from
  935. # linked queue rows below.
  936. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN plate_id INTEGER")
  937. # Migration: Add on_maintenance_due column to notification_providers
  938. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0")
  939. # Migration: Add location column to printers for grouping
  940. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN location VARCHAR(100)")
  941. # Migration: Add interval_type column to maintenance_types
  942. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'")
  943. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  944. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0")
  945. # Migration: Add custom_interval_type column to printer_maintenance
  946. await _safe_execute(conn, "ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)")
  947. # Migration: Add power alert columns to smart_plugs
  948. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0")
  949. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL")
  950. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL")
  951. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME")
  952. # Migration: Add schedule columns to smart_plugs
  953. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0")
  954. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)")
  955. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)")
  956. # Migration: Add daily digest columns to notification_providers
  957. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0")
  958. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)")
  959. # Migration: Add missing-spool-assignment print-start notification toggle
  960. try:
  961. async with conn.begin_nested():
  962. await conn.execute(
  963. text(
  964. "ALTER TABLE notification_providers ADD COLUMN on_print_missing_spool_assignment BOOLEAN DEFAULT 0"
  965. )
  966. )
  967. except (OperationalError, ProgrammingError):
  968. pass # Already applied
  969. # Migration: Add project_id column to print_archives
  970. try:
  971. async with conn.begin_nested():
  972. await conn.execute(
  973. text(
  974. "ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  975. )
  976. )
  977. except (OperationalError, ProgrammingError):
  978. pass # Already applied
  979. # Migration: Add project_id column to print_queue
  980. try:
  981. async with conn.begin_nested():
  982. await conn.execute(
  983. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  984. )
  985. except (OperationalError, ProgrammingError):
  986. pass # Already applied
  987. # Migration: Enforce uniqueness on user_oidc_links for existing rows.
  988. # create_all() is idempotent and does not add constraints to existing tables,
  989. # so we create covering unique indexes explicitly here.
  990. await _safe_execute(
  991. conn,
  992. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_provider_sub"
  993. " ON user_oidc_links (provider_id, provider_user_id)",
  994. )
  995. await _safe_execute(
  996. conn,
  997. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_user_provider ON user_oidc_links (user_id, provider_id)",
  998. )
  999. # Migration: Create FTS5 virtual table for archive full-text search (SQLite only)
  1000. # PostgreSQL uses tsvector + GIN index instead (set up in archives.py search route)
  1001. if is_sqlite():
  1002. try:
  1003. await conn.execute(
  1004. text("""
  1005. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  1006. print_name,
  1007. filename,
  1008. tags,
  1009. notes,
  1010. designer,
  1011. filament_type,
  1012. content='print_archives',
  1013. content_rowid='id'
  1014. )
  1015. """)
  1016. )
  1017. except (OperationalError, ProgrammingError):
  1018. pass # Already applied
  1019. # Migration: Create triggers to keep FTS index in sync
  1020. try:
  1021. await conn.execute(
  1022. text("""
  1023. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  1024. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  1025. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  1026. END
  1027. """)
  1028. )
  1029. except (OperationalError, ProgrammingError):
  1030. pass # Already applied
  1031. try:
  1032. await conn.execute(
  1033. text("""
  1034. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  1035. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  1036. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  1037. END
  1038. """)
  1039. )
  1040. except (OperationalError, ProgrammingError):
  1041. pass # Already applied
  1042. try:
  1043. await conn.execute(
  1044. text("""
  1045. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  1046. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  1047. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  1048. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  1049. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  1050. END
  1051. """)
  1052. )
  1053. except (OperationalError, ProgrammingError):
  1054. pass # Already applied
  1055. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  1056. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0")
  1057. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME")
  1058. # Migration: Add auto_off_persistent column to smart_plugs (keep auto-off enabled between prints)
  1059. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_persistent BOOLEAN DEFAULT 0")
  1060. # Migration: Add AMS alarm notification columns to notification_providers
  1061. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0")
  1062. try:
  1063. async with conn.begin_nested():
  1064. await conn.execute(
  1065. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  1066. )
  1067. except (OperationalError, ProgrammingError):
  1068. pass # Already applied
  1069. # Migration: Add AMS-HT alarm notification columns to notification_providers
  1070. try:
  1071. async with conn.begin_nested():
  1072. await conn.execute(
  1073. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  1074. )
  1075. except (OperationalError, ProgrammingError):
  1076. pass # Already applied
  1077. try:
  1078. async with conn.begin_nested():
  1079. await conn.execute(
  1080. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  1081. )
  1082. except (OperationalError, ProgrammingError):
  1083. pass # Already applied
  1084. # Migration: Add plate not empty notification column to notification_providers
  1085. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1")
  1086. # Migration: Add notes column to projects (Phase 2)
  1087. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN notes TEXT")
  1088. # Migration: Add attachments column to projects (Phase 3)
  1089. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN attachments JSON")
  1090. # Migration: Add tags column to projects (Phase 4)
  1091. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN tags TEXT")
  1092. # Migration: Add due_date column to projects (Phase 5)
  1093. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN due_date DATETIME")
  1094. # Migration: Add priority column to projects (Phase 5)
  1095. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'")
  1096. # Migration: Add budget column to projects (Phase 6)
  1097. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN budget REAL")
  1098. # Migration: Add is_template column to projects (Phase 8)
  1099. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0")
  1100. # Migration: Add template_source_id column to projects (Phase 8)
  1101. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN template_source_id INTEGER")
  1102. # Migration: Add parent_id column to projects (Phase 10)
  1103. try:
  1104. async with conn.begin_nested():
  1105. await conn.execute(
  1106. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  1107. )
  1108. except (OperationalError, ProgrammingError):
  1109. pass # Already applied
  1110. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  1111. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired")
  1112. # Migration: Add unit_price column to project_bom_items
  1113. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN unit_price REAL")
  1114. # Migration: Add sourcing_url column to project_bom_items
  1115. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)")
  1116. # Migration: Rename notes to remarks in project_bom_items
  1117. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks")
  1118. # Migration: Add show_in_switchbar column to smart_plugs
  1119. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0")
  1120. # Migration: Add runtime tracking columns to printers
  1121. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0")
  1122. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME")
  1123. # Migration: Add quantity column to print_archives for tracking item count
  1124. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1")
  1125. # Migration: Add manual_start column to print_queue for staged prints
  1126. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0")
  1127. # Migration: Add wiki_url column to maintenance_types for documentation links
  1128. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)")
  1129. # Migration: Add tailscale_disabled column to virtual_printers. Opt-in: default TRUE so
  1130. # the auto-detect + fallback noise only runs for users who explicitly enable it.
  1131. # Postgres rejects `DEFAULT 1` for BOOLEAN (#1070 round-2 review).
  1132. if is_sqlite():
  1133. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT 1")
  1134. else:
  1135. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT true")
  1136. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  1137. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT")
  1138. # Migration: filament_short flag on print_queue (#1496). Set by the
  1139. # dispatch scheduler when the assigned spool can't satisfy the print's
  1140. # per-slot weight; surfaced as a "filament short" badge on the queue row.
  1141. # Postgres rejects `DEFAULT 0` for BOOLEAN — branch on dialect.
  1142. if is_sqlite():
  1143. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_short BOOLEAN DEFAULT 0")
  1144. else:
  1145. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_short BOOLEAN DEFAULT false")
  1146. # Migration: skip_filament_check flag on print_queue (#1698-followup).
  1147. # Persists the user's "Print Anyway" acknowledgement so the scheduler
  1148. # doesn't re-flag the item every tick after they've confirmed dispatch
  1149. # despite the deficit warning. Set from the start route's skip_filament_check
  1150. # query param and from PrintModal at queue-creation time. Postgres / SQLite
  1151. # boolean default branch matches filament_short above.
  1152. if is_sqlite():
  1153. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN skip_filament_check BOOLEAN DEFAULT 0")
  1154. else:
  1155. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN skip_filament_check BOOLEAN DEFAULT false")
  1156. # Migration: cleanup flag for transient printer-card uploads routed through
  1157. # the scheduler. The archive copy is durable; the library row/file can be
  1158. # deleted after dispatch.
  1159. if is_sqlite():
  1160. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN cleanup_library_after_dispatch BOOLEAN DEFAULT 0")
  1161. else:
  1162. await _safe_execute(
  1163. conn, "ALTER TABLE print_queue ADD COLUMN cleanup_library_after_dispatch BOOLEAN DEFAULT false"
  1164. )
  1165. # Migration: Add queue_force_color_match column to virtual_printers (#1188).
  1166. # Opt-in flag: when true, VP queue-mode uploads pin the per-slot type+color
  1167. # from the 3MF onto the queue item's filament_overrides so the scheduler
  1168. # refuses to dispatch onto a printer with the wrong filament loaded.
  1169. # Default false to preserve current behaviour for upgraders.
  1170. if is_sqlite():
  1171. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT 0")
  1172. else:
  1173. await _safe_execute(
  1174. conn, "ALTER TABLE virtual_printers ADD COLUMN queue_force_color_match BOOLEAN DEFAULT FALSE"
  1175. )
  1176. # Migration: Add save_ams_mapping column to virtual_printers. Opt-in flag:
  1177. # when true, VP queue-mode uploads persist the slicer's own AMS-slot pick
  1178. # onto the archive (`extra_data.slicer_ams_mapping`) for reuse on reprint.
  1179. # Default false to preserve current behaviour for upgraders.
  1180. if is_sqlite():
  1181. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN save_ams_mapping BOOLEAN DEFAULT 0")
  1182. else:
  1183. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN save_ams_mapping BOOLEAN DEFAULT FALSE")
  1184. # Per-VP opt-in for auto-print G-code injection (#1516). Default false so
  1185. # existing gcode_snippets users don't silently start injecting on VP/Studio
  1186. # Send jobs after upgrading.
  1187. if is_sqlite():
  1188. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN gcode_injection BOOLEAN DEFAULT 0")
  1189. else:
  1190. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE")
  1191. # Migration: nozzle_mapping + nozzles_info on print_queue for H2C rack-swap
  1192. # slicer-pick preservation (#1780). Opaque JSON-string column carrying
  1193. # BambuStudio's per-filament physical nozzle position IDs, forwarded
  1194. # straight from the VP intake to the dispatcher's project_file MQTT
  1195. # command. NULL on every other model. Nullable TEXT — no Postgres / SQLite
  1196. # divergence here. `nozzles_info` shipped in the original #1780 attempt
  1197. # but BambuStudio never actually sends it (verified via wire capture on
  1198. # H2C, see CHANGELOG 0.2.5b1) — the column stays nullable so old rows
  1199. # still load; nothing reads or writes to it anymore.
  1200. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_mapping TEXT")
  1201. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzles_info TEXT")
  1202. # Migration: Add target_parts_count column to projects for tracking total parts needed
  1203. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_parts_count INTEGER")
  1204. # Migration: Add url + cover_image_filename columns to projects (#1155).
  1205. # url: external link rendered next to the project name on the card.
  1206. # cover_image_filename: filename of the project's hero image inside the
  1207. # existing attachments dir; rendered as a thumbnail on the card.
  1208. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN url VARCHAR(2048)")
  1209. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN cover_image_filename VARCHAR(255)")
  1210. # Migration: enhanced filament colour handling on color_catalog (#1154).
  1211. # Mirrors the Spool columns added below; widens hex_color to VARCHAR(9)
  1212. # so catalog entries can store an alpha component (#RRGGBBAA). SQLite
  1213. # ignores VARCHAR length, so the widen only matters on PostgreSQL.
  1214. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN extra_colors VARCHAR(255)")
  1215. await _safe_execute(conn, "ALTER TABLE color_catalog ADD COLUMN effect_type VARCHAR(20)")
  1216. if not is_sqlite():
  1217. await _safe_execute(conn, "ALTER TABLE color_catalog ALTER COLUMN hex_color TYPE VARCHAR(9)")
  1218. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  1219. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  1220. # PostgreSQL gets the correct schema from create_all(), so skip this
  1221. if is_sqlite():
  1222. try:
  1223. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  1224. row = result.fetchone()
  1225. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  1226. await conn.execute(
  1227. text("""
  1228. CREATE TABLE print_queue_new (
  1229. id INTEGER PRIMARY KEY,
  1230. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  1231. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1232. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  1233. position INTEGER DEFAULT 0,
  1234. scheduled_time DATETIME,
  1235. manual_start BOOLEAN DEFAULT 0,
  1236. require_previous_success BOOLEAN DEFAULT 0,
  1237. auto_off_after BOOLEAN DEFAULT 0,
  1238. ams_mapping TEXT,
  1239. status VARCHAR(20) DEFAULT 'pending',
  1240. started_at DATETIME,
  1241. completed_at DATETIME,
  1242. error_message TEXT,
  1243. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  1244. )
  1245. """)
  1246. )
  1247. await conn.execute(
  1248. text("""
  1249. INSERT INTO print_queue_new
  1250. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  1251. manual_start, require_previous_success, auto_off_after, ams_mapping,
  1252. status, started_at, completed_at, error_message, created_at
  1253. FROM print_queue
  1254. """)
  1255. )
  1256. await conn.execute(text("DROP TABLE print_queue"))
  1257. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  1258. except (OperationalError, ProgrammingError):
  1259. pass # Already applied
  1260. # Migration: Add plug_type column to smart_plugs for HA integration
  1261. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'")
  1262. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  1263. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)")
  1264. # Migration: Add project_id column to library_folders for linking folders to projects
  1265. try:
  1266. async with conn.begin_nested():
  1267. await conn.execute(
  1268. text(
  1269. "ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  1270. )
  1271. )
  1272. except (OperationalError, ProgrammingError):
  1273. pass # Already applied
  1274. # Migration: Add archive_id column to library_folders for linking folders to archives
  1275. try:
  1276. async with conn.begin_nested():
  1277. await conn.execute(
  1278. text(
  1279. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  1280. )
  1281. )
  1282. except (OperationalError, ProgrammingError):
  1283. pass # Already applied
  1284. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  1285. # PostgreSQL gets the correct schema from create_all(), so skip this
  1286. if is_sqlite():
  1287. try:
  1288. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  1289. row = result.fetchone()
  1290. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  1291. await conn.execute(
  1292. text("""
  1293. CREATE TABLE smart_plugs_new (
  1294. id INTEGER PRIMARY KEY,
  1295. name VARCHAR(100) NOT NULL,
  1296. ip_address VARCHAR(45),
  1297. plug_type VARCHAR(20) DEFAULT 'tasmota',
  1298. ha_entity_id VARCHAR(100),
  1299. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  1300. enabled BOOLEAN NOT NULL DEFAULT 1,
  1301. auto_on BOOLEAN NOT NULL DEFAULT 1,
  1302. auto_off BOOLEAN NOT NULL DEFAULT 1,
  1303. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  1304. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  1305. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  1306. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  1307. username VARCHAR(50),
  1308. password VARCHAR(100),
  1309. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  1310. power_alert_high FLOAT,
  1311. power_alert_low FLOAT,
  1312. power_alert_last_triggered DATETIME,
  1313. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  1314. schedule_on_time VARCHAR(5),
  1315. schedule_off_time VARCHAR(5),
  1316. show_in_switchbar BOOLEAN DEFAULT 0,
  1317. last_state VARCHAR(10),
  1318. last_checked DATETIME,
  1319. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  1320. auto_off_pending BOOLEAN DEFAULT 0,
  1321. auto_off_pending_since DATETIME,
  1322. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  1323. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  1324. )
  1325. """)
  1326. )
  1327. await conn.execute(
  1328. text("""
  1329. INSERT INTO smart_plugs_new
  1330. SELECT id, name, ip_address,
  1331. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  1332. enabled, auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  1333. off_delay_mode, off_delay_minutes, off_temp_threshold,
  1334. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  1335. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  1336. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  1337. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  1338. FROM smart_plugs
  1339. """)
  1340. )
  1341. await conn.execute(text("DROP TABLE smart_plugs"))
  1342. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  1343. except (OperationalError, ProgrammingError):
  1344. pass # Already applied
  1345. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  1346. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN plate_id INTEGER")
  1347. # Migration: Add print options columns to print_queue
  1348. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1")
  1349. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0")
  1350. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1")
  1351. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0")
  1352. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0")
  1353. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1")
  1354. # Migration: Add nozzle offset calibration option (dual-nozzle printers, #1682).
  1355. # Postgres rejects `DEFAULT 1` on a BOOLEAN column — use TRUE / 1 per dialect.
  1356. if is_sqlite():
  1357. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_offset_cali BOOLEAN DEFAULT 1")
  1358. else:
  1359. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_offset_cali BOOLEAN DEFAULT TRUE")
  1360. # Migration: convert bed_levelling / flow_cali / nozzle_offset_cali from
  1361. # boolean to tri-state strings (off/on/auto). BambuStudio exposes a third
  1362. # "auto" state for these (skip the calibration if it was done recently); our
  1363. # booleans could only send force-on / off. Legacy rows map true->'on',
  1364. # false->'off'; the new default is 'auto'. Idempotent on both dialects:
  1365. # SQLite leans on column affinity (a BOOLEAN-declared column stores text
  1366. # fine) and only rewrites rows still holding 0/1; PostgreSQL alters the
  1367. # column type only while it is still boolean, so re-runs and fresh
  1368. # create_all() schemas (already VARCHAR) are skipped. Column names are
  1369. # hardcoded constants, not user input.
  1370. _tristate_cols = ("bed_levelling", "flow_cali", "nozzle_offset_cali")
  1371. if is_sqlite():
  1372. for _col in _tristate_cols:
  1373. async with conn.begin_nested():
  1374. # B608 is a false positive here: _col is a hardcoded constant
  1375. # from _tristate_cols, never user input, and SQL identifiers
  1376. # can't be bound as parameters. Suppressed inline below.
  1377. await conn.execute(
  1378. text(f"UPDATE print_queue SET {_col} = 'on' WHERE {_col} IN (1, '1', 'true', 'True')") # nosec B608
  1379. )
  1380. await conn.execute(
  1381. text(f"UPDATE print_queue SET {_col} = 'off' WHERE {_col} IN (0, '0', 'false', 'False')") # nosec B608
  1382. )
  1383. else:
  1384. for _col in _tristate_cols:
  1385. result = await conn.execute(
  1386. text(
  1387. "SELECT data_type FROM information_schema.columns "
  1388. "WHERE table_name = 'print_queue' AND column_name = :col"
  1389. ),
  1390. {"col": _col},
  1391. )
  1392. row = result.fetchone()
  1393. if row and row[0] == "boolean":
  1394. await _safe_execute(conn, f"ALTER TABLE print_queue ALTER COLUMN {_col} DROP DEFAULT")
  1395. await _safe_execute(
  1396. conn,
  1397. f"ALTER TABLE print_queue ALTER COLUMN {_col} TYPE VARCHAR(8) "
  1398. f"USING (CASE WHEN {_col} THEN 'on' ELSE 'off' END)",
  1399. )
  1400. await _safe_execute(conn, f"ALTER TABLE print_queue ALTER COLUMN {_col} SET DEFAULT 'auto'")
  1401. # Migration: normalise the workflow-default settings rows that back these
  1402. # options from legacy "true"/"false" to the tri-state vocabulary so the API
  1403. # returns real values (the AppSettings validator also coerces on read, but
  1404. # rewriting keeps the stored data honest). Only these three became tri-state.
  1405. for _skey in ("default_bed_levelling", "default_flow_cali", "default_nozzle_offset_cali"):
  1406. async with conn.begin_nested():
  1407. await conn.execute(
  1408. text("UPDATE settings SET value = 'on' WHERE key = :k AND lower(value) IN ('true', '1')"),
  1409. {"k": _skey},
  1410. )
  1411. await conn.execute(
  1412. text("UPDATE settings SET value = 'off' WHERE key = :k AND lower(value) IN ('false', '0')"),
  1413. {"k": _skey},
  1414. )
  1415. # Migration: Per-item preheat / heat-soak override (#1468). preheat_override
  1416. # is one of {inherit, on, off} — 'inherit' falls back to the global
  1417. # preheat_enabled setting; 'on' / 'off' force the decision. The chamber
  1418. # target column overrides the filament-map derivation when not null.
  1419. # Existing rows default to 'inherit' + NULL so behaviour is unchanged for
  1420. # in-flight queues.
  1421. await _safe_execute(
  1422. conn,
  1423. "ALTER TABLE print_queue ADD COLUMN preheat_override VARCHAR(10) DEFAULT 'inherit'",
  1424. )
  1425. await _safe_execute(
  1426. conn,
  1427. "ALTER TABLE print_queue ADD COLUMN preheat_chamber_target_override INTEGER",
  1428. )
  1429. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  1430. # This allows queue items to reference library files directly (archive created at print start)
  1431. try:
  1432. async with conn.begin_nested():
  1433. await conn.execute(
  1434. text(
  1435. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  1436. )
  1437. )
  1438. except (OperationalError, ProgrammingError):
  1439. pass # Already applied
  1440. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  1441. # PostgreSQL gets the correct schema from create_all(), so skip this
  1442. if is_sqlite():
  1443. try:
  1444. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  1445. row = result.fetchone()
  1446. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  1447. await conn.execute(
  1448. text("""
  1449. CREATE TABLE print_queue_new2 (
  1450. id INTEGER PRIMARY KEY,
  1451. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  1452. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  1453. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  1454. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  1455. position INTEGER DEFAULT 0,
  1456. scheduled_time DATETIME,
  1457. manual_start BOOLEAN DEFAULT 0,
  1458. require_previous_success BOOLEAN DEFAULT 0,
  1459. auto_off_after BOOLEAN DEFAULT 0,
  1460. ams_mapping TEXT,
  1461. plate_id INTEGER,
  1462. bed_levelling BOOLEAN DEFAULT 1,
  1463. flow_cali BOOLEAN DEFAULT 0,
  1464. vibration_cali BOOLEAN DEFAULT 1,
  1465. layer_inspect BOOLEAN DEFAULT 0,
  1466. timelapse BOOLEAN DEFAULT 0,
  1467. use_ams BOOLEAN DEFAULT 1,
  1468. status VARCHAR(20) DEFAULT 'pending',
  1469. started_at DATETIME,
  1470. completed_at DATETIME,
  1471. error_message TEXT,
  1472. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  1473. )
  1474. """)
  1475. )
  1476. await conn.execute(
  1477. text("""
  1478. INSERT INTO print_queue_new2
  1479. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  1480. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  1481. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  1482. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  1483. status, started_at, completed_at, error_message, created_at
  1484. FROM print_queue
  1485. """)
  1486. )
  1487. await conn.execute(text("DROP TABLE print_queue"))
  1488. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  1489. except (OperationalError, ProgrammingError):
  1490. pass # Already applied
  1491. # Migration: Add dispatching_at claim column to print_queue (#2615). Nullable
  1492. # timestamp; the type differs by dialect (SQLite DATETIME vs Postgres
  1493. # TIMESTAMP) so an existing-DB upgrade doesn't hit "type datetime does not
  1494. # exist" on Postgres. On a fresh DB create_all() already built the column, so
  1495. # the ALTER is swallowed as "already exists".
  1496. #
  1497. # Placed AFTER the print_queue_new2 table-recreate above: that recreate
  1498. # (SQLite-only, and only on ancient DBs whose archive_id is still NOT NULL)
  1499. # rebuilds print_queue from an explicit column list that doesn't carry this
  1500. # column, so adding it earlier would let the recreate silently drop it. Adding
  1501. # it here means it survives that path.
  1502. if is_sqlite():
  1503. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN dispatching_at DATETIME")
  1504. else:
  1505. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN dispatching_at TIMESTAMP")
  1506. # Migration: Add HA energy sensor entity columns to smart_plugs
  1507. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)")
  1508. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)")
  1509. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)")
  1510. # Migration: Create users table for authentication
  1511. try:
  1512. async with conn.begin_nested():
  1513. await conn.execute(
  1514. text("""
  1515. CREATE TABLE IF NOT EXISTS users (
  1516. id INTEGER PRIMARY KEY,
  1517. username VARCHAR(100) NOT NULL UNIQUE,
  1518. password_hash VARCHAR(255) NOT NULL,
  1519. role VARCHAR(20) NOT NULL DEFAULT 'user',
  1520. is_active BOOLEAN NOT NULL DEFAULT 1,
  1521. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1522. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1523. )
  1524. """)
  1525. )
  1526. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  1527. except (OperationalError, ProgrammingError):
  1528. pass # Already applied
  1529. # Migration: Add external camera columns to printers
  1530. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)")
  1531. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)")
  1532. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0")
  1533. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_snapshot_url VARCHAR(500)")
  1534. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  1535. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)")
  1536. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  1537. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)")
  1538. # Migration: Add is_external column to library_files for external cloud files
  1539. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0")
  1540. # Migration: Add project_id column to library_files
  1541. try:
  1542. async with conn.begin_nested():
  1543. await conn.execute(
  1544. text(
  1545. "ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  1546. )
  1547. )
  1548. except (OperationalError, ProgrammingError):
  1549. pass # Already applied
  1550. # Migration: Add is_external column to library_folders for external cloud folders
  1551. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0")
  1552. # Migration: Add external folder settings columns to library_folders
  1553. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0")
  1554. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0")
  1555. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)")
  1556. # Migration: Add plate_detection_enabled column to printers
  1557. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0")
  1558. # Migration: Add plate detection ROI columns to printers
  1559. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL")
  1560. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL")
  1561. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL")
  1562. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL")
  1563. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  1564. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  1565. # SQLite requires table recreation to drop constraints
  1566. # PostgreSQL gets the correct schema from create_all(), so skip this
  1567. if is_sqlite():
  1568. try:
  1569. needs_migration = False
  1570. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  1571. row = result.fetchone()
  1572. table_sql = (row[0] or "").upper() if row else ""
  1573. if "PRINTER_ID" in table_sql and "UNIQUE" in table_sql:
  1574. import re
  1575. if re.search(r'"?PRINTER_ID"?\s+\w+\s+UNIQUE', table_sql) or re.search(
  1576. r'UNIQUE\s*\([^)]*"?PRINTER_ID"?', table_sql
  1577. ):
  1578. needs_migration = True
  1579. idx_result = await conn.execute(
  1580. text("SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='smart_plugs' AND sql IS NOT NULL")
  1581. )
  1582. for idx_row in idx_result.fetchall():
  1583. idx_sql = (idx_row[0] or "").upper()
  1584. if "UNIQUE" in idx_sql and "PRINTER_ID" in idx_sql:
  1585. needs_migration = True
  1586. break
  1587. if needs_migration:
  1588. # Create new table without UNIQUE constraint on printer_id
  1589. await conn.execute(
  1590. text("""
  1591. CREATE TABLE smart_plugs_temp (
  1592. id INTEGER PRIMARY KEY,
  1593. name VARCHAR(100) NOT NULL,
  1594. ip_address VARCHAR(45),
  1595. plug_type VARCHAR(20) DEFAULT 'tasmota',
  1596. ha_entity_id VARCHAR(100),
  1597. ha_power_entity VARCHAR(100),
  1598. ha_energy_today_entity VARCHAR(100),
  1599. ha_energy_total_entity VARCHAR(100),
  1600. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1601. enabled BOOLEAN NOT NULL DEFAULT 1,
  1602. auto_on BOOLEAN NOT NULL DEFAULT 1,
  1603. auto_off BOOLEAN NOT NULL DEFAULT 1,
  1604. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  1605. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  1606. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  1607. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  1608. username VARCHAR(50),
  1609. password VARCHAR(100),
  1610. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  1611. power_alert_high FLOAT,
  1612. power_alert_low FLOAT,
  1613. power_alert_last_triggered DATETIME,
  1614. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  1615. schedule_on_time VARCHAR(5),
  1616. schedule_off_time VARCHAR(5),
  1617. show_in_switchbar BOOLEAN DEFAULT 0,
  1618. last_state VARCHAR(10),
  1619. last_checked DATETIME,
  1620. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  1621. auto_off_pending BOOLEAN DEFAULT 0,
  1622. auto_off_pending_since DATETIME,
  1623. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  1624. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  1625. )
  1626. """)
  1627. )
  1628. # Copy data
  1629. await conn.execute(
  1630. text("""
  1631. INSERT INTO smart_plugs_temp
  1632. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  1633. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  1634. auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  1635. off_delay_mode, off_delay_minutes, off_temp_threshold,
  1636. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  1637. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  1638. show_in_switchbar, last_state, last_checked, auto_off_executed,
  1639. auto_off_pending, auto_off_pending_since, created_at, updated_at
  1640. FROM smart_plugs
  1641. """)
  1642. )
  1643. # Drop old table and rename new one
  1644. await conn.execute(text("DROP TABLE smart_plugs"))
  1645. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  1646. except (OperationalError, ProgrammingError):
  1647. pass # Already applied
  1648. # Migration: Add show_on_printer_card column to smart_plugs
  1649. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1")
  1650. # Migration: Add MQTT smart plug fields (legacy)
  1651. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)")
  1652. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)")
  1653. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)")
  1654. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)")
  1655. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0")
  1656. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  1657. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)")
  1658. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0")
  1659. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)")
  1660. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0")
  1661. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)")
  1662. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)")
  1663. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  1664. try:
  1665. async with conn.begin_nested():
  1666. await conn.execute(
  1667. text("""
  1668. UPDATE smart_plugs
  1669. SET mqtt_power_topic = mqtt_topic,
  1670. mqtt_power_multiplier = mqtt_multiplier
  1671. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  1672. """)
  1673. )
  1674. except (OperationalError, ProgrammingError):
  1675. pass # Already applied
  1676. # Migration: Create groups table for permission-based access control
  1677. try:
  1678. async with conn.begin_nested():
  1679. await conn.execute(
  1680. text("""
  1681. CREATE TABLE IF NOT EXISTS groups (
  1682. id INTEGER PRIMARY KEY,
  1683. name VARCHAR(100) NOT NULL UNIQUE,
  1684. description VARCHAR(500),
  1685. permissions JSON,
  1686. is_system BOOLEAN NOT NULL DEFAULT 0,
  1687. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1688. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1689. )
  1690. """)
  1691. )
  1692. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  1693. except (OperationalError, ProgrammingError):
  1694. pass # Already applied
  1695. # Migration: Create user_groups association table
  1696. try:
  1697. async with conn.begin_nested():
  1698. await conn.execute(
  1699. text("""
  1700. CREATE TABLE IF NOT EXISTS user_groups (
  1701. user_id INTEGER NOT NULL,
  1702. group_id INTEGER NOT NULL,
  1703. PRIMARY KEY (user_id, group_id),
  1704. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  1705. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  1706. )
  1707. """)
  1708. )
  1709. except (OperationalError, ProgrammingError):
  1710. pass # Already applied
  1711. # Migration: Add model-based queue assignment columns to print_queue
  1712. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)")
  1713. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT")
  1714. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT")
  1715. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  1716. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1")
  1717. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  1718. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0")
  1719. # Migration: Add queue notification event columns to notification_providers
  1720. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0")
  1721. try:
  1722. async with conn.begin_nested():
  1723. await conn.execute(
  1724. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  1725. )
  1726. except (OperationalError, ProgrammingError):
  1727. pass # Already applied
  1728. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0")
  1729. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1")
  1730. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1")
  1731. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1")
  1732. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0")
  1733. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  1734. try:
  1735. async with conn.begin_nested():
  1736. await conn.execute(
  1737. text(
  1738. "ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  1739. )
  1740. )
  1741. except (OperationalError, ProgrammingError):
  1742. pass # Already applied
  1743. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  1744. try:
  1745. async with conn.begin_nested():
  1746. await conn.execute(
  1747. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1748. )
  1749. except (OperationalError, ProgrammingError):
  1750. pass # Already applied
  1751. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  1752. try:
  1753. async with conn.begin_nested():
  1754. await conn.execute(
  1755. text(
  1756. "ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  1757. )
  1758. )
  1759. except (OperationalError, ProgrammingError):
  1760. pass # Already applied
  1761. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  1762. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)")
  1763. # Migration: Convert absolute paths to relative paths in library_files table
  1764. # This ensures backup/restore portability across different installations
  1765. try:
  1766. async with conn.begin_nested():
  1767. base_dir_str = str(settings.base_dir)
  1768. # Ensure we have a trailing slash for clean replacement
  1769. if not base_dir_str.endswith("/"):
  1770. base_dir_str += "/"
  1771. # Update file_path - remove base_dir prefix from absolute paths
  1772. await conn.execute(
  1773. text("""
  1774. UPDATE library_files
  1775. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  1776. WHERE file_path LIKE :pattern
  1777. """),
  1778. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1779. )
  1780. # Update thumbnail_path - remove base_dir prefix from absolute paths
  1781. await conn.execute(
  1782. text("""
  1783. UPDATE library_files
  1784. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  1785. WHERE thumbnail_path LIKE :pattern
  1786. """),
  1787. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1788. )
  1789. except (OperationalError, ProgrammingError):
  1790. pass # Already applied
  1791. # Create active_print_spoolman table for Spoolman per-filament tracking.
  1792. # filament_usage is nullable so the no-3MF branch can still create a row
  1793. # that carries only tray_remain_start for the remain%-delta fallback
  1794. # (#1820 — matches internal-inventory Path 2 in usage_tracker).
  1795. await _safe_execute(
  1796. conn,
  1797. """
  1798. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1799. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1800. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1801. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1802. filament_usage TEXT,
  1803. ams_trays TEXT NOT NULL,
  1804. slot_to_tray TEXT,
  1805. layer_usage TEXT,
  1806. filament_properties TEXT,
  1807. tray_remain_start TEXT,
  1808. UNIQUE(printer_id, archive_id)
  1809. )
  1810. """
  1811. if is_sqlite()
  1812. else """
  1813. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1814. id SERIAL PRIMARY KEY,
  1815. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1816. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1817. filament_usage TEXT,
  1818. ams_trays TEXT NOT NULL,
  1819. slot_to_tray TEXT,
  1820. layer_usage TEXT,
  1821. filament_properties TEXT,
  1822. tray_remain_start TEXT,
  1823. UNIQUE(printer_id, archive_id)
  1824. )
  1825. """,
  1826. )
  1827. # Migration for installs that already created active_print_spoolman with
  1828. # the original schema: add tray_remain_start, and relax filament_usage's
  1829. # NOT NULL so the no-3MF branch can persist a remain-only tracking row.
  1830. await _safe_execute(conn, "ALTER TABLE active_print_spoolman ADD COLUMN tray_remain_start TEXT")
  1831. if is_sqlite():
  1832. # SQLite can't ALTER COLUMN; patch sqlite_master directly. Mirrors the
  1833. # users.password_hash NULL-relaxation a few hundred lines below — see
  1834. # the comment there for the schema_version bump rationale.
  1835. try:
  1836. result = await conn.execute(
  1837. text("SELECT sql FROM sqlite_master WHERE type='table' AND name='active_print_spoolman'")
  1838. )
  1839. tbl_sql = result.scalar()
  1840. if tbl_sql and "filament_usage TEXT NOT NULL" in tbl_sql:
  1841. version_result = await conn.execute(text("PRAGMA schema_version"))
  1842. schema_version = version_result.scalar() or 0
  1843. await conn.execute(text("PRAGMA writable_schema = ON"))
  1844. await conn.execute(
  1845. text(
  1846. "UPDATE sqlite_master "
  1847. "SET sql = replace(sql, 'filament_usage TEXT NOT NULL', 'filament_usage TEXT') "
  1848. "WHERE type='table' AND name='active_print_spoolman'"
  1849. )
  1850. )
  1851. await conn.execute(text(f"PRAGMA schema_version = {schema_version + 1}"))
  1852. await conn.execute(text("PRAGMA writable_schema = OFF"))
  1853. except (OperationalError, ProgrammingError) as exc:
  1854. logger.warning(
  1855. "Could not relax active_print_spoolman.filament_usage NOT NULL via writable_schema: %s — "
  1856. "no-3MF Spoolman fallback will be a no-op on this install",
  1857. exc,
  1858. )
  1859. else:
  1860. await _safe_execute(conn, "ALTER TABLE active_print_spoolman ALTER COLUMN filament_usage DROP NOT NULL")
  1861. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1862. try:
  1863. async with conn.begin_nested():
  1864. await conn.execute(
  1865. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1866. )
  1867. except (OperationalError, ProgrammingError):
  1868. pass # Already applied
  1869. # Migration: Add email column to users for Advanced Auth (PR #322)
  1870. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN email VARCHAR(255)")
  1871. # Migration: Add inventory spool tracking columns
  1872. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN added_full BOOLEAN")
  1873. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_used DATETIME")
  1874. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN encode_time DATETIME")
  1875. # Migration: Add RFID tag matching columns to spool
  1876. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)")
  1877. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)")
  1878. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)")
  1879. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)")
  1880. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  1881. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER")
  1882. # Migration: Create spool_usage_history table for filament consumption tracking
  1883. await _safe_execute(
  1884. conn,
  1885. """
  1886. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1887. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1888. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1889. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1890. print_name VARCHAR(500),
  1891. weight_used REAL NOT NULL DEFAULT 0,
  1892. percent_used INTEGER NOT NULL DEFAULT 0,
  1893. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1894. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1895. )
  1896. """
  1897. if is_sqlite()
  1898. else """
  1899. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1900. id SERIAL PRIMARY KEY,
  1901. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1902. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1903. print_name VARCHAR(500),
  1904. weight_used REAL NOT NULL DEFAULT 0,
  1905. percent_used INTEGER NOT NULL DEFAULT 0,
  1906. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1907. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  1908. )
  1909. """,
  1910. )
  1911. # Migration: Add open_in_new_tab column to external_links
  1912. await _safe_execute(conn, "ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0")
  1913. # Migration: Add bed cooled notification column to notification_providers
  1914. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0")
  1915. # Migration: Add first layer complete notification column to notification_providers
  1916. try:
  1917. async with conn.begin_nested():
  1918. await conn.execute(
  1919. text("ALTER TABLE notification_providers ADD COLUMN on_first_layer_complete BOOLEAN DEFAULT 0")
  1920. )
  1921. except (OperationalError, ProgrammingError):
  1922. pass # Already applied
  1923. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  1924. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0")
  1925. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  1926. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER")
  1927. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME")
  1928. # Migration: Add cost tracking fields to spool table
  1929. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN cost_per_kg REAL")
  1930. # Migration: Per-spool category + low-stock threshold override (#729). Both
  1931. # nullable — NULL category leaves the spool uncategorised, NULL threshold
  1932. # falls back to the global low_stock_threshold setting.
  1933. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN category VARCHAR(50)")
  1934. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN low_stock_threshold_pct INTEGER")
  1935. # Migration: Add user-editable storage location to spool table
  1936. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN storage_location VARCHAR(255)")
  1937. # Migration: Add weight_used_baseline anchor for the resettable "Total
  1938. # Consumed" stat (#1390). Existing spools default to 0 (no baseline),
  1939. # so the counter starts unaffected; pressing "Reset usage to 0" now
  1940. # stamps baseline = weight_used without touching remaining.
  1941. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_used_baseline REAL DEFAULT 0")
  1942. # Migration: Widen tag_uid column from VARCHAR(16) to VARCHAR(32) to accommodate 7-byte NFC
  1943. # UIDs (14 hex chars) in addition to 8-byte Bambu Lab UIDs (16 hex chars).
  1944. # ALTER COLUMN ... TYPE is PostgreSQL-only syntax; SQLite ignores VARCHAR sizes so no-op there.
  1945. if not is_sqlite():
  1946. await _safe_execute(conn, "ALTER TABLE spool ALTER COLUMN tag_uid TYPE VARCHAR(32)")
  1947. # Migration: enhanced filament colour handling (#1154). `extra_colors` is
  1948. # a comma-separated list of 6- or 8-char hex tokens (no `#`) for multi-
  1949. # colour gradients; `effect_type` is one of {sparkle, wood, marble, glow,
  1950. # matte} as a visual rendering hint. Both nullable — NULL keeps the
  1951. # current single-rgba/no-effect behaviour.
  1952. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN extra_colors VARCHAR(255)")
  1953. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN effect_type VARCHAR(20)")
  1954. # Migration: Add cost field to spool_usage_history table
  1955. await _safe_execute(conn, "ALTER TABLE spool_usage_history ADD COLUMN cost REAL")
  1956. # Migration: Add archive_id field to spool_usage_history table
  1957. try:
  1958. async with conn.begin_nested():
  1959. await conn.execute(
  1960. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  1961. )
  1962. except (OperationalError, ProgrammingError):
  1963. pass # Already applied
  1964. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  1965. try:
  1966. async with conn.begin_nested():
  1967. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  1968. count = result.scalar() or 0
  1969. if count == 0:
  1970. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  1971. row = result.fetchone()
  1972. if row:
  1973. # Old settings exist — migrate to first virtual printer row
  1974. old_enabled = row[0] == "true" if row[0] else False
  1975. result = await conn.execute(
  1976. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  1977. )
  1978. row = result.fetchone()
  1979. old_access_code = row[0] if row else None
  1980. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  1981. row = result.fetchone()
  1982. old_mode = row[0] if row else "archive"
  1983. # Translate to canonical wire values (#1429 mode-label
  1984. # discrepancy): legacy `immediate` → `archive`, legacy
  1985. # `print_queue` → `queue`. The historical `queue` alias
  1986. # for `review` predates the canonical rename and is
  1987. # preserved (existing user intent was "pending review").
  1988. if old_mode == "queue":
  1989. old_mode = "review"
  1990. elif old_mode == "immediate":
  1991. old_mode = "archive"
  1992. elif old_mode == "print_queue":
  1993. old_mode = "queue"
  1994. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  1995. row = result.fetchone()
  1996. old_model = row[0] if row else "BL-P001"
  1997. result = await conn.execute(
  1998. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1999. )
  2000. row = result.fetchone()
  2001. old_target_id = int(row[0]) if row and row[0] else None
  2002. result = await conn.execute(
  2003. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  2004. )
  2005. row = result.fetchone()
  2006. old_remote_iface = row[0] if row else None
  2007. await conn.execute(
  2008. text("""
  2009. INSERT INTO virtual_printers
  2010. (name, enabled, mode, model, access_code, target_printer_id,
  2011. bind_ip, remote_interface_ip, serial_suffix, position)
  2012. VALUES
  2013. (:name, :enabled, :mode, :model, :access_code, :target_id,
  2014. NULL, :remote_iface, '391800001', 0)
  2015. """),
  2016. {
  2017. "name": "Bambuddy",
  2018. "enabled": old_enabled,
  2019. "mode": old_mode or "archive",
  2020. "model": old_model,
  2021. "access_code": old_access_code,
  2022. "target_id": old_target_id,
  2023. "remote_iface": old_remote_iface,
  2024. },
  2025. )
  2026. except (OperationalError, ProgrammingError, IntegrityError):
  2027. pass # Table may not exist yet on first run, or columns have different constraints
  2028. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  2029. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT")
  2030. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  2031. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)")
  2032. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)")
  2033. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100")
  2034. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0")
  2035. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0")
  2036. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME")
  2037. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  2038. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT")
  2039. # Migration: Add OTA update tracking columns to spoolbuddy_devices
  2040. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_status VARCHAR(20)")
  2041. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_message VARCHAR(255)")
  2042. # Migration: Persist SpoolBuddy backend URL and queued system payload
  2043. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN backend_url VARCHAR(255)")
  2044. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_system_payload TEXT")
  2045. # Migration: Add system_stats JSON blob column to spoolbuddy_devices
  2046. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN system_stats TEXT")
  2047. # Migration: Add SSH host key for TOFU verification (H1 security fix)
  2048. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN ssh_host_key VARCHAR(500)")
  2049. # Migration: Widen ssh_host_key from VARCHAR(500) to TEXT — RSA-3072+ host keys
  2050. # in OpenSSH format exceed 500 chars (RSA-4096 ~720 chars). PostgreSQL enforces
  2051. # the limit and rejects the UPDATE; SQLite ignores VARCHAR length so no-op there.
  2052. if not is_sqlite():
  2053. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ALTER COLUMN ssh_host_key TYPE TEXT")
  2054. # Migration: Convert ams_labels table from (printer_id, ams_id) key to ams_serial_number key
  2055. # Labels are now keyed by AMS serial number so they persist when the AMS is moved to another printer.
  2056. # PostgreSQL gets the correct schema from create_all(), so skip this
  2057. if is_sqlite():
  2058. try:
  2059. await conn.execute(text("DROP TABLE IF EXISTS ams_labels_new"))
  2060. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='ams_labels'"))
  2061. row = result.fetchone()
  2062. if row and "printer_id" in (row[0] or ""):
  2063. # Old schema: rebuild the table with ams_serial_number as the unique key.
  2064. # Existing rows get a synthetic serial "p{printer_id}a{ams_id}" so data is preserved.
  2065. await conn.execute(
  2066. text("""
  2067. CREATE TABLE ams_labels_new (
  2068. id INTEGER PRIMARY KEY,
  2069. ams_serial_number VARCHAR(50) NOT NULL,
  2070. ams_id INTEGER,
  2071. label VARCHAR(100) NOT NULL,
  2072. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2073. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2074. CONSTRAINT uq_ams_label_serial UNIQUE (ams_serial_number)
  2075. )
  2076. """)
  2077. )
  2078. await conn.execute(
  2079. text("""
  2080. INSERT INTO ams_labels_new (id, ams_serial_number, ams_id, label, created_at, updated_at)
  2081. SELECT id,
  2082. 'p' || CAST(printer_id AS TEXT) || 'a' || CAST(ams_id AS TEXT),
  2083. ams_id,
  2084. label,
  2085. created_at,
  2086. updated_at
  2087. FROM ams_labels
  2088. """)
  2089. )
  2090. await conn.execute(text("DROP TABLE ams_labels"))
  2091. await conn.execute(text("ALTER TABLE ams_labels_new RENAME TO ams_labels"))
  2092. except (OperationalError, ProgrammingError):
  2093. pass # Already migrated or table does not exist yet
  2094. # Migration: Add auto_dispatch column to virtual_printers
  2095. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN auto_dispatch BOOLEAN DEFAULT 1")
  2096. # Migration: Fix VP model codes — convert legacy SSDP codes and display names to correct SSDP codes
  2097. # Legacy codes (from multi-VP refactor) and display names (from proxy auto-inherit)
  2098. vp_model_fixes = {
  2099. "3DPrinter-X1-Carbon": "BL-P001",
  2100. "3DPrinter-X1": "BL-P002",
  2101. "X1C": "BL-P001",
  2102. "X1": "BL-P002",
  2103. "X1E": "C13",
  2104. "X2D": "N6",
  2105. "P1P": "C11",
  2106. "P1S": "C12",
  2107. "P2S": "N7",
  2108. "A1": "N2S",
  2109. "A1 Mini": "N1",
  2110. "H2D": "O1D",
  2111. "H2C": "O1C",
  2112. "H2S": "O1S",
  2113. }
  2114. for old_val, new_val in vp_model_fixes.items():
  2115. await conn.execute(
  2116. text("UPDATE virtual_printers SET model = :new WHERE model = :old"),
  2117. {"old": old_val, "new": new_val},
  2118. )
  2119. await conn.execute(
  2120. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_model' AND value = :old"),
  2121. {"old": old_val, "new": new_val},
  2122. )
  2123. # Migration: Rename VP mode wire values to match the user-facing labels
  2124. # (#1429 follow-up). The UI button "Archive" had always saved `immediate`
  2125. # and "Queue" had always saved `print_queue` — a mismatch that showed up
  2126. # confusingly in every support bundle. The button labels stay; the wire
  2127. # value is what changes. Idempotent: re-running the UPDATE on canonical
  2128. # values is a no-op. SQLite and Postgres both accept this statement
  2129. # unchanged (string literal comparison, no driver-specific syntax).
  2130. vp_mode_renames = [("immediate", "archive"), ("print_queue", "queue")]
  2131. for old_val, new_val in vp_mode_renames:
  2132. await conn.execute(
  2133. text("UPDATE virtual_printers SET mode = :new WHERE mode = :old"),
  2134. {"old": old_val, "new": new_val},
  2135. )
  2136. await conn.execute(
  2137. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_mode' AND value = :old"),
  2138. {"old": old_val, "new": new_val},
  2139. )
  2140. # Migration: Auto-sync VP access codes from their target printer.
  2141. # Non-proxy VPs with a target printer (the live-mirror bridge) forward the
  2142. # slicer's MQTT/RTSPS auth bytes through to the real printer, so the VP's
  2143. # access code MUST equal the target's — earlier UIs let them diverge,
  2144. # producing a VP that the slicer could bind but whose bridge silently
  2145. # failed to authenticate against the real printer. The route layer now
  2146. # auto-inherits on every create/update; this backfill corrects any rows
  2147. # that pre-date that change. Idempotent (re-running on synced rows is a
  2148. # no-op because the WHERE clause excludes them). SQLite and Postgres both
  2149. # accept correlated subqueries in UPDATE — no driver-specific syntax.
  2150. mismatch_result = await conn.execute(
  2151. text(
  2152. "SELECT vp.id AS vp_id, vp.name AS vp_name, p.name AS target_name "
  2153. "FROM virtual_printers vp "
  2154. "JOIN printers p ON vp.target_printer_id = p.id "
  2155. "WHERE vp.mode != 'proxy' "
  2156. " AND (vp.access_code IS NULL OR vp.access_code != p.access_code)"
  2157. )
  2158. )
  2159. for row in mismatch_result.fetchall():
  2160. logger.info(
  2161. "VP %r (id=%d) access code synced from target printer %r",
  2162. row.vp_name,
  2163. row.vp_id,
  2164. row.target_name,
  2165. )
  2166. await conn.execute(
  2167. text(
  2168. "UPDATE virtual_printers "
  2169. "SET access_code = ("
  2170. " SELECT access_code FROM printers WHERE printers.id = virtual_printers.target_printer_id"
  2171. ") "
  2172. "WHERE virtual_printers.target_printer_id IS NOT NULL "
  2173. " AND virtual_printers.mode != 'proxy' "
  2174. " AND (virtual_printers.access_code IS NULL OR virtual_printers.access_code != ("
  2175. " SELECT access_code FROM printers WHERE printers.id = virtual_printers.target_printer_id"
  2176. " ))"
  2177. )
  2178. )
  2179. # Migration: Recover queue items that got stuck in `skipped` because of
  2180. # the cancellation-cascade bug (#1667). Pre-fix, the scheduler's
  2181. # `_check_previous_success` lookback excluded `cancelled` but included
  2182. # `skipped`, so a single user-cancelled print poisoned every downstream
  2183. # item with `require_previous_success=True` indefinitely. The reporter saw
  2184. # 18 items blocked over 3 days from one cancellation.
  2185. #
  2186. # Conservative reversal: ONLY reset rows whose immediate predecessor on
  2187. # the same printer (by completed_at desc, excluding the skipped-bug
  2188. # cascade) was `cancelled`. Skipped items whose true predecessor was a
  2189. # real `failed` or `aborted` print stay skipped — those were legitimate.
  2190. # Genuine failure-skips share the same status + error_message + completed_at
  2191. # fingerprint as bug-skips, so the predecessor check is what distinguishes
  2192. # them. Idempotent (post-reset rows no longer match the WHERE clause).
  2193. #
  2194. # Correlated subquery is portable across SQLite and Postgres. The
  2195. # `error_message` literal matches the exact string the buggy scheduler
  2196. # wrote — narrowing further on intent.
  2197. stuck_skipped_result = await conn.execute(
  2198. text(
  2199. "SELECT pq.id, pq.printer_id "
  2200. "FROM print_queue pq "
  2201. "WHERE pq.status = 'skipped' "
  2202. " AND pq.error_message = 'Previous print failed or was aborted' "
  2203. " AND pq.completed_at IS NOT NULL "
  2204. " AND ("
  2205. " SELECT prev.status FROM print_queue prev "
  2206. " WHERE prev.printer_id = pq.printer_id "
  2207. " AND prev.id != pq.id "
  2208. " AND prev.status IN ('completed', 'failed', 'cancelled', 'aborted') "
  2209. " AND prev.completed_at IS NOT NULL "
  2210. " AND prev.completed_at < pq.completed_at "
  2211. " ORDER BY prev.completed_at DESC LIMIT 1"
  2212. " ) = 'cancelled'"
  2213. )
  2214. )
  2215. stuck_ids = [row.id for row in stuck_skipped_result.fetchall()]
  2216. if stuck_ids:
  2217. logger.info(
  2218. "Queue cancellation-cascade migration (#1667): resetting %d skipped item(s) to pending",
  2219. len(stuck_ids),
  2220. )
  2221. await conn.execute(
  2222. text(
  2223. "UPDATE print_queue "
  2224. "SET status = 'pending', error_message = NULL, completed_at = NULL "
  2225. "WHERE id IN ("
  2226. " SELECT pq.id FROM print_queue pq "
  2227. " WHERE pq.status = 'skipped' "
  2228. " AND pq.error_message = 'Previous print failed or was aborted' "
  2229. " AND pq.completed_at IS NOT NULL "
  2230. " AND ("
  2231. " SELECT prev.status FROM print_queue prev "
  2232. " WHERE prev.printer_id = pq.printer_id "
  2233. " AND prev.id != pq.id "
  2234. " AND prev.status IN ('completed', 'failed', 'cancelled', 'aborted') "
  2235. " AND prev.completed_at IS NOT NULL "
  2236. " AND prev.completed_at < pq.completed_at "
  2237. " ORDER BY prev.completed_at DESC LIMIT 1"
  2238. " ) = 'cancelled'"
  2239. ")"
  2240. )
  2241. )
  2242. # Migration: Unify `LibraryFile.file_type` across ingest paths (#1600).
  2243. # Pre-#1600, only the external-folder scan path stored `gcode.3mf` for
  2244. # sliced outputs — the upload, ZIP-extract, and in-process paths all
  2245. # stripped to the trailing `.3mf` and stored `3mf`, so the same file
  2246. # family was split between two values depending on how it was ingested.
  2247. # Going forward `classify_file_type()` is canonical; this backfill flips
  2248. # existing legacy `3mf` rows whose filename ends in `.gcode.3mf` to the
  2249. # canonical compound name. Idempotent (post-update rows no longer match
  2250. # `file_type = '3mf'`) and dialect-neutral (`LOWER` + `LIKE` work the
  2251. # same under SQLite and Postgres).
  2252. await conn.execute(
  2253. text(
  2254. "UPDATE library_files SET file_type = 'gcode.3mf' "
  2255. "WHERE file_type = '3mf' AND LOWER(filename) LIKE '%.gcode.3mf'"
  2256. )
  2257. )
  2258. # Migration: Add per-user Bambu Cloud credential columns
  2259. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_token VARCHAR(500)")
  2260. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_email VARCHAR(255)")
  2261. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_region VARCHAR(10)")
  2262. # Cleanup: Remove obsolete settings keys that are no longer used
  2263. obsolete_keys = ["slicer_binary_path"]
  2264. for key in obsolete_keys:
  2265. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  2266. # Migration: Create user_email_preferences table for user-specific email notification settings
  2267. try:
  2268. async with conn.begin_nested():
  2269. await conn.execute(
  2270. text("""
  2271. CREATE TABLE IF NOT EXISTS user_email_preferences (
  2272. id INTEGER PRIMARY KEY,
  2273. user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  2274. notify_print_start BOOLEAN NOT NULL DEFAULT 1,
  2275. notify_print_complete BOOLEAN NOT NULL DEFAULT 1,
  2276. notify_print_failed BOOLEAN NOT NULL DEFAULT 1,
  2277. notify_print_stopped BOOLEAN NOT NULL DEFAULT 1,
  2278. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2279. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  2280. )
  2281. """)
  2282. )
  2283. await conn.execute(
  2284. text("CREATE INDEX IF NOT EXISTS ix_user_email_preferences_user_id ON user_email_preferences(user_id)")
  2285. )
  2286. except (OperationalError, ProgrammingError):
  2287. pass # Already applied
  2288. # Legacy migration: Add notify_print_stopped column (for any existing partial tables)
  2289. try:
  2290. async with conn.begin_nested():
  2291. await conn.execute(
  2292. text("ALTER TABLE user_email_preferences ADD COLUMN notify_print_stopped BOOLEAN NOT NULL DEFAULT 1")
  2293. )
  2294. except (OperationalError, ProgrammingError):
  2295. pass # Column already exists or table created with full schema
  2296. # Migration: Add camera_rotation column to printers
  2297. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN camera_rotation INTEGER DEFAULT 0")
  2298. # Migration: Add awaiting_plate_clear column to printers (#961)
  2299. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN awaiting_plate_clear BOOLEAN DEFAULT FALSE NOT NULL")
  2300. # Migration: Add REST/Webhook smart plug fields
  2301. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_url VARCHAR(500)")
  2302. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_body TEXT")
  2303. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_url VARCHAR(500)")
  2304. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_body TEXT")
  2305. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_method VARCHAR(10)")
  2306. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_headers TEXT")
  2307. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_url VARCHAR(500)")
  2308. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_path VARCHAR(200)")
  2309. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_on_value VARCHAR(50)")
  2310. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_path VARCHAR(200)")
  2311. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_path VARCHAR(200)")
  2312. # Migration: Add separate REST power/energy URLs and multipliers
  2313. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_url VARCHAR(500)")
  2314. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_multiplier REAL DEFAULT 1.0")
  2315. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_url VARCHAR(500)")
  2316. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_multiplier REAL DEFAULT 1.0")
  2317. # Migration (#2539): a REST plug's lifetime energy counter, separate from its
  2318. # today counter. Devices differ in which they expose — a Shelly reports only
  2319. # a cumulative `aenergy.total`, a Tasmota behind a REST bridge reports both —
  2320. # and conflating the two made the cumulative value read as "today", so it
  2321. # never reset at midnight and "Total" stayed empty forever.
  2322. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_total_path VARCHAR(200)")
  2323. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_total_multiplier REAL DEFAULT 1.0")
  2324. # Migration: Add batch_id column to print_queue for batch grouping
  2325. try:
  2326. async with conn.begin_nested():
  2327. await conn.execute(
  2328. text(
  2329. "ALTER TABLE print_queue ADD COLUMN batch_id INTEGER REFERENCES print_batches(id) ON DELETE SET NULL"
  2330. )
  2331. )
  2332. except (OperationalError, ProgrammingError):
  2333. pass
  2334. # Migration (#342): batch orders — planning metadata on print_batches. The
  2335. # per-plate target rows live in their own table, created by create_all().
  2336. await _safe_execute(
  2337. conn, "ALTER TABLE print_batches ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  2338. )
  2339. await _safe_execute(conn, "ALTER TABLE print_batches ADD COLUMN notes TEXT")
  2340. if is_sqlite():
  2341. await _safe_execute(conn, "ALTER TABLE print_batches ADD COLUMN due_date DATETIME")
  2342. await _safe_execute(conn, "ALTER TABLE print_batches ADD COLUMN completed_at DATETIME")
  2343. else:
  2344. await _safe_execute(conn, "ALTER TABLE print_batches ADD COLUMN due_date TIMESTAMP")
  2345. await _safe_execute(conn, "ALTER TABLE print_batches ADD COLUMN completed_at TIMESTAMP")
  2346. # Migration (#342): attribute a logged run to the queue item that produced
  2347. # it, so batch cost/energy can be summed without guessing from archive_id.
  2348. await _safe_execute(
  2349. conn,
  2350. "ALTER TABLE print_log_entries ADD COLUMN queue_item_id INTEGER REFERENCES print_queue(id) ON DELETE SET NULL",
  2351. )
  2352. await _safe_execute(
  2353. conn, "CREATE INDEX IF NOT EXISTS ix_print_log_entries_queue_item_id ON print_log_entries (queue_item_id)"
  2354. )
  2355. # Migration: Shortest-job-first scheduling columns on print_queue
  2356. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN print_time_seconds INTEGER")
  2357. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN been_jumped BOOLEAN DEFAULT FALSE NOT NULL")
  2358. # Migration: Auto-print G-code injection (#422)
  2359. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE NOT NULL")
  2360. # Migration: Add backup_spools and backup_archives columns to github_backup_config
  2361. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_spools BOOLEAN DEFAULT 0")
  2362. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_archives BOOLEAN DEFAULT 0")
  2363. # Migration: Widen columns where SQLite allowed data beyond the declared VARCHAR limit
  2364. if not is_sqlite():
  2365. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_hash TYPE VARCHAR(255)")
  2366. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_prefix TYPE VARCHAR(20)")
  2367. await _safe_execute(conn, "ALTER TABLE print_archives ALTER COLUMN filament_color TYPE VARCHAR(200)")
  2368. # Migration: Create GIN index for full-text search on PostgreSQL
  2369. # (SQLite uses FTS5 virtual table instead, set up above)
  2370. if not is_sqlite():
  2371. try:
  2372. await conn.execute(
  2373. text("""
  2374. CREATE INDEX IF NOT EXISTS idx_archives_fulltext
  2375. ON print_archives
  2376. USING GIN (to_tsvector('simple',
  2377. COALESCE(print_name, '') || ' ' ||
  2378. COALESCE(filename, '') || ' ' ||
  2379. COALESCE(tags, '') || ' ' ||
  2380. COALESCE(notes, '') || ' ' ||
  2381. COALESCE(designer, '') || ' ' ||
  2382. COALESCE(filament_type, '')
  2383. ))
  2384. """)
  2385. )
  2386. except (OperationalError, ProgrammingError):
  2387. pass # Already applied
  2388. # Migration: Normalize empty printer_ids [] to NULL (global access) on API keys
  2389. # Previously both None and [] meant "all printers"; now [] means "no printers"
  2390. # PostgreSQL stores printer_ids as JSONB; comparing JSONB to a string literal fails
  2391. # with "operator does not exist: jsonb = unknown" — cast the literal to jsonb explicitly.
  2392. await _migrate_normalize_printer_ids(conn)
  2393. # Migration: Add auth_source column to users for LDAP support (#794)
  2394. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN auth_source VARCHAR(20) DEFAULT 'local' NOT NULL")
  2395. # Migration: Make password_hash nullable for LDAP users (#794)
  2396. # LDAP users have no local password — the column must allow NULL so auto-provisioning
  2397. # doesn't hit a NOT NULL constraint failure on upgraded installs whose users table was
  2398. # originally created before LDAP support landed.
  2399. if is_sqlite():
  2400. # SQLite can't ALTER COLUMN; patch sqlite_master directly via writable_schema.
  2401. # Bump schema_version afterwards so SQLite reloads the table definition from disk —
  2402. # without that bump, the current connection keeps enforcing the old NOT NULL from
  2403. # its cached schema. Safe because row data is untouched and the replace() is a
  2404. # no-op if the constraint has already been removed.
  2405. try:
  2406. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='users'"))
  2407. users_sql = result.scalar()
  2408. if users_sql and "password_hash VARCHAR(255) NOT NULL" in users_sql:
  2409. version_result = await conn.execute(text("PRAGMA schema_version"))
  2410. schema_version = version_result.scalar() or 0
  2411. await conn.execute(text("PRAGMA writable_schema = ON"))
  2412. await conn.execute(
  2413. text(
  2414. "UPDATE sqlite_master "
  2415. "SET sql = replace(sql, 'password_hash VARCHAR(255) NOT NULL', 'password_hash VARCHAR(255)') "
  2416. "WHERE type = 'table' AND name = 'users'"
  2417. )
  2418. )
  2419. await conn.execute(text(f"PRAGMA schema_version = {schema_version + 1}"))
  2420. await conn.execute(text("PRAGMA writable_schema = OFF"))
  2421. except (OperationalError, ProgrammingError) as exc:
  2422. logger.error(
  2423. "Failed to remove NOT NULL from users.password_hash via writable_schema — "
  2424. "OIDC/LDAP user creation will fail on this install: %s",
  2425. exc,
  2426. exc_info=True,
  2427. )
  2428. else:
  2429. await _safe_execute(conn, "ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL")
  2430. # Migration: Add energy_start_kwh to print_archives (#941)
  2431. # Persists the smart plug lifetime counter captured at print start, so per-print
  2432. # energy tracking survives a backend restart mid-print.
  2433. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN energy_start_kwh REAL")
  2434. # Migration: Add subtask_id to print_archives (#972)
  2435. # MQTT-provided task identifier used to resume the same archive row across a
  2436. # backend restart mid-print. Without it, a long print (e.g. 13h) triggers
  2437. # stale-cancel + new-archive, losing started_at continuity.
  2438. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN subtask_id VARCHAR(64)")
  2439. # Migration: Add bed_type to print_archives (#1253)
  2440. # Build plate type extracted from 3MF (curr_bed_type), drives the bed icon
  2441. # rendered on archive cards.
  2442. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN bed_type VARCHAR(64)")
  2443. # Migration: Add deleted_at to print_archives (#1343)
  2444. # Soft-delete sentinel so deleting an archive entry from the UI no longer
  2445. # wipes its filament / time / cost contribution from Quick Stats. Listings
  2446. # hide rows where deleted_at IS NOT NULL; the stats endpoint counts them all.
  2447. # DATETIME on SQLite, TIMESTAMP on PostgreSQL (PG doesn't accept DATETIME on
  2448. # ALTER TABLE the same way it tolerates it inside CREATE TABLE).
  2449. _deleted_at_type = "DATETIME" if is_sqlite() else "TIMESTAMP"
  2450. await _safe_execute(conn, f"ALTER TABLE print_archives ADD COLUMN deleted_at {_deleted_at_type}")
  2451. await _safe_execute(
  2452. conn,
  2453. "CREATE INDEX IF NOT EXISTS ix_print_archives_deleted_at ON print_archives (deleted_at)",
  2454. )
  2455. # Migration: Add bambuddy_forced_timelapse to print_archives (#1397)
  2456. # Tracks prints where Bambuddy forced the firmware to record a timelapse
  2457. # so the finish-photo extractor could pull the post-park-pre-drop frame.
  2458. # The cleanup path uses this to delete the timelapse both locally and on
  2459. # the printer's SD after extraction — the user didn't opt in to a
  2460. # timelapse recording. Postgres rejects `DEFAULT 0` for BOOLEAN; SQLite
  2461. # accepts both 0/FALSE — branch the literal.
  2462. _bool_false_literal = "0" if is_sqlite() else "FALSE"
  2463. await _safe_execute(
  2464. conn,
  2465. f"ALTER TABLE print_archives ADD COLUMN bambuddy_forced_timelapse BOOLEAN DEFAULT {_bool_false_literal}",
  2466. )
  2467. # Migration: Create smart_plug_energy_snapshots table (#941)
  2468. # Hourly snapshots of each plug's lifetime counter, so date-range queries in
  2469. # "total consumption" energy mode can compute (last - first) deltas.
  2470. await _safe_execute(
  2471. conn,
  2472. """
  2473. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  2474. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2475. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  2476. recorded_at DATETIME NOT NULL,
  2477. lifetime_kwh REAL NOT NULL
  2478. )
  2479. """
  2480. if is_sqlite()
  2481. else """
  2482. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  2483. id SERIAL PRIMARY KEY,
  2484. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  2485. recorded_at TIMESTAMP NOT NULL,
  2486. lifetime_kwh REAL NOT NULL
  2487. )
  2488. """,
  2489. )
  2490. await _safe_execute(
  2491. conn,
  2492. "CREATE INDEX IF NOT EXISTS ix_plug_energy_snapshots_plug_time "
  2493. "ON smart_plug_energy_snapshots(plug_id, recorded_at)",
  2494. )
  2495. # Migration: Add PKCE code_verifier column to auth_ephemeral_tokens
  2496. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN code_verifier VARCHAR(128)")
  2497. # Migration: Add TOTP replay-protection counter to user_totp
  2498. await _safe_execute(conn, "ALTER TABLE user_totp ADD COLUMN last_totp_counter BIGINT")
  2499. # Migration: Add challenge_id for pre-auth token client binding (HttpOnly cookie)
  2500. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN challenge_id VARCHAR(128)")
  2501. # Migration: Add auto_link_existing_accounts column to oidc_providers (M-4)
  2502. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  2503. if is_sqlite():
  2504. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT 0")
  2505. else:
  2506. await _safe_execute(
  2507. conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT false"
  2508. )
  2509. # Migration: Azure Entra ID support — configurable email claim and verification requirement
  2510. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN email_claim VARCHAR(64) DEFAULT 'email'")
  2511. # Postgres rejects `DEFAULT 1` for BOOLEAN columns.
  2512. if is_sqlite():
  2513. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT 1")
  2514. else:
  2515. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN require_email_verified BOOLEAN DEFAULT true")
  2516. # SEC-1 backfill: reset auto_link only for Fall B (email_claim='email' + require_email_verified=False).
  2517. # Fall C (custom claim) is now allowed to use auto_link — do NOT reset those rows.
  2518. # Runs BEFORE the CHECK constraint below so Fall B rows self-heal rather than failing
  2519. # PostgreSQL's "check constraint is violated by some row" on ADD CONSTRAINT.
  2520. # On fresh installs the column defaults guarantee this UPDATE matches zero rows.
  2521. # TRUE/FALSE literals are accepted by both SQLite (≥ 3.23) and PostgreSQL — no dialect branch needed.
  2522. try:
  2523. async with conn.begin_nested():
  2524. await conn.execute(
  2525. text(
  2526. "UPDATE oidc_providers SET auto_link_existing_accounts = FALSE "
  2527. "WHERE auto_link_existing_accounts = TRUE "
  2528. "AND email_claim = 'email' AND require_email_verified = FALSE"
  2529. )
  2530. )
  2531. except Exception as exc:
  2532. logger.error(
  2533. "SEC-1 safety backfill FAILED — auto_link_existing_accounts may remain enabled "
  2534. "on providers with unsafe email settings: %s",
  2535. exc,
  2536. exc_info=True,
  2537. )
  2538. raise
  2539. # SEC-1: Add DB-level CHECK constraint for existing PostgreSQL installs.
  2540. # SQLite does not support ALTER TABLE ADD CONSTRAINT — handled by __table_args__ at creation.
  2541. # Runs AFTER the backfill so Fall B rows don't fail constraint validation.
  2542. if not is_sqlite():
  2543. try:
  2544. async with conn.begin_nested():
  2545. await conn.execute(
  2546. text(
  2547. "ALTER TABLE oidc_providers ADD CONSTRAINT ck_auto_link_requires_verified_email_claim "
  2548. "CHECK (auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE)"
  2549. )
  2550. )
  2551. except (OperationalError, ProgrammingError) as exc:
  2552. msg = str(exc).lower()
  2553. if "already exists" not in msg:
  2554. logger.error(
  2555. "Security constraint migration FAILED — auto_link safety constraint may not be enforced: %s",
  2556. exc,
  2557. exc_info=True,
  2558. )
  2559. raise
  2560. # Migration: Update auto_link CHECK constraint formula (existing installs).
  2561. # Existing PostgreSQL installs that ran the ADD CONSTRAINT above with the old formula
  2562. # (or a previous version of this code) need an explicit DROP + ADD to update it.
  2563. # For SQLite, the table is recreated with the new constraint formula if the old formula
  2564. # is still present in sqlite_master (SQLite cannot ALTER TABLE DROP/ADD CONSTRAINT).
  2565. await _migrate_update_auto_link_constraint(conn)
  2566. # Migration: Add default_group_id to oidc_providers.
  2567. # Must run AFTER _migrate_update_auto_link_constraint to avoid being dropped during
  2568. # the SQLite table recreation that function performs on stale-formula databases.
  2569. await _safe_execute(
  2570. conn,
  2571. "ALTER TABLE oidc_providers ADD COLUMN default_group_id INTEGER REFERENCES groups(id) ON DELETE SET NULL",
  2572. )
  2573. # Migration: Add cached-icon columns to oidc_providers (#1333).
  2574. # SPA's strict CSP (img-src 'self' data: blob:) blocks hotlinking external
  2575. # icon hosts, so we proxy them: admin sets icon_url, backend fetches and
  2576. # caches the bytes here, the SPA renders <img src="/api/v1/auth/oidc/providers/{id}/icon">.
  2577. # Must run AFTER _migrate_update_auto_link_constraint for the same reason as
  2578. # default_group_id above (SQLite table recreation drops unknown columns).
  2579. # Dialect-conditional type: BLOB on SQLite, BYTEA on PostgreSQL.
  2580. _blob_type = "BLOB" if is_sqlite() else "BYTEA"
  2581. await _safe_execute(conn, f"ALTER TABLE oidc_providers ADD COLUMN icon_data {_blob_type}")
  2582. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN icon_content_type VARCHAR(20)")
  2583. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN icon_etag VARCHAR(64)")
  2584. # PostgreSQL-only: enforce the all-or-nothing triplet at the DB layer.
  2585. # SQLite cannot ADD CONSTRAINT to an existing table — fresh SQLite
  2586. # installs get the CHECK via metadata.create_all (model __table_args__);
  2587. # stale SQLite installs rely on the application layer, same trade-off
  2588. # as the default_group_id FK ON DELETE SET NULL above.
  2589. if not is_sqlite():
  2590. await _safe_execute(
  2591. conn,
  2592. "ALTER TABLE oidc_providers ADD CONSTRAINT ck_oidc_icon_triplet_co_null "
  2593. "CHECK ((icon_data IS NULL) = (icon_content_type IS NULL) "
  2594. "AND (icon_content_type IS NULL) = (icon_etag IS NULL))",
  2595. )
  2596. # Migration: Add password_changed_at to users (M-R7-B)
  2597. # Tracks the last time a user's password was changed/reset. JWTs whose iat
  2598. # predates this timestamp are rejected in all six auth validation paths.
  2599. # R4 fix: TIMESTAMP is accepted by both SQLite and PostgreSQL; DATETIME
  2600. # is rejected by Postgres ("type 'datetime' does not exist"), which made
  2601. # _safe_execute swallow the error and leave existing Postgres installs
  2602. # without the column — causing UndefinedColumnError on every User query.
  2603. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP")
  2604. # Migration: Back-fill password_changed_at = created_at for existing users (I2).
  2605. # Users who never changed their password would have NULL here, meaning old
  2606. # tokens could never be invalidated via the freshness check. Setting it to
  2607. # created_at is conservative: any token issued before the account was created
  2608. # is always invalid, so this is a safe lower bound.
  2609. async with conn.begin_nested():
  2610. await conn.execute(text("UPDATE users SET password_changed_at = created_at WHERE password_changed_at IS NULL"))
  2611. # Migration: Provenance columns on library_files for MakerWorld imports.
  2612. # source_url is indexed so "already imported" dedupe lookups stay O(log N)
  2613. # as the library grows.
  2614. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_type VARCHAR(32)")
  2615. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_url VARCHAR(512)")
  2616. await _safe_execute(
  2617. conn,
  2618. "CREATE INDEX IF NOT EXISTS ix_library_files_source_url ON library_files(source_url)",
  2619. )
  2620. # Migration: Cache metadata title on pending uploads (#1152 follow-up).
  2621. # Without this column the review card always shows the FTP filename while
  2622. # the eventual archive's print_name comes from the 3MF metadata title,
  2623. # creating a confusing review→archive name mismatch. Captured at upload
  2624. # time so /pending-uploads/ list calls don't have to reopen each 3MF.
  2625. await _safe_execute(
  2626. conn,
  2627. "ALTER TABLE pending_uploads ADD COLUMN metadata_print_name VARCHAR(255)",
  2628. )
  2629. # Migration: Per-user API key ownership + cloud-access scope (#1182).
  2630. # user_id is nullable so legacy keys (created before #1182) survive the
  2631. # migration; cloud routes reject calls from keys without an owner so the
  2632. # operator is forced to recreate them. ON DELETE CASCADE so deleting a user
  2633. # takes their keys with them — orphan keys must never authenticate.
  2634. # SQLite ignores REFERENCES on ADD COLUMN (not enforced but not an error);
  2635. # PostgreSQL enforces the FK from this point forward. Indexed for the
  2636. # auth-gate's owner→keys lookup that runs on every API-keyed request.
  2637. await _safe_execute(
  2638. conn,
  2639. "ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE CASCADE",
  2640. )
  2641. await _safe_execute(
  2642. conn,
  2643. "CREATE INDEX IF NOT EXISTS ix_api_keys_user_id ON api_keys(user_id)",
  2644. )
  2645. # ``DEFAULT 0`` works on SQLite (boolean is just integer-coerced) but
  2646. # asyncpg's strict type-check rejects it: "column is of type boolean but
  2647. # default expression is of type integer". Use ``DEFAULT FALSE`` so both
  2648. # dialects accept the same statement — same pattern as the print_queue
  2649. # gcode_injection migration above.
  2650. await _safe_execute(
  2651. conn,
  2652. "ALTER TABLE api_keys ADD COLUMN can_access_cloud BOOLEAN DEFAULT FALSE",
  2653. )
  2654. # Narrowly-scoped settings-write toggle for the dynamic-tariff push case
  2655. # documented in wiki/features/energy.md (#1356). Defaults FALSE so existing
  2656. # keys never silently gain settings-write capability on upgrade.
  2657. await _safe_execute(
  2658. conn,
  2659. "ALTER TABLE api_keys ADD COLUMN can_update_energy_cost BOOLEAN DEFAULT FALSE",
  2660. )
  2661. # GHSA-r2qv-8222-hqg3 (CVE-2026-pending, CVSS 9.9): split file-management out
  2662. # of the implicit "any API key" grant into an explicit scope flag. The
  2663. # allowlist-based ``_check_apikey_permissions`` (see ``core/auth.py``) routes
  2664. # LIBRARY_UPLOAD / LIBRARY_UPDATE_OWN / LIBRARY_DELETE_OWN / MAKERWORLD_IMPORT
  2665. # through this flag. DEFAULT TRUE matches the existing "queue + read" trust
  2666. # baseline; backfill mirrors can_queue so a key the user previously created as
  2667. # "queue-only" retains the file-upload step its queue workflow already used,
  2668. # while a hardened "read-only" key (can_queue=False) does not silently gain a
  2669. # new write capability on upgrade. Backfill is gated on column non-existence
  2670. # so user-edited values are never overwritten on subsequent startup.
  2671. column_existed = await _api_keys_column_exists(conn, "can_manage_library")
  2672. await _safe_execute(
  2673. conn,
  2674. "ALTER TABLE api_keys ADD COLUMN can_manage_library BOOLEAN DEFAULT TRUE",
  2675. )
  2676. if not column_existed:
  2677. async with conn.begin_nested():
  2678. await conn.execute(text("UPDATE api_keys SET can_manage_library = can_queue"))
  2679. # Same shape: SpoolBuddy NFC/scale/system endpoints plus manual inventory
  2680. # writes split out of the implicit "any API key" grant. Backfill mirrors
  2681. # ``can_queue`` so the bundled SpoolBuddy kiosk key (created via the CLI
  2682. # with can_queue=False) does NOT silently gain inventory writes — but
  2683. # the CLI override sets the new flag True explicitly, since the kiosk
  2684. # itself is the legitimate writer (see ``cli.py``).
  2685. column_existed = await _api_keys_column_exists(conn, "can_manage_inventory")
  2686. await _safe_execute(
  2687. conn,
  2688. "ALTER TABLE api_keys ADD COLUMN can_manage_inventory BOOLEAN DEFAULT TRUE",
  2689. )
  2690. if not column_existed:
  2691. async with conn.begin_nested():
  2692. await conn.execute(text("UPDATE api_keys SET can_manage_inventory = can_queue"))
  2693. # #1832 follow-up: carve maintenance CRUD out of the admin denylist so
  2694. # HA-style automations can log "cleaned nozzle" via API key. Distinct
  2695. # from the two backfills above: MAINTENANCE_CREATE / _UPDATE / _DELETE
  2696. # were EXPLICITLY denied for every API key under the pre-migration model
  2697. # (they were on ``_APIKEY_DENIED_PERMISSIONS``), so no existing
  2698. # integration relies on them. Column default TRUE matches the "safe,
  2699. # on-by-default" pattern for keys created via the UI going forward;
  2700. # existing rows backfill to FALSE so the upgrade path does not silently
  2701. # widen scope for keys created before this flag existed. Users opt in
  2702. # via Settings → API Keys per key.
  2703. column_existed = await _api_keys_column_exists(conn, "can_manage_maintenance")
  2704. await _safe_execute(
  2705. conn,
  2706. "ALTER TABLE api_keys ADD COLUMN can_manage_maintenance BOOLEAN DEFAULT TRUE",
  2707. )
  2708. if not column_existed:
  2709. async with conn.begin_nested():
  2710. await conn.execute(text("UPDATE api_keys SET can_manage_maintenance = FALSE"))
  2711. # #1888: carve archive CRUD (create/update/delete — NOT purge) out of the
  2712. # admin denylist so automations can prune old prints via API key. Same
  2713. # shape and reasoning as can_manage_maintenance above: ARCHIVES_CREATE /
  2714. # _UPDATE_* / _DELETE_* were EXPLICITLY denied for every API key under the
  2715. # pre-migration model (they were on ``_APIKEY_DENIED_PERMISSIONS``), so no
  2716. # existing integration relies on them. Column default TRUE for keys created
  2717. # via the UI going forward; existing rows backfill to FALSE so the upgrade
  2718. # path does not silently widen scope for keys created before this flag
  2719. # existed. Users opt in via Settings → API Keys per key. BOOLEAN is valid
  2720. # on both SQLite and Postgres, so no dialect branch is needed.
  2721. column_existed = await _api_keys_column_exists(conn, "can_manage_archives")
  2722. await _safe_execute(
  2723. conn,
  2724. "ALTER TABLE api_keys ADD COLUMN can_manage_archives BOOLEAN DEFAULT TRUE",
  2725. )
  2726. if not column_existed:
  2727. async with conn.begin_nested():
  2728. await conn.execute(text("UPDATE api_keys SET can_manage_archives = FALSE"))
  2729. # #1893: carve project CRUD + membership (create/update/delete, add-archives)
  2730. # out of the admin denylist so automations can manage projects via API key.
  2731. # Identical shape and reasoning to can_manage_archives above: PROJECTS_CREATE
  2732. # / _UPDATE / _DELETE were EXPLICITLY denied for every API key under the
  2733. # pre-migration model (they were on ``_APIKEY_DENIED_PERMISSIONS``), so no
  2734. # existing integration relies on them. Column default TRUE for keys created
  2735. # via the UI going forward; existing rows backfill to FALSE so the upgrade
  2736. # path does not silently widen scope for keys created before this flag
  2737. # existed. Users opt in via Settings → API Keys per key. BOOLEAN is valid on
  2738. # both SQLite and Postgres, so no dialect branch is needed.
  2739. column_existed = await _api_keys_column_exists(conn, "can_manage_projects")
  2740. await _safe_execute(
  2741. conn,
  2742. "ALTER TABLE api_keys ADD COLUMN can_manage_projects BOOLEAN DEFAULT TRUE",
  2743. )
  2744. if not column_existed:
  2745. async with conn.begin_nested():
  2746. await conn.execute(text("UPDATE api_keys SET can_manage_projects = FALSE"))
  2747. # Migration: Soft-delete column for trash bin (Issue #1008). Indexed so the
  2748. # sweeper's "SELECT ... WHERE deleted_at < cutoff" and the trash list's
  2749. # "WHERE deleted_at IS NOT NULL" stay cheap as the table grows.
  2750. #
  2751. # ``DATETIME`` is a SQLite-only type alias — PostgreSQL rejects it as
  2752. # invalid syntax, _safe_execute swallows the error, and the column is
  2753. # never added (breaking every query that references it). Emit
  2754. # dialect-appropriate SQL so both backends get the column.
  2755. if is_sqlite():
  2756. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at DATETIME")
  2757. else:
  2758. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at TIMESTAMP")
  2759. await _safe_execute(
  2760. conn,
  2761. "CREATE INDEX IF NOT EXISTS ix_library_files_deleted_at ON library_files(deleted_at)",
  2762. )
  2763. # Legacy SQLite installs created `settings` without a UNIQUE constraint on `key`,
  2764. # so `INSERT OR IGNORE` below silently degrades to a plain INSERT and dupes rows on
  2765. # every restart. Dedupe (keep lowest id per key) and add the missing unique index
  2766. # before seeding. Safe/idempotent on both dialects — fresh installs already have
  2767. # no dupes and `create_all` already emits the index.
  2768. async with conn.begin_nested():
  2769. await conn.execute(text("DELETE FROM settings WHERE id NOT IN (SELECT MIN(id) FROM settings GROUP BY key)"))
  2770. await _safe_execute(conn, "CREATE UNIQUE INDEX IF NOT EXISTS ix_settings_key ON settings(key)")
  2771. # Migration: Normalise provider_email to lowercase (SEC-3).
  2772. # Required for Entra ID where UPN/email claims may arrive in mixed case.
  2773. # LOWER() is supported by both SQLite and PostgreSQL; the UPDATE is idempotent.
  2774. # Executed directly (not via _safe_execute) so any column-reference failure
  2775. # is always fatal and never silently swallowed.
  2776. async with conn.begin_nested():
  2777. await conn.execute(
  2778. text(
  2779. "UPDATE user_oidc_links SET provider_email = LOWER(provider_email) "
  2780. "WHERE provider_email IS NOT NULL AND provider_email != LOWER(provider_email)"
  2781. )
  2782. )
  2783. # Migration: Create spoolman_slot_assignments table for local AMS-slot→Spoolman-spool mapping.
  2784. # Replaces the pattern of writing spool.location in Spoolman (which polluted the
  2785. # user-editable storage_location field in the UI).
  2786. # ck_ams_id_range formula was widened in #1274 to admit AMS-HT (ams_id 128-191).
  2787. await _safe_execute(
  2788. conn,
  2789. """
  2790. CREATE TABLE IF NOT EXISTS spoolman_slot_assignments (
  2791. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2792. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2793. 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),
  2794. tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3),
  2795. spoolman_spool_id INTEGER NOT NULL,
  2796. assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2797. CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)
  2798. )
  2799. """
  2800. if is_sqlite()
  2801. else """
  2802. CREATE TABLE IF NOT EXISTS spoolman_slot_assignments (
  2803. id SERIAL PRIMARY KEY,
  2804. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2805. 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),
  2806. tray_id INTEGER NOT NULL CHECK (tray_id >= 0 AND tray_id <= 3),
  2807. spoolman_spool_id INTEGER NOT NULL,
  2808. assigned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2809. CONSTRAINT uq_slot_assignment UNIQUE(printer_id, ams_id, tray_id)
  2810. )
  2811. """,
  2812. )
  2813. await _safe_execute(
  2814. conn,
  2815. "CREATE INDEX IF NOT EXISTS ix_slot_assignment_spool ON spoolman_slot_assignments (spoolman_spool_id)",
  2816. )
  2817. # Migration: widen ck_ams_id_range on spoolman_slot_assignments to allow
  2818. # AMS-HT ids (128-191). Existing installs created before #1274 carry the
  2819. # stale formula which rejects every AMS-HT slot link with a CHECK violation.
  2820. await _migrate_widen_spoolman_slot_ams_id_range(conn)
  2821. # Migration: Create spoolman_k_profile table for K-value calibration profiles linked to Spoolman spools.
  2822. await _safe_execute(
  2823. conn,
  2824. """
  2825. CREATE TABLE IF NOT EXISTS spoolman_k_profile (
  2826. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2827. spoolman_spool_id INTEGER NOT NULL,
  2828. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2829. extruder INTEGER NOT NULL DEFAULT 0 CHECK (extruder >= 0 AND extruder <= 1),
  2830. nozzle_diameter VARCHAR(10) NOT NULL DEFAULT '0.4',
  2831. nozzle_type VARCHAR(50),
  2832. k_value REAL NOT NULL,
  2833. name VARCHAR(100),
  2834. cali_idx INTEGER,
  2835. setting_id VARCHAR(50),
  2836. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2837. CONSTRAINT uq_spoolman_k_profile UNIQUE(spoolman_spool_id, printer_id, extruder, nozzle_diameter)
  2838. )
  2839. """
  2840. if is_sqlite()
  2841. else """
  2842. CREATE TABLE IF NOT EXISTS spoolman_k_profile (
  2843. id SERIAL PRIMARY KEY,
  2844. spoolman_spool_id INTEGER NOT NULL,
  2845. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  2846. extruder INTEGER NOT NULL DEFAULT 0 CHECK (extruder >= 0 AND extruder <= 1),
  2847. nozzle_diameter VARCHAR(10) NOT NULL DEFAULT '0.4',
  2848. nozzle_type VARCHAR(50),
  2849. k_value DOUBLE PRECISION NOT NULL,
  2850. name VARCHAR(100),
  2851. cali_idx INTEGER,
  2852. setting_id VARCHAR(50),
  2853. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2854. CONSTRAINT uq_spoolman_k_profile UNIQUE(spoolman_spool_id, printer_id, extruder, nozzle_diameter)
  2855. )
  2856. """,
  2857. )
  2858. await _safe_execute(
  2859. conn,
  2860. "CREATE INDEX IF NOT EXISTS ix_spoolman_k_profile_spool ON spoolman_k_profile (spoolman_spool_id)",
  2861. )
  2862. # Migration: Add provider column to github_backup_config for multi-provider support
  2863. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN provider VARCHAR(30) DEFAULT 'github'")
  2864. # Migration: Add allow_insecure_http column to github_backup_config for self-hosted HTTP instances
  2865. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN allow_insecure_http BOOLEAN DEFAULT FALSE")
  2866. # Seed default settings keys that must exist on fresh install
  2867. default_settings = [
  2868. ("advanced_auth_enabled", "false"),
  2869. ("smtp_auth_enabled", "true"),
  2870. ]
  2871. for key, value in default_settings:
  2872. try:
  2873. if is_sqlite():
  2874. await conn.execute(
  2875. text("INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)"),
  2876. {"key": key, "value": value},
  2877. )
  2878. else:
  2879. await conn.execute(
  2880. text("INSERT INTO settings (key, value) VALUES (:key, :value) ON CONFLICT (key) DO NOTHING"),
  2881. {"key": key, "value": value},
  2882. )
  2883. except (OperationalError, ProgrammingError):
  2884. pass
  2885. # Migration: Create filament_sku_settings table for reorder forecasting
  2886. if is_sqlite():
  2887. await _safe_execute(
  2888. conn,
  2889. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  2890. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2891. material VARCHAR(50) NOT NULL,
  2892. subtype VARCHAR(50),
  2893. brand VARCHAR(100),
  2894. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2895. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2896. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2897. color_name VARCHAR(100),
  2898. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2899. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2900. UNIQUE (material, subtype, brand, color_name)
  2901. )""",
  2902. )
  2903. async with conn.begin_nested():
  2904. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  2905. await _safe_execute(
  2906. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_value INTEGER NOT NULL DEFAULT 14"
  2907. )
  2908. await _safe_execute(
  2909. conn, "ALTER TABLE filament_sku_settings ADD COLUMN safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'"
  2910. )
  2911. await _safe_execute(
  2912. conn, "ALTER TABLE filament_sku_settings ADD COLUMN alerts_snoozed BOOLEAN NOT NULL DEFAULT 0"
  2913. )
  2914. # Migration: add color_name to filament_sku_settings so forecasts
  2915. # distinguish colours within a SKU. The matching ALTER for
  2916. # filament_shopping_list runs AFTER that table's CREATE below — on
  2917. # fresh installs the table doesn't exist yet at this point and
  2918. # _safe_execute does not swallow "no such table".
  2919. await _safe_execute(conn, "ALTER TABLE filament_sku_settings ADD COLUMN color_name VARCHAR(100)")
  2920. # Backfill and drop legacy safety_margin_days column — SQLite requires a table rebuild.
  2921. # Only run if the stale column still exists.
  2922. cols_result = await conn.execute(text("PRAGMA table_info(filament_sku_settings)"))
  2923. col_names = [row[1] for row in cols_result.fetchall()]
  2924. if "safety_margin_days" in col_names:
  2925. async with conn.begin_nested():
  2926. # Defensive: a previous startup may have crashed mid-rebuild leaving
  2927. # filament_sku_settings_new behind, which would break the CREATE below.
  2928. await conn.execute(text("DROP TABLE IF EXISTS filament_sku_settings_new"))
  2929. await conn.execute(
  2930. text(
  2931. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  2932. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  2933. )
  2934. )
  2935. await conn.execute(
  2936. text(
  2937. """CREATE TABLE filament_sku_settings_new (
  2938. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2939. material VARCHAR(50) NOT NULL,
  2940. subtype VARCHAR(50),
  2941. brand VARCHAR(100),
  2942. color_name VARCHAR(100),
  2943. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2944. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2945. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2946. alerts_snoozed BOOLEAN NOT NULL DEFAULT 0,
  2947. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2948. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2949. UNIQUE (material, subtype, brand, color_name)
  2950. )"""
  2951. )
  2952. )
  2953. await conn.execute(
  2954. text(
  2955. """INSERT INTO filament_sku_settings_new
  2956. (id, material, subtype, brand, color_name, lead_time_days, safety_margin_value,
  2957. safety_margin_unit, alerts_snoozed, created_at, updated_at)
  2958. SELECT id, material, subtype, brand, color_name, lead_time_days, safety_margin_value,
  2959. safety_margin_unit, COALESCE(alerts_snoozed, 0), created_at, updated_at
  2960. FROM filament_sku_settings"""
  2961. )
  2962. )
  2963. await conn.execute(text("DROP TABLE filament_sku_settings"))
  2964. await conn.execute(text("ALTER TABLE filament_sku_settings_new RENAME TO filament_sku_settings"))
  2965. # Widen the unique key to include color_name on pre-existing tables. The
  2966. # auto-created UNIQUE index still covers only (material, subtype, brand)
  2967. # after the ADD COLUMN above, so rebuild the table to refresh it (#forecast
  2968. # -color-grouping). Detected by inspecting the index columns; skipped once
  2969. # color_name is already part of the key.
  2970. idx_rows = await conn.execute(text("PRAGMA index_list(filament_sku_settings)"))
  2971. needs_uq_rebuild = False
  2972. for idx in idx_rows.fetchall():
  2973. if idx[3] != "u": # origin col: 'u' = UNIQUE constraint, 'c' = CREATE INDEX, 'pk' = primary key
  2974. continue
  2975. info = await conn.execute(text(f"PRAGMA index_info({idx[1]})"))
  2976. cols = {row[2] for row in info.fetchall()}
  2977. if "material" in cols and "color_name" not in cols:
  2978. needs_uq_rebuild = True
  2979. break
  2980. if needs_uq_rebuild:
  2981. async with conn.begin_nested():
  2982. await conn.execute(text("DROP TABLE IF EXISTS filament_sku_settings_uqfix"))
  2983. await conn.execute(
  2984. text(
  2985. """CREATE TABLE filament_sku_settings_uqfix (
  2986. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2987. material VARCHAR(50) NOT NULL,
  2988. subtype VARCHAR(50),
  2989. brand VARCHAR(100),
  2990. color_name VARCHAR(100),
  2991. lead_time_days INTEGER NOT NULL DEFAULT 0,
  2992. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  2993. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  2994. alerts_snoozed BOOLEAN NOT NULL DEFAULT 0,
  2995. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2996. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  2997. UNIQUE (material, subtype, brand, color_name)
  2998. )"""
  2999. )
  3000. )
  3001. await conn.execute(
  3002. text(
  3003. """INSERT INTO filament_sku_settings_uqfix
  3004. (id, material, subtype, brand, color_name, lead_time_days, safety_margin_value,
  3005. safety_margin_unit, alerts_snoozed, created_at, updated_at)
  3006. SELECT id, material, subtype, brand, color_name, lead_time_days, safety_margin_value,
  3007. safety_margin_unit, COALESCE(alerts_snoozed, 0), created_at, updated_at
  3008. FROM filament_sku_settings"""
  3009. )
  3010. )
  3011. await conn.execute(text("DROP TABLE filament_sku_settings"))
  3012. await conn.execute(text("ALTER TABLE filament_sku_settings_uqfix RENAME TO filament_sku_settings"))
  3013. await _safe_execute(
  3014. conn,
  3015. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  3016. id INTEGER PRIMARY KEY AUTOINCREMENT,
  3017. material VARCHAR(50) NOT NULL,
  3018. subtype VARCHAR(50),
  3019. brand VARCHAR(100),
  3020. color_name VARCHAR(100),
  3021. quantity_spools INTEGER NOT NULL DEFAULT 1,
  3022. note VARCHAR(500),
  3023. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  3024. purchased_at DATETIME,
  3025. added_at DATETIME DEFAULT CURRENT_TIMESTAMP
  3026. )""",
  3027. )
  3028. # Backfill color_name on pre-#1814 upgrades — the CREATE above already
  3029. # has it for fresh installs; the ALTER is the upgrade path. "duplicate
  3030. # column name" is swallowed by _safe_execute, so re-runs are no-ops.
  3031. await _safe_execute(conn, "ALTER TABLE filament_shopping_list ADD COLUMN color_name VARCHAR(100)")
  3032. # SQLite has no implicit updated_at trigger — add one so the column stays current.
  3033. await _safe_execute(
  3034. conn,
  3035. """CREATE TRIGGER IF NOT EXISTS trg_filament_sku_settings_updated_at
  3036. AFTER UPDATE ON filament_sku_settings FOR EACH ROW
  3037. BEGIN
  3038. UPDATE filament_sku_settings SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
  3039. END""",
  3040. )
  3041. else:
  3042. await _safe_execute(
  3043. conn,
  3044. """CREATE TABLE IF NOT EXISTS filament_sku_settings (
  3045. id SERIAL PRIMARY KEY,
  3046. material VARCHAR(50) NOT NULL,
  3047. subtype VARCHAR(50),
  3048. brand VARCHAR(100),
  3049. lead_time_days INTEGER NOT NULL DEFAULT 0,
  3050. safety_margin_value INTEGER NOT NULL DEFAULT 14,
  3051. safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days',
  3052. color_name VARCHAR(100),
  3053. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  3054. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  3055. UNIQUE (material, subtype, brand, color_name)
  3056. )""",
  3057. )
  3058. async with conn.begin_nested():
  3059. await conn.execute(text("UPDATE filament_sku_settings SET lead_time_days = 0 WHERE lead_time_days = 7"))
  3060. await _safe_execute(
  3061. conn,
  3062. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_value INTEGER NOT NULL DEFAULT 14",
  3063. )
  3064. await _safe_execute(
  3065. conn,
  3066. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS safety_margin_unit VARCHAR(10) NOT NULL DEFAULT 'days'",
  3067. )
  3068. await _safe_execute(
  3069. conn,
  3070. "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS alerts_snoozed BOOLEAN NOT NULL DEFAULT FALSE",
  3071. )
  3072. # Migration: add color_name to filament_sku_settings and widen the
  3073. # unique key to include it so forecasts distinguish colours within a
  3074. # SKU (#forecast-color-grouping). The matching ALTER for
  3075. # filament_shopping_list runs AFTER that table's CREATE below — on
  3076. # fresh installs the table doesn't exist yet at this point.
  3077. await _safe_execute(conn, "ALTER TABLE filament_sku_settings ADD COLUMN IF NOT EXISTS color_name VARCHAR(100)")
  3078. # Widen UNIQUE (material, subtype, brand) → (material, subtype, brand, color_name).
  3079. # The original constraint was declared with name="uq_filament_sku" in the
  3080. # model, so we drop/re-add by that name. Gated on a pg_constraint lookup so
  3081. # the rebuild only runs when color_name is missing from the key — without
  3082. # the gate, every startup would take an ACCESS EXCLUSIVE lock on the table
  3083. # and churn the constraint.
  3084. uq_check = await conn.execute(
  3085. text(
  3086. "SELECT 1 FROM pg_constraint c "
  3087. "JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) "
  3088. "WHERE c.conname = 'uq_filament_sku' AND a.attname = 'color_name' LIMIT 1"
  3089. )
  3090. )
  3091. if uq_check.scalar_one_or_none() is None:
  3092. await _safe_execute(
  3093. conn,
  3094. "ALTER TABLE filament_sku_settings DROP CONSTRAINT IF EXISTS uq_filament_sku",
  3095. )
  3096. await _safe_execute(
  3097. conn,
  3098. "ALTER TABLE filament_sku_settings ADD CONSTRAINT uq_filament_sku "
  3099. "UNIQUE (material, subtype, brand, color_name)",
  3100. )
  3101. # Only backfill from safety_margin_days if that column still exists (PostgreSQL).
  3102. col_check = await conn.execute(
  3103. text(
  3104. "SELECT 1 FROM information_schema.columns "
  3105. "WHERE table_name = 'filament_sku_settings' AND column_name = 'safety_margin_days'"
  3106. )
  3107. )
  3108. if col_check.fetchone():
  3109. async with conn.begin_nested():
  3110. await conn.execute(
  3111. text(
  3112. "UPDATE filament_sku_settings SET safety_margin_value = safety_margin_days "
  3113. "WHERE safety_margin_value = 14 AND safety_margin_days != 14"
  3114. )
  3115. )
  3116. await _safe_execute(
  3117. conn,
  3118. """CREATE TABLE IF NOT EXISTS filament_shopping_list (
  3119. id SERIAL PRIMARY KEY,
  3120. material VARCHAR(50) NOT NULL,
  3121. subtype VARCHAR(50),
  3122. brand VARCHAR(100),
  3123. color_name VARCHAR(100),
  3124. quantity_spools INTEGER NOT NULL DEFAULT 1,
  3125. note VARCHAR(500),
  3126. status VARCHAR(20) NOT NULL DEFAULT 'pending',
  3127. purchased_at TIMESTAMP,
  3128. added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  3129. )""",
  3130. )
  3131. await _safe_execute(
  3132. conn,
  3133. "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'pending'",
  3134. )
  3135. await _safe_execute(conn, "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS purchased_at TIMESTAMP")
  3136. # Backfill color_name on pre-#1814 upgrades — the CREATE above already
  3137. # has it for fresh installs; the ALTER is the upgrade path.
  3138. await _safe_execute(conn, "ALTER TABLE filament_shopping_list ADD COLUMN IF NOT EXISTS color_name VARCHAR(100)")
  3139. # Migration: Add inventory stock alert columns to notification_providers.
  3140. # Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  3141. if is_sqlite():
  3142. await _safe_execute(
  3143. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT 0"
  3144. )
  3145. await _safe_execute(
  3146. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT 0"
  3147. )
  3148. else:
  3149. await _safe_execute(
  3150. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_reorder_alert BOOLEAN DEFAULT false"
  3151. )
  3152. await _safe_execute(
  3153. conn, "ALTER TABLE notification_providers ADD COLUMN on_stock_break_alert BOOLEAN DEFAULT false"
  3154. )
  3155. # Migration: Heal orphan auth-related rows left behind by user-delete
  3156. # on SQLite. user_oidc_links, user_totp, user_otp_codes (introduced in
  3157. # PR #933) and long_lived_tokens (PR #1108) all declare ON DELETE
  3158. # CASCADE on user_id — both predate the explicit APIKey-cleanup
  3159. # pattern in PR #1182. PostgreSQL enforces the cascade, but SQLite
  3160. # ships with FK enforcement off, so rows pointing to a deleted user
  3161. # persisted — blocking SSO re-login (the OIDC callback finds the
  3162. # orphan link, fails to resolve the missing user, and falls through
  3163. # to "account_inactive" instead of triggering auto_create), leaking
  3164. # MFA secrets, and leaving camera-stream tokens whose secret_hash is
  3165. # still verify()-able by lookup_prefix. See issue #1285 (#1295 review
  3166. # extended the cleanup to long_lived_tokens). This migration is a
  3167. # no-op on PostgreSQL and idempotent on SQLite.
  3168. async with conn.begin_nested():
  3169. oidc_result = await conn.execute(
  3170. text("DELETE FROM user_oidc_links WHERE user_id NOT IN (SELECT id FROM users)")
  3171. )
  3172. totp_result = await conn.execute(text("DELETE FROM user_totp WHERE user_id NOT IN (SELECT id FROM users)"))
  3173. otp_result = await conn.execute(text("DELETE FROM user_otp_codes WHERE user_id NOT IN (SELECT id FROM users)"))
  3174. llt_result = await conn.execute(
  3175. text("DELETE FROM long_lived_tokens WHERE user_id NOT IN (SELECT id FROM users)")
  3176. )
  3177. oidc_n = oidc_result.rowcount or 0
  3178. totp_n = totp_result.rowcount or 0
  3179. otp_n = otp_result.rowcount or 0
  3180. llt_n = llt_result.rowcount or 0
  3181. if oidc_n or totp_n or otp_n or llt_n:
  3182. logger.info(
  3183. "Cleaned up orphan auth rows: %d OIDC links, %d TOTP, %d OTP codes, %d long-lived tokens",
  3184. oidc_n,
  3185. totp_n,
  3186. otp_n,
  3187. llt_n,
  3188. )
  3189. # Migration: extend print_log_entries with archive_id, cost, energy, failure_reason,
  3190. # created_by_id (#1378). Statistics queries shift from PrintArchive to PrintLogEntry
  3191. # so reprints contribute new rows instead of overwriting the source archive's data.
  3192. if is_sqlite():
  3193. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN archive_id INTEGER")
  3194. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN cost REAL")
  3195. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN energy_kwh REAL")
  3196. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN energy_cost REAL")
  3197. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN failure_reason VARCHAR(100)")
  3198. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN created_by_id INTEGER")
  3199. else:
  3200. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS archive_id INTEGER")
  3201. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS cost DOUBLE PRECISION")
  3202. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS energy_kwh DOUBLE PRECISION")
  3203. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS energy_cost DOUBLE PRECISION")
  3204. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS failure_reason VARCHAR(100)")
  3205. await _safe_execute(conn, "ALTER TABLE print_log_entries ADD COLUMN IF NOT EXISTS created_by_id INTEGER")
  3206. await _safe_execute(
  3207. conn, "CREATE INDEX IF NOT EXISTS ix_print_log_entries_archive_id ON print_log_entries (archive_id)"
  3208. )
  3209. # Backfill PrintLogEntry → PrintArchive linkage and per-event cost/energy
  3210. # for pre-#1378 rows the column-add migration left NULL (#1390).
  3211. #
  3212. # Without this backfill the user's Quick Stats show Filament Cost = 0 and
  3213. # Time Accuracy empty even though their archives carry both, because:
  3214. #
  3215. # - the new stats queries SUM PrintLogEntry.cost (NULL for old rows)
  3216. # - the time-accuracy query JOINs PrintArchive ON archive_id (NULL for
  3217. # old rows, so old runs get excluded from the average)
  3218. #
  3219. # Pre-#1378, archive.cost / energy_kwh / energy_cost were overwritten by
  3220. # each rerun, so the current archive values represent the *latest* run.
  3221. # Backfilling them onto the latest matching PrintLogEntry per archive
  3222. # reconstructs the pre-fix total exactly (sum across archives stays
  3223. # unchanged), and leaves earlier reprints with NULL cost so they
  3224. # contribute zero — matching the "first/latest writes, rest stay NULL"
  3225. # convention #1378 introduced for new prints.
  3226. #
  3227. # DML, not DDL — use conn.execute() inside a savepoint per _safe_execute's
  3228. # own docstring. SQL is plain ANSI (correlated UPDATE, MAX/GROUP BY/HAVING,
  3229. # CASE in HAVING) and runs unchanged on SQLite + PostgreSQL; verified
  3230. # against postgres:16-alpine + asyncpg.
  3231. #
  3232. # Step 1: link old log entries to their archive via print_name + printer_id.
  3233. # Picks the highest-id matching archive when multiple share the same key
  3234. # (newest archive wins — closest to the log's overwrite-then-leave shape).
  3235. from sqlalchemy import text as _text
  3236. async with conn.begin_nested():
  3237. await conn.execute(
  3238. _text("""
  3239. UPDATE print_log_entries
  3240. SET archive_id = (
  3241. SELECT a.id
  3242. FROM print_archives a
  3243. WHERE a.print_name = print_log_entries.print_name
  3244. AND (
  3245. a.printer_id = print_log_entries.printer_id
  3246. OR (a.printer_id IS NULL AND print_log_entries.printer_id IS NULL)
  3247. )
  3248. ORDER BY a.id DESC
  3249. LIMIT 1
  3250. )
  3251. WHERE archive_id IS NULL AND print_name IS NOT NULL
  3252. """)
  3253. )
  3254. # Step 2: backfill cost / energy_kwh / energy_cost onto the latest linked
  3255. # log entry per archive — the row whose creation time best matches the
  3256. # value currently stored on the archive (overwrite-on-reprint semantics
  3257. # under the old design). Only fires for archives where NO log entry has
  3258. # cost set yet, which gives the migration a clean idempotency property:
  3259. # the second pass sees the archive already has a cost-bearing run and
  3260. # leaves the rest of its history NULL (instead of marching up the
  3261. # ID-ordered list of NULL runs on every pass).
  3262. async with conn.begin_nested():
  3263. await conn.execute(
  3264. _text("""
  3265. UPDATE print_log_entries
  3266. SET cost = (SELECT cost FROM print_archives WHERE id = print_log_entries.archive_id),
  3267. energy_kwh = (SELECT energy_kwh FROM print_archives WHERE id = print_log_entries.archive_id),
  3268. energy_cost = (SELECT energy_cost FROM print_archives WHERE id = print_log_entries.archive_id)
  3269. WHERE id IN (
  3270. SELECT MAX(id)
  3271. FROM print_log_entries
  3272. WHERE archive_id IS NOT NULL
  3273. GROUP BY archive_id
  3274. HAVING SUM(CASE WHEN cost IS NOT NULL THEN 1 ELSE 0 END) = 0
  3275. )
  3276. """)
  3277. )
  3278. # Migration: smart_plugs gets per-plug auto-off-after-drying toggle and
  3279. # delay (#1349). Fires whenever any AMS attached to the linked printer
  3280. # finishes a dry cycle. Plain ANSI ALTER TABLE works on both SQLite and
  3281. # Postgres for INTEGER/BOOLEAN with simple defaults.
  3282. if is_sqlite():
  3283. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_after_drying BOOLEAN DEFAULT 0")
  3284. await _safe_execute(
  3285. conn, "ALTER TABLE smart_plugs ADD COLUMN off_delay_after_drying_minutes INTEGER DEFAULT 10"
  3286. )
  3287. else:
  3288. await _safe_execute(
  3289. conn,
  3290. "ALTER TABLE smart_plugs ADD COLUMN IF NOT EXISTS auto_off_after_drying BOOLEAN DEFAULT false",
  3291. )
  3292. await _safe_execute(
  3293. conn,
  3294. "ALTER TABLE smart_plugs ADD COLUMN IF NOT EXISTS off_delay_after_drying_minutes INTEGER DEFAULT 10",
  3295. )
  3296. # Migration: Add per-user Orca Cloud credential columns. Mirrors the Bambu
  3297. # Cloud columns but adds refresh_token + expires_at (Supabase PKCE issues
  3298. # short-lived access tokens with rotating refresh tokens), plus three
  3299. # transient PKCE state columns held during the auth handshake. DATETIME
  3300. # is SQLite-only — Postgres uses TIMESTAMP, so the datetime columns are
  3301. # dialect-branched per project convention.
  3302. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_token VARCHAR(2000)")
  3303. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_refresh_token VARCHAR(128)")
  3304. if is_sqlite():
  3305. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_expires_at DATETIME")
  3306. else:
  3307. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN IF NOT EXISTS orca_cloud_expires_at TIMESTAMP")
  3308. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_email VARCHAR(255)")
  3309. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_user_id VARCHAR(64)")
  3310. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_verifier VARCHAR(64)")
  3311. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_state VARCHAR(32)")
  3312. if is_sqlite():
  3313. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN orca_cloud_pending_at DATETIME")
  3314. else:
  3315. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN IF NOT EXISTS orca_cloud_pending_at TIMESTAMP")
  3316. # Migration: record when Bambu rejects a stored cloud token. Until now the
  3317. # only state we kept was the token string itself, so a dead credential was
  3318. # indistinguishable from a live one and the UI reported "connected" forever
  3319. # while every cloud call 401'd. DATETIME is SQLite-only — Postgres uses
  3320. # TIMESTAMP, so the column is dialect-branched per project convention.
  3321. if is_sqlite():
  3322. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_token_invalid_at DATETIME")
  3323. else:
  3324. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN IF NOT EXISTS cloud_token_invalid_at TIMESTAMP")
  3325. # Data migration: drop the embedded 3MF Title (`print_name`) from library
  3326. # file metadata so the FileManager displays the filename, not the title (#1489).
  3327. await _migrate_drop_library_print_name(conn)
  3328. # Data migration: queue items written before #2551 carry every selected plate's
  3329. # filament overrides, so a force-colour plate waits on colours it never prints.
  3330. await _migrate_scope_force_color_overrides_to_plate(conn)
  3331. # Backfill NULL print_archives.created_at — older rows (and rows imported
  3332. # via the SQLite ↔ Postgres cross-DB restore path) can land with NULL
  3333. # because the column was originally created without a DEFAULT clause and
  3334. # server_default=func.now() only fires at table creation, not column
  3335. # population. The list_archives response model requires a datetime, so a
  3336. # single NULL row 500s the whole endpoint (#1732).
  3337. async with conn.begin_nested():
  3338. if is_sqlite():
  3339. await conn.execute(
  3340. text(
  3341. "UPDATE print_archives "
  3342. "SET created_at = COALESCE(completed_at, started_at, datetime('now')) "
  3343. "WHERE created_at IS NULL"
  3344. )
  3345. )
  3346. else:
  3347. await conn.execute(
  3348. text(
  3349. "UPDATE print_archives "
  3350. "SET created_at = COALESCE(completed_at, started_at, NOW()) "
  3351. "WHERE created_at IS NULL"
  3352. )
  3353. )
  3354. # Migration: structured storage locations (#1004). Flat catalog of physical
  3355. # shelves/drawers; spool.location_id FK with storage_location kept denormalized.
  3356. await _safe_execute(
  3357. conn,
  3358. """
  3359. CREATE TABLE IF NOT EXISTS locations (
  3360. id INTEGER PRIMARY KEY AUTOINCREMENT,
  3361. name VARCHAR(255) NOT NULL UNIQUE,
  3362. name_key VARCHAR(255),
  3363. identifier VARCHAR(100),
  3364. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  3365. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  3366. )
  3367. """
  3368. if is_sqlite()
  3369. else """
  3370. CREATE TABLE IF NOT EXISTS locations (
  3371. id SERIAL PRIMARY KEY,
  3372. name VARCHAR(255) NOT NULL UNIQUE,
  3373. name_key VARCHAR(255),
  3374. identifier VARCHAR(100),
  3375. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  3376. updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  3377. )
  3378. """,
  3379. )
  3380. await _safe_execute(conn, "ALTER TABLE locations ADD COLUMN name_key VARCHAR(255)")
  3381. await _safe_execute(conn, "CREATE UNIQUE INDEX IF NOT EXISTS ix_locations_name_key ON locations (name_key)")
  3382. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN location_id INTEGER REFERENCES locations(id)")
  3383. await _safe_execute(conn, "CREATE INDEX IF NOT EXISTS ix_spool_location_id ON spool (location_id)")
  3384. # Backfill name_key on legacy rows FIRST. If a pre-existing locations
  3385. # row was manually inserted before this migration ran, its name_key is
  3386. # NULL. The dedup INSERT below would then be silently skipped by
  3387. # UNIQUE(name) (legacy row already has the name), AND the spool-link
  3388. # UPDATE that joins on name_key would miss it. Doing this backfill BEFORE
  3389. # the INSERT keeps the join consistent on both branches of the migration.
  3390. async with conn.begin_nested():
  3391. await conn.execute(
  3392. text(
  3393. """
  3394. UPDATE locations
  3395. SET name_key = LOWER(TRIM(name))
  3396. WHERE name_key IS NULL OR TRIM(name_key) = ''
  3397. """
  3398. )
  3399. )
  3400. # Backfill locations from existing free-text storage_location values.
  3401. # GROUP BY name_key so case variants ("Drybox 1" / "DRYBOX 1") collapse to
  3402. # one row; INSERT OR IGNORE / ON CONFLICT keeps the migration idempotent.
  3403. _location_backfill_sql = (
  3404. """
  3405. INSERT OR IGNORE INTO locations (name, name_key, created_at, updated_at)
  3406. SELECT MIN(TRIM(storage_location)), LOWER(TRIM(storage_location)), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
  3407. FROM spool
  3408. WHERE TRIM(COALESCE(storage_location, '')) != ''
  3409. GROUP BY LOWER(TRIM(storage_location))
  3410. """
  3411. if is_sqlite()
  3412. else """
  3413. INSERT INTO locations (name, name_key, created_at, updated_at)
  3414. SELECT MIN(TRIM(storage_location)), LOWER(TRIM(storage_location)), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
  3415. FROM spool
  3416. WHERE TRIM(COALESCE(storage_location, '')) != ''
  3417. GROUP BY LOWER(TRIM(storage_location))
  3418. ON CONFLICT (name_key) DO NOTHING
  3419. """
  3420. )
  3421. async with conn.begin_nested():
  3422. await conn.execute(text(_location_backfill_sql))
  3423. await conn.execute(
  3424. text(
  3425. """
  3426. UPDATE spool
  3427. SET location_id = (
  3428. SELECT l.id FROM locations l
  3429. WHERE l.name_key = LOWER(TRIM(spool.storage_location))
  3430. LIMIT 1
  3431. )
  3432. WHERE TRIM(COALESCE(storage_location, '')) != ''
  3433. AND location_id IS NULL
  3434. """
  3435. )
  3436. )
  3437. # Sanity check: any spools that still have a free-text storage_location
  3438. # but no location_id link mean a row slipped through the dedup INSERT
  3439. # (most likely a pre-existing manually-inserted locations row with a
  3440. # hostile name shape that the UNIQUE(name) check tripped on). Surface
  3441. # the count so ops can investigate — the user won't see those spools in
  3442. # location-filtered queries until they're manually linked or re-saved.
  3443. orphan_count_row = await conn.execute(
  3444. text("SELECT COUNT(*) FROM spool WHERE TRIM(COALESCE(storage_location, '')) != '' AND location_id IS NULL")
  3445. )
  3446. orphan_count = orphan_count_row.scalar() or 0
  3447. if orphan_count:
  3448. logger.warning(
  3449. "Storage-location migration left %d spool(s) with free-text storage_location "
  3450. "but no location_id link. Re-save those spools or merge the orphaned location "
  3451. "names manually.",
  3452. orphan_count,
  3453. )
  3454. # Migration: Add on_ai_failure_detection column to notification_providers (#1794).
  3455. # Splits Obico AI failure detection out of the multiplexed on_printer_error
  3456. # event so users can subscribe to spaghetti alerts independently of HMS
  3457. # hardware-error alerts. Postgres rejects `DEFAULT 0` for BOOLEAN columns.
  3458. if is_sqlite():
  3459. await _safe_execute(
  3460. conn,
  3461. "ALTER TABLE notification_providers ADD COLUMN on_ai_failure_detection BOOLEAN DEFAULT 0",
  3462. )
  3463. else:
  3464. await _safe_execute(
  3465. conn,
  3466. "ALTER TABLE notification_providers ADD COLUMN on_ai_failure_detection BOOLEAN DEFAULT false",
  3467. )
  3468. # Migration: Add gate_acknowledged column to print_queue (#1818). Cleared
  3469. # by the per-printer "Resume after failure" action so the scheduler's
  3470. # `_check_previous_success` lookback skips this row. Postgres rejects
  3471. # `DEFAULT 0` for BOOLEAN columns.
  3472. if is_sqlite():
  3473. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gate_acknowledged BOOLEAN DEFAULT 0")
  3474. else:
  3475. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gate_acknowledged BOOLEAN DEFAULT false")
  3476. # Migration: Add is_autologin column to oidc_providers (#1589). Postgres
  3477. # rejects ``DEFAULT 0`` for BOOLEAN columns.
  3478. if is_sqlite():
  3479. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN is_autologin BOOLEAN DEFAULT 0")
  3480. else:
  3481. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN is_autologin BOOLEAN DEFAULT false")
  3482. # Migration: Add is_env_managed column to oidc_providers (#2593). Marks the
  3483. # provider upserted from BAMBUDDY_OIDC_* env vars on startup. Postgres
  3484. # rejects ``DEFAULT 0`` for BOOLEAN columns.
  3485. if is_sqlite():
  3486. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN is_env_managed BOOLEAN DEFAULT 0")
  3487. else:
  3488. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN is_env_managed BOOLEAN DEFAULT false")
  3489. # Migration: Add dispatch_attempts to print_queue (#2555). Counts the times
  3490. # the start-watchdog reverted the row from 'printing' back to 'pending' so a
  3491. # printer that never actually starts stops being retried forever. INTEGER
  3492. # DEFAULT 0 is spelled identically on SQLite and Postgres — no dialect branch.
  3493. # Verified on both dialects: ADD COLUMN ... DEFAULT 0 backfills existing rows,
  3494. # so no separate UPDATE is needed (and _safe_execute is DDL-only — see its
  3495. # docstring). The scheduler reads it as `(item.dispatch_attempts or 0) + 1`
  3496. # regardless, so even a NULL row could not disable the retry cap.
  3497. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN dispatch_attempts INTEGER DEFAULT 0")
  3498. # Backfill: copy the selected plate from linked queue rows onto their archives
  3499. # (#2603). Recovers the plate for archives created before print_archives had a
  3500. # plate_id column, wherever the queue row still points at the archive and
  3501. # carries a plate. Runs here — after every print_queue column migration
  3502. # (plate_id, archive_id) — because it reads print_queue.plate_id, which is
  3503. # added far earlier in this function but must exist before this DML runs on a
  3504. # first-ever migration pass. Correlated-subquery form so the DML is identical
  3505. # on SQLite and Postgres; the WHERE plate_id IS NULL guard makes it idempotent
  3506. # and keeps it from clobbering values set on later runs.
  3507. async with conn.begin_nested():
  3508. # Only do any work (and, on SQLite, the FTS rebuild below) when there is
  3509. # actually a plate to recover — so this is a one-off cost on the upgrade
  3510. # boot, not an every-boot tax once every archive is backfilled.
  3511. has_work = (
  3512. await conn.execute(
  3513. text(
  3514. "SELECT 1 FROM print_archives a "
  3515. "JOIN print_queue q ON q.archive_id = a.id "
  3516. "WHERE a.plate_id IS NULL AND q.plate_id IS NOT NULL "
  3517. "LIMIT 1"
  3518. )
  3519. )
  3520. ).first() is not None
  3521. if has_work:
  3522. # SQLite: print_archives has an external-content FTS index (archive_fts,
  3523. # created above) whose AFTER UPDATE trigger issues an FTS 'delete' for
  3524. # the row. Archives created before that table existed were never indexed
  3525. # (its creation runs no rebuild), and updating an un-indexed row trips
  3526. # "database disk image is malformed". plate_id isn't even an FTS column,
  3527. # so the trigger's re-index is pointless here — but it still fires. Rebuild
  3528. # the index from the content table first so every row is present and the
  3529. # trigger's 'delete' is well-defined. Postgres has no such FTS table.
  3530. if is_sqlite():
  3531. await conn.execute(text("INSERT INTO archive_fts(archive_fts) VALUES('rebuild')"))
  3532. await conn.execute(
  3533. text(
  3534. "UPDATE print_archives "
  3535. "SET plate_id = ("
  3536. " SELECT pq.plate_id FROM print_queue pq "
  3537. " WHERE pq.archive_id = print_archives.id AND pq.plate_id IS NOT NULL "
  3538. " LIMIT 1"
  3539. ") "
  3540. "WHERE plate_id IS NULL "
  3541. "AND EXISTS ("
  3542. " SELECT 1 FROM print_queue pq "
  3543. " WHERE pq.archive_id = print_archives.id AND pq.plate_id IS NOT NULL"
  3544. ")"
  3545. )
  3546. )
  3547. # Migration: repair completed print-log rows that stored a multi-plate 3MF's
  3548. # whole-file filament instead of the printed plate's (#2614). Runs AFTER the
  3549. # #2603 archive plate_id backfill above so print_archives.plate_id is populated.
  3550. await _migrate_scope_run_filament_to_plate(conn)
  3551. # Migration: Add controls_printer_power to smart_plugs (#2629). Marks
  3552. # whether a plug actually feeds the printer's own power — only then may an
  3553. # auto-off mark the printer offline. Defaults to true so existing plugs
  3554. # keep the previous behaviour; accessory plugs (filter fan, lights) are
  3555. # opted out by the user. BOOLEAN literals differ per dialect (SQLite has
  3556. # no true/false keyword), so the default is dialect-branched.
  3557. if is_sqlite():
  3558. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN controls_printer_power BOOLEAN DEFAULT 1")
  3559. else:
  3560. await _safe_execute(
  3561. conn,
  3562. "ALTER TABLE smart_plugs ADD COLUMN IF NOT EXISTS controls_printer_power BOOLEAN DEFAULT true",
  3563. )
  3564. # Migration: real filesystem mtime for library files/folders (#2680). The
  3565. # folder tree's "sort by recent activity" and the file pane's date sort must
  3566. # track the on-disk mtime (``ls -t``), not Bambuddy's DB ``updated_at`` — for
  3567. # a bulk external scan every row's ``updated_at`` is the same scan instant, so
  3568. # ordering was arbitrary. Nullable; the timestamp type differs by dialect
  3569. # (SQLite DATETIME vs Postgres TIMESTAMP) so an existing-DB upgrade doesn't hit
  3570. # "type datetime does not exist" on Postgres. On a fresh DB create_all() already
  3571. # built the column, so the ALTER is swallowed as "already exists".
  3572. if is_sqlite():
  3573. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN fs_modified_at DATETIME")
  3574. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN fs_modified_at DATETIME")
  3575. else:
  3576. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN fs_modified_at TIMESTAMP")
  3577. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN fs_modified_at TIMESTAMP")
  3578. # Migration: Disambiguate the four ``user_print_*`` notification template
  3579. # names by appending " Email" (#1792). See ``_migrate_rename_user_print_template_names``.
  3580. await _migrate_rename_user_print_template_names(conn)
  3581. # Migration: per-file print progress inside a project (#1897).
  3582. # - print_archives.library_file_id: which library file a queued run was
  3583. # dispatched from; nullable, no FK constraint added to existing tables
  3584. # (SQLite can't ADD CONSTRAINT; the application uses SET NULL semantics
  3585. # via the ORM on fresh installs and tolerates dangling ids by matching
  3586. # hash/filename as fallback anyway).
  3587. # - projects.target_sets: optional copies-per-file target. INTEGER is
  3588. # spelled identically on SQLite and Postgres — no dialect branch.
  3589. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN library_file_id INTEGER")
  3590. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_sets INTEGER")
  3591. # Migration: persist the timelapse snapshot-diff baseline (#2704).
  3592. # The list of video filenames present on the printer when the print began,
  3593. # so the diff survives a restart and the manual scan can use it instead of
  3594. # the clock-based matching that a LAN-only printer defeats. No dialect
  3595. # branch: SQLAlchemy renders this column as `JSON` on both SQLite and
  3596. # Postgres for a fresh install (checked with CreateTable against each
  3597. # dialect), so spelling the ALTER the same way keeps a migrated database
  3598. # identical to a new one. Matching matters on Postgres in particular —
  3599. # asyncpg binds the serialised value as json and would reject a TEXT column
  3600. # (mirrors the `projects.attachments JSON` migration above).
  3601. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN timelapse_baseline JSON")
  3602. # Migration: plate-clear-required notification opt-in (#2525). Off by
  3603. # default — it fires after every print, at the same moment as the
  3604. # print-complete alert. Postgres rejects `DEFAULT 0` for BOOLEAN.
  3605. if is_sqlite():
  3606. await _safe_execute(
  3607. conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_clear_required BOOLEAN DEFAULT 0"
  3608. )
  3609. else:
  3610. await _safe_execute(
  3611. conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_clear_required BOOLEAN DEFAULT false"
  3612. )
  3613. # Migration: variant grouping for library files (#671 / #2570). The
  3614. # `file_variant_groups` table itself needs no migration — create_all() above
  3615. # builds it — but the two member-side columns do. INTEGER and the inline
  3616. # REFERENCES clause are spelled identically on SQLite and Postgres, and
  3617. # SQLite accepts a REFERENCES on ADD COLUMN (same form as the
  3618. # pipeline_runs.parent_run_id migration at the top of this function).
  3619. await _safe_execute(
  3620. conn,
  3621. "ALTER TABLE library_files ADD COLUMN variant_group_id INTEGER "
  3622. "REFERENCES file_variant_groups(id) ON DELETE SET NULL",
  3623. )
  3624. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN variant_position INTEGER DEFAULT 0")
  3625. # User-declared target model for a file whose 3MF does not say (#671).
  3626. # VARCHAR(50) is spelled identically on SQLite and Postgres.
  3627. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN variant_target_model VARCHAR(50)")
  3628. # The model declares index=True, so fresh installs get this from create_all();
  3629. # migrated databases need it spelled out. Resolution looks members up by group
  3630. # on every scheduler pass that touches a grouped item.
  3631. await _safe_execute(
  3632. conn,
  3633. "CREATE INDEX IF NOT EXISTS ix_library_files_variant_group_id ON library_files (variant_group_id)",
  3634. )
  3635. await _migrate_backfill_variant_groups(conn)
  3636. # Migration: Home Assistant sensor alerts (#1148). The printer_ha_sensors
  3637. # table itself is new, so create_all() builds it; only the provider opt-in
  3638. # column needs adding to existing databases.
  3639. #
  3640. # DEFAULT FALSE, not DEFAULT 0: Postgres will not take an integer default
  3641. # for a boolean column, and _safe_execute swallows the DatatypeMismatchError
  3642. # — so the older "BOOLEAN DEFAULT 0" migrations above quietly do nothing on
  3643. # Postgres and only work there because create_all() builds the column on a
  3644. # fresh install. SQLite has understood FALSE since 3.23, so this spelling
  3645. # is the one that actually applies on both.
  3646. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_ha_sensor_alert BOOLEAN DEFAULT FALSE")
  3647. async def _migrate_backfill_variant_groups(conn) -> None:
  3648. """Build variant groups from the slice provenance already on disk (#671 / #2570).
  3649. ``sliced_from_library_file_id`` has been stamped into ``file_metadata`` by the
  3650. Slice button (routes/library.py) and the pipeline runner (routes/pipeline_runs.py)
  3651. since those features shipped, and until now nothing ever read it back — the
  3652. link existed but was inert. This promotes it to real group membership so an
  3653. existing library arrives with its slice sets already grouped instead of
  3654. requiring the user to re-declare by hand what Bambuddy itself recorded.
  3655. Only sources with **two or more** sliced children carrying **distinct**
  3656. ``sliced_for_model`` values produce a group:
  3657. - Fewer than two candidates is not a choice, and a one-member group would
  3658. change nothing at print time while creating a row per sliced file in every
  3659. library on earth.
  3660. - Two children sliced for the same printer are not alternatives — the
  3661. resolver has no basis to prefer one, so grouping them would turn a
  3662. harmless duplicate into an arbitrary pick. Those sources are skipped
  3663. whole; the user can still group them by hand and choose an order.
  3664. The unsliced source file is deliberately not a member. It has no
  3665. ``sliced_for_model``, so it can never be a dispatch candidate; showing it
  3666. alongside its variants is a File Manager listing concern, which is out of
  3667. scope.
  3668. Idempotent: only files with no group yet are considered, so a re-run after a
  3669. partial apply resumes rather than duplicating, and a user who has since
  3670. ungrouped files by hand does not get them silently regrouped.
  3671. """
  3672. from sqlalchemy import text
  3673. from backend.app.models.library import FileVariantGroup
  3674. if is_sqlite():
  3675. source_expr = "json_extract(file_metadata, '$.sliced_from_library_file_id')"
  3676. model_expr = "json_extract(file_metadata, '$.sliced_for_model')"
  3677. else:
  3678. # file_metadata is JSON, not JSONB — cast before using the -> operators,
  3679. # matching _migrate_drop_library_print_name above.
  3680. source_expr = "file_metadata::jsonb->>'sliced_from_library_file_id'"
  3681. model_expr = "file_metadata::jsonb->>'sliced_for_model'"
  3682. async with conn.begin_nested():
  3683. rows = (
  3684. await conn.execute(
  3685. text(
  3686. f"SELECT id, {source_expr} AS source_id, {model_expr} AS model " # noqa: S608 — dialect literals
  3687. "FROM library_files "
  3688. f"WHERE {source_expr} IS NOT NULL AND {model_expr} IS NOT NULL "
  3689. "AND variant_group_id IS NULL AND deleted_at IS NULL "
  3690. "ORDER BY id"
  3691. )
  3692. )
  3693. ).fetchall()
  3694. by_source: dict[str, list[tuple[int, str]]] = {}
  3695. for file_id, source_id, model in rows:
  3696. by_source.setdefault(str(source_id), []).append((file_id, str(model)))
  3697. for source_id, members in by_source.items():
  3698. if len(members) < 2:
  3699. continue
  3700. models = [m for _, m in members]
  3701. if len(set(models)) != len(models):
  3702. # Same printer sliced twice — ambiguous, leave it to the user.
  3703. continue
  3704. # Name the group after the source file when it is still around; its
  3705. # filename is what the user recognises. A deleted source leaves the
  3706. # variants perfectly usable, so fall back rather than skip.
  3707. name_row = (
  3708. await conn.execute(
  3709. text("SELECT filename FROM library_files WHERE id = :sid"),
  3710. {"sid": int(source_id)},
  3711. )
  3712. ).fetchone()
  3713. group_name = name_row[0] if name_row else f"{members[0][1]} + {len(members) - 1} more"
  3714. result = await conn.execute(FileVariantGroup.__table__.insert().values(name=group_name))
  3715. group_id = result.inserted_primary_key[0]
  3716. for position, (file_id, _model) in enumerate(members):
  3717. await conn.execute(
  3718. text("UPDATE library_files SET variant_group_id = :gid, variant_position = :pos WHERE id = :fid"),
  3719. {"gid": group_id, "pos": position, "fid": file_id},
  3720. )
  3721. _USER_PRINT_TEMPLATE_RENAMES: tuple[tuple[str, str, str], ...] = (
  3722. ("user_print_start", "User Print Started", "User Print Started Email"),
  3723. ("user_print_complete", "User Print Completed", "User Print Completed Email"),
  3724. ("user_print_failed", "User Print Failed", "User Print Failed Email"),
  3725. ("user_print_stopped", "User Print Stopped", "User Print Stopped Email"),
  3726. )
  3727. async def _migrate_rename_user_print_template_names(conn) -> None:
  3728. """Append " Email" to the four ``user_print_*`` notification template names (#1792).
  3729. The provider-level "Print Completed" and the per-user "User Print Completed"
  3730. rows were visually indistinguishable in the Message Templates list because
  3731. the seed name lacked the suffix that the EVENT_NAMES display map in
  3732. routes/notification_templates.py already uses ("User Print Completed Email").
  3733. Renames only rows where ``name`` is still the old default — admins who
  3734. renamed the template themselves keep their custom name. Standard SQL
  3735. UPDATE works on both SQLite and Postgres.
  3736. """
  3737. from sqlalchemy import text
  3738. async with conn.begin_nested():
  3739. for event_type, old_name, new_name in _USER_PRINT_TEMPLATE_RENAMES:
  3740. await conn.execute(
  3741. text("UPDATE notification_templates SET name = :new WHERE event_type = :et AND name = :old"),
  3742. {"new": new_name, "et": event_type, "old": old_name},
  3743. )
  3744. async def seed_notification_templates():
  3745. """Seed default notification templates if they don't exist."""
  3746. from sqlalchemy import select
  3747. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  3748. async with async_session() as session:
  3749. # Get existing template event types
  3750. result = await session.execute(select(NotificationTemplate.event_type))
  3751. existing_types = {row[0] for row in result.fetchall()}
  3752. if not existing_types:
  3753. # No templates exist - insert all defaults
  3754. for template_data in DEFAULT_TEMPLATES:
  3755. template = NotificationTemplate(
  3756. event_type=template_data["event_type"],
  3757. name=template_data["name"],
  3758. title_template=template_data["title_template"],
  3759. body_template=template_data["body_template"],
  3760. is_default=True,
  3761. )
  3762. session.add(template)
  3763. else:
  3764. # Templates exist - only add missing ones
  3765. for template_data in DEFAULT_TEMPLATES:
  3766. if template_data["event_type"] not in existing_types:
  3767. template = NotificationTemplate(
  3768. event_type=template_data["event_type"],
  3769. name=template_data["name"],
  3770. title_template=template_data["title_template"],
  3771. body_template=template_data["body_template"],
  3772. is_default=True,
  3773. )
  3774. session.add(template)
  3775. await session.commit()
  3776. async def seed_default_groups():
  3777. """Seed default groups and migrate existing users to appropriate groups.
  3778. Creates the default system groups (Administrators, Operators, Viewers) if they
  3779. don't exist, then migrates existing users:
  3780. - Users with role='admin' -> Administrators group
  3781. - Users with role='user' -> Operators group
  3782. Also migrates old permissions to new ownership-based permissions (Issue #205).
  3783. """
  3784. import logging
  3785. from sqlalchemy import select
  3786. from backend.app.core.permissions import ALL_PERMISSIONS, DEFAULT_GROUPS
  3787. from backend.app.models.group import Group
  3788. from backend.app.models.user import User
  3789. logger = logging.getLogger(__name__)
  3790. # Map old permissions to new ones for migration
  3791. # Administrators get *_all permissions, Operators get *_own permissions.
  3792. #
  3793. # NOTE on the read-flag asymmetry: write permissions (`update`, `delete`,
  3794. # `reprint`) are removed from the legacy flag and remapped to the OWN/ALL
  3795. # split — the legacy flag is dead on the API side. Read permissions are
  3796. # different: the frontend still gates UI actions (download buttons in
  3797. # ArchivesPage, preview button in FileManagerPage) on the LEGACY
  3798. # `archives:read` / `library:read` / `queue:read` strings. For admin we
  3799. # therefore keep the legacy flag (the `*_all` companion gets added via the
  3800. # backfill block below). For non-admin roles the legacy IS renamed to
  3801. # `_own` — that closes the IDOR (operators with a custom `archives:read`
  3802. # row can no longer read cross-user data) and the UI gates degrade to
  3803. # disabled-button state until the frontend is migrated to also accept
  3804. # `_own` (separate change). See maziggy/bambuddy-security #2.
  3805. PERMISSION_MIGRATION_ALL = {
  3806. "queue:update": "queue:update_all",
  3807. "queue:delete": "queue:delete_all",
  3808. "archives:update": "archives:update_all",
  3809. "archives:delete": "archives:delete_all",
  3810. "archives:reprint": "archives:reprint_all",
  3811. "library:update": "library:update_all",
  3812. "library:delete": "library:delete_all",
  3813. }
  3814. PERMISSION_MIGRATION_OWN = {
  3815. "queue:update": "queue:update_own",
  3816. "queue:delete": "queue:delete_own",
  3817. # Read permissions: any role NOT flagged as Administrator gets
  3818. # ownership-scoped reads. Pre-existing custom roles with the legacy
  3819. # `*:read` flag silently saw every user's items; the OWN variant
  3820. # closes that IDOR. Roles that genuinely need cross-user visibility
  3821. # must be re-granted `*:read_all` explicitly by an administrator
  3822. # after upgrade — fail-closed by default (per CWE-636).
  3823. "queue:read": "queue:read_own",
  3824. "archives:update": "archives:update_own",
  3825. "archives:delete": "archives:delete_own",
  3826. "archives:reprint": "archives:reprint_own",
  3827. "archives:read": "archives:read_own",
  3828. "library:update": "library:update_own",
  3829. "library:delete": "library:delete_own",
  3830. "library:read": "library:read_own",
  3831. }
  3832. async with async_session() as session:
  3833. # Get existing groups
  3834. result = await session.execute(select(Group))
  3835. existing_groups = {group.name: group for group in result.scalars().all()}
  3836. # Create default groups if they don't exist
  3837. groups_created = []
  3838. for group_name, group_config in DEFAULT_GROUPS.items():
  3839. if group_name not in existing_groups:
  3840. group = Group(
  3841. name=group_name,
  3842. description=group_config["description"],
  3843. permissions=group_config["permissions"],
  3844. is_system=group_config["is_system"],
  3845. )
  3846. session.add(group)
  3847. groups_created.append(group_name)
  3848. logger.info("Created default group: %s", group_name)
  3849. else:
  3850. # Migrate existing group's permissions from old to new format
  3851. group = existing_groups[group_name]
  3852. if group.permissions:
  3853. updated = False
  3854. new_permissions = list(group.permissions)
  3855. # Determine which migration map to use based on group
  3856. migration_map = (
  3857. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  3858. )
  3859. for old_perm, new_perm in migration_map.items():
  3860. if old_perm in new_permissions:
  3861. new_permissions.remove(old_perm)
  3862. if new_perm not in new_permissions:
  3863. new_permissions.append(new_perm)
  3864. updated = True
  3865. logger.info(
  3866. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  3867. )
  3868. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  3869. if group_name == "Administrators":
  3870. for _own_perm, all_perm in [
  3871. ("queue:update_own", "queue:update_all"),
  3872. ("queue:delete_own", "queue:delete_all"),
  3873. ("queue:read_own", "queue:read_all"),
  3874. ("archives:update_own", "archives:update_all"),
  3875. ("archives:delete_own", "archives:delete_all"),
  3876. ("archives:reprint_own", "archives:reprint_all"),
  3877. ("archives:read_own", "archives:read_all"),
  3878. ("library:update_own", "library:update_all"),
  3879. ("library:delete_own", "library:delete_all"),
  3880. ("library:read_own", "library:read_all"),
  3881. ]:
  3882. # Add *_all if not present
  3883. if all_perm not in new_permissions:
  3884. new_permissions.append(all_perm)
  3885. updated = True
  3886. if updated:
  3887. group.permissions = new_permissions
  3888. await session.commit()
  3889. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  3890. result = await session.execute(select(Group))
  3891. all_groups = result.scalars().all()
  3892. for group in all_groups:
  3893. if (
  3894. group.permissions
  3895. and "printers:control" in group.permissions
  3896. and "printers:clear_plate" not in group.permissions
  3897. ):
  3898. group.permissions = [*group.permissions, "printers:clear_plate"]
  3899. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  3900. await session.commit()
  3901. # Migrate new permissions for MakerWorld integration: groups that
  3902. # already have library:upload (i.e. can write to the library) are
  3903. # the correct audience for makerworld:view + makerworld:import, and
  3904. # groups that only have library:read get makerworld:view (browse
  3905. # only). Matches the intent of DEFAULT_GROUPS without clobbering
  3906. # any user-customised permission lists.
  3907. result = await session.execute(select(Group))
  3908. for group in result.scalars().all():
  3909. if not group.permissions:
  3910. continue
  3911. perms = list(group.permissions)
  3912. changed = False
  3913. if "library:upload" in perms:
  3914. for new_perm in ("makerworld:view", "makerworld:import"):
  3915. if new_perm not in perms:
  3916. perms.append(new_perm)
  3917. changed = True
  3918. logger.info("Added %s to group '%s' (has library:upload)", new_perm, group.name)
  3919. elif "library:read" in perms and "makerworld:view" not in perms:
  3920. perms.append("makerworld:view")
  3921. changed = True
  3922. logger.info("Added makerworld:view to group '%s' (has library:read)", group.name)
  3923. if changed:
  3924. group.permissions = perms
  3925. await session.commit()
  3926. # Backfill: sync the Administrators system group to ALL_PERMISSIONS.
  3927. # Administrators' contract is full access to every feature — fresh
  3928. # installs get that via DEFAULT_GROUPS["Administrators"]["permissions"]
  3929. # = ALL_PERMISSIONS. Upgrading installs would otherwise stay frozen at
  3930. # whatever permission set existed when they were first seeded, so a
  3931. # newly-added Permission enum member silently leaves admins gated out
  3932. # of the feature it controls.
  3933. #
  3934. # Generalises the previous one-off admin backfills (library:purge,
  3935. # archives:purge, the OWN/ALL read-flag set + legacy read flags,
  3936. # orca_cloud:auth, printer_sensor_history:read, …): every current
  3937. # Permission enum value is appended to the admin group if missing.
  3938. # Additive only — never removes a permission an operator added by
  3939. # hand. Run AFTER the legacy-rename migration above so the renamed
  3940. # OWN/ALL variants land in the group before the sync sees them.
  3941. result = await session.execute(select(Group).where(Group.name == "Administrators"))
  3942. admin_group = result.scalar_one_or_none()
  3943. if admin_group and admin_group.permissions is not None:
  3944. perms = list(admin_group.permissions)
  3945. added = False
  3946. for new_perm in ALL_PERMISSIONS:
  3947. if new_perm not in perms:
  3948. perms.append(new_perm)
  3949. added = True
  3950. logger.info("Added %s to Administrators group (ALL_PERMISSIONS sync)", new_perm)
  3951. if added:
  3952. admin_group.permissions = perms
  3953. await session.commit()
  3954. # Same OWN-tier backfill for non-admin system groups. Operators and
  3955. # Viewers are seeded with _own on fresh installs (see DEFAULT_GROUPS),
  3956. # but the legacy-rename migration above won't run on a role that
  3957. # didn't carry the legacy `archives:read` flag. Without this block,
  3958. # an existing Operators row whose permissions list lacks the legacy
  3959. # flag would never get archives:read_own and operators would lose
  3960. # read access after upgrade. Re-check by group name so customised
  3961. # rows still get the correct OWN tier on next startup.
  3962. #
  3963. # Operators also get orca_cloud:auth backfilled — fresh installs now
  3964. # include it in the DEFAULT_GROUPS bootstrap, so this keeps upgrades
  3965. # consistent. Viewers do NOT get orca_cloud:auth (read-only role,
  3966. # not expected to author slicer presets / sync to Orca Cloud).
  3967. for non_admin_group_name in ("Operators", "Viewers"):
  3968. grp = (await session.execute(select(Group).where(Group.name == non_admin_group_name))).scalar_one_or_none()
  3969. if grp is None or grp.permissions is None:
  3970. continue
  3971. perms = list(grp.permissions)
  3972. changed = False
  3973. for own_perm in ("archives:read_own", "library:read_own", "queue:read_own"):
  3974. if own_perm not in perms:
  3975. perms.append(own_perm)
  3976. changed = True
  3977. logger.info("Added %s to %s group (backfill)", own_perm, non_admin_group_name)
  3978. if non_admin_group_name == "Operators" and "orca_cloud:auth" not in perms:
  3979. perms.append("orca_cloud:auth")
  3980. changed = True
  3981. logger.info("Added orca_cloud:auth to Operators group (backfill)")
  3982. if changed:
  3983. grp.permissions = perms
  3984. await session.commit()
  3985. # Backfill inventory forecast permissions for existing groups.
  3986. # inventory:forecast_read was added after initial seeding, so groups
  3987. # that already have inventory:read (or inventory:update) need it added.
  3988. # inventory:forecast_write goes to any group with inventory:update.
  3989. result = await session.execute(select(Group))
  3990. for group in result.scalars().all():
  3991. if not group.permissions:
  3992. continue
  3993. perms = list(group.permissions)
  3994. changed = False
  3995. if "inventory:read" in perms and "inventory:forecast_read" not in perms:
  3996. perms.append("inventory:forecast_read")
  3997. changed = True
  3998. logger.info("Added inventory:forecast_read to group '%s' (backfill)", group.name)
  3999. if "inventory:update" in perms and "inventory:forecast_write" not in perms:
  4000. perms.append("inventory:forecast_write")
  4001. changed = True
  4002. logger.info("Added inventory:forecast_write to group '%s' (backfill)", group.name)
  4003. if changed:
  4004. group.permissions = perms
  4005. await session.commit()
  4006. # Backfill pipeline permissions (#1425) for non-admin groups.
  4007. # Administrators is handled by the ALL_PERMISSIONS sync above.
  4008. # - Operators: all three (matches fresh-install DEFAULT_GROUPS)
  4009. # - Any other group with library:read_own or settings:read:
  4010. # pipelines:read only
  4011. result = await session.execute(select(Group))
  4012. for group in result.scalars().all():
  4013. if not group.permissions or group.name == "Administrators":
  4014. continue
  4015. perms = list(group.permissions)
  4016. changed = False
  4017. if group.name == "Operators":
  4018. for new_perm in ("pipelines:read", "pipelines:write", "pipelines:run"):
  4019. if new_perm not in perms:
  4020. perms.append(new_perm)
  4021. changed = True
  4022. logger.info("Added %s to Operators group (backfill)", new_perm)
  4023. elif "pipelines:read" not in perms and ("library:read_own" in perms or "settings:read" in perms):
  4024. perms.append("pipelines:read")
  4025. changed = True
  4026. logger.info("Added pipelines:read to group '%s' (backfill)", group.name)
  4027. if changed:
  4028. group.permissions = perms
  4029. await session.commit()
  4030. # Migrate existing users to groups if they're not already in any group
  4031. if groups_created:
  4032. # Refresh to get newly created groups
  4033. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  4034. admin_group = admin_result.scalar_one_or_none()
  4035. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  4036. operators_group = operators_result.scalar_one_or_none()
  4037. # Get all users
  4038. users_result = await session.execute(select(User))
  4039. users = users_result.scalars().all()
  4040. for user in users:
  4041. # Skip if user already has groups
  4042. if user.groups:
  4043. continue
  4044. if user.role == "admin" and admin_group:
  4045. user.groups.append(admin_group)
  4046. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  4047. elif operators_group:
  4048. user.groups.append(operators_group)
  4049. logger.info("Migrated user '%s' to Operators group", user.username)
  4050. await session.commit()
  4051. async def seed_spool_catalog():
  4052. """Seed the spool catalog with default entries if empty."""
  4053. import logging
  4054. from sqlalchemy import func, select
  4055. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  4056. from backend.app.models.spool_catalog import SpoolCatalogEntry
  4057. logger = logging.getLogger(__name__)
  4058. async with async_session() as session:
  4059. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  4060. count = result.scalar() or 0
  4061. if count > 0:
  4062. return # Already seeded
  4063. for name, weight in DEFAULT_SPOOL_CATALOG:
  4064. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  4065. await session.commit()
  4066. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  4067. async def seed_color_catalog():
  4068. """Seed the color catalog with default entries if empty."""
  4069. import logging
  4070. from sqlalchemy import func, select
  4071. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  4072. from backend.app.models.color_catalog import ColorCatalogEntry
  4073. logger = logging.getLogger(__name__)
  4074. async with async_session() as session:
  4075. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  4076. count = result.scalar() or 0
  4077. if count > 0:
  4078. return # Already seeded
  4079. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  4080. session.add(
  4081. ColorCatalogEntry(
  4082. manufacturer=manufacturer,
  4083. color_name=color_name,
  4084. hex_color=hex_color,
  4085. material=material,
  4086. is_default=True,
  4087. )
  4088. )
  4089. await session.commit()
  4090. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))