edinburgh 0.4.1 → 0.4.2

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/skill/SKILL.md ADDED
@@ -0,0 +1,1349 @@
1
+ ---
2
+ name: edinburgh
3
+ description: Expert guidance for using the Edinburgh ORM — a high-performance TypeScript ORM built on LMDB. Covers model definitions, typed fields, transactions, indexes, links, schema migration, and advanced patterns.
4
+ ---
5
+ # Edinburgh
6
+ **TypeScript objects that live in the database.**
7
+
8
+ Edinburgh blurs the line between in-memory objects and database records. Define a model class, and its instances *are* the database rows. They are read directly from a memory-mapped [LMDB](http://www.lmdb.tech/doc/) store on first access, and mutations are written back in an ACID transaction on commit. There is no SQL layer, no query builder, no network round-trip, and no result-set marshalling. A primary-key lookup completes in about 1 µs.
9
+
10
+ This makes problems like n+1 queries irrelevant: traversing `post.author.department.manager` is just a chain of microsecond memory-mapped reads, not a cascade of network calls.
11
+
12
+ Built on [OLMDB](https://github.com/vanviegen/olmdb) (an optimistic-locking wrapper around LMDB).
13
+
14
+ - **Objects are records**: model fields are backed by memory-mapped storage; no serialization boundary between your code and the database
15
+ - **Sub-microsecond reads**: embedded B+ tree in the same process, no network hop, no query parsing
16
+ - **Type-safe at every layer**: TypeScript inference at compile time, runtime validation at write time
17
+ - **First-class relationships**: `E.link(OtherModel)` fields load lazily and transparently on access
18
+ - **Indexes**: primary, unique, and secondary indexes with efficient range queries
19
+ - **ACID transactions**: optimistic locking with automatic retry on conflict (up to 6 attempts)
20
+ - **Zero-downtime schema evolution**: old rows are lazily migrated on read; no batch DDL required
21
+
22
+ ## Quick Demo
23
+ ```typescript
24
+ import * as E from "edinburgh";
25
+
26
+ // Initialize the database (optional, defaults to ".edinburgh")
27
+ E.init("./my-database");
28
+
29
+ // Define a model
30
+ @E.registerModel
31
+ class User extends E.Model<User> {
32
+ // Define a primary key (optional, defaults to using the "id" field)
33
+ static pk = E.primary(User, "id");
34
+ // Define a unique index on the email field
35
+ static byEmail = E.unique(User, "email");
36
+
37
+ // Define fields with simple types -- they will be type-checked at compile time and validated at runtime.
38
+ id = E.field(E.identifier);
39
+ name = E.field(E.string);
40
+ age = E.field(E.number);
41
+ email = E.field(E.opt(E.string)); // TypeScript: undefined | string
42
+
43
+ // Link to another instance of this model
44
+ supervisor = E.field(E.opt(E.link(User)));
45
+
46
+ // A field with a more elaborate type. In TypeScript: `User | User[] | "unknown" | "whatever"`
47
+ something = E.field(E.or(E.link(User), E.array(E.link(User)), E.literal("unknown"), E.literal("whatever")), { default: "unknown" });
48
+ }
49
+
50
+ // Use in transactions
51
+ await E.transact(() => {
52
+ const boss = new User({
53
+ name: "Big Boss",
54
+ age: 50,
55
+ });
56
+ const john = new User({ // Unique 'id' is automatically generated if not provided
57
+ name: "John Doe",
58
+ age: 41,
59
+ email: "john@example.com",
60
+ supervisor: boss, // Link to another model instance
61
+ });
62
+ });
63
+
64
+ await E.transact(() => {
65
+ // Query by unique index
66
+ const john = User.byEmail.get("john@example.com")!;
67
+
68
+ // The transaction will retry if there's a conflict, such as another transaction
69
+ // modifying the same user (from another async function or another process)
70
+ john.age++;
71
+
72
+ // The supervisor object is lazy loaded on first access
73
+ console.log(`${john.supervisor!.name} is ${john.name}'s supervisor`);
74
+ });
75
+ ```
76
+
77
+ ## Tutorial
78
+
79
+ ### TypeScript Configuration
80
+
81
+ When using TypeScript to transpile to JavaScript, make sure to enable the following options in your `tsconfig.json`:
82
+
83
+ ```json
84
+ {
85
+ "compilerOptions": {
86
+ "target": "es2022",
87
+ "experimentalDecorators": true
88
+ }
89
+ }
90
+ ```
91
+
92
+ ### Defining Models
93
+
94
+ Models are classes that extend `E.Model<Self>` and use the `@E.registerModel` decorator:
95
+
96
+ ```typescript
97
+ import * as E from "edinburgh";
98
+
99
+ @E.registerModel
100
+ class User extends E.Model<User> {
101
+ static pk = E.primary(User, "id");
102
+
103
+ id = E.field(E.identifier);
104
+ name = E.field(E.string);
105
+ email = E.field(E.string);
106
+ age = E.field(E.number);
107
+ }
108
+ ```
109
+
110
+ Instance fields are declared with `E.field(type, options?)`. Available types:
111
+
112
+ | Type | TypeScript type | Notes |
113
+ |------|----------------|-------|
114
+ | `E.string` | `string` | |
115
+ | `E.orderedString` | `string` | Lexicographic sort in indexes; no null bytes |
116
+ | `E.number` | `number` | |
117
+ | `E.boolean` | `boolean` | |
118
+ | `E.dateTime` | `Date` | Defaults to `new Date()` |
119
+ | `E.identifier` | `string` | Auto-generated 8-char unique ID |
120
+ | `E.opt(T)` | `T \| undefined` | Makes any type optional |
121
+ | `E.or(A, B, ...)` | `A \| B \| ...` | Union type; args can be types or literal values |
122
+ | `E.literal(v)` | literal type | Constant value; defaults to that value |
123
+ | `E.array(T)` | `T[]` | Optional `{min, max}` constraints |
124
+ | `E.link(Model)` | `Model` | Foreign key, lazy-loaded on access |
125
+
126
+ #### Defaults
127
+
128
+ ```typescript
129
+ @E.registerModel
130
+ class Post extends E.Model<Post> {
131
+ static pk = E.primary(Post, "id");
132
+
133
+ id = E.field(E.identifier); // auto-generated
134
+ title = E.field(E.string);
135
+ status = E.field(E.or("draft", "published"), {default: "draft"});
136
+ tags = E.field(E.array(E.string), {default: () => []}); // use function for mutable defaults
137
+ createdAt = E.field(E.dateTime); // dateTime defaults to new Date()
138
+ }
139
+ ```
140
+
141
+ ### Transactions
142
+
143
+ All database operations must run inside `E.transact()`:
144
+
145
+ ```typescript
146
+ // Initialize (optional — defaults to ".edinburgh" directory)
147
+ E.init("./my-database");
148
+
149
+ // Create
150
+ await E.transact(() => {
151
+ const user = new User({name: "Alice", email: "alice@example.com", age: 30});
152
+ // user.id is auto-generated
153
+ });
154
+
155
+ // Read + Update
156
+ await E.transact(() => {
157
+ const user = User.byEmail.get("alice@example.com");
158
+ if (user) user.age++;
159
+ });
160
+
161
+ // Return values from transactions
162
+ const name = await E.transact(() => {
163
+ const user = User.byEmail.get("alice@example.com");
164
+ return user?.name;
165
+ });
166
+ ```
167
+
168
+ Transactions auto-retry on conflict (up to 6 times by default). Keep transaction functions idempotent.
169
+
170
+ ### Indexes
171
+
172
+ Edinburgh supports three index types:
173
+
174
+ ```typescript
175
+ @E.registerModel
176
+ class Product extends E.Model<Product> {
177
+ static pk = E.primary(Product, "sku"); // primary: one per model, stores data
178
+ static byName = E.unique(Product, "name"); // unique: enforces uniqueness + fast lookup
179
+ static byCategory = E.index(Product, "category");// secondary: non-unique, for queries
180
+
181
+ sku = E.field(E.string);
182
+ name = E.field(E.string);
183
+ category = E.field(E.string);
184
+ price = E.field(E.number);
185
+ }
186
+ ```
187
+
188
+ If no `E.primary()` is declared, Edinburgh auto-creates one on an `id` field (adding `E.identifier` if missing).
189
+
190
+ #### Lookups
191
+
192
+ ```typescript
193
+ await E.transact(() => {
194
+ // Primary key lookup
195
+ const p = Product.pk.get("SKU-001");
196
+
197
+ // Unique index lookup
198
+ const p2 = Product.byName.get("Widget");
199
+
200
+ // All return undefined if not found
201
+ });
202
+ ```
203
+
204
+ #### Range Queries
205
+
206
+ All index types support `.find()` for range iteration:
207
+
208
+ ```typescript
209
+ await E.transact(() => {
210
+ // Exact match
211
+ for (const p of Product.byCategory.find({is: "electronics"})) {
212
+ console.log(p.name);
213
+ }
214
+
215
+ // Range (inclusive)
216
+ for (const p of Product.pk.find({from: "A", to: "M"})) {
217
+ console.log(p.sku);
218
+ }
219
+
220
+ // Exclusive bounds
221
+ for (const p of Product.pk.find({after: "A", before: "M"})) { ... }
222
+
223
+ // Open-ended
224
+ for (const p of Product.pk.find({from: "M"})) { ... }
225
+
226
+ // Reverse
227
+ for (const p of Product.pk.find({reverse: true})) { ... }
228
+
229
+ // Count and fetch helpers
230
+ const count = Product.byCategory.find({is: "electronics"}).count();
231
+ const first = Product.byCategory.find({is: "electronics"}).fetch(); // first match or undefined
232
+ });
233
+ ```
234
+
235
+ #### Composite Indexes
236
+
237
+ ```typescript
238
+ @E.registerModel
239
+ class Event extends E.Model<Event> {
240
+ static pk = E.primary(Event, ["year", "month", "id"]);
241
+
242
+ year = E.field(E.number);
243
+ month = E.field(E.number);
244
+ id = E.field(E.identifier);
245
+ title = E.field(E.string);
246
+ }
247
+
248
+ await E.transact(() => {
249
+ // Prefix matching — find all events in 2025
250
+ for (const e of Event.pk.find({is: [2025]})) { ... }
251
+
252
+ // Find events in March 2025
253
+ for (const e of Event.pk.find({is: [2025, 3]})) { ... }
254
+ });
255
+ ```
256
+
257
+ ### Relationships (Links)
258
+
259
+ Use `E.link(Model)` for foreign keys:
260
+
261
+ ```typescript
262
+ @E.registerModel
263
+ class Author extends E.Model<Author> {
264
+ static pk = E.primary(Author, "id");
265
+ id = E.field(E.identifier);
266
+ name = E.field(E.string);
267
+ }
268
+
269
+ @E.registerModel
270
+ class Book extends E.Model<Book> {
271
+ static pk = E.primary(Book, "id");
272
+ id = E.field(E.identifier);
273
+ title = E.field(E.string);
274
+ author = E.field(E.link(Author));
275
+ }
276
+
277
+ await E.transact(() => {
278
+ const author = new Author({name: "Tolkien"});
279
+ const book = new Book({title: "The Hobbit", author});
280
+
281
+ // Later: linked models are lazy-loaded on property access
282
+ const b = Book.pk.get(book.id)!;
283
+ console.log(b.author.name); // loads Author automatically (~1µs)
284
+ });
285
+ ```
286
+
287
+ ### Deleting
288
+
289
+ ```typescript
290
+ await E.transact(() => {
291
+ const user = User.pk.get(someId);
292
+ if (user) user.delete();
293
+ });
294
+ ```
295
+
296
+ ### Model Utilities
297
+
298
+ ```typescript
299
+ await E.transact(() => {
300
+ const user = new User({name: "Bob", email: "bob@example.com", age: 25});
301
+
302
+ user.validate(); // returns Error[]
303
+ user.isValid(); // returns boolean
304
+ user.getState(); // "created" | "loaded" | "lazy" | "deleted"
305
+ user.getPrimaryKey(); // Uint8Array
306
+ user.preventPersist(); // exclude from commit
307
+ });
308
+
309
+ // findAll iterates all instances
310
+ await E.transact(() => {
311
+ for (const user of User.findAll()) { ... }
312
+ for (const user of User.findAll({reverse: true})) { ... }
313
+ });
314
+
315
+ // replaceInto: upsert by primary key
316
+ await E.transact(() => {
317
+ User.replaceInto({id: existingId, name: "Updated Name", email: "new@example.com", age: 30});
318
+ });
319
+ ```
320
+
321
+ ### Batch Processing
322
+
323
+ For large datasets, `batchProcess` auto-commits in batches:
324
+
325
+ ```typescript
326
+ await Product.byCategory.batchProcess({is: "old"}, (product) => {
327
+ product.category = "archived";
328
+ });
329
+ // Commits every ~1 second or 4096 rows (configurable via limitSeconds, limitRows)
330
+ ```
331
+
332
+ ### Schema Evolution
333
+
334
+ Edinburgh handles schema changes automatically:
335
+
336
+ - **Adding/removing fields**: Old rows are lazily migrated on read. New fields use their default value.
337
+ - **Changing field types**: Requires a `static migrate()` function.
338
+ - **Adding/removing indexes**: Requires running `npx migrate-edinburgh`.
339
+
340
+ ```typescript
341
+ @E.registerModel
342
+ class User extends E.Model<User> {
343
+ static pk = E.primary(User, "id");
344
+ id = E.field(E.identifier);
345
+ name = E.field(E.string);
346
+ role = E.field(E.string, {default: "user"}); // new field
347
+
348
+ static migrate(record: Record<string, any>) {
349
+ record.role ??= "user"; // provide value for old rows
350
+ }
351
+ }
352
+ ```
353
+
354
+ Run `npx migrate-edinburgh` (or call `E.runMigration()`) after adding/removing indexes, changing index field types, or when a `migrate()` function affects indexed fields.
355
+
356
+ ### preCommit Hook
357
+
358
+ Compute derived fields before data is written:
359
+
360
+ ```typescript
361
+ @E.registerModel
362
+ class Article extends E.Model<Article> {
363
+ static pk = E.primary(Article, "id");
364
+ id = E.field(E.identifier);
365
+ title = E.field(E.string);
366
+ slug = E.field(E.string);
367
+
368
+ preCommit() {
369
+ this.slug = this.title.toLowerCase().replace(/\s+/g, "-");
370
+ }
371
+ }
372
+ ```
373
+
374
+ ### Change Tracking
375
+
376
+ Monitor commits with `setOnSaveCallback`:
377
+
378
+ ```typescript
379
+ E.setOnSaveCallback((commitId, items) => {
380
+ for (const [instance, change] of items) {
381
+ if (change === "created") { /* new record */ }
382
+ else if (change === "deleted") { /* removed */ }
383
+ else { /* change is an object with old values of modified fields */ }
384
+ }
385
+ });
386
+ ```
387
+
388
+ ### Logging
389
+
390
+ Enable debug logging by setting the `EDINBURGH_LOG_LEVEL` environment variable (0–3). Higher numbers produce more verbose logs.
391
+
392
+ - 0: no logging (default)
393
+ - 1: model-level logs
394
+ - 2: + update logs
395
+ - 3: + read logs
396
+
397
+ ### AI Integration
398
+
399
+ If you use Claude Code, GitHub Copilot or another AI agent that supports Skills, Edinburgh includes a `skill/` directory in its npm package that provides specialized knowledge to the AI about how to use the library effectively.
400
+
401
+ Symlink the skill into your project's `.claude/skills` directory:
402
+
403
+ ```bash
404
+ mkdir -p .claude/skills
405
+ ln -s ../../node_modules/edinburgh/skill .claude/skills/edinburgh
406
+ ```
407
+
408
+ ## API Reference
409
+
410
+ The following is auto-generated from `src/edinburgh.ts`:
411
+
412
+ ### scheduleInit · function
413
+
414
+ **Signature:** `() => void`
415
+
416
+ ### init · function
417
+
418
+ Initialize the database with the specified directory path.
419
+ This function may be called multiple times with the same parameters. If it is not called before the first transact(),
420
+ the database will be automatically initialized with the default directory.
421
+
422
+ **Signature:** `(dbDir: string) => void`
423
+
424
+ **Parameters:**
425
+
426
+ - `dbDir: string`
427
+
428
+ **Examples:**
429
+
430
+ ```typescript
431
+ init("./my-database");
432
+ ```
433
+
434
+ ### transact · function
435
+
436
+ Executes a function within a database transaction context.
437
+
438
+ Loading models (also through links in other models) and changing models can only be done from
439
+ within a transaction.
440
+
441
+ Transactions have a consistent view of the database, and changes made within a transaction are
442
+ isolated from other transactions until they are committed. In case a commit clashes with changes
443
+ made by another transaction, the transaction function will automatically be re-executed up to 6
444
+ times.
445
+
446
+ **Signature:** `<T>(fn: () => T) => Promise<T>`
447
+
448
+ **Type Parameters:**
449
+
450
+ - `T` - The return type of the transaction function.
451
+
452
+ **Parameters:**
453
+
454
+ - `fn: () => T` - - The function to execute within the transaction context. Receives a Transaction instance.
455
+
456
+ **Returns:** A promise that resolves with the function's return value.
457
+
458
+ **Throws:**
459
+
460
+ - With code "RACING_TRANSACTION" if the transaction fails after retries due to conflicts.
461
+ - With code "TXN_LIMIT" if maximum number of transactions is reached.
462
+ - With code "LMDB-{code}" for LMDB-specific errors.
463
+
464
+ **Examples:**
465
+
466
+ ```typescript
467
+ const paid = await E.transact(() => {
468
+ const user = User.pk.get("john_doe");
469
+ if (user.credits > 0) {
470
+ user.credits--;
471
+ return true;
472
+ }
473
+ return false;
474
+ });
475
+ ```
476
+ ```typescript
477
+ // Transaction with automatic retry on conflicts
478
+ await E.transact(() => {
479
+ const counter = Counter.pk.get("global") || new Counter({id: "global", value: 0});
480
+ counter.value++;
481
+ });
482
+ ```
483
+
484
+ ### setMaxRetryCount · function
485
+
486
+ Set the maximum number of retries for a transaction in case of conflicts.
487
+ The default value is 6. Setting it to 0 will disable retries and cause transactions to fail immediately on conflict.
488
+
489
+ **Signature:** `(count: number) => void`
490
+
491
+ **Parameters:**
492
+
493
+ - `count: number` - The maximum number of retries for a transaction.
494
+
495
+ ### setOnSaveCallback · function
496
+
497
+ Set a callback function to be called after a model is saved and committed.
498
+
499
+ **Signature:** `(callback: (commitId: number, items: Map<Model<any>, Change>) => void) => void`
500
+
501
+ **Parameters:**
502
+
503
+ - `callback: ((commitId: number, items: Map<Model<any>, Change>) => void) | undefined` - The callback function to set. It gets called after each successful
504
+ `transact()` commit that has changes, with the following arguments:
505
+ - A sequential number. Higher numbers have been committed after lower numbers.
506
+ - A map of model instances to their changes. The change can be "created", "deleted", or an object containing the old values.
507
+
508
+ ### deleteEverything · function
509
+
510
+ **Signature:** `() => Promise<void>`
511
+
512
+ ### Model · abstract class
513
+
514
+ [object Object],[object Object],[object Object],[object Object],[object Object]
515
+
516
+ **Type Parameters:**
517
+
518
+ - `SUB` - The concrete model subclass (for proper typing).
519
+
520
+ **Examples:**
521
+
522
+ ```typescript
523
+ ⁣@E.registerModel
524
+ class User extends E.Model<User> {
525
+ static pk = E.primary(User, "id");
526
+
527
+ id = E.field(E.identifier);
528
+ name = E.field(E.string);
529
+ email = E.field(E.string);
530
+
531
+ static byEmail = E.unique(User, "email");
532
+ }
533
+ ```
534
+
535
+ #### Model.tableName · static property
536
+
537
+ The database table name (defaults to class name).
538
+
539
+ **Type:** `string`
540
+
541
+ #### Model.override · static property
542
+
543
+ When true, registerModel replaces an existing model with the same tableName.
544
+
545
+ **Type:** `boolean`
546
+
547
+ #### Model.fields · static property
548
+
549
+ Field configuration metadata.
550
+
551
+ **Type:** `Record<string | number | symbol, FieldConfig<unknown>>`
552
+
553
+ #### Model.migrate · static method
554
+
555
+ Optional migration function called when deserializing rows written with an older schema version.
556
+ Receives a plain record with all fields (primary key fields + value fields) and should mutate it
557
+ in-place to match the current schema.
558
+
559
+ This is called both during lazy loading (when a row is read from disk) and during batch
560
+ migration (via `runMigration()` / `npx migrate-edinburgh`). The function's source code is hashed
561
+ to detect changes. Modifying `migrate()` triggers a new schema version.
562
+
563
+ If `migrate()` changes values of fields used in secondary or unique indexes, those indexes
564
+ will only be updated when `runMigration()` is run (not during lazy loading).
565
+
566
+ **Signature:** `(record: Record<string, any>) => void`
567
+
568
+ **Parameters:**
569
+
570
+ - `record: Record<string, any>` - - A plain object with all field values from the old schema version.
571
+
572
+ **Examples:**
573
+
574
+ ```typescript
575
+ ⁣@E.registerModel
576
+ class User extends E.Model<User> {
577
+ static pk = E.primary(User, "id");
578
+ id = E.field(E.identifier);
579
+ name = E.field(E.string);
580
+ role = E.field(E.string); // new field
581
+
582
+ static migrate(record: Record<string, any>) {
583
+ record.role ??= "user"; // default for rows that predate the 'role' field
584
+ }
585
+ }
586
+ ```
587
+
588
+ #### Model.findAll · static method
589
+
590
+ Find all instances of this model in the database, ordered by primary key.
591
+
592
+ **Signature:** `<T extends typeof Model<unknown>>(this: T, opts?: { reverse?: boolean; }) => IndexRangeIterator<T>`
593
+
594
+ **Parameters:**
595
+
596
+ - `this: T`
597
+ - `opts?: {reverse?: boolean}` - - Optional parameters.
598
+
599
+ **Returns:** An iterator.
600
+
601
+ #### Model.replaceInto · static method
602
+
603
+ Load an existing instance by primary key and update it, or create a new one.
604
+
605
+ The provided object must contain all primary key fields. If a matching row exists,
606
+ the remaining properties from `obj` are set on the loaded instance. Otherwise a
607
+ new instance is created with `obj` as its initial properties.
608
+
609
+ **Signature:** `<T extends typeof Model<any>>(this: T, obj: Partial<Omit<InstanceType<T>, "constructor">>) => InstanceType<T>`
610
+
611
+ **Parameters:**
612
+
613
+ - `this: T`
614
+ - `obj: Partial<Omit<InstanceType<T>, "constructor">>` - - Partial model data that **must** include every primary key field.
615
+
616
+ **Returns:** The loaded-and-updated or newly created instance.
617
+
618
+ #### model.preCommit · method
619
+
620
+ Optional hook called on each modified instance right before the transaction commits.
621
+ Runs before data is written to disk, so changes made here are included in the commit.
622
+
623
+ Common use cases:
624
+ - Computing derived or denormalized fields
625
+ - Enforcing cross-field validation rules
626
+ - Creating or updating related model instances (newly created instances will also
627
+ have their `preCommit()` called)
628
+
629
+ **Signature:** `() => void`
630
+
631
+ **Parameters:**
632
+
633
+
634
+ **Examples:**
635
+
636
+ ```typescript
637
+ ⁣@E.registerModel
638
+ class Post extends E.Model<Post> {
639
+ static pk = E.primary(Post, "id");
640
+ id = E.field(E.identifier);
641
+ title = E.field(E.string);
642
+ slug = E.field(E.string);
643
+
644
+ preCommit() {
645
+ this.slug = this.title.toLowerCase().replace(/\s+/g, "-");
646
+ }
647
+ }
648
+ ```
649
+
650
+ #### model.getPrimaryKey · method
651
+
652
+ **Signature:** `() => Uint8Array<ArrayBufferLike>`
653
+
654
+ **Parameters:**
655
+
656
+
657
+ **Returns:** The primary key for this instance.
658
+
659
+ #### model.getPrimaryKeyHash · method
660
+
661
+ **Signature:** `() => number`
662
+
663
+ **Parameters:**
664
+
665
+
666
+ **Returns:** A 53-bit positive integer non-cryptographic hash of the primary key, or undefined if not yet saved.
667
+
668
+ #### model.isLazyField · method
669
+
670
+ **Signature:** `(field: keyof this) => boolean`
671
+
672
+ **Parameters:**
673
+
674
+ - `field: keyof this`
675
+
676
+ #### model.preventPersist · method
677
+
678
+ Prevent this instance from being persisted to the database.
679
+
680
+ **Signature:** `() => this`
681
+
682
+ **Parameters:**
683
+
684
+
685
+ **Returns:** This model instance for chaining.
686
+
687
+ **Examples:**
688
+
689
+ ```typescript
690
+ const user = User.load("user123");
691
+ user.name = "New Name";
692
+ user.preventPersist(); // Changes won't be saved
693
+ ```
694
+
695
+ #### model.delete · method
696
+
697
+ Delete this model instance from the database.
698
+
699
+ Removes the instance and all its index entries from the database and prevents further persistence.
700
+
701
+ **Signature:** `() => void`
702
+
703
+ **Parameters:**
704
+
705
+
706
+ **Examples:**
707
+
708
+ ```typescript
709
+ const user = User.load("user123");
710
+ user.delete(); // Removes from database
711
+ ```
712
+
713
+ #### model.validate · method
714
+
715
+ Validate all fields in this model instance.
716
+
717
+ **Signature:** `(raise?: boolean) => Error[]`
718
+
719
+ **Parameters:**
720
+
721
+ - `raise: boolean` (optional) - - If true, throw on first validation error.
722
+
723
+ **Returns:** Array of validation errors (empty if valid).
724
+
725
+ **Examples:**
726
+
727
+ ```typescript
728
+ const user = new User();
729
+ const errors = user.validate();
730
+ if (errors.length > 0) {
731
+ console.log("Validation failed:", errors);
732
+ }
733
+ ```
734
+
735
+ #### model.isValid · method
736
+
737
+ Check if this model instance is valid.
738
+
739
+ **Signature:** `() => boolean`
740
+
741
+ **Parameters:**
742
+
743
+
744
+ **Returns:** true if all validations pass.
745
+
746
+ **Examples:**
747
+
748
+ ```typescript
749
+ const user = new User({name: "John"});
750
+ if (!user.isValid()) shoutAtTheUser();
751
+ ```
752
+
753
+ #### model.getState · method
754
+
755
+ **Signature:** `() => "created" | "deleted" | "loaded" | "lazy"`
756
+
757
+ **Parameters:**
758
+
759
+
760
+ #### model.toString · method
761
+
762
+ **Signature:** `() => string`
763
+
764
+ **Parameters:**
765
+
766
+
767
+ #### model.[Symbol.for('nodejs.util.inspect.custom')] · method
768
+
769
+ **Signature:** `() => string`
770
+
771
+ **Parameters:**
772
+
773
+
774
+ ### registerModel · function
775
+
776
+ Register a model class with the Edinburgh ORM system.
777
+
778
+ **Signature:** `<T extends typeof Model<unknown>>(MyModel: T) => T`
779
+
780
+ **Type Parameters:**
781
+
782
+ - `T extends typeof Model<unknown>` - The model class type.
783
+
784
+ **Parameters:**
785
+
786
+ - `MyModel: T` - - The model class to register.
787
+
788
+ **Returns:** The enhanced model class with ORM capabilities.
789
+
790
+ **Examples:**
791
+
792
+ ```typescript
793
+ ⁣@E.registerModel
794
+ class User extends E.Model<User> {
795
+ static pk = E.index(User, ["id"], "primary");
796
+ id = E.field(E.identifier);
797
+ name = E.field(E.string);
798
+ }
799
+ ```
800
+
801
+ ### field · function
802
+
803
+ Create a field definition for a model property.
804
+
805
+ This function uses TypeScript magic to return the field configuration object
806
+ while appearing to return the actual field value type to the type system.
807
+ This allows for both runtime introspection and compile-time type safety.
808
+
809
+ **Signature:** `<T>(type: TypeWrapper<T>, options?: Partial<FieldConfig<T>>) => T`
810
+
811
+ **Type Parameters:**
812
+
813
+ - `T` - The field type.
814
+
815
+ **Parameters:**
816
+
817
+ - `type: TypeWrapper<T>` - - The type wrapper for this field.
818
+ - `options: Partial<FieldConfig<T>>` (optional) - - Additional field configuration options.
819
+
820
+ **Returns:** The field value (typed as T, but actually returns FieldConfig<T>).
821
+
822
+ **Examples:**
823
+
824
+ ```typescript
825
+ class User extends E.Model<User> {
826
+ name = E.field(E.string, {description: "User's full name"});
827
+ age = E.field(E.opt(E.number), {description: "User's age", default: 25});
828
+ }
829
+ ```
830
+
831
+ ### string · constant
832
+
833
+ Type wrapper instance for the string type.
834
+
835
+ **Value:** `TypeWrapper<string>`
836
+
837
+ ### orderedString · constant
838
+
839
+ Type wrapper instance for the ordered string type, which is just like a string
840
+ except that it sorts lexicographically in the database (instead of by incrementing
841
+ length first), making it suitable for index fields that want lexicographic range
842
+ scans. Ordered strings are implemented as null-terminated UTF-8 strings, so they
843
+ may not contain null characters.
844
+
845
+ **Value:** `TypeWrapper<string>`
846
+
847
+ ### number · constant
848
+
849
+ Type wrapper instance for the number type.
850
+
851
+ **Value:** `TypeWrapper<number>`
852
+
853
+ ### dateTime · constant
854
+
855
+ Type wrapper instance for the date/time type.
856
+
857
+ **Value:** `TypeWrapper<Date>`
858
+
859
+ ### boolean · constant
860
+
861
+ Type wrapper instance for the boolean type.
862
+
863
+ **Value:** `TypeWrapper<boolean>`
864
+
865
+ ### identifier · constant
866
+
867
+ Type wrapper instance for the identifier type.
868
+
869
+ **Value:** `TypeWrapper<string>`
870
+
871
+ ### undef · constant
872
+
873
+ Type wrapper instance for the 'undefined' type.
874
+
875
+ **Value:** `TypeWrapper<undefined>`
876
+
877
+ ### opt · function
878
+
879
+ Create an optional type wrapper (allows undefined).
880
+
881
+ **Signature:** `<const T extends TypeWrapper<unknown> | BasicType>(inner: T) => TypeWrapper<T extends TypeWrapper<infer U> ? U : T>`
882
+
883
+ **Type Parameters:**
884
+
885
+ - `T extends TypeWrapper<unknown>|BasicType` - Type wrapper or basic type to make optional.
886
+
887
+ **Parameters:**
888
+
889
+ - `inner: T` - - The inner type to make optional.
890
+
891
+ **Returns:** A union type that accepts the inner type or undefined.
892
+
893
+ **Examples:**
894
+
895
+ ```typescript
896
+ const optionalString = E.opt(E.string);
897
+ const optionalNumber = E.opt(E.number);
898
+ ```
899
+
900
+ ### or · function
901
+
902
+ Create a union type wrapper from multiple type choices.
903
+
904
+ **Signature:** `<const T extends (TypeWrapper<unknown> | BasicType)[]>(...choices: T) => TypeWrapper<UnwrapTypes<T>>`
905
+
906
+ **Type Parameters:**
907
+
908
+ - `T extends (TypeWrapper<unknown>|BasicType)[]` - Array of type wrapper or basic types.
909
+
910
+ **Parameters:**
911
+
912
+ - `choices: T` - - The type choices for the union.
913
+
914
+ **Returns:** A union type instance.
915
+
916
+ **Examples:**
917
+
918
+ ```typescript
919
+ const stringOrNumber = E.or(E.string, E.number);
920
+ const status = E.or("active", "inactive", "pending");
921
+ ```
922
+
923
+ ### array · function
924
+
925
+ Create an array type wrapper with optional length constraints.
926
+
927
+ **Signature:** `<const T>(inner: TypeWrapper<T>, opts?: { min?: number; max?: number; }) => TypeWrapper<T[]>`
928
+
929
+ **Type Parameters:**
930
+
931
+ - `T` - The element type.
932
+
933
+ **Parameters:**
934
+
935
+ - `inner: TypeWrapper<T>` - - Type wrapper for array elements.
936
+ - `opts: {min?: number, max?: number}` (optional) - - Optional constraints (min/max length).
937
+
938
+ **Returns:** An array type instance.
939
+
940
+ **Examples:**
941
+
942
+ ```typescript
943
+ const stringArray = E.array(E.string);
944
+ const boundedArray = E.array(E.number, {min: 1, max: 10});
945
+ ```
946
+
947
+ ### literal · function
948
+
949
+ Create a literal type wrapper for a constant value.
950
+
951
+ **Signature:** `<const T>(value: T) => TypeWrapper<T>`
952
+
953
+ **Type Parameters:**
954
+
955
+ - `T` - The literal type.
956
+
957
+ **Parameters:**
958
+
959
+ - `value: T` - - The literal value.
960
+
961
+ **Returns:** A literal type instance.
962
+
963
+ **Examples:**
964
+
965
+ ```typescript
966
+ const statusType = E.literal("active");
967
+ const countType = E.literal(42);
968
+ ```
969
+
970
+ ### link · function
971
+
972
+ Create a link type wrapper for model relationships.
973
+
974
+ **Signature:** `<const T extends typeof Model<any>>(TargetModel: T) => TypeWrapper<InstanceType<T>>`
975
+
976
+ **Type Parameters:**
977
+
978
+ - `T extends typeof Model<any>` - The target model class.
979
+
980
+ **Parameters:**
981
+
982
+ - `TargetModel: T` - - The model class this link points to.
983
+
984
+ **Returns:** A link type instance.
985
+
986
+ **Examples:**
987
+
988
+ ```typescript
989
+ class User extends E.Model<User> {
990
+ posts = E.field(E.array(E.link(Post, 'author')));
991
+ }
992
+
993
+ class Post extends E.Model<Post> {
994
+ author = E.field(E.link(User));
995
+ }
996
+ ```
997
+
998
+ ### index · function
999
+
1000
+ Create a secondary index on model fields.
1001
+
1002
+ **Signature:** `{ <M extends typeof Model, const F extends (keyof InstanceType<M> & string)>(MyModel: M, field: F): SecondaryIndex<M, [F]>; <M extends typeof Model, const FS extends readonly (keyof InstanceType<M> & string)[]>(MyModel: M, fields: FS): SecondaryIndex<...>; }`
1003
+
1004
+ **Type Parameters:**
1005
+
1006
+ - `M extends typeof Model` - The model class.
1007
+ - `F extends (keyof InstanceType<M> & string)` - The field name (for single field index).
1008
+
1009
+ **Parameters:**
1010
+
1011
+ - `MyModel: M` - - The model class to create the index for.
1012
+ - `field: F` - - Single field name for simple indexes.
1013
+
1014
+ **Returns:** A new SecondaryIndex instance.
1015
+
1016
+ **Examples:**
1017
+
1018
+ ```typescript
1019
+ class User extends E.Model<User> {
1020
+ static byAge = E.index(User, "age");
1021
+ static byTagsDate = E.index(User, ["tags", "createdAt"]);
1022
+ }
1023
+ ```
1024
+
1025
+ ### primary · function
1026
+
1027
+ Create a primary index on model fields.
1028
+
1029
+ **Signature:** `{ <M extends typeof Model, const F extends (keyof InstanceType<M> & string)>(MyModel: M, field: F): PrimaryIndex<M, [F]>; <M extends typeof Model, const FS extends readonly (keyof InstanceType<M> & string)[]>(MyModel: M, fields: FS): PrimaryIndex<...>; }`
1030
+
1031
+ **Type Parameters:**
1032
+
1033
+ - `M extends typeof Model` - The model class.
1034
+ - `F extends (keyof InstanceType<M> & string)` - The field name (for single field index).
1035
+
1036
+ **Parameters:**
1037
+
1038
+ - `MyModel: M` - - The model class to create the index for.
1039
+ - `field: F` - - Single field name for simple indexes.
1040
+
1041
+ **Returns:** A new PrimaryIndex instance.
1042
+
1043
+ **Examples:**
1044
+
1045
+ ```typescript
1046
+ class User extends E.Model<User> {
1047
+ static pk = E.primary(User, ["id"]);
1048
+ static pkSingle = E.primary(User, "id");
1049
+ }
1050
+ ```
1051
+
1052
+ ### unique · function
1053
+
1054
+ Create a unique index on model fields.
1055
+
1056
+ **Signature:** `{ <M extends typeof Model, const F extends (keyof InstanceType<M> & string)>(MyModel: M, field: F): UniqueIndex<M, [F]>; <M extends typeof Model, const FS extends readonly (keyof InstanceType<M> & string)[]>(MyModel: M, fields: FS): UniqueIndex<...>; }`
1057
+
1058
+ **Type Parameters:**
1059
+
1060
+ - `M extends typeof Model` - The model class.
1061
+ - `F extends (keyof InstanceType<M> & string)` - The field name (for single field index).
1062
+
1063
+ **Parameters:**
1064
+
1065
+ - `MyModel: M` - - The model class to create the index for.
1066
+ - `field: F` - - Single field name for simple indexes.
1067
+
1068
+ **Returns:** A new UniqueIndex instance.
1069
+
1070
+ **Examples:**
1071
+
1072
+ ```typescript
1073
+ class User extends E.Model<User> {
1074
+ static byEmail = E.unique(User, "email");
1075
+ static byNameAge = E.unique(User, ["name", "age"]);
1076
+ }
1077
+ ```
1078
+
1079
+ ### dump · function
1080
+
1081
+ Dump database contents for debugging.
1082
+
1083
+ Prints all indexes and their data to the console for inspection.
1084
+ This is primarily useful for development and debugging purposes.
1085
+
1086
+ **Signature:** `() => void`
1087
+
1088
+ ### BaseIndex · abstract class
1089
+
1090
+ Base class for database indexes for efficient lookups on model fields.
1091
+
1092
+ Indexes enable fast queries on specific field combinations and enforce uniqueness constraints.
1093
+
1094
+ **Type Parameters:**
1095
+
1096
+ - `M extends typeof Model` - The model class this index belongs to.
1097
+ - `F extends readonly (keyof InstanceType<M> & string)[]` - The field names that make up this index.
1098
+
1099
+ **Constructor Parameters:**
1100
+
1101
+ - `MyModel`: - The model class this index belongs to.
1102
+ - `_fieldNames`: - Array of field names that make up this index.
1103
+
1104
+ #### baseIndex.find · method
1105
+
1106
+ **Signature:** `(opts?: FindOptions<IndexArgTypes<M, F>>) => IndexRangeIterator<M>`
1107
+
1108
+ **Parameters:**
1109
+
1110
+ - `opts: FindOptions<IndexArgTypes<M, F>>` (optional)
1111
+
1112
+ #### baseIndex.batchProcess · method
1113
+
1114
+ [object Object],[object Object],[object Object]
1115
+
1116
+ **Signature:** `(opts: FindOptions<IndexArgTypes<M, F>> & { limitSeconds?: number; limitRows?: number; }, callback: (row: InstanceType<M>) => void | Promise<...>) => Promise<...>`
1117
+
1118
+ **Parameters:**
1119
+
1120
+ - `opts: FindOptions<IndexArgTypes<M, F>> & { limitSeconds?: number; limitRows?: number }` (optional) - - Query options (same as `find()`), plus:
1121
+ - `callback: (row: InstanceType<M>) => void | Promise<void>` - - Called for each matching row within a transaction
1122
+
1123
+ #### baseIndex.toString · method
1124
+
1125
+ **Signature:** `() => string`
1126
+
1127
+ **Parameters:**
1128
+
1129
+
1130
+ ### UniqueIndex · class
1131
+
1132
+ Unique index that stores references to the primary key.
1133
+
1134
+ **Type Parameters:**
1135
+
1136
+ - `M extends typeof Model` - The model class this index belongs to.
1137
+ - `F extends readonly (keyof InstanceType<M> & string)[]` - The field names that make up this index.
1138
+
1139
+ #### uniqueIndex.get · method
1140
+
1141
+ Get a model instance by unique index key values.
1142
+
1143
+ **Signature:** `(...args: IndexArgTypes<M, F>) => InstanceType<M>`
1144
+
1145
+ **Parameters:**
1146
+
1147
+ - `args: IndexArgTypes<M, F>` - - The unique index key values.
1148
+
1149
+ **Returns:** The model instance if found, undefined otherwise.
1150
+
1151
+ **Examples:**
1152
+
1153
+ ```typescript
1154
+ const userByEmail = User.byEmail.get("john@example.com");
1155
+ ```
1156
+
1157
+ ### PrimaryIndex · class
1158
+
1159
+ Primary index that stores the actual model data.
1160
+
1161
+ **Type Parameters:**
1162
+
1163
+ - `M extends typeof Model` - The model class this index belongs to.
1164
+ - `F extends readonly (keyof InstanceType<M> & string)[]` - The field names that make up this index.
1165
+
1166
+ #### primaryIndex.get · method
1167
+
1168
+ Get a model instance by primary key values.
1169
+
1170
+ **Signature:** `(...args: IndexArgTypes<M, F>) => InstanceType<M>`
1171
+
1172
+ **Parameters:**
1173
+
1174
+ - `args: IndexArgTypes<M, F>` - - The primary key values.
1175
+
1176
+ **Returns:** The model instance if found, undefined otherwise.
1177
+
1178
+ **Examples:**
1179
+
1180
+ ```typescript
1181
+ const user = User.pk.get("john_doe");
1182
+ ```
1183
+
1184
+ #### primaryIndex.getLazy · method
1185
+
1186
+ Does the same as as `get()`, but will delay loading the instance from disk until the first
1187
+ property access. In case it turns out the instance doesn't exist, an error will be thrown
1188
+ at that time.
1189
+
1190
+ **Signature:** `(...args: IndexArgTypes<M, F>) => InstanceType<M>`
1191
+
1192
+ **Parameters:**
1193
+
1194
+ - `args: IndexArgTypes<M, F>` - Primary key field values. (Or a single Uint8Array containing the key.)
1195
+
1196
+ **Returns:** The (lazily loaded) model instance.
1197
+
1198
+ ### SecondaryIndex · class
1199
+
1200
+ Secondary index for non-unique lookups.
1201
+
1202
+ **Type Parameters:**
1203
+
1204
+ - `M extends typeof Model` - The model class this index belongs to.
1205
+ - `F extends readonly (keyof InstanceType<M> & string)[]` - The field names that make up this index.
1206
+
1207
+ ### Change · type
1208
+
1209
+ **Type:** `Record<any, any> | "created" | "deleted"`
1210
+
1211
+ ### Transaction · interface
1212
+
1213
+ #### transaction.id · member
1214
+
1215
+ **Type:** `number`
1216
+
1217
+ #### transaction.instances · member
1218
+
1219
+ **Type:** `Set<Model<unknown>>`
1220
+
1221
+ #### transaction.instancesByPk · member
1222
+
1223
+ **Type:** `Map<number, Model<unknown>>`
1224
+
1225
+ ### DatabaseError · constant
1226
+
1227
+ The DatabaseError class is used to represent errors that occur during database operations.
1228
+ It extends the built-in Error class and has a machine readable error code string property.
1229
+
1230
+ The lowlevel API will throw DatabaseError instances for all database-related errors.
1231
+ Invalid function arguments will throw TypeError.
1232
+
1233
+ **Value:** `DatabaseErrorConstructor`
1234
+
1235
+ ### runMigration · function
1236
+
1237
+ Run database migration: upgrade all rows to the latest schema version,
1238
+ convert old primary indices, and clean up orphaned secondary indices.
1239
+
1240
+ **Signature:** `(options?: MigrationOptions) => Promise<MigrationResult>`
1241
+
1242
+ **Parameters:**
1243
+
1244
+ - `options: MigrationOptions` (optional)
1245
+
1246
+ ### MigrationOptions · interface
1247
+
1248
+ #### migrationOptions.tables · member
1249
+
1250
+ Limit migration to specific table names.
1251
+
1252
+ **Type:** `string[]`
1253
+
1254
+ #### migrationOptions.convertOldPrimaries · member
1255
+
1256
+ Whether to convert old primary indices for known tables (default: true).
1257
+
1258
+ **Type:** `boolean`
1259
+
1260
+ #### migrationOptions.deleteOrphanedIndexes · member
1261
+
1262
+ Whether to delete orphaned secondary/unique indices (default: true).
1263
+
1264
+ **Type:** `boolean`
1265
+
1266
+ #### migrationOptions.upgradeVersions · member
1267
+
1268
+ Whether to upgrade rows to the latest version (default: true).
1269
+
1270
+ **Type:** `boolean`
1271
+
1272
+ #### migrationOptions.onProgress · member
1273
+
1274
+ Progress callback.
1275
+
1276
+ **Type:** `(info: ProgressInfo) => void`
1277
+
1278
+ ### MigrationResult · interface
1279
+
1280
+ #### migrationResult.secondaries · member
1281
+
1282
+ Per-table stats for row upgrades.
1283
+
1284
+ **Type:** `Record<string, number>`
1285
+
1286
+ #### migrationResult.primaries · member
1287
+
1288
+ Per-table stats for old primary conversions.
1289
+
1290
+ **Type:** `Record<string, number>`
1291
+
1292
+ #### migrationResult.conversionFailures · member
1293
+
1294
+ Per-table conversion failure counts by reason.
1295
+
1296
+ **Type:** `Record<string, Record<string, number>>`
1297
+
1298
+ #### migrationResult.orphaned · member
1299
+
1300
+ Number of orphaned index entries deleted.
1301
+
1302
+ **Type:** `number`
1303
+
1304
+ ## Schema Migrations
1305
+
1306
+ Edinburgh automatically tracks the schema version of each model. When you change fields, field types, indexes, or the `migrate()` function, Edinburgh detects a new schema version.
1307
+
1308
+ ### What happens automatically (lazy migration)
1309
+
1310
+ Changes to regular (non-index) field values are migrated lazily. When a row with an old schema version is loaded from disk, it is deserialized using the old field types and transformed by the optional static `migrate()` function. This is transparent and requires no downtime.
1311
+
1312
+ ```typescript
1313
+ @E.registerModel
1314
+ class User extends E.Model<User> {
1315
+ static pk = E.primary(User, "id");
1316
+ id = E.field(E.identifier);
1317
+ name = E.field(E.string);
1318
+ role = E.field(E.string); // newly added field
1319
+
1320
+ static migrate(record: Record<string, any>) {
1321
+ record.role ??= "user"; // provide a default for old rows
1322
+ }
1323
+ }
1324
+ ```
1325
+
1326
+ ### What requires `migrate-edinburgh`
1327
+
1328
+ The `migrate-edinburgh` CLI tool (or the `runMigration()` API) must be run when:
1329
+
1330
+ - **Adding or removing** secondary or unique indexes
1331
+ - **Changing the fields or types** of an existing index
1332
+ - A **`migrate()` function changes values** that are used in index fields
1333
+
1334
+ The tool populates new indexes, removes orphaned ones, and updates index entries whose values were changed by `migrate()`. It does *not* rewrite primary data rows - lazy migration handles that on read.
1335
+
1336
+ ```bash
1337
+ npx migrate-edinburgh --import ./src/models.ts
1338
+ ```
1339
+
1340
+ Run `npx migrate-edinburgh` to see all of its options.
1341
+
1342
+ You can also call `runMigration()` programmatically:
1343
+
1344
+ ```typescript
1345
+ import { runMigration } from "edinburgh";
1346
+
1347
+ const result = await runMigration({ tables: ["User"] });
1348
+ console.log(result.upgraded); // { User: 1500 }
1349
+ ```