database.py 194 KB

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