database.py 76 KB

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