lines-db 0.0.0-stage → 0.18.0
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/CHANGELOG.md +437 -0
- package/LICENSE +21 -0
- package/README.ja.md +621 -0
- package/README.md +619 -2
- package/bin/cli.mjs +3725 -0
- package/dist/index.d.mts +880 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2846 -0
- package/dist/index.mjs.map +1 -0
- package/dist/internal.d.mts +6 -0
- package/dist/internal.d.mts.map +1 -0
- package/dist/internal.mjs +1 -0
- package/dist/jsonl-reader-CoYEJ9pg.d.mts +186 -0
- package/dist/jsonl-reader-CoYEJ9pg.d.mts.map +1 -0
- package/dist/replace-file-AWLIm7aN.mjs +203 -0
- package/dist/replace-file-AWLIm7aN.mjs.map +1 -0
- package/package.json +72 -3
package/README.md
CHANGED
|
@@ -1,3 +1,620 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lines-db
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[日本語](./README.ja.md)
|
|
4
|
+
|
|
5
|
+
lines-db loads JSONL files into SQLite tables and writes changes back to their source files. Use it for seed data and test fixtures that you keep in files.
|
|
6
|
+
|
|
7
|
+
Columns are inferred from the rows. Define a schema with a Standard Schema library such as Valibot or Zod to validate rows and generate TypeScript types. Objects and arrays are stored as JSON columns. Schemas can transform values on load and convert them back when saving.
|
|
8
|
+
|
|
9
|
+
The CLI validates, migrates, fills missing values, and generates types. Install `@lines-db/studio` to edit data in a browser, or use the [VS Code extension](https://marketplace.visualstudio.com/items?itemName=toiroakr.lines-db-vscode) for validation in the editor.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
Requires Node.js 22.18.0 or later.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install lines-db
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
With pnpm, use `pnpm add lines-db`.
|
|
20
|
+
|
|
21
|
+
## CLI usage
|
|
22
|
+
|
|
23
|
+
### Define schemas
|
|
24
|
+
|
|
25
|
+
Place a schema file next to the JSONL file, using the same table name.
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
data/
|
|
29
|
+
├── users.jsonl
|
|
30
|
+
├── users.schema.ts
|
|
31
|
+
├── products.jsonl
|
|
32
|
+
└── products.schema.ts
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The following `users.schema.ts` uses Valibot. Add it with `npm install valibot`.
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import * as v from 'valibot';
|
|
39
|
+
import { defineSchema } from 'lines-db';
|
|
40
|
+
|
|
41
|
+
export const schema = defineSchema(
|
|
42
|
+
v.object({
|
|
43
|
+
id: v.pipe(v.number(), v.integer(), v.minValue(1)),
|
|
44
|
+
name: v.pipe(v.string(), v.minLength(1)),
|
|
45
|
+
age: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(150)),
|
|
46
|
+
email: v.pipe(v.string(), v.email()),
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
export default schema;
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Any library implementing [Standard Schema](https://standardschema.dev/) can be used.
|
|
53
|
+
|
|
54
|
+
`initialize()` fails if a schema file cannot be imported or does not export a Standard Schema as `schema` or `default`. The error includes the file and the reason.
|
|
55
|
+
|
|
56
|
+
### Validate JSONL files
|
|
57
|
+
|
|
58
|
+
Validate a file, or all JSONL files in a directory, against their schemas.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npx lines-db validate <path>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
npx lines-db validate ./data
|
|
66
|
+
|
|
67
|
+
npx lines-db validate ./data/users.jsonl
|
|
68
|
+
|
|
69
|
+
npx lines-db validate ./data --verbose
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The command loads the corresponding schema files and checks each row. Validation errors include the file and details of the failure.
|
|
73
|
+
|
|
74
|
+
#### Validate named datasets
|
|
75
|
+
|
|
76
|
+
Define shared data and scenario data in `lines-db.config.json`:
|
|
77
|
+
|
|
78
|
+
```json
|
|
79
|
+
{
|
|
80
|
+
"schemaDir": "./data",
|
|
81
|
+
"base": ["./data"],
|
|
82
|
+
"datasets": {
|
|
83
|
+
"cogs": ["./data/cogs"],
|
|
84
|
+
"sales": ["./data/sales"]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Omit the positional path to read `lines-db.config.json` in the current working directory and validate only `base`.
|
|
90
|
+
`--dataset <name>` adds the named dataset to `base`; repeat the flag to combine several sets in the specified order. `--all-datasets` combines `base` and every dataset in one
|
|
91
|
+
validation run; IDs shared by different scenarios will cause duplicate errors.
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx lines-db validate
|
|
95
|
+
npx lines-db validate --dataset cogs
|
|
96
|
+
npx lines-db validate --dataset cogs --dataset sales
|
|
97
|
+
npx lines-db validate --all-datasets
|
|
98
|
+
npx lines-db validate --config ./seed/lines-db.config.json --dataset cogs
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Use `--config <path>` to select another configuration file. `schemaDir`, `base` and `datasets` are required.
|
|
102
|
+
`base` and each dataset must contain at least one directory; use `datasets: {}` when there are no additional sets.
|
|
103
|
+
Relative paths are resolved from the configuration file's directory. Directories are loaded in base-then-dataset
|
|
104
|
+
order, with each directory loaded only once. Subdirectories are not discovered automatically. Schemas, unique
|
|
105
|
+
constraints and foreign keys are checked across the combined data, and errors identify the original file.
|
|
106
|
+
|
|
107
|
+
Combining `--dataset` with `--all-datasets`, or using configuration options with a positional path, is an error.
|
|
108
|
+
Unknown dataset names and invalid configurations also fail. Existing `validate <path>` commands keep working
|
|
109
|
+
without reading a configuration file. Only the `validate` CLI command uses this configuration.
|
|
110
|
+
|
|
111
|
+
Programs can load the same configuration with `loadDatasetConfig()`:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { LinesDB, loadDatasetConfig } from 'lines-db';
|
|
115
|
+
|
|
116
|
+
const config = await loadDatasetConfig('./lines-db.config.json', {
|
|
117
|
+
datasets: ['cogs', 'sales'],
|
|
118
|
+
});
|
|
119
|
+
const db = LinesDB.create(config);
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Omit `datasets` or pass `[]` for base only. An array combines base and the selected sets in array order;
|
|
123
|
+
`'all'` combines base and every set in configuration order. Each directory is loaded once, including symlink aliases.
|
|
124
|
+
Calling `loadDatasetConfig()` without arguments reads `lines-db.config.json` in the current working directory.
|
|
125
|
+
It returns `Promise<DatabaseConfig>` and rejects unreadable or invalid configuration, unknown set names and missing
|
|
126
|
+
selected data directories. A missing `schemaDir` or one pointing to a file is also rejected. Call `db.initialize()` to load and validate the data.
|
|
127
|
+
|
|
128
|
+
### Migrate data
|
|
129
|
+
|
|
130
|
+
Apply a function to each row, validate the result, and save it to the JSONL file.
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
npx lines-db migrate <file> <transform> [options]
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
npx lines-db migrate ./data/users.jsonl "(row) => ({ ...row, age: row.age + 1 })"
|
|
138
|
+
|
|
139
|
+
npx lines-db migrate ./data/users.jsonl "(row) => ({ ...row, active: true })" --filter "{ age: (age) => age > 18 }"
|
|
140
|
+
|
|
141
|
+
npx lines-db migrate ./data/users.jsonl "(row) => ({ ...row, age: row.age + 1 })" --errorOutput ./migrated.jsonl
|
|
142
|
+
|
|
143
|
+
npx lines-db migrate ./data "(row) => row" --fields id
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Available options:
|
|
147
|
+
|
|
148
|
+
- `--filter, -f <expr>`: Select rows with a filter expression.
|
|
149
|
+
- `--fields <list>`: Write back only the comma-separated fields. Other values remain as stored in the JSONL file. If omitted, write every field.
|
|
150
|
+
- `--errorOutput, -e <path>`: Save the transformed data to this path if migration fails.
|
|
151
|
+
- `--verbose, -v`: Show detailed error messages.
|
|
152
|
+
|
|
153
|
+
The migration runs in a transaction and validates all transformed rows before committing.
|
|
154
|
+
|
|
155
|
+
#### Write back selected fields
|
|
156
|
+
|
|
157
|
+
A normal migration writes whole rows back to the file, including schema defaults and fields that were omitted. Use `--fields` to keep other values as they were.
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
npx lines-db migrate ./data/users.jsonl "(row) => row" --fields id
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Rows are matched by primary key, or by position when the file has no primary key yet, such as when filling in that key. Existing row order is preserved, and new rows are appended. If the file has no primary key and the row count has changed, the migration fails because the rows cannot be matched.
|
|
164
|
+
|
|
165
|
+
`--fields` applies to all target tables. Tables without the named fields are not written back, so one list can cover tables with different columns. A field absent from every table causes an error.
|
|
166
|
+
|
|
167
|
+
### Fill missing values
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
npx lines-db fill <path...> [--schema-dir ./schemas] [--fields id,createdAt]
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Pass one or more data directories or JSONL files. Use `--schema-dir` for shared schemas; otherwise schemas are loaded next to each JSONL file. The command fills missing fields with values supplied by the validation schema. Without `--fields`, it fills each table's primary key.
|
|
174
|
+
|
|
175
|
+
Existing values are never replaced. Lines that gain no values remain unchanged, including line endings. Updated lines use the schema's key order. Rows that fail validation are not written. All values are computed before writing any files. If another tool changed a file after it was read, the command writes nothing and stops with a `JsonlConflictError` naming that file.
|
|
176
|
+
|
|
177
|
+
Use field names as stored in the file. When a `backward` transformation renames a primary key, the default target is the database's primary key name; pass the file's field name with `--fields`.
|
|
178
|
+
|
|
179
|
+
`fillFields()` accepts a function to compute values. This example uses a `hook` exported by the schema file. If the function throws, nothing is written.
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { fillFields, unwrap } from 'lines-db';
|
|
183
|
+
|
|
184
|
+
const { filled } = unwrap(
|
|
185
|
+
await fillFields({
|
|
186
|
+
path: './data',
|
|
187
|
+
fields: ['id'],
|
|
188
|
+
loadFiller: (schemaModule, { schemaPath }) => {
|
|
189
|
+
if (typeof schemaModule.hook !== 'function') throw new Error(`${schemaPath} does not export \`hook\``);
|
|
190
|
+
return schemaModule.hook;
|
|
191
|
+
},
|
|
192
|
+
}),
|
|
193
|
+
);
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
The result's `tablesWithoutSchema` lists tables without schemas, `unreadableLines` lists lines that are not JSON objects, and `unproducedFields` lists fields for which no table produced a value.
|
|
197
|
+
|
|
198
|
+
`fillFields()` accepts a string or a non-empty readonly array of strings for `path`. Across all paths, every value is computed and every pending write is checked for outside changes before writing. If a write fails, files already written are restored. Overlapping paths process each file only once. Unreadable lines are still reported and left unchanged.
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
unwrap(
|
|
202
|
+
await fillFields({
|
|
203
|
+
path: ['./data/dataset-a', './data/dataset-b'],
|
|
204
|
+
schemaDir: './data',
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### Browse and Edit in the Browser
|
|
210
|
+
|
|
211
|
+
Install Studio in the project and start it with the CLI.
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
npm install -D @lines-db/studio
|
|
215
|
+
npx lines-db studio ./data --open
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The default URL is `http://127.0.0.1:4848`. Changes are validated and written to the JSONL files when you save. See the [Studio documentation](https://github.com/toiroakr/lines-db/blob/main/studio/README.md) for editing, shared schemas, and multiple data directories.
|
|
219
|
+
|
|
220
|
+
## TypeScript usage
|
|
221
|
+
|
|
222
|
+
### Generate types
|
|
223
|
+
|
|
224
|
+
Generate a database config and types from the schemas. The default output is `<dataDir>/db.ts`.
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
npx lines-db generate <dataDir>
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
npx lines-db generate ./data
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
To run these commands through `package.json`:
|
|
235
|
+
|
|
236
|
+
```json
|
|
237
|
+
{
|
|
238
|
+
"scripts": {
|
|
239
|
+
"db:validate": "lines-db validate ./data",
|
|
240
|
+
"db:generate": "lines-db generate ./data"
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Load data
|
|
246
|
+
|
|
247
|
+
Create `data/users.jsonl`.
|
|
248
|
+
|
|
249
|
+
```text
|
|
250
|
+
{"id":1,"name":"Alice","age":30,"email":"alice@example.com"}
|
|
251
|
+
{"id":2,"name":"Bob","age":25,"email":"bob@example.com"}
|
|
252
|
+
{"id":3,"name":"Charlie","age":35,"email":"charlie@example.com"}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Load the directory from TypeScript.
|
|
256
|
+
|
|
257
|
+
```typescript
|
|
258
|
+
import { LinesDB, unwrap } from 'lines-db';
|
|
259
|
+
|
|
260
|
+
const db = LinesDB.create({ dataDir: './data' });
|
|
261
|
+
unwrap(await db.initialize());
|
|
262
|
+
|
|
263
|
+
const users = unwrap(db.find('users'));
|
|
264
|
+
console.log(users); // [{ id: 1, name: "Alice", ... }, ...]
|
|
265
|
+
|
|
266
|
+
const user = unwrap(db.findOne('users', { id: 1 }));
|
|
267
|
+
console.log(user); // { id: 1, name: "Alice", age: 30, ... }
|
|
268
|
+
|
|
269
|
+
const adults = unwrap(db.find('users', { age: (age) => age >= 30 }));
|
|
270
|
+
|
|
271
|
+
unwrap(await db.close());
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
`unwrap()` returns the value from a successful `Result` or throws its error. See [Error handling](#error-handling) for handling failures explicitly.
|
|
275
|
+
|
|
276
|
+
### Use generated types
|
|
277
|
+
|
|
278
|
+
The generated config infers row types from table names.
|
|
279
|
+
|
|
280
|
+
```typescript
|
|
281
|
+
import { LinesDB, unwrap } from 'lines-db';
|
|
282
|
+
import { config } from './data/db.js';
|
|
283
|
+
|
|
284
|
+
const db = LinesDB.create(config);
|
|
285
|
+
unwrap(await db.initialize());
|
|
286
|
+
|
|
287
|
+
const users = unwrap(db.find('users'));
|
|
288
|
+
|
|
289
|
+
unwrap(
|
|
290
|
+
db.insert('users', {
|
|
291
|
+
id: 10,
|
|
292
|
+
name: 'Alice',
|
|
293
|
+
age: 30,
|
|
294
|
+
email: 'alice@example.com',
|
|
295
|
+
}),
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
unwrap(await db.close());
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
## Error handling
|
|
302
|
+
|
|
303
|
+
Methods in `LinesDB` and `JsonlReader` that can fail return `Result<T, Error>`. A successful result is `{ ok: true, value }`; a failed result is `{ ok: false, error }`. `getSchema`, `getTableNames`, and `getDb` return their values directly.
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
const result = db.insert('users', { id: 2, name: '' });
|
|
307
|
+
|
|
308
|
+
if (result.ok) {
|
|
309
|
+
console.log(result.value.changes);
|
|
310
|
+
} else {
|
|
311
|
+
console.log(result.error.message);
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`unwrap(result)` returns the value on success and throws the error on failure. Use it when a failure should stop the current operation.
|
|
316
|
+
|
|
317
|
+
```typescript
|
|
318
|
+
import { unwrap } from 'lines-db';
|
|
319
|
+
|
|
320
|
+
const users = unwrap(db.find('users'));
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Inside a transaction, `tx` also returns Results. A failed `insert()` or `update()` does not roll back the transaction by itself. To abort on failure, use `unwrap()` or check the Result and throw with `throw result.error`.
|
|
324
|
+
|
|
325
|
+
Write through `tx` inside the transaction. Writes through `db` from other code would become part of the same transaction, so they are refused while it is open. SQL through `db.getDb()`, `db.execute()`, and `db.query()` is read-only during the transaction. `SELECT`, `VALUES`, `WITH`, `EXPLAIN`, and read-only pragmas such as `PRAGMA table_info(...)` are accepted. Run transaction control or pragmas that set values through `tx`.
|
|
326
|
+
|
|
327
|
+
## API
|
|
328
|
+
|
|
329
|
+
The operations below return `Result<T, Error>` unless noted otherwise. `getSchema`, `getTableNames`, and `getDb` return their values directly.
|
|
330
|
+
|
|
331
|
+
### Queries
|
|
332
|
+
|
|
333
|
+
- `find(table, where?)`: Find all matching records.
|
|
334
|
+
- `findOne(table, where?)`: Find one record.
|
|
335
|
+
- `query(sql, params?)`: Run a raw SQL query.
|
|
336
|
+
|
|
337
|
+
### Changes
|
|
338
|
+
|
|
339
|
+
- `insert(table, data)`: Insert one record.
|
|
340
|
+
- `update(table, data, where)`: Update matching records.
|
|
341
|
+
- `delete(table, where)`: Delete matching records.
|
|
342
|
+
|
|
343
|
+
### Batch operations
|
|
344
|
+
|
|
345
|
+
- `batchInsert(table, data[])`: Insert several records.
|
|
346
|
+
- `batchUpdate(table, updates[])`: Update several records.
|
|
347
|
+
- `batchDelete(table, where)`: Delete several records.
|
|
348
|
+
|
|
349
|
+
### Transactions and schemas
|
|
350
|
+
|
|
351
|
+
- `transaction(fn)`: Run operations in a transaction.
|
|
352
|
+
- `sync(table?, options?)`: Write changes back to the JSONL files.
|
|
353
|
+
- `getSchema(table)`: Get the schema. Returns `TableSchema | undefined` directly.
|
|
354
|
+
- `validateRow(table, row)`: Validate a row, including a row from a table excluded on load due to validation errors. Returns `Result<JsonObject, ValidationError>`.
|
|
355
|
+
- `getTableNames()`: Get all table names. Returns `string[]` directly.
|
|
356
|
+
|
|
357
|
+
### Query conditions
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
unwrap(db.find('users', { age: 30 }));
|
|
361
|
+
|
|
362
|
+
unwrap(db.find('users', { age: 30, name: 'Alice' }));
|
|
363
|
+
|
|
364
|
+
unwrap(
|
|
365
|
+
db.find('users', {
|
|
366
|
+
age: (age) => age > 25,
|
|
367
|
+
name: (name) => name.startsWith('A'),
|
|
368
|
+
}),
|
|
369
|
+
);
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
### JSON columns
|
|
373
|
+
|
|
374
|
+
Objects and arrays are stored as JSON columns and returned as their original values.
|
|
375
|
+
|
|
376
|
+
```typescript
|
|
377
|
+
unwrap(
|
|
378
|
+
db.insert('orders', {
|
|
379
|
+
id: 1,
|
|
380
|
+
items: [{ name: 'Laptop', quantity: 1 }],
|
|
381
|
+
metadata: { source: 'web' },
|
|
382
|
+
}),
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
const order = unwrap(db.findOne('orders', { id: 1 }));
|
|
386
|
+
console.log(order.items[0].name); // "Laptop"
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
### Schema transformations
|
|
390
|
+
|
|
391
|
+
If a schema converts date strings to `Date` objects on load, define a `backward` transformation to convert them to strings when saving. JSONL stores the strings; the application works with `Date` objects.
|
|
392
|
+
|
|
393
|
+
```typescript
|
|
394
|
+
import * as v from 'valibot';
|
|
395
|
+
import { defineSchema } from 'lines-db';
|
|
396
|
+
|
|
397
|
+
const eventSchema = v.pipe(
|
|
398
|
+
v.object({
|
|
399
|
+
id: v.number(),
|
|
400
|
+
date: v.pipe(
|
|
401
|
+
v.string(),
|
|
402
|
+
v.isoDate(),
|
|
403
|
+
v.transform((str) => new Date(str)),
|
|
404
|
+
),
|
|
405
|
+
}),
|
|
406
|
+
);
|
|
407
|
+
|
|
408
|
+
export const schema = defineSchema(eventSchema, {
|
|
409
|
+
backward: (output) => ({
|
|
410
|
+
...output,
|
|
411
|
+
date: output.date.toISOString().slice(0, 10),
|
|
412
|
+
}),
|
|
413
|
+
});
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
Store the date as a string in `events.jsonl`.
|
|
417
|
+
|
|
418
|
+
```text
|
|
419
|
+
{"id":1,"date":"2024-01-01"}
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
The loaded row exposes the date as a `Date`.
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
const event = unwrap(db.findOne('events', { id: 1 }));
|
|
426
|
+
console.log(event.date instanceof Date); // true
|
|
427
|
+
console.log(event.date.getFullYear()); // 2024
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
### Transactions
|
|
431
|
+
|
|
432
|
+
Changes outside a transaction are automatically synced to the JSONL file.
|
|
433
|
+
|
|
434
|
+
```typescript
|
|
435
|
+
unwrap(db.insert('users', { id: 10, name: 'Alice', age: 30 }));
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
Sync preserves the original row order and appends new rows.
|
|
439
|
+
|
|
440
|
+
Use a transaction to save several changes together.
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
unwrap(
|
|
444
|
+
await db.transaction(async (tx) => {
|
|
445
|
+
unwrap(tx.insert('users', { id: 10, name: 'Alice', age: 30 }));
|
|
446
|
+
unwrap(tx.update('users', { age: 31 }, { id: 1 }));
|
|
447
|
+
}),
|
|
448
|
+
);
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
Use `unwrap()` inside the callback to throw on a failed operation and roll back the transaction.
|
|
452
|
+
|
|
453
|
+
After the callback finishes, changed tables are written back before committing. All target files are checked before the first write. If write-back fails, the transaction is rolled back and files already written are restored. If restoration also fails, that file keeps its changes.
|
|
454
|
+
|
|
455
|
+
Unchanged tables are not written back. However, SQL that changes rows through `tx.execute()` or `tx.query()` writes back every table because the changed tables cannot be identified. Calling `sync()` inside the callback returns an error; the transaction handles write-back at the end.
|
|
456
|
+
|
|
457
|
+
### Files changed after loading
|
|
458
|
+
|
|
459
|
+
The database records each JSONL file's contents when reading or writing it. If an editor or another tool has changed or deleted the file since then, sync leaves it untouched and returns a `JsonlConflictError` naming the file.
|
|
460
|
+
|
|
461
|
+
```typescript
|
|
462
|
+
const result = await db.transaction((tx) => unwrap(tx.update('users', { age: 31 }, { id: 1 })));
|
|
463
|
+
|
|
464
|
+
if (!result.ok && result.error.name === 'JsonlConflictError') {
|
|
465
|
+
console.log(`${(result.error as JsonlConflictError).file} has changed on disk`);
|
|
466
|
+
}
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
To load external changes, recreate the database, call `initialize()`, and retry the write. A transaction writes back only changed tables and rolls back the database changes if a conflict occurs.
|
|
470
|
+
|
|
471
|
+
With `sync()` or automatic sync outside a transaction, database changes remain after a failed write-back. A `sync()` without a table name targets every table, so a change to any file causes it to fail. Automatic sync reports errors through `console.error`.
|
|
472
|
+
|
|
473
|
+
Files are not locked between checking their contents and writing. Changes saved by another process during that interval are overwritten. This is intended for one person editing local files; it does not coordinate concurrent writers.
|
|
474
|
+
|
|
475
|
+
`hasExternalChanges()` detects changes, additions, and deletions of JSONL and schema files since the last read or write. `findExternalChanges()` lists the affected files. Use them to detect edits made by other tools and reload data in a long-running process.
|
|
476
|
+
|
|
477
|
+
```typescript
|
|
478
|
+
if (unwrap(await db.hasExternalChanges())) {
|
|
479
|
+
await db.close();
|
|
480
|
+
db = LinesDB.create(config);
|
|
481
|
+
unwrap(await db.initialize());
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
### Values the Schema Fills In
|
|
486
|
+
|
|
487
|
+
Normal sync writes whole rows, including schema defaults and computed values. With `writeFilledValues: 'primaryKey'`, it writes fields present in the file, passed to `insert()`, or changed by `update()`. Other defaults remain omitted. Generated primary keys are saved so the row keeps its identity on the next load.
|
|
488
|
+
|
|
489
|
+
```typescript
|
|
490
|
+
const db = LinesDB.create({ dataDir: './data', writeFilledValues: 'primaryKey' });
|
|
491
|
+
// people.jsonl: {"id":1,"name":"Alice"}
|
|
492
|
+
unwrap(await db.transaction((tx) => unwrap(tx.update('people', { name: 'Alicia' }, { id: 1 }))));
|
|
493
|
+
// people.jsonl: {"id":1,"name":"Alicia"}
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
Use `sync(tableName, { writeFilledValues })` to override the setting for one sync. Setting a field to its existing value is not a change, so setting a defaulted field to that same value does not write it to the file. Fields explicitly named in `writeBackFields` or `sync(..., { fields })` are written even when the schema supplied them.
|
|
497
|
+
|
|
498
|
+
`resetToDefault` restores a field's schema default. With `writeFilledValues: 'primaryKey'`, that field is removed from the file.
|
|
499
|
+
|
|
500
|
+
```typescript
|
|
501
|
+
unwrap(db.update('people', {}, { id: 1 }, { resetToDefault: ['age'] }));
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
`findWithDefaults()` returns each row and the names of fields supplied by the schema. Use it to distinguish defaults from values stored in the file.
|
|
505
|
+
|
|
506
|
+
```typescript
|
|
507
|
+
unwrap(await db.findWithDefaults('people'));
|
|
508
|
+
// [{ row: { id: 1, name: 'Alicia', age: 20 }, defaulted: ['age'] }]
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
Rows whose `backward` transformation renames fields, or rows added by SQL with no original row or write record, are written in full because explicitly supplied fields cannot be identified. A table changed through SQL also has all rows written back. Fields set by a migration `transform` on load count as explicitly supplied.
|
|
512
|
+
|
|
513
|
+
Unknown fields from the original row retain their position on write-back. Schemas that strip unknown keys, such as Valibot's `v.object()`, allow those rows to pass validation. Use `v.strictObject()` or another schema that rejects unknown keys to report them as errors.
|
|
514
|
+
|
|
515
|
+
### Write back selected fields
|
|
516
|
+
|
|
517
|
+
When fields are specified, their database values are written even if the schema supplied them. Other values remain as stored in the file.
|
|
518
|
+
|
|
519
|
+
```typescript
|
|
520
|
+
// users.jsonl: {"name":"Alice"}
|
|
521
|
+
unwrap(await db.sync('users', { fields: ['id'] }));
|
|
522
|
+
// users.jsonl: {"id":"...","name":"Alice"}
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
Set `writeBackFields` in the config to apply the rule to every sync, including automatic sync after inserts, updates, and transactions.
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
const db = LinesDB.create({ dataDir: './data', writeBackFields: ['id'] });
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
Rows are matched by primary key, or by position when the file has no primary key yet. Row order is preserved, and new rows are appended. Selected fields use the database value, including null. If rows cannot be matched, `sync()` returns a failed Result.
|
|
532
|
+
|
|
533
|
+
New fields are inserted in schema order. For example, an `id` declared first is inserted at the beginning of the row when filled later. Existing keys do not move, and unknown keys stay after declared keys.
|
|
534
|
+
|
|
535
|
+
Key order is read from the rows produced by the schema. Fields produced first are ordered first; fields first encountered in later rows follow them. Set `mergeFields`'s `keyOrder` to specify the order explicitly.
|
|
536
|
+
|
|
537
|
+
A `sync()` for a specific table rejects fields that the table does not have. Sync across all tables and the config's `writeBackFields` skip tables without those fields, so the same list works for different column sets.
|
|
538
|
+
|
|
539
|
+
### Edit rows without a database
|
|
540
|
+
|
|
541
|
+
`mergeFields` takes the original row and a computed row and returns a row with only the selected fields updated. Use it to edit files without loading them into SQLite, such as when a hook supplies IDs.
|
|
542
|
+
|
|
543
|
+
```typescript
|
|
544
|
+
import { JsonlReader, JsonlWriter, mergeFields, unwrap } from 'lines-db';
|
|
545
|
+
|
|
546
|
+
const rows = unwrap(await JsonlReader.read('./data/users.jsonl'));
|
|
547
|
+
const filled = rows.map((row) => mergeFields(row, fillIds(row), { fields: ['id'] }));
|
|
548
|
+
await JsonlWriter.write('./data/users.jsonl', filled);
|
|
549
|
+
|
|
550
|
+
// {"name":"Alice"} -> {"id":"018f...","name":"Alice"}
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
Fields outside the selection are not validated. Even if their values would fail the schema, selected fields can still be updated. Fields absent from the computed row keep their original values. If computed key order differs from schema order, use `keyOrder` to set the position of new keys.
|
|
554
|
+
|
|
555
|
+
## Configuration
|
|
556
|
+
|
|
557
|
+
```typescript
|
|
558
|
+
interface DatabaseConfig {
|
|
559
|
+
dataDir: string | readonly string[];
|
|
560
|
+
schemaDir?: string;
|
|
561
|
+
writeDataSets?: boolean;
|
|
562
|
+
writeBackFields?: readonly string[];
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const db = LinesDB.create({ dataDir: './data' });
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
### Data sets
|
|
569
|
+
|
|
570
|
+
Split shared seed data from scenario-specific data and load the directories you need together.
|
|
571
|
+
|
|
572
|
+
```
|
|
573
|
+
data/
|
|
574
|
+
Item.schema.ts Item.jsonl # schemas and base data
|
|
575
|
+
ItemValuation.schema.ts
|
|
576
|
+
cogs/
|
|
577
|
+
Item.jsonl # additional Item rows
|
|
578
|
+
ItemValuation.jsonl # references Item rows from both sets
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
```typescript
|
|
582
|
+
const db = LinesDB.create({ dataDir: ['./data', './data/cogs'], schemaDir: './data' });
|
|
583
|
+
const result = unwrap(await db.initialize({ detailedValidate: true }));
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
Rows for the same table are concatenated in `dataDir` order. Validation, unique constraints, and foreign keys are checked across all rows. `cogs/ItemValuation.jsonl` can reference rows from `data/Item.jsonl`. Duplicate IDs across sets cause a constraint violation. Errors identify the source file and row within it.
|
|
587
|
+
|
|
588
|
+
Multiple directories require `schemaDir` to locate shared schemas. It can also be used with one directory. If omitted for a single directory, schemas are looked up next to the JSONL files.
|
|
589
|
+
|
|
590
|
+
Databases with multiple directories are read-only by default. Set `writeDataSets: true` to write updates and deletions back to their source files. Inserts require an explicit configured directory.
|
|
591
|
+
|
|
592
|
+
```typescript
|
|
593
|
+
const db = LinesDB.create({ dataDir: ['./data', './data/cogs'], schemaDir: './data', writeDataSets: true });
|
|
594
|
+
unwrap(await db.initialize());
|
|
595
|
+
unwrap(
|
|
596
|
+
await db.transaction((tx) => {
|
|
597
|
+
const inserted = tx.insert('Item', { id: 'new-item', name: 'New item' }, { dataDir: './data/cogs' });
|
|
598
|
+
if (!inserted.ok) throw inserted.error;
|
|
599
|
+
}),
|
|
600
|
+
);
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
Use `insert()` with a destination to add rows across multiple directories. `batchInsert()` has no destination argument. SQL through `execute()`, `query()`, `queryOne()`, and `getDb()` remains read-only to preserve each row's source location.
|
|
604
|
+
|
|
605
|
+
Transactions check target files before writing and restore files already written if a later write fails. Studio enables `writeDataSets` automatically.
|
|
606
|
+
|
|
607
|
+
## Type mapping
|
|
608
|
+
|
|
609
|
+
| JSON type | Column type | SQLite storage |
|
|
610
|
+
| ---------------- | ----------- | -------------- |
|
|
611
|
+
| number (integer) | INTEGER | INTEGER |
|
|
612
|
+
| number (float) | REAL | REAL |
|
|
613
|
+
| string | TEXT | TEXT |
|
|
614
|
+
| boolean | INTEGER | INTEGER |
|
|
615
|
+
| object | JSON | TEXT |
|
|
616
|
+
| array | JSON | TEXT |
|
|
617
|
+
|
|
618
|
+
## License
|
|
619
|
+
|
|
620
|
+
MIT
|