Spaces:
Sleeping

File size: 13,704 Bytes
2eef5d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""
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)