database.py 70 KB

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