database.py 251 KB

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