database.py 239 KB

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