@hedystia/db 2.0.6 → 2.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cache/index.mjs +12 -0
- package/dist/cache/index.mjs.map +1 -0
- package/dist/cache/manager.mjs +156 -153
- package/dist/cache/manager.mjs.map +1 -1
- package/dist/cache/memory-store.mjs +113 -111
- package/dist/cache/memory-store.mjs.map +1 -1
- package/dist/cli/commands/migrate.cjs +78 -0
- package/dist/cli/commands/migrate.cjs.map +1 -0
- package/dist/cli/commands/migrate.mjs +83 -0
- package/dist/cli/commands/migrate.mjs.map +1 -0
- package/dist/cli/commands/migration.cjs +3 -2
- package/dist/cli/commands/migration.cjs.map +1 -1
- package/dist/cli/commands/migration.mjs +4 -3
- package/dist/cli/commands/migration.mjs.map +1 -1
- package/dist/cli.cjs +44 -5
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.mjs +45 -5
- package/dist/cli.mjs.map +1 -1
- package/dist/core/database.cjs +75 -29
- package/dist/core/database.cjs.map +1 -1
- package/dist/core/database.d.cts +11 -0
- package/dist/core/database.d.mts +11 -0
- package/dist/core/database.mjs +91 -34
- package/dist/core/database.mjs.map +1 -1
- package/dist/core/repository.mjs +414 -410
- package/dist/core/repository.mjs.map +1 -1
- package/dist/drivers/driver.mjs +9 -7
- package/dist/drivers/driver.mjs.map +1 -1
- package/dist/drivers/file.mjs +315 -312
- package/dist/drivers/file.mjs.map +1 -1
- package/dist/drivers/index.mjs +15 -6
- package/dist/drivers/index.mjs.map +1 -1
- package/dist/drivers/mysql.mjs +261 -256
- package/dist/drivers/mysql.mjs.map +1 -1
- package/dist/drivers/sql-compiler.mjs +4 -1
- package/dist/drivers/sql-compiler.mjs.map +1 -1
- package/dist/drivers/sqlite.cjs +12 -1
- package/dist/drivers/sqlite.cjs.map +1 -1
- package/dist/drivers/sqlite.mjs +258 -242
- package/dist/drivers/sqlite.mjs.map +1 -1
- package/dist/errors.mjs +48 -64
- package/dist/errors.mjs.map +1 -1
- package/dist/index.mjs +21 -9
- package/dist/index.mjs.map +1 -1
- package/dist/migrations/templates.cjs +4 -3
- package/dist/migrations/templates.cjs.map +1 -1
- package/dist/migrations/templates.d.cts +3 -2
- package/dist/migrations/templates.d.mts +3 -2
- package/dist/migrations/templates.mjs +4 -3
- package/dist/migrations/templates.mjs.map +1 -1
- package/dist/schema/column.mjs +155 -157
- package/dist/schema/column.mjs.map +1 -1
- package/dist/schema/columns/index.mjs +103 -171
- package/dist/schema/columns/index.mjs.map +1 -1
- package/dist/schema/index.mjs +15 -0
- package/dist/schema/index.mjs.map +1 -0
- package/dist/schema/registry.mjs +122 -119
- package/dist/schema/registry.mjs.map +1 -1
- package/dist/schema/table.mjs +4 -1
- package/dist/schema/table.mjs.map +1 -1
- package/dist/sync/synchronizer.mjs +2 -1
- package/dist/sync/synchronizer.mjs.map +1 -1
- package/dist/utils/naming.cjs +9 -0
- package/dist/utils/naming.cjs.map +1 -1
- package/dist/utils/naming.mjs +9 -1
- package/dist/utils/naming.mjs.map +1 -1
- package/package.json +1 -1
package/dist/drivers/sqlite.mjs
CHANGED
|
@@ -1,262 +1,278 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { __esmMin } from "../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { DriverError, init_errors } from "../errors.mjs";
|
|
3
|
+
import { BaseDriver, init_driver } from "./driver.mjs";
|
|
4
|
+
import { compileColumnDef, compileCreateTable, init_sql_compiler } from "./sql-compiler.mjs";
|
|
4
5
|
//#region src/drivers/sqlite.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
* Connect to the SQLite database
|
|
19
|
-
*/
|
|
20
|
-
async connect() {
|
|
21
|
-
if (this.connected) return;
|
|
22
|
-
try {
|
|
23
|
-
this.db = await this.getAdapter();
|
|
24
|
-
await this.db.exec("PRAGMA journal_mode=WAL");
|
|
25
|
-
await this.db.exec("PRAGMA foreign_keys=ON");
|
|
26
|
-
this.connected = true;
|
|
27
|
-
} catch (err) {
|
|
28
|
-
throw new DriverError(`Failed to connect to SQLite database: ${err.message}`);
|
|
6
|
+
var SQLiteDriver;
|
|
7
|
+
var init_sqlite = __esmMin((() => {
|
|
8
|
+
init_errors();
|
|
9
|
+
init_driver();
|
|
10
|
+
init_sql_compiler();
|
|
11
|
+
SQLiteDriver = class extends BaseDriver {
|
|
12
|
+
db = null;
|
|
13
|
+
config;
|
|
14
|
+
provider;
|
|
15
|
+
constructor(config, provider) {
|
|
16
|
+
super();
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.provider = provider;
|
|
29
19
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Connect to the SQLite database
|
|
22
|
+
*/
|
|
23
|
+
async connect() {
|
|
24
|
+
if (this.connected) return;
|
|
25
|
+
try {
|
|
26
|
+
this.db = await this.getAdapter();
|
|
27
|
+
await this.db.exec("PRAGMA journal_mode=WAL");
|
|
28
|
+
await this.db.exec("PRAGMA foreign_keys=ON");
|
|
29
|
+
this.connected = true;
|
|
30
|
+
} catch (err) {
|
|
31
|
+
throw new DriverError(`Failed to connect to SQLite database: ${err.message}`);
|
|
32
|
+
}
|
|
38
33
|
}
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
34
|
+
async getAdapter() {
|
|
35
|
+
const provider = this.provider;
|
|
36
|
+
if (!provider || provider === "better-sqlite3") try {
|
|
37
|
+
const BetterSqlite3 = await import("better-sqlite3");
|
|
38
|
+
return new (BetterSqlite3.default || BetterSqlite3)(this.config.filename);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
if (provider === "better-sqlite3") throw err;
|
|
41
|
+
}
|
|
42
|
+
if (!provider || provider === "sqlite3") try {
|
|
43
|
+
const db = new (await (import("sqlite3"))).Database(this.config.filename);
|
|
44
|
+
return {
|
|
45
|
+
close: () => new Promise((res, rej) => db.close((err) => err ? rej(err) : res())),
|
|
46
|
+
exec: (sql) => new Promise((res, rej) => db.exec(sql, (err) => err ? rej(err) : res())),
|
|
47
|
+
prepare: (sql) => ({
|
|
48
|
+
run: (...params) => new Promise((res, rej) => {
|
|
49
|
+
db.run(sql, params, function(err) {
|
|
50
|
+
if (err) return rej(err);
|
|
51
|
+
res({
|
|
52
|
+
lastInsertRowid: this.lastID,
|
|
53
|
+
changes: this.changes
|
|
54
|
+
});
|
|
51
55
|
});
|
|
52
|
-
})
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
+
}),
|
|
57
|
+
all: (...params) => new Promise((res, rej) => {
|
|
58
|
+
db.all(sql, params, (err, rows) => err ? rej(err) : res(rows));
|
|
59
|
+
})
|
|
56
60
|
})
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
};
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (provider === "sqlite3") throw err;
|
|
64
|
+
}
|
|
65
|
+
if (!provider || provider === "sql.js") try {
|
|
66
|
+
const SQL = await (await import("sql.js")).default();
|
|
67
|
+
const fs = await import("fs");
|
|
68
|
+
let data;
|
|
69
|
+
if (fs.existsSync(this.config.filename)) data = fs.readFileSync(this.config.filename);
|
|
70
|
+
const db = new SQL.Database(data);
|
|
71
|
+
return {
|
|
72
|
+
close: () => {
|
|
73
|
+
const binaryArray = db.export();
|
|
74
|
+
fs.writeFileSync(this.config.filename, Buffer.from(binaryArray));
|
|
75
|
+
db.close();
|
|
76
|
+
},
|
|
77
|
+
exec: (sql) => db.run(sql),
|
|
78
|
+
prepare: (sql) => {
|
|
79
|
+
const stmt = db.prepare(sql);
|
|
80
|
+
return {
|
|
81
|
+
run: (...params) => {
|
|
82
|
+
stmt.run(params);
|
|
83
|
+
const result = db.exec("SELECT last_insert_rowid()");
|
|
84
|
+
return {
|
|
85
|
+
lastInsertRowid: result[0]?.values[0] ? result[0].values[0][0] : 0,
|
|
86
|
+
changes: db.getRowsModified()
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
all: (...params) => {
|
|
90
|
+
const rows = [];
|
|
91
|
+
stmt.bind(params);
|
|
92
|
+
while (stmt.step()) rows.push(stmt.getAsObject());
|
|
93
|
+
return rows;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (provider === "sql.js") throw err;
|
|
100
|
+
}
|
|
101
|
+
if (!provider || provider === "bun:sqlite") try {
|
|
102
|
+
const { Database } = await import("bun:sqlite");
|
|
103
|
+
return new Database(this.config.filename);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (provider === "bun:sqlite") throw err;
|
|
106
|
+
}
|
|
107
|
+
throw new Error(provider ? `SQLite provider "${provider}" not found.` : "No SQLite driver found. Please install better-sqlite3, sqlite3, sql.js or run with Bun.");
|
|
61
108
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
109
|
+
/**
|
|
110
|
+
* Disconnect from the SQLite database
|
|
111
|
+
*/
|
|
112
|
+
async disconnect() {
|
|
113
|
+
if (this.db) {
|
|
114
|
+
try {
|
|
115
|
+
await this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
116
|
+
} catch {}
|
|
117
|
+
await this.db.close();
|
|
118
|
+
this.db = null;
|
|
119
|
+
this.connected = false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Execute a SQL statement
|
|
124
|
+
* @param {string} sql - SQL statement
|
|
125
|
+
* @param {unknown[]} [params] - Query parameters
|
|
126
|
+
* @returns {Promise<any>} Execution result with lastInsertRowid and changes
|
|
127
|
+
*/
|
|
128
|
+
async execute(sql, params = []) {
|
|
129
|
+
try {
|
|
130
|
+
const formatted = this.formatParams(params);
|
|
131
|
+
if (formatted.length === 0) {
|
|
132
|
+
await this.db.exec(sql);
|
|
77
133
|
return {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const result = db.exec("SELECT last_insert_rowid()");
|
|
81
|
-
return {
|
|
82
|
-
lastInsertRowid: result[0]?.values[0] ? result[0].values[0][0] : 0,
|
|
83
|
-
changes: db.getRowsModified()
|
|
84
|
-
};
|
|
85
|
-
},
|
|
86
|
-
all: (...params) => {
|
|
87
|
-
const rows = [];
|
|
88
|
-
stmt.bind(params);
|
|
89
|
-
while (stmt.step()) rows.push(stmt.getAsObject());
|
|
90
|
-
return rows;
|
|
91
|
-
}
|
|
134
|
+
insertId: 0,
|
|
135
|
+
affectedRows: 0
|
|
92
136
|
};
|
|
93
137
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
138
|
+
const result = await this.db.prepare(sql).run(...formatted);
|
|
139
|
+
return {
|
|
140
|
+
insertId: Number(result.lastInsertRowid),
|
|
141
|
+
affectedRows: result.changes
|
|
142
|
+
};
|
|
143
|
+
} catch (err) {
|
|
144
|
+
throw new DriverError(`SQLite execute error: ${err.message}`);
|
|
145
|
+
}
|
|
97
146
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
147
|
+
/**
|
|
148
|
+
* Execute a SQL query
|
|
149
|
+
* @param {string} sql - SQL query
|
|
150
|
+
* @param {unknown[]} [params] - Query parameters
|
|
151
|
+
* @returns {Promise<any[]>} Query results
|
|
152
|
+
*/
|
|
153
|
+
async query(sql, params = []) {
|
|
154
|
+
try {
|
|
155
|
+
return await this.db.prepare(sql).all(...this.formatParams(params));
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw new DriverError(`SQLite query error: ${err.message}`);
|
|
158
|
+
}
|
|
103
159
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
async disconnect() {
|
|
110
|
-
if (this.db) {
|
|
111
|
-
await this.db.close();
|
|
112
|
-
this.db = null;
|
|
113
|
-
this.connected = false;
|
|
160
|
+
formatParams(params) {
|
|
161
|
+
return params.map((p) => {
|
|
162
|
+
if (p instanceof Date) return p.toISOString();
|
|
163
|
+
return p;
|
|
164
|
+
});
|
|
114
165
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
async execute(sql, params = []) {
|
|
123
|
-
try {
|
|
124
|
-
const result = await this.db.prepare(sql).run(...this.formatParams(params));
|
|
125
|
-
return {
|
|
126
|
-
insertId: Number(result.lastInsertRowid),
|
|
127
|
-
affectedRows: result.changes
|
|
128
|
-
};
|
|
129
|
-
} catch (err) {
|
|
130
|
-
throw new DriverError(`SQLite execute error: ${err.message}`);
|
|
166
|
+
/**
|
|
167
|
+
* Check if a table exists
|
|
168
|
+
* @param {string} name - Table name
|
|
169
|
+
* @returns {Promise<boolean>} Whether the table exists
|
|
170
|
+
*/
|
|
171
|
+
async tableExists(name) {
|
|
172
|
+
return (await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name=?", [name])).length > 0;
|
|
131
173
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
174
|
+
/**
|
|
175
|
+
* Get column metadata for a table
|
|
176
|
+
* @param {string} name - Table name
|
|
177
|
+
* @returns {Promise<ColumnMetadata[]>} Column metadata
|
|
178
|
+
*/
|
|
179
|
+
async getTableColumns(name) {
|
|
180
|
+
return (await this.query(`PRAGMA table_info(\`${name}\`)`)).map((row) => ({
|
|
181
|
+
name: row.name,
|
|
182
|
+
type: this.mapSQLiteType(row.type),
|
|
183
|
+
primaryKey: row.pk === 1,
|
|
184
|
+
autoIncrement: row.pk === 1 && row.type.toUpperCase() === "INTEGER",
|
|
185
|
+
notNull: row.notnull === 1,
|
|
186
|
+
unique: false,
|
|
187
|
+
defaultValue: row.dflt_value
|
|
188
|
+
}));
|
|
144
189
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Check if a table exists
|
|
154
|
-
* @param {string} name - Table name
|
|
155
|
-
* @returns {Promise<boolean>} Whether the table exists
|
|
156
|
-
*/
|
|
157
|
-
async tableExists(name) {
|
|
158
|
-
return (await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name=?", [name])).length > 0;
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Get column metadata for a table
|
|
162
|
-
* @param {string} name - Table name
|
|
163
|
-
* @returns {Promise<ColumnMetadata[]>} Column metadata
|
|
164
|
-
*/
|
|
165
|
-
async getTableColumns(name) {
|
|
166
|
-
return (await this.query(`PRAGMA table_info(\`${name}\`)`)).map((row) => ({
|
|
167
|
-
name: row.name,
|
|
168
|
-
type: this.mapSQLiteType(row.type),
|
|
169
|
-
primaryKey: row.pk === 1,
|
|
170
|
-
autoIncrement: row.pk === 1 && row.type.toUpperCase() === "INTEGER",
|
|
171
|
-
notNull: row.notnull === 1,
|
|
172
|
-
unique: false,
|
|
173
|
-
defaultValue: row.dflt_value
|
|
174
|
-
}));
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Create a table from metadata
|
|
178
|
-
* @param {TableMetadata} meta - Table metadata
|
|
179
|
-
*/
|
|
180
|
-
async createTable(meta) {
|
|
181
|
-
const sql = compileCreateTable(meta, "sqlite");
|
|
182
|
-
await this.execute(sql);
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Drop a table
|
|
186
|
-
* @param {string} name - Table name
|
|
187
|
-
*/
|
|
188
|
-
async dropTable(name) {
|
|
189
|
-
await this.execute(`DROP TABLE IF EXISTS \`${name}\``);
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Add a column to a table
|
|
193
|
-
* @param {string} table - Table name
|
|
194
|
-
* @param {ColumnMetadata} column - Column metadata
|
|
195
|
-
*/
|
|
196
|
-
async addColumn(table, column) {
|
|
197
|
-
const colDef = compileColumnDef(column, "sqlite");
|
|
198
|
-
await this.execute(`ALTER TABLE \`${table}\` ADD COLUMN ${colDef}`);
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Drop a column from a table
|
|
202
|
-
* @param {string} table - Table name
|
|
203
|
-
* @param {string} name - Column name
|
|
204
|
-
*/
|
|
205
|
-
async dropColumn(table, name) {
|
|
206
|
-
await this.execute(`ALTER TABLE \`${table}\` DROP COLUMN \`${name}\``);
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Rename a column
|
|
210
|
-
* @param {string} table - Table name
|
|
211
|
-
* @param {string} oldName - Current name
|
|
212
|
-
* @param {string} newName - New name
|
|
213
|
-
*/
|
|
214
|
-
async renameColumn(table, oldName, newName) {
|
|
215
|
-
await this.execute(`ALTER TABLE \`${table}\` RENAME COLUMN \`${oldName}\` TO \`${newName}\``);
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Execute within a transaction
|
|
219
|
-
* @param {() => Promise<T>} fn - Function to execute
|
|
220
|
-
* @returns {Promise<T>} Result
|
|
221
|
-
*/
|
|
222
|
-
async transaction(fn) {
|
|
223
|
-
await this.execute("BEGIN TRANSACTION");
|
|
224
|
-
try {
|
|
225
|
-
const result = await fn();
|
|
226
|
-
await this.execute("COMMIT");
|
|
227
|
-
return result;
|
|
228
|
-
} catch (err) {
|
|
229
|
-
await this.execute("ROLLBACK");
|
|
230
|
-
throw err;
|
|
190
|
+
/**
|
|
191
|
+
* Create a table from metadata
|
|
192
|
+
* @param {TableMetadata} meta - Table metadata
|
|
193
|
+
*/
|
|
194
|
+
async createTable(meta) {
|
|
195
|
+
const sql = compileCreateTable(meta, "sqlite");
|
|
196
|
+
await this.execute(sql);
|
|
231
197
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
198
|
+
/**
|
|
199
|
+
* Drop a table
|
|
200
|
+
* @param {string} name - Table name
|
|
201
|
+
*/
|
|
202
|
+
async dropTable(name) {
|
|
203
|
+
await this.execute(`DROP TABLE IF EXISTS \`${name}\``);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Add a column to a table
|
|
207
|
+
* @param {string} table - Table name
|
|
208
|
+
* @param {ColumnMetadata} column - Column metadata
|
|
209
|
+
*/
|
|
210
|
+
async addColumn(table, column) {
|
|
211
|
+
const colDef = compileColumnDef(column, "sqlite");
|
|
212
|
+
await this.execute(`ALTER TABLE \`${table}\` ADD COLUMN ${colDef}`);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Drop a column from a table
|
|
216
|
+
* @param {string} table - Table name
|
|
217
|
+
* @param {string} name - Column name
|
|
218
|
+
*/
|
|
219
|
+
async dropColumn(table, name) {
|
|
220
|
+
await this.execute(`ALTER TABLE \`${table}\` DROP COLUMN \`${name}\``);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Rename a column
|
|
224
|
+
* @param {string} table - Table name
|
|
225
|
+
* @param {string} oldName - Current name
|
|
226
|
+
* @param {string} newName - New name
|
|
227
|
+
*/
|
|
228
|
+
async renameColumn(table, oldName, newName) {
|
|
229
|
+
await this.execute(`ALTER TABLE \`${table}\` RENAME COLUMN \`${oldName}\` TO \`${newName}\``);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Execute within a transaction
|
|
233
|
+
* @param {() => Promise<T>} fn - Function to execute
|
|
234
|
+
* @returns {Promise<T>} Result
|
|
235
|
+
*/
|
|
236
|
+
async transaction(fn) {
|
|
237
|
+
await this.execute("BEGIN TRANSACTION");
|
|
238
|
+
try {
|
|
239
|
+
const result = await fn();
|
|
240
|
+
await this.execute("COMMIT");
|
|
241
|
+
return result;
|
|
242
|
+
} catch (err) {
|
|
243
|
+
await this.execute("ROLLBACK");
|
|
244
|
+
throw err;
|
|
244
245
|
}
|
|
245
|
-
return result;
|
|
246
|
-
} catch (err) {
|
|
247
|
-
throw new DriverError(`Failed to fetch all table columns: ${err.message}`);
|
|
248
246
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
247
|
+
/**
|
|
248
|
+
* Fetch all column metadata for all tables in the database
|
|
249
|
+
* @returns {Promise<Record<string, ColumnMetadata[]>>} Columns grouped by table name
|
|
250
|
+
*/
|
|
251
|
+
async getAllTableColumns() {
|
|
252
|
+
try {
|
|
253
|
+
const tables = await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
|
|
254
|
+
const result = {};
|
|
255
|
+
for (const table of tables) {
|
|
256
|
+
const tableName = table.name;
|
|
257
|
+
result[tableName] = await this.getTableColumns(tableName);
|
|
258
|
+
}
|
|
259
|
+
return result;
|
|
260
|
+
} catch (err) {
|
|
261
|
+
throw new DriverError(`Failed to fetch all table columns: ${err.message}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
mapSQLiteType(type) {
|
|
265
|
+
const upper = type.toUpperCase();
|
|
266
|
+
if (upper.includes("INT")) return "integer";
|
|
267
|
+
if (upper.includes("CHAR") || upper.includes("TEXT") || upper.includes("CLOB")) return "text";
|
|
268
|
+
if (upper.includes("REAL") || upper.includes("FLOAT") || upper.includes("DOUBLE")) return "float";
|
|
269
|
+
if (upper.includes("BLOB")) return "blob";
|
|
270
|
+
return "text";
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}));
|
|
259
274
|
//#endregion
|
|
260
|
-
|
|
275
|
+
init_sqlite();
|
|
276
|
+
export { SQLiteDriver, init_sqlite };
|
|
261
277
|
|
|
262
278
|
//# sourceMappingURL=sqlite.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/drivers/sqlite.ts"],"sourcesContent":["import { DriverError } from \"../errors\";\nimport type { ColumnMetadata, SQLiteConnectionConfig, TableMetadata } from \"../types\";\nimport { BaseDriver } from \"./driver\";\nimport { compileColumnDef, compileCreateTable } from \"./sql-compiler\";\n\n/**\n * Interface for SQLite database adapters\n */\ninterface SQLiteAdapter {\n close(): void | Promise<void>;\n prepare(sql: string): SQLiteStatement;\n exec(sql: string): void | Promise<void>;\n}\n\ninterface SQLiteStatement {\n run(...params: any[]): any | Promise<any>;\n all(...params: any[]): any[] | Promise<any[]>;\n}\n\n/**\n * SQLite database driver supporting multiple libraries (better-sqlite3, sqlite3, sql.js, bun:sqlite)\n */\nexport class SQLiteDriver extends BaseDriver {\n private db: SQLiteAdapter | null = null;\n private config: SQLiteConnectionConfig;\n private provider?: \"better-sqlite3\" | \"sqlite3\" | \"sql.js\" | \"bun:sqlite\";\n\n constructor(\n config: SQLiteConnectionConfig,\n provider?: \"better-sqlite3\" | \"sqlite3\" | \"sql.js\" | \"bun:sqlite\",\n ) {\n super();\n this.config = config;\n this.provider = provider;\n }\n\n /**\n * Connect to the SQLite database\n */\n async connect(): Promise<void> {\n if (this.connected) {\n return;\n }\n\n try {\n const adapter = await this.getAdapter();\n this.db = adapter;\n await this.db.exec(\"PRAGMA journal_mode=WAL\");\n await this.db.exec(\"PRAGMA foreign_keys=ON\");\n this.connected = true;\n } catch (err: any) {\n throw new DriverError(`Failed to connect to SQLite database: ${err.message}`);\n }\n }\n\n private async getAdapter(): Promise<SQLiteAdapter> {\n const provider = this.provider;\n\n if (!provider || provider === \"better-sqlite3\") {\n try {\n const BetterSqlite3 = await import(\"better-sqlite3\");\n const Database = BetterSqlite3.default || BetterSqlite3;\n return new Database(this.config.filename) as any;\n } catch (err) {\n if (provider === \"better-sqlite3\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"sqlite3\") {\n try {\n const sqlite3 = await import(\"sqlite3\");\n const db = new sqlite3.Database(this.config.filename);\n\n return {\n close: () => new Promise<void>((res, rej) => db.close((err) => (err ? rej(err) : res()))),\n exec: (sql: string) =>\n new Promise<void>((res, rej) => db.exec(sql, (err) => (err ? rej(err) : res()))),\n prepare: (sql: string) => ({\n run: (...params: any[]) =>\n new Promise<{ lastInsertRowid: number; changes: number }>((res, rej) => {\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) {\n return rej(err);\n }\n res({ lastInsertRowid: this.lastID, changes: this.changes });\n });\n }),\n all: (...params: any[]) =>\n new Promise<any[]>((res, rej) => {\n db.all(sql, params, (err, rows) => (err ? rej(err) : res(rows)));\n }),\n }),\n } as any;\n } catch (err) {\n if (provider === \"sqlite3\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"sql.js\") {\n try {\n const initSqlJs = await import(\"sql.js\");\n const SQL = await initSqlJs.default();\n const fs = await import(\"fs\");\n let data: Buffer | undefined;\n if (fs.existsSync(this.config.filename)) {\n data = fs.readFileSync(this.config.filename);\n }\n const db = new SQL.Database(data);\n return {\n close: () => {\n const binaryArray = db.export();\n fs.writeFileSync(this.config.filename, Buffer.from(binaryArray));\n db.close();\n },\n exec: (sql: string) => db.run(sql),\n prepare: (sql: string) => {\n const stmt = db.prepare(sql);\n return {\n run: (...params: any[]) => {\n stmt.run(params);\n const result = db.exec(\"SELECT last_insert_rowid()\");\n const lastInsertRowid = result[0]?.values[0]\n ? (result[0].values[0][0] as number)\n : 0;\n return { lastInsertRowid, changes: db.getRowsModified() };\n },\n all: (...params: any[]) => {\n const rows: any[] = [];\n stmt.bind(params);\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n return rows;\n },\n };\n },\n } as any;\n } catch (err) {\n if (provider === \"sql.js\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"bun:sqlite\") {\n try {\n const { Database } = await import(\"bun:sqlite\");\n return new Database(this.config.filename) as any;\n } catch (err) {\n if (provider === \"bun:sqlite\") {\n throw err;\n }\n }\n }\n\n throw new Error(\n provider\n ? `SQLite provider \"${provider}\" not found.`\n : \"No SQLite driver found. Please install better-sqlite3, sqlite3, sql.js or run with Bun.\",\n );\n }\n\n /**\n * Disconnect from the SQLite database\n */\n async disconnect(): Promise<void> {\n if (this.db) {\n await this.db.close();\n this.db = null;\n this.connected = false;\n }\n }\n\n /**\n * Execute a SQL statement\n * @param {string} sql - SQL statement\n * @param {unknown[]} [params] - Query parameters\n * @returns {Promise<any>} Execution result with lastInsertRowid and changes\n */\n async execute(sql: string, params: unknown[] = []): Promise<any> {\n try {\n const stmt = this.db!.prepare(sql);\n const result = await stmt.run(...this.formatParams(params));\n return {\n insertId: Number(result.lastInsertRowid),\n affectedRows: result.changes,\n };\n } catch (err: any) {\n throw new DriverError(`SQLite execute error: ${err.message}`);\n }\n }\n\n /**\n * Execute a SQL query\n * @param {string} sql - SQL query\n * @param {unknown[]} [params] - Query parameters\n * @returns {Promise<any[]>} Query results\n */\n async query(sql: string, params: unknown[] = []): Promise<any[]> {\n try {\n const stmt = this.db!.prepare(sql);\n return await stmt.all(...this.formatParams(params));\n } catch (err: any) {\n throw new DriverError(`SQLite query error: ${err.message}`);\n }\n }\n\n private formatParams(params: unknown[]): any[] {\n return params.map((p) => {\n if (p instanceof Date) {\n return p.toISOString();\n }\n return p;\n });\n }\n\n /**\n * Check if a table exists\n * @param {string} name - Table name\n * @returns {Promise<boolean>} Whether the table exists\n */\n async tableExists(name: string): Promise<boolean> {\n const rows = await this.query(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", [\n name,\n ]);\n return rows.length > 0;\n }\n\n /**\n * Get column metadata for a table\n * @param {string} name - Table name\n * @returns {Promise<ColumnMetadata[]>} Column metadata\n */\n async getTableColumns(name: string): Promise<ColumnMetadata[]> {\n const rows = (await this.query(`PRAGMA table_info(\\`${name}\\`)`)) as any[];\n return rows.map((row: any) => ({\n name: row.name,\n type: this.mapSQLiteType(row.type),\n primaryKey: row.pk === 1,\n autoIncrement: row.pk === 1 && row.type.toUpperCase() === \"INTEGER\",\n notNull: row.notnull === 1,\n unique: false,\n defaultValue: row.dflt_value,\n }));\n }\n\n /**\n * Create a table from metadata\n * @param {TableMetadata} meta - Table metadata\n */\n async createTable(meta: TableMetadata): Promise<void> {\n const sql = compileCreateTable(meta, \"sqlite\");\n await this.execute(sql);\n }\n\n /**\n * Drop a table\n * @param {string} name - Table name\n */\n async dropTable(name: string): Promise<void> {\n await this.execute(`DROP TABLE IF EXISTS \\`${name}\\``);\n }\n\n /**\n * Add a column to a table\n * @param {string} table - Table name\n * @param {ColumnMetadata} column - Column metadata\n */\n async addColumn(table: string, column: ColumnMetadata): Promise<void> {\n const colDef = compileColumnDef(column, \"sqlite\");\n await this.execute(`ALTER TABLE \\`${table}\\` ADD COLUMN ${colDef}`);\n }\n\n /**\n * Drop a column from a table\n * @param {string} table - Table name\n * @param {string} name - Column name\n */\n async dropColumn(table: string, name: string): Promise<void> {\n await this.execute(`ALTER TABLE \\`${table}\\` DROP COLUMN \\`${name}\\``);\n }\n\n /**\n * Rename a column\n * @param {string} table - Table name\n * @param {string} oldName - Current name\n * @param {string} newName - New name\n */\n async renameColumn(table: string, oldName: string, newName: string): Promise<void> {\n await this.execute(`ALTER TABLE \\`${table}\\` RENAME COLUMN \\`${oldName}\\` TO \\`${newName}\\``);\n }\n\n /**\n * Execute within a transaction\n * @param {() => Promise<T>} fn - Function to execute\n * @returns {Promise<T>} Result\n */\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n await this.execute(\"BEGIN TRANSACTION\");\n try {\n const result = await fn();\n await this.execute(\"COMMIT\");\n return result;\n } catch (err) {\n await this.execute(\"ROLLBACK\");\n throw err;\n }\n }\n\n /**\n * Fetch all column metadata for all tables in the database\n * @returns {Promise<Record<string, ColumnMetadata[]>>} Columns grouped by table name\n */\n async getAllTableColumns(): Promise<Record<string, ColumnMetadata[]>> {\n try {\n const tables = await this.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\",\n );\n const result: Record<string, ColumnMetadata[]> = {};\n\n for (const table of tables) {\n const tableName = table.name;\n result[tableName] = await this.getTableColumns(tableName);\n }\n return result;\n } catch (err: any) {\n throw new DriverError(`Failed to fetch all table columns: ${err.message}`);\n }\n }\n\n private mapSQLiteType(type: string): ColumnMetadata[\"type\"] {\n const upper = type.toUpperCase();\n if (upper.includes(\"INT\")) {\n return \"integer\";\n }\n if (upper.includes(\"CHAR\") || upper.includes(\"TEXT\") || upper.includes(\"CLOB\")) {\n return \"text\";\n }\n if (upper.includes(\"REAL\") || upper.includes(\"FLOAT\") || upper.includes(\"DOUBLE\")) {\n return \"float\";\n }\n if (upper.includes(\"BLOB\")) {\n return \"blob\";\n }\n return \"text\";\n }\n}\n"],"mappings":";;;;;;;AAsBA,IAAa,eAAb,cAAkC,WAAW;CAC3C,KAAmC;CACnC;CACA;CAEA,YACE,QACA,UACA;AACA,SAAO;AACP,OAAK,SAAS;AACd,OAAK,WAAW;;;;;CAMlB,MAAM,UAAyB;AAC7B,MAAI,KAAK,UACP;AAGF,MAAI;AAEF,QAAK,KADW,MAAM,KAAK,YAAY;AAEvC,SAAM,KAAK,GAAG,KAAK,0BAA0B;AAC7C,SAAM,KAAK,GAAG,KAAK,yBAAyB;AAC5C,QAA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I;;;;;;;;CASxE,MAAM,aAAa,OAAe,SAAiB,SAAgC;AACjF,QAAM,KAAK,QAAQ,iBAAiB,MAAM,qBAAqB,QAAQ,UAAU,QAAQ,IAAI;;;;;;;CAQ/F,MAAM,YAAe,IAAkC;AACrD,QAAM,KAAK,QAAQ,oBAAoB;AACvC,MAAI;GACF,MAAM,SAAS,MAAM,IAAI;AACzB,SAAM,KAAK,QAAQ,SAAS;AAC5B,UAAO;WACA,KAAK;AACZ,SAAM,KAAK,QAAQ,WAAW;AAC9B,SAAM;;;;;;;CAQV,MAAM,qBAAgE;AACpE,MAAI;GACF,MAAM,SAAS,MAAM,KAAK,MACxB,iFACD;GACD,MAAM,SAA2C,EAAE;AAEnD,QAAK,MAAM,SAAS,QAAQ;IAC1B,MAAM,YAAY,MAAM;AACxB,WAAO,aAAa,MAAM,KAAK,gBAAgB,UAAU;;AAE3D,UAAO;WACA,KAAU;AACjB,SAAM,IAAI,YAAY,sCAAsC,IAAI,UAAU;;;CAI9E,cAAsB,MAAsC;EAC1D,MAAM,QAAQ,KAAK,aAAa;AAChC,MAAI,MAAM,SAAS,MAAM,CACvB,QAAO;AAET,MAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,OAAO,CAC5E,QAAO;AAET,MAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,QAAQ,IAAI,MAAM,SAAS,SAAS,CAC/E,QAAO;AAET,MAAI,MAAM,SAAS,OAAO,CACxB,QAAO;AAET,SAAO"}
|
|
1
|
+
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/drivers/sqlite.ts"],"sourcesContent":["import { DriverError } from \"../errors\";\nimport type { ColumnMetadata, SQLiteConnectionConfig, TableMetadata } from \"../types\";\nimport { BaseDriver } from \"./driver\";\nimport { compileColumnDef, compileCreateTable } from \"./sql-compiler\";\n\n/**\n * Interface for SQLite database adapters\n */\ninterface SQLiteAdapter {\n close(): void | Promise<void>;\n prepare(sql: string): SQLiteStatement;\n exec(sql: string): void | Promise<void>;\n}\n\ninterface SQLiteStatement {\n run(...params: any[]): any | Promise<any>;\n all(...params: any[]): any[] | Promise<any[]>;\n}\n\n/**\n * SQLite database driver supporting multiple libraries (better-sqlite3, sqlite3, sql.js, bun:sqlite)\n */\nexport class SQLiteDriver extends BaseDriver {\n private db: SQLiteAdapter | null = null;\n private config: SQLiteConnectionConfig;\n private provider?: \"better-sqlite3\" | \"sqlite3\" | \"sql.js\" | \"bun:sqlite\";\n\n constructor(\n config: SQLiteConnectionConfig,\n provider?: \"better-sqlite3\" | \"sqlite3\" | \"sql.js\" | \"bun:sqlite\",\n ) {\n super();\n this.config = config;\n this.provider = provider;\n }\n\n /**\n * Connect to the SQLite database\n */\n async connect(): Promise<void> {\n if (this.connected) {\n return;\n }\n\n try {\n const adapter = await this.getAdapter();\n this.db = adapter;\n await this.db.exec(\"PRAGMA journal_mode=WAL\");\n await this.db.exec(\"PRAGMA foreign_keys=ON\");\n this.connected = true;\n } catch (err: any) {\n throw new DriverError(`Failed to connect to SQLite database: ${err.message}`);\n }\n }\n\n private async getAdapter(): Promise<SQLiteAdapter> {\n const provider = this.provider;\n\n if (!provider || provider === \"better-sqlite3\") {\n try {\n const BetterSqlite3 = await import(\"better-sqlite3\");\n const Database = BetterSqlite3.default || BetterSqlite3;\n return new Database(this.config.filename) as any;\n } catch (err) {\n if (provider === \"better-sqlite3\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"sqlite3\") {\n try {\n const sqlite3 = await import(\"sqlite3\");\n const db = new sqlite3.Database(this.config.filename);\n\n return {\n close: () => new Promise<void>((res, rej) => db.close((err) => (err ? rej(err) : res()))),\n exec: (sql: string) =>\n new Promise<void>((res, rej) => db.exec(sql, (err) => (err ? rej(err) : res()))),\n prepare: (sql: string) => ({\n run: (...params: any[]) =>\n new Promise<{ lastInsertRowid: number; changes: number }>((res, rej) => {\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) {\n return rej(err);\n }\n res({ lastInsertRowid: this.lastID, changes: this.changes });\n });\n }),\n all: (...params: any[]) =>\n new Promise<any[]>((res, rej) => {\n db.all(sql, params, (err, rows) => (err ? rej(err) : res(rows)));\n }),\n }),\n } as any;\n } catch (err) {\n if (provider === \"sqlite3\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"sql.js\") {\n try {\n const initSqlJs = await import(\"sql.js\");\n const SQL = await initSqlJs.default();\n const fs = await import(\"fs\");\n let data: Buffer | undefined;\n if (fs.existsSync(this.config.filename)) {\n data = fs.readFileSync(this.config.filename);\n }\n const db = new SQL.Database(data);\n return {\n close: () => {\n const binaryArray = db.export();\n fs.writeFileSync(this.config.filename, Buffer.from(binaryArray));\n db.close();\n },\n exec: (sql: string) => db.run(sql),\n prepare: (sql: string) => {\n const stmt = db.prepare(sql);\n return {\n run: (...params: any[]) => {\n stmt.run(params);\n const result = db.exec(\"SELECT last_insert_rowid()\");\n const lastInsertRowid = result[0]?.values[0]\n ? (result[0].values[0][0] as number)\n : 0;\n return { lastInsertRowid, changes: db.getRowsModified() };\n },\n all: (...params: any[]) => {\n const rows: any[] = [];\n stmt.bind(params);\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n return rows;\n },\n };\n },\n } as any;\n } catch (err) {\n if (provider === \"sql.js\") {\n throw err;\n }\n }\n }\n\n if (!provider || provider === \"bun:sqlite\") {\n try {\n const { Database } = await import(\"bun:sqlite\");\n return new Database(this.config.filename) as any;\n } catch (err) {\n if (provider === \"bun:sqlite\") {\n throw err;\n }\n }\n }\n\n throw new Error(\n provider\n ? `SQLite provider \"${provider}\" not found.`\n : \"No SQLite driver found. Please install better-sqlite3, sqlite3, sql.js or run with Bun.\",\n );\n }\n\n /**\n * Disconnect from the SQLite database\n */\n async disconnect(): Promise<void> {\n if (this.db) {\n try {\n await this.db.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\");\n } catch {}\n await this.db.close();\n this.db = null;\n this.connected = false;\n }\n }\n\n /**\n * Execute a SQL statement\n * @param {string} sql - SQL statement\n * @param {unknown[]} [params] - Query parameters\n * @returns {Promise<any>} Execution result with lastInsertRowid and changes\n */\n async execute(sql: string, params: unknown[] = []): Promise<any> {\n try {\n const formatted = this.formatParams(params);\n if (formatted.length === 0) {\n await this.db!.exec(sql);\n return { insertId: 0, affectedRows: 0 };\n }\n const stmt = this.db!.prepare(sql);\n const result = await stmt.run(...formatted);\n return {\n insertId: Number(result.lastInsertRowid),\n affectedRows: result.changes,\n };\n } catch (err: any) {\n throw new DriverError(`SQLite execute error: ${err.message}`);\n }\n }\n\n /**\n * Execute a SQL query\n * @param {string} sql - SQL query\n * @param {unknown[]} [params] - Query parameters\n * @returns {Promise<any[]>} Query results\n */\n async query(sql: string, params: unknown[] = []): Promise<any[]> {\n try {\n const stmt = this.db!.prepare(sql);\n return await stmt.all(...this.formatParams(params));\n } catch (err: any) {\n throw new DriverError(`SQLite query error: ${err.message}`);\n }\n }\n\n private formatParams(params: unknown[]): any[] {\n return params.map((p) => {\n if (p instanceof Date) {\n return p.toISOString();\n }\n return p;\n });\n }\n\n /**\n * Check if a table exists\n * @param {string} name - Table name\n * @returns {Promise<boolean>} Whether the table exists\n */\n async tableExists(name: string): Promise<boolean> {\n const rows = await this.query(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", [\n name,\n ]);\n return rows.length > 0;\n }\n\n /**\n * Get column metadata for a table\n * @param {string} name - Table name\n * @returns {Promise<ColumnMetadata[]>} Column metadata\n */\n async getTableColumns(name: string): Promise<ColumnMetadata[]> {\n const rows = (await this.query(`PRAGMA table_info(\\`${name}\\`)`)) as any[];\n return rows.map((row: any) => ({\n name: row.name,\n type: this.mapSQLiteType(row.type),\n primaryKey: row.pk === 1,\n autoIncrement: row.pk === 1 && row.type.toUpperCase() === \"INTEGER\",\n notNull: row.notnull === 1,\n unique: false,\n defaultValue: row.dflt_value,\n }));\n }\n\n /**\n * Create a table from metadata\n * @param {TableMetadata} meta - Table metadata\n */\n async createTable(meta: TableMetadata): Promise<void> {\n const sql = compileCreateTable(meta, \"sqlite\");\n await this.execute(sql);\n }\n\n /**\n * Drop a table\n * @param {string} name - Table name\n */\n async dropTable(name: string): Promise<void> {\n await this.execute(`DROP TABLE IF EXISTS \\`${name}\\``);\n }\n\n /**\n * Add a column to a table\n * @param {string} table - Table name\n * @param {ColumnMetadata} column - Column metadata\n */\n async addColumn(table: string, column: ColumnMetadata): Promise<void> {\n const colDef = compileColumnDef(column, \"sqlite\");\n await this.execute(`ALTER TABLE \\`${table}\\` ADD COLUMN ${colDef}`);\n }\n\n /**\n * Drop a column from a table\n * @param {string} table - Table name\n * @param {string} name - Column name\n */\n async dropColumn(table: string, name: string): Promise<void> {\n await this.execute(`ALTER TABLE \\`${table}\\` DROP COLUMN \\`${name}\\``);\n }\n\n /**\n * Rename a column\n * @param {string} table - Table name\n * @param {string} oldName - Current name\n * @param {string} newName - New name\n */\n async renameColumn(table: string, oldName: string, newName: string): Promise<void> {\n await this.execute(`ALTER TABLE \\`${table}\\` RENAME COLUMN \\`${oldName}\\` TO \\`${newName}\\``);\n }\n\n /**\n * Execute within a transaction\n * @param {() => Promise<T>} fn - Function to execute\n * @returns {Promise<T>} Result\n */\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n await this.execute(\"BEGIN TRANSACTION\");\n try {\n const result = await fn();\n await this.execute(\"COMMIT\");\n return result;\n } catch (err) {\n await this.execute(\"ROLLBACK\");\n throw err;\n }\n }\n\n /**\n * Fetch all column metadata for all tables in the database\n * @returns {Promise<Record<string, ColumnMetadata[]>>} Columns grouped by table name\n */\n async getAllTableColumns(): Promise<Record<string, ColumnMetadata[]>> {\n try {\n const tables = await this.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\",\n );\n const result: Record<string, ColumnMetadata[]> = {};\n\n for (const table of tables) {\n const tableName = table.name;\n result[tableName] = await this.getTableColumns(tableName);\n }\n return result;\n } catch (err: any) {\n throw new DriverError(`Failed to fetch all table columns: ${err.message}`);\n }\n }\n\n private mapSQLiteType(type: string): ColumnMetadata[\"type\"] {\n const upper = type.toUpperCase();\n if (upper.includes(\"INT\")) {\n return \"integer\";\n }\n if (upper.includes(\"CHAR\") || upper.includes(\"TEXT\") || upper.includes(\"CLOB\")) {\n return \"text\";\n }\n if (upper.includes(\"REAL\") || upper.includes(\"FLOAT\") || upper.includes(\"DOUBLE\")) {\n return \"float\";\n }\n if (upper.includes(\"BLOB\")) {\n return \"blob\";\n }\n return \"text\";\n }\n}\n"],"mappings":";;;;;;;cAAwC;cAEF;oBACgC;AAmBzD,gBAAb,cAAkC,WAAW;EAC3C,KAAmC;EACnC;EACA;EAEA,YACE,QACA,UACA;AACA,UAAO;AACP,QAAK,SAAS;AACd,QAAK,WAAW;;;;;EAMlB,MAAM,UAAyB;AAC7B,OAAI,KAAK,UACP;AAGF,OAAI;AAEF,SAAK,KADW,MAAM,KAAK,YAAY;AAEvC,UAAM,KAAK,GAAG,KAAK,0BAA0B;AAC7C,UAAM,KAAK,GAAG,KAAK,yBAAyB;AAC5C,SAAK,YAAY;YACV,KAAU;AACjB,UAAM,IAAI,YAAY,yCAAyC,IAAI,UAAU;;;EAIjF,MAAc,aAAqC;GACjD,MAAM,WAAW,KAAK;AAEtB,OAAI,CAAC,YAAY,aAAa,iBAC5B,KAAI;IACF,MAAM,gBAAgB,MAAM,OAAO;AAEnC,WAAO,KADU,cAAc,WAAW,eACtB,KAAK,OAAO,SAAS;YAClC,KAAK;AACZ,QAAI,aAAa,iBACf,OAAM;;AAKZ,OAAI,CAAC,YAAY,aAAa,UAC5B,KAAI;IAEF,MAAM,KAAK,KADK,OAAM,OAAO,aACN,SAAS,KAAK,OAAO,SAAS;AAErD,WAAO;KACL,aAAa,IAAI,SAAe,KAAK,QAAQ,GAAG,OAAO,QAAS,MAAM,IAAI,IAAI,GAAG,KAAK,CAAE,CAAC;KACzF,OAAO,QACL,IAAI,SAAe,KAAK,QAAQ,GAAG,KAAK,MAAM,QAAS,MAAM,I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