@travetto/model-sqlite 8.0.0-alpha.9 → 8.0.1
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 +24 -42
- package/__index__.ts +3 -2
- package/package.json +18 -23
- package/src/config.ts +30 -0
- package/src/connection.ts +136 -69
- package/src/dialect.ts +219 -110
- package/src/service.ts +28 -0
package/README.md
CHANGED
|
@@ -13,78 +13,60 @@ npm install @travetto/model-sqlite
|
|
|
13
13
|
yarn add @travetto/model-sqlite
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
This module provides a [SQLite](https://www.sqlite.org/)-based implementation for the [Data Modeling Support](https://github.com/travetto/travetto/tree/main/module/model#readme "Datastore abstraction for core operations.") module.
|
|
16
|
+
This module provides a [SQLite](https://www.sqlite.org/)-based implementation for the [Data Modeling Support](https://github.com/travetto/travetto/tree/main/module/model#readme "Datastore abstraction for core operations.") module. This source allows the [Data Modeling Support](https://github.com/travetto/travetto/tree/main/module/model#readme "Datastore abstraction for core operations.") module to read, write and query against [SQL](https://en.wikipedia.org/wiki/SQL) databases. In development mode, the [SqliteModelService](https://github.com/travetto/travetto/tree/main/module/model-sqlite/src/service.ts#L12) will also modify the database schema in real time to minimize impact to development.
|
|
17
17
|
|
|
18
|
-
The schema generated will not generally map to existing tables as it is attempting to produce a document store like experience on top of a [SQL](https://en.wikipedia.org/wiki/SQL) database.
|
|
18
|
+
The schema generated will not generally map to existing tables as it is attempting to produce a document store like experience on top of a [SQL](https://en.wikipedia.org/wiki/SQL) database. Every table generated maps to a model, with simple fields mapped as individual columns and complex fields/arrays mapped as serialized `TEXT` columns.
|
|
19
19
|
|
|
20
20
|
Supported features:
|
|
21
|
-
* [
|
|
22
|
-
* [
|
|
21
|
+
* [Bulk](https://github.com/travetto/travetto/tree/main/module/model/src/types/bulk.ts#L60)
|
|
22
|
+
* [CRUD](https://github.com/travetto/travetto/tree/main/module/model/src/types/crud.ts#L10)
|
|
23
|
+
* [Expiry](https://github.com/travetto/travetto/tree/main/module/model/src/types/expiry.ts#L10)
|
|
24
|
+
* [Indexed](https://github.com/travetto/travetto/tree/main/module/model-indexed/src/types/service.ts#L21)
|
|
23
25
|
* [Query Crud](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/crud.ts#L11)
|
|
24
26
|
* [Facet](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/facet.ts#L14)
|
|
25
|
-
* [Query](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/query.ts#L10)
|
|
26
27
|
* [Suggest](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/suggest.ts#L12)
|
|
28
|
+
* [Query](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/query.ts#L10)
|
|
27
29
|
|
|
28
30
|
Out of the box, by installing the module, everything should be wired up by default.If you need to customize any aspect of the source or config, you can override and register it with the [Dependency Injection](https://github.com/travetto/travetto/tree/main/module/di#readme "Dependency registration/management and injection support.") module.
|
|
29
31
|
|
|
30
32
|
**Code: Wiring up a custom Model Source**
|
|
31
33
|
```typescript
|
|
32
|
-
import type { AsyncContext } from '@travetto/context';
|
|
33
34
|
import { InjectableFactory } from '@travetto/di';
|
|
34
|
-
|
|
35
|
-
import { SQLModelService, type SQLModelConfig } from '@travetto/model-sql';
|
|
36
|
-
import { SqliteDialect } from '@travetto/model-sqlite';
|
|
35
|
+
import { type SqliteConnection, SqliteModelService } from '@travetto/model-sqlite';
|
|
37
36
|
|
|
38
37
|
export class Init {
|
|
39
38
|
@InjectableFactory({ primary: true })
|
|
40
|
-
static getModelService(
|
|
41
|
-
return new
|
|
39
|
+
static getModelService(connection: SqliteConnection) {
|
|
40
|
+
return new SqliteModelService(connection);
|
|
42
41
|
}
|
|
43
42
|
}
|
|
44
43
|
```
|
|
45
44
|
|
|
46
|
-
where the [
|
|
45
|
+
where the [SqliteModelConfig](https://github.com/travetto/travetto/tree/main/module/model-sqlite/src/config.ts#L10) is defined by:
|
|
47
46
|
|
|
48
|
-
**Code: Structure of
|
|
47
|
+
**Code: Structure of SqliteModelConfig**
|
|
49
48
|
```typescript
|
|
50
|
-
@Config('model.
|
|
51
|
-
export class
|
|
52
|
-
/**
|
|
53
|
-
* Host to connect to
|
|
54
|
-
*/
|
|
55
|
-
host = '127.0.0.1';
|
|
56
|
-
/**
|
|
57
|
-
* Default port
|
|
58
|
-
*/
|
|
59
|
-
port = 0;
|
|
60
|
-
/**
|
|
61
|
-
* Username
|
|
62
|
-
*/
|
|
63
|
-
user = Runtime.production ? '' : 'travetto';
|
|
64
|
-
/**
|
|
65
|
-
* Password
|
|
66
|
-
*/
|
|
67
|
-
password = Runtime.production ? '' : 'travetto';
|
|
49
|
+
@Config('model.sqlite')
|
|
50
|
+
export class SqliteModelConfig {
|
|
68
51
|
/**
|
|
69
|
-
*
|
|
52
|
+
* Namespace/schema prefix for table names
|
|
70
53
|
*/
|
|
71
54
|
namespace = '';
|
|
55
|
+
|
|
72
56
|
/**
|
|
73
|
-
*
|
|
74
|
-
*/
|
|
75
|
-
database = 'app';
|
|
76
|
-
/**
|
|
77
|
-
* Allow storage modification at runtime
|
|
57
|
+
* Allow storage modifications (like table auto-creation and schema updates) at runtime
|
|
78
58
|
*/
|
|
79
|
-
modifyStorage
|
|
59
|
+
modifyStorage = !Runtime.production;
|
|
60
|
+
|
|
80
61
|
/**
|
|
81
|
-
*
|
|
62
|
+
* SQLite file location
|
|
82
63
|
*/
|
|
83
|
-
|
|
64
|
+
file?: string;
|
|
65
|
+
|
|
84
66
|
/**
|
|
85
|
-
*
|
|
67
|
+
* Custom options
|
|
86
68
|
*/
|
|
87
|
-
options
|
|
69
|
+
options?: DatabaseSyncOptions;
|
|
88
70
|
}
|
|
89
71
|
```
|
|
90
72
|
|
package/__index__.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export * from './src/
|
|
2
|
-
export * from './src/connection.ts';
|
|
1
|
+
export * from './src/config.ts';
|
|
2
|
+
export * from './src/connection.ts';
|
|
3
|
+
export * from './src/service.ts';
|
package/package.json
CHANGED
|
@@ -1,47 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@travetto/model-sqlite",
|
|
3
|
-
"version": "8.0.
|
|
4
|
-
"type": "module",
|
|
3
|
+
"version": "8.0.1",
|
|
5
4
|
"description": "SQLite backing for the travetto model module, with real-time modeling support for SQL schemas.",
|
|
6
5
|
"keywords": [
|
|
7
|
-
"sql",
|
|
8
6
|
"data-modeling",
|
|
9
|
-
"real-time",
|
|
10
7
|
"model",
|
|
8
|
+
"real-time",
|
|
9
|
+
"sql",
|
|
11
10
|
"travetto",
|
|
12
11
|
"typescript"
|
|
13
12
|
],
|
|
14
13
|
"homepage": "https://travetto.io",
|
|
15
14
|
"license": "MIT",
|
|
16
15
|
"author": {
|
|
17
|
-
"
|
|
18
|
-
"
|
|
16
|
+
"name": "Travetto Framework",
|
|
17
|
+
"email": "travetto.framework@gmail.com"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"url": "git+https://github.com/travetto/travetto.git",
|
|
21
|
+
"directory": "module/model-sqlite"
|
|
19
22
|
},
|
|
20
23
|
"files": [
|
|
21
24
|
"__index__.ts",
|
|
22
25
|
"src"
|
|
23
26
|
],
|
|
27
|
+
"type": "module",
|
|
24
28
|
"main": "__index__.ts",
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"directory": "module/model-sqlite"
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
28
31
|
},
|
|
29
32
|
"dependencies": {
|
|
30
|
-
"@travetto/config": "^8.0.
|
|
31
|
-
"@travetto/context": "^8.0.
|
|
32
|
-
"@travetto/model": "^8.0.
|
|
33
|
-
"@travetto/model-query": "^8.0.
|
|
34
|
-
"@travetto/model-sql": "^8.0.
|
|
33
|
+
"@travetto/config": "^8.0.1",
|
|
34
|
+
"@travetto/context": "^8.0.1",
|
|
35
|
+
"@travetto/model": "^8.0.1",
|
|
36
|
+
"@travetto/model-query": "^8.0.1",
|
|
37
|
+
"@travetto/model-sql": "^8.0.1"
|
|
35
38
|
},
|
|
36
39
|
"travetto": {
|
|
37
|
-
"displayName": "SQLite Model Service"
|
|
38
|
-
"build": {
|
|
39
|
-
"binaryDependencies": [
|
|
40
|
-
"better-sqlite3"
|
|
41
|
-
]
|
|
42
|
-
}
|
|
43
|
-
},
|
|
44
|
-
"publishConfig": {
|
|
45
|
-
"access": "public"
|
|
40
|
+
"displayName": "SQLite Model Service"
|
|
46
41
|
}
|
|
47
42
|
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { DatabaseSyncOptions } from 'node:sqlite';
|
|
2
|
+
|
|
3
|
+
import { Config } from '@travetto/config';
|
|
4
|
+
import { Runtime } from '@travetto/runtime';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* SQLite Model Configuration
|
|
8
|
+
*/
|
|
9
|
+
@Config('model.sqlite')
|
|
10
|
+
export class SqliteModelConfig {
|
|
11
|
+
/**
|
|
12
|
+
* Namespace/schema prefix for table names
|
|
13
|
+
*/
|
|
14
|
+
namespace = '';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Allow storage modifications (like table auto-creation and schema updates) at runtime
|
|
18
|
+
*/
|
|
19
|
+
modifyStorage = !Runtime.production;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* SQLite file location
|
|
23
|
+
*/
|
|
24
|
+
file?: string;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Custom options
|
|
28
|
+
*/
|
|
29
|
+
options?: DatabaseSyncOptions;
|
|
30
|
+
}
|
package/src/connection.ts
CHANGED
|
@@ -1,38 +1,51 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { DatabaseSync, type
|
|
3
|
+
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
|
|
4
4
|
|
|
5
|
-
import { type Pool
|
|
5
|
+
import { createPool, type Pool } from 'generic-pool';
|
|
6
6
|
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { ExistsError } from '@travetto/model';
|
|
10
|
-
import {
|
|
7
|
+
import type { AsyncContext } from '@travetto/context';
|
|
8
|
+
import { Injectable } from '@travetto/di';
|
|
9
|
+
import { ExistsError, UniqueError } from '@travetto/model';
|
|
10
|
+
import { SQLConnection } from '@travetto/model-sql';
|
|
11
|
+
import { castTo, JSONUtil, Runtime, RuntimeError, ShutdownManager, Util } from '@travetto/runtime';
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
import type { SqliteModelConfig } from './config.ts';
|
|
14
|
+
import { SqliteDialect } from './dialect.ts';
|
|
13
15
|
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
+
const RECOVERABLE_MESSAGE = /database( table| schema)? is (locked|busy)/;
|
|
17
|
+
const isRecoverableError = (error: unknown): error is Error => error instanceof Error && RECOVERABLE_MESSAGE.test(error.message);
|
|
18
|
+
|
|
19
|
+
const normalizeParameter = (val: unknown) => {
|
|
20
|
+
if (val === null) {
|
|
21
|
+
return val;
|
|
22
|
+
} else if (val instanceof Date) {
|
|
23
|
+
return val.toISOString();
|
|
24
|
+
} else if (typeof val === 'object') {
|
|
25
|
+
return JSONUtil.toUTF8(val);
|
|
26
|
+
} else {
|
|
27
|
+
return castTo<SQLInputValue>(val);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
16
30
|
|
|
17
31
|
/**
|
|
18
|
-
* Connection
|
|
32
|
+
* SQLite Connection Manager.
|
|
33
|
+
* Operates on node:sqlite DatabaseSync using a pool with max=1.
|
|
19
34
|
*/
|
|
20
|
-
|
|
21
|
-
|
|
35
|
+
@Injectable()
|
|
36
|
+
export class SqliteConnection extends SQLConnection<DatabaseSync> {
|
|
37
|
+
readonly dialect = new SqliteDialect();
|
|
22
38
|
isolatedTransactions = false;
|
|
23
39
|
|
|
24
|
-
#config: SQLModelConfig<DatabaseSyncOptions & { file?: string }>;
|
|
25
40
|
#pool: Pool<DatabaseSync>;
|
|
41
|
+
readonly config: SqliteModelConfig;
|
|
26
42
|
|
|
27
|
-
constructor(
|
|
28
|
-
context: AsyncContext,
|
|
29
|
-
config: SQLModelConfig<DatabaseSyncOptions & { file?: string }>
|
|
30
|
-
) {
|
|
43
|
+
constructor(context: AsyncContext, config: SqliteModelConfig) {
|
|
31
44
|
super(context);
|
|
32
|
-
this
|
|
45
|
+
this.config = config;
|
|
33
46
|
}
|
|
34
47
|
|
|
35
|
-
async #withRetries<T>(operation: () => Promise<T>, retries = 10, delay =
|
|
48
|
+
async #withRetries<T>(operation: () => Promise<T>, retries = 10, delay = 300): Promise<T> {
|
|
36
49
|
for (; retries > 1; retries -= 1) {
|
|
37
50
|
try {
|
|
38
51
|
return await operation();
|
|
@@ -48,91 +61,145 @@ export class SqliteConnection extends Connection<DatabaseSync> {
|
|
|
48
61
|
}
|
|
49
62
|
|
|
50
63
|
async #create(): Promise<DatabaseSync> {
|
|
51
|
-
const file = path.resolve(this
|
|
64
|
+
const file = path.resolve(this.config.file ?? Runtime.toolPath('@', 'sqlite_db'));
|
|
52
65
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
53
|
-
const db = new DatabaseSync(file, this
|
|
54
|
-
for (const q of [
|
|
55
|
-
'PRAGMA foreign_keys = ON',
|
|
56
|
-
'PRAGMA journal_mode = WAL',
|
|
57
|
-
'PRAGMA synchronous = NORMAL',
|
|
58
|
-
]) {
|
|
66
|
+
const db = new DatabaseSync(file, this.config.options ?? {});
|
|
67
|
+
for (const q of ['PRAGMA foreign_keys = ON', 'PRAGMA journal_mode = WAL', 'PRAGMA synchronous = NORMAL']) {
|
|
59
68
|
await this.#withRetries(async () => db.exec(q));
|
|
60
69
|
}
|
|
61
|
-
|
|
70
|
+
// Register custom regex function for SQL regex support
|
|
71
|
+
db.function('regexp', (pattern, value) => {
|
|
72
|
+
const patStr = String(pattern);
|
|
73
|
+
const valStr = String(value);
|
|
74
|
+
if (patStr.startsWith('(?i)')) {
|
|
75
|
+
return new RegExp(patStr.slice(4), 'i').test(valStr) ? 1 : 0;
|
|
76
|
+
}
|
|
77
|
+
return new RegExp(patStr).test(valStr) ? 1 : 0;
|
|
78
|
+
});
|
|
79
|
+
// Register custom json_contains function for JSON containment checks
|
|
80
|
+
db.function('json_contains', (target, candidate) => {
|
|
81
|
+
try {
|
|
82
|
+
const targetRaw = JSON.parse(String(target));
|
|
83
|
+
const candidateRaw = JSON.parse(String(candidate));
|
|
84
|
+
|
|
85
|
+
const matches = (t: unknown, c: unknown): boolean => {
|
|
86
|
+
if (c === null) {
|
|
87
|
+
return t === null;
|
|
88
|
+
}
|
|
89
|
+
if (typeof c === 'object') {
|
|
90
|
+
if (typeof t !== 'object' || t === null) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (Array.isArray(c)) {
|
|
94
|
+
if (!Array.isArray(t)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
return c.every(cv => t.some(tv => matches(tv, cv)));
|
|
98
|
+
} else {
|
|
99
|
+
// @ts-expect-error
|
|
100
|
+
return Object.keys(c).every(k => matches(t[k], c[k]));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return t === c;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return matches(targetRaw, candidateRaw) ? 1 : 0;
|
|
107
|
+
} catch {
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
62
111
|
return db;
|
|
63
112
|
}
|
|
64
113
|
|
|
65
114
|
/**
|
|
66
|
-
* Initializes
|
|
115
|
+
* Initializes the pool and sets connection pragma configuration
|
|
67
116
|
*/
|
|
68
|
-
|
|
69
|
-
override async init(): Promise<void> {
|
|
70
|
-
this.transactionDialect = { ...this.transactionDialect, begin: 'BEGIN IMMEDIATE;' };
|
|
71
|
-
|
|
117
|
+
async init(): Promise<void> {
|
|
72
118
|
await this.#create();
|
|
73
119
|
|
|
74
|
-
this.#pool = createPool<DatabaseSync>(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
120
|
+
this.#pool = createPool<DatabaseSync>(
|
|
121
|
+
{
|
|
122
|
+
create: () => this.#withRetries(() => this.#create()),
|
|
123
|
+
destroy: async db => {
|
|
124
|
+
db.close();
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
{ max: 1 }
|
|
128
|
+
);
|
|
78
129
|
|
|
79
|
-
// Close postgres
|
|
80
130
|
ShutdownManager.signal.addEventListener('abort', () => this.#pool.clear());
|
|
81
131
|
}
|
|
82
132
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Acquires a DB connection
|
|
135
|
+
*/
|
|
136
|
+
acquire(): Promise<DatabaseSync> {
|
|
137
|
+
return this.#withRetries(() => this.#pool.acquire());
|
|
138
|
+
}
|
|
87
139
|
|
|
140
|
+
/**
|
|
141
|
+
* Releases a DB connection back to pool
|
|
142
|
+
*/
|
|
143
|
+
release(connection: DatabaseSync): void {
|
|
144
|
+
this.#pool.release(connection);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Executes a query on the active client or pool directly
|
|
149
|
+
*/
|
|
150
|
+
async execute<Type = unknown>(query: string, values?: unknown[]): Promise<{ count: number; records: Type[] }> {
|
|
151
|
+
const isSelect =
|
|
152
|
+
query.trim().startsWith('SELECT') ||
|
|
153
|
+
query.trim().startsWith('PRAGMA') ||
|
|
154
|
+
query.trim().startsWith('EXISTS') ||
|
|
155
|
+
query.includes('RETURNING');
|
|
156
|
+
|
|
157
|
+
const normalized = (values ?? []).map(normalizeParameter);
|
|
158
|
+
|
|
159
|
+
return this.#withRetries(async () => {
|
|
160
|
+
console.debug('Executing SQLite query', { query, values });
|
|
161
|
+
const client = this.active ?? (await this.acquire());
|
|
88
162
|
try {
|
|
89
|
-
const prepared =
|
|
163
|
+
const prepared = client.prepare(query);
|
|
90
164
|
prepared.setReadBigInts(true);
|
|
91
165
|
if (isSelect) {
|
|
92
|
-
const out = prepared.all(...
|
|
93
|
-
const records:
|
|
166
|
+
const out = prepared.all(...normalized);
|
|
167
|
+
const records: Type[] = out.map(item => ({ ...castTo<Type>(item) }));
|
|
94
168
|
return { count: out.length, records };
|
|
95
169
|
} else {
|
|
96
|
-
const out = prepared.run(...
|
|
170
|
+
const out = prepared.run(...normalized);
|
|
97
171
|
return { count: typeof out.changes === 'number' ? out.changes : +out.changes.toString(), records: [] };
|
|
98
172
|
}
|
|
99
173
|
} catch (error) {
|
|
100
174
|
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
101
|
-
const message =
|
|
175
|
+
const message = error instanceof Error ? error.message : undefined;
|
|
102
176
|
switch (code) {
|
|
103
177
|
case 'ERR_SQLITE_ERROR': {
|
|
104
178
|
if (message?.startsWith('UNIQUE')) {
|
|
105
|
-
|
|
179
|
+
const match = message.match(/UNIQUE constraint failed: (.*)/);
|
|
180
|
+
const key = match ? match[1] : 'query';
|
|
181
|
+
throw new UniqueError('query', key, { message, query });
|
|
106
182
|
}
|
|
107
183
|
break;
|
|
108
184
|
}
|
|
109
|
-
case 'SQLITE_CONSTRAINT_PRIMARYKEY':
|
|
110
185
|
case 'SQLITE_CONSTRAINT_UNIQUE':
|
|
111
|
-
case 'SQLITE_CONSTRAINT_INDEX':
|
|
112
|
-
|
|
186
|
+
case 'SQLITE_CONSTRAINT_INDEX': {
|
|
187
|
+
const match = message?.match(/UNIQUE constraint failed: (.*)/);
|
|
188
|
+
const key = match ? match[1] : 'query';
|
|
189
|
+
throw new UniqueError('query', key, { message, query });
|
|
190
|
+
}
|
|
191
|
+
case 'SQLITE_CONSTRAINT_PRIMARYKEY':
|
|
192
|
+
throw new ExistsError('query', query);
|
|
193
|
+
}
|
|
113
194
|
if (/index.*?already exists/.test(message ?? '')) {
|
|
114
195
|
throw new ExistsError('index', query);
|
|
115
196
|
}
|
|
116
197
|
throw error;
|
|
198
|
+
} finally {
|
|
199
|
+
if (!this.active) {
|
|
200
|
+
this.release(client);
|
|
201
|
+
}
|
|
117
202
|
}
|
|
118
203
|
});
|
|
119
204
|
}
|
|
120
|
-
|
|
121
|
-
async acquire(): Promise<DatabaseSync> {
|
|
122
|
-
return await this.#pool.acquire();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async release(db: DatabaseSync): Promise<void> {
|
|
126
|
-
return this.#pool.release(db);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async pragma<T>(query: string): Promise<T> {
|
|
130
|
-
const db = await this.acquire();
|
|
131
|
-
try {
|
|
132
|
-
const result = this.#withRetries(async () => db.prepare(`PRAGMA ${query}`).get());
|
|
133
|
-
return castTo<T>(result);
|
|
134
|
-
} finally {
|
|
135
|
-
await this.release(db);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
205
|
+
}
|
package/src/dialect.ts
CHANGED
|
@@ -1,123 +1,232 @@
|
|
|
1
|
+
import { AbstractANSI99Dialect, type ResolvedPathContext, type TableContext, type TransactionStatements } from '@travetto/model-sql';
|
|
2
|
+
import { type Class, castTo, JSONUtil } from '@travetto/runtime';
|
|
1
3
|
import type { SchemaFieldConfig } from '@travetto/schema';
|
|
2
|
-
import { Injectable } from '@travetto/di';
|
|
3
|
-
import type { AsyncContext } from '@travetto/context';
|
|
4
|
-
import type { WhereClause } from '@travetto/model-query';
|
|
5
|
-
import { castTo } from '@travetto/runtime';
|
|
6
|
-
|
|
7
|
-
import { type SQLModelConfig, SQLDialect, type VisitStack, type SQLTableDescription } from '@travetto/model-sql';
|
|
8
|
-
|
|
9
|
-
import { SqliteConnection } from './connection.ts';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Sqlite Dialect for the SQL Model Source
|
|
13
|
-
*/
|
|
14
|
-
@Injectable()
|
|
15
|
-
export class SqliteDialect extends SQLDialect {
|
|
16
|
-
|
|
17
|
-
connection: SqliteConnection;
|
|
18
|
-
config: SQLModelConfig;
|
|
19
|
-
|
|
20
|
-
constructor(context: AsyncContext, config: SQLModelConfig) {
|
|
21
|
-
super(config.namespace);
|
|
22
|
-
this.connection = new SqliteConnection(context, config);
|
|
23
|
-
this.config = config;
|
|
24
|
-
|
|
25
|
-
// Special operators
|
|
26
|
-
Object.assign(this.SQL_OPS, {
|
|
27
|
-
$regex: 'REGEXP',
|
|
28
|
-
$ilike: undefined
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
// Special types
|
|
32
|
-
Object.assign(this.COLUMN_TYPES, {
|
|
33
|
-
JSON: 'TEXT',
|
|
34
|
-
TIMESTAMP: 'INTEGER'
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
override resolveDateValue(value: Date): string {
|
|
39
|
-
return `${value.getTime()}`;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* How to hash
|
|
44
|
-
*/
|
|
45
|
-
hash(value: string): string {
|
|
46
|
-
return `hex('${value}')`;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async describeTable(table: string): Promise<SQLTableDescription | undefined> {
|
|
50
|
-
const IGNORE_FIELDS = [this.pathField.name, this.parentPathField.name, this.idxField.name].map(field => `'${field}'`);
|
|
51
|
-
|
|
52
|
-
const [columns, foreignKeys, indices] = await Promise.all([
|
|
53
|
-
this.executeSQL<{ name: string, type: string, is_not_null: 1 | 0 }>(`
|
|
54
|
-
SELECT
|
|
55
|
-
name,
|
|
56
|
-
type,
|
|
57
|
-
${this.identifier('notnull')} <> 0 AS is_not_null
|
|
58
|
-
FROM PRAGMA_TABLE_INFO('${table}')
|
|
59
|
-
WHERE name NOT IN (${IGNORE_FIELDS.join(',')})
|
|
60
|
-
`),
|
|
61
|
-
this.executeSQL<{ name: string, to_table: string, from_column: string, to_column: string }>(`
|
|
62
|
-
SELECT
|
|
63
|
-
'fk_' || '${table}' || '_' || ${this.identifier('from')} AS name,
|
|
64
|
-
${this.identifier('from')} as from_column,
|
|
65
|
-
${this.identifier('to')} as to_column,
|
|
66
|
-
${this.identifier('table')} as to_table
|
|
67
|
-
FROM PRAGMA_FOREIGN_KEY_LIST('${table}')
|
|
68
|
-
`),
|
|
69
|
-
this.executeSQL<{ name: string, is_unique: boolean, columns: string }>(`
|
|
70
|
-
SELECT
|
|
71
|
-
il.name as name,
|
|
72
|
-
il.${this.identifier('unique')} = 1 as is_unique,
|
|
73
|
-
GROUP_CONCAT(ii.seqno || ' ' || ii.name || ' ' || ii.desc) AS columns
|
|
74
|
-
FROM PRAGMA_INDEX_LIST('${table}') il
|
|
75
|
-
JOIN PRAGMA_INDEX_XINFO(il.name) ii
|
|
76
|
-
WHERE il.name NOT LIKE 'sqlite_%'
|
|
77
|
-
GROUP BY 1, 2
|
|
78
|
-
`)
|
|
79
|
-
]);
|
|
80
4
|
|
|
5
|
+
export class SqliteDialect extends AbstractANSI99Dialect {
|
|
6
|
+
returningSupport = true;
|
|
7
|
+
transactionStatements: TransactionStatements = {
|
|
8
|
+
...AbstractANSI99Dialect.TRANSACTION_STATEMENTS,
|
|
9
|
+
begin: 'BEGIN IMMEDIATE;'
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
override getUpsertSQL(
|
|
13
|
+
context: TableContext,
|
|
14
|
+
columns: string[],
|
|
15
|
+
placeholders: string[],
|
|
16
|
+
conflictTarget: string[],
|
|
17
|
+
updates: string[]
|
|
18
|
+
): string {
|
|
19
|
+
return `INSERT INTO ${this.escapeIdentifier(context.tableName)} (${columns.join(', ')}) VALUES (${placeholders.join(', ')}) ON CONFLICT (${conflictTarget.join(', ')}) DO UPDATE SET ${updates.join(', ')} RETURNING *;`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
getComplexColumnType(field: SchemaFieldConfig): string {
|
|
23
|
+
return 'TEXT';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
getColumnType(fieldConfiguration: SchemaFieldConfig): string {
|
|
27
|
+
if (fieldConfiguration.type === castTo(BigInt)) {
|
|
28
|
+
return 'INTEGER';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (fieldConfiguration.type === Number) {
|
|
32
|
+
return 'NUMERIC';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (fieldConfiguration.type === Date) {
|
|
36
|
+
return 'TEXT';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (fieldConfiguration.type === Boolean) {
|
|
40
|
+
return 'INTEGER';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (fieldConfiguration.type === String) {
|
|
44
|
+
return 'TEXT';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return 'TEXT';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
compileJsonIndexPath(columnName: string, jsonPath: string[]): string {
|
|
51
|
+
return `json_extract(${columnName}, '$.${this.formatJsonPath(jsonPath)}')`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
#getSqliteArrayExpression(context: ResolvedPathContext): string {
|
|
55
|
+
if (!context.arrayPath || context.arrayPath.length === 0) {
|
|
56
|
+
return context.sqlPath;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const columnName = this.escapeIdentifier(context.arrayPath[0]);
|
|
60
|
+
return context.arrayPath.length > 1 ? `json_extract(${columnName}, '$.${context.arrayPath.slice(1).join('.')}')` : columnName;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#buildSubPathCondition(context: ResolvedPathContext, parentExpression: string, onLeaf: (leafExpression: string) => string): string {
|
|
64
|
+
if (!context.subPath || context.subPath.length === 0) {
|
|
65
|
+
return onLeaf(parentExpression);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const subPathMetadata = this.getSchemaSubPathMetadata(context.arrayField?.type, context.subPath);
|
|
69
|
+
const arraySegmentIndices = subPathMetadata
|
|
70
|
+
.map((metadataItem, metadataIndex) => (metadataItem.isArray ? metadataIndex : -1))
|
|
71
|
+
.filter(itemIndex => itemIndex !== -1);
|
|
72
|
+
|
|
73
|
+
if (arraySegmentIndices.length === 0) {
|
|
74
|
+
const leafExpression = `json_extract(${parentExpression}, '$.${context.subPath.join('.')}')`;
|
|
75
|
+
return onLeaf(leafExpression);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const buildLevel = (levelIndex: number, currentParent: string): string => {
|
|
79
|
+
const startPathIndex = levelIndex === 0 ? 0 : arraySegmentIndices[levelIndex - 1] + 1;
|
|
80
|
+
const endPathIndex = arraySegmentIndices[levelIndex];
|
|
81
|
+
const arrayPath = context.subPath!.slice(startPathIndex, endPathIndex + 1).join('.');
|
|
82
|
+
const alias = `ing_${levelIndex}`;
|
|
83
|
+
|
|
84
|
+
const innerCondition =
|
|
85
|
+
levelIndex === arraySegmentIndices.length - 1
|
|
86
|
+
? (() => {
|
|
87
|
+
const leafPath = context.subPath!.slice(endPathIndex + 1).join('.');
|
|
88
|
+
const leafExpression = leafPath ? `json_extract(${alias}.value, '$.${leafPath}')` : `${alias}.value`;
|
|
89
|
+
return onLeaf(leafExpression);
|
|
90
|
+
})()
|
|
91
|
+
: buildLevel(levelIndex + 1, `${alias}.value`);
|
|
92
|
+
|
|
93
|
+
return `
|
|
94
|
+
EXISTS (
|
|
95
|
+
SELECT 1
|
|
96
|
+
FROM json_each(${currentParent}, '$.${arrayPath}') AS ${alias}
|
|
97
|
+
WHERE ${innerCondition}
|
|
98
|
+
)`;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
return buildLevel(0, parentExpression);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
#buildArrayElementExists(context: ResolvedPathContext, onLeaf: (leafExpression: string) => string): string {
|
|
105
|
+
const jsonArrayExpression = this.#getSqliteArrayExpression(context);
|
|
106
|
+
const subPathCondition = this.#buildSubPathCondition(context, 'elem.value', onLeaf);
|
|
107
|
+
return `EXISTS (
|
|
108
|
+
SELECT 1
|
|
109
|
+
FROM json_each(${jsonArrayExpression}) AS elem
|
|
110
|
+
WHERE ${subPathCondition}
|
|
111
|
+
)`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
compileArrayAll(context: ResolvedPathContext, identifier: string, value: unknown[]): { sql: string; formatted: unknown } {
|
|
115
|
+
const elementExists = this.#buildArrayElementExists(context, leafExpression => `${leafExpression} = req.value`);
|
|
81
116
|
return {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
name: idx.name,
|
|
89
|
-
is_unique: idx.is_unique,
|
|
90
|
-
columns: idx.columns.split(',')
|
|
91
|
-
.map(col => col.split(' '))
|
|
92
|
-
.map(([order, name, desc]) => [+order, { name, desc: desc === '1' }] as const)
|
|
93
|
-
.sort((a, b) => a[0] - b[0])
|
|
94
|
-
.map(([, item]) => item)
|
|
95
|
-
}))
|
|
117
|
+
sql: `NOT EXISTS (
|
|
118
|
+
SELECT 1
|
|
119
|
+
FROM json_each(${identifier}) AS req
|
|
120
|
+
WHERE NOT ${elementExists}
|
|
121
|
+
)`,
|
|
122
|
+
formatted: JSONUtil.toUTF8(value)
|
|
96
123
|
};
|
|
97
124
|
}
|
|
98
125
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
126
|
+
compileArrayEquals(context: ResolvedPathContext, identifier: string, values: unknown): { sql: string; formatted: unknown } {
|
|
127
|
+
if (Array.isArray(values)) {
|
|
128
|
+
return {
|
|
129
|
+
sql: this.#buildArrayElementExists(context, leafExpression => `${leafExpression} IN (SELECT value FROM json_each(${identifier}))`),
|
|
130
|
+
formatted: JSONUtil.toUTF8(values)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (typeof values === 'object' && values !== null) {
|
|
135
|
+
return {
|
|
136
|
+
sql: this.#buildArrayElementExists(context, leafExpression => `json_patch(${leafExpression}, ${identifier}) = ${leafExpression}`),
|
|
137
|
+
formatted: JSONUtil.toUTF8(values)
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
sql: this.#buildArrayElementExists(context, leafExpression => `${leafExpression} = ${identifier}`),
|
|
143
|
+
formatted: values
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
compileArrayAny(context: ResolvedPathContext, identifier: string, values: unknown[]): { sql: string; formatted: unknown } {
|
|
148
|
+
return this.compileArrayEquals(context, identifier, values);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
compileArrayExists(context: ResolvedPathContext, identifier?: string): { sql: string } {
|
|
152
|
+
const jsonArrayExpression = this.#getSqliteArrayExpression(context);
|
|
153
|
+
return { sql: `(${jsonArrayExpression} IS NOT NULL AND json_array_length(${jsonArrayExpression}) > 0)` };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
compileArrayRegex(context: ResolvedPathContext, identifier: string, value: RegExp | string): { sql: string; formatted: unknown } {
|
|
157
|
+
const regex = value instanceof RegExp ? value : new RegExp(String(value));
|
|
158
|
+
const caseInsensitive = regex.flags.includes('i');
|
|
159
|
+
const regexOp = this.getRegexOperator(caseInsensitive);
|
|
160
|
+
const regexSource = this.formatRegex(regex.source, caseInsensitive);
|
|
161
|
+
return {
|
|
162
|
+
sql: this.#buildArrayElementExists(context, leafExpression => `${leafExpression} ${regexOp} ${identifier}`),
|
|
163
|
+
formatted: regexSource
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
getRegexOperator(caseInsensitive: boolean): string {
|
|
168
|
+
return 'REGEXP';
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
formatRegex(source: string, caseInsensitive: boolean): string {
|
|
172
|
+
return caseInsensitive ? `(?i)${source}` : source;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
castColumn(sqlPath: string, type: Class): string {
|
|
176
|
+
if (type === Number) {
|
|
177
|
+
return `CAST(${sqlPath} AS NUMERIC)`;
|
|
178
|
+
}
|
|
179
|
+
return sqlPath;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
getTableExistsQuery(context: TableContext): { sql: string; parameters?: unknown[] } {
|
|
183
|
+
return {
|
|
184
|
+
sql: `
|
|
185
|
+
SELECT name
|
|
186
|
+
FROM sqlite_master
|
|
187
|
+
WHERE type='table' AND name=?;`,
|
|
188
|
+
parameters: [context.tableName]
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
parseTableExistsResult(records: unknown[]): boolean {
|
|
193
|
+
return records.length > 0;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
getExistingColumnsQuery(context: TableContext): { sql: string; parameters?: unknown[] } {
|
|
197
|
+
return {
|
|
198
|
+
sql: `PRAGMA table_info('${this.escapeLiteral(context.tableName)}');`
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
parseExistingColumns(records: unknown[]): Map<string, string> {
|
|
203
|
+
return new Map(castTo<{ name: string; type: string }[]>(records).map(record => [record.name, record.type.toUpperCase()]));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
getExistingIndexesQuery(context: TableContext): { sql: string; parameters?: unknown[] } {
|
|
207
|
+
return {
|
|
208
|
+
sql: `
|
|
209
|
+
SELECT name, sql
|
|
210
|
+
FROM sqlite_master
|
|
211
|
+
WHERE type='index' AND tbl_name=?;
|
|
212
|
+
`,
|
|
213
|
+
parameters: [context.tableName]
|
|
214
|
+
};
|
|
107
215
|
}
|
|
108
216
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
217
|
+
parseExistingIndexes(records: unknown[]): Map<string, string> {
|
|
218
|
+
return new Map(
|
|
219
|
+
castTo<{ name: string; sql: string }[]>(records)
|
|
220
|
+
.filter(record => record.sql && !record.name.startsWith('sqlite_'))
|
|
221
|
+
.map(record => [record.name, record.sql])
|
|
222
|
+
);
|
|
114
223
|
}
|
|
115
224
|
|
|
116
|
-
|
|
117
|
-
return
|
|
225
|
+
getDropIndexSQL(context: TableContext, indexName: string): string {
|
|
226
|
+
return `DROP INDEX IF EXISTS ${this.escapeIdentifier(indexName)};`;
|
|
118
227
|
}
|
|
119
228
|
|
|
120
|
-
|
|
121
|
-
return
|
|
229
|
+
getTruncateTableSQL(context: TableContext): string {
|
|
230
|
+
return `DELETE FROM ${this.escapeIdentifier(context.tableName)};`;
|
|
122
231
|
}
|
|
123
|
-
}
|
|
232
|
+
}
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
|
|
3
|
+
import { Injectable, PostConstruct } from '@travetto/di';
|
|
4
|
+
import { BaseSQLModelService } from '@travetto/model-sql';
|
|
5
|
+
|
|
6
|
+
import type { SqliteConnection } from './connection.ts';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A SQLite JSON-based document store model service
|
|
10
|
+
*/
|
|
11
|
+
@Injectable()
|
|
12
|
+
export class SqliteModelService extends BaseSQLModelService {
|
|
13
|
+
connection: SqliteConnection;
|
|
14
|
+
|
|
15
|
+
constructor(connection: SqliteConnection) {
|
|
16
|
+
super();
|
|
17
|
+
this.connection = connection;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get client(): DatabaseSync {
|
|
21
|
+
return this.connection.active!;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
@PostConstruct()
|
|
25
|
+
override async initialize(): Promise<void> {
|
|
26
|
+
await super.initialize();
|
|
27
|
+
}
|
|
28
|
+
}
|