@atscript/utils-db 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 +320 -0
- package/dist/index.cjs +595 -0
- package/dist/index.d.ts +488 -0
- package/dist/index.mjs +566 -0
- package/package.json +46 -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,320 @@
|
|
|
1
|
+
# @atscript/utils-db
|
|
2
|
+
|
|
3
|
+
Generic database abstraction layer for Atscript. Provides a unified CRUD interface driven by `@db.*` annotations, with pluggable database adapters.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Full-stack Atscript projects define data models with `@db.*` annotations — table names, indexes, column mappings, defaults, primary keys. This package extracts all that metadata and provides:
|
|
8
|
+
|
|
9
|
+
- **`AtscriptDbTable`** — a concrete class that reads `@db.*` annotations, pre-computes indexes and field metadata, orchestrates validation/defaults/column mapping, and delegates actual database calls to an adapter.
|
|
10
|
+
- **`BaseDbAdapter`** — an abstract class that adapter authors extend to connect any database (MongoDB, SQLite, MySQL, PostgreSQL, etc.).
|
|
11
|
+
|
|
12
|
+
The same annotated type works with any adapter. Cross-cutting concerns (field-level permissions, audit logging, soft deletes) are added by subclassing `AtscriptDbTable` — they work with every adapter automatically.
|
|
13
|
+
|
|
14
|
+
## Architecture
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
AtscriptDbTable ──delegates CRUD──▶ BaseDbAdapter
|
|
18
|
+
◀──reads metadata── (via this._table)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**One adapter per table.** The adapter gets a back-reference to the table instance via `registerTable()`, giving it full access to computed metadata (flatMap, indexes, primaryKeys, columnMap, etc.) for internal use in query rendering, index sync, and other adapter-specific logic.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm add @atscript/utils-db
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Peer dependencies: `@atscript/core`, `@atscript/typescript`.
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
### 1. Define your type in Atscript (`.as` file)
|
|
34
|
+
|
|
35
|
+
```atscript
|
|
36
|
+
@db.table "users"
|
|
37
|
+
@db.schema "auth"
|
|
38
|
+
interface User {
|
|
39
|
+
@meta.id
|
|
40
|
+
id: number
|
|
41
|
+
|
|
42
|
+
@db.index.unique "email_idx"
|
|
43
|
+
@db.column "email_address"
|
|
44
|
+
email: string
|
|
45
|
+
|
|
46
|
+
@db.index.plain "name_idx"
|
|
47
|
+
name: string
|
|
48
|
+
|
|
49
|
+
@db.default.value "active"
|
|
50
|
+
status: string
|
|
51
|
+
|
|
52
|
+
@db.ignore
|
|
53
|
+
displayName?: string
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 2. Create an adapter and table
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { AtscriptDbTable } from '@atscript/utils-db'
|
|
61
|
+
import { MyAdapter } from './my-adapter'
|
|
62
|
+
import { User } from './user.as'
|
|
63
|
+
|
|
64
|
+
const adapter = new MyAdapter(/* db connection */)
|
|
65
|
+
const users = new AtscriptDbTable(User, adapter)
|
|
66
|
+
|
|
67
|
+
// CRUD operations
|
|
68
|
+
await users.insertOne({ name: 'John', email: 'john@example.com' })
|
|
69
|
+
await users.findMany({ status: 'active' }, { limit: 10 })
|
|
70
|
+
await users.deleteOne(123)
|
|
71
|
+
await users.syncIndexes()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Writing a Database Adapter
|
|
75
|
+
|
|
76
|
+
Extend `BaseDbAdapter` and implement the abstract methods. The adapter receives a back-reference to the `AtscriptDbTable` instance — use `this._table` to access all computed metadata.
|
|
77
|
+
|
|
78
|
+
### Minimal adapter
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import {
|
|
82
|
+
BaseDbAdapter,
|
|
83
|
+
type TDbFilter,
|
|
84
|
+
type TDbFindOptions,
|
|
85
|
+
type TDbInsertResult,
|
|
86
|
+
type TDbInsertManyResult,
|
|
87
|
+
type TDbUpdateResult,
|
|
88
|
+
type TDbDeleteResult,
|
|
89
|
+
} from '@atscript/utils-db'
|
|
90
|
+
|
|
91
|
+
class SqliteAdapter extends BaseDbAdapter {
|
|
92
|
+
constructor(private db: SqliteDatabase) {
|
|
93
|
+
super()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Access table metadata via this._table:
|
|
97
|
+
// this._table.tableName — resolved table name
|
|
98
|
+
// this._table.schema — database schema/namespace
|
|
99
|
+
// this._table.flatMap — Map<string, TAtscriptAnnotatedType>
|
|
100
|
+
// this._table.indexes — Map<string, TDbIndex>
|
|
101
|
+
// this._table.primaryKeys — readonly string[]
|
|
102
|
+
// this._table.columnMap — Map<string, string> (logical → physical)
|
|
103
|
+
// this._table.defaults — Map<string, TDbDefaultValue>
|
|
104
|
+
// this._table.ignoredFields — Set<string>
|
|
105
|
+
// this._table.uniqueProps — Set<string>
|
|
106
|
+
|
|
107
|
+
async insertOne(data: Record<string, unknown>): Promise<TDbInsertResult> {
|
|
108
|
+
const table = this._table.tableName
|
|
109
|
+
const keys = Object.keys(data)
|
|
110
|
+
const placeholders = keys.map(() => '?').join(', ')
|
|
111
|
+
const sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders})`
|
|
112
|
+
const result = this.db.run(sql, Object.values(data))
|
|
113
|
+
return { insertedId: result.lastInsertRowid }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async insertMany(data: Record<string, unknown>[]): Promise<TDbInsertManyResult> {
|
|
117
|
+
const ids: unknown[] = []
|
|
118
|
+
for (const row of data) {
|
|
119
|
+
const result = await this.insertOne(row)
|
|
120
|
+
ids.push(result.insertedId)
|
|
121
|
+
}
|
|
122
|
+
return { insertedCount: ids.length, insertedIds: ids }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async findOne(
|
|
126
|
+
filter: TDbFilter,
|
|
127
|
+
options?: TDbFindOptions
|
|
128
|
+
): Promise<Record<string, unknown> | null> {
|
|
129
|
+
const { sql, params } = this.buildSelect(filter, { ...options, limit: 1 })
|
|
130
|
+
return this.db.get(sql, params) ?? null
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async findMany(
|
|
134
|
+
filter: TDbFilter,
|
|
135
|
+
options?: TDbFindOptions
|
|
136
|
+
): Promise<Record<string, unknown>[]> {
|
|
137
|
+
const { sql, params } = this.buildSelect(filter, options)
|
|
138
|
+
return this.db.all(sql, params)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async updateOne(
|
|
142
|
+
filter: TDbFilter,
|
|
143
|
+
data: Record<string, unknown>
|
|
144
|
+
): Promise<TDbUpdateResult> {
|
|
145
|
+
// ... build UPDATE ... SET ... WHERE ...
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async replaceOne(
|
|
149
|
+
filter: TDbFilter,
|
|
150
|
+
data: Record<string, unknown>
|
|
151
|
+
): Promise<TDbUpdateResult> {
|
|
152
|
+
// ... INSERT OR REPLACE ...
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async deleteOne(filter: TDbFilter): Promise<TDbDeleteResult> {
|
|
156
|
+
// ... DELETE FROM ... WHERE ...
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async count(filter: TDbFilter): Promise<number> {
|
|
160
|
+
// ... SELECT COUNT(*) ...
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async updateMany(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult> {
|
|
164
|
+
// ... UPDATE ... SET ... WHERE ...
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async replaceMany(filter: TDbFilter, data: Record<string, unknown>): Promise<TDbUpdateResult> {
|
|
168
|
+
// ... batch replace ...
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async deleteMany(filter: TDbFilter): Promise<TDbDeleteResult> {
|
|
172
|
+
// ... DELETE FROM ... WHERE ...
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async syncIndexes(): Promise<void> {
|
|
176
|
+
// Read this._table.indexes and CREATE INDEX / DROP INDEX as needed
|
|
177
|
+
for (const [key, index] of this._table.indexes) {
|
|
178
|
+
const cols = index.fields.map(f =>
|
|
179
|
+
`${f.name} ${f.sort === 'desc' ? 'DESC' : 'ASC'}`
|
|
180
|
+
).join(', ')
|
|
181
|
+
const unique = index.type === 'unique' ? 'UNIQUE' : ''
|
|
182
|
+
this.db.run(
|
|
183
|
+
`CREATE ${unique} INDEX IF NOT EXISTS ${index.name}
|
|
184
|
+
ON ${this._table.tableName} (${cols})`
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async ensureTable(): Promise<void> {
|
|
190
|
+
// Use this._table.flatMap, primaryKeys, etc. to build CREATE TABLE
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Adapter hooks
|
|
196
|
+
|
|
197
|
+
Override these optional methods to process adapter-specific annotations during field scanning:
|
|
198
|
+
|
|
199
|
+
| Hook | When it runs | Use case |
|
|
200
|
+
|---|---|---|
|
|
201
|
+
| `onBeforeFlatten(type)` | Before field scanning begins | Extract table-level adapter annotations |
|
|
202
|
+
| `onFieldScanned(field, type, metadata)` | For each field during scanning | Extract field-level adapter annotations |
|
|
203
|
+
| `onAfterFlatten()` | After all fields are scanned | Finalize adapter-specific computed state |
|
|
204
|
+
| `getAdapterTableName(type)` | During constructor | Return adapter-specific table name (e.g., from `@db.mongo.collection`) |
|
|
205
|
+
| `getTopLevelArrayTag()` | During flatten | Return custom tag for top-level array detection |
|
|
206
|
+
|
|
207
|
+
### Overridable behaviors
|
|
208
|
+
|
|
209
|
+
| Method | Default | Override to... |
|
|
210
|
+
|---|---|---|
|
|
211
|
+
| `prepareId(id, fieldType)` | passthrough | Convert string → ObjectId, parse UUIDs, etc. |
|
|
212
|
+
| `getValidatorPlugins()` | `[]` | Add adapter-specific validation (e.g., ObjectId format) |
|
|
213
|
+
| `supportsNativePatch()` | `false` | Enable native array patch operations |
|
|
214
|
+
| `nativePatch(filter, patch)` | throws | Implement native patch (e.g., MongoDB `$push`/`$pull`) |
|
|
215
|
+
|
|
216
|
+
## What `AtscriptDbTable` Does For You
|
|
217
|
+
|
|
218
|
+
When you call `insertOne(payload)`, the table automatically:
|
|
219
|
+
|
|
220
|
+
1. **Flattens** the annotated type (lazy, cached) — extracts all fields, indexes, metadata
|
|
221
|
+
2. **Applies defaults** — fills `@db.default.value` fields that are missing
|
|
222
|
+
3. **Validates** — runs Atscript validators + adapter plugins
|
|
223
|
+
4. **Prepares IDs** — calls `adapter.prepareId()` on primary key fields
|
|
224
|
+
5. **Strips ignored fields** — removes `@db.ignore` fields
|
|
225
|
+
6. **Maps columns** — renames `@db.column` logical names to physical names
|
|
226
|
+
7. **Delegates** — calls `adapter.insertOne()` with the cleaned data
|
|
227
|
+
|
|
228
|
+
For `updateOne()`, it additionally:
|
|
229
|
+
- Extracts a filter from primary key fields in the payload
|
|
230
|
+
- Routes to `adapter.nativePatch()` if supported, otherwise decomposes the patch generically
|
|
231
|
+
|
|
232
|
+
## Supported Annotations
|
|
233
|
+
|
|
234
|
+
These `@db.*` annotations are defined in `@atscript/core` and processed by `AtscriptDbTable`:
|
|
235
|
+
|
|
236
|
+
| Annotation | Level | Purpose |
|
|
237
|
+
|---|---|---|
|
|
238
|
+
| `@db.table "name"` | Interface | Table/collection name |
|
|
239
|
+
| `@db.schema "name"` | Interface | Database schema/namespace |
|
|
240
|
+
| `@meta.id` | Field | Marks primary key (no args; multiple = composite key) |
|
|
241
|
+
| `@db.column "name"` | Field | Physical column name override |
|
|
242
|
+
| `@db.default.value "val"` | Field | Default value on insert |
|
|
243
|
+
| `@db.default.fn "now"` | Field | Default function (`now`, `uuid`, `increment`) |
|
|
244
|
+
| `@db.ignore` | Field | Exclude from database operations |
|
|
245
|
+
| `@db.index.plain "name"` | Field | B-tree index (optional sort: `"name", "desc"`) |
|
|
246
|
+
| `@db.index.unique "name"` | Field | Unique index |
|
|
247
|
+
| `@db.index.fulltext "name"` | Field | Full-text search index |
|
|
248
|
+
|
|
249
|
+
Multiple fields with the same index name form a **composite index**.
|
|
250
|
+
|
|
251
|
+
## Cross-Cutting Concerns
|
|
252
|
+
|
|
253
|
+
Since `AtscriptDbTable` is concrete, extend it for cross-cutting concerns that work with any adapter:
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
class SecureDbTable extends AtscriptDbTable {
|
|
257
|
+
constructor(type, adapter, private permissions: PermissionConfig) {
|
|
258
|
+
super(type, adapter)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async insertOne(payload) {
|
|
262
|
+
this.checkPermission('write', payload)
|
|
263
|
+
return super.insertOne(payload)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async findOne(filter, options) {
|
|
267
|
+
const result = await super.findOne(filter, options)
|
|
268
|
+
return result ? this.filterFields(result, 'read') : null
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Works with any adapter:
|
|
273
|
+
const secureUsers = new SecureDbTable(User, new MongoAdapter(db), perms)
|
|
274
|
+
const secureOrders = new SecureDbTable(Order, new SqliteAdapter(db), perms)
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Array Patch Operations
|
|
278
|
+
|
|
279
|
+
For fields that are arrays of objects, `updateOne()` supports structured patch operators:
|
|
280
|
+
|
|
281
|
+
```typescript
|
|
282
|
+
await users.updateOne({
|
|
283
|
+
id: 123,
|
|
284
|
+
tags: {
|
|
285
|
+
$insert: [{ name: 'new-tag' }], // append items
|
|
286
|
+
$upsert: [{ name: 'existing', value: 1 }], // insert or replace by key
|
|
287
|
+
$update: [{ name: 'existing', value: 2 }], // partial update by key
|
|
288
|
+
$remove: [{ name: 'old-tag' }], // remove by key
|
|
289
|
+
$replace: [/* full replacement */], // replace entire array
|
|
290
|
+
}
|
|
291
|
+
})
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Array element identity uses `@expect.array.key` annotations. Adapters with native patch support (e.g., MongoDB's `$push`/`$pull`) can implement `nativePatch()` for optimal performance. Otherwise, `decomposePatch()` provides a generic decomposition.
|
|
295
|
+
|
|
296
|
+
## Exports
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
// Classes
|
|
300
|
+
export { AtscriptDbTable } from './db-table'
|
|
301
|
+
export { BaseDbAdapter } from './base-adapter'
|
|
302
|
+
|
|
303
|
+
// Utilities
|
|
304
|
+
export { decomposePatch } from './patch-decomposer'
|
|
305
|
+
export { getKeyProps } from './patch-types'
|
|
306
|
+
|
|
307
|
+
// Types
|
|
308
|
+
export type {
|
|
309
|
+
TDbFilter, TDbFindOptions,
|
|
310
|
+
TDbInsertResult, TDbInsertManyResult, TDbUpdateResult, TDbDeleteResult,
|
|
311
|
+
TDbIndex, TDbIndexField, TDbDefaultValue, TIdDescriptor, TDbFieldMeta,
|
|
312
|
+
TArrayPatch, TDbPatch,
|
|
313
|
+
} from './types'
|
|
314
|
+
export type { TGenericLogger } from './logger'
|
|
315
|
+
export { NoopLogger } from './logger'
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
## License
|
|
319
|
+
|
|
320
|
+
ISC
|