database.py 67 KB

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