File size: 5,674 Bytes
94193b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Project Database Manager
 *
 * Lightweight per-project SQLite database for user-defined tables.
 * No system tables — just user DDL/SQL.
 *
 * Project databases live at data/projects/{projectId}/database.sqlite
 * and are extracted to deployment runtime.sqlite on publish.
 */

import type { Database } from 'better-sqlite3';
import { TableInfo } from '../types';
import {
  getProjectDatabaseConnection,
  closeProjectDatabase,
} from './sqlite-connection';

/**
 * Escape a table name for use in SQL identifiers (double-quote escaping)
 */
function escapeIdentifier(name: string): string {
  return `"${name.replace(/"/g, '""')}"`;
}

/**
 * Per-project database manager
 */
export class ProjectDatabase {
  private db: Database;
  private projectId: string;
  private baseDir: string | undefined;

  constructor(projectId: string, baseDir?: string) {
    this.projectId = projectId;
    this.baseDir = baseDir;
    this.db = getProjectDatabaseConnection(projectId, baseDir);
  }

  /**
   * Initialize — no-op, exists for interface symmetry with RuntimeDatabase
   */
  init(): void {
    // No system tables to create
  }

  /**
   * Close the database connection
   */
  close(): void {
    closeProjectDatabase(this.projectId, this.baseDir);
  }

  /**
   * Execute DDL statements (CREATE TABLE, etc.)
   */
  private static readonly BLOCKED_PATTERNS = /^\s*(ATTACH|DETACH|PRAGMA|VACUUM)\b/i;

  executeDDL(sql: string): void {
    const statements = sql.split(';').filter(s => s.trim());
    for (const stmt of statements) {
      if (ProjectDatabase.BLOCKED_PATTERNS.test(stmt.trim())) {
        throw new Error('Statement type not allowed');
      }
    }
    this.db.exec(sql);
  }

  /**
   * Get schema information for all tables
   */
  getTableSchema(): TableInfo[] {
    const tables = this.db.prepare(`
      SELECT name FROM sqlite_master
      WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
      ORDER BY name
    `).all() as Array<{ name: string }>;

    return tables.map(table => {
      const escaped = escapeIdentifier(table.name);
      const columns = this.db.prepare(`PRAGMA table_info(${escaped})`).all() as Array<{
        cid: number;
        name: string;
        type: string;
        notnull: number;
        dflt_value: string | null;
        pk: number;
      }>;

      const countResult = this.db.prepare(`SELECT COUNT(*) as count FROM ${escaped}`).get() as { count: number };

      return {
        name: table.name,
        columns: columns.map(col => ({
          name: col.name,
          type: col.type,
          nullable: !col.notnull,
          primaryKey: col.pk > 0,
          defaultValue: col.dflt_value ?? undefined,
        })),
        rowCount: countResult.count,
        isSystemTable: false,
      };
    });
  }

  /**
   * Execute raw SQL (SELECT or DML)
   */
  executeRawSQL(sql: string, params?: unknown[]): {
    columns: string[];
    rows: unknown[][];
    rowsAffected: number;
  } {
    if (ProjectDatabase.BLOCKED_PATTERNS.test(sql)) {
      throw new Error('Statement type not allowed');
    }

    const trimmedSql = sql.trim().toLowerCase();
    const isSelect = trimmedSql.startsWith('select');

    if (isSelect) {
      const stmt = this.db.prepare(sql);
      const rows = params ? stmt.all(...params) : stmt.all();

      if (rows.length === 0) {
        return { columns: [], rows: [], rowsAffected: 0 };
      }

      const columns = Object.keys(rows[0] as Record<string, unknown>);
      const rowsArray = rows.map(row => columns.map(col => (row as Record<string, unknown>)[col]));

      return { columns, rows: rowsArray, rowsAffected: 0 };
    } else {
      const stmt = this.db.prepare(sql);
      const result = params ? stmt.run(...params) : stmt.run();

      return {
        columns: [],
        rows: [],
        rowsAffected: result.changes,
      };
    }
  }

  /**
   * Get data from a specific table with pagination
   */
  getTableData(tableName: string, limit: number = 100, offset: number = 0): {
    columns: string[];
    rows: unknown[][];
    total: number;
  } {
    const validTables = this.db.prepare(`
      SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?
    `).get(tableName);

    if (!validTables) {
      throw new Error(`Table "${tableName}" does not exist`);
    }

    const escaped = escapeIdentifier(tableName);
    const countResult = this.db.prepare(`SELECT COUNT(*) as count FROM ${escaped}`).get() as { count: number };
    const rows = this.db.prepare(`SELECT * FROM ${escaped} LIMIT ? OFFSET ?`).all(limit, offset) as Record<string, unknown>[];

    if (rows.length === 0) {
      return { columns: [], rows: [], total: countResult.count };
    }

    const columns = Object.keys(rows[0]);
    const rowsArray = rows.map(row => columns.map(col => row[col]));

    return {
      columns,
      rows: rowsArray,
      total: countResult.count,
    };
  }

  /**
   * Generate schema SQL from sqlite_master for export/extraction.
   * Uses the original DDL stored by SQLite — preserves AUTOINCREMENT,
   * FOREIGN KEY, CHECK constraints, and indexes.
   */
  getSchemaForExport(): string {
    const tables = this.db.prepare(`
      SELECT sql FROM sqlite_master
      WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND sql IS NOT NULL
      ORDER BY name
    `).all() as Array<{ sql: string }>;

    const indexes = this.db.prepare(`
      SELECT sql FROM sqlite_master
      WHERE type = 'index' AND sql IS NOT NULL
      ORDER BY name
    `).all() as Array<{ sql: string }>;

    if (tables.length === 0) {
      return '';
    }

    return [...tables, ...indexes].map(r => r.sql + ';').join('\n\n') + '\n';
  }
}