database.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  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. def _create_engine():
  20. """Create the async engine with dialect-appropriate settings."""
  21. if is_sqlite():
  22. kwargs = {"pool_size": 20, "max_overflow": 200}
  23. else:
  24. kwargs = {"pool_size": 10, "max_overflow": 20}
  25. eng = create_async_engine(
  26. settings.database_url,
  27. echo=settings.debug,
  28. **kwargs,
  29. )
  30. if is_sqlite():
  31. event.listen(eng.sync_engine, "connect", _set_sqlite_pragmas)
  32. else:
  33. # Strip timezone info from aware datetimes before they reach asyncpg.
  34. # asyncpg rejects timezone-aware values for TIMESTAMP WITHOUT TIME ZONE columns.
  35. # The codebase uses datetime.now(timezone.utc) in many places — this makes
  36. # Postgres behave like SQLite which ignores timezone info entirely.
  37. @event.listens_for(eng.sync_engine, "before_cursor_execute", retval=True)
  38. def _strip_tz_from_params(conn, cursor, statement, parameters, context, executemany):
  39. import datetime
  40. if parameters is None:
  41. return statement, parameters
  42. # Recursive strip that walks any nesting of dict/list/tuple. Needed
  43. # because SQLAlchemy passes parameters in several shapes depending
  44. # on the path: a dict for named binds, a tuple for positional, a
  45. # list of dicts/tuples for executemany, and for insertmanyvalues
  46. # sometimes a list of tuples inside an outer list. The simplest
  47. # correct answer is "strip datetimes at any depth".
  48. def _strip(val):
  49. if isinstance(val, datetime.datetime) and val.tzinfo is not None:
  50. return val.replace(tzinfo=None)
  51. if isinstance(val, dict):
  52. return {k: _strip(v) for k, v in val.items()}
  53. if isinstance(val, list):
  54. return [_strip(v) for v in val]
  55. if isinstance(val, tuple):
  56. return tuple(_strip(v) for v in val)
  57. return val
  58. return statement, _strip(parameters)
  59. return eng
  60. engine = _create_engine()
  61. async_session = async_sessionmaker(
  62. engine,
  63. class_=AsyncSession,
  64. expire_on_commit=False,
  65. )
  66. async def run_with_retry(fn, *, max_attempts: int = 3, label: str = ""):
  67. """Run an async DB operation with retry for SQLite 'database is locked' errors.
  68. ``fn`` is an async callable that receives an ``AsyncSession`` and performs
  69. the full query-mutate-commit cycle. On each retry a fresh session is used
  70. so there are no stale-object / expired-attribute issues after rollback.
  71. On PostgreSQL this calls ``fn`` once with no retry (Postgres uses row-level
  72. locking and doesn't suffer from single-writer contention).
  73. """
  74. if not is_sqlite():
  75. async with async_session() as db:
  76. return await fn(db)
  77. last_exc: OperationalError | None = None
  78. for attempt in range(1, max_attempts + 1):
  79. try:
  80. async with async_session() as db:
  81. return await fn(db)
  82. except OperationalError as exc:
  83. last_exc = exc
  84. if "database is locked" not in str(exc) or attempt == max_attempts:
  85. raise
  86. delay = 0.5 * attempt # 0.5s, 1.0s
  87. logger.warning(
  88. "SQLite locked%s (attempt %d/%d), retrying in %.1fs: %s",
  89. f" ({label})" if label else "",
  90. attempt,
  91. max_attempts,
  92. delay,
  93. exc,
  94. )
  95. await asyncio.sleep(delay)
  96. raise last_exc # unreachable, but keeps type checkers happy
  97. async def close_all_connections():
  98. """Close all database connections for backup/restore operations."""
  99. global engine
  100. await engine.dispose()
  101. async def reinitialize_database():
  102. """Reinitialize database connection after restore."""
  103. global engine, async_session
  104. engine = _create_engine()
  105. async_session = async_sessionmaker(
  106. engine,
  107. class_=AsyncSession,
  108. expire_on_commit=False,
  109. )
  110. class Base(DeclarativeBase):
  111. pass
  112. async def get_db() -> AsyncSession:
  113. async with async_session() as session:
  114. try:
  115. yield session
  116. await session.commit()
  117. except Exception:
  118. await session.rollback()
  119. raise
  120. finally:
  121. await session.close()
  122. async def init_db():
  123. # Import models to register them with SQLAlchemy
  124. from backend.app.models import ( # noqa: F401
  125. active_print_spoolman,
  126. ams_history,
  127. ams_label,
  128. api_key,
  129. archive,
  130. auth_ephemeral,
  131. bug_report,
  132. color_catalog,
  133. external_link,
  134. filament,
  135. github_backup,
  136. group,
  137. kprofile_note,
  138. library,
  139. local_preset,
  140. maintenance,
  141. notification,
  142. notification_template,
  143. oidc_provider,
  144. orca_base_cache,
  145. pending_upload,
  146. print_batch,
  147. print_log,
  148. print_queue,
  149. printer,
  150. project,
  151. project_bom,
  152. settings,
  153. slot_preset,
  154. smart_plug,
  155. smart_plug_energy_snapshot,
  156. spool,
  157. spool_assignment,
  158. spool_catalog,
  159. spool_k_profile,
  160. spool_usage_history,
  161. spoolbuddy_device,
  162. user,
  163. user_email_pref,
  164. user_otp_code,
  165. user_totp,
  166. virtual_printer,
  167. )
  168. async with engine.begin() as conn:
  169. await conn.run_sync(Base.metadata.create_all)
  170. # Run migrations for new columns (SQLite doesn't auto-add columns)
  171. await run_migrations(conn)
  172. # Seed default notification templates
  173. await seed_notification_templates()
  174. # Seed default groups and migrate existing users
  175. await seed_default_groups()
  176. # Seed default catalog entries
  177. await seed_spool_catalog()
  178. await seed_color_catalog()
  179. async def _safe_execute(conn, sql):
  180. """Execute a migration statement, ignoring 'already exists' errors.
  181. Uses a savepoint so that a failed statement doesn't poison the
  182. surrounding transaction (required for PostgreSQL).
  183. """
  184. from sqlalchemy import text
  185. try:
  186. async with conn.begin_nested():
  187. await conn.execute(text(sql))
  188. except (OperationalError, ProgrammingError):
  189. pass
  190. async def run_migrations(conn):
  191. """Add new columns to existing tables if they don't exist."""
  192. from sqlalchemy import text
  193. # Migration: Add is_favorite column to print_archives
  194. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0")
  195. # Migration: Add content_hash column to print_archives for duplicate detection
  196. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)")
  197. # Migration: Add auto_off_executed column to smart_plugs
  198. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0")
  199. # Migration: Add on_print_stopped column to notification_providers
  200. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1")
  201. # Migration: Add source_3mf_path column to print_archives
  202. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)")
  203. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  204. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)")
  205. # Migration: Add on_maintenance_due column to notification_providers
  206. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0")
  207. # Migration: Add location column to printers for grouping
  208. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN location VARCHAR(100)")
  209. # Migration: Add interval_type column to maintenance_types
  210. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'")
  211. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  212. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0")
  213. # Migration: Add custom_interval_type column to printer_maintenance
  214. await _safe_execute(conn, "ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)")
  215. # Migration: Add power alert columns to smart_plugs
  216. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0")
  217. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL")
  218. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL")
  219. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME")
  220. # Migration: Add schedule columns to smart_plugs
  221. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0")
  222. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)")
  223. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)")
  224. # Migration: Add daily digest columns to notification_providers
  225. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0")
  226. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)")
  227. # Migration: Add missing-spool-assignment print-start notification toggle
  228. try:
  229. async with conn.begin_nested():
  230. await conn.execute(
  231. text(
  232. "ALTER TABLE notification_providers ADD COLUMN on_print_missing_spool_assignment BOOLEAN DEFAULT 0"
  233. )
  234. )
  235. except (OperationalError, ProgrammingError):
  236. pass # Already applied
  237. # Migration: Add project_id column to print_archives
  238. try:
  239. async with conn.begin_nested():
  240. await conn.execute(
  241. text(
  242. "ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  243. )
  244. )
  245. except (OperationalError, ProgrammingError):
  246. pass # Already applied
  247. # Migration: Add project_id column to print_queue
  248. try:
  249. async with conn.begin_nested():
  250. await conn.execute(
  251. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  252. )
  253. except (OperationalError, ProgrammingError):
  254. pass # Already applied
  255. # Migration: Enforce uniqueness on user_oidc_links for existing rows.
  256. # create_all() is idempotent and does not add constraints to existing tables,
  257. # so we create covering unique indexes explicitly here.
  258. await _safe_execute(
  259. conn,
  260. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_provider_sub"
  261. " ON user_oidc_links (provider_id, provider_user_id)",
  262. )
  263. await _safe_execute(
  264. conn,
  265. "CREATE UNIQUE INDEX IF NOT EXISTS uq_oidc_link_user_provider ON user_oidc_links (user_id, provider_id)",
  266. )
  267. # Migration: Create FTS5 virtual table for archive full-text search (SQLite only)
  268. # PostgreSQL uses tsvector + GIN index instead (set up in archives.py search route)
  269. if is_sqlite():
  270. try:
  271. await conn.execute(
  272. text("""
  273. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  274. print_name,
  275. filename,
  276. tags,
  277. notes,
  278. designer,
  279. filament_type,
  280. content='print_archives',
  281. content_rowid='id'
  282. )
  283. """)
  284. )
  285. except (OperationalError, ProgrammingError):
  286. pass # Already applied
  287. # Migration: Create triggers to keep FTS index in sync
  288. try:
  289. await conn.execute(
  290. text("""
  291. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  292. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  293. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  294. END
  295. """)
  296. )
  297. except (OperationalError, ProgrammingError):
  298. pass # Already applied
  299. try:
  300. await conn.execute(
  301. text("""
  302. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  303. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  304. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  305. END
  306. """)
  307. )
  308. except (OperationalError, ProgrammingError):
  309. pass # Already applied
  310. try:
  311. await conn.execute(
  312. text("""
  313. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  314. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  315. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  316. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  317. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  318. END
  319. """)
  320. )
  321. except (OperationalError, ProgrammingError):
  322. pass # Already applied
  323. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  324. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0")
  325. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME")
  326. # Migration: Add auto_off_persistent column to smart_plugs (keep auto-off enabled between prints)
  327. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN auto_off_persistent BOOLEAN DEFAULT 0")
  328. # Migration: Add AMS alarm notification columns to notification_providers
  329. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0")
  330. try:
  331. async with conn.begin_nested():
  332. await conn.execute(
  333. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  334. )
  335. except (OperationalError, ProgrammingError):
  336. pass # Already applied
  337. # Migration: Add AMS-HT alarm notification columns to notification_providers
  338. try:
  339. async with conn.begin_nested():
  340. await conn.execute(
  341. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  342. )
  343. except (OperationalError, ProgrammingError):
  344. pass # Already applied
  345. try:
  346. async with conn.begin_nested():
  347. await conn.execute(
  348. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  349. )
  350. except (OperationalError, ProgrammingError):
  351. pass # Already applied
  352. # Migration: Add plate not empty notification column to notification_providers
  353. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1")
  354. # Migration: Add notes column to projects (Phase 2)
  355. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN notes TEXT")
  356. # Migration: Add attachments column to projects (Phase 3)
  357. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN attachments JSON")
  358. # Migration: Add tags column to projects (Phase 4)
  359. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN tags TEXT")
  360. # Migration: Add due_date column to projects (Phase 5)
  361. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN due_date DATETIME")
  362. # Migration: Add priority column to projects (Phase 5)
  363. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'")
  364. # Migration: Add budget column to projects (Phase 6)
  365. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN budget REAL")
  366. # Migration: Add is_template column to projects (Phase 8)
  367. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0")
  368. # Migration: Add template_source_id column to projects (Phase 8)
  369. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN template_source_id INTEGER")
  370. # Migration: Add parent_id column to projects (Phase 10)
  371. try:
  372. async with conn.begin_nested():
  373. await conn.execute(
  374. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  375. )
  376. except (OperationalError, ProgrammingError):
  377. pass # Already applied
  378. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  379. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired")
  380. # Migration: Add unit_price column to project_bom_items
  381. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN unit_price REAL")
  382. # Migration: Add sourcing_url column to project_bom_items
  383. await _safe_execute(conn, "ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)")
  384. # Migration: Rename notes to remarks in project_bom_items
  385. await _safe_execute(conn, "ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks")
  386. # Migration: Add show_in_switchbar column to smart_plugs
  387. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0")
  388. # Migration: Add runtime tracking columns to printers
  389. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0")
  390. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME")
  391. # Migration: Add quantity column to print_archives for tracking item count
  392. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1")
  393. # Migration: Add manual_start column to print_queue for staged prints
  394. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0")
  395. # Migration: Add wiki_url column to maintenance_types for documentation links
  396. await _safe_execute(conn, "ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)")
  397. # Migration: Add tailscale_disabled column to virtual_printers for user opt-out
  398. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN tailscale_disabled BOOLEAN DEFAULT 0")
  399. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  400. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT")
  401. # Migration: Add target_parts_count column to projects for tracking total parts needed
  402. await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_parts_count INTEGER")
  403. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  404. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  405. # PostgreSQL gets the correct schema from create_all(), so skip this
  406. if is_sqlite():
  407. try:
  408. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  409. row = result.fetchone()
  410. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  411. await conn.execute(
  412. text("""
  413. CREATE TABLE print_queue_new (
  414. id INTEGER PRIMARY KEY,
  415. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  416. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  417. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  418. position INTEGER DEFAULT 0,
  419. scheduled_time DATETIME,
  420. manual_start BOOLEAN DEFAULT 0,
  421. require_previous_success BOOLEAN DEFAULT 0,
  422. auto_off_after BOOLEAN DEFAULT 0,
  423. ams_mapping TEXT,
  424. status VARCHAR(20) DEFAULT 'pending',
  425. started_at DATETIME,
  426. completed_at DATETIME,
  427. error_message TEXT,
  428. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  429. )
  430. """)
  431. )
  432. await conn.execute(
  433. text("""
  434. INSERT INTO print_queue_new
  435. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  436. manual_start, require_previous_success, auto_off_after, ams_mapping,
  437. status, started_at, completed_at, error_message, created_at
  438. FROM print_queue
  439. """)
  440. )
  441. await conn.execute(text("DROP TABLE print_queue"))
  442. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  443. except (OperationalError, ProgrammingError):
  444. pass # Already applied
  445. # Migration: Add plug_type column to smart_plugs for HA integration
  446. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'")
  447. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  448. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)")
  449. # Migration: Add project_id column to library_folders for linking folders to projects
  450. try:
  451. async with conn.begin_nested():
  452. await conn.execute(
  453. text(
  454. "ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  455. )
  456. )
  457. except (OperationalError, ProgrammingError):
  458. pass # Already applied
  459. # Migration: Add archive_id column to library_folders for linking folders to archives
  460. try:
  461. async with conn.begin_nested():
  462. await conn.execute(
  463. text(
  464. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  465. )
  466. )
  467. except (OperationalError, ProgrammingError):
  468. pass # Already applied
  469. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  470. # PostgreSQL gets the correct schema from create_all(), so skip this
  471. if is_sqlite():
  472. try:
  473. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  474. row = result.fetchone()
  475. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  476. await conn.execute(
  477. text("""
  478. CREATE TABLE smart_plugs_new (
  479. id INTEGER PRIMARY KEY,
  480. name VARCHAR(100) NOT NULL,
  481. ip_address VARCHAR(45),
  482. plug_type VARCHAR(20) DEFAULT 'tasmota',
  483. ha_entity_id VARCHAR(100),
  484. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  485. enabled BOOLEAN NOT NULL DEFAULT 1,
  486. auto_on BOOLEAN NOT NULL DEFAULT 1,
  487. auto_off BOOLEAN NOT NULL DEFAULT 1,
  488. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  489. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  490. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  491. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  492. username VARCHAR(50),
  493. password VARCHAR(100),
  494. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  495. power_alert_high FLOAT,
  496. power_alert_low FLOAT,
  497. power_alert_last_triggered DATETIME,
  498. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  499. schedule_on_time VARCHAR(5),
  500. schedule_off_time VARCHAR(5),
  501. show_in_switchbar BOOLEAN DEFAULT 0,
  502. last_state VARCHAR(10),
  503. last_checked DATETIME,
  504. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  505. auto_off_pending BOOLEAN DEFAULT 0,
  506. auto_off_pending_since DATETIME,
  507. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  508. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  509. )
  510. """)
  511. )
  512. await conn.execute(
  513. text("""
  514. INSERT INTO smart_plugs_new
  515. SELECT id, name, ip_address,
  516. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  517. enabled, auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  518. off_delay_mode, off_delay_minutes, off_temp_threshold,
  519. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  520. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  521. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  522. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  523. FROM smart_plugs
  524. """)
  525. )
  526. await conn.execute(text("DROP TABLE smart_plugs"))
  527. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  528. except (OperationalError, ProgrammingError):
  529. pass # Already applied
  530. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  531. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN plate_id INTEGER")
  532. # Migration: Add print options columns to print_queue
  533. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1")
  534. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0")
  535. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1")
  536. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0")
  537. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0")
  538. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1")
  539. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  540. # This allows queue items to reference library files directly (archive created at print start)
  541. try:
  542. async with conn.begin_nested():
  543. await conn.execute(
  544. text(
  545. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  546. )
  547. )
  548. except (OperationalError, ProgrammingError):
  549. pass # Already applied
  550. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  551. # PostgreSQL gets the correct schema from create_all(), so skip this
  552. if is_sqlite():
  553. try:
  554. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  555. row = result.fetchone()
  556. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  557. await conn.execute(
  558. text("""
  559. CREATE TABLE print_queue_new2 (
  560. id INTEGER PRIMARY KEY,
  561. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  562. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  563. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  564. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  565. position INTEGER DEFAULT 0,
  566. scheduled_time DATETIME,
  567. manual_start BOOLEAN DEFAULT 0,
  568. require_previous_success BOOLEAN DEFAULT 0,
  569. auto_off_after BOOLEAN DEFAULT 0,
  570. ams_mapping TEXT,
  571. plate_id INTEGER,
  572. bed_levelling BOOLEAN DEFAULT 1,
  573. flow_cali BOOLEAN DEFAULT 0,
  574. vibration_cali BOOLEAN DEFAULT 1,
  575. layer_inspect BOOLEAN DEFAULT 0,
  576. timelapse BOOLEAN DEFAULT 0,
  577. use_ams BOOLEAN DEFAULT 1,
  578. status VARCHAR(20) DEFAULT 'pending',
  579. started_at DATETIME,
  580. completed_at DATETIME,
  581. error_message TEXT,
  582. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  583. )
  584. """)
  585. )
  586. await conn.execute(
  587. text("""
  588. INSERT INTO print_queue_new2
  589. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  590. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  591. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  592. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  593. status, started_at, completed_at, error_message, created_at
  594. FROM print_queue
  595. """)
  596. )
  597. await conn.execute(text("DROP TABLE print_queue"))
  598. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  599. except (OperationalError, ProgrammingError):
  600. pass # Already applied
  601. # Migration: Add HA energy sensor entity columns to smart_plugs
  602. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)")
  603. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)")
  604. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)")
  605. # Migration: Create users table for authentication
  606. try:
  607. async with conn.begin_nested():
  608. await conn.execute(
  609. text("""
  610. CREATE TABLE IF NOT EXISTS users (
  611. id INTEGER PRIMARY KEY,
  612. username VARCHAR(100) NOT NULL UNIQUE,
  613. password_hash VARCHAR(255) NOT NULL,
  614. role VARCHAR(20) NOT NULL DEFAULT 'user',
  615. is_active BOOLEAN NOT NULL DEFAULT 1,
  616. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  617. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  618. )
  619. """)
  620. )
  621. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  622. except (OperationalError, ProgrammingError):
  623. pass # Already applied
  624. # Migration: Add external camera columns to printers
  625. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)")
  626. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)")
  627. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0")
  628. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  629. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)")
  630. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  631. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)")
  632. # Migration: Add is_external column to library_files for external cloud files
  633. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0")
  634. # Migration: Add project_id column to library_files
  635. try:
  636. async with conn.begin_nested():
  637. await conn.execute(
  638. text(
  639. "ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL"
  640. )
  641. )
  642. except (OperationalError, ProgrammingError):
  643. pass # Already applied
  644. # Migration: Add is_external column to library_folders for external cloud folders
  645. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0")
  646. # Migration: Add external folder settings columns to library_folders
  647. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0")
  648. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0")
  649. await _safe_execute(conn, "ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)")
  650. # Migration: Add plate_detection_enabled column to printers
  651. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0")
  652. # Migration: Add plate detection ROI columns to printers
  653. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL")
  654. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL")
  655. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL")
  656. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL")
  657. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  658. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  659. # SQLite requires table recreation to drop constraints
  660. # PostgreSQL gets the correct schema from create_all(), so skip this
  661. if is_sqlite():
  662. try:
  663. needs_migration = False
  664. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  665. row = result.fetchone()
  666. table_sql = (row[0] or "").upper() if row else ""
  667. if "PRINTER_ID" in table_sql and "UNIQUE" in table_sql:
  668. import re
  669. if re.search(r'"?PRINTER_ID"?\s+\w+\s+UNIQUE', table_sql) or re.search(
  670. r'UNIQUE\s*\([^)]*"?PRINTER_ID"?', table_sql
  671. ):
  672. needs_migration = True
  673. idx_result = await conn.execute(
  674. text("SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='smart_plugs' AND sql IS NOT NULL")
  675. )
  676. for idx_row in idx_result.fetchall():
  677. idx_sql = (idx_row[0] or "").upper()
  678. if "UNIQUE" in idx_sql and "PRINTER_ID" in idx_sql:
  679. needs_migration = True
  680. break
  681. if needs_migration:
  682. # Create new table without UNIQUE constraint on printer_id
  683. await conn.execute(
  684. text("""
  685. CREATE TABLE smart_plugs_temp (
  686. id INTEGER PRIMARY KEY,
  687. name VARCHAR(100) NOT NULL,
  688. ip_address VARCHAR(45),
  689. plug_type VARCHAR(20) DEFAULT 'tasmota',
  690. ha_entity_id VARCHAR(100),
  691. ha_power_entity VARCHAR(100),
  692. ha_energy_today_entity VARCHAR(100),
  693. ha_energy_total_entity VARCHAR(100),
  694. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  695. enabled BOOLEAN NOT NULL DEFAULT 1,
  696. auto_on BOOLEAN NOT NULL DEFAULT 1,
  697. auto_off BOOLEAN NOT NULL DEFAULT 1,
  698. auto_off_persistent BOOLEAN NOT NULL DEFAULT 0,
  699. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  700. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  701. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  702. username VARCHAR(50),
  703. password VARCHAR(100),
  704. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  705. power_alert_high FLOAT,
  706. power_alert_low FLOAT,
  707. power_alert_last_triggered DATETIME,
  708. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  709. schedule_on_time VARCHAR(5),
  710. schedule_off_time VARCHAR(5),
  711. show_in_switchbar BOOLEAN DEFAULT 0,
  712. last_state VARCHAR(10),
  713. last_checked DATETIME,
  714. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  715. auto_off_pending BOOLEAN DEFAULT 0,
  716. auto_off_pending_since DATETIME,
  717. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  718. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  719. )
  720. """)
  721. )
  722. # Copy data
  723. await conn.execute(
  724. text("""
  725. INSERT INTO smart_plugs_temp
  726. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  727. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  728. auto_on, auto_off, COALESCE(auto_off_persistent, 0),
  729. off_delay_mode, off_delay_minutes, off_temp_threshold,
  730. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  731. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  732. show_in_switchbar, last_state, last_checked, auto_off_executed,
  733. auto_off_pending, auto_off_pending_since, created_at, updated_at
  734. FROM smart_plugs
  735. """)
  736. )
  737. # Drop old table and rename new one
  738. await conn.execute(text("DROP TABLE smart_plugs"))
  739. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  740. except (OperationalError, ProgrammingError):
  741. pass # Already applied
  742. # Migration: Add show_on_printer_card column to smart_plugs
  743. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1")
  744. # Migration: Add MQTT smart plug fields (legacy)
  745. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)")
  746. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)")
  747. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)")
  748. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)")
  749. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0")
  750. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  751. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)")
  752. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0")
  753. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)")
  754. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0")
  755. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)")
  756. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)")
  757. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  758. try:
  759. async with conn.begin_nested():
  760. await conn.execute(
  761. text("""
  762. UPDATE smart_plugs
  763. SET mqtt_power_topic = mqtt_topic,
  764. mqtt_power_multiplier = mqtt_multiplier
  765. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  766. """)
  767. )
  768. except (OperationalError, ProgrammingError):
  769. pass # Already applied
  770. # Migration: Create groups table for permission-based access control
  771. try:
  772. async with conn.begin_nested():
  773. await conn.execute(
  774. text("""
  775. CREATE TABLE IF NOT EXISTS groups (
  776. id INTEGER PRIMARY KEY,
  777. name VARCHAR(100) NOT NULL UNIQUE,
  778. description VARCHAR(500),
  779. permissions JSON,
  780. is_system BOOLEAN NOT NULL DEFAULT 0,
  781. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  782. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  783. )
  784. """)
  785. )
  786. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  787. except (OperationalError, ProgrammingError):
  788. pass # Already applied
  789. # Migration: Create user_groups association table
  790. try:
  791. async with conn.begin_nested():
  792. await conn.execute(
  793. text("""
  794. CREATE TABLE IF NOT EXISTS user_groups (
  795. user_id INTEGER NOT NULL,
  796. group_id INTEGER NOT NULL,
  797. PRIMARY KEY (user_id, group_id),
  798. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  799. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  800. )
  801. """)
  802. )
  803. except (OperationalError, ProgrammingError):
  804. pass # Already applied
  805. # Migration: Add model-based queue assignment columns to print_queue
  806. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)")
  807. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT")
  808. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT")
  809. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  810. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1")
  811. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  812. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0")
  813. # Migration: Add queue notification event columns to notification_providers
  814. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0")
  815. try:
  816. async with conn.begin_nested():
  817. await conn.execute(
  818. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  819. )
  820. except (OperationalError, ProgrammingError):
  821. pass # Already applied
  822. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0")
  823. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1")
  824. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1")
  825. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1")
  826. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0")
  827. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  828. try:
  829. async with conn.begin_nested():
  830. await conn.execute(
  831. text(
  832. "ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  833. )
  834. )
  835. except (OperationalError, ProgrammingError):
  836. pass # Already applied
  837. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  838. try:
  839. async with conn.begin_nested():
  840. await conn.execute(
  841. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  842. )
  843. except (OperationalError, ProgrammingError):
  844. pass # Already applied
  845. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  846. try:
  847. async with conn.begin_nested():
  848. await conn.execute(
  849. text(
  850. "ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL"
  851. )
  852. )
  853. except (OperationalError, ProgrammingError):
  854. pass # Already applied
  855. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  856. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)")
  857. # Migration: Convert absolute paths to relative paths in library_files table
  858. # This ensures backup/restore portability across different installations
  859. try:
  860. async with conn.begin_nested():
  861. base_dir_str = str(settings.base_dir)
  862. # Ensure we have a trailing slash for clean replacement
  863. if not base_dir_str.endswith("/"):
  864. base_dir_str += "/"
  865. # Update file_path - remove base_dir prefix from absolute paths
  866. await conn.execute(
  867. text("""
  868. UPDATE library_files
  869. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  870. WHERE file_path LIKE :pattern
  871. """),
  872. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  873. )
  874. # Update thumbnail_path - remove base_dir prefix from absolute paths
  875. await conn.execute(
  876. text("""
  877. UPDATE library_files
  878. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  879. WHERE thumbnail_path LIKE :pattern
  880. """),
  881. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  882. )
  883. except (OperationalError, ProgrammingError):
  884. pass # Already applied
  885. # Create active_print_spoolman table for Spoolman per-filament tracking
  886. try:
  887. async with conn.begin_nested():
  888. await conn.execute(
  889. text("""
  890. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  891. id INTEGER PRIMARY KEY AUTOINCREMENT,
  892. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  893. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  894. filament_usage TEXT NOT NULL,
  895. ams_trays TEXT NOT NULL,
  896. slot_to_tray TEXT,
  897. layer_usage TEXT,
  898. filament_properties TEXT,
  899. UNIQUE(printer_id, archive_id)
  900. )
  901. """)
  902. )
  903. except (OperationalError, ProgrammingError):
  904. pass # Already applied
  905. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  906. try:
  907. async with conn.begin_nested():
  908. await conn.execute(
  909. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  910. )
  911. except (OperationalError, ProgrammingError):
  912. pass # Already applied
  913. # Migration: Add email column to users for Advanced Auth (PR #322)
  914. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN email VARCHAR(255)")
  915. # Migration: Add inventory spool tracking columns
  916. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN added_full BOOLEAN")
  917. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_used DATETIME")
  918. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN encode_time DATETIME")
  919. # Migration: Add RFID tag matching columns to spool
  920. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)")
  921. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)")
  922. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)")
  923. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)")
  924. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  925. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER")
  926. # Migration: Create spool_usage_history table for filament consumption tracking
  927. try:
  928. async with conn.begin_nested():
  929. await conn.execute(
  930. text("""
  931. CREATE TABLE IF NOT EXISTS spool_usage_history (
  932. id INTEGER PRIMARY KEY AUTOINCREMENT,
  933. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  934. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  935. print_name VARCHAR(500),
  936. weight_used REAL NOT NULL DEFAULT 0,
  937. percent_used INTEGER NOT NULL DEFAULT 0,
  938. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  939. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  940. )
  941. """)
  942. )
  943. except (OperationalError, ProgrammingError):
  944. pass # Already applied
  945. # Migration: Add open_in_new_tab column to external_links
  946. await _safe_execute(conn, "ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0")
  947. # Migration: Add bed cooled notification column to notification_providers
  948. await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0")
  949. # Migration: Add first layer complete notification column to notification_providers
  950. try:
  951. async with conn.begin_nested():
  952. await conn.execute(
  953. text("ALTER TABLE notification_providers ADD COLUMN on_first_layer_complete BOOLEAN DEFAULT 0")
  954. )
  955. except (OperationalError, ProgrammingError):
  956. pass # Already applied
  957. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  958. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0")
  959. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  960. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER")
  961. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME")
  962. # Migration: Add cost tracking fields to spool table
  963. await _safe_execute(conn, "ALTER TABLE spool ADD COLUMN cost_per_kg REAL")
  964. # Migration: Add cost field to spool_usage_history table
  965. await _safe_execute(conn, "ALTER TABLE spool_usage_history ADD COLUMN cost REAL")
  966. # Migration: Add archive_id field to spool_usage_history table
  967. try:
  968. async with conn.begin_nested():
  969. await conn.execute(
  970. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  971. )
  972. except (OperationalError, ProgrammingError):
  973. pass # Already applied
  974. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  975. try:
  976. async with conn.begin_nested():
  977. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  978. count = result.scalar() or 0
  979. if count == 0:
  980. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  981. row = result.fetchone()
  982. if row:
  983. # Old settings exist — migrate to first virtual printer row
  984. old_enabled = row[0] == "true" if row[0] else False
  985. result = await conn.execute(
  986. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  987. )
  988. row = result.fetchone()
  989. old_access_code = row[0] if row else None
  990. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  991. row = result.fetchone()
  992. old_mode = row[0] if row else "immediate"
  993. if old_mode == "queue":
  994. old_mode = "review"
  995. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  996. row = result.fetchone()
  997. old_model = row[0] if row else "BL-P001"
  998. result = await conn.execute(
  999. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1000. )
  1001. row = result.fetchone()
  1002. old_target_id = int(row[0]) if row and row[0] else None
  1003. result = await conn.execute(
  1004. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  1005. )
  1006. row = result.fetchone()
  1007. old_remote_iface = row[0] if row else None
  1008. await conn.execute(
  1009. text("""
  1010. INSERT INTO virtual_printers
  1011. (name, enabled, mode, model, access_code, target_printer_id,
  1012. bind_ip, remote_interface_ip, serial_suffix, position)
  1013. VALUES
  1014. (:name, :enabled, :mode, :model, :access_code, :target_id,
  1015. NULL, :remote_iface, '391800001', 0)
  1016. """),
  1017. {
  1018. "name": "Bambuddy",
  1019. "enabled": old_enabled,
  1020. "mode": old_mode or "immediate",
  1021. "model": old_model,
  1022. "access_code": old_access_code,
  1023. "target_id": old_target_id,
  1024. "remote_iface": old_remote_iface,
  1025. },
  1026. )
  1027. except (OperationalError, ProgrammingError, IntegrityError):
  1028. pass # Table may not exist yet on first run, or columns have different constraints
  1029. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  1030. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT")
  1031. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  1032. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)")
  1033. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)")
  1034. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100")
  1035. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0")
  1036. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0")
  1037. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME")
  1038. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  1039. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT")
  1040. # Migration: Add OTA update tracking columns to spoolbuddy_devices
  1041. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_status VARCHAR(20)")
  1042. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN update_message VARCHAR(255)")
  1043. # Migration: Persist SpoolBuddy backend URL and queued system payload
  1044. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN backend_url VARCHAR(255)")
  1045. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN pending_system_payload TEXT")
  1046. # Migration: Add system_stats JSON blob column to spoolbuddy_devices
  1047. await _safe_execute(conn, "ALTER TABLE spoolbuddy_devices ADD COLUMN system_stats TEXT")
  1048. # Migration: Convert ams_labels table from (printer_id, ams_id) key to ams_serial_number key
  1049. # Labels are now keyed by AMS serial number so they persist when the AMS is moved to another printer.
  1050. # PostgreSQL gets the correct schema from create_all(), so skip this
  1051. if is_sqlite():
  1052. try:
  1053. await conn.execute(text("DROP TABLE IF EXISTS ams_labels_new"))
  1054. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='ams_labels'"))
  1055. row = result.fetchone()
  1056. if row and "printer_id" in (row[0] or ""):
  1057. # Old schema: rebuild the table with ams_serial_number as the unique key.
  1058. # Existing rows get a synthetic serial "p{printer_id}a{ams_id}" so data is preserved.
  1059. await conn.execute(
  1060. text("""
  1061. CREATE TABLE ams_labels_new (
  1062. id INTEGER PRIMARY KEY,
  1063. ams_serial_number VARCHAR(50) NOT NULL,
  1064. ams_id INTEGER,
  1065. label VARCHAR(100) NOT NULL,
  1066. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1067. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1068. CONSTRAINT uq_ams_label_serial UNIQUE (ams_serial_number)
  1069. )
  1070. """)
  1071. )
  1072. await conn.execute(
  1073. text("""
  1074. INSERT INTO ams_labels_new (id, ams_serial_number, ams_id, label, created_at, updated_at)
  1075. SELECT id,
  1076. 'p' || CAST(printer_id AS TEXT) || 'a' || CAST(ams_id AS TEXT),
  1077. ams_id,
  1078. label,
  1079. created_at,
  1080. updated_at
  1081. FROM ams_labels
  1082. """)
  1083. )
  1084. await conn.execute(text("DROP TABLE ams_labels"))
  1085. await conn.execute(text("ALTER TABLE ams_labels_new RENAME TO ams_labels"))
  1086. except (OperationalError, ProgrammingError):
  1087. pass # Already migrated or table does not exist yet
  1088. # Migration: Add auto_dispatch column to virtual_printers
  1089. await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN auto_dispatch BOOLEAN DEFAULT 1")
  1090. # Migration: Fix VP model codes — convert legacy SSDP codes and display names to correct SSDP codes
  1091. # Legacy codes (from multi-VP refactor) and display names (from proxy auto-inherit)
  1092. vp_model_fixes = {
  1093. "3DPrinter-X1-Carbon": "BL-P001",
  1094. "3DPrinter-X1": "BL-P002",
  1095. "X1C": "BL-P001",
  1096. "X1": "BL-P002",
  1097. "X1E": "C13",
  1098. "X2D": "N6",
  1099. "P1P": "C11",
  1100. "P1S": "C12",
  1101. "P2S": "N7",
  1102. "A1": "N2S",
  1103. "A1 Mini": "N1",
  1104. "H2D": "O1D",
  1105. "H2C": "O1C",
  1106. "H2S": "O1S",
  1107. }
  1108. for old_val, new_val in vp_model_fixes.items():
  1109. await conn.execute(
  1110. text("UPDATE virtual_printers SET model = :new WHERE model = :old"),
  1111. {"old": old_val, "new": new_val},
  1112. )
  1113. await conn.execute(
  1114. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_model' AND value = :old"),
  1115. {"old": old_val, "new": new_val},
  1116. )
  1117. # Migration: Add per-user Bambu Cloud credential columns
  1118. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_token VARCHAR(500)")
  1119. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_email VARCHAR(255)")
  1120. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN cloud_region VARCHAR(10)")
  1121. # Cleanup: Remove obsolete settings keys that are no longer used
  1122. obsolete_keys = ["slicer_binary_path"]
  1123. for key in obsolete_keys:
  1124. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  1125. # Migration: Create user_email_preferences table for user-specific email notification settings
  1126. try:
  1127. async with conn.begin_nested():
  1128. await conn.execute(
  1129. text("""
  1130. CREATE TABLE IF NOT EXISTS user_email_preferences (
  1131. id INTEGER PRIMARY KEY,
  1132. user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  1133. notify_print_start BOOLEAN NOT NULL DEFAULT 1,
  1134. notify_print_complete BOOLEAN NOT NULL DEFAULT 1,
  1135. notify_print_failed BOOLEAN NOT NULL DEFAULT 1,
  1136. notify_print_stopped BOOLEAN NOT NULL DEFAULT 1,
  1137. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1138. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1139. )
  1140. """)
  1141. )
  1142. await conn.execute(
  1143. text("CREATE INDEX IF NOT EXISTS ix_user_email_preferences_user_id ON user_email_preferences(user_id)")
  1144. )
  1145. except (OperationalError, ProgrammingError):
  1146. pass # Already applied
  1147. # Legacy migration: Add notify_print_stopped column (for any existing partial tables)
  1148. try:
  1149. async with conn.begin_nested():
  1150. await conn.execute(
  1151. text("ALTER TABLE user_email_preferences ADD COLUMN notify_print_stopped BOOLEAN NOT NULL DEFAULT 1")
  1152. )
  1153. except (OperationalError, ProgrammingError):
  1154. pass # Column already exists or table created with full schema
  1155. # Migration: Add camera_rotation column to printers
  1156. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN camera_rotation INTEGER DEFAULT 0")
  1157. # Migration: Add awaiting_plate_clear column to printers (#961)
  1158. await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN awaiting_plate_clear BOOLEAN DEFAULT FALSE NOT NULL")
  1159. # Migration: Add REST/Webhook smart plug fields
  1160. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_url VARCHAR(500)")
  1161. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_on_body TEXT")
  1162. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_url VARCHAR(500)")
  1163. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_off_body TEXT")
  1164. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_method VARCHAR(10)")
  1165. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_headers TEXT")
  1166. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_url VARCHAR(500)")
  1167. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_path VARCHAR(200)")
  1168. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_status_on_value VARCHAR(50)")
  1169. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_path VARCHAR(200)")
  1170. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_path VARCHAR(200)")
  1171. # Migration: Add separate REST power/energy URLs and multipliers
  1172. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_url VARCHAR(500)")
  1173. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_power_multiplier REAL DEFAULT 1.0")
  1174. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_url VARCHAR(500)")
  1175. await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN rest_energy_multiplier REAL DEFAULT 1.0")
  1176. # Migration: Add batch_id column to print_queue for batch grouping
  1177. try:
  1178. async with conn.begin_nested():
  1179. await conn.execute(
  1180. text(
  1181. "ALTER TABLE print_queue ADD COLUMN batch_id INTEGER REFERENCES print_batches(id) ON DELETE SET NULL"
  1182. )
  1183. )
  1184. except (OperationalError, ProgrammingError):
  1185. pass
  1186. # Migration: Shortest-job-first scheduling columns on print_queue
  1187. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN print_time_seconds INTEGER")
  1188. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN been_jumped BOOLEAN DEFAULT FALSE NOT NULL")
  1189. # Migration: Auto-print G-code injection (#422)
  1190. await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE NOT NULL")
  1191. # Migration: Add backup_spools and backup_archives columns to github_backup_config
  1192. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_spools BOOLEAN DEFAULT 0")
  1193. await _safe_execute(conn, "ALTER TABLE github_backup_config ADD COLUMN backup_archives BOOLEAN DEFAULT 0")
  1194. # Migration: Widen columns where SQLite allowed data beyond the declared VARCHAR limit
  1195. if not is_sqlite():
  1196. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_hash TYPE VARCHAR(255)")
  1197. await _safe_execute(conn, "ALTER TABLE api_keys ALTER COLUMN key_prefix TYPE VARCHAR(20)")
  1198. await _safe_execute(conn, "ALTER TABLE print_archives ALTER COLUMN filament_color TYPE VARCHAR(200)")
  1199. # Migration: Create GIN index for full-text search on PostgreSQL
  1200. # (SQLite uses FTS5 virtual table instead, set up above)
  1201. if not is_sqlite():
  1202. try:
  1203. await conn.execute(
  1204. text("""
  1205. CREATE INDEX IF NOT EXISTS idx_archives_fulltext
  1206. ON print_archives
  1207. USING GIN (to_tsvector('simple',
  1208. COALESCE(print_name, '') || ' ' ||
  1209. COALESCE(filename, '') || ' ' ||
  1210. COALESCE(tags, '') || ' ' ||
  1211. COALESCE(notes, '') || ' ' ||
  1212. COALESCE(designer, '') || ' ' ||
  1213. COALESCE(filament_type, '')
  1214. ))
  1215. """)
  1216. )
  1217. except (OperationalError, ProgrammingError):
  1218. pass # Already applied
  1219. # Migration: Normalize empty printer_ids [] to NULL (global access) on API keys
  1220. # Previously both None and [] meant "all printers"; now [] means "no printers"
  1221. await _safe_execute(conn, "UPDATE api_keys SET printer_ids = NULL WHERE printer_ids = '[]'")
  1222. # Migration: Add auth_source column to users for LDAP support (#794)
  1223. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN auth_source VARCHAR(20) DEFAULT 'local' NOT NULL")
  1224. # Migration: Make password_hash nullable for LDAP users (#794)
  1225. # LDAP users have no local password — the column must allow NULL so auto-provisioning
  1226. # doesn't hit a NOT NULL constraint failure on upgraded installs whose users table was
  1227. # originally created before LDAP support landed.
  1228. if is_sqlite():
  1229. # SQLite can't ALTER COLUMN; patch sqlite_master directly via writable_schema.
  1230. # Bump schema_version afterwards so SQLite reloads the table definition from disk —
  1231. # without that bump, the current connection keeps enforcing the old NOT NULL from
  1232. # its cached schema. Safe because row data is untouched and the replace() is a
  1233. # no-op if the constraint has already been removed.
  1234. try:
  1235. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='users'"))
  1236. users_sql = result.scalar()
  1237. if users_sql and "password_hash VARCHAR(255) NOT NULL" in users_sql:
  1238. version_result = await conn.execute(text("PRAGMA schema_version"))
  1239. schema_version = version_result.scalar() or 0
  1240. await conn.execute(text("PRAGMA writable_schema = ON"))
  1241. await conn.execute(
  1242. text(
  1243. "UPDATE sqlite_master "
  1244. "SET sql = replace(sql, 'password_hash VARCHAR(255) NOT NULL', 'password_hash VARCHAR(255)') "
  1245. "WHERE type = 'table' AND name = 'users'"
  1246. )
  1247. )
  1248. await conn.execute(text(f"PRAGMA schema_version = {schema_version + 1}"))
  1249. await conn.execute(text("PRAGMA writable_schema = OFF"))
  1250. except (OperationalError, ProgrammingError):
  1251. pass
  1252. else:
  1253. await _safe_execute(conn, "ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL")
  1254. # Migration: Add energy_start_kwh to print_archives (#941)
  1255. # Persists the smart plug lifetime counter captured at print start, so per-print
  1256. # energy tracking survives a backend restart mid-print.
  1257. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN energy_start_kwh REAL")
  1258. # Migration: Add subtask_id to print_archives (#972)
  1259. # MQTT-provided task identifier used to resume the same archive row across a
  1260. # backend restart mid-print. Without it, a long print (e.g. 13h) triggers
  1261. # stale-cancel + new-archive, losing started_at continuity.
  1262. await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN subtask_id VARCHAR(64)")
  1263. # Migration: Create smart_plug_energy_snapshots table (#941)
  1264. # Hourly snapshots of each plug's lifetime counter, so date-range queries in
  1265. # "total consumption" energy mode can compute (last - first) deltas.
  1266. await _safe_execute(
  1267. conn,
  1268. """
  1269. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1270. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1271. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1272. recorded_at DATETIME NOT NULL,
  1273. lifetime_kwh REAL NOT NULL
  1274. )
  1275. """
  1276. if is_sqlite()
  1277. else """
  1278. CREATE TABLE IF NOT EXISTS smart_plug_energy_snapshots (
  1279. id SERIAL PRIMARY KEY,
  1280. plug_id INTEGER NOT NULL REFERENCES smart_plugs(id) ON DELETE CASCADE,
  1281. recorded_at TIMESTAMP NOT NULL,
  1282. lifetime_kwh REAL NOT NULL
  1283. )
  1284. """,
  1285. )
  1286. await _safe_execute(
  1287. conn,
  1288. "CREATE INDEX IF NOT EXISTS ix_plug_energy_snapshots_plug_time "
  1289. "ON smart_plug_energy_snapshots(plug_id, recorded_at)",
  1290. )
  1291. # Migration: Add PKCE code_verifier column to auth_ephemeral_tokens
  1292. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN code_verifier VARCHAR(128)")
  1293. # Migration: Add TOTP replay-protection counter to user_totp
  1294. await _safe_execute(conn, "ALTER TABLE user_totp ADD COLUMN last_totp_counter BIGINT")
  1295. # Migration: Add challenge_id for pre-auth token client binding (HttpOnly cookie)
  1296. await _safe_execute(conn, "ALTER TABLE auth_ephemeral_tokens ADD COLUMN challenge_id VARCHAR(128)")
  1297. # Migration: Add auto_link_existing_accounts column to oidc_providers (M-4)
  1298. await _safe_execute(conn, "ALTER TABLE oidc_providers ADD COLUMN auto_link_existing_accounts BOOLEAN DEFAULT 1")
  1299. # Migration: Add password_changed_at to users (M-R7-B)
  1300. # Tracks the last time a user's password was changed/reset. JWTs whose iat
  1301. # predates this timestamp are rejected in all six auth validation paths.
  1302. # R4 fix: TIMESTAMP is accepted by both SQLite and PostgreSQL; DATETIME
  1303. # is rejected by Postgres ("type 'datetime' does not exist"), which made
  1304. # _safe_execute swallow the error and leave existing Postgres installs
  1305. # without the column — causing UndefinedColumnError on every User query.
  1306. await _safe_execute(conn, "ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP")
  1307. # Migration: Back-fill password_changed_at = created_at for existing users (I2).
  1308. # Users who never changed their password would have NULL here, meaning old
  1309. # tokens could never be invalidated via the freshness check. Setting it to
  1310. # created_at is conservative: any token issued before the account was created
  1311. # is always invalid, so this is a safe lower bound.
  1312. await _safe_execute(
  1313. conn,
  1314. "UPDATE users SET password_changed_at = created_at WHERE password_changed_at IS NULL",
  1315. )
  1316. # Migration: Provenance columns on library_files for MakerWorld imports.
  1317. # source_url is indexed so "already imported" dedupe lookups stay O(log N)
  1318. # as the library grows.
  1319. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_type VARCHAR(32)")
  1320. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN source_url VARCHAR(512)")
  1321. await _safe_execute(
  1322. conn,
  1323. "CREATE INDEX IF NOT EXISTS ix_library_files_source_url ON library_files(source_url)",
  1324. )
  1325. # Migration: Soft-delete column for trash bin (Issue #1008). Indexed so the
  1326. # sweeper's "SELECT ... WHERE deleted_at < cutoff" and the trash list's
  1327. # "WHERE deleted_at IS NOT NULL" stay cheap as the table grows.
  1328. #
  1329. # ``DATETIME`` is a SQLite-only type alias — PostgreSQL rejects it as
  1330. # invalid syntax, _safe_execute swallows the error, and the column is
  1331. # never added (breaking every query that references it). Emit
  1332. # dialect-appropriate SQL so both backends get the column.
  1333. if is_sqlite():
  1334. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at DATETIME")
  1335. else:
  1336. await _safe_execute(conn, "ALTER TABLE library_files ADD COLUMN deleted_at TIMESTAMP")
  1337. await _safe_execute(
  1338. conn,
  1339. "CREATE INDEX IF NOT EXISTS ix_library_files_deleted_at ON library_files(deleted_at)",
  1340. )
  1341. # Seed default settings keys that must exist on fresh install
  1342. default_settings = [
  1343. ("advanced_auth_enabled", "false"),
  1344. ("smtp_auth_enabled", "true"),
  1345. ]
  1346. for key, value in default_settings:
  1347. try:
  1348. if is_sqlite():
  1349. await conn.execute(
  1350. text("INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)"),
  1351. {"key": key, "value": value},
  1352. )
  1353. else:
  1354. await conn.execute(
  1355. text("INSERT INTO settings (key, value) VALUES (:key, :value) ON CONFLICT (key) DO NOTHING"),
  1356. {"key": key, "value": value},
  1357. )
  1358. except (OperationalError, ProgrammingError):
  1359. pass
  1360. async def seed_notification_templates():
  1361. """Seed default notification templates if they don't exist."""
  1362. from sqlalchemy import select
  1363. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  1364. async with async_session() as session:
  1365. # Get existing template event types
  1366. result = await session.execute(select(NotificationTemplate.event_type))
  1367. existing_types = {row[0] for row in result.fetchall()}
  1368. if not existing_types:
  1369. # No templates exist - insert all defaults
  1370. for template_data in DEFAULT_TEMPLATES:
  1371. template = NotificationTemplate(
  1372. event_type=template_data["event_type"],
  1373. name=template_data["name"],
  1374. title_template=template_data["title_template"],
  1375. body_template=template_data["body_template"],
  1376. is_default=True,
  1377. )
  1378. session.add(template)
  1379. else:
  1380. # Templates exist - only add missing ones
  1381. for template_data in DEFAULT_TEMPLATES:
  1382. if template_data["event_type"] not in existing_types:
  1383. template = NotificationTemplate(
  1384. event_type=template_data["event_type"],
  1385. name=template_data["name"],
  1386. title_template=template_data["title_template"],
  1387. body_template=template_data["body_template"],
  1388. is_default=True,
  1389. )
  1390. session.add(template)
  1391. await session.commit()
  1392. async def seed_default_groups():
  1393. """Seed default groups and migrate existing users to appropriate groups.
  1394. Creates the default system groups (Administrators, Operators, Viewers) if they
  1395. don't exist, then migrates existing users:
  1396. - Users with role='admin' -> Administrators group
  1397. - Users with role='user' -> Operators group
  1398. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1399. """
  1400. import logging
  1401. from sqlalchemy import select
  1402. from backend.app.core.permissions import DEFAULT_GROUPS
  1403. from backend.app.models.group import Group
  1404. from backend.app.models.user import User
  1405. logger = logging.getLogger(__name__)
  1406. # Map old permissions to new ones for migration
  1407. # Administrators get *_all permissions, Operators get *_own permissions
  1408. PERMISSION_MIGRATION_ALL = {
  1409. "queue:update": "queue:update_all",
  1410. "queue:delete": "queue:delete_all",
  1411. "archives:update": "archives:update_all",
  1412. "archives:delete": "archives:delete_all",
  1413. "archives:reprint": "archives:reprint_all",
  1414. "library:update": "library:update_all",
  1415. "library:delete": "library:delete_all",
  1416. }
  1417. PERMISSION_MIGRATION_OWN = {
  1418. "queue:update": "queue:update_own",
  1419. "queue:delete": "queue:delete_own",
  1420. "archives:update": "archives:update_own",
  1421. "archives:delete": "archives:delete_own",
  1422. "archives:reprint": "archives:reprint_own",
  1423. "library:update": "library:update_own",
  1424. "library:delete": "library:delete_own",
  1425. }
  1426. async with async_session() as session:
  1427. # Get existing groups
  1428. result = await session.execute(select(Group))
  1429. existing_groups = {group.name: group for group in result.scalars().all()}
  1430. # Create default groups if they don't exist
  1431. groups_created = []
  1432. for group_name, group_config in DEFAULT_GROUPS.items():
  1433. if group_name not in existing_groups:
  1434. group = Group(
  1435. name=group_name,
  1436. description=group_config["description"],
  1437. permissions=group_config["permissions"],
  1438. is_system=group_config["is_system"],
  1439. )
  1440. session.add(group)
  1441. groups_created.append(group_name)
  1442. logger.info("Created default group: %s", group_name)
  1443. else:
  1444. # Migrate existing group's permissions from old to new format
  1445. group = existing_groups[group_name]
  1446. if group.permissions:
  1447. updated = False
  1448. new_permissions = list(group.permissions)
  1449. # Determine which migration map to use based on group
  1450. migration_map = (
  1451. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1452. )
  1453. for old_perm, new_perm in migration_map.items():
  1454. if old_perm in new_permissions:
  1455. new_permissions.remove(old_perm)
  1456. if new_perm not in new_permissions:
  1457. new_permissions.append(new_perm)
  1458. updated = True
  1459. logger.info(
  1460. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  1461. )
  1462. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1463. if group_name == "Administrators":
  1464. for _own_perm, all_perm in [
  1465. ("queue:update_own", "queue:update_all"),
  1466. ("queue:delete_own", "queue:delete_all"),
  1467. ("archives:update_own", "archives:update_all"),
  1468. ("archives:delete_own", "archives:delete_all"),
  1469. ("archives:reprint_own", "archives:reprint_all"),
  1470. ("library:update_own", "library:update_all"),
  1471. ("library:delete_own", "library:delete_all"),
  1472. ]:
  1473. # Add *_all if not present
  1474. if all_perm not in new_permissions:
  1475. new_permissions.append(all_perm)
  1476. updated = True
  1477. if updated:
  1478. group.permissions = new_permissions
  1479. await session.commit()
  1480. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  1481. result = await session.execute(select(Group))
  1482. all_groups = result.scalars().all()
  1483. for group in all_groups:
  1484. if (
  1485. group.permissions
  1486. and "printers:control" in group.permissions
  1487. and "printers:clear_plate" not in group.permissions
  1488. ):
  1489. group.permissions = [*group.permissions, "printers:clear_plate"]
  1490. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  1491. await session.commit()
  1492. # Migrate new permissions for MakerWorld integration: groups that
  1493. # already have library:upload (i.e. can write to the library) are
  1494. # the correct audience for makerworld:view + makerworld:import, and
  1495. # groups that only have library:read get makerworld:view (browse
  1496. # only). Matches the intent of DEFAULT_GROUPS without clobbering
  1497. # any user-customised permission lists.
  1498. result = await session.execute(select(Group))
  1499. for group in result.scalars().all():
  1500. if not group.permissions:
  1501. continue
  1502. perms = list(group.permissions)
  1503. changed = False
  1504. if "library:upload" in perms:
  1505. for new_perm in ("makerworld:view", "makerworld:import"):
  1506. if new_perm not in perms:
  1507. perms.append(new_perm)
  1508. changed = True
  1509. logger.info("Added %s to group '%s' (has library:upload)", new_perm, group.name)
  1510. elif "library:read" in perms and "makerworld:view" not in perms:
  1511. perms.append("makerworld:view")
  1512. changed = True
  1513. logger.info("Added makerworld:view to group '%s' (has library:read)", group.name)
  1514. if changed:
  1515. group.permissions = perms
  1516. await session.commit()
  1517. # Backfill library:purge + archives:purge for the Administrators group
  1518. # on existing installs. Both permissions were added after Administrators
  1519. # was first seeded, so upgrading users miss them even though the default
  1520. # config (ALL_PERMISSIONS) includes them for fresh installs.
  1521. result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1522. admin_group = result.scalar_one_or_none()
  1523. if admin_group and admin_group.permissions is not None:
  1524. perms = list(admin_group.permissions)
  1525. added = False
  1526. for new_perm in ("library:purge", "archives:purge"):
  1527. if new_perm not in perms:
  1528. perms.append(new_perm)
  1529. added = True
  1530. logger.info("Added %s to Administrators group (backfill)", new_perm)
  1531. if added:
  1532. admin_group.permissions = perms
  1533. await session.commit()
  1534. # Migrate existing users to groups if they're not already in any group
  1535. if groups_created:
  1536. # Refresh to get newly created groups
  1537. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1538. admin_group = admin_result.scalar_one_or_none()
  1539. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1540. operators_group = operators_result.scalar_one_or_none()
  1541. # Get all users
  1542. users_result = await session.execute(select(User))
  1543. users = users_result.scalars().all()
  1544. for user in users:
  1545. # Skip if user already has groups
  1546. if user.groups:
  1547. continue
  1548. if user.role == "admin" and admin_group:
  1549. user.groups.append(admin_group)
  1550. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  1551. elif operators_group:
  1552. user.groups.append(operators_group)
  1553. logger.info("Migrated user '%s' to Operators group", user.username)
  1554. await session.commit()
  1555. async def seed_spool_catalog():
  1556. """Seed the spool catalog with default entries if empty."""
  1557. import logging
  1558. from sqlalchemy import func, select
  1559. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  1560. from backend.app.models.spool_catalog import SpoolCatalogEntry
  1561. logger = logging.getLogger(__name__)
  1562. async with async_session() as session:
  1563. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  1564. count = result.scalar() or 0
  1565. if count > 0:
  1566. return # Already seeded
  1567. for name, weight in DEFAULT_SPOOL_CATALOG:
  1568. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  1569. await session.commit()
  1570. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  1571. async def seed_color_catalog():
  1572. """Seed the color catalog with default entries if empty."""
  1573. import logging
  1574. from sqlalchemy import func, select
  1575. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  1576. from backend.app.models.color_catalog import ColorCatalogEntry
  1577. logger = logging.getLogger(__name__)
  1578. async with async_session() as session:
  1579. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  1580. count = result.scalar() or 0
  1581. if count > 0:
  1582. return # Already seeded
  1583. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  1584. session.add(
  1585. ColorCatalogEntry(
  1586. manufacturer=manufacturer,
  1587. color_name=color_name,
  1588. hex_color=hex_color,
  1589. material=material,
  1590. is_default=True,
  1591. )
  1592. )
  1593. await session.commit()
  1594. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))