database.py 361 KB

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