Files
microfish/backend/app/db.py
Kunthawat Greethong 8b84378fe1 feat: SaaS foundation for CrowdSight
Elevate MiroFish/CrowdSight from single-container dev to a SaaS foundation:

- Local memory backend (Zep-compatible): memory services/models, local graph
  builder + updater, AgentActivity seam, import-boundary isolation; Zep stays
  default, local is opt-in behind MEMORY_BACKEND. Semantic parity not yet proven.
- Durable product persistence: projects/simulations/reports schema (migration
  0007) + tenant/owner-scoped ProductRepository + dual-write + scoped_project
  read-first + ArtifactStore abstraction; durable JobQueue + worker.py.
- SaaS hardening: durable RateLimiter (wired to login), UsageService (LLM
  accounting), redacted AuditService, idempotency, CORS allowlist, safe API
  errors, single-use PasswordResetService + endpoints (covers invite-pending).
- Exactly 3 roles (super_admin/admin/user) with tenant authz policy.
- Admin UI: GET/POST/PATCH /api/admin/users + GET/PUT /api/admin/settings
  (super-admin only, encrypted/masked); AdminView.vue + SettingsView.vue with
  admin/super-admin route guards, th/en i18n.
- Production deploy topology: multi-stage Dockerfile (frontend build + gunicorn
  wsgi + nginx SPA-proxy + supervisord worker), backend/wsgi.py, gunicorn dep.

Backend 197 passed; frontend 10 tests + build green. ruff unavailable (gap).
No commit of credentials; secrets handled via env/.env.example.
Deferred: Zep semantic A/B parity, object storage cutover, mobile QA, EasyPanel
container build of deploy topology.
2026-08-31 13:05:21 +07:00

51 lines
1.6 KiB
Python

"""Database engine and declarative base helpers."""
from __future__ import annotations
import os
from pathlib import Path
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
class Base(DeclarativeBase):
pass
def create_database_engine(database_url: str | None = None, **kwargs) -> Engine:
"""Create a configured SQLAlchemy engine without opening a global session."""
url = database_url or os.environ.get("DATABASE_URL")
if not url:
data_dir = Path(os.environ.get("CROWDSIGHT_DATA_DIR", "backend/uploads"))
data_dir.mkdir(parents=True, exist_ok=True)
url = f"sqlite+pysqlite:///{(data_dir / 'crowdsight.db').resolve()}"
connect_args = dict(kwargs.pop("connect_args", {}))
if url.startswith("sqlite"):
connect_args.setdefault("check_same_thread", False)
engine = create_engine(
url,
future=True,
pool_pre_ping=True,
connect_args=connect_args,
**kwargs,
)
if url.startswith("sqlite"):
@event.listens_for(engine, "connect")
def _enable_sqlite_foreign_keys(dbapi_connection, _connection_record):
cursor = dbapi_connection.cursor()
try:
cursor.execute("PRAGMA foreign_keys=ON")
finally:
cursor.close()
return engine
def create_session_factory(engine: Engine) -> sessionmaker[Session]:
"""Return a factory; callers own transaction boundaries and commits."""
return sessionmaker(bind=engine, autoflush=True, expire_on_commit=False)