database.py 265 KB

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