@devbro/neko-sql 0.1.30 → 0.1.32
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/README.md +42 -2
- package/dist/databases/index.d.mts +4 -0
- package/dist/databases/index.mjs +1 -0
- package/dist/databases/index.mjs.map +1 -1
- package/dist/databases/postgresql/PostgresqlConnection.d.mts +2 -2
- package/dist/databases/postgresql/PostgresqlConnection.mjs +10 -8
- package/dist/databases/postgresql/PostgresqlConnection.mjs.map +1 -1
- package/dist/databases/sqlite/SqliteConnection.d.mts +132 -0
- package/dist/databases/sqlite/SqliteConnection.mjs +242 -0
- package/dist/databases/sqlite/SqliteConnection.mjs.map +1 -0
- package/dist/databases/sqlite/SqliteQueryGrammar.d.mts +17 -0
- package/dist/databases/sqlite/SqliteQueryGrammar.mjs +40 -0
- package/dist/databases/sqlite/SqliteQueryGrammar.mjs.map +1 -0
- package/dist/databases/sqlite/SqliteSchemaGrammar.d.mts +7 -0
- package/dist/databases/sqlite/SqliteSchemaGrammar.mjs +12 -0
- package/dist/databases/sqlite/SqliteSchemaGrammar.mjs.map +1 -0
- package/dist/databases/sqlite/index.d.mts +6 -0
- package/dist/databases/sqlite/index.mjs +4 -0
- package/dist/databases/sqlite/index.mjs.map +1 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.js +295 -10
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
package/README.md
CHANGED
|
@@ -14,16 +14,56 @@ SQL engine for quick abstracted relational database connections.
|
|
|
14
14
|
currently supported databases:
|
|
15
15
|
|
|
16
16
|
- postgresql
|
|
17
|
+
- sqlite
|
|
17
18
|
|
|
18
19
|
future planned:
|
|
19
20
|
|
|
20
21
|
- mysql
|
|
21
|
-
- sqlite
|
|
22
22
|
- mssql
|
|
23
23
|
|
|
24
24
|
## how to use
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
### PostgreSQL Example
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { PostgresqlConnection } from '@devbro/neko-sql';
|
|
30
|
+
|
|
31
|
+
const conn = new PostgresqlConnection({
|
|
32
|
+
host: 'localhost',
|
|
33
|
+
database: 'mydb',
|
|
34
|
+
user: 'myuser',
|
|
35
|
+
password: 'mypassword',
|
|
36
|
+
port: 5432,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
await conn.connect();
|
|
40
|
+
|
|
41
|
+
// Use Query builder
|
|
42
|
+
const query = conn.getQuery();
|
|
43
|
+
const results = await query.table('users').whereOp('id', '=', 1).get();
|
|
44
|
+
|
|
45
|
+
await conn.disconnect();
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### SQLite Example
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import { SqliteConnection } from '@devbro/neko-sql';
|
|
52
|
+
|
|
53
|
+
const conn = new SqliteConnection({
|
|
54
|
+
filename: './database.db',
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
await conn.connect();
|
|
58
|
+
|
|
59
|
+
// Use Query builder
|
|
60
|
+
const query = conn.getQuery();
|
|
61
|
+
const results = await query.table('users').whereOp('id', '=', 1).get();
|
|
62
|
+
|
|
63
|
+
await conn.disconnect();
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
please check test classes for more robust examples
|
|
27
67
|
|
|
28
68
|
## APIs
|
|
29
69
|
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
export { PostgresqlConnection } from './postgresql/PostgresqlConnection.mjs';
|
|
2
2
|
export { PostgresqlQueryGrammar } from './postgresql/PostgresqlQueryGrammar.mjs';
|
|
3
3
|
export { PostgresqlSchemaGrammar } from './postgresql/PostgresqlSchemaGrammar.mjs';
|
|
4
|
+
export { SqliteConfig, SqliteConnection } from './sqlite/SqliteConnection.mjs';
|
|
5
|
+
export { SqliteQueryGrammar } from './sqlite/SqliteQueryGrammar.mjs';
|
|
6
|
+
export { SqliteSchemaGrammar } from './sqlite/SqliteSchemaGrammar.mjs';
|
|
4
7
|
import '../Blueprint-D3WHeqRS.mjs';
|
|
5
8
|
import '@devbro/neko-helper';
|
|
6
9
|
import 'pg';
|
|
10
|
+
import 'better-sqlite3';
|
package/dist/databases/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/databases/index.mts"],"sourcesContent":["export * from './postgresql/index.mjs';\n"],"mappings":"AAAA,cAAc;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/databases/index.mts"],"sourcesContent":["export * from './postgresql/index.mjs';\nexport * from './sqlite/index.mjs';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { PostgresqlQueryGrammar } from './PostgresqlQueryGrammar.mjs';
|
|
2
|
-
import { PostgresqlSchemaGrammar } from './PostgresqlSchemaGrammar.mjs';
|
|
3
1
|
import { b as Connection, c as connection_events, m as CompiledSql, d as Query, S as Schema } from '../../Blueprint-D3WHeqRS.mjs';
|
|
4
2
|
import { PoolClient, Pool, PoolConfig } from 'pg';
|
|
3
|
+
import { PostgresqlQueryGrammar } from './PostgresqlQueryGrammar.mjs';
|
|
4
|
+
import { PostgresqlSchemaGrammar } from './PostgresqlSchemaGrammar.mjs';
|
|
5
5
|
import '@devbro/neko-helper';
|
|
6
6
|
|
|
7
7
|
declare class PostgresqlConnection extends Connection {
|
|
@@ -44,7 +44,8 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
async connect() {
|
|
47
|
-
this.eventManager.emit("connect")
|
|
47
|
+
this.eventManager.emit("connect").catch(() => {
|
|
48
|
+
});
|
|
48
49
|
this.connection = await PostgresqlConnection.pool.connect();
|
|
49
50
|
return true;
|
|
50
51
|
}
|
|
@@ -57,7 +58,8 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
57
58
|
if (sql.parts && sql.parts.length > 0) {
|
|
58
59
|
sql2 = sql.parts.map((v) => v === "?" ? "$" + counter++ : v).join(" ");
|
|
59
60
|
}
|
|
60
|
-
this.eventManager.emit("query", { sql: sql2, bindings: sql.bindings })
|
|
61
|
+
this.eventManager.emit("query", { sql: sql2, bindings: sql.bindings }).catch(() => {
|
|
62
|
+
});
|
|
61
63
|
if (!this.isConnected()) {
|
|
62
64
|
await this.connect();
|
|
63
65
|
}
|
|
@@ -73,7 +75,8 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
73
75
|
}
|
|
74
76
|
await this.connection?.release();
|
|
75
77
|
this.connection = void 0;
|
|
76
|
-
this.eventManager.emit("disconnect")
|
|
78
|
+
this.eventManager.emit("disconnect").catch(() => {
|
|
79
|
+
});
|
|
77
80
|
return true;
|
|
78
81
|
}
|
|
79
82
|
getQuery() {
|
|
@@ -97,9 +100,8 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
97
100
|
async rollback() {
|
|
98
101
|
await this.runQuery({ sql: "ROLLBACK", bindings: [], parts: ["ROLLBACK"] });
|
|
99
102
|
}
|
|
100
|
-
static
|
|
101
|
-
PostgresqlConnection.pool.end();
|
|
102
|
-
return;
|
|
103
|
+
static destroy() {
|
|
104
|
+
return PostgresqlConnection.pool.end();
|
|
103
105
|
}
|
|
104
106
|
isConnected() {
|
|
105
107
|
return this.connection !== void 0;
|
|
@@ -136,7 +138,7 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
136
138
|
if (this.isConnected()) {
|
|
137
139
|
throw new Error("Cannot create database while connected.");
|
|
138
140
|
}
|
|
139
|
-
|
|
141
|
+
const conn = new Client({
|
|
140
142
|
...PostgresqlConnection.pool.options,
|
|
141
143
|
database: "postgres"
|
|
142
144
|
});
|
|
@@ -149,7 +151,7 @@ class PostgresqlConnection extends ConnectionAbs {
|
|
|
149
151
|
if (this.isConnected()) {
|
|
150
152
|
throw new Error("Cannot drop database while connected.");
|
|
151
153
|
}
|
|
152
|
-
|
|
154
|
+
const conn = new Client({
|
|
153
155
|
...PostgresqlConnection.pool.options,
|
|
154
156
|
database: "postgres"
|
|
155
157
|
// connect to default 'postgres' database to drop others
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/databases/postgresql/PostgresqlConnection.mts"],"sourcesContent":["import { connection_events, Connection as ConnectionAbs } from '../../Connection.mjs';\nimport { Client, PoolClient, PoolConfig } from 'pg';\nimport { Pool } from 'pg';\nimport { CompiledSql } from '../../types.mjs';\nimport { Query } from '../../Query.mjs';\nimport { PostgresqlQueryGrammar } from './PostgresqlQueryGrammar.mjs';\nimport { Schema } from '../../Schema.mjs';\nimport { PostgresqlSchemaGrammar } from './PostgresqlSchemaGrammar.mjs';\nimport Cursor from 'pg-cursor';\nimport { EventManager } from '@devbro/neko-helper';\n\nexport class PostgresqlConnection extends ConnectionAbs {\n private eventManager = new EventManager();\n\n on(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.on(event, listener);\n return this;\n }\n off(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.off(event, listener);\n return this;\n }\n emit(event: connection_events, ...args: any[]): Promise<boolean> {\n return this.eventManager.emit(event, ...args);\n }\n\n connection: PoolClient | undefined;\n static pool: Pool;\n\n static defaults: PoolConfig = {\n port: 5432,\n ssl: false,\n max: 20,\n idleTimeoutMillis: 1, // wait X milli seconds before closing an idle/released connection\n connectionTimeoutMillis: 30000, // wait up to 30 seconds to obtain a new connection\n maxUses: 7500,\n };\n\n constructor(params: PoolConfig) {\n super();\n if (!PostgresqlConnection.pool) {\n PostgresqlConnection.pool = new Pool({ ...PostgresqlConnection.defaults, ...params });\n }\n }\n async connect(): Promise<boolean> {\n this.eventManager.emit('connect');\n this.connection = await PostgresqlConnection.pool.connect();\n return true;\n }\n async runQuery(sql: CompiledSql | string): Promise<any> {\n if( typeof sql === 'string') {\n sql = { sql: sql, bindings: [], parts: [sql] };\n }\n let counter = 1;\n let sql2 = sql.sql;\n if (sql.parts && sql.parts.length > 0) {\n sql2 = sql.parts.map((v) => (v === '?' ? '$' + counter++ : v)).join(' ');\n }\n\n this.eventManager.emit('query', { sql: sql2, bindings: sql.bindings });\n\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query(sql2, sql.bindings);\n return result?.rows;\n }\n\n async runCursor(sql: CompiledSql): Promise<any> {\n return this.connection?.query(new Cursor(sql.sql, sql.bindings));\n }\n\n async disconnect(): Promise<boolean> {\n if (this.connection === undefined) {\n return true;\n }\n await this.connection?.release();\n this.connection = undefined;\n this.eventManager.emit('disconnect');\n return true;\n }\n\n getQuery(): Query {\n return new Query(this, new PostgresqlQueryGrammar());\n }\n\n getSchema(): Schema {\n return new Schema(this, new PostgresqlSchemaGrammar());\n }\n\n getQueryGrammar(): PostgresqlQueryGrammar {\n return new PostgresqlQueryGrammar();\n }\n getSchemaGrammar(): PostgresqlSchemaGrammar {\n return new PostgresqlSchemaGrammar();\n }\n\n async beginTransaction(): Promise<void> {\n await this.runQuery({ sql: 'BEGIN', bindings: [], parts: ['BEGIN'] });\n }\n\n async commit(): Promise<void> {\n await this.runQuery({ sql: 'COMMIT', bindings: [], parts: ['COMMIT'] });\n }\n\n async rollback(): Promise<void> {\n await this.runQuery({ sql: 'ROLLBACK', bindings: [], parts: ['ROLLBACK'] });\n }\n\n static async destroy(): Promise<void> {\n PostgresqlConnection.pool.end();\n return;\n }\n\n isConnected(): boolean {\n return this.connection !== undefined;\n }\n\n /**\n * Validates and escapes a PostgreSQL identifier (database name, table name, etc.)\n * Uses a whitelist approach to ensure only safe characters are allowed\n */\n private validateAndEscapeIdentifier(name: string): string {\n // PostgreSQL identifiers can contain: letters, digits, underscores, and dollar signs\n // They must start with a letter or underscore\n const validIdentifierPattern = /^[a-zA-Z_][a-zA-Z0-9_$]*$/;\n\n if (!validIdentifierPattern.test(name)) {\n throw new Error(\n `Invalid identifier: \"${name}\". Identifiers must start with a letter or underscore and contain only letters, digits, underscores, and dollar signs.`\n );\n }\n\n // PostgreSQL reserved keywords that should be quoted\n const reservedKeywords = new Set([\n 'user',\n 'table',\n 'database',\n 'order',\n 'group',\n 'select',\n 'insert',\n 'update',\n 'delete',\n ]);\n\n // Quote the identifier if it's a reserved keyword or contains uppercase letters\n if (reservedKeywords.has(name.toLowerCase()) || name !== name.toLowerCase()) {\n // Escape any double quotes in the name\n const escapedName = name.replace(/\"/g, '\"\"');\n return `\"${escapedName}\"`;\n }\n\n return name;\n }\n\n async createDatabase(name: string): Promise<void> {\n if (this.isConnected()) {\n throw new Error('Cannot create database while connected.');\n }\n\n let conn = new Client({\n ...PostgresqlConnection.pool.options,\n database: 'postgres',\n });\n await conn.connect();\n const safeName = this.validateAndEscapeIdentifier(name);\n await conn.query(`CREATE DATABASE ${safeName}`);\n await conn.end();\n }\n\n async dropDatabase(name: string): Promise<void> {\n if (this.isConnected()) {\n throw new Error('Cannot drop database while connected.');\n }\n\n let conn = new Client({\n ...PostgresqlConnection.pool.options,\n database: 'postgres', // connect to default 'postgres' database to drop others\n });\n await conn.connect();\n const safeName = this.validateAndEscapeIdentifier(name);\n await conn.query(`DROP DATABASE ${safeName}`);\n await conn.end();\n }\n\n async listDatabases(): Promise<string[]> {\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query(\n 'SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname'\n );\n return result.rows.map((row: any) => row.datname);\n }\n\n async existsDatabase(name: string): Promise<boolean> {\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query('SELECT 1 FROM pg_database WHERE datname = $1', [\n name,\n ]);\n return result.rows.length > 0;\n }\n}\n"],"mappings":";;AAAA,SAA4B,cAAc,qBAAqB;AAC/D,SAAS,cAAsC;AAC/C,SAAS,YAAY;AAErB,SAAS,aAAa;AACtB,SAAS,8BAA8B;AACvC,SAAS,cAAc;AACvB,SAAS,+BAA+B;AACxC,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAEtB,MAAM,6BAA6B,cAAc;AAAA,EAXxD,OAWwD;AAAA;AAAA;AAAA,EAC9C,eAAe,IAAI,aAAa;AA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AAK,YAAY,GAAG;AACvB,YAAM,KAAK,QAAQ;AAAA,IACrB;AACA,UAAM,SAAS,MAAM,KAAK,WAAY;AAAA,MACpC;AAAA,IACF;AACA,WAAO,OAAO,KAAK,IAAI,CAAC,QAAa,IAAI,OAAO;AAAA,EAClD;AAAA,EAEA,MAAM,eAAe,MAAgC;AACnD,QAAI,CAAC,KAAK,YAAY,GAAG;AACvB,YAAM,KAAK,QAAQ;AAAA,IACrB;AACA,UAAM,SAAS,MAAM,KAAK,WAAY,MAAM,gDAAgD;AAAA,MAC1F;AAAA,IACF,CAAC;AACD,WAAO,OAAO,KAAK,SAAS;AAAA,EAC9B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/databases/postgresql/PostgresqlConnection.mts"],"sourcesContent":["import { connection_events, Connection as ConnectionAbs } from '../../Connection.mjs';\nimport { Client, PoolClient, PoolConfig } from 'pg';\nimport { Pool } from 'pg';\nimport { CompiledSql } from '../../types.mjs';\nimport { Query } from '../../Query.mjs';\nimport { PostgresqlQueryGrammar } from './PostgresqlQueryGrammar.mjs';\nimport { Schema } from '../../Schema.mjs';\nimport { PostgresqlSchemaGrammar } from './PostgresqlSchemaGrammar.mjs';\nimport Cursor from 'pg-cursor';\nimport { EventManager } from '@devbro/neko-helper';\n\nexport class PostgresqlConnection extends ConnectionAbs {\n private eventManager = new EventManager();\n\n on(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.on(event, listener);\n return this;\n }\n off(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.off(event, listener);\n return this;\n }\n emit(event: connection_events, ...args: any[]): Promise<boolean> {\n return this.eventManager.emit(event, ...args);\n }\n\n connection: PoolClient | undefined;\n static pool: Pool;\n\n static defaults: PoolConfig = {\n port: 5432,\n ssl: false,\n max: 20,\n idleTimeoutMillis: 1, // wait X milli seconds before closing an idle/released connection\n connectionTimeoutMillis: 30000, // wait up to 30 seconds to obtain a new connection\n maxUses: 7500,\n };\n\n constructor(params: PoolConfig) {\n super();\n if (!PostgresqlConnection.pool) {\n PostgresqlConnection.pool = new Pool({ ...PostgresqlConnection.defaults, ...params });\n }\n }\n async connect(): Promise<boolean> {\n this.eventManager.emit('connect').catch(() => {});\n this.connection = await PostgresqlConnection.pool.connect();\n return true;\n }\n async runQuery(sql: CompiledSql | string): Promise<any> {\n if (typeof sql === 'string') {\n sql = { sql: sql, bindings: [], parts: [sql] };\n }\n let counter = 1;\n let sql2 = sql.sql;\n if (sql.parts && sql.parts.length > 0) {\n sql2 = sql.parts.map((v) => (v === '?' ? '$' + counter++ : v)).join(' ');\n }\n\n this.eventManager.emit('query', { sql: sql2, bindings: sql.bindings }).catch(() => {});\n\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query(sql2, sql.bindings);\n return result?.rows;\n }\n\n async runCursor(sql: CompiledSql): Promise<any> {\n return this.connection?.query(new Cursor(sql.sql, sql.bindings));\n }\n\n async disconnect(): Promise<boolean> {\n if (this.connection === undefined) {\n return true;\n }\n await this.connection?.release();\n this.connection = undefined;\n this.eventManager.emit('disconnect').catch(() => {});\n return true;\n }\n\n getQuery(): Query {\n return new Query(this, new PostgresqlQueryGrammar());\n }\n\n getSchema(): Schema {\n return new Schema(this, new PostgresqlSchemaGrammar());\n }\n\n getQueryGrammar(): PostgresqlQueryGrammar {\n return new PostgresqlQueryGrammar();\n }\n getSchemaGrammar(): PostgresqlSchemaGrammar {\n return new PostgresqlSchemaGrammar();\n }\n\n async beginTransaction(): Promise<void> {\n await this.runQuery({ sql: 'BEGIN', bindings: [], parts: ['BEGIN'] });\n }\n\n async commit(): Promise<void> {\n await this.runQuery({ sql: 'COMMIT', bindings: [], parts: ['COMMIT'] });\n }\n\n async rollback(): Promise<void> {\n await this.runQuery({ sql: 'ROLLBACK', bindings: [], parts: ['ROLLBACK'] });\n }\n\n static destroy(): Promise<void> {\n return PostgresqlConnection.pool.end();\n }\n\n isConnected(): boolean {\n return this.connection !== undefined;\n }\n\n /**\n * Validates and escapes a PostgreSQL identifier (database name, table name, etc.)\n * Uses a whitelist approach to ensure only safe characters are allowed\n */\n private validateAndEscapeIdentifier(name: string): string {\n // PostgreSQL identifiers can contain: letters, digits, underscores, and dollar signs\n // They must start with a letter or underscore\n const validIdentifierPattern = /^[a-zA-Z_][a-zA-Z0-9_$]*$/;\n\n if (!validIdentifierPattern.test(name)) {\n throw new Error(\n `Invalid identifier: \"${name}\". Identifiers must start with a letter or underscore and contain only letters, digits, underscores, and dollar signs.`\n );\n }\n\n // PostgreSQL reserved keywords that should be quoted\n const reservedKeywords = new Set([\n 'user',\n 'table',\n 'database',\n 'order',\n 'group',\n 'select',\n 'insert',\n 'update',\n 'delete',\n ]);\n\n // Quote the identifier if it's a reserved keyword or contains uppercase letters\n if (reservedKeywords.has(name.toLowerCase()) || name !== name.toLowerCase()) {\n // Escape any double quotes in the name\n const escapedName = name.replace(/\"/g, '\"\"');\n return `\"${escapedName}\"`;\n }\n\n return name;\n }\n\n async createDatabase(name: string): Promise<void> {\n if (this.isConnected()) {\n throw new Error('Cannot create database while connected.');\n }\n\n const conn = new Client({\n ...PostgresqlConnection.pool.options,\n database: 'postgres',\n });\n await conn.connect();\n const safeName = this.validateAndEscapeIdentifier(name);\n await conn.query(`CREATE DATABASE ${safeName}`);\n await conn.end();\n }\n\n async dropDatabase(name: string): Promise<void> {\n if (this.isConnected()) {\n throw new Error('Cannot drop database while connected.');\n }\n\n const conn = new Client({\n ...PostgresqlConnection.pool.options,\n database: 'postgres', // connect to default 'postgres' database to drop others\n });\n await conn.connect();\n const safeName = this.validateAndEscapeIdentifier(name);\n await conn.query(`DROP DATABASE ${safeName}`);\n await conn.end();\n }\n\n async listDatabases(): Promise<string[]> {\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query(\n 'SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname'\n );\n return result.rows.map((row: any) => row.datname);\n }\n\n async existsDatabase(name: string): Promise<boolean> {\n if (!this.isConnected()) {\n await this.connect();\n }\n const result = await this.connection!.query('SELECT 1 FROM pg_database WHERE datname = $1', [\n name,\n ]);\n return result.rows.length > 0;\n }\n}\n"],"mappings":";;AAAA,SAA4B,cAAc,qBAAqB;AAC/D,SAAS,cAAsC;AAC/C,SAAS,YAAY;AAErB,SAAS,aAAa;AACtB,SAAS,8BAA8B;AACvC,SAAS,cAAc;AACvB,SAAS,+BAA+B;AACxC,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAEtB,MAAM,6BAA6B,cAAc;AAAA,EAXxD,OAWwD;AAAA;AAAA;AAAA,EAC9C,eAAe,IAAI,aAAa;AAAA,EAExC,GAAG,OAA0B,UAA0C;AACrE,SAAK,aAAa,GAAG,OAAO,QAAQ;AACpC,WAAO;AAAA,EACT;AAAA,EACA,IAAI,OAA0B,UAA0C;AACtE,SAAK,aAAa,IAAI,OAAO,QAAQ;AACrC,WAAO;AAAA,EACT;AAAA,EACA,KAAK,UAA6B,MAA+B;AAC/D,WAAO,KAAK,aAAa,KAAK,OAAO,GAAG,IAAI;AAAA,EAC9C;AAAA,EAEA;AAAA,EACA,OAAO;AAAA,EAEP,OAAO,WAAuB;AAAA,IAC5B,MAAM;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AAAA,IACL,mBAAmB;AAAA;AAAA,IACnB,yBAAyB;AAAA;AAAA,IACzB,SAAS;AAAA,EACX;AAAA,EAEA,YAAY,QAAoB;AAC9B,UAAM;AACN,QAAI,CAAC,qBAAqB,MAAM;AAC9B,2BAAqB,OAAO,IAAI,KAAK,EAAE,GAAG,qBAAqB,UAAU,GAAG,OAAO,CAAC;AAAA,IACtF;AAAA,EACF;AAAA,EACA,MAAM,UAA4B;AAChC,SAAK,aAAa,KAAK,SAAS,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAChD,SAAK,aAAa,MAAM,qBAAqB,KAAK,QAAQ;AAC1D,WAAO;AAAA,EACT;AAAA,EACA,MAAM,SAAS,KAAyC;AACtD,QAAI,OAAO,QAAQ,UAAU;AA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D,UAAM,KAAK,MAAM,mBAAmB,QAAQ,EAAE;AAC9C,UAAM,KAAK,IAAI;AAAA,EACjB;AAAA,EAEA,MAAM,aAAa,MAA6B;AAC9C,QAAI,KAAK,YAAY,GAAG;AACtB,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAEA,UAAM,OAAO,IAAI,OAAO;AAAA,MACtB,GAAG,qBAAqB,KAAK;AAAA,MAC7B,UAAU;AAAA;AAAA,IACZ,CAAC;AACD,UAAM,KAAK,QAAQ;AACnB,UAAM,WAAW,KAAK,4BAA4B,IAAI;AACtD,UAAM,KAAK,MAAM,iBAAiB,QAAQ,EAAE;AAC5C,UAAM,KAAK,IAAI;AAAA,EACjB;AAAA,EAEA,MAAM,gBAAmC;AACvC,QAAI,CAAC,KAAK,YAAY,GAAG;AACvB,YAAM,KAAK,QAAQ;AAAA,IACrB;AACA,UAAM,SAAS,MAAM,KAAK,WAAY;AAAA,MACpC;AAAA,IACF;AACA,WAAO,OAAO,KAAK,IAAI,CAAC,QAAa,IAAI,OAAO;AAAA,EAClD;AAAA,EAEA,MAAM,eAAe,MAAgC;AACnD,QAAI,CAAC,KAAK,YAAY,GAAG;AACvB,YAAM,KAAK,QAAQ;AAAA,IACrB;AACA,UAAM,SAAS,MAAM,KAAK,WAAY,MAAM,gDAAgD;AAAA,MAC1F;AAAA,IACF,CAAC;AACD,WAAO,OAAO,KAAK,SAAS;AAAA,EAC9B;AACF;","names":[]}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { b as Connection, c as connection_events, m as CompiledSql, d as Query, S as Schema } from '../../Blueprint-D3WHeqRS.mjs';
|
|
2
|
+
import Database from 'better-sqlite3';
|
|
3
|
+
import { SqliteQueryGrammar } from './SqliteQueryGrammar.mjs';
|
|
4
|
+
import { SqliteSchemaGrammar } from './SqliteSchemaGrammar.mjs';
|
|
5
|
+
import '@devbro/neko-helper';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration options for SQLite database connection
|
|
9
|
+
*/
|
|
10
|
+
interface SqliteConfig {
|
|
11
|
+
/** Path to the SQLite database file */
|
|
12
|
+
filename: string;
|
|
13
|
+
/** Open the database in read-only mode (default: false) */
|
|
14
|
+
readonly?: boolean;
|
|
15
|
+
/** Throw an error if the database file doesn't exist (default: false) */
|
|
16
|
+
fileMustExist?: boolean;
|
|
17
|
+
/** Timeout in milliseconds for database operations (default: 5000) */
|
|
18
|
+
timeout?: number;
|
|
19
|
+
/** Optional verbose logging function for debugging SQL statements */
|
|
20
|
+
verbose?: (message?: unknown, ...additionalArgs: unknown[]) => void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* SQLite database connection implementation
|
|
24
|
+
*
|
|
25
|
+
* Provides a connection to SQLite databases using better-sqlite3.
|
|
26
|
+
* Supports transactions, queries, schema operations, and database management.
|
|
27
|
+
*/
|
|
28
|
+
declare class SqliteConnection extends Connection {
|
|
29
|
+
private eventManager;
|
|
30
|
+
on(event: connection_events, listener: (...args: any[]) => void): this;
|
|
31
|
+
off(event: connection_events, listener: (...args: any[]) => void): this;
|
|
32
|
+
emit(event: connection_events, ...args: any[]): Promise<boolean>;
|
|
33
|
+
connection: Database.Database | undefined;
|
|
34
|
+
private config;
|
|
35
|
+
/** Default configuration values for SQLite connections */
|
|
36
|
+
static defaults: Partial<SqliteConfig>;
|
|
37
|
+
constructor(params: SqliteConfig);
|
|
38
|
+
/**
|
|
39
|
+
* Establishes a connection to the SQLite database
|
|
40
|
+
* Creates or opens the database file specified in the configuration
|
|
41
|
+
*/
|
|
42
|
+
connect(): Promise<boolean>;
|
|
43
|
+
/**
|
|
44
|
+
* Executes a SQL query against the database
|
|
45
|
+
* Automatically detects SELECT queries and queries with RETURNING clauses
|
|
46
|
+
*
|
|
47
|
+
* @param sql - Compiled SQL or raw SQL string to execute
|
|
48
|
+
* @returns Query results (rows for SELECT, run info for INSERT/UPDATE/DELETE)
|
|
49
|
+
*/
|
|
50
|
+
runQuery(sql: CompiledSql | string): Promise<any>;
|
|
51
|
+
/**
|
|
52
|
+
* Executes a query and returns an iterator for streaming results
|
|
53
|
+
* Useful for large result sets to avoid loading all rows into memory
|
|
54
|
+
*
|
|
55
|
+
* @param sql - Compiled SQL to execute
|
|
56
|
+
* @returns Iterator over query results
|
|
57
|
+
*/
|
|
58
|
+
runCursor(sql: CompiledSql): Promise<any>;
|
|
59
|
+
/**
|
|
60
|
+
* Closes the database connection
|
|
61
|
+
*/
|
|
62
|
+
disconnect(): Promise<boolean>;
|
|
63
|
+
/**
|
|
64
|
+
* Creates a new query builder instance for this connection
|
|
65
|
+
*/
|
|
66
|
+
getQuery(): Query;
|
|
67
|
+
/**
|
|
68
|
+
* Creates a new schema builder instance for this connection
|
|
69
|
+
*/
|
|
70
|
+
getSchema(): Schema;
|
|
71
|
+
/**
|
|
72
|
+
* Gets the query grammar for building SQL statements
|
|
73
|
+
*/
|
|
74
|
+
getQueryGrammar(): SqliteQueryGrammar;
|
|
75
|
+
/**
|
|
76
|
+
* Gets the schema grammar for building DDL statements
|
|
77
|
+
*/
|
|
78
|
+
getSchemaGrammar(): SqliteSchemaGrammar;
|
|
79
|
+
/**
|
|
80
|
+
* Starts a new database transaction
|
|
81
|
+
*/
|
|
82
|
+
beginTransaction(): Promise<void>;
|
|
83
|
+
/**
|
|
84
|
+
* Commits the current transaction
|
|
85
|
+
*/
|
|
86
|
+
commit(): Promise<void>;
|
|
87
|
+
/**
|
|
88
|
+
* Rolls back the current transaction
|
|
89
|
+
*/
|
|
90
|
+
rollback(): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Checks if the database connection is active
|
|
93
|
+
*/
|
|
94
|
+
isConnected(): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Validates and escapes a SQLite identifier (database name, table name, etc.)
|
|
97
|
+
* Uses a whitelist approach to ensure only safe characters are allowed
|
|
98
|
+
*
|
|
99
|
+
* @param name - The identifier to validate and escape
|
|
100
|
+
* @returns The escaped identifier, quoted if it's a reserved keyword
|
|
101
|
+
* @throws Error if the identifier contains invalid characters
|
|
102
|
+
*/
|
|
103
|
+
private validateAndEscapeIdentifier;
|
|
104
|
+
/**
|
|
105
|
+
* Creates a new SQLite database file
|
|
106
|
+
*
|
|
107
|
+
* @param name - Name or path of the database file to create
|
|
108
|
+
*/
|
|
109
|
+
createDatabase(name: string): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Deletes a SQLite database file
|
|
112
|
+
*
|
|
113
|
+
* @param name - Name or path of the database file to delete
|
|
114
|
+
*/
|
|
115
|
+
dropDatabase(name: string): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Lists available databases
|
|
118
|
+
* For SQLite, this returns the current database filename
|
|
119
|
+
*
|
|
120
|
+
* @returns Array containing the current database filename
|
|
121
|
+
*/
|
|
122
|
+
listDatabases(): Promise<string[]>;
|
|
123
|
+
/**
|
|
124
|
+
* Checks if a database file exists
|
|
125
|
+
*
|
|
126
|
+
* @param name - Name or path of the database file to check
|
|
127
|
+
* @returns True if the database file exists, false otherwise
|
|
128
|
+
*/
|
|
129
|
+
existsDatabase(name: string): Promise<boolean>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export { type SqliteConfig, SqliteConnection };
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
import { Connection as ConnectionAbs } from "../../Connection.mjs";
|
|
4
|
+
import Database from "better-sqlite3";
|
|
5
|
+
import { Query } from "../../Query.mjs";
|
|
6
|
+
import { SqliteQueryGrammar } from "./SqliteQueryGrammar.mjs";
|
|
7
|
+
import { Schema } from "../../Schema.mjs";
|
|
8
|
+
import { SqliteSchemaGrammar } from "./SqliteSchemaGrammar.mjs";
|
|
9
|
+
import { EventManager } from "@devbro/neko-helper";
|
|
10
|
+
import * as fs from "fs";
|
|
11
|
+
class SqliteConnection extends ConnectionAbs {
|
|
12
|
+
static {
|
|
13
|
+
__name(this, "SqliteConnection");
|
|
14
|
+
}
|
|
15
|
+
eventManager = new EventManager();
|
|
16
|
+
on(event, listener) {
|
|
17
|
+
this.eventManager.on(event, listener);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
off(event, listener) {
|
|
21
|
+
this.eventManager.off(event, listener);
|
|
22
|
+
return this;
|
|
23
|
+
}
|
|
24
|
+
emit(event, ...args) {
|
|
25
|
+
return this.eventManager.emit(event, ...args);
|
|
26
|
+
}
|
|
27
|
+
connection;
|
|
28
|
+
config;
|
|
29
|
+
/** Default configuration values for SQLite connections */
|
|
30
|
+
static defaults = {
|
|
31
|
+
readonly: false,
|
|
32
|
+
fileMustExist: false,
|
|
33
|
+
timeout: 5e3
|
|
34
|
+
};
|
|
35
|
+
constructor(params) {
|
|
36
|
+
super();
|
|
37
|
+
this.config = { ...SqliteConnection.defaults, ...params };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Establishes a connection to the SQLite database
|
|
41
|
+
* Creates or opens the database file specified in the configuration
|
|
42
|
+
*/
|
|
43
|
+
async connect() {
|
|
44
|
+
this.eventManager.emit("connect").catch(() => {
|
|
45
|
+
});
|
|
46
|
+
this.connection = new Database(this.config.filename, {
|
|
47
|
+
readonly: this.config.readonly,
|
|
48
|
+
fileMustExist: this.config.fileMustExist,
|
|
49
|
+
timeout: this.config.timeout,
|
|
50
|
+
verbose: this.config.verbose
|
|
51
|
+
});
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Executes a SQL query against the database
|
|
56
|
+
* Automatically detects SELECT queries and queries with RETURNING clauses
|
|
57
|
+
*
|
|
58
|
+
* @param sql - Compiled SQL or raw SQL string to execute
|
|
59
|
+
* @returns Query results (rows for SELECT, run info for INSERT/UPDATE/DELETE)
|
|
60
|
+
*/
|
|
61
|
+
async runQuery(sql) {
|
|
62
|
+
if (typeof sql === "string") {
|
|
63
|
+
sql = { sql, bindings: [], parts: [sql] };
|
|
64
|
+
}
|
|
65
|
+
this.eventManager.emit("query", { sql: sql.sql, bindings: sql.bindings }).catch(() => {
|
|
66
|
+
});
|
|
67
|
+
if (!this.isConnected()) {
|
|
68
|
+
await this.connect();
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const stmt = this.connection.prepare(sql.sql);
|
|
72
|
+
const sqlUpper = sql.sql.trim().toUpperCase();
|
|
73
|
+
if (sqlUpper.startsWith("SELECT") || sqlUpper.includes("RETURNING")) {
|
|
74
|
+
return stmt.all(...sql.bindings);
|
|
75
|
+
} else {
|
|
76
|
+
const result = stmt.run(...sql.bindings);
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
} catch (error) {
|
|
80
|
+
this.eventManager.emit("error", error).catch(() => {
|
|
81
|
+
});
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Executes a query and returns an iterator for streaming results
|
|
87
|
+
* Useful for large result sets to avoid loading all rows into memory
|
|
88
|
+
*
|
|
89
|
+
* @param sql - Compiled SQL to execute
|
|
90
|
+
* @returns Iterator over query results
|
|
91
|
+
*/
|
|
92
|
+
async runCursor(sql) {
|
|
93
|
+
if (!this.isConnected()) {
|
|
94
|
+
await this.connect();
|
|
95
|
+
}
|
|
96
|
+
const stmt = this.connection.prepare(sql.sql);
|
|
97
|
+
return stmt.iterate(...sql.bindings);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Closes the database connection
|
|
101
|
+
*/
|
|
102
|
+
async disconnect() {
|
|
103
|
+
if (this.connection === void 0) {
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
this.connection.close();
|
|
107
|
+
this.connection = void 0;
|
|
108
|
+
this.eventManager.emit("disconnect").catch(() => {
|
|
109
|
+
});
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates a new query builder instance for this connection
|
|
114
|
+
*/
|
|
115
|
+
getQuery() {
|
|
116
|
+
return new Query(this, new SqliteQueryGrammar());
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Creates a new schema builder instance for this connection
|
|
120
|
+
*/
|
|
121
|
+
getSchema() {
|
|
122
|
+
return new Schema(this, new SqliteSchemaGrammar());
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Gets the query grammar for building SQL statements
|
|
126
|
+
*/
|
|
127
|
+
getQueryGrammar() {
|
|
128
|
+
return new SqliteQueryGrammar();
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Gets the schema grammar for building DDL statements
|
|
132
|
+
*/
|
|
133
|
+
getSchemaGrammar() {
|
|
134
|
+
return new SqliteSchemaGrammar();
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Starts a new database transaction
|
|
138
|
+
*/
|
|
139
|
+
async beginTransaction() {
|
|
140
|
+
await this.runQuery({
|
|
141
|
+
sql: "BEGIN TRANSACTION",
|
|
142
|
+
bindings: [],
|
|
143
|
+
parts: ["BEGIN", "TRANSACTION"]
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Commits the current transaction
|
|
148
|
+
*/
|
|
149
|
+
async commit() {
|
|
150
|
+
await this.runQuery({ sql: "COMMIT", bindings: [], parts: ["COMMIT"] });
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Rolls back the current transaction
|
|
154
|
+
*/
|
|
155
|
+
async rollback() {
|
|
156
|
+
await this.runQuery({ sql: "ROLLBACK", bindings: [], parts: ["ROLLBACK"] });
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Checks if the database connection is active
|
|
160
|
+
*/
|
|
161
|
+
isConnected() {
|
|
162
|
+
return this.connection !== void 0 && this.connection.open;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Validates and escapes a SQLite identifier (database name, table name, etc.)
|
|
166
|
+
* Uses a whitelist approach to ensure only safe characters are allowed
|
|
167
|
+
*
|
|
168
|
+
* @param name - The identifier to validate and escape
|
|
169
|
+
* @returns The escaped identifier, quoted if it's a reserved keyword
|
|
170
|
+
* @throws Error if the identifier contains invalid characters
|
|
171
|
+
*/
|
|
172
|
+
validateAndEscapeIdentifier(name) {
|
|
173
|
+
const validIdentifierPattern = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
174
|
+
if (!validIdentifierPattern.test(name)) {
|
|
175
|
+
throw new Error(
|
|
176
|
+
`Invalid identifier: "${name}". Identifiers must start with a letter or underscore and contain only letters, digits, and underscores.`
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
const reservedKeywords = /* @__PURE__ */ new Set([
|
|
180
|
+
"table",
|
|
181
|
+
"database",
|
|
182
|
+
"order",
|
|
183
|
+
"group",
|
|
184
|
+
"select",
|
|
185
|
+
"insert",
|
|
186
|
+
"update",
|
|
187
|
+
"delete",
|
|
188
|
+
"index",
|
|
189
|
+
"from",
|
|
190
|
+
"where"
|
|
191
|
+
]);
|
|
192
|
+
if (reservedKeywords.has(name.toLowerCase())) {
|
|
193
|
+
const escapedName = name.replace(/"/g, '""');
|
|
194
|
+
return `"${escapedName}"`;
|
|
195
|
+
}
|
|
196
|
+
return name;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Creates a new SQLite database file
|
|
200
|
+
*
|
|
201
|
+
* @param name - Name or path of the database file to create
|
|
202
|
+
*/
|
|
203
|
+
async createDatabase(name) {
|
|
204
|
+
const dbPath = name.endsWith(".db") ? name : `${name}.db`;
|
|
205
|
+
const tempDb = new Database(dbPath);
|
|
206
|
+
tempDb.close();
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Deletes a SQLite database file
|
|
210
|
+
*
|
|
211
|
+
* @param name - Name or path of the database file to delete
|
|
212
|
+
*/
|
|
213
|
+
async dropDatabase(name) {
|
|
214
|
+
const dbPath = name.endsWith(".db") ? name : `${name}.db`;
|
|
215
|
+
if (fs.existsSync(dbPath)) {
|
|
216
|
+
fs.unlinkSync(dbPath);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Lists available databases
|
|
221
|
+
* For SQLite, this returns the current database filename
|
|
222
|
+
*
|
|
223
|
+
* @returns Array containing the current database filename
|
|
224
|
+
*/
|
|
225
|
+
async listDatabases() {
|
|
226
|
+
return [this.config.filename];
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Checks if a database file exists
|
|
230
|
+
*
|
|
231
|
+
* @param name - Name or path of the database file to check
|
|
232
|
+
* @returns True if the database file exists, false otherwise
|
|
233
|
+
*/
|
|
234
|
+
async existsDatabase(name) {
|
|
235
|
+
const dbPath = name.endsWith(".db") ? name : `${name}.db`;
|
|
236
|
+
return fs.existsSync(dbPath);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
export {
|
|
240
|
+
SqliteConnection
|
|
241
|
+
};
|
|
242
|
+
//# sourceMappingURL=SqliteConnection.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/databases/sqlite/SqliteConnection.mts"],"sourcesContent":["import { connection_events, Connection as ConnectionAbs } from '../../Connection.mjs';\nimport Database from 'better-sqlite3';\nimport { CompiledSql } from '../../types.mjs';\nimport { Query } from '../../Query.mjs';\nimport { SqliteQueryGrammar } from './SqliteQueryGrammar.mjs';\nimport { Schema } from '../../Schema.mjs';\nimport { SqliteSchemaGrammar } from './SqliteSchemaGrammar.mjs';\nimport { EventManager } from '@devbro/neko-helper';\nimport * as fs from 'fs';\n\n/**\n * Configuration options for SQLite database connection\n */\nexport interface SqliteConfig {\n /** Path to the SQLite database file */\n filename: string;\n /** Open the database in read-only mode (default: false) */\n readonly?: boolean;\n /** Throw an error if the database file doesn't exist (default: false) */\n fileMustExist?: boolean;\n /** Timeout in milliseconds for database operations (default: 5000) */\n timeout?: number;\n /** Optional verbose logging function for debugging SQL statements */\n verbose?: (message?: unknown, ...additionalArgs: unknown[]) => void;\n}\n\n/**\n * SQLite database connection implementation\n *\n * Provides a connection to SQLite databases using better-sqlite3.\n * Supports transactions, queries, schema operations, and database management.\n */\nexport class SqliteConnection extends ConnectionAbs {\n private eventManager = new EventManager();\n\n on(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.on(event, listener);\n return this;\n }\n off(event: connection_events, listener: (...args: any[]) => void): this {\n this.eventManager.off(event, listener);\n return this;\n }\n emit(event: connection_events, ...args: any[]): Promise<boolean> {\n return this.eventManager.emit(event, ...args);\n }\n\n connection: Database.Database | undefined;\n private config: SqliteConfig;\n\n /** Default configuration values for SQLite connections */\n static defaults: Partial<SqliteConfig> = {\n readonly: false,\n fileMustExist: false,\n timeout: 5000,\n };\n\n constructor(params: SqliteConfig) {\n super();\n this.config = { ...SqliteConnection.defaults, ...params } as SqliteConfig;\n }\n\n /**\n * Establishes a connection to the SQLite database\n * Creates or opens the database file specified in the configuration\n */\n async connect(): Promise<boolean> {\n this.eventManager.emit('connect').catch(() => {});\n this.connection = new Database(this.config.filename, {\n readonly: this.config.readonly,\n fileMustExist: this.config.fileMustExist,\n timeout: this.config.timeout,\n verbose: this.config.verbose,\n });\n return true;\n }\n\n /**\n * Executes a SQL query against the database\n * Automatically detects SELECT queries and queries with RETURNING clauses\n *\n * @param sql - Compiled SQL or raw SQL string to execute\n * @returns Query results (rows for SELECT, run info for INSERT/UPDATE/DELETE)\n */\n async runQuery(sql: CompiledSql | string): Promise<any> {\n if (typeof sql === 'string') {\n sql = { sql: sql, bindings: [], parts: [sql] };\n }\n\n this.eventManager.emit('query', { sql: sql.sql, bindings: sql.bindings }).catch(() => {});\n\n if (!this.isConnected()) {\n await this.connect();\n }\n\n try {\n const stmt = this.connection!.prepare(sql.sql);\n\n // Check if the query is a SELECT or contains RETURNING clause\n const sqlUpper = sql.sql.trim().toUpperCase();\n if (sqlUpper.startsWith('SELECT') || sqlUpper.includes('RETURNING')) {\n return stmt.all(...sql.bindings);\n } else {\n const result = stmt.run(...sql.bindings);\n return result;\n }\n } catch (error) {\n this.eventManager.emit('error', error).catch(() => {});\n throw error;\n }\n }\n\n /**\n * Executes a query and returns an iterator for streaming results\n * Useful for large result sets to avoid loading all rows into memory\n *\n * @param sql - Compiled SQL to execute\n * @returns Iterator over query results\n */\n async runCursor(sql: CompiledSql): Promise<any> {\n // SQLite doesn't have native cursor support, return iterator\n if (!this.isConnected()) {\n await this.connect();\n }\n const stmt = this.connection!.prepare(sql.sql);\n return stmt.iterate(...sql.bindings);\n }\n\n /**\n * Closes the database connection\n */\n async disconnect(): Promise<boolean> {\n if (this.connection === undefined) {\n return true;\n }\n this.connection.close();\n this.connection = undefined;\n this.eventManager.emit('disconnect').catch(() => {});\n return true;\n }\n\n /**\n * Creates a new query builder instance for this connection\n */\n getQuery(): Query {\n return new Query(this, new SqliteQueryGrammar());\n }\n\n /**\n * Creates a new schema builder instance for this connection\n */\n getSchema(): Schema {\n return new Schema(this, new SqliteSchemaGrammar());\n }\n\n /**\n * Gets the query grammar for building SQL statements\n */\n getQueryGrammar(): SqliteQueryGrammar {\n return new SqliteQueryGrammar();\n }\n\n /**\n * Gets the schema grammar for building DDL statements\n */\n getSchemaGrammar(): SqliteSchemaGrammar {\n return new SqliteSchemaGrammar();\n }\n\n /**\n * Starts a new database transaction\n */\n async beginTransaction(): Promise<void> {\n await this.runQuery({\n sql: 'BEGIN TRANSACTION',\n bindings: [],\n parts: ['BEGIN', 'TRANSACTION'],\n });\n }\n\n /**\n * Commits the current transaction\n */\n async commit(): Promise<void> {\n await this.runQuery({ sql: 'COMMIT', bindings: [], parts: ['COMMIT'] });\n }\n\n /**\n * Rolls back the current transaction\n */\n async rollback(): Promise<void> {\n await this.runQuery({ sql: 'ROLLBACK', bindings: [], parts: ['ROLLBACK'] });\n }\n\n /**\n * Checks if the database connection is active\n */\n isConnected(): boolean {\n return this.connection !== undefined && this.connection.open;\n }\n\n /**\n * Validates and escapes a SQLite identifier (database name, table name, etc.)\n * Uses a whitelist approach to ensure only safe characters are allowed\n *\n * @param name - The identifier to validate and escape\n * @returns The escaped identifier, quoted if it's a reserved keyword\n * @throws Error if the identifier contains invalid characters\n */\n private validateAndEscapeIdentifier(name: string): string {\n // SQLite identifiers can contain: letters, digits, underscores\n // They must start with a letter or underscore\n const validIdentifierPattern = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n if (!validIdentifierPattern.test(name)) {\n throw new Error(\n `Invalid identifier: \"${name}\". Identifiers must start with a letter or underscore and contain only letters, digits, and underscores.`\n );\n }\n\n // SQLite reserved keywords that should be quoted\n const reservedKeywords = new Set([\n 'table',\n 'database',\n 'order',\n 'group',\n 'select',\n 'insert',\n 'update',\n 'delete',\n 'index',\n 'from',\n 'where',\n ]);\n\n // Quote the identifier if it's a reserved keyword\n if (reservedKeywords.has(name.toLowerCase())) {\n // Escape any double quotes in the name\n const escapedName = name.replace(/\"/g, '\"\"');\n return `\"${escapedName}\"`;\n }\n\n return name;\n }\n\n /**\n * Creates a new SQLite database file\n *\n * @param name - Name or path of the database file to create\n */\n async createDatabase(name: string): Promise<void> {\n // SQLite databases are files, creating a database means creating a new connection\n const dbPath = name.endsWith('.db') ? name : `${name}.db`;\n const tempDb = new Database(dbPath);\n tempDb.close();\n }\n\n /**\n * Deletes a SQLite database file\n *\n * @param name - Name or path of the database file to delete\n */\n async dropDatabase(name: string): Promise<void> {\n // SQLite databases are files, dropping means deleting the file\n const dbPath = name.endsWith('.db') ? name : `${name}.db`;\n if (fs.existsSync(dbPath)) {\n fs.unlinkSync(dbPath);\n }\n }\n\n /**\n * Lists available databases\n * For SQLite, this returns the current database filename\n *\n * @returns Array containing the current database filename\n */\n async listDatabases(): Promise<string[]> {\n // SQLite doesn't have a concept of multiple databases in the same connection\n // This would require listing files in a directory\n return [this.config.filename];\n }\n\n /**\n * Checks if a database file exists\n *\n * @param name - Name or path of the database file to check\n * @returns True if the database file exists, false otherwise\n */\n async existsDatabase(name: string): Promise<boolean> {\n const dbPath = name.endsWith('.db') ? name :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ACA;AAAA,IACF,CAAC;AAGD,QAAI,iBAAiB,IAAI,KAAK,YAAY,CAAC,GAAG;AAE5C,YAAM,cAAc,KAAK,QAAQ,MAAM,IAAI;AAC3C,aAAO,IAAI,WAAW;AAAA,IACxB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,eAAe,MAA6B;AAEhD,UAAM,SAAS,KAAK,SAAS,KAAK,IAAI,OAAO,GAAG,IAAI;AACpD,UAAM,SAAS,IAAI,SAAS,MAAM;AAClC,WAAO,MAAM;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,aAAa,MAA6B;AAE9C,UAAM,SAAS,KAAK,SAAS,KAAK,IAAI,OAAO,GAAG,IAAI;AACpD,QAAI,GAAG,WAAW,MAAM,GAAG;AACzB,SAAG,WAAW,MAAM;AAAA,IACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,gBAAmC;AAGvC,WAAO,CAAC,KAAK,OAAO,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,eAAe,MAAgC;AACnD,UAAM,SAAS,KAAK,SAAS,KAAK,IAAI,OAAO,GAAG,IAAI;AACpD,WAAO,GAAG,WAAW,MAAM;AAAA,EAC7B;AACF;","names":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { e as QueryGrammar, d as Query, m as CompiledSql, P as Parameter } from '../../Blueprint-D3WHeqRS.mjs';
|
|
2
|
+
import '@devbro/neko-helper';
|
|
3
|
+
|
|
4
|
+
declare class SqliteQueryGrammar extends QueryGrammar {
|
|
5
|
+
constructor();
|
|
6
|
+
toSql(query: Query): CompiledSql;
|
|
7
|
+
compileInsert(query: Query, data: Record<string, any>): CompiledSql;
|
|
8
|
+
compileInsertGetId(query: Query, data: Record<string, any>, options?: {
|
|
9
|
+
primaryKey: string[];
|
|
10
|
+
}): CompiledSql;
|
|
11
|
+
compileUpdate(query: Query, data: Record<string, any>): CompiledSql;
|
|
12
|
+
compileDelete(query: Query): CompiledSql;
|
|
13
|
+
compileUpsert(query: Query, data: Record<string, Parameter>, conflictFields: string[], updateFields: string[]): CompiledSql;
|
|
14
|
+
compileCount(query: Query): CompiledSql;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export { SqliteQueryGrammar };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
import { QueryGrammar } from "../../QueryGrammar.mjs";
|
|
4
|
+
import { Arr } from "@devbro/neko-helper";
|
|
5
|
+
class SqliteQueryGrammar extends QueryGrammar {
|
|
6
|
+
static {
|
|
7
|
+
__name(this, "SqliteQueryGrammar");
|
|
8
|
+
}
|
|
9
|
+
constructor() {
|
|
10
|
+
super();
|
|
11
|
+
}
|
|
12
|
+
toSql(query) {
|
|
13
|
+
return super.toSql(query);
|
|
14
|
+
}
|
|
15
|
+
compileInsert(query, data) {
|
|
16
|
+
return super.compileInsert(query, data);
|
|
17
|
+
}
|
|
18
|
+
compileInsertGetId(query, data, options = { primaryKey: ["id"] }) {
|
|
19
|
+
const rc = super.compileInsert(query, data);
|
|
20
|
+
rc.sql += ` RETURNING ${options.primaryKey.join(", ")}`;
|
|
21
|
+
rc.parts = rc.parts.concat(["RETURNING", ...Arr.intersperse(options.primaryKey, ",")]);
|
|
22
|
+
return rc;
|
|
23
|
+
}
|
|
24
|
+
compileUpdate(query, data) {
|
|
25
|
+
return super.compileUpdate(query, data);
|
|
26
|
+
}
|
|
27
|
+
compileDelete(query) {
|
|
28
|
+
return super.compileDelete(query);
|
|
29
|
+
}
|
|
30
|
+
compileUpsert(query, data, conflictFields, updateFields) {
|
|
31
|
+
return super.compileUpsert(query, data, conflictFields, updateFields);
|
|
32
|
+
}
|
|
33
|
+
compileCount(query) {
|
|
34
|
+
return super.compileCount(query);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
SqliteQueryGrammar
|
|
39
|
+
};
|
|
40
|
+
//# sourceMappingURL=SqliteQueryGrammar.mjs.map
|