database.py 330 KB

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