File size: 1,962 Bytes
345a446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sqlite3
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_DB_PATH = os.path.join(BASE_DIR, "database", "company.db")

# Holds the currently active database path
_current_db_path = DEFAULT_DB_PATH


def set_db_path(path: str):
    global _current_db_path
    _current_db_path = path


def get_db_path() -> str:
    return _current_db_path


def get_connection():
    return sqlite3.connect(_current_db_path)


def execute_query(query: str, params=None):
    conn = get_connection()
    cursor = conn.cursor()
    if params:
        cursor.execute(query, params)
    else:
        cursor.execute(query)
    conn.commit()
    conn.close()


def fetch_query(query: str, params=None):
    conn = get_connection()
    cursor = conn.cursor()
    if params:
        cursor.execute(query, params)
    else:
        cursor.execute(query)
    # Return list of dicts
    columns = [desc[0] for desc in cursor.description]
    rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
    conn.close()
    return rows


def get_schema_info(db_path: str) -> str:
    """Extract full schema string from a SQLite database."""
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = [row[0] for row in cursor.fetchall()]

        schema_parts = []
        for table in tables:
            cursor.execute(f"PRAGMA table_info({table})")
            cols = cursor.fetchall()
            col_defs = []
            for col in cols:
                col_name = col[1]
                col_type = col[2]
                pk = " PRIMARY KEY" if col[5] else ""
                col_defs.append(f"    {col_name} {col_type}{pk}")
            schema_parts.append(f"{table}(\n" + ",\n".join(col_defs) + "\n)")

        conn.close()
        return "\n\n".join(schema_parts)
    except Exception as e:
        return f"Error reading schema: {e}"