database.py 285 KB

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