""" Database abstraction layer supporting SQLite (dev) and PostgreSQL (prod). Usage: from database import get_db, execute, fetch_one, fetch_all, close_all conn = get_db() rows = fetch_all(conn, "SELECT * FROM users WHERE role = ?", ("user",)) close_all() """ import os import sqlite3 import logging from contextlib import contextmanager from typing import Any, Optional log = logging.getLogger(__name__) DATABASE_URL = os.environ.get("DATABASE_URL", "") IS_POSTGRES = DATABASE_URL.startswith("postgresql://") # ── Connection pool (PostgreSQL) ── _pool = None def _get_pool(): """Lazy-initialize a psycopg2 connection pool for PostgreSQL.""" global _pool if _pool is not None: return _pool if not IS_POSTGRES: return None try: import psycopg2 from psycopg2 import pool as pg_pool _pool = pg_pool.ThreadedConnectionPool( minconn=2, maxconn=20, dsn=DATABASE_URL, ) log.info("PostgreSQL connection pool initialized (%s)", DATABASE_URL.split("@")[-1]) return _pool except ImportError: log.warning("psycopg2 not installed — falling back to SQLite") return None except Exception as e: log.error("Failed to connect to PostgreSQL: %s", e) return None # ── Row wrapper for dict-like access ── class DictRow: """Thin wrapper that provides dict-like access on top of a psycopg2 row or sqlite3.Row.""" def __init__(self, row, columns): self._row = row self._columns = columns def __getitem__(self, key): if isinstance(key, int): return self._row[key] try: idx = self._columns.index(key) return self._row[idx] except (ValueError, KeyError): raise KeyError(key) def __contains__(self, key): return key in self._columns def __iter__(self): return iter(self._columns) def __len__(self): return len(self._columns) def __repr__(self): d = {c: self._row[i] for i, c in enumerate(self._columns)} return f"DictRow({d})" def dict(self): return {c: self._row[i] for i, c in enumerate(self._columns)} def _wrap_pg_row(row, cursor): """Wrap a psycopg2 row as a DictRow.""" if row is None: return None columns = [desc[0] for desc in cursor.description] return DictRow(row, columns) # ── Core DB functions ── def get_db(): """ Return a database connection. - SQLite: returns a sqlite3.Connection (row_factory=sqlite3.Row) - PostgreSQL: returns a psycopg2 connection from the pool """ if IS_POSTGRES: pool = _get_pool() if pool is None: raise RuntimeError("PostgreSQL pool not available") conn = pool.getconn() conn.autocommit = False return conn else: from app import DB_PATH conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") return conn def close_db(conn): """Return a connection to the pool (PostgreSQL) or close it (SQLite).""" if conn is None: return if IS_POSTGRES: pool = _get_pool() if pool: pool.putconn(conn) else: conn.close() def close_all(): """Close all connections in the pool.""" global _pool if _pool is not None: _pool.closeall() _pool = None def fetch_one(conn, sql: str, params: tuple = ()) -> Optional[DictRow]: """Execute query and return first row as DictRow or None.""" cur = conn.cursor() try: cur.execute(sql, params) if IS_POSTGRES: row = cur.fetchone() return _wrap_pg_row(row, cur) else: return cur.fetchone() finally: cur.close() def fetch_all(conn, sql: str, params: tuple = ()) -> list: """Execute query and return all rows as list of DictRow.""" cur = conn.cursor() try: cur.execute(sql, params) if IS_POSTGRES: rows = cur.fetchall() return [_wrap_pg_row(r, cur) for r in rows] else: return cur.fetchall() finally: cur.close() def execute(conn, sql: str, params: tuple = ()) -> Any: """Execute a statement (INSERT/UPDATE/DELETE) and return cursor.""" cur = conn.cursor() try: cur.execute(sql, params) return cur finally: cur.close() def execute_many(conn, sql: str, params_list: list) -> None: """Execute a statement with many parameter sets.""" cur = conn.cursor() try: cur.executemany(sql, params_list) finally: cur.close() def commit(conn): """Commit the current transaction.""" conn.commit() def rollback(conn): """Rollback the current transaction.""" conn.rollback() @contextmanager def db_transaction(): """Context manager for database transactions. Auto-commits or rolls back.""" conn = get_db() try: yield conn commit(conn) except Exception: rollback(conn) raise finally: close_db(conn) def init_db(): """Initialize database schema. Creates tables if they don't exist.""" conn = get_db() try: if IS_POSTGRES: _init_postgres(conn) else: _init_sqlite(conn) commit(conn) log.info("Database initialized (%s)", "PostgreSQL" if IS_POSTGRES else "SQLite") finally: close_db(conn) def _init_sqlite(conn): """Initialize SQLite schema.""" conn.executescript(""" CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, email TEXT UNIQUE, password_hash TEXT NOT NULL, full_name TEXT NOT NULL, phone TEXT DEFAULT '', avatar_url TEXT DEFAULT '', role TEXT DEFAULT 'user', latitude REAL DEFAULT 0, longitude REAL DEFAULT 0, location_updated_at TEXT, is_active INTEGER DEFAULT 1, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS guest_locations ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, latitude REAL DEFAULT 0, longitude REAL DEFAULT 0, user_agent TEXT DEFAULT '', ip_address TEXT DEFAULT '', created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS products ( id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT UNIQUE NOT NULL, sku TEXT DEFAULT '', category_id TEXT DEFAULT '', description TEXT DEFAULT '', selling_price REAL DEFAULT 0, cost_price REAL DEFAULT 0, compare_price REAL DEFAULT 0, stock INTEGER DEFAULT 0, images TEXT DEFAULT '[]', is_featured INTEGER DEFAULT 0, is_active INTEGER DEFAULT 1, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')), deleted_at TEXT ); CREATE TABLE IF NOT EXISTS categories ( id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT UNIQUE NOT NULL, description TEXT DEFAULT '', image_url TEXT DEFAULT '', sort_order INTEGER DEFAULT 0, is_active INTEGER DEFAULT 1, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, order_number TEXT UNIQUE NOT NULL, user_id TEXT NOT NULL, status TEXT DEFAULT 'pending', payment_status TEXT DEFAULT 'unpaid', grand_total REAL DEFAULT 0, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS system_settings ( id INTEGER PRIMARY KEY AUTOINCREMENT, setting_key TEXT UNIQUE NOT NULL, setting_value TEXT DEFAULT '', description TEXT DEFAULT '', created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS chat_sessions ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, title TEXT DEFAULT 'New chat', channel TEXT DEFAULT '', channel_user_id TEXT DEFAULT '', channel_user_name TEXT DEFAULT '', guest_id TEXT DEFAULT '', rating INTEGER DEFAULT 0, rating_note TEXT DEFAULT '', created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS chat_messages ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, plans TEXT DEFAULT '[]', channel TEXT DEFAULT '', source TEXT DEFAULT 'ai', answered_by TEXT DEFAULT '', dynamic_ui TEXT DEFAULT '[]', created_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS bookings ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_id TEXT NOT NULL, type TEXT DEFAULT 'other', title TEXT DEFAULT '', description TEXT DEFAULT '', items TEXT DEFAULT '[]', status TEXT DEFAULT 'planned', created_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS user_agent_config ( user_id TEXT PRIMARY KEY, scope TEXT DEFAULT '', instructions TEXT DEFAULT '', model TEXT DEFAULT '', updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS notifications ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, type TEXT DEFAULT 'info', title TEXT NOT NULL, message TEXT DEFAULT '', data TEXT DEFAULT '{}', is_read INTEGER DEFAULT 0, created_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS channel_configs ( channel TEXT PRIMARY KEY, config TEXT DEFAULT '{}', is_enabled INTEGER DEFAULT 0, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS channel_users ( id TEXT PRIMARY KEY, channel TEXT NOT NULL, external_id TEXT NOT NULL, name TEXT DEFAULT '', avatar_url TEXT DEFAULT '', raw_data TEXT DEFAULT '{}', last_seen_at TEXT DEFAULT (datetime('now')), created_at TEXT DEFAULT (datetime('now')), UNIQUE(channel, external_id) ); CREATE TABLE IF NOT EXISTS channel_inbound ( channel TEXT NOT NULL, external_msg_id TEXT NOT NULL, processed_at TEXT DEFAULT (datetime('now')), PRIMARY KEY (channel, external_msg_id) ); CREATE TABLE IF NOT EXISTS webauthn_credentials ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, credential_id TEXT UNIQUE NOT NULL, public_key TEXT NOT NULL, counter INTEGER DEFAULT 0, transports TEXT DEFAULT '[]', nickname TEXT DEFAULT '', device_type TEXT DEFAULT '', created_at TEXT DEFAULT (datetime('now')), last_used_at TEXT DEFAULT (datetime('now')) ); """) conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_sessions_user ON chat_sessions(user_id)") conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_messages_session ON chat_messages(session_id)") conn.execute("CREATE INDEX IF NOT EXISTS idx_bookings_user ON bookings(user_id)") conn.execute("CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id)") for stmt in [ "ALTER TABLE users ADD COLUMN avatar_url TEXT DEFAULT ''", "ALTER TABLE products ADD COLUMN description TEXT DEFAULT ''", "ALTER TABLE chat_messages ADD COLUMN source TEXT DEFAULT 'ai'", "ALTER TABLE chat_messages ADD COLUMN answered_by TEXT DEFAULT ''", "ALTER TABLE products ADD COLUMN compare_price REAL DEFAULT 0", "ALTER TABLE products ADD COLUMN is_featured INTEGER DEFAULT 0", "ALTER TABLE categories ADD COLUMN image_url TEXT DEFAULT ''", "ALTER TABLE chat_sessions ADD COLUMN channel TEXT DEFAULT ''", "ALTER TABLE chat_sessions ADD COLUMN channel_user_id TEXT DEFAULT ''", "ALTER TABLE chat_sessions ADD COLUMN channel_user_name TEXT DEFAULT ''", "ALTER TABLE chat_messages ADD COLUMN dynamic_ui TEXT DEFAULT '[]'", "ALTER TABLE chat_sessions ADD COLUMN guest_id TEXT DEFAULT ''", "ALTER TABLE chat_sessions ADD COLUMN rating INTEGER DEFAULT 0", "ALTER TABLE chat_sessions ADD COLUMN rating_note TEXT DEFAULT ''", ]: try: conn.execute(stmt) except Exception: pass # Indexes on migrated columns must be created after the ALTER loop above. conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_sessions_guest ON chat_sessions(guest_id)") conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_sessions_channel ON chat_sessions(channel)") def _init_postgres(conn): """Initialize PostgreSQL schema — read from schema.sql file.""" import re schema_path = os.path.join(os.path.dirname(__file__), "database", "schema.sql") if os.path.exists(schema_path): with open(schema_path, "r") as f: sql = f.read() cur = conn.cursor() try: # Split by semicolons and execute each statement for statement in re.split(r";\s*\n", sql): statement = statement.strip() if statement: cur.execute(statement) finally: cur.close() else: log.warning("PostgreSQL schema file not found: %s", schema_path)