database.py 75 KB

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