database.py 310 KB

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