database.py 65 KB

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