database.py 74 KB

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