database.py 62 KB

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