feat: seed predefined tags on database initialization
Automatically insert predefined tags when the tags table is empty during DB init. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4,10 +4,10 @@ import os
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
|
|
||||||
from sqlalchemy import create_engine
|
from sqlalchemy import create_engine, text
|
||||||
from sqlalchemy.orm import Session, sessionmaker
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
from .models import Base
|
from .models import Base, Tag
|
||||||
|
|
||||||
|
|
||||||
# Default database path - relative to project root
|
# Default database path - relative to project root
|
||||||
@@ -106,9 +106,30 @@ def init_db(db_path: Path | None = None) -> Path:
|
|||||||
_engine = engine
|
_engine = engine
|
||||||
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
# Seed predefined tags if the table is empty
|
||||||
|
_seed_tags_if_empty(engine)
|
||||||
|
|
||||||
return db_path
|
return db_path
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_tags_if_empty(engine):
|
||||||
|
"""Insert predefined tags if the tags table is empty."""
|
||||||
|
from ..scripts.seed_tags import PREDEFINED_TAGS
|
||||||
|
|
||||||
|
session = Session(bind=engine)
|
||||||
|
try:
|
||||||
|
count = session.execute(text("SELECT COUNT(*) FROM tags")).scalar()
|
||||||
|
if count == 0:
|
||||||
|
for tag_name in PREDEFINED_TAGS:
|
||||||
|
session.add(Tag(nom=tag_name))
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
def reset_connection():
|
def reset_connection():
|
||||||
"""Reset global connection (useful for testing)."""
|
"""Reset global connection (useful for testing)."""
|
||||||
global _engine, _SessionLocal
|
global _engine, _SessionLocal
|
||||||
|
|||||||
Reference in New Issue
Block a user