database.py 80 KB

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