@atscript/db-sqlite 0.1.28
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/LICENSE +21 -0
- package/README.md +208 -0
- package/dist/index.cjs +478 -0
- package/dist/index.d.ts +144 -0
- package/dist/index.mjs +459 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Atscript
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# @atscript/db-sqlite
|
|
2
|
+
|
|
3
|
+
SQLite adapter for `@atscript/utils-db` with a swappable driver architecture. Define your schema once in Atscript, then use it with any SQLite engine.
|
|
4
|
+
|
|
5
|
+
## Architecture
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
AtscriptDbTable ──delegates──▶ SqliteAdapter ──delegates──▶ TSqliteDriver
|
|
9
|
+
(extends BaseDbAdapter) (interface)
|
|
10
|
+
│
|
|
11
|
+
┌─────────┴──────────┐
|
|
12
|
+
│ │
|
|
13
|
+
BetterSqlite3Driver (your own driver)
|
|
14
|
+
(ships with package) node:sqlite
|
|
15
|
+
sql.js, etc.
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The adapter defines a minimal `TSqliteDriver` interface — just raw SQL primitives (`run`, `all`, `get`, `exec`, `close`). The actual SQLite engine is injected, not hardcoded.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pnpm add @atscript/db-sqlite better-sqlite3
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`better-sqlite3` is an **optional peer dependency** — only required if you use the built-in `BetterSqlite3Driver`. Bring your own driver if you prefer a different engine.
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { AtscriptDbTable } from '@atscript/utils-db'
|
|
32
|
+
import { SqliteAdapter, BetterSqlite3Driver } from '@atscript/db-sqlite'
|
|
33
|
+
import { User } from './user.as'
|
|
34
|
+
|
|
35
|
+
// 1. Create a driver (in-memory or file-based)
|
|
36
|
+
const driver = new BetterSqlite3Driver(':memory:')
|
|
37
|
+
// or: new BetterSqlite3Driver('./data.db')
|
|
38
|
+
|
|
39
|
+
// 2. Create adapter + table
|
|
40
|
+
const adapter = new SqliteAdapter(driver)
|
|
41
|
+
const users = new AtscriptDbTable(User, adapter)
|
|
42
|
+
|
|
43
|
+
// 3. Set up schema
|
|
44
|
+
await users.ensureTable() // CREATE TABLE IF NOT EXISTS
|
|
45
|
+
await users.syncIndexes() // CREATE INDEX / DROP INDEX
|
|
46
|
+
|
|
47
|
+
// 4. CRUD
|
|
48
|
+
await users.insertOne({ name: 'John', email: 'john@example.com' })
|
|
49
|
+
const john = await users.findOne({ name: 'John' })
|
|
50
|
+
await users.findMany({ status: 'active' }, { limit: 10, sort: { name: 1 } })
|
|
51
|
+
await users.count({ status: 'active' })
|
|
52
|
+
await users.updateMany({ status: 'inactive' }, { status: 'archived' })
|
|
53
|
+
await users.deleteOne(123)
|
|
54
|
+
await users.deleteMany({ status: 'archived' })
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Swapping the Driver
|
|
58
|
+
|
|
59
|
+
The `TSqliteDriver` interface is minimal — implement these 5 methods:
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
interface TSqliteDriver {
|
|
63
|
+
run(sql: string, params?: unknown[]): TSqliteRunResult
|
|
64
|
+
all<T>(sql: string, params?: unknown[]): T[]
|
|
65
|
+
get<T>(sql: string, params?: unknown[]): T | null
|
|
66
|
+
exec(sql: string): void
|
|
67
|
+
close(): void
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface TSqliteRunResult {
|
|
71
|
+
changes: number
|
|
72
|
+
lastInsertRowid: number | bigint
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Example: Custom driver
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
import { SqliteAdapter, type TSqliteDriver } from '@atscript/db-sqlite'
|
|
80
|
+
|
|
81
|
+
class MyDriver implements TSqliteDriver {
|
|
82
|
+
run(sql: string, params?: unknown[]) {
|
|
83
|
+
// your implementation
|
|
84
|
+
return { changes: 0, lastInsertRowid: 0 }
|
|
85
|
+
}
|
|
86
|
+
all(sql: string, params?: unknown[]) { /* ... */ }
|
|
87
|
+
get(sql: string, params?: unknown[]) { /* ... */ }
|
|
88
|
+
exec(sql: string) { /* ... */ }
|
|
89
|
+
close() { /* ... */ }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const adapter = new SqliteAdapter(new MyDriver())
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Example: node:sqlite (Node 22.5+)
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
99
|
+
import { SqliteAdapter, type TSqliteDriver } from '@atscript/db-sqlite'
|
|
100
|
+
|
|
101
|
+
class NodeSqliteDriver implements TSqliteDriver {
|
|
102
|
+
private db: DatabaseSync
|
|
103
|
+
|
|
104
|
+
constructor(path: string) {
|
|
105
|
+
this.db = new DatabaseSync(path)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
run(sql: string, params?: unknown[]) {
|
|
109
|
+
const stmt = this.db.prepare(sql)
|
|
110
|
+
stmt.run(...(params ?? []))
|
|
111
|
+
return {
|
|
112
|
+
changes: this.db.changes,
|
|
113
|
+
lastInsertRowid: this.db.lastInsertRowId,
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
all<T>(sql: string, params?: unknown[]): T[] {
|
|
118
|
+
return this.db.prepare(sql).all(...(params ?? [])) as T[]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
get<T>(sql: string, params?: unknown[]): T | null {
|
|
122
|
+
return (this.db.prepare(sql).get(...(params ?? [])) as T) ?? null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
exec(sql: string) { this.db.exec(sql) }
|
|
126
|
+
close() { this.db.close() }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const adapter = new SqliteAdapter(new NodeSqliteDriver(':memory:'))
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Filter Syntax
|
|
133
|
+
|
|
134
|
+
Filters use MongoDB-style query objects (same format as URLQL):
|
|
135
|
+
|
|
136
|
+
| Filter | SQL |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `{ field: value }` | `field = ?` |
|
|
139
|
+
| `{ field: { $gt: 5 } }` | `field > ?` |
|
|
140
|
+
| `{ field: { $gte: 5 } }` | `field >= ?` |
|
|
141
|
+
| `{ field: { $lt: 5 } }` | `field < ?` |
|
|
142
|
+
| `{ field: { $lte: 5 } }` | `field <= ?` |
|
|
143
|
+
| `{ field: { $ne: value } }` | `field != ?` |
|
|
144
|
+
| `{ field: { $in: [1, 2] } }` | `field IN (?, ?)` |
|
|
145
|
+
| `{ field: { $nin: [1, 2] } }` | `field NOT IN (?, ?)` |
|
|
146
|
+
| `{ field: { $exists: true } }` | `field IS NOT NULL` |
|
|
147
|
+
| `{ field: { $regex: '^abc' } }` | `field LIKE 'abc%'` |
|
|
148
|
+
| `{ $and: [...] }` | `(... AND ...)` |
|
|
149
|
+
| `{ $or: [...] }` | `(... OR ...)` |
|
|
150
|
+
| `{ $not: {...} }` | `NOT (...)` |
|
|
151
|
+
|
|
152
|
+
All values are parameterized — no SQL injection risk.
|
|
153
|
+
|
|
154
|
+
## Schema Operations
|
|
155
|
+
|
|
156
|
+
### `ensureTable()`
|
|
157
|
+
|
|
158
|
+
Generates `CREATE TABLE IF NOT EXISTS` from the Atscript type:
|
|
159
|
+
- Column types inferred from `designType` (`string` → TEXT, `number` → REAL, `boolean` → INTEGER)
|
|
160
|
+
- Primary keys from `@meta.id`
|
|
161
|
+
- `NOT NULL` for required fields
|
|
162
|
+
- `@db.column` mappings applied (logical → physical column names)
|
|
163
|
+
- `@db.ignore` fields excluded
|
|
164
|
+
|
|
165
|
+
### `syncIndexes()`
|
|
166
|
+
|
|
167
|
+
Compares existing indexes with `@db.index.*` annotations:
|
|
168
|
+
- Creates missing indexes (`CREATE INDEX` / `CREATE UNIQUE INDEX`)
|
|
169
|
+
- Drops stale indexes no longer in the definition
|
|
170
|
+
- Supports `@db.index.plain`, `@db.index.unique`
|
|
171
|
+
- `@db.index.fulltext` is skipped (requires FTS5 virtual tables — not auto-managed)
|
|
172
|
+
|
|
173
|
+
## Write Pipeline
|
|
174
|
+
|
|
175
|
+
When you call `insertOne(payload)`, `AtscriptDbTable` automatically:
|
|
176
|
+
|
|
177
|
+
1. Applies `@db.default.value` defaults for missing fields
|
|
178
|
+
2. Validates against the Atscript type
|
|
179
|
+
3. Strips `@db.ignore` fields
|
|
180
|
+
4. Maps `@db.column` logical names to physical column names
|
|
181
|
+
5. Delegates to `SqliteAdapter.insertOne()` which generates and runs the SQL
|
|
182
|
+
|
|
183
|
+
## Exports
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
// Classes
|
|
187
|
+
export { SqliteAdapter } from './sqlite-adapter'
|
|
188
|
+
export { BetterSqlite3Driver } from './better-sqlite3-driver'
|
|
189
|
+
|
|
190
|
+
// Utilities
|
|
191
|
+
export { buildWhere } from './filter-builder'
|
|
192
|
+
|
|
193
|
+
// Types
|
|
194
|
+
export type { TSqliteDriver, TSqliteRunResult } from './types'
|
|
195
|
+
export type { TSqlFragment } from './filter-builder'
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Why Sync Driver Interface?
|
|
199
|
+
|
|
200
|
+
The driver interface is **synchronous** because:
|
|
201
|
+
- SQLite is an embedded engine — no network I/O
|
|
202
|
+
- `better-sqlite3` and `node:sqlite` are both synchronous
|
|
203
|
+
- The `SqliteAdapter` wraps sync calls in promises for the async `BaseDbAdapter` contract
|
|
204
|
+
- For truly async drivers, implement the interface with a synchronous wrapper or create a custom adapter subclass
|
|
205
|
+
|
|
206
|
+
## License
|
|
207
|
+
|
|
208
|
+
ISC
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
//#region rolldown:runtime
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
const __atscript_utils_db = __toESM(require("@atscript/utils-db"));
|
|
26
|
+
|
|
27
|
+
//#region packages/db-sqlite/src/filter-builder.ts
|
|
28
|
+
function buildWhere(filter) {
|
|
29
|
+
if (!filter || Object.keys(filter).length === 0) return {
|
|
30
|
+
sql: "1=1",
|
|
31
|
+
params: []
|
|
32
|
+
};
|
|
33
|
+
const parts = [];
|
|
34
|
+
const params = [];
|
|
35
|
+
for (const [key, value] of Object.entries(filter)) if (key === "$and") {
|
|
36
|
+
const sub = value.map((f) => buildWhere(f));
|
|
37
|
+
parts.push(`(${sub.map((s) => s.sql).join(" AND ")})`);
|
|
38
|
+
for (const s of sub) params.push(...s.params);
|
|
39
|
+
} else if (key === "$or") {
|
|
40
|
+
const sub = value.map((f) => buildWhere(f));
|
|
41
|
+
parts.push(`(${sub.map((s) => s.sql).join(" OR ")})`);
|
|
42
|
+
for (const s of sub) params.push(...s.params);
|
|
43
|
+
} else if (key === "$not") {
|
|
44
|
+
const sub = buildWhere(value);
|
|
45
|
+
parts.push(`NOT (${sub.sql})`);
|
|
46
|
+
params.push(...sub.params);
|
|
47
|
+
} else if (typeof value === "object" && value !== null && !Array.isArray(value)) for (const [op, opVal] of Object.entries(value)) {
|
|
48
|
+
const fragment = buildOperator(key, op, opVal);
|
|
49
|
+
parts.push(fragment.sql);
|
|
50
|
+
params.push(...fragment.params);
|
|
51
|
+
}
|
|
52
|
+
else if (value === null) parts.push(`"${escapeIdent(key)}" IS NULL`);
|
|
53
|
+
else {
|
|
54
|
+
parts.push(`"${escapeIdent(key)}" = ?`);
|
|
55
|
+
params.push(value);
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
sql: parts.join(" AND "),
|
|
59
|
+
params
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function buildOperator(field, op, value) {
|
|
63
|
+
const col = `"${escapeIdent(field)}"`;
|
|
64
|
+
switch (op) {
|
|
65
|
+
case "$gt": return {
|
|
66
|
+
sql: `${col} > ?`,
|
|
67
|
+
params: [value]
|
|
68
|
+
};
|
|
69
|
+
case "$gte": return {
|
|
70
|
+
sql: `${col} >= ?`,
|
|
71
|
+
params: [value]
|
|
72
|
+
};
|
|
73
|
+
case "$lt": return {
|
|
74
|
+
sql: `${col} < ?`,
|
|
75
|
+
params: [value]
|
|
76
|
+
};
|
|
77
|
+
case "$lte": return {
|
|
78
|
+
sql: `${col} <= ?`,
|
|
79
|
+
params: [value]
|
|
80
|
+
};
|
|
81
|
+
case "$ne": {
|
|
82
|
+
if (value === null) return {
|
|
83
|
+
sql: `${col} IS NOT NULL`,
|
|
84
|
+
params: []
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
sql: `${col} != ?`,
|
|
88
|
+
params: [value]
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
case "$in": {
|
|
92
|
+
const arr = value;
|
|
93
|
+
if (arr.length === 0) return {
|
|
94
|
+
sql: "0=1",
|
|
95
|
+
params: []
|
|
96
|
+
};
|
|
97
|
+
const placeholders = arr.map(() => "?").join(", ");
|
|
98
|
+
return {
|
|
99
|
+
sql: `${col} IN (${placeholders})`,
|
|
100
|
+
params: [...arr]
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
case "$nin": {
|
|
104
|
+
const arr = value;
|
|
105
|
+
if (arr.length === 0) return {
|
|
106
|
+
sql: "1=1",
|
|
107
|
+
params: []
|
|
108
|
+
};
|
|
109
|
+
const placeholders = arr.map(() => "?").join(", ");
|
|
110
|
+
return {
|
|
111
|
+
sql: `${col} NOT IN (${placeholders})`,
|
|
112
|
+
params: [...arr]
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
case "$exists": return value ? {
|
|
116
|
+
sql: `${col} IS NOT NULL`,
|
|
117
|
+
params: []
|
|
118
|
+
} : {
|
|
119
|
+
sql: `${col} IS NULL`,
|
|
120
|
+
params: []
|
|
121
|
+
};
|
|
122
|
+
case "$regex": {
|
|
123
|
+
const pattern = regexToLike(String(value));
|
|
124
|
+
return {
|
|
125
|
+
sql: `${col} LIKE ?`,
|
|
126
|
+
params: [pattern]
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
default: throw new Error(`Unsupported filter operator: ${op}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Basic regex-to-LIKE conversion.
|
|
134
|
+
* - `^abc` → `abc%`
|
|
135
|
+
* - `abc$` → `%abc`
|
|
136
|
+
* - `^abc$` → `abc`
|
|
137
|
+
* - `abc` → `%abc%`
|
|
138
|
+
*/ function regexToLike(pattern) {
|
|
139
|
+
const hasStart = pattern.startsWith("^");
|
|
140
|
+
const hasEnd = pattern.endsWith("$");
|
|
141
|
+
let core = pattern;
|
|
142
|
+
if (hasStart) core = core.slice(1);
|
|
143
|
+
if (hasEnd) core = core.slice(0, -1);
|
|
144
|
+
core = core.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
145
|
+
core = core.replace(/\.\*/g, "%").replace(/\./g, "_");
|
|
146
|
+
if (hasStart && hasEnd) return core;
|
|
147
|
+
if (hasStart) return `${core}%`;
|
|
148
|
+
if (hasEnd) return `%${core}`;
|
|
149
|
+
return `%${core}%`;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Escapes a SQL identifier to prevent injection.
|
|
153
|
+
* Doubles any embedded double-quotes.
|
|
154
|
+
*/ function escapeIdent(name) {
|
|
155
|
+
return name.replace(/"/g, "\"\"");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region packages/db-sqlite/src/sql-builder.ts
|
|
160
|
+
function buildInsert(table, data) {
|
|
161
|
+
const keys = Object.keys(data);
|
|
162
|
+
const cols = keys.map((k) => `"${esc$1(k)}"`).join(", ");
|
|
163
|
+
const placeholders = keys.map(() => "?").join(", ");
|
|
164
|
+
return {
|
|
165
|
+
sql: `INSERT INTO "${esc$1(table)}" (${cols}) VALUES (${placeholders})`,
|
|
166
|
+
params: keys.map((k) => toSqliteValue$1(data[k]))
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function buildSelect(table, where, options) {
|
|
170
|
+
const cols = buildProjection(options?.projection);
|
|
171
|
+
let sql = `SELECT ${cols} FROM "${esc$1(table)}" WHERE ${where.sql}`;
|
|
172
|
+
const params = [...where.params];
|
|
173
|
+
if (options?.sort) {
|
|
174
|
+
const orderParts = [];
|
|
175
|
+
for (const [col, dir] of Object.entries(options.sort)) orderParts.push(`"${esc$1(col)}" ${dir === -1 ? "DESC" : "ASC"}`);
|
|
176
|
+
if (orderParts.length > 0) sql += ` ORDER BY ${orderParts.join(", ")}`;
|
|
177
|
+
}
|
|
178
|
+
if (options?.limit !== undefined) {
|
|
179
|
+
sql += ` LIMIT ?`;
|
|
180
|
+
params.push(options.limit);
|
|
181
|
+
}
|
|
182
|
+
if (options?.skip !== undefined) {
|
|
183
|
+
if (options.limit === undefined) sql += ` LIMIT -1`;
|
|
184
|
+
sql += ` OFFSET ?`;
|
|
185
|
+
params.push(options.skip);
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
sql,
|
|
189
|
+
params
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function buildUpdate(table, data, where) {
|
|
193
|
+
const setClauses = [];
|
|
194
|
+
const params = [];
|
|
195
|
+
for (const [key, value] of Object.entries(data)) {
|
|
196
|
+
setClauses.push(`"${esc$1(key)}" = ?`);
|
|
197
|
+
params.push(toSqliteValue$1(value));
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
sql: `UPDATE "${esc$1(table)}" SET ${setClauses.join(", ")} WHERE ${where.sql}`,
|
|
201
|
+
params: [...params, ...where.params]
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function buildDelete(table, where) {
|
|
205
|
+
return {
|
|
206
|
+
sql: `DELETE FROM "${esc$1(table)}" WHERE ${where.sql}`,
|
|
207
|
+
params: [...where.params]
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function buildCreateTable(table, fields) {
|
|
211
|
+
const colDefs = [];
|
|
212
|
+
const primaryKeys = fields.filter((f) => f.isPrimaryKey);
|
|
213
|
+
for (const field of fields) {
|
|
214
|
+
if (field.ignored) continue;
|
|
215
|
+
const sqlType = sqliteTypeFromDesignType(field.designType);
|
|
216
|
+
let def = `"${esc$1(field.physicalName)}" ${sqlType}`;
|
|
217
|
+
if (field.isPrimaryKey && primaryKeys.length === 1) def += " PRIMARY KEY";
|
|
218
|
+
if (!field.optional && !field.isPrimaryKey) def += " NOT NULL";
|
|
219
|
+
colDefs.push(def);
|
|
220
|
+
}
|
|
221
|
+
if (primaryKeys.length > 1) {
|
|
222
|
+
const pkCols = primaryKeys.map((pk) => `"${esc$1(pk.physicalName)}"`).join(", ");
|
|
223
|
+
colDefs.push(`PRIMARY KEY (${pkCols})`);
|
|
224
|
+
}
|
|
225
|
+
return `CREATE TABLE IF NOT EXISTS "${esc$1(table)}" (${colDefs.join(", ")})`;
|
|
226
|
+
}
|
|
227
|
+
function sqliteTypeFromDesignType(designType) {
|
|
228
|
+
switch (designType) {
|
|
229
|
+
case "number":
|
|
230
|
+
case "integer": return "REAL";
|
|
231
|
+
case "boolean": return "INTEGER";
|
|
232
|
+
case "string": return "TEXT";
|
|
233
|
+
default: return "TEXT";
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function buildProjection(projection) {
|
|
237
|
+
if (!projection) return "*";
|
|
238
|
+
if (Array.isArray(projection)) {
|
|
239
|
+
if (projection.length === 0) return "*";
|
|
240
|
+
return projection.map((k) => `"${esc$1(k)}"`).join(", ");
|
|
241
|
+
}
|
|
242
|
+
const entries = Object.entries(projection);
|
|
243
|
+
if (entries.length === 0) return "*";
|
|
244
|
+
const firstVal = entries[0][1];
|
|
245
|
+
if (firstVal === 1) return entries.filter(([_, v]) => v === 1).map(([k]) => `"${esc$1(k)}"`).join(", ");
|
|
246
|
+
return "*";
|
|
247
|
+
}
|
|
248
|
+
function esc$1(name) {
|
|
249
|
+
return name.replace(/"/g, "\"\"");
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Converts a JS value to a SQLite-compatible value.
|
|
253
|
+
* Objects and arrays are stored as JSON strings.
|
|
254
|
+
*/ function toSqliteValue$1(value) {
|
|
255
|
+
if (value === undefined) return null;
|
|
256
|
+
if (value === null) return null;
|
|
257
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
258
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
259
|
+
return value;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region packages/db-sqlite/src/sqlite-adapter.ts
|
|
264
|
+
function _define_property$1(obj, key, value) {
|
|
265
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
266
|
+
value,
|
|
267
|
+
enumerable: true,
|
|
268
|
+
configurable: true,
|
|
269
|
+
writable: true
|
|
270
|
+
});
|
|
271
|
+
else obj[key] = value;
|
|
272
|
+
return obj;
|
|
273
|
+
}
|
|
274
|
+
var SqliteAdapter = class extends __atscript_utils_db.BaseDbAdapter {
|
|
275
|
+
/** SQLite does not use schemas — override to always exclude schema. */ resolveTableName() {
|
|
276
|
+
return super.resolveTableName(false);
|
|
277
|
+
}
|
|
278
|
+
prepareId(id, _fieldType) {
|
|
279
|
+
return id;
|
|
280
|
+
}
|
|
281
|
+
async insertOne(data) {
|
|
282
|
+
const { sql, params } = buildInsert(this.resolveTableName(), data);
|
|
283
|
+
const result = this.driver.run(sql, params);
|
|
284
|
+
return { insertedId: result.lastInsertRowid };
|
|
285
|
+
}
|
|
286
|
+
async insertMany(data) {
|
|
287
|
+
const ids = [];
|
|
288
|
+
this.driver.exec("BEGIN");
|
|
289
|
+
try {
|
|
290
|
+
for (const row of data) {
|
|
291
|
+
const { sql, params } = buildInsert(this.resolveTableName(), row);
|
|
292
|
+
const result = this.driver.run(sql, params);
|
|
293
|
+
ids.push(result.lastInsertRowid);
|
|
294
|
+
}
|
|
295
|
+
this.driver.exec("COMMIT");
|
|
296
|
+
} catch (error) {
|
|
297
|
+
this.driver.exec("ROLLBACK");
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
insertedCount: ids.length,
|
|
302
|
+
insertedIds: ids
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
async findOne(filter, options) {
|
|
306
|
+
const where = buildWhere(filter);
|
|
307
|
+
const { sql, params } = buildSelect(this.resolveTableName(), where, {
|
|
308
|
+
...options,
|
|
309
|
+
limit: 1
|
|
310
|
+
});
|
|
311
|
+
return this.driver.get(sql, params);
|
|
312
|
+
}
|
|
313
|
+
async findMany(filter, options) {
|
|
314
|
+
const where = buildWhere(filter);
|
|
315
|
+
const { sql, params } = buildSelect(this.resolveTableName(), where, options);
|
|
316
|
+
return this.driver.all(sql, params);
|
|
317
|
+
}
|
|
318
|
+
async count(filter) {
|
|
319
|
+
const where = buildWhere(filter);
|
|
320
|
+
const tableName = this.resolveTableName();
|
|
321
|
+
const sql = `SELECT COUNT(*) as cnt FROM "${esc(tableName)}" WHERE ${where.sql}`;
|
|
322
|
+
const row = this.driver.get(sql, where.params);
|
|
323
|
+
return row?.cnt ?? 0;
|
|
324
|
+
}
|
|
325
|
+
async updateOne(filter, data) {
|
|
326
|
+
const where = buildWhere(filter);
|
|
327
|
+
const tableName = this.resolveTableName();
|
|
328
|
+
const setClauses = [];
|
|
329
|
+
const setParams = [];
|
|
330
|
+
for (const [key, value] of Object.entries(data)) {
|
|
331
|
+
setClauses.push(`"${esc(key)}" = ?`);
|
|
332
|
+
setParams.push(toSqliteValue(value));
|
|
333
|
+
}
|
|
334
|
+
const sql = `UPDATE "${esc(tableName)}" SET ${setClauses.join(", ")} WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
335
|
+
const result = this.driver.run(sql, [...setParams, ...where.params]);
|
|
336
|
+
return {
|
|
337
|
+
matchedCount: result.changes,
|
|
338
|
+
modifiedCount: result.changes
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
async updateMany(filter, data) {
|
|
342
|
+
const where = buildWhere(filter);
|
|
343
|
+
const { sql, params } = buildUpdate(this.resolveTableName(), data, where);
|
|
344
|
+
const result = this.driver.run(sql, params);
|
|
345
|
+
return {
|
|
346
|
+
matchedCount: result.changes,
|
|
347
|
+
modifiedCount: result.changes
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
async replaceOne(filter, data) {
|
|
351
|
+
const where = buildWhere(filter);
|
|
352
|
+
const tableName = this.resolveTableName();
|
|
353
|
+
this.driver.exec("BEGIN");
|
|
354
|
+
try {
|
|
355
|
+
const delSql = `DELETE FROM "${esc(tableName)}" WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
356
|
+
const delResult = this.driver.run(delSql, where.params);
|
|
357
|
+
if (delResult.changes > 0) {
|
|
358
|
+
const { sql, params } = buildInsert(tableName, data);
|
|
359
|
+
this.driver.run(sql, params);
|
|
360
|
+
}
|
|
361
|
+
this.driver.exec("COMMIT");
|
|
362
|
+
return {
|
|
363
|
+
matchedCount: delResult.changes,
|
|
364
|
+
modifiedCount: delResult.changes
|
|
365
|
+
};
|
|
366
|
+
} catch (error) {
|
|
367
|
+
this.driver.exec("ROLLBACK");
|
|
368
|
+
throw error;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async replaceMany(filter, data) {
|
|
372
|
+
const where = buildWhere(filter);
|
|
373
|
+
const { sql, params } = buildUpdate(this.resolveTableName(), data, where);
|
|
374
|
+
const result = this.driver.run(sql, params);
|
|
375
|
+
return {
|
|
376
|
+
matchedCount: result.changes,
|
|
377
|
+
modifiedCount: result.changes
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
async deleteOne(filter) {
|
|
381
|
+
const where = buildWhere(filter);
|
|
382
|
+
const tableName = this.resolveTableName();
|
|
383
|
+
const sql = `DELETE FROM "${esc(tableName)}" WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
384
|
+
const result = this.driver.run(sql, where.params);
|
|
385
|
+
return { deletedCount: result.changes };
|
|
386
|
+
}
|
|
387
|
+
async deleteMany(filter) {
|
|
388
|
+
const where = buildWhere(filter);
|
|
389
|
+
const { sql, params } = buildDelete(this.resolveTableName(), where);
|
|
390
|
+
const result = this.driver.run(sql, params);
|
|
391
|
+
return { deletedCount: result.changes };
|
|
392
|
+
}
|
|
393
|
+
async ensureTable() {
|
|
394
|
+
const sql = buildCreateTable(this.resolveTableName(), this._table.fieldDescriptors);
|
|
395
|
+
this.driver.exec(sql);
|
|
396
|
+
}
|
|
397
|
+
async syncIndexes() {
|
|
398
|
+
const tableName = this.resolveTableName();
|
|
399
|
+
const columnMap = this._table.columnMap;
|
|
400
|
+
await this.syncIndexesWithDiff({
|
|
401
|
+
listExisting: async () => this.driver.all(`PRAGMA index_list("${esc(tableName)}")`).filter((i) => !i.name.startsWith("sqlite_")),
|
|
402
|
+
createIndex: async (index) => {
|
|
403
|
+
const unique = index.type === "unique" ? "UNIQUE " : "";
|
|
404
|
+
const cols = index.fields.map((f) => {
|
|
405
|
+
const physical = columnMap.get(f.name) ?? f.name;
|
|
406
|
+
return `"${esc(physical)}" ${f.sort === "desc" ? "DESC" : "ASC"}`;
|
|
407
|
+
}).join(", ");
|
|
408
|
+
this.driver.exec(`CREATE ${unique}INDEX IF NOT EXISTS "${esc(index.key)}" ON "${esc(tableName)}" (${cols})`);
|
|
409
|
+
},
|
|
410
|
+
dropIndex: async (name) => {
|
|
411
|
+
this.driver.exec(`DROP INDEX IF EXISTS "${esc(name)}"`);
|
|
412
|
+
},
|
|
413
|
+
shouldSkipType: (type) => type === "fulltext"
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
constructor(driver) {
|
|
417
|
+
super(), _define_property$1(this, "driver", void 0), this.driver = driver;
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
function esc(name) {
|
|
421
|
+
return name.replace(/"/g, "\"\"");
|
|
422
|
+
}
|
|
423
|
+
function toSqliteValue(value) {
|
|
424
|
+
if (value === undefined) return null;
|
|
425
|
+
if (value === null) return null;
|
|
426
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
427
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
428
|
+
return value;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
//#endregion
|
|
432
|
+
//#region packages/db-sqlite/src/better-sqlite3-driver.ts
|
|
433
|
+
function _define_property(obj, key, value) {
|
|
434
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
435
|
+
value,
|
|
436
|
+
enumerable: true,
|
|
437
|
+
configurable: true,
|
|
438
|
+
writable: true
|
|
439
|
+
});
|
|
440
|
+
else obj[key] = value;
|
|
441
|
+
return obj;
|
|
442
|
+
}
|
|
443
|
+
var BetterSqlite3Driver = class {
|
|
444
|
+
run(sql, params) {
|
|
445
|
+
const stmt = this.db.prepare(sql);
|
|
446
|
+
const result = params ? stmt.run(...params) : stmt.run();
|
|
447
|
+
return {
|
|
448
|
+
changes: result.changes,
|
|
449
|
+
lastInsertRowid: result.lastInsertRowid
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
all(sql, params) {
|
|
453
|
+
const stmt = this.db.prepare(sql);
|
|
454
|
+
return params ? stmt.all(...params) : stmt.all();
|
|
455
|
+
}
|
|
456
|
+
get(sql, params) {
|
|
457
|
+
const stmt = this.db.prepare(sql);
|
|
458
|
+
return (params ? stmt.get(...params) : stmt.get()) ?? null;
|
|
459
|
+
}
|
|
460
|
+
exec(sql) {
|
|
461
|
+
this.db.exec(sql);
|
|
462
|
+
}
|
|
463
|
+
close() {
|
|
464
|
+
this.db.close();
|
|
465
|
+
}
|
|
466
|
+
constructor(pathOrDb, options) {
|
|
467
|
+
_define_property(this, "db", void 0);
|
|
468
|
+
if (typeof pathOrDb === "string") {
|
|
469
|
+
const Database = require("better-sqlite3");
|
|
470
|
+
this.db = new Database(pathOrDb, options);
|
|
471
|
+
} else this.db = pathOrDb;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
//#endregion
|
|
476
|
+
exports.BetterSqlite3Driver = BetterSqlite3Driver
|
|
477
|
+
exports.SqliteAdapter = SqliteAdapter
|
|
478
|
+
exports.buildWhere = buildWhere
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { TAtscriptAnnotatedType } from '@atscript/typescript/utils';
|
|
2
|
+
import { BaseDbAdapter, TDbInsertResult, TDbInsertManyResult, TDbFilter, TDbFindOptions, TDbUpdateResult, TDbDeleteResult } from '@atscript/utils-db';
|
|
3
|
+
import * as better_sqlite3 from 'better-sqlite3';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Result of a SQL statement that modifies data (INSERT, UPDATE, DELETE).
|
|
7
|
+
*/
|
|
8
|
+
interface TSqliteRunResult {
|
|
9
|
+
/** Number of rows changed by the statement. */
|
|
10
|
+
changes: number;
|
|
11
|
+
/** Rowid of the last inserted row (for INSERT statements). */
|
|
12
|
+
lastInsertRowid: number | bigint;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Minimal driver interface for SQLite engines.
|
|
16
|
+
*
|
|
17
|
+
* Intentionally synchronous — SQLite is an embedded engine with no network I/O.
|
|
18
|
+
* Both `better-sqlite3` and `node:sqlite` (DatabaseSync) are synchronous.
|
|
19
|
+
* The {@link SqliteAdapter} wraps these calls in promises for the async
|
|
20
|
+
* {@link BaseDbAdapter} contract.
|
|
21
|
+
*
|
|
22
|
+
* For async drivers (e.g., `sql.js`), create a synchronous wrapper
|
|
23
|
+
* or implement a custom adapter.
|
|
24
|
+
*/
|
|
25
|
+
interface TSqliteDriver {
|
|
26
|
+
/**
|
|
27
|
+
* Execute a SQL statement that doesn't return rows.
|
|
28
|
+
* Used for INSERT, UPDATE, DELETE, CREATE, DROP, etc.
|
|
29
|
+
*/
|
|
30
|
+
run(sql: string, params?: unknown[]): TSqliteRunResult;
|
|
31
|
+
/**
|
|
32
|
+
* Execute a query and return all matching rows.
|
|
33
|
+
*/
|
|
34
|
+
all<T = Record<string, unknown>>(sql: string, params?: unknown[]): T[];
|
|
35
|
+
/**
|
|
36
|
+
* Execute a query and return the first matching row, or null.
|
|
37
|
+
*/
|
|
38
|
+
get<T = Record<string, unknown>>(sql: string, params?: unknown[]): T | null;
|
|
39
|
+
/**
|
|
40
|
+
* Execute raw SQL without returning results.
|
|
41
|
+
* Used for multi-statement strings like PRAGMA or BEGIN/COMMIT.
|
|
42
|
+
*/
|
|
43
|
+
exec(sql: string): void;
|
|
44
|
+
/**
|
|
45
|
+
* Close the database connection.
|
|
46
|
+
*/
|
|
47
|
+
close(): void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* SQLite adapter for {@link AtscriptDbTable}.
|
|
52
|
+
*
|
|
53
|
+
* Accepts any {@link TSqliteDriver} implementation — the actual SQLite engine
|
|
54
|
+
* is fully swappable (better-sqlite3, node:sqlite, sql.js, etc.).
|
|
55
|
+
*
|
|
56
|
+
* Usage:
|
|
57
|
+
* ```typescript
|
|
58
|
+
* import { BetterSqlite3Driver } from '@atscript/db-sqlite'
|
|
59
|
+
*
|
|
60
|
+
* const driver = new BetterSqlite3Driver(':memory:')
|
|
61
|
+
* const adapter = new SqliteAdapter(driver)
|
|
62
|
+
* const users = new AtscriptDbTable(UsersType, adapter)
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
declare class SqliteAdapter extends BaseDbAdapter {
|
|
66
|
+
protected readonly driver: TSqliteDriver;
|
|
67
|
+
constructor(driver: TSqliteDriver);
|
|
68
|
+
/** SQLite does not use schemas — override to always exclude schema. */
|
|
69
|
+
resolveTableName(): string;
|
|
70
|
+
prepareId(id: unknown, _fieldType: TAtscriptAnnotatedType): unknown;
|
|
71
|
+
insertOne(data: Record<string, unknown>): Promise<TDbInsertResult>;
|
|
72
|
+
insertMany(data: Array<Record<string, unknown>>): Promise<TDbInsertManyResult>;
|
|
73
|
+
findOne(filter: TDbFilter, options?: TDbFindOptions): Promise<Record<string, unknown> | null>;
|
|
74
|
+
findMany(filter: TDbFilter, options?: TDbFindOptions): Promise<Array<Record<string, unknown>>>;
|
|
75
|
+
count(filter: TDbFilter): Promise<number>;
|
|
76
|
+
updateOne(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult>;
|
|
77
|
+
updateMany(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult>;
|
|
78
|
+
replaceOne(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult>;
|
|
79
|
+
replaceMany(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult>;
|
|
80
|
+
deleteOne(filter: TDbFilter): Promise<TDbDeleteResult>;
|
|
81
|
+
deleteMany(filter: TDbFilter): Promise<TDbDeleteResult>;
|
|
82
|
+
ensureTable(): Promise<void>;
|
|
83
|
+
syncIndexes(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* {@link TSqliteDriver} implementation backed by `better-sqlite3`.
|
|
88
|
+
*
|
|
89
|
+
* Accepts either a file path (opens a new database) or a pre-created
|
|
90
|
+
* `Database` instance from `better-sqlite3`.
|
|
91
|
+
*
|
|
92
|
+
* ```typescript
|
|
93
|
+
* import { BetterSqlite3Driver } from '@atscript/db-sqlite'
|
|
94
|
+
*
|
|
95
|
+
* // In-memory database
|
|
96
|
+
* const driver = new BetterSqlite3Driver(':memory:')
|
|
97
|
+
*
|
|
98
|
+
* // File-based database
|
|
99
|
+
* const driver = new BetterSqlite3Driver('./my-data.db')
|
|
100
|
+
*
|
|
101
|
+
* // Pre-created instance
|
|
102
|
+
* import Database from 'better-sqlite3'
|
|
103
|
+
* const db = new Database(':memory:', { verbose: console.log })
|
|
104
|
+
* const driver = new BetterSqlite3Driver(db)
|
|
105
|
+
* ```
|
|
106
|
+
*
|
|
107
|
+
* Requires `better-sqlite3` to be installed:
|
|
108
|
+
* ```bash
|
|
109
|
+
* pnpm add better-sqlite3
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
declare class BetterSqlite3Driver implements TSqliteDriver {
|
|
113
|
+
private db;
|
|
114
|
+
constructor(pathOrDb: string | better_sqlite3.Database, options?: Record<string, unknown>);
|
|
115
|
+
run(sql: string, params?: unknown[]): TSqliteRunResult;
|
|
116
|
+
all<T = Record<string, unknown>>(sql: string, params?: unknown[]): T[];
|
|
117
|
+
get<T = Record<string, unknown>>(sql: string, params?: unknown[]): T | null;
|
|
118
|
+
exec(sql: string): void;
|
|
119
|
+
close(): void;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface TSqlFragment {
|
|
123
|
+
sql: string;
|
|
124
|
+
params: unknown[];
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Translates a MongoDB-style filter object into a SQL WHERE clause
|
|
128
|
+
* with parameterized values.
|
|
129
|
+
*
|
|
130
|
+
* Supports:
|
|
131
|
+
* - Equality: `{ field: value }`
|
|
132
|
+
* - Comparison: `$gt`, `$gte`, `$lt`, `$lte`, `$ne`
|
|
133
|
+
* - Set: `$in`, `$nin`
|
|
134
|
+
* - Existence: `$exists`
|
|
135
|
+
* - Pattern: `$regex` (converted to LIKE)
|
|
136
|
+
* - Logical: `$and`, `$or`, `$not`
|
|
137
|
+
*
|
|
138
|
+
* @returns `{ sql, params }` — the WHERE clause (without "WHERE") and bound params.
|
|
139
|
+
* Returns `{ sql: '1=1', params: [] }` for empty filters.
|
|
140
|
+
*/
|
|
141
|
+
declare function buildWhere(filter: TDbFilter): TSqlFragment;
|
|
142
|
+
|
|
143
|
+
export { BetterSqlite3Driver, SqliteAdapter, buildWhere };
|
|
144
|
+
export type { TSqlFragment, TSqliteDriver, TSqliteRunResult };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { BaseDbAdapter } from "@atscript/utils-db";
|
|
2
|
+
|
|
3
|
+
//#region rolldown:runtime
|
|
4
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
|
|
5
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
6
|
+
throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function.");
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region packages/db-sqlite/src/filter-builder.ts
|
|
11
|
+
function buildWhere(filter) {
|
|
12
|
+
if (!filter || Object.keys(filter).length === 0) return {
|
|
13
|
+
sql: "1=1",
|
|
14
|
+
params: []
|
|
15
|
+
};
|
|
16
|
+
const parts = [];
|
|
17
|
+
const params = [];
|
|
18
|
+
for (const [key, value] of Object.entries(filter)) if (key === "$and") {
|
|
19
|
+
const sub = value.map((f) => buildWhere(f));
|
|
20
|
+
parts.push(`(${sub.map((s) => s.sql).join(" AND ")})`);
|
|
21
|
+
for (const s of sub) params.push(...s.params);
|
|
22
|
+
} else if (key === "$or") {
|
|
23
|
+
const sub = value.map((f) => buildWhere(f));
|
|
24
|
+
parts.push(`(${sub.map((s) => s.sql).join(" OR ")})`);
|
|
25
|
+
for (const s of sub) params.push(...s.params);
|
|
26
|
+
} else if (key === "$not") {
|
|
27
|
+
const sub = buildWhere(value);
|
|
28
|
+
parts.push(`NOT (${sub.sql})`);
|
|
29
|
+
params.push(...sub.params);
|
|
30
|
+
} else if (typeof value === "object" && value !== null && !Array.isArray(value)) for (const [op, opVal] of Object.entries(value)) {
|
|
31
|
+
const fragment = buildOperator(key, op, opVal);
|
|
32
|
+
parts.push(fragment.sql);
|
|
33
|
+
params.push(...fragment.params);
|
|
34
|
+
}
|
|
35
|
+
else if (value === null) parts.push(`"${escapeIdent(key)}" IS NULL`);
|
|
36
|
+
else {
|
|
37
|
+
parts.push(`"${escapeIdent(key)}" = ?`);
|
|
38
|
+
params.push(value);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
sql: parts.join(" AND "),
|
|
42
|
+
params
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function buildOperator(field, op, value) {
|
|
46
|
+
const col = `"${escapeIdent(field)}"`;
|
|
47
|
+
switch (op) {
|
|
48
|
+
case "$gt": return {
|
|
49
|
+
sql: `${col} > ?`,
|
|
50
|
+
params: [value]
|
|
51
|
+
};
|
|
52
|
+
case "$gte": return {
|
|
53
|
+
sql: `${col} >= ?`,
|
|
54
|
+
params: [value]
|
|
55
|
+
};
|
|
56
|
+
case "$lt": return {
|
|
57
|
+
sql: `${col} < ?`,
|
|
58
|
+
params: [value]
|
|
59
|
+
};
|
|
60
|
+
case "$lte": return {
|
|
61
|
+
sql: `${col} <= ?`,
|
|
62
|
+
params: [value]
|
|
63
|
+
};
|
|
64
|
+
case "$ne": {
|
|
65
|
+
if (value === null) return {
|
|
66
|
+
sql: `${col} IS NOT NULL`,
|
|
67
|
+
params: []
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
sql: `${col} != ?`,
|
|
71
|
+
params: [value]
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
case "$in": {
|
|
75
|
+
const arr = value;
|
|
76
|
+
if (arr.length === 0) return {
|
|
77
|
+
sql: "0=1",
|
|
78
|
+
params: []
|
|
79
|
+
};
|
|
80
|
+
const placeholders = arr.map(() => "?").join(", ");
|
|
81
|
+
return {
|
|
82
|
+
sql: `${col} IN (${placeholders})`,
|
|
83
|
+
params: [...arr]
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
case "$nin": {
|
|
87
|
+
const arr = value;
|
|
88
|
+
if (arr.length === 0) return {
|
|
89
|
+
sql: "1=1",
|
|
90
|
+
params: []
|
|
91
|
+
};
|
|
92
|
+
const placeholders = arr.map(() => "?").join(", ");
|
|
93
|
+
return {
|
|
94
|
+
sql: `${col} NOT IN (${placeholders})`,
|
|
95
|
+
params: [...arr]
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
case "$exists": return value ? {
|
|
99
|
+
sql: `${col} IS NOT NULL`,
|
|
100
|
+
params: []
|
|
101
|
+
} : {
|
|
102
|
+
sql: `${col} IS NULL`,
|
|
103
|
+
params: []
|
|
104
|
+
};
|
|
105
|
+
case "$regex": {
|
|
106
|
+
const pattern = regexToLike(String(value));
|
|
107
|
+
return {
|
|
108
|
+
sql: `${col} LIKE ?`,
|
|
109
|
+
params: [pattern]
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
default: throw new Error(`Unsupported filter operator: ${op}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Basic regex-to-LIKE conversion.
|
|
117
|
+
* - `^abc` → `abc%`
|
|
118
|
+
* - `abc$` → `%abc`
|
|
119
|
+
* - `^abc$` → `abc`
|
|
120
|
+
* - `abc` → `%abc%`
|
|
121
|
+
*/ function regexToLike(pattern) {
|
|
122
|
+
const hasStart = pattern.startsWith("^");
|
|
123
|
+
const hasEnd = pattern.endsWith("$");
|
|
124
|
+
let core = pattern;
|
|
125
|
+
if (hasStart) core = core.slice(1);
|
|
126
|
+
if (hasEnd) core = core.slice(0, -1);
|
|
127
|
+
core = core.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
128
|
+
core = core.replace(/\.\*/g, "%").replace(/\./g, "_");
|
|
129
|
+
if (hasStart && hasEnd) return core;
|
|
130
|
+
if (hasStart) return `${core}%`;
|
|
131
|
+
if (hasEnd) return `%${core}`;
|
|
132
|
+
return `%${core}%`;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Escapes a SQL identifier to prevent injection.
|
|
136
|
+
* Doubles any embedded double-quotes.
|
|
137
|
+
*/ function escapeIdent(name) {
|
|
138
|
+
return name.replace(/"/g, "\"\"");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region packages/db-sqlite/src/sql-builder.ts
|
|
143
|
+
function buildInsert(table, data) {
|
|
144
|
+
const keys = Object.keys(data);
|
|
145
|
+
const cols = keys.map((k) => `"${esc$1(k)}"`).join(", ");
|
|
146
|
+
const placeholders = keys.map(() => "?").join(", ");
|
|
147
|
+
return {
|
|
148
|
+
sql: `INSERT INTO "${esc$1(table)}" (${cols}) VALUES (${placeholders})`,
|
|
149
|
+
params: keys.map((k) => toSqliteValue$1(data[k]))
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function buildSelect(table, where, options) {
|
|
153
|
+
const cols = buildProjection(options?.projection);
|
|
154
|
+
let sql = `SELECT ${cols} FROM "${esc$1(table)}" WHERE ${where.sql}`;
|
|
155
|
+
const params = [...where.params];
|
|
156
|
+
if (options?.sort) {
|
|
157
|
+
const orderParts = [];
|
|
158
|
+
for (const [col, dir] of Object.entries(options.sort)) orderParts.push(`"${esc$1(col)}" ${dir === -1 ? "DESC" : "ASC"}`);
|
|
159
|
+
if (orderParts.length > 0) sql += ` ORDER BY ${orderParts.join(", ")}`;
|
|
160
|
+
}
|
|
161
|
+
if (options?.limit !== undefined) {
|
|
162
|
+
sql += ` LIMIT ?`;
|
|
163
|
+
params.push(options.limit);
|
|
164
|
+
}
|
|
165
|
+
if (options?.skip !== undefined) {
|
|
166
|
+
if (options.limit === undefined) sql += ` LIMIT -1`;
|
|
167
|
+
sql += ` OFFSET ?`;
|
|
168
|
+
params.push(options.skip);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
sql,
|
|
172
|
+
params
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function buildUpdate(table, data, where) {
|
|
176
|
+
const setClauses = [];
|
|
177
|
+
const params = [];
|
|
178
|
+
for (const [key, value] of Object.entries(data)) {
|
|
179
|
+
setClauses.push(`"${esc$1(key)}" = ?`);
|
|
180
|
+
params.push(toSqliteValue$1(value));
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
sql: `UPDATE "${esc$1(table)}" SET ${setClauses.join(", ")} WHERE ${where.sql}`,
|
|
184
|
+
params: [...params, ...where.params]
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function buildDelete(table, where) {
|
|
188
|
+
return {
|
|
189
|
+
sql: `DELETE FROM "${esc$1(table)}" WHERE ${where.sql}`,
|
|
190
|
+
params: [...where.params]
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function buildCreateTable(table, fields) {
|
|
194
|
+
const colDefs = [];
|
|
195
|
+
const primaryKeys = fields.filter((f) => f.isPrimaryKey);
|
|
196
|
+
for (const field of fields) {
|
|
197
|
+
if (field.ignored) continue;
|
|
198
|
+
const sqlType = sqliteTypeFromDesignType(field.designType);
|
|
199
|
+
let def = `"${esc$1(field.physicalName)}" ${sqlType}`;
|
|
200
|
+
if (field.isPrimaryKey && primaryKeys.length === 1) def += " PRIMARY KEY";
|
|
201
|
+
if (!field.optional && !field.isPrimaryKey) def += " NOT NULL";
|
|
202
|
+
colDefs.push(def);
|
|
203
|
+
}
|
|
204
|
+
if (primaryKeys.length > 1) {
|
|
205
|
+
const pkCols = primaryKeys.map((pk) => `"${esc$1(pk.physicalName)}"`).join(", ");
|
|
206
|
+
colDefs.push(`PRIMARY KEY (${pkCols})`);
|
|
207
|
+
}
|
|
208
|
+
return `CREATE TABLE IF NOT EXISTS "${esc$1(table)}" (${colDefs.join(", ")})`;
|
|
209
|
+
}
|
|
210
|
+
function sqliteTypeFromDesignType(designType) {
|
|
211
|
+
switch (designType) {
|
|
212
|
+
case "number":
|
|
213
|
+
case "integer": return "REAL";
|
|
214
|
+
case "boolean": return "INTEGER";
|
|
215
|
+
case "string": return "TEXT";
|
|
216
|
+
default: return "TEXT";
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function buildProjection(projection) {
|
|
220
|
+
if (!projection) return "*";
|
|
221
|
+
if (Array.isArray(projection)) {
|
|
222
|
+
if (projection.length === 0) return "*";
|
|
223
|
+
return projection.map((k) => `"${esc$1(k)}"`).join(", ");
|
|
224
|
+
}
|
|
225
|
+
const entries = Object.entries(projection);
|
|
226
|
+
if (entries.length === 0) return "*";
|
|
227
|
+
const firstVal = entries[0][1];
|
|
228
|
+
if (firstVal === 1) return entries.filter(([_, v]) => v === 1).map(([k]) => `"${esc$1(k)}"`).join(", ");
|
|
229
|
+
return "*";
|
|
230
|
+
}
|
|
231
|
+
function esc$1(name) {
|
|
232
|
+
return name.replace(/"/g, "\"\"");
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Converts a JS value to a SQLite-compatible value.
|
|
236
|
+
* Objects and arrays are stored as JSON strings.
|
|
237
|
+
*/ function toSqliteValue$1(value) {
|
|
238
|
+
if (value === undefined) return null;
|
|
239
|
+
if (value === null) return null;
|
|
240
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
241
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
242
|
+
return value;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region packages/db-sqlite/src/sqlite-adapter.ts
|
|
247
|
+
function _define_property$1(obj, key, value) {
|
|
248
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
249
|
+
value,
|
|
250
|
+
enumerable: true,
|
|
251
|
+
configurable: true,
|
|
252
|
+
writable: true
|
|
253
|
+
});
|
|
254
|
+
else obj[key] = value;
|
|
255
|
+
return obj;
|
|
256
|
+
}
|
|
257
|
+
var SqliteAdapter = class extends BaseDbAdapter {
|
|
258
|
+
/** SQLite does not use schemas — override to always exclude schema. */ resolveTableName() {
|
|
259
|
+
return super.resolveTableName(false);
|
|
260
|
+
}
|
|
261
|
+
prepareId(id, _fieldType) {
|
|
262
|
+
return id;
|
|
263
|
+
}
|
|
264
|
+
async insertOne(data) {
|
|
265
|
+
const { sql, params } = buildInsert(this.resolveTableName(), data);
|
|
266
|
+
const result = this.driver.run(sql, params);
|
|
267
|
+
return { insertedId: result.lastInsertRowid };
|
|
268
|
+
}
|
|
269
|
+
async insertMany(data) {
|
|
270
|
+
const ids = [];
|
|
271
|
+
this.driver.exec("BEGIN");
|
|
272
|
+
try {
|
|
273
|
+
for (const row of data) {
|
|
274
|
+
const { sql, params } = buildInsert(this.resolveTableName(), row);
|
|
275
|
+
const result = this.driver.run(sql, params);
|
|
276
|
+
ids.push(result.lastInsertRowid);
|
|
277
|
+
}
|
|
278
|
+
this.driver.exec("COMMIT");
|
|
279
|
+
} catch (error) {
|
|
280
|
+
this.driver.exec("ROLLBACK");
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
insertedCount: ids.length,
|
|
285
|
+
insertedIds: ids
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
async findOne(filter, options) {
|
|
289
|
+
const where = buildWhere(filter);
|
|
290
|
+
const { sql, params } = buildSelect(this.resolveTableName(), where, {
|
|
291
|
+
...options,
|
|
292
|
+
limit: 1
|
|
293
|
+
});
|
|
294
|
+
return this.driver.get(sql, params);
|
|
295
|
+
}
|
|
296
|
+
async findMany(filter, options) {
|
|
297
|
+
const where = buildWhere(filter);
|
|
298
|
+
const { sql, params } = buildSelect(this.resolveTableName(), where, options);
|
|
299
|
+
return this.driver.all(sql, params);
|
|
300
|
+
}
|
|
301
|
+
async count(filter) {
|
|
302
|
+
const where = buildWhere(filter);
|
|
303
|
+
const tableName = this.resolveTableName();
|
|
304
|
+
const sql = `SELECT COUNT(*) as cnt FROM "${esc(tableName)}" WHERE ${where.sql}`;
|
|
305
|
+
const row = this.driver.get(sql, where.params);
|
|
306
|
+
return row?.cnt ?? 0;
|
|
307
|
+
}
|
|
308
|
+
async updateOne(filter, data) {
|
|
309
|
+
const where = buildWhere(filter);
|
|
310
|
+
const tableName = this.resolveTableName();
|
|
311
|
+
const setClauses = [];
|
|
312
|
+
const setParams = [];
|
|
313
|
+
for (const [key, value] of Object.entries(data)) {
|
|
314
|
+
setClauses.push(`"${esc(key)}" = ?`);
|
|
315
|
+
setParams.push(toSqliteValue(value));
|
|
316
|
+
}
|
|
317
|
+
const sql = `UPDATE "${esc(tableName)}" SET ${setClauses.join(", ")} WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
318
|
+
const result = this.driver.run(sql, [...setParams, ...where.params]);
|
|
319
|
+
return {
|
|
320
|
+
matchedCount: result.changes,
|
|
321
|
+
modifiedCount: result.changes
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
async updateMany(filter, data) {
|
|
325
|
+
const where = buildWhere(filter);
|
|
326
|
+
const { sql, params } = buildUpdate(this.resolveTableName(), data, where);
|
|
327
|
+
const result = this.driver.run(sql, params);
|
|
328
|
+
return {
|
|
329
|
+
matchedCount: result.changes,
|
|
330
|
+
modifiedCount: result.changes
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
async replaceOne(filter, data) {
|
|
334
|
+
const where = buildWhere(filter);
|
|
335
|
+
const tableName = this.resolveTableName();
|
|
336
|
+
this.driver.exec("BEGIN");
|
|
337
|
+
try {
|
|
338
|
+
const delSql = `DELETE FROM "${esc(tableName)}" WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
339
|
+
const delResult = this.driver.run(delSql, where.params);
|
|
340
|
+
if (delResult.changes > 0) {
|
|
341
|
+
const { sql, params } = buildInsert(tableName, data);
|
|
342
|
+
this.driver.run(sql, params);
|
|
343
|
+
}
|
|
344
|
+
this.driver.exec("COMMIT");
|
|
345
|
+
return {
|
|
346
|
+
matchedCount: delResult.changes,
|
|
347
|
+
modifiedCount: delResult.changes
|
|
348
|
+
};
|
|
349
|
+
} catch (error) {
|
|
350
|
+
this.driver.exec("ROLLBACK");
|
|
351
|
+
throw error;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
async replaceMany(filter, data) {
|
|
355
|
+
const where = buildWhere(filter);
|
|
356
|
+
const { sql, params } = buildUpdate(this.resolveTableName(), data, where);
|
|
357
|
+
const result = this.driver.run(sql, params);
|
|
358
|
+
return {
|
|
359
|
+
matchedCount: result.changes,
|
|
360
|
+
modifiedCount: result.changes
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
async deleteOne(filter) {
|
|
364
|
+
const where = buildWhere(filter);
|
|
365
|
+
const tableName = this.resolveTableName();
|
|
366
|
+
const sql = `DELETE FROM "${esc(tableName)}" WHERE rowid = (SELECT rowid FROM "${esc(tableName)}" WHERE ${where.sql} LIMIT 1)`;
|
|
367
|
+
const result = this.driver.run(sql, where.params);
|
|
368
|
+
return { deletedCount: result.changes };
|
|
369
|
+
}
|
|
370
|
+
async deleteMany(filter) {
|
|
371
|
+
const where = buildWhere(filter);
|
|
372
|
+
const { sql, params } = buildDelete(this.resolveTableName(), where);
|
|
373
|
+
const result = this.driver.run(sql, params);
|
|
374
|
+
return { deletedCount: result.changes };
|
|
375
|
+
}
|
|
376
|
+
async ensureTable() {
|
|
377
|
+
const sql = buildCreateTable(this.resolveTableName(), this._table.fieldDescriptors);
|
|
378
|
+
this.driver.exec(sql);
|
|
379
|
+
}
|
|
380
|
+
async syncIndexes() {
|
|
381
|
+
const tableName = this.resolveTableName();
|
|
382
|
+
const columnMap = this._table.columnMap;
|
|
383
|
+
await this.syncIndexesWithDiff({
|
|
384
|
+
listExisting: async () => this.driver.all(`PRAGMA index_list("${esc(tableName)}")`).filter((i) => !i.name.startsWith("sqlite_")),
|
|
385
|
+
createIndex: async (index) => {
|
|
386
|
+
const unique = index.type === "unique" ? "UNIQUE " : "";
|
|
387
|
+
const cols = index.fields.map((f) => {
|
|
388
|
+
const physical = columnMap.get(f.name) ?? f.name;
|
|
389
|
+
return `"${esc(physical)}" ${f.sort === "desc" ? "DESC" : "ASC"}`;
|
|
390
|
+
}).join(", ");
|
|
391
|
+
this.driver.exec(`CREATE ${unique}INDEX IF NOT EXISTS "${esc(index.key)}" ON "${esc(tableName)}" (${cols})`);
|
|
392
|
+
},
|
|
393
|
+
dropIndex: async (name) => {
|
|
394
|
+
this.driver.exec(`DROP INDEX IF EXISTS "${esc(name)}"`);
|
|
395
|
+
},
|
|
396
|
+
shouldSkipType: (type) => type === "fulltext"
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
constructor(driver) {
|
|
400
|
+
super(), _define_property$1(this, "driver", void 0), this.driver = driver;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
function esc(name) {
|
|
404
|
+
return name.replace(/"/g, "\"\"");
|
|
405
|
+
}
|
|
406
|
+
function toSqliteValue(value) {
|
|
407
|
+
if (value === undefined) return null;
|
|
408
|
+
if (value === null) return null;
|
|
409
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
410
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
411
|
+
return value;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region packages/db-sqlite/src/better-sqlite3-driver.ts
|
|
416
|
+
function _define_property(obj, key, value) {
|
|
417
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
418
|
+
value,
|
|
419
|
+
enumerable: true,
|
|
420
|
+
configurable: true,
|
|
421
|
+
writable: true
|
|
422
|
+
});
|
|
423
|
+
else obj[key] = value;
|
|
424
|
+
return obj;
|
|
425
|
+
}
|
|
426
|
+
var BetterSqlite3Driver = class {
|
|
427
|
+
run(sql, params) {
|
|
428
|
+
const stmt = this.db.prepare(sql);
|
|
429
|
+
const result = params ? stmt.run(...params) : stmt.run();
|
|
430
|
+
return {
|
|
431
|
+
changes: result.changes,
|
|
432
|
+
lastInsertRowid: result.lastInsertRowid
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
all(sql, params) {
|
|
436
|
+
const stmt = this.db.prepare(sql);
|
|
437
|
+
return params ? stmt.all(...params) : stmt.all();
|
|
438
|
+
}
|
|
439
|
+
get(sql, params) {
|
|
440
|
+
const stmt = this.db.prepare(sql);
|
|
441
|
+
return (params ? stmt.get(...params) : stmt.get()) ?? null;
|
|
442
|
+
}
|
|
443
|
+
exec(sql) {
|
|
444
|
+
this.db.exec(sql);
|
|
445
|
+
}
|
|
446
|
+
close() {
|
|
447
|
+
this.db.close();
|
|
448
|
+
}
|
|
449
|
+
constructor(pathOrDb, options) {
|
|
450
|
+
_define_property(this, "db", void 0);
|
|
451
|
+
if (typeof pathOrDb === "string") {
|
|
452
|
+
const Database = __require("better-sqlite3");
|
|
453
|
+
this.db = new Database(pathOrDb, options);
|
|
454
|
+
} else this.db = pathOrDb;
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
//#endregion
|
|
459
|
+
export { BetterSqlite3Driver, SqliteAdapter, buildWhere };
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@atscript/db-sqlite",
|
|
3
|
+
"version": "0.1.28",
|
|
4
|
+
"description": "SQLite adapter for @atscript/utils-db with swappable driver support.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"atscript",
|
|
7
|
+
"database",
|
|
8
|
+
"sqlite"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://github.com/moostjs/atscript/tree/main/packages/db-sqlite#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/moostjs/atscript/issues"
|
|
13
|
+
},
|
|
14
|
+
"license": "ISC",
|
|
15
|
+
"author": "Artem Maltsev",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/moostjs/atscript.git",
|
|
19
|
+
"directory": "packages/db-sqlite"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "dist/index.mjs",
|
|
26
|
+
"types": "dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.mjs",
|
|
31
|
+
"require": "./dist/index.cjs"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"better-sqlite3": "^12.6.2",
|
|
37
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
38
|
+
"vitest": "3.2.4"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"better-sqlite3": ">=11.0.0",
|
|
42
|
+
"@atscript/core": "^0.1.28",
|
|
43
|
+
"@atscript/utils-db": "^0.1.28",
|
|
44
|
+
"@atscript/typescript": "^0.1.28"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"better-sqlite3": {
|
|
48
|
+
"optional": true
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"pub": "pnpm publish --access public",
|
|
53
|
+
"test": "vitest"
|
|
54
|
+
}
|
|
55
|
+
}
|