@hono-crud/drizzle 0.1.22 → 0.1.25
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 +43 -0
- package/dist/index.d.ts +291 -41
- package/dist/index.js +2 -2
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# @hono-crud/drizzle
|
|
2
2
|
|
|
3
|
+
## 0.1.25
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9912f26: Cursor pagination now walks both ways. Cursor-mode list responses carry `result_info.prev_cursor` next to `next_cursor`; either one goes back as `?cursor=`, and both pages come back in ascending order. `prev_cursor` is present only while rows precede the page, so the first page looks exactly as before.
|
|
8
|
+
|
|
9
|
+
- The keyset key is the cursor field plus the primary key (the same tie-break sorted reads use since #144), so a non-unique cursor field such as `createdAt` walks every row exactly once in both directions. Before, rows sharing a cursor value at a page boundary were skipped.
|
|
10
|
+
- Compatible with existing callers: when the cursor field is the only primary key (the default `id`), `next_cursor` keeps its old format (`encodeCursor(id)`), and cursors minted by earlier releases are still accepted. Other cursors are URL-safe `c2.` tokens that also carry Date values (timestamp cursor fields on D1).
|
|
11
|
+
- Prisma now uses the same WHERE keyset window as Drizzle and memory instead of its native `cursor` option, so a cursor whose boundary row was deleted continues the walk instead of returning an empty page.
|
|
12
|
+
- The typed RPC client sees `prev_cursor` on `ResultInfo` and `limit` on `CrudListQuery`; the OpenAPI list schema documents `prev_cursor`.
|
|
13
|
+
- `hono-crud/internal` exports the shared keyset helpers (`resolveCursorWindow`, `encodeKeysetCursor`, `decodeKeysetCursor`, `isPastCursor`, `cursorKeyFields`) for adapter authors.
|
|
14
|
+
|
|
15
|
+
- 578bbeb: FTS5 full-text search for SQLite and Cloudflare D1 in `DrizzleSearchEndpoint`.
|
|
16
|
+
|
|
17
|
+
- `defineFts5Index({ table, columns })` describes an external-content FTS5 index once. `index.migration()` returns the statements for the virtual table, the insert/update/delete sync triggers and an initial `'rebuild'` (ready for a D1/wrangler or drizzle-kit migration); `dropMigration()` and `rebuild()` cover teardown and re-indexing. Defaults: `unicode61 remove_diacritics 2` tokenizer (case- and accent-insensitive) and `prefix='2 3'` indexes. A `casing` option matches `drizzle(client, { casing: 'snake_case' })` for columns declared without explicit names.
|
|
18
|
+
- `protected fts5 = index` on a Drizzle search endpoint switches it to an FTS5 `MATCH` ranked by `bm25()` in SQL (weighted by `fieldWeights`), before pagination, so pages are globally ordered and `total_count`/`minScore` are exact. The last term is a prefix by default (`fts5PrefixMatch: 'last' | 'all' | 'none'`), `any`/`all`/`phrase` map to `OR`/`AND`/phrase, and `?fields=` becomes an FTS5 column filter.
|
|
19
|
+
- User input is compiled to quoted FTS5 terms and bound as a parameter: FTS5 operators typed by users are plain text and never cause a syntax error.
|
|
20
|
+
- `?highlight=true` returns FTS5 `snippet()`s with the text HTML-escaped and matches wrapped in `highlightTag`.
|
|
21
|
+
- Soft-delete, filters and tenant scope apply exactly as on List (the shared WHERE builder is now `buildDrizzleListWhere`). A non-`sqlite` dialect or a searchable field that is not indexed is a 500 `CONFIGURATION_ERROR`.
|
|
22
|
+
- `hono-crud/internal` now exports the `SearchFieldConfig` and `SearchMode` types for adapters.
|
|
23
|
+
|
|
24
|
+
- baf37a9: Read-side hooks and adapter methods are typed as the stored row (`InferModelRow`) instead of the public schema: every `after` hook (class, builder, functional and config APIs), clone's `before`, `computedFields[].compute`, `policies.read`/`write`/`fields`, and the adapter methods that read or return records (`read`, `list`, `search`, `findExisting`, `create`'s return, and the rest). A Drizzle `Delete.after(prior)` can read `prior.r2Key` without a cast. Request bodies, `before` hooks on create/update/upsert/import, and `transform` keep the schema type. Migration: overrides annotated with the schema type fail to compile where a Drizzle row differs from the schema (a `text` column behind a `z.enum`, a JSON text column behind `z.array`); annotate them with `InferModelRow<typeof Model>` or drop the annotation.
|
|
25
|
+
|
|
26
|
+
## 0.1.24
|
|
27
|
+
|
|
28
|
+
### Patch Changes
|
|
29
|
+
|
|
30
|
+
- 1c742bf: Sorted list, search, and export reads now break ties on the primary key. A `?sort=` column with repeated values used to leave the order of tied rows to the database, which could differ per query, so an offset page walk could repeat one row and skip another. The adapters now order by the sort column, then each primary-key field in the same direction (`ORDER BY title ASC, id ASC`), so every page walk visits each row once, and `order=desc` is the exact reverse of `order=asc`. The memory adapter used to break ties by insertion order; it now uses the same primary-key order as the SQL adapters. Unsorted requests are unchanged.
|
|
31
|
+
|
|
32
|
+
## 0.1.23
|
|
33
|
+
|
|
34
|
+
### Patch Changes
|
|
35
|
+
|
|
36
|
+
- fabc720: Cloudflare ergonomics:
|
|
37
|
+
|
|
38
|
+
- `hono-crud/cloudflare` exports `runAfterResponse(ctx, promise)` and `createAfterResponse(ctx)` — background work that outlives the response on every runtime (`executionCtx.waitUntil` on Workers, in-band with logged rejections elsewhere). `OpenAPIRoute.runAfterResponse` now delegates to the same implementation.
|
|
39
|
+
- Health checks receive the request context (`check: async (c) => …`), so a readiness probe can reach `c.env` bindings; `createHealthRoutes<Env>` is generic over the app's Env. Zero-argument checks keep working.
|
|
40
|
+
- `AuthType` gains `'session'` for sessions resolved by an external auth library and mapped with `setAuthContext`.
|
|
41
|
+
- `sqliteAuditLogTable()` and `sqliteVersionHistoryTable()` now ship the indexes their storages' lookups need (`(table_name, record_id)` + `(timestamp)`; `(resource_table, record_id, version)`) and accept an `extraConfig` callback for more.
|
|
42
|
+
- New `docs/cloudflare.md`: wrangler template, per-request binding injection, column conventions that keep D1 happy, and the D1/KV limits to design around.
|
|
43
|
+
|
|
44
|
+
- fabc720: Engine-managed timestamps are now written in the representation each column declares, which makes soft delete and `Model.timestamps` safe on Cloudflare D1 (whose `bind()` rejects objects). Core gains a `managedTimestampValue(field)` hook on `CrudEndpoint` (default `Date.now()`, unchanged for the memory and Prisma adapters) that `applyManagedInsertFields` / `applyManagedUpdateFields` call for `createdAt` / `updatedAt`. The Drizzle adapter overrides it on every write verb — and uses the same rule for the soft-delete marker, which used to bind `new Date()` unconditionally — reading the Drizzle column's `dataType`: `date` columns (`timestamp()`, `integer({ mode: 'timestamp' | 'timestamp_ms' })`) get a `Date`, `number` columns get epoch milliseconds, `string` columns get an ISO-8601 string. New exports: `resolveTimestampValue`, `resolveTimestampRepresentation`, `TimestampRepresentation`.
|
|
45
|
+
|
|
3
46
|
## 0.1.22
|
|
4
47
|
|
|
5
48
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { MetaInput, IncludeOptions, FilterCondition, RelationConfig, CreateEndpoint, ModelObject, ReadEndpoint, UpdateEndpoint, NestedUpdateInput, NestedWriteResult, DeleteEndpoint, ListEndpoint, ListFilters, PaginatedResult, RestoreEndpoint, BatchCreateEndpoint, BatchDeleteEndpoint, BatchRestoreEndpoint, BatchUpdateEndpoint, BatchUpdateItem, AggregateEndpoint, AggregateOptions, AggregateResult, BatchUpsertEndpoint, BulkPatchEndpoint, CloneEndpoint, UpsertEndpoint, SearchEndpoint, SearchOptions, SearchResult, ExportEndpoint, ImportEndpoint, VersionCompareEndpoint, VersionHistoryEndpoint, VersionReadEndpoint, VersionRollbackEndpoint, VersioningStorage, VersionHistoryEntry, AuditLogStorage, AuditLogEntry, AuditAction, AdapterBundle } from 'hono-crud/internal';
|
|
1
|
+
import { MetaInput, IncludeOptions, FilterCondition, RelationConfig, CreateEndpoint, ModelObject, InferModelRow, ReadEndpoint, UpdateEndpoint, NestedUpdateInput, NestedWriteResult, DeleteEndpoint, ListEndpoint, ListFilters, PaginatedResult, RestoreEndpoint, BatchCreateEndpoint, BatchDeleteEndpoint, BatchRestoreEndpoint, BatchUpdateEndpoint, BatchUpdateItem, SearchMode, AggregateEndpoint, AggregateOptions, AggregateResult, BatchUpsertEndpoint, BulkPatchEndpoint, CloneEndpoint, UpsertEndpoint, SearchEndpoint, SearchFieldConfig, SearchOptions, SearchResult, ExportEndpoint, ImportEndpoint, VersionCompareEndpoint, VersionHistoryEndpoint, VersionReadEndpoint, VersionRollbackEndpoint, VersioningStorage, VersionHistoryEntry, AuditLogStorage, AuditLogEntry, AuditAction, AdapterBundle } from 'hono-crud/internal';
|
|
2
2
|
import { Env } from 'hono';
|
|
3
|
+
import * as drizzle_orm from 'drizzle-orm';
|
|
4
|
+
import { BuildColumns } from 'drizzle-orm';
|
|
3
5
|
import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
|
|
6
|
+
import { SQLiteTableExtraConfigValue } from 'drizzle-orm/sqlite-core';
|
|
4
7
|
import { z } from 'zod';
|
|
5
8
|
|
|
6
9
|
/**
|
|
@@ -40,6 +43,7 @@ interface DrizzleSql {
|
|
|
40
43
|
*/
|
|
41
44
|
interface QueryBuilder<Row = unknown> extends PromiseLike<Row[]> {
|
|
42
45
|
where(condition: unknown): QueryBuilder<Row>;
|
|
46
|
+
innerJoin(source: unknown, on: unknown): QueryBuilder<Row>;
|
|
43
47
|
limit(n: number): QueryBuilder<Row>;
|
|
44
48
|
offset(n: number): QueryBuilder<Row>;
|
|
45
49
|
orderBy(...columns: unknown[]): QueryBuilder<Row>;
|
|
@@ -76,8 +80,9 @@ interface Database<Row = unknown> {
|
|
|
76
80
|
* Casts a database handle to the internal {@link Database} interface for method
|
|
77
81
|
* calls, parametrized over the row type `Row` that queries resolve to. This is
|
|
78
82
|
* the single sanctioned boundary `as`: all Drizzle databases expose these
|
|
79
|
-
* methods at runtime, and the row type
|
|
80
|
-
* (`
|
|
83
|
+
* methods at runtime, and the row type is the model's stored row
|
|
84
|
+
* (`InferModelRow<M['model']>`: the table's `$inferSelect` matched
|
|
85
|
+
* structurally), never an imported drizzle-orm type.
|
|
81
86
|
*/
|
|
82
87
|
declare function cast<Row = unknown>(instance: unknown): Database<Row>;
|
|
83
88
|
/**
|
|
@@ -282,11 +287,13 @@ declare abstract class DrizzleCreateEndpoint<E extends Env = Env, M extends Meta
|
|
|
282
287
|
*/
|
|
283
288
|
protected getDb(): DB;
|
|
284
289
|
protected getTable(): DrizzleTable;
|
|
290
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
291
|
+
protected managedTimestampValue(field: string): unknown;
|
|
285
292
|
/**
|
|
286
293
|
* Gets a related table from the relation config.
|
|
287
294
|
*/
|
|
288
295
|
protected getRelatedTable(relationConfig: RelationConfig): DrizzleTable | undefined;
|
|
289
|
-
create(data: ModelObject<M['model']>, tx?: unknown): Promise<
|
|
296
|
+
create(data: ModelObject<M['model']>, tx?: unknown): Promise<InferModelRow<M['model']>>;
|
|
290
297
|
/**
|
|
291
298
|
* Creates nested related records.
|
|
292
299
|
*/
|
|
@@ -312,7 +319,7 @@ declare abstract class DrizzleReadEndpoint<E extends Env = Env, M extends MetaIn
|
|
|
312
319
|
protected getDb(): DB;
|
|
313
320
|
protected getTable(): DrizzleTable;
|
|
314
321
|
protected getColumn(field: string): DrizzleColumn;
|
|
315
|
-
read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<
|
|
322
|
+
read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<InferModelRow<M['model']> | null>;
|
|
316
323
|
}
|
|
317
324
|
/**
|
|
318
325
|
* Drizzle Update endpoint.
|
|
@@ -335,6 +342,8 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
|
|
|
335
342
|
/** Gets the database instance from property, transaction, or context */
|
|
336
343
|
protected getDb(): DB;
|
|
337
344
|
protected getTable(): DrizzleTable;
|
|
345
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
346
|
+
protected managedTimestampValue(field: string): unknown;
|
|
338
347
|
protected getColumn(field: string): DrizzleColumn;
|
|
339
348
|
/**
|
|
340
349
|
* Gets a related table from the relation config.
|
|
@@ -343,8 +352,8 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
|
|
|
343
352
|
/**
|
|
344
353
|
* Finds an existing record for audit logging.
|
|
345
354
|
*/
|
|
346
|
-
protected findExisting(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<
|
|
347
|
-
update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>, tx?: unknown): Promise<
|
|
355
|
+
protected findExisting(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
|
|
356
|
+
update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
|
|
348
357
|
/**
|
|
349
358
|
* Processes nested write operations.
|
|
350
359
|
*/
|
|
@@ -375,6 +384,8 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
|
|
|
375
384
|
/** Gets the database instance from property, transaction, or context */
|
|
376
385
|
protected getDb(): DB;
|
|
377
386
|
protected getTable(): DrizzleTable;
|
|
387
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
388
|
+
protected managedTimestampValue(field: string): unknown;
|
|
378
389
|
protected getColumn(field: string): DrizzleColumn;
|
|
379
390
|
/**
|
|
380
391
|
* Gets a related table from the relation config.
|
|
@@ -383,8 +394,8 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
|
|
|
383
394
|
/**
|
|
384
395
|
* Finds a record without deleting it (for constraint checks).
|
|
385
396
|
*/
|
|
386
|
-
findForDelete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<
|
|
387
|
-
delete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<
|
|
397
|
+
findForDelete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
|
|
398
|
+
delete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
|
|
388
399
|
/**
|
|
389
400
|
* Counts related records for restrict check.
|
|
390
401
|
*/
|
|
@@ -428,13 +439,13 @@ declare abstract class DrizzleListEndpoint<E extends Env = Env, M extends MetaIn
|
|
|
428
439
|
* See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
429
440
|
*/
|
|
430
441
|
protected dialect: DrizzleDialect;
|
|
431
|
-
/** Keyset cursor pagination is implemented (
|
|
442
|
+
/** Keyset cursor pagination is implemented (both directions, PK tie-break). */
|
|
432
443
|
protected supportsCursorPagination: boolean;
|
|
433
444
|
/** Gets the database instance from property or context */
|
|
434
445
|
protected getDb(): DB;
|
|
435
446
|
protected getTable(): DrizzleTable;
|
|
436
447
|
protected getColumn(field: string): DrizzleColumn;
|
|
437
|
-
list(filters: ListFilters): Promise<PaginatedResult<
|
|
448
|
+
list(filters: ListFilters): Promise<PaginatedResult<InferModelRow<M['model']>>>;
|
|
438
449
|
}
|
|
439
450
|
/**
|
|
440
451
|
* Drizzle Restore endpoint for un-deleting soft-deleted records.
|
|
@@ -458,7 +469,7 @@ declare abstract class DrizzleRestoreEndpoint<E extends Env = Env, M extends Met
|
|
|
458
469
|
protected getDb(): DB;
|
|
459
470
|
protected getTable(): DrizzleTable;
|
|
460
471
|
protected getColumn(field: string): DrizzleColumn;
|
|
461
|
-
restore(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<
|
|
472
|
+
restore(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
|
|
462
473
|
/**
|
|
463
474
|
* Override handle to wrap in transaction when useTransaction is true.
|
|
464
475
|
*/
|
|
@@ -475,7 +486,9 @@ declare abstract class DrizzleBatchCreateEndpoint<E extends Env = Env, M extends
|
|
|
475
486
|
/** Gets the database instance from property or context */
|
|
476
487
|
protected getDb(): DB;
|
|
477
488
|
protected getTable(): DrizzleTable;
|
|
478
|
-
|
|
489
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
490
|
+
protected managedTimestampValue(field: string): unknown;
|
|
491
|
+
batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<InferModelRow<M['model']>[]>;
|
|
479
492
|
}
|
|
480
493
|
/**
|
|
481
494
|
* Drizzle Batch Update endpoint.
|
|
@@ -489,9 +502,11 @@ declare abstract class DrizzleBatchUpdateEndpoint<E extends Env = Env, M extends
|
|
|
489
502
|
/** Gets the database instance from property or context */
|
|
490
503
|
protected getDb(): DB;
|
|
491
504
|
protected getTable(): DrizzleTable;
|
|
505
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
506
|
+
protected managedTimestampValue(field: string): unknown;
|
|
492
507
|
protected getColumn(field: string): DrizzleColumn;
|
|
493
508
|
batchUpdate(items: BatchUpdateItem<ModelObject<M['model']>>[]): Promise<{
|
|
494
|
-
updated:
|
|
509
|
+
updated: InferModelRow<M['model']>[];
|
|
495
510
|
notFound: string[];
|
|
496
511
|
}>;
|
|
497
512
|
}
|
|
@@ -507,9 +522,11 @@ declare abstract class DrizzleBatchDeleteEndpoint<E extends Env = Env, M extends
|
|
|
507
522
|
/** Gets the database instance from property or context. */
|
|
508
523
|
protected getDb(): DB;
|
|
509
524
|
protected getTable(): DrizzleTable;
|
|
525
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
526
|
+
protected managedTimestampValue(field: string): unknown;
|
|
510
527
|
protected getColumn(field: string): DrizzleColumn;
|
|
511
528
|
batchDelete(ids: string[]): Promise<{
|
|
512
|
-
deleted:
|
|
529
|
+
deleted: InferModelRow<M['model']>[];
|
|
513
530
|
notFound: string[];
|
|
514
531
|
}>;
|
|
515
532
|
}
|
|
@@ -527,11 +544,137 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
|
|
|
527
544
|
protected getTable(): DrizzleTable;
|
|
528
545
|
protected getColumn(field: string): DrizzleColumn;
|
|
529
546
|
batchRestore(ids: string[]): Promise<{
|
|
530
|
-
restored:
|
|
547
|
+
restored: InferModelRow<M['model']>[];
|
|
531
548
|
notFound: string[];
|
|
532
549
|
}>;
|
|
533
550
|
}
|
|
534
551
|
|
|
552
|
+
/** Default FTS5 tokenizer: Unicode-aware, accent-insensitive (`ação` ≡ `acao`). */
|
|
553
|
+
declare const DEFAULT_FTS5_TOKENIZE = "unicode61 remove_diacritics 2";
|
|
554
|
+
/** Default FTS5 prefix indexes (fast `ab*` / `abc*` prefix queries). */
|
|
555
|
+
declare const DEFAULT_FTS5_PREFIX_INDEX: readonly number[];
|
|
556
|
+
/** Configuration accepted by {@link defineFts5Index}. */
|
|
557
|
+
interface Fts5IndexConfig {
|
|
558
|
+
/**
|
|
559
|
+
* The Drizzle table whose rows are indexed. It becomes the FTS5
|
|
560
|
+
* external-content table: the index stores only tokens, and reads row text
|
|
561
|
+
* (for `snippet()`) back from this table.
|
|
562
|
+
*/
|
|
563
|
+
table: DrizzleTable;
|
|
564
|
+
/**
|
|
565
|
+
* Model fields to index, in FTS5 column order (Drizzle property names; the
|
|
566
|
+
* index uses their database column names). Text columns only.
|
|
567
|
+
*/
|
|
568
|
+
columns: readonly string[];
|
|
569
|
+
/** FTS5 virtual table name. Defaults to `<table>_fts`. */
|
|
570
|
+
name?: string;
|
|
571
|
+
/**
|
|
572
|
+
* The `casing` your Drizzle database is created with (`drizzle(client, {
|
|
573
|
+
* casing })`). Columns declared without an explicit name are then stored
|
|
574
|
+
* under the converted name (`titlePt` → `title_pt`), and the generated SQL
|
|
575
|
+
* must use it too. Omit when columns carry explicit names or no casing is
|
|
576
|
+
* configured.
|
|
577
|
+
*/
|
|
578
|
+
casing?: 'snake_case' | 'camelCase';
|
|
579
|
+
/**
|
|
580
|
+
* Integer column linking index rows to content rows (FTS5
|
|
581
|
+
* `content_rowid`). Defaults to SQLite's implicit `rowid`, which is right
|
|
582
|
+
* for any rowid table. Set it to a model field when the table has an
|
|
583
|
+
* `INTEGER PRIMARY KEY` you want to name explicitly.
|
|
584
|
+
*/
|
|
585
|
+
contentRowid?: string;
|
|
586
|
+
/** FTS5 `tokenize` option. Defaults to {@link DEFAULT_FTS5_TOKENIZE}. */
|
|
587
|
+
tokenize?: string;
|
|
588
|
+
/**
|
|
589
|
+
* FTS5 `prefix` option: token-prefix lengths to index for fast prefix
|
|
590
|
+
* queries. Defaults to {@link DEFAULT_FTS5_PREFIX_INDEX}; `[]` disables
|
|
591
|
+
* prefix indexes (prefix queries still work, just slower).
|
|
592
|
+
*/
|
|
593
|
+
prefixIndex?: readonly number[];
|
|
594
|
+
}
|
|
595
|
+
/** An FTS5 index definition (see {@link defineFts5Index}). */
|
|
596
|
+
interface Fts5Index {
|
|
597
|
+
/** FTS5 virtual table name. */
|
|
598
|
+
readonly name: string;
|
|
599
|
+
/** The content table (the Drizzle table passed in). */
|
|
600
|
+
readonly table: DrizzleTable;
|
|
601
|
+
/** Content table's database name. */
|
|
602
|
+
readonly tableName: string;
|
|
603
|
+
/** Indexed model fields, in FTS5 column order. */
|
|
604
|
+
readonly fields: readonly string[];
|
|
605
|
+
/** Database column names of {@link fields}, in the same order. */
|
|
606
|
+
readonly columnNames: readonly string[];
|
|
607
|
+
/** Content-rowid model field, or `undefined` for SQLite's implicit `rowid`. */
|
|
608
|
+
readonly contentRowid?: string;
|
|
609
|
+
/** Database column name of {@link contentRowid} (`'rowid'` when unset). */
|
|
610
|
+
readonly contentRowidColumn: string;
|
|
611
|
+
/**
|
|
612
|
+
* SQL statements that create the index, keep it in sync, and fill it from
|
|
613
|
+
* existing rows: `CREATE VIRTUAL TABLE`, the insert/delete/update triggers,
|
|
614
|
+
* and a `'rebuild'`. Idempotent (`IF NOT EXISTS`). Each entry is one
|
|
615
|
+
* complete statement — run them in order (a D1 batch, a wrangler/drizzle-kit
|
|
616
|
+
* migration file, or one `db.run(sql.raw(statement))` each).
|
|
617
|
+
*/
|
|
618
|
+
migration(): string[];
|
|
619
|
+
/** SQL statements that drop the triggers and the virtual table. */
|
|
620
|
+
dropMigration(): string[];
|
|
621
|
+
/**
|
|
622
|
+
* The `'rebuild'` statement: re-reads every content row into the index.
|
|
623
|
+
* Run it after bulk changes that bypass the triggers, or after a `VACUUM`
|
|
624
|
+
* on a table without an `INTEGER PRIMARY KEY` (which may renumber rowids).
|
|
625
|
+
*/
|
|
626
|
+
rebuild(): string;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Describes an external-content FTS5 index over a Drizzle SQLite/D1 table.
|
|
630
|
+
* Validation runs at definition time and throws a plain `Error` (fail fast
|
|
631
|
+
* at boot).
|
|
632
|
+
*
|
|
633
|
+
* @example
|
|
634
|
+
* ```ts
|
|
635
|
+
* export const gamesFts = defineFts5Index({
|
|
636
|
+
* table: games,
|
|
637
|
+
* columns: ['title', 'description'],
|
|
638
|
+
* });
|
|
639
|
+
* // migration: gamesFts.migration() → CREATE VIRTUAL TABLE + triggers
|
|
640
|
+
* class GameSearch extends DrizzleSearchEndpoint {
|
|
641
|
+
* _meta = gameMeta;
|
|
642
|
+
* protected override fts5 = gamesFts;
|
|
643
|
+
* }
|
|
644
|
+
* ```
|
|
645
|
+
*/
|
|
646
|
+
declare function defineFts5Index(config: Fts5IndexConfig): Fts5Index;
|
|
647
|
+
/** Which search terms get FTS5 prefix matching (`term*`). */
|
|
648
|
+
type Fts5PrefixMatch = 'last' | 'all' | 'none';
|
|
649
|
+
/** Options for {@link buildFts5Match}. */
|
|
650
|
+
interface Fts5MatchOptions {
|
|
651
|
+
/** `any` → OR, `all` → AND, `phrase` → one phrase. */
|
|
652
|
+
mode: SearchMode;
|
|
653
|
+
/** Prefix-match policy. Defaults to `'last'` (search-as-you-type). */
|
|
654
|
+
prefix?: Fts5PrefixMatch;
|
|
655
|
+
/**
|
|
656
|
+
* Restrict the match to these FTS5 column names (an FTS5 column filter).
|
|
657
|
+
* Omit to search every indexed column.
|
|
658
|
+
*/
|
|
659
|
+
columns?: readonly string[];
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Splits user input into FTS5 terms: whitespace-separated chunks that contain
|
|
663
|
+
* at least one letter or digit (pure punctuation yields no FTS5 token).
|
|
664
|
+
*/
|
|
665
|
+
declare function tokenizeFts5Query(query: string): string[];
|
|
666
|
+
/**
|
|
667
|
+
* Compiles user search text into a safe FTS5 query expression, or `null`
|
|
668
|
+
* when it contains no searchable term.
|
|
669
|
+
*
|
|
670
|
+
* Every term is emitted as a quoted FTS5 string, so FTS5 operators typed by
|
|
671
|
+
* the user (`AND`, `OR`, `NOT`, `NEAR`, `*`, `^`, `:`, parentheses, column
|
|
672
|
+
* filters) are inert text and the expression is always syntactically valid —
|
|
673
|
+
* malformed input can never surface as an `fts5: syntax error`. Prefix
|
|
674
|
+
* matching appends `*` outside the quotes.
|
|
675
|
+
*/
|
|
676
|
+
declare function buildFts5Match(query: string, options: Fts5MatchOptions): string | null;
|
|
677
|
+
|
|
535
678
|
/**
|
|
536
679
|
* Drizzle Upsert endpoint.
|
|
537
680
|
* Creates a record if it doesn't exist, updates it if it does.
|
|
@@ -552,10 +695,12 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
|
|
|
552
695
|
/** Gets the database instance from property or context. */
|
|
553
696
|
protected getDb(): DB;
|
|
554
697
|
protected getTable(): DrizzleTable;
|
|
698
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
699
|
+
protected managedTimestampValue(field: string): unknown;
|
|
555
700
|
protected getColumn(field: string): DrizzleColumn;
|
|
556
|
-
findExisting(data: Partial<ModelObject<M['model']>>): Promise<
|
|
557
|
-
create(data: Partial<ModelObject<M['model']>>): Promise<
|
|
558
|
-
update(existing:
|
|
701
|
+
findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
|
|
702
|
+
create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
703
|
+
update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
559
704
|
/**
|
|
560
705
|
* Performs a native database upsert using ON CONFLICT DO UPDATE (PostgreSQL/SQLite)
|
|
561
706
|
* or ON DUPLICATE KEY UPDATE (MySQL).
|
|
@@ -572,7 +717,7 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
|
|
|
572
717
|
* rather than unified.
|
|
573
718
|
*/
|
|
574
719
|
protected nativeUpsert(data: Partial<ModelObject<M['model']>>, _tx?: unknown): Promise<{
|
|
575
|
-
data:
|
|
720
|
+
data: InferModelRow<M['model']>;
|
|
576
721
|
created: boolean;
|
|
577
722
|
}>;
|
|
578
723
|
}
|
|
@@ -590,10 +735,12 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
590
735
|
/** Gets the database instance from property or context. */
|
|
591
736
|
protected getDb(): DB;
|
|
592
737
|
protected getTable(): DrizzleTable;
|
|
738
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
739
|
+
protected managedTimestampValue(field: string): unknown;
|
|
593
740
|
protected getColumn(field: string): DrizzleColumn;
|
|
594
|
-
findExisting(data: Partial<ModelObject<M['model']>>): Promise<
|
|
595
|
-
create(data: Partial<ModelObject<M['model']>>): Promise<
|
|
596
|
-
update(existing:
|
|
741
|
+
findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
|
|
742
|
+
create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
743
|
+
update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
597
744
|
/**
|
|
598
745
|
* Performs a native database batch upsert using ON CONFLICT DO UPDATE (PostgreSQL/SQLite)
|
|
599
746
|
* or ON DUPLICATE KEY UPDATE (MySQL).
|
|
@@ -611,7 +758,7 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
611
758
|
*/
|
|
612
759
|
protected nativeBatchUpsert(items: Partial<ModelObject<M['model']>>[], _tx?: unknown): Promise<{
|
|
613
760
|
items: Array<{
|
|
614
|
-
data:
|
|
761
|
+
data: InferModelRow<M['model']>;
|
|
615
762
|
created: boolean;
|
|
616
763
|
index: number;
|
|
617
764
|
}>;
|
|
@@ -643,13 +790,15 @@ declare abstract class DrizzleBulkPatchEndpoint<E extends Env = Env, M extends M
|
|
|
643
790
|
/** Gets the database instance from property or context. */
|
|
644
791
|
protected getDb(): DB;
|
|
645
792
|
protected getTable(): DrizzleTable;
|
|
793
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
794
|
+
protected managedTimestampValue(field: string): unknown;
|
|
646
795
|
protected getColumn(field: string): DrizzleColumn;
|
|
647
796
|
/** WHERE clause shared by countMatching/applyPatch: filters + soft-delete guard. */
|
|
648
797
|
private buildConditions;
|
|
649
798
|
countMatching(filters: ListFilters): Promise<number>;
|
|
650
799
|
applyPatch(data: Partial<ModelObject<M['model']>>, filters: ListFilters): Promise<{
|
|
651
800
|
updated: number;
|
|
652
|
-
records?:
|
|
801
|
+
records?: InferModelRow<M['model']>[];
|
|
653
802
|
}>;
|
|
654
803
|
}
|
|
655
804
|
/**
|
|
@@ -714,7 +863,7 @@ declare abstract class DrizzleVersionRollbackEndpoint<E extends Env = Env, M ext
|
|
|
714
863
|
field: string;
|
|
715
864
|
value: string;
|
|
716
865
|
}): Promise<boolean>;
|
|
717
|
-
rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<
|
|
866
|
+
rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<InferModelRow<M['model']>>;
|
|
718
867
|
}
|
|
719
868
|
/**
|
|
720
869
|
* Drizzle Aggregate endpoint.
|
|
@@ -739,10 +888,13 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
|
|
|
739
888
|
* Provides full-text search with relevance scoring and highlighting.
|
|
740
889
|
*
|
|
741
890
|
* For PostgreSQL, this can leverage native tsvector/tsquery for better performance.
|
|
742
|
-
* For SQLite/
|
|
743
|
-
*
|
|
891
|
+
* For SQLite / Cloudflare D1, set {@link DrizzleSearchEndpoint.fts5} to an
|
|
892
|
+
* index from `defineFts5Index()` for FTS5 full-text search ranked by bm25.
|
|
893
|
+
* Otherwise it falls back to dialect-native substring-position search
|
|
894
|
+
* (INSTR/POSITION/LOCATE) with in-memory scoring.
|
|
744
895
|
*
|
|
745
896
|
* Features:
|
|
897
|
+
* - SQLite/D1: FTS5 MATCH with bm25 ranking, prefix matching and snippets
|
|
746
898
|
* - PostgreSQL: Uses to_tsvector() and plainto_tsquery() for native full-text search
|
|
747
899
|
* - Fallback: dialect-native substring match with in-memory scoring
|
|
748
900
|
* - Configurable field weights
|
|
@@ -795,12 +947,41 @@ declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends Meta
|
|
|
795
947
|
* PostgreSQL text search configuration (e.g., 'english', 'simple').
|
|
796
948
|
*/
|
|
797
949
|
protected vectorConfig: string;
|
|
950
|
+
/**
|
|
951
|
+
* SQLite / D1 FTS5 index (from `defineFts5Index()`). When set, search runs
|
|
952
|
+
* as an FTS5 `MATCH` against this external-content index: rows are ranked
|
|
953
|
+
* by `bm25()` in SQL (weighted by the searchable fields' weights) before
|
|
954
|
+
* pagination, prefix matching follows {@link fts5PrefixMatch}, and
|
|
955
|
+
* highlights come from FTS5 `snippet()`. Requires `dialect: 'sqlite'`.
|
|
956
|
+
*
|
|
957
|
+
* Without `searchFields`/`searchableFields`, the indexed columns are the
|
|
958
|
+
* searchable fields. Explicitly configured searchable fields must all be
|
|
959
|
+
* indexed columns.
|
|
960
|
+
*/
|
|
961
|
+
protected fts5?: Fts5Index;
|
|
962
|
+
/**
|
|
963
|
+
* FTS5 prefix matching: `'last'` (default) makes the last term a prefix
|
|
964
|
+
* (search-as-you-type: `super mar` → `super AND mar*`), `'all'` makes every
|
|
965
|
+
* term a prefix, `'none'` matches whole tokens only.
|
|
966
|
+
*/
|
|
967
|
+
protected fts5PrefixMatch: Fts5PrefixMatch;
|
|
968
|
+
/** Approximate snippet length, in tokens, of FTS5 highlights (1-64). */
|
|
969
|
+
protected fts5SnippetTokens: number;
|
|
970
|
+
protected getSearchableFields(): Record<string, SearchFieldConfig>;
|
|
798
971
|
protected getTable(): DrizzleTable;
|
|
799
972
|
protected getColumn(field: string): DrizzleColumn;
|
|
800
973
|
/**
|
|
801
974
|
* Performs search on database.
|
|
802
975
|
*/
|
|
803
|
-
search(options: SearchOptions, filters: ListFilters): Promise<SearchResult<
|
|
976
|
+
search(options: SearchOptions, filters: ListFilters): Promise<SearchResult<InferModelRow<M['model']>>>;
|
|
977
|
+
/**
|
|
978
|
+
* FTS5 search path (SQLite / D1). Joins the content table to the FTS5 hits
|
|
979
|
+
* (`rowid`, `bm25()`, `snippet()` per column), applies the same WHERE as
|
|
980
|
+
* List (soft-delete, filters, tenant scope), counts, and pages in SQL.
|
|
981
|
+
* Order: bm25 rank (best first), then the primary key; an explicit
|
|
982
|
+
* `order_by` (`?sort=` or `defaultSort`) takes precedence over the rank.
|
|
983
|
+
*/
|
|
984
|
+
protected searchFts5(index: Fts5Index, options: SearchOptions, filters: ListFilters): Promise<SearchResult<InferModelRow<M['model']>>>;
|
|
804
985
|
}
|
|
805
986
|
/**
|
|
806
987
|
* Drizzle Export endpoint.
|
|
@@ -819,7 +1000,7 @@ declare abstract class DrizzleExportEndpoint<E extends Env = Env, M extends Meta
|
|
|
819
1000
|
protected getDb(): DB;
|
|
820
1001
|
protected getTable(): DrizzleTable;
|
|
821
1002
|
protected getColumn(field: string): DrizzleColumn;
|
|
822
|
-
list(filters: ListFilters): Promise<PaginatedResult<
|
|
1003
|
+
list(filters: ListFilters): Promise<PaginatedResult<InferModelRow<M['model']>>>;
|
|
823
1004
|
}
|
|
824
1005
|
/**
|
|
825
1006
|
* Drizzle Import endpoint.
|
|
@@ -831,19 +1012,21 @@ declare abstract class DrizzleImportEndpoint<E extends Env = Env, M extends Meta
|
|
|
831
1012
|
/** Gets the database instance from property or context. */
|
|
832
1013
|
protected getDb(): DB;
|
|
833
1014
|
protected getTable(): DrizzleTable;
|
|
1015
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
1016
|
+
protected managedTimestampValue(field: string): unknown;
|
|
834
1017
|
protected getColumn(field: string): DrizzleColumn;
|
|
835
1018
|
/**
|
|
836
1019
|
* Finds an existing record by upsert keys.
|
|
837
1020
|
*/
|
|
838
|
-
findExisting(data: Partial<ModelObject<M['model']>>): Promise<
|
|
1021
|
+
findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
|
|
839
1022
|
/**
|
|
840
1023
|
* Creates a new record.
|
|
841
1024
|
*/
|
|
842
|
-
create(data: Partial<ModelObject<M['model']>>): Promise<
|
|
1025
|
+
create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
843
1026
|
/**
|
|
844
1027
|
* Updates an existing record.
|
|
845
1028
|
*/
|
|
846
|
-
update(existing:
|
|
1029
|
+
update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
|
|
847
1030
|
}
|
|
848
1031
|
/**
|
|
849
1032
|
* Drizzle Clone endpoint.
|
|
@@ -869,11 +1052,13 @@ declare abstract class DrizzleCloneEndpoint<E extends Env = Env, M extends MetaI
|
|
|
869
1052
|
/** Gets the database instance from property or context. */
|
|
870
1053
|
protected getDb(): DB;
|
|
871
1054
|
protected getTable(): DrizzleTable;
|
|
1055
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
1056
|
+
protected managedTimestampValue(field: string): unknown;
|
|
872
1057
|
protected getColumn(field: string): DrizzleColumn;
|
|
873
1058
|
/** Generates the primary-key value for the cloned row. Defaults to UUIDv4. */
|
|
874
1059
|
protected generateId(): string;
|
|
875
|
-
findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<
|
|
876
|
-
createClone(data:
|
|
1060
|
+
findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<InferModelRow<M['model']> | null>;
|
|
1061
|
+
createClone(data: InferModelRow<M['model']>): Promise<InferModelRow<M['model']>>;
|
|
877
1062
|
}
|
|
878
1063
|
|
|
879
1064
|
/**
|
|
@@ -1003,14 +1188,30 @@ declare class DrizzleVersioningStorage implements VersioningStorage {
|
|
|
1003
1188
|
pruneVersions(tableName: string, recordId: string | number, keepCount: number): Promise<number>;
|
|
1004
1189
|
deleteAllVersions(tableName: string, recordId: string | number): Promise<number>;
|
|
1005
1190
|
}
|
|
1191
|
+
/** Column builders of {@link sqliteVersionHistoryTable} (fresh per call — builders are single-use). */
|
|
1192
|
+
declare function versionHistoryColumns(): {
|
|
1193
|
+
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
1194
|
+
resourceTable: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"resource_table", [string, ...string[]], number | undefined>>;
|
|
1195
|
+
recordId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record_id", [string, ...string[]], number | undefined>>;
|
|
1196
|
+
version: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"version">>;
|
|
1197
|
+
data: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"data", [string, ...string[]], number | undefined>>;
|
|
1198
|
+
createdAt: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"created_at">>;
|
|
1199
|
+
changedBy: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changed_by", [string, ...string[]], number | undefined>;
|
|
1200
|
+
changeReason: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"change_reason", [string, ...string[]], number | undefined>;
|
|
1201
|
+
changes: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changes", [string, ...string[]], number | undefined>;
|
|
1202
|
+
};
|
|
1203
|
+
/** The built columns handed to an `extraConfig` callback of {@link sqliteVersionHistoryTable}. */
|
|
1204
|
+
type SqliteVersionHistoryColumns = BuildColumns<string, ReturnType<typeof versionHistoryColumns>, 'sqlite'>;
|
|
1006
1205
|
/**
|
|
1007
1206
|
* Build a SQLite/D1 history table with the columns
|
|
1008
|
-
* {@link DrizzleVersioningStorage} expects.
|
|
1009
|
-
*
|
|
1207
|
+
* {@link DrizzleVersioningStorage} expects. Ships with an index on
|
|
1208
|
+
* `(resource_table, record_id, version)`, which backs every per-record
|
|
1209
|
+
* lookup the storage performs.
|
|
1010
1210
|
*
|
|
1011
1211
|
* @param name - Table name. Default `version_history`.
|
|
1212
|
+
* @param extraConfig - Additional indexes/constraints, appended to the default.
|
|
1012
1213
|
*/
|
|
1013
|
-
declare function sqliteVersionHistoryTable(name?: string): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1214
|
+
declare function sqliteVersionHistoryTable(name?: string, extraConfig?: (table: SqliteVersionHistoryColumns) => SQLiteTableExtraConfigValue[]): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1014
1215
|
name: string;
|
|
1015
1216
|
schema: undefined;
|
|
1016
1217
|
columns: {
|
|
@@ -1258,15 +1459,34 @@ declare class DrizzleAuditLogStorage implements AuditLogStorage {
|
|
|
1258
1459
|
offset?: number;
|
|
1259
1460
|
}): Promise<AuditLogEntry[]>;
|
|
1260
1461
|
}
|
|
1462
|
+
/** Column builders of {@link sqliteAuditLogTable} (fresh per call — builders are single-use). */
|
|
1463
|
+
declare function auditLogColumns(): {
|
|
1464
|
+
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
1465
|
+
tableName: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"table_name", [string, ...string[]], number | undefined>>;
|
|
1466
|
+
recordId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record_id", [string, ...string[]], number | undefined>>;
|
|
1467
|
+
action: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"action", [string, ...string[]], number | undefined>>;
|
|
1468
|
+
timestamp: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"timestamp">>;
|
|
1469
|
+
userId: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"user_id", [string, ...string[]], number | undefined>;
|
|
1470
|
+
record: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record", [string, ...string[]], number | undefined>;
|
|
1471
|
+
previousRecord: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"previous_record", [string, ...string[]], number | undefined>;
|
|
1472
|
+
changes: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changes", [string, ...string[]], number | undefined>;
|
|
1473
|
+
metadata: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"metadata", [string, ...string[]], number | undefined>;
|
|
1474
|
+
};
|
|
1475
|
+
/** The built columns handed to an `extraConfig` callback of {@link sqliteAuditLogTable}. */
|
|
1476
|
+
type SqliteAuditLogColumns = BuildColumns<string, ReturnType<typeof auditLogColumns>, 'sqlite'>;
|
|
1261
1477
|
/**
|
|
1262
1478
|
* Build a SQLite/D1 audit table with the columns {@link DrizzleAuditLogStorage}
|
|
1263
1479
|
* expects. `tableName`/`recordId`/`timestamp` back the per-record lookups and
|
|
1264
|
-
* the `getAll` filters the storage performs
|
|
1480
|
+
* the `getAll` filters the storage performs, so the table ships with indexes
|
|
1481
|
+
* on `(table_name, record_id)` and `(timestamp)` — D1 charges per row
|
|
1482
|
+
* scanned, and an unindexed audit table grows without bound.
|
|
1265
1483
|
*
|
|
1266
1484
|
* @param name - Table name. Default `audit_logs` (matches `AuditConfig`'s
|
|
1267
1485
|
* default `tableName`).
|
|
1486
|
+
* @param extraConfig - Additional indexes/constraints, appended to the
|
|
1487
|
+
* defaults (`(t) => [index('audit_user_idx').on(t.userId)]`).
|
|
1268
1488
|
*/
|
|
1269
|
-
declare function sqliteAuditLogTable(name?: string): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1489
|
+
declare function sqliteAuditLogTable(name?: string, extraConfig?: (table: SqliteAuditLogColumns) => SQLiteTableExtraConfigValue[]): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1270
1490
|
name: string;
|
|
1271
1491
|
schema: undefined;
|
|
1272
1492
|
columns: {
|
|
@@ -1462,6 +1682,36 @@ declare function sqliteAuditLogTable(name?: string): drizzle_orm_sqlite_core.SQL
|
|
|
1462
1682
|
dialect: "sqlite";
|
|
1463
1683
|
}>;
|
|
1464
1684
|
|
|
1685
|
+
/**
|
|
1686
|
+
* Column-aware timestamp values for engine-managed writes.
|
|
1687
|
+
*
|
|
1688
|
+
* Core stamps `createdAt` / `updatedAt` / the soft-delete marker at the
|
|
1689
|
+
* write site, but the value a SQL driver can bind depends on how the column
|
|
1690
|
+
* was declared: a Drizzle `integer({ mode: 'timestamp' | 'timestamp_ms' })` or
|
|
1691
|
+
* `timestamp()` column expects a `Date` (Drizzle converts it), a plain
|
|
1692
|
+
* `integer()` expects epoch milliseconds, and a `text()` column expects a
|
|
1693
|
+
* string. Cloudflare D1 makes the distinction matter: its `bind()` rejects
|
|
1694
|
+
* objects outright, so a `Date` against a plain integer column fails with
|
|
1695
|
+
* `D1_TYPE_ERROR`, while libsql silently accepts it.
|
|
1696
|
+
*
|
|
1697
|
+
* The representation is read structurally from the column's `dataType`
|
|
1698
|
+
* (`'date' | 'number' | 'string' | …`), which every Drizzle column exposes
|
|
1699
|
+
* regardless of dialect, so this module needs no drizzle-orm import.
|
|
1700
|
+
*/
|
|
1701
|
+
/** How a column stores a point in time. */
|
|
1702
|
+
type TimestampRepresentation = 'date' | 'number' | 'string';
|
|
1703
|
+
/**
|
|
1704
|
+
* The representation a Drizzle column expects for a timestamp write.
|
|
1705
|
+
* Unknown or non-column values fall back to `'date'` (Drizzle's own
|
|
1706
|
+
* timestamp column shape).
|
|
1707
|
+
*/
|
|
1708
|
+
declare function resolveTimestampRepresentation(column: unknown): TimestampRepresentation;
|
|
1709
|
+
/**
|
|
1710
|
+
* `now` in the representation the column can bind: a `Date`, epoch
|
|
1711
|
+
* milliseconds, or an ISO-8601 string.
|
|
1712
|
+
*/
|
|
1713
|
+
declare function resolveTimestampValue(column: unknown, now?: Date): Date | number | string;
|
|
1714
|
+
|
|
1465
1715
|
/**
|
|
1466
1716
|
* Drizzle-Zod schema utilities.
|
|
1467
1717
|
*
|
|
@@ -1629,4 +1879,4 @@ declare function isDrizzleZodAvailable(): boolean;
|
|
|
1629
1879
|
*/
|
|
1630
1880
|
declare const DrizzleAdapters: AdapterBundle;
|
|
1631
1881
|
|
|
1632
|
-
export { type CountRow, type CreateDrizzleCrudOptions, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleAuditLogStorage, type DrizzleAuditLogStorageOptions, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleBulkPatchEndpoint, DrizzleCloneEndpoint, type DrizzleColumn, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, type DrizzleSql, type DrizzleTable, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, DrizzleVersioningStorage, type DrizzleVersioningStorageOptions, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, sqliteAuditLogTable, sqliteVersionHistoryTable, substringMatch };
|
|
1882
|
+
export { type CountRow, type CreateDrizzleCrudOptions, DEFAULT_FTS5_PREFIX_INDEX, DEFAULT_FTS5_TOKENIZE, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleAuditLogStorage, type DrizzleAuditLogStorageOptions, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleBulkPatchEndpoint, DrizzleCloneEndpoint, type DrizzleColumn, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, type DrizzleSql, type DrizzleTable, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, DrizzleVersioningStorage, type DrizzleVersioningStorageOptions, type Fts5Index, type Fts5IndexConfig, type Fts5MatchOptions, type Fts5PrefixMatch, type QueryBuilder, type SqliteAuditLogColumns, type SqliteVersionHistoryColumns, type TimestampRepresentation, batchLoadDrizzleRelations, buildFts5Match, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, defineFts5Index, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, resolveTimestampRepresentation, resolveTimestampValue, sqliteAuditLogTable, sqliteVersionHistoryTable, substringMatch, tokenizeFts5Query };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt,gte,gt,ne,eq,sql,
|
|
1
|
+
import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt as lt$1,gte,gt as gt$1,ne as ne$1,eq,sql,getTableName,desc,asc,and,or}from'drizzle-orm';import {ConfigurationException,resolveRelationValueAsync,loadRelationsForItem,batchLoadRelations,assertNever,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,buildIncludeOptions,buildCursorPage,buildOffsetPageInfo,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint,UpsertEndpoint,BatchUpsertEndpoint,BulkPatchEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,isFilterOperator,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CONTEXT_KEYS,resolveCursorWindow}from'hono-crud/internal';import {toSnakeCase,toCamelCase}from'drizzle-orm/casing';import {sqliteTable,index,text,integer}from'drizzle-orm/sqlite-core';import {z as z$1}from'zod';function b(o){let e=o;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.(CONTEXT_KEYS.db);if(t)return t;throw new ConfigurationException(`Database not configured. Either:
|
|
2
2
|
1. Set db property: db = myDb;
|
|
3
3
|
2. Use middleware: c.set(CONTEXT_KEYS.db, myDb);
|
|
4
|
-
3. Use factory: createDrizzleCrud(db, meta)`)}function A(o){return o}function J(o,e){return m(o).transaction(async t=>{o._tx=t;try{return await e()}finally{o._tx=void 0;}})}function g(...o){return and(...o)}function re(...o){return or(...o)}function R(o,e,t){e.enabled&&o.push(isNull(t(e.field)));}var rt=["sqlite","pg","mysql"];function b(o){if(!o.model.table)throw new ConfigurationException(`Model ${o.model.tableName} does not have a table reference`);return o.model.table}function p(o,e){let t=getTableColumns(o),n=t[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return n}function ye(o){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n,r)=>{let i=[inArray(p(e,t),n)];return r?.tenantField!=null&&r.tenantValue!=null&&i.push(eq(p(e,r.tenantField),r.tenantValue)),r?.excludeDeletedField!=null&&i.push(isNull(p(e,r.excludeDeletedField))),o.select().from(e).where(i.length===1?i[0]:and(...i))}}}async function ot(o,e,t,n){let r=n.table;if(!r)return e;let i=ye(o),s=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:s}}async function Me(o,e,t,n){return loadRelationsForItem(e,t,ye(o),n)}async function k(o,e,t,n){return batchLoadRelations(e,t,ye(o),n)}function X(o,e,t="sqlite"){let n=p(o,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne(n,e.value);case "gt":return gt(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return P(n,String(e.value).replace(/%/g,""),t,{caseSensitive:true});case "ilike":return P(n,String(e.value).replace(/%/g,""),t);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[r,i]=e.value;return between(n,r,i)}default:return assertNever(e.operator)}}function I(o){return Number(o[0]?.count)||0}async function G(o){let{db:e,table:t,filters:n,dialect:r,searchFields:i=[],softDeleteConfig:s,defaultPerPage:a=20,extraConditions:l=[],cursorField:c}=o,u=[];if(s?.enabled){let f=p(t,s.field);n.options.onlyDeleted?u.push(isNotNull(f)):n.options.withDeleted||u.push(isNull(f));}for(let f of n.filters){let O=X(t,f,r);O&&u.push(O);}if(n.options.search&&i.length>0){let f=n.options.search,O=i.map(qe=>P(p(t,qe),f,r));u.push(re(...O));}u.push(...l);let d=u.length>0?g(...u):void 0,h=await e.select({count:sql`count(*)`}).from(t).where(d),M=I(h),D=c!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0),C=d,w=false;if(D&&n.options.cursor){let f=decodeCursor(n.options.cursor);f!==null&&(C=g(d,gt(p(t,c),f)),w=true);}let y=e.select().from(t).where(C);if(n.options.order_by){let f=p(t,n.options.order_by),O=n.options.order_by_direction==="desc"?desc:asc;y=y.orderBy(O(f));}if(D){let f=n.options.limit||n.options.per_page||a;return {records:await y.limit(f+1),totalCount:M,page:0,perPage:f,cursor:{limit:f,applied:w}}}let E=n.options.page||1,S=n.options.per_page||a;return {records:await y.limit(S).offset((E-1)*S),totalCount:M,page:E,perPage:S}}async function oe(o,e,t,n,r){let i=[];for(let a of r){let l=n[a];l!==void 0&&i.push(eq(t(a),l));}return i.length===0?null:(await o.select().from(e).where(g(...i)).limit(1))[0]||null}function P(o,e,t,n){if(n?.caseSensitive)switch(t){case "pg":return sql`POSITION(${e} IN ${o}) > 0`;case "mysql":return sql`LOCATE(${e}, ${o}) > 0`;default:return sql`INSTR(${o}, ${e}) > 0`}switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${o})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${o})) > 0`;default:return sql`INSTR(LOWER(${o}), LOWER(${e})) > 0`}}var _=class extends CreateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let n=t??this.getDb(),r=this.getTable(),i=this.applyManagedInsertFields(e,"drizzle");return (await n.insert(r).values(i).returning())[0]}async createNested(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],c=[];for(let u of l){if(typeof u!="object"||u===null)continue;let d={...u,id:crypto.randomUUID(),[n.foreignKey]:e},h=await s.insert(a).values(d).returning();h[0]&&c.push(h[0]);}return c}async handle(){return this.useTransaction?J(this,()=>super.handle()):super.handle()}},q=class extends ReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),i=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(i,e)];if(t)for(let[u,d]of Object.entries(t))a.push(eq(this.getColumn(u),d));R(a,s,u=>this.getColumn(u));let l=await this.getDb().select().from(r).where(g(...a)).limit(1);return l[0]?await Me(this.getDb(),l[0],this._meta,n):null}},N=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,d]of Object.entries(t))l.push(eq(this.getColumn(u),d));return R(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(g(...l)).limit(1))[0]||null}async update(e,t,n,r){let i=r??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),c=[eq(a,e)];if(n)for(let[d,h]of Object.entries(n))c.push(eq(this.getColumn(d),h));return R(c,l,d=>this.getColumn(d)),(await i.update(s).set(this.applyManagedUpdateFields(t)).where(g(...c)).returning())[0]||null}async processNestedWrites(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},c=p(a,n.foreignKey),u=p(a,"id");if(r.create){let d=Array.isArray(r.create)?r.create:[r.create];for(let h of d){if(typeof h!="object"||h===null)continue;let M={...h,id:crypto.randomUUID(),[n.foreignKey]:e},D=await s.insert(a).values(M).returning();D[0]&&l.created.push(D[0]);}}if(r.update)for(let d of r.update){if(!d.id||!(await s.select().from(a).where(g(eq(u,d.id),eq(c,e))).limit(1))[0])continue;let{id:M,...D}=d,C=await s.update(a).set(D).where(eq(u,M)).returning();C[0]&&l.updated.push(C[0]);}if(r.delete)for(let d of r.delete)(await s.delete(a).where(g(eq(u,d),eq(c,e))).returning())[0]&&l.deleted.push(d);if(r.connect)for(let d of r.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(u,d)).returning())[0]&&l.connected.push(d);if(r.disconnect)for(let d of r.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(g(eq(u,d),eq(c,e))).returning())[0]&&l.disconnected.push(d);return l}async handle(){return this.useTransaction?J(this,()=>super.handle()):super.handle()}},F=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,d]of Object.entries(t))l.push(eq(this.getColumn(u),d));return R(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(g(...l)).limit(1))[0]||null}async delete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[c,u]of Object.entries(t))l.push(eq(this.getColumn(c),u));return R(l,a,c=>this.getColumn(c)),a.enabled?(await r.update(i).set({[a.field]:new Date}).where(g(...l)).returning())[0]||null:(await r.delete(i).where(g(...l)).returning())[0]||null}async countRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey),l=await i.select({count:sql`count(*)`}).from(s).where(eq(a,e));return I(l)}async deleteRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?J(this,()=>super.handle()):super.handle()}},L=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await G({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,cursorField:this.isCursorPaginationActive()?this.cursorField||"id":void 0}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));if(t.cursor){let{items:i,result_info:s}=buildCursorPage({rows:t.records,limit:t.cursor.limit,totalCount:t.totalCount,cursorField:this.cursorField||"id",cursorApplied:t.cursor.applied});return {result:await k(this.getDb(),i,this._meta,n),result_info:s}}return {result:await k(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},U=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,d]of Object.entries(t))l.push(eq(this.getColumn(u),d));return l.push(isNotNull(this.getColumn(a.field))),(await r.update(i).set({[a.field]:null}).where(g(...l)).returning())[0]||null}async handle(){return this.useTransaction?J(this,()=>super.handle()):super.handle()}};var Z=class extends BatchCreateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}async batchCreate(e){let t=this.getTable(),n=e.map(i=>this.applyManagedInsertFields(i,"drizzle"));return await this.getDb().insert(t).values(n).returning()}},V=class extends BatchUpdateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[],s=[],a=this.getTenantScopeFilter();for(let l of e){let c=[eq(n,l.id)];R(c,r,d=>this.getColumn(d)),a&&c.push(eq(this.getColumn(a.field),a.value));let u=await this.getDb().update(t).set(this.applyManagedUpdateFields(l.data)).where(g(...c)).returning();u[0]?i.push(u[0]):s.push(l.id);}return {updated:i,notFound:s}}},K=class extends BatchDeleteEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e)];R(i,r,d=>this.getColumn(d));let s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let a;r.enabled?a=await this.getDb().update(t).set({[r.field]:new Date}).where(g(...i)).returning():a=await this.getDb().delete(t).where(g(...i)).returning();let l=a,c=new Set(l.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!c.has(d));return {deleted:l,notFound:u}}},$=class extends BatchRestoreEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e),isNotNull(this.getColumn(r.field))],s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let l=await this.getDb().update(t).set({[r.field]:null}).where(g(...i)).returning(),c=new Set(l.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!c.has(d));return {restored:l,notFound:u}}};function qt(o){return o.split(/\s+/).filter(e=>e.length>0)}var Q=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return oe(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeUpsert(e,t){let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),c={};for(let[C,w]of Object.entries(e))!r.includes(C)&&C!==i&&(this.createOnlyFields?.includes(C)||(c[C]=w));a.enabled&&(c[a.updatedAt]=Date.now());let u=r.map(C=>this.getColumn(C)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));let h=Object.keys(c).length>0?c:{[i]:sql`${this.getColumn(i)}`},M=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await M.onDuplicateKeyUpdate({set:h}).returning())[0],created:false}:{data:(await M.onConflictDoUpdate({target:u,set:h,where:d}).returning())[0],created:false}}},W=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return oe(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),a=e.map(D=>this.applyManagedInsertFields(D,"drizzle")),l={},c=e[0];for(let D of Object.keys(c))!r.includes(D)&&D!==i&&(this.createOnlyFields?.includes(D)||(l[D]=sql`excluded.${sql.identifier(D)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=r.map(D=>this.getColumn(D)),d=Object.keys(l).length>0?l:{[i]:sql`${this.getColumn(i)}`},h=this.getDb().insert(n).values(a),M=await(this.dialect==="mysql"?h.onDuplicateKeyUpdate({set:d}):h.onConflictDoUpdate({target:u,set:d})).returning();return {items:M.map((D,C)=>({data:D,created:false,index:C})),createdCount:0,updatedCount:M.length,totalCount:M.length}}},se=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}buildConditions(e){let t=this.getTable(),n=[];for(let i of e.filters){let s=X(t,i,this.dialect);s&&n.push(s);}let r=this.getSoftDeleteConfig();return R(n,r,i=>this.getColumn(i)),n}async countMatching(e){let t=this.buildConditions(e),n=await this.getDb().select({count:sql`count(*)`}).from(this.getTable()).where(g(...t));return I(n)}async applyPatch(e,t){let n=this.buildConditions(t),r=await this.getDb().update(this.getTable()).set(this.applyManagedUpdateFields(e)).where(g(...n)).returning();return {updated:r.length,records:r}}};async function be(o,e,t,n,r){let i=r?g(eq(t,n),eq(p(e,r.field),r.value)):eq(t,n),s=await o.select({count:sql`count(*)`}).from(e).where(i);return I(s)>0}var ae=class extends VersionHistoryEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return be(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},le=class extends VersionReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return be(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},de=class extends VersionCompareEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return be(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ce=class extends VersionRollbackEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return be(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}async rollback(e,t,n){let r=this.getTable(),i=this.getVersioningConfig().field;return (await this.getDb().update(r).set({...t,[i]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},ue=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async aggregate(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||R(n,r,c=>this.getColumn(c));}if(e.filters)for(let[a,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[c,u]of Object.entries(l)){if(!isFilterOperator(c)){n.push(sql`1 = 0`);continue}let d=X(t,{field:a,operator:c,value:u},this.dialect);d&&n.push(d);}else n.push(eq(this.getColumn(a),l));let i=n.length>0?g(...n):void 0,s=await this.getDb().select().from(t).where(i);return computeAggregations(s,e)}},H=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return m(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async search(e,t){let n=this.getTable(),r=[],i=this.getSearchableFields(),s=e.fields||Object.keys(i);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),y=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;r.push(sql`${w} @@ ${y}`);}else {let w=(y,E)=>{try{let S=this.getColumn(y);return P(sql`CAST(${S} AS TEXT)`,E,this.dialect)}catch{return}};if(e.mode==="all"){let y=qt(e.query);if(y.length>0){let E=[];for(let S of y){let fe=s.map(f=>w(f,S)).filter(f=>f!==void 0);fe.length>0&&E.push(re(...fe));}E.length>0&&r.push(g(...E));}}else {let y=s.map(E=>w(E,e.query)).filter(E=>E!==void 0);y.length>0&&r.push(re(...y));}}let a=await G({db:this.getDb(),table:n,filters:t,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,extraConditions:r}),l=a.records,c=a.totalCount,u=e.mode==="all"?{...e,mode:"any"}:e,d=searchInMemory(l,u,i),h=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),M=d.map(w=>w.item),D=await k(this.getDb(),M,this._meta,h);return {items:d.map((w,y)=>({...w,item:D[y]})),totalCount:c}}},pe=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await G({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));return {result:await k(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},ge=class extends ImportEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return oe(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}},me=class extends CloneEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let n=this.getTable(),r=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),s=[eq(r,e)];if(t)for(let[l,c]of Object.entries(t))s.push(eq(this.getColumn(l),c));R(s,i,l=>this.getColumn(l));let a=await this.getDb().select().from(n).where(g(...s)).limit(1);return a[0]?a[0]:null}async createClone(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(n).returning())[0]}};function Vn(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends _{_meta=e;db=o},Read:class extends q{_meta=e;db=o},Update:class extends N{_meta=e;db=o},Delete:class extends F{_meta=e;db=o},List:class extends L{_meta=e;db=o;dialect=n},Restore:class extends U{_meta=e;db=o},Upsert:class extends Q{_meta=e;db=o;dialect=n},Search:class extends H{_meta=e;db=o;dialect=n},BatchCreate:class extends Z{_meta=e;db=o},BatchUpdate:class extends V{_meta=e;db=o},BatchDelete:class extends K{_meta=e;db=o},BatchRestore:class extends ${_meta=e;db=o},BatchUpsert:class extends W{_meta=e;db=o;dialect=n}}}var je=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}recordScope(e,t){return and(eq(this.col("resourceTable"),e),eq(this.col("recordId"),String(t)))}toEntry(e){return {id:e.id,recordId:e.recordId,version:e.version,data:JSON.parse(e.data),createdAt:new Date(e.createdAt),...e.changedBy!=null?{changedBy:e.changedBy}:{},...e.changeReason!=null?{changeReason:e.changeReason}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{}}}async store(e,t){let n=t.createdAt instanceof Date?t.createdAt:new Date(t.createdAt);await this.db.insert(this.table).values({id:t.id,resourceTable:e,recordId:String(t.recordId),version:t.version,data:JSON.stringify(t.data),createdAt:n.getTime(),changedBy:t.changedBy??null,changeReason:t.changeReason??null,changes:t.changes?JSON.stringify(t.changes):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version")));return (n?.limit!=null||n?.offset!=null)&&(r=r.limit(n?.limit??Number.MAX_SAFE_INTEGER)),n?.offset!=null&&(r=r.offset(n.offset)),(await r).map(s=>this.toEntry(s))}async getVersion(e,t,n){let r=await this.db.select().from(this.table).where(and(this.recordScope(e,t),eq(this.col("version"),n))).limit(1);return r.length>0?this.toEntry(r[0]):null}async getLatestVersion(e,t){let n=await this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version"))).limit(1);return n.length>0?n[0].version:0}async pruneVersions(e,t,n){if(n<=0)return this.deleteAllVersions(e,t);let r=await this.getByRecordId(e,t);if(r.length<=n)return 0;let i=r[n-1].version;return (await this.db.delete(this.table).where(and(this.recordScope(e,t),lt(this.col("version"),i))).returning()).length}async deleteAllVersions(e,t){return (await this.db.delete(this.table).where(this.recordScope(e,t)).returning()).length}};function lr(o="version_history"){return sqliteTable(o,{id:text("id").primaryKey(),resourceTable:text("resource_table").notNull(),recordId:text("record_id").notNull(),version:integer("version").notNull(),data:text("data").notNull(),createdAt:integer("created_at").notNull(),changedBy:text("changed_by"),changeReason:text("change_reason"),changes:text("changes")})}var Pe=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}toEntry(e){return {id:e.id,timestamp:new Date(e.timestamp),action:e.action,tableName:e.tableName,recordId:e.recordId,...e.userId!=null?{userId:e.userId}:{},...e.record!=null?{record:JSON.parse(e.record)}:{},...e.previousRecord!=null?{previousRecord:JSON.parse(e.previousRecord)}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{},...e.metadata!=null?{metadata:JSON.parse(e.metadata)}:{}}}async store(e){let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);await this.db.insert(this.table).values({id:e.id,tableName:e.tableName,recordId:String(e.recordId),action:e.action,timestamp:t.getTime(),userId:e.userId??null,record:e.record!==void 0?JSON.stringify(e.record):null,previousRecord:e.previousRecord!==void 0?JSON.stringify(e.previousRecord):null,changes:e.changes!==void 0?JSON.stringify(e.changes):null,metadata:e.metadata!==void 0?JSON.stringify(e.metadata):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(g(eq(this.col("tableName"),e),eq(this.col("recordId"),String(t)))).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=n?.offset||0,s=n?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}async getAll(e){let t=[];e?.tableName&&t.push(eq(this.col("tableName"),e.tableName)),e?.action&&t.push(eq(this.col("action"),e.action)),e?.userId&&t.push(eq(this.col("userId"),e.userId)),e?.startDate&&t.push(gte(this.col("timestamp"),e.startDate.getTime())),e?.endDate&&t.push(lte(this.col("timestamp"),e.endDate.getTime()));let n=t.length>0?g(...t):void 0,r=this.db.select().from(this.table).where(n).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=e?.offset||0,s=e?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}};function gr(o="audit_logs"){return sqliteTable(o,{id:text("id").primaryKey(),tableName:text("table_name").notNull(),recordId:text("record_id").notNull(),action:text("action").notNull(),timestamp:integer("timestamp").notNull(),userId:text("user_id"),record:text("record"),previousRecord:text("previous_record"),changes:text("changes"),metadata:text("metadata")})}var ee=null,Ae=false,he=null;async function De(){if(Ae){if(he)throw he;if(ee)return ee}Ae=true;try{return ee=await import('drizzle-zod'),ee}catch{throw he=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),he}}async function Kt(o,e){return (await De()).createSelectSchema(o,e)}async function $t(o,e){return (await De()).createInsertSchema(o,e)}async function Qt(o,e){let t=await De();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Wt(o,e){let t=await De(),n=e?.coerceDates!==false,r=n?Gt(o):new Set,i=t.createSelectSchema(o,e?.selectRefine),s=t.createInsertSchema(o,e?.insertRefine),a;return t.createUpdateSchema?a=t.createUpdateSchema(o,e?.updateRefine):a=t.createInsertSchema(o,e?.updateRefine).partial(),n&&r.size>0&&(s=_e(s,r),a=_e(a,r)),{select:i,insert:s,update:a}}function Ht(){return ee!==null}var Jt=z.preprocess(o=>{if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z.date()),Xt=z.preprocess(o=>{if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z.date().nullable());function Gt(o){let e=new Set,t=o;for(let[n,r]of Object.entries(t)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let i=r;if(!i||typeof i!="object")continue;let s=String(i.dataType??"").toLowerCase(),a=String(i.columnType??"").toLowerCase(),l=i.config,c=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||c.includes("timestamp")||c.includes("date"))&&e.add(n);}return e}function _e(o,e){if(e.size===0)return o;let t=o.shape,n={};for(let[r,i]of Object.entries(t))if(e.has(r)){let s=i.isOptional?.()??false,a=i.isNullable?.()??false,l=Jt;(a||s)&&(l=Xt),s&&(l=l.optional()),n[r]=l;}else n[r]=i;return z.object(n)}var Cr={CreateEndpoint:_,ListEndpoint:L,ReadEndpoint:q,UpdateEndpoint:N,DeleteEndpoint:F,RestoreEndpoint:U,BatchCreateEndpoint:Z,BatchUpdateEndpoint:V,BatchDeleteEndpoint:K,BatchRestoreEndpoint:$,BatchUpsertEndpoint:W,SearchEndpoint:H,AggregateEndpoint:ue,ExportEndpoint:pe,ImportEndpoint:ge,UpsertEndpoint:Q,CloneEndpoint:me,BulkPatchEndpoint:se,VersionHistoryEndpoint:ae,VersionReadEndpoint:le,VersionCompareEndpoint:de,VersionRollbackEndpoint:ce};export{rt as DRIZZLE_DIALECTS,Cr as DrizzleAdapters,ue as DrizzleAggregateEndpoint,Pe as DrizzleAuditLogStorage,Z as DrizzleBatchCreateEndpoint,K as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,V as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,se as DrizzleBulkPatchEndpoint,me as DrizzleCloneEndpoint,_ as DrizzleCreateEndpoint,F as DrizzleDeleteEndpoint,pe as DrizzleExportEndpoint,ge as DrizzleImportEndpoint,L as DrizzleListEndpoint,q as DrizzleReadEndpoint,U as DrizzleRestoreEndpoint,H as DrizzleSearchEndpoint,N as DrizzleUpdateEndpoint,Q as DrizzleUpsertEndpoint,de as DrizzleVersionCompareEndpoint,ae as DrizzleVersionHistoryEndpoint,le as DrizzleVersionReadEndpoint,ce as DrizzleVersionRollbackEndpoint,je as DrizzleVersioningStorage,k as batchLoadDrizzleRelations,X as buildWhereCondition,A as cast,Vn as createDrizzleCrud,Wt as createDrizzleSchemas,$t as createInsertSchema,Kt as createSelectSchema,Qt as createUpdateSchema,p as getColumn,b as getTable,Ht as isDrizzleZodAvailable,ot as loadDrizzleRelation,Me as loadDrizzleRelations,I as readCount,gr as sqliteAuditLogTable,lr as sqliteVersionHistoryTable,P as substringMatch};
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}function j(o){return o}function ne(o,e){return b(o).transaction(async t=>{o._tx=t;try{return await e()}finally{o._tx=void 0;}})}function f(...o){return and(...o)}function re(...o){return or(...o)}function k(o,e,t){e.enabled&&o.push(isNull(t(e.field)));}var Ot=["sqlite","pg","mysql"];function z(o){if(!o.model.table)throw new ConfigurationException(`Model ${o.model.tableName} does not have a table reference`);return o.model.table}function p(o,e){let t=getTableColumns(o),n=t[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return n}function _e(o){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n,r)=>{let i=[inArray(p(e,t),n)];return r?.tenantField!=null&&r.tenantValue!=null&&i.push(eq(p(e,r.tenantField),r.tenantValue)),r?.excludeDeletedField!=null&&i.push(isNull(p(e,r.excludeDeletedField))),o.select().from(e).where(i.length===1?i[0]:and(...i))}}}async function At(o,e,t,n){let r=n.table;if(!r)return e;let i=_e(o),s=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:s}}async function Pe(o,e,t,n){return loadRelationsForItem(e,t,_e(o),n)}async function O(o,e,t,n){return batchLoadRelations(e,t,_e(o),n)}function oe(o,e,t="sqlite"){let n=p(o,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return L(n,String(e.value).replace(/%/g,""),t,{caseSensitive:true});case "ilike":return L(n,String(e.value).replace(/%/g,""),t);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[r,i]=e.value;return between(n,r,i)}default:return assertNever(e.operator)}}function A(o){return Number(o[0]?.count)||0}function Nt(o,e,t){let n=t.direction==="next"?gt$1:lt$1,r=[];for(let i=0;i<t.values.length;i++){let s=[];for(let a=0;a<i;a++)s.push(eq(p(o,e[a]),t.values[a]));s.push(n(p(o,e[i]),t.values[i])),r.push(s.length===1?s[0]:f(...s));}return r.length===1?r[0]:re(...r)}function Fe(o){let{table:e,filters:t,dialect:n,searchFields:r=[],softDeleteConfig:i,extraConditions:s=[]}=o,a=[];if(i?.enabled){let l=p(e,i.field);t.options.onlyDeleted?a.push(isNotNull(l)):t.options.withDeleted||a.push(isNull(l));}for(let l of t.filters){let d=oe(e,l,n);d&&a.push(d);}if(t.options.search&&r.length>0){let l=t.options.search,d=r.map(u=>L(p(e,u),l,n));a.push(re(...d));}return a.push(...s),a.length>0?f(...a):void 0}async function ie(o){let{db:e,table:t,filters:n,dialect:r,searchFields:i=[],softDeleteConfig:s,defaultPerPage:a=20,primaryKeys:l,extraConditions:d=[],cursorField:u}=o,c=Fe({table:t,filters:n,dialect:r,searchFields:i,softDeleteConfig:s,extraConditions:d}),g=await e.select({count:sql`count(*)`}).from(t).where(c),m=A(g);if(u!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0)){let w=resolveCursorWindow({cursor:n.options.cursor,limit:n.options.limit,perPage:n.options.per_page,defaultPerPage:a,cursorField:u,primaryKeys:l}),B=w.cursor===null?c:f(c,Nt(t,w.keyFields,w.cursor)),x=w.direction==="prev"?desc:asc;return {records:await e.select().from(t).where(B).orderBy(...w.keyFields.map(ce=>x(p(t,ce)))).limit(w.limit+1),totalCount:m,page:0,perPage:w.limit,cursor:{limit:w.limit,applied:w.cursor!==null,direction:w.direction}}}let h=e.select().from(t).where(c),y=n.options.order_by;if(y){let w=n.options.order_by_direction==="desc"?desc:asc,B=[y,...l.filter(x=>x!==y)];h=h.orderBy(...B.map(x=>w(p(t,x))));}let R=n.options.page||1,T=n.options.per_page||a;return {records:await h.limit(T).offset((R-1)*T),totalCount:m,page:R,perPage:T}}async function ge(o,e,t,n,r){let i=[];for(let a of r){let l=n[a];l!==void 0&&i.push(eq(t(a),l));}return i.length===0?null:(await o.select().from(e).where(f(...i)).limit(1))[0]||null}function L(o,e,t,n){if(n?.caseSensitive)switch(t){case "pg":return sql`POSITION(${e} IN ${o}) > 0`;case "mysql":return sql`LOCATE(${e}, ${o}) > 0`;default:return sql`INSTR(${o}, ${e}) > 0`}switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${o})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${o})) > 0`;default:return sql`INSTR(LOWER(${o}), LOWER(${e})) > 0`}}function $t(o){if(!o||typeof o!="object")return "date";let e=String(o.dataType??"").toLowerCase();return e==="number"?"number":e==="string"?"string":"date"}function S(o,e=new Date){switch($t(o)){case "number":return e.getTime();case "string":return e.toISOString();default:return e}}var U=class extends CreateEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getRelatedTable(e){return e.table}async create(e,t){let n=t??this.getDb(),r=this.getTable(),i=this.applyManagedInsertFields(e,"drizzle");return (await n.insert(r).values(i).returning())[0]}async createNested(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(c).returning();g[0]&&d.push(g[0]);}return d}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},V=class extends ReadEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),i=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(i,e)];if(t)for(let[u,c]of Object.entries(t))a.push(eq(this.getColumn(u),c));k(a,s,u=>this.getColumn(u));let l=await this.getDb().select().from(r).where(f(...a)).limit(1);return l[0]?await Pe(this.getDb(),l[0],this._meta,n):null}},Z=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return k(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(f(...l)).limit(1))[0]||null}async update(e,t,n,r){let i=r??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(a,e)];if(n)for(let[c,g]of Object.entries(n))d.push(eq(this.getColumn(c),g));return k(d,l,c=>this.getColumn(c)),(await i.update(s).set(this.applyManagedUpdateFields(t)).where(f(...d)).returning())[0]||null}async processNestedWrites(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=p(a,n.foreignKey),u=p(a,"id");if(r.create){let c=Array.isArray(r.create)?r.create:[r.create];for(let g of c){if(typeof g!="object"||g===null)continue;let m={...g,id:crypto.randomUUID(),[n.foreignKey]:e},h=await s.insert(a).values(m).returning();h[0]&&l.created.push(h[0]);}}if(r.update)for(let c of r.update){if(!c.id||!(await s.select().from(a).where(f(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:m,...h}=c,y=await s.update(a).set(h).where(eq(u,m)).returning();y[0]&&l.updated.push(y[0]);}if(r.delete)for(let c of r.delete)(await s.delete(a).where(f(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(r.connect)for(let c of r.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(r.disconnect)for(let c of r.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(f(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},K=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return k(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(f(...l)).limit(1))[0]||null}async delete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return k(l,a,d=>this.getColumn(d)),a.enabled?(await r.update(i).set({[a.field]:this.managedTimestampValue(a.field)}).where(f(...l)).returning())[0]||null:(await r.delete(i).where(f(...l)).returning())[0]||null}async countRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey),l=await i.select({count:sql`count(*)`}).from(s).where(eq(a,e));return A(l)}async deleteRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},Q=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await ie({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,cursorField:this.isCursorPaginationActive()?this.cursorField||"id":void 0}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));if(t.cursor){let{items:i,result_info:s}=buildCursorPage({rows:t.records,limit:t.cursor.limit,totalCount:t.totalCount,cursorField:this.cursorField||"id",primaryKeys:this._meta.model.primaryKeys,direction:t.cursor.direction,cursorApplied:t.cursor.applied});return {result:await O(this.getDb(),i,this._meta,n),result_info:s}}return {result:await O(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},W=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(a.field))),(await r.update(i).set({[a.field]:null}).where(f(...l)).returning())[0]||null}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}};var H=class extends BatchCreateEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}async batchCreate(e){let t=this.getTable(),n=e.map(i=>this.applyManagedInsertFields(i,"drizzle"));return await this.getDb().insert(t).values(n).returning()}},G=class extends BatchUpdateEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[],s=[],a=this.getTenantScopeFilter();for(let l of e){let d=[eq(n,l.id)];k(d,r,c=>this.getColumn(c)),a&&d.push(eq(this.getColumn(a.field),a.value));let u=await this.getDb().update(t).set(this.applyManagedUpdateFields(l.data)).where(f(...d)).returning();u[0]?i.push(u[0]):s.push(l.id);}return {updated:i,notFound:s}}},X=class extends BatchDeleteEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e)];k(i,r,c=>this.getColumn(c));let s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let a;r.enabled?a=await this.getDb().update(t).set({[r.field]:this.managedTimestampValue(r.field)}).where(f(...i)).returning():a=await this.getDb().delete(t).where(f(...i)).returning();let l=a,d=new Set(l.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!d.has(c));return {deleted:l,notFound:u}}},J=class extends BatchRestoreEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e),isNotNull(this.getColumn(r.field))],s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let l=await this.getDb().update(t).set({[r.field]:null}).where(f(...i)).returning(),d=new Set(l.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!d.has(c));return {restored:l,notFound:u}}};var ot="unicode61 remove_diacritics 2",it=[2,3];function se(o){return `"${o.replace(/"/g,'""')}"`}function he(o){return `'${o.replace(/'/g,"''")}'`}function rt(o,e,t){let n=getTableColumns(o),r=n[e];if(!r||typeof r.name!="string")throw new Error(`defineFts5Index: column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return r.keyAsName===true&&t==="snake_case"?toSnakeCase(r.name):r.keyAsName===true&&t==="camelCase"?toCamelCase(r.name):r.name}function an(o){let{table:e,columns:t}=o;if(t.length===0)throw new Error("defineFts5Index: `columns` must list at least one field");if(new Set(t).size!==t.length)throw new Error("defineFts5Index: `columns` contains duplicates");let n=o.prefixIndex??it;for(let I of n)if(!Number.isInteger(I)||I<1||I>99)throw new Error(`defineFts5Index: invalid prefixIndex length ${I} (1-99)`);let r=getTableName(e),i=o.name??`${r}_fts`,s=t.map(I=>rt(e,I,o.casing)),a=o.contentRowid===void 0?"rowid":rt(e,o.contentRowid,o.casing),l=o.tokenize??ot,d=se(i),u=se(r),c=o.contentRowid===void 0?"rowid":se(a),g=s.map(se),m=g.join(", "),h=g.map(I=>`new.${I}`).join(", "),y=g.map(I=>`old.${I}`).join(", "),R=I=>se(`${i}_${I}`),T=`INSERT INTO ${d}(${d}, rowid, ${m}) VALUES('delete', old.${c}, ${y});`,E=`INSERT INTO ${d}(rowid, ${m}) VALUES (new.${c}, ${h});`,w=[...g,...o.contentRowid===void 0?[]:[c]].join(", "),B=[`content=${he(r)}`,`content_rowid=${he(a)}`,`tokenize=${he(l)}`,...n.length>0?[`prefix=${he(n.join(" "))}`]:[]],x=`INSERT INTO ${d}(${d}) VALUES('rebuild')`;return {name:i,table:e,tableName:r,fields:[...t],columnNames:s,contentRowid:o.contentRowid,contentRowidColumn:a,migration:()=>[`CREATE VIRTUAL TABLE IF NOT EXISTS ${d} USING fts5(${m}, ${B.join(", ")})`,`CREATE TRIGGER IF NOT EXISTS ${R("ai")} AFTER INSERT ON ${u} BEGIN ${E} END`,`CREATE TRIGGER IF NOT EXISTS ${R("ad")} AFTER DELETE ON ${u} BEGIN ${T} END`,`CREATE TRIGGER IF NOT EXISTS ${R("au")} AFTER UPDATE OF ${w} ON ${u} BEGIN ${T} ${E} END`,x],dropMigration:()=>[`DROP TRIGGER IF EXISTS ${R("ai")}`,`DROP TRIGGER IF EXISTS ${R("ad")}`,`DROP TRIGGER IF EXISTS ${R("au")}`,`DROP TABLE IF EXISTS ${d}`],rebuild:()=>x}}function Oe(o){return `"${o.replace(/"/g,'""')}"`}function st(o){return o.split(/\s+/).map(e=>e.trim()).filter(e=>/[\p{L}\p{N}]/u.test(e))}function Ne(o,e){let t=st(o);if(t.length===0)return null;let n=e.prefix??"last",r=(s,a)=>n==="all"||n==="last"&&s===a-1?"*":"",i;if(e.mode==="phrase")i=`${Oe(t.join(" "))}${r(0,1)}`;else {let s=e.mode==="all"?" AND ":" OR ";i=t.map((a,l)=>`${Oe(a)}${r(l,t.length)}`).join(s);}return e.columns&&e.columns.length>0?`{${e.columns.map(Oe).join(" ")}} : (${i})`:i}var be="__fts5_rank",ze="__fts5_snippet_",ln="fts5_hits",Ae="",at="";function lt(o,e,t,n){let r=sql.identifier(o.name),i=sql.identifier(ln),s=sql.join(t.map(g=>sql.raw(String(g))),sql.raw(", ")),a=o.columnNames.map((g,m)=>sql`snippet(${r}, ${sql.raw(String(m))}, ${Ae}, ${at}, ${"\u2026"}, ${sql.raw(String(n))}) AS ${sql.identifier(`s${m}`)}`),l=sql`(SELECT ${r}.rowid AS ${sql.identifier("fts_rowid")}, bm25(${r}, ${s}) AS ${sql.identifier("fts_rank")}, ${sql.join(a,sql.raw(", "))} FROM ${r} WHERE ${r} MATCH ${e}) AS ${i}`,d=o.contentRowid===void 0?sql`${sql.identifier(o.tableName)}.rowid`:sql`${sql.identifier(o.tableName)}.${sql.identifier(o.contentRowidColumn)}`,u=sql`${i}.${sql.identifier("fts_rank")}`,c={[be]:u};return o.columnNames.forEach((g,m)=>{c[`${ze}${m}`]=sql`${i}.${sql.identifier(`s${m}`)}`;}),{source:l,on:sql`${i}.${sql.identifier("fts_rowid")} = ${d}`,rank:u,selection:c}}function dt(o){let e=Math.max(0,-o);return e/(1+e)}function ct(o){let e=Math.min(Math.max(o,0),.999999);return -(e/(1-e))}function dn(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ut(o,e){return typeof o!="string"||!o.includes(Ae)?null:dn(o).split(Ae).join(`<${e}>`).split(at).join(`</${e}>`)}function vn(o){return o.split(/\s+/).filter(e=>e.length>0)}var Y=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeUpsert(e,t){let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[y,R]of Object.entries(e))!r.includes(y)&&y!==i&&(this.createOnlyFields?.includes(y)||(d[y]=R));a.enabled&&(d[a.updatedAt]=Date.now());let u=r.map(y=>this.getColumn(y)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let g=Object.keys(d).length>0?d:{[i]:sql`${this.getColumn(i)}`},m=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await m.onDuplicateKeyUpdate({set:g}).returning())[0],created:false}:{data:(await m.onConflictDoUpdate({target:u,set:g,where:c}).returning())[0],created:false}}},ee=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),a=e.map(h=>this.applyManagedInsertFields(h,"drizzle")),l={},d=e[0];for(let h of Object.keys(d))!r.includes(h)&&h!==i&&(this.createOnlyFields?.includes(h)||(l[h]=sql`excluded.${sql.identifier(h)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=r.map(h=>this.getColumn(h)),c=Object.keys(l).length>0?l:{[i]:sql`${this.getColumn(i)}`},g=this.getDb().insert(n).values(a),m=await(this.dialect==="mysql"?g.onDuplicateKeyUpdate({set:c}):g.onConflictDoUpdate({target:u,set:c})).returning();return {items:m.map((h,y)=>({data:h,created:false,index:y})),createdCount:0,updatedCount:m.length,totalCount:m.length}}},ye=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}buildConditions(e){let t=this.getTable(),n=[];for(let i of e.filters){let s=oe(t,i,this.dialect);s&&n.push(s);}let r=this.getSoftDeleteConfig();return k(n,r,i=>this.getColumn(i)),n}async countMatching(e){let t=this.buildConditions(e),n=await this.getDb().select({count:sql`count(*)`}).from(this.getTable()).where(f(...t));return A(n)}async applyPatch(e,t){let n=this.buildConditions(t),r=await this.getDb().update(this.getTable()).set(this.applyManagedUpdateFields(e)).where(f(...n)).returning();return {updated:r.length,records:r}}};async function Se(o,e,t,n,r){let i=r?f(eq(t,n),eq(p(e,r.field),r.value)):eq(t,n),s=await o.select({count:sql`count(*)`}).from(e).where(i);return A(s)>0}var we=class extends VersionHistoryEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Ce=class extends VersionReadEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Re=class extends VersionCompareEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Te=class extends VersionRollbackEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}async rollback(e,t,n){let r=this.getTable(),i=this.getVersioningConfig().field;return (await this.getDb().update(r).set({...t,[i]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Me=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async aggregate(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||k(n,r,d=>this.getColumn(d));}if(e.filters)for(let[a,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){if(!isFilterOperator(d)){n.push(sql`1 = 0`);continue}let c=oe(t,{field:a,operator:d,value:u},this.dialect);c&&n.push(c);}else n.push(eq(this.getColumn(a),l));let i=n.length>0?f(...n):void 0,s=await this.getDb().select().from(t).where(i);return computeAggregations(s,e)}},te=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return b(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";fts5;fts5PrefixMatch="last";fts5SnippetTokens=24;getSearchableFields(){let e=Object.keys(this.searchableFields).length>0||this.searchFields.length>0;return this.fts5&&!e?Object.fromEntries(this.fts5.fields.map(t=>[t,{weight:this.fieldWeights[t]??1}])):super.getSearchableFields()}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async search(e,t){if(this.fts5)return this.searchFts5(this.fts5,e,t);let n=this.getTable(),r=[],i=this.getSearchableFields(),s=e.fields||Object.keys(i);if(this.useNativeSearch&&this.vectorColumn){let R=this.getColumn(this.vectorColumn),T=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;r.push(sql`${R} @@ ${T}`);}else {let R=(T,E)=>{try{let w=this.getColumn(T);return L(sql`CAST(${w} AS TEXT)`,E,this.dialect)}catch{return}};if(e.mode==="all"){let T=vn(e.query);if(T.length>0){let E=[];for(let w of T){let B=s.map(x=>R(x,w)).filter(x=>x!==void 0);B.length>0&&E.push(re(...B));}E.length>0&&r.push(f(...E));}}else {let T=s.map(E=>R(E,e.query)).filter(E=>E!==void 0);T.length>0&&r.push(re(...T));}}let a=await ie({db:this.getDb(),table:n,filters:t,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,extraConditions:r}),l=a.records,d=a.totalCount,u=e.mode==="all"?{...e,mode:"any"}:e,c=searchInMemory(l,u,i),g=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),m=c.map(R=>R.item),h=await O(this.getDb(),m,this._meta,g);return {items:c.map((R,T)=>({...R,item:h[T]})),totalCount:d}}async searchFts5(e,t,n){if(this.dialect!=="sqlite")throw new ConfigurationException(`fts5 search requires dialect 'sqlite' (SQLite / Cloudflare D1), got '${this.dialect}'.`);let r=this.getTable(),i=getTableName(r);if(i!==e.tableName)throw new ConfigurationException(`fts5 index '${e.name}' indexes table '${e.tableName}', but this endpoint's model table is '${i}'.`);let s=this.getSearchableFields(),a=Object.keys(s).filter(M=>!e.fields.includes(M));if(a.length>0)throw new ConfigurationException(`Searchable fields [${a.join(", ")}] are not columns of fts5 index '${e.name}' (indexed: ${e.fields.join(", ")}).`);let l=(t.fields??Object.keys(s)).filter(M=>e.fields.includes(M)),d=l.length>0&&l.length<e.fields.length,u=Ne(t.query,{mode:t.mode,prefix:this.fts5PrefixMatch,columns:d?l.map(M=>e.columnNames[e.fields.indexOf(M)]):void 0});if(u===null||l.length===0)return {items:[],totalCount:0};let c=e.fields.map(M=>{let N=s[M]?.weight??1;return Number.isFinite(N)?N:1}),g=Math.min(64,Math.max(1,Math.trunc(this.fts5SnippetTokens))),m=lt(e,u,c,g),h=Fe({table:r,filters:n,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),extraConditions:t.minScore>0?[sql`${m.rank} <= ${ct(t.minScore)}`]:[]}),y=this.getDb(),R=await y.select({count:sql`count(*)`}).from(r).innerJoin(m.source,m.on).where(h),T=A(R),E=this._meta.model.primaryKeys,w=n.options.order_by,B=n.options.order_by_direction==="desc"?desc:asc,x=w?[B(this.getColumn(w)),asc(m.rank)]:[asc(m.rank)];for(let M of E)M!==w&&x.push((w?B:asc)(this.getColumn(M)));let I=n.options.page||1,ce=n.options.per_page||this.defaultPerPage,Ue=(await y.select({...getTableColumns(r),...m.selection}).from(r).innerJoin(m.source,m.on).where(h).orderBy(...x).limit(ce).offset((I-1)*ce)).map(M=>{let N={},Ve=[];for(let[F,ue]of Object.entries(M))if(F!==be){if(F.startsWith(ze)){Ve[Number(F.slice(ze.length))]=ue;continue}N[F]=ue;}let Ze={},Ke=[];return e.fields.forEach((F,ue)=>{if(!l.includes(F))return;let Qe=ut(Ve[ue],this.highlightTag);Qe!==null&&(Ke.push(F),Ze[F]=[Qe]);}),{item:N,score:dt(Number(M[be])),matchedFields:Ke,...t.highlight?{highlights:Ze}:{}}}),Dt=buildIncludeOptions(n.options.include,this.getRelationScope(n.options.withDeleted)),yt=await O(y,Ue.map(M=>M.item),this._meta,Dt);return {items:Ue.map((M,N)=>({...M,item:yt[N]})),totalCount:T}}},Ee=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await ie({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));return {result:await O(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},xe=class extends ImportEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}},Ie=class extends CloneEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let n=this.getTable(),r=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),s=[eq(r,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));k(s,i,l=>this.getColumn(l));let a=await this.getDb().select().from(n).where(f(...s)).limit(1);return a[0]?a[0]:null}async createClone(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(n).returning())[0]}};function Wr(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=o},Read:class extends V{_meta=e;db=o},Update:class extends Z{_meta=e;db=o},Delete:class extends K{_meta=e;db=o},List:class extends Q{_meta=e;db=o;dialect=n},Restore:class extends W{_meta=e;db=o},Upsert:class extends Y{_meta=e;db=o;dialect=n},Search:class extends te{_meta=e;db=o;dialect=n},BatchCreate:class extends H{_meta=e;db=o},BatchUpdate:class extends G{_meta=e;db=o},BatchDelete:class extends X{_meta=e;db=o},BatchRestore:class extends J{_meta=e;db=o},BatchUpsert:class extends ee{_meta=e;db=o;dialect=n}}}var gt=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}recordScope(e,t){return and(eq(this.col("resourceTable"),e),eq(this.col("recordId"),String(t)))}toEntry(e){return {id:e.id,recordId:e.recordId,version:e.version,data:JSON.parse(e.data),createdAt:new Date(e.createdAt),...e.changedBy!=null?{changedBy:e.changedBy}:{},...e.changeReason!=null?{changeReason:e.changeReason}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{}}}async store(e,t){let n=t.createdAt instanceof Date?t.createdAt:new Date(t.createdAt);await this.db.insert(this.table).values({id:t.id,resourceTable:e,recordId:String(t.recordId),version:t.version,data:JSON.stringify(t.data),createdAt:n.getTime(),changedBy:t.changedBy??null,changeReason:t.changeReason??null,changes:t.changes?JSON.stringify(t.changes):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version")));return (n?.limit!=null||n?.offset!=null)&&(r=r.limit(n?.limit??Number.MAX_SAFE_INTEGER)),n?.offset!=null&&(r=r.offset(n.offset)),(await r).map(s=>this.toEntry(s))}async getVersion(e,t,n){let r=await this.db.select().from(this.table).where(and(this.recordScope(e,t),eq(this.col("version"),n))).limit(1);return r.length>0?this.toEntry(r[0]):null}async getLatestVersion(e,t){let n=await this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version"))).limit(1);return n.length>0?n[0].version:0}async pruneVersions(e,t,n){if(n<=0)return this.deleteAllVersions(e,t);let r=await this.getByRecordId(e,t);if(r.length<=n)return 0;let i=r[n-1].version;return (await this.db.delete(this.table).where(and(this.recordScope(e,t),lt$1(this.col("version"),i))).returning()).length}async deleteAllVersions(e,t){return (await this.db.delete(this.table).where(this.recordScope(e,t)).returning()).length}};function Pn(){return {id:text("id").primaryKey(),resourceTable:text("resource_table").notNull(),recordId:text("record_id").notNull(),version:integer("version").notNull(),data:text("data").notNull(),createdAt:integer("created_at").notNull(),changedBy:text("changed_by"),changeReason:text("change_reason"),changes:text("changes")}}function mo(o="version_history",e){return sqliteTable(o,Pn(),t=>[index(`${o}_record_version_idx`).on(t.resourceTable,t.recordId,t.version),...e?.(t)??[]])}var ht=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}toEntry(e){return {id:e.id,timestamp:new Date(e.timestamp),action:e.action,tableName:e.tableName,recordId:e.recordId,...e.userId!=null?{userId:e.userId}:{},...e.record!=null?{record:JSON.parse(e.record)}:{},...e.previousRecord!=null?{previousRecord:JSON.parse(e.previousRecord)}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{},...e.metadata!=null?{metadata:JSON.parse(e.metadata)}:{}}}async store(e){let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);await this.db.insert(this.table).values({id:e.id,tableName:e.tableName,recordId:String(e.recordId),action:e.action,timestamp:t.getTime(),userId:e.userId??null,record:e.record!==void 0?JSON.stringify(e.record):null,previousRecord:e.previousRecord!==void 0?JSON.stringify(e.previousRecord):null,changes:e.changes!==void 0?JSON.stringify(e.changes):null,metadata:e.metadata!==void 0?JSON.stringify(e.metadata):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(f(eq(this.col("tableName"),e),eq(this.col("recordId"),String(t)))).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=n?.offset||0,s=n?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}async getAll(e){let t=[];e?.tableName&&t.push(eq(this.col("tableName"),e.tableName)),e?.action&&t.push(eq(this.col("action"),e.action)),e?.userId&&t.push(eq(this.col("userId"),e.userId)),e?.startDate&&t.push(gte(this.col("timestamp"),e.startDate.getTime())),e?.endDate&&t.push(lte(this.col("timestamp"),e.endDate.getTime()));let n=t.length>0?f(...t):void 0,r=this.db.select().from(this.table).where(n).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=e?.offset||0,s=e?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}};function $n(){return {id:text("id").primaryKey(),tableName:text("table_name").notNull(),recordId:text("record_id").notNull(),action:text("action").notNull(),timestamp:integer("timestamp").notNull(),userId:text("user_id"),record:text("record"),previousRecord:text("previous_record"),changes:text("changes"),metadata:text("metadata")}}function zo(o="audit_logs",e){return sqliteTable(o,$n(),t=>[index(`${o}_record_idx`).on(t.tableName,t.recordId),index(`${o}_timestamp_idx`).on(t.timestamp),...e?.(t)??[]])}var le=null,bt=false,ke=null;async function Be(){if(bt){if(ke)throw ke;if(le)return le}bt=true;try{return le=await import('drizzle-zod'),le}catch{throw ke=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ke}}async function qn(o,e){return (await Be()).createSelectSchema(o,e)}async function Ln(o,e){return (await Be()).createInsertSchema(o,e)}async function jn(o,e){let t=await Be();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Un(o,e){let t=await Be(),n=e?.coerceDates!==false,r=n?Qn(o):new Set,i=t.createSelectSchema(o,e?.selectRefine),s=t.createInsertSchema(o,e?.insertRefine),a;return t.createUpdateSchema?a=t.createUpdateSchema(o,e?.updateRefine):a=t.createInsertSchema(o,e?.updateRefine).partial(),n&&r.size>0&&(s=zt(s,r),a=zt(a,r)),{select:i,insert:s,update:a}}function Vn(){return le!==null}var Zn=z$1.preprocess(o=>{if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z$1.date()),Kn=z$1.preprocess(o=>{if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z$1.date().nullable());function Qn(o){let e=new Set,t=o;for(let[n,r]of Object.entries(t)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let i=r;if(!i||typeof i!="object")continue;let s=String(i.dataType??"").toLowerCase(),a=String(i.columnType??"").toLowerCase(),l=i.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(n);}return e}function zt(o,e){if(e.size===0)return o;let t=o.shape,n={};for(let[r,i]of Object.entries(t))if(e.has(r)){let s=i.isOptional?.()??false,a=i.isNullable?.()??false,l=Zn;(a||s)&&(l=Kn),s&&(l=l.optional()),n[r]=l;}else n[r]=i;return z$1.object(n)}var Mo={CreateEndpoint:U,ListEndpoint:Q,ReadEndpoint:V,UpdateEndpoint:Z,DeleteEndpoint:K,RestoreEndpoint:W,BatchCreateEndpoint:H,BatchUpdateEndpoint:G,BatchDeleteEndpoint:X,BatchRestoreEndpoint:J,BatchUpsertEndpoint:ee,SearchEndpoint:te,AggregateEndpoint:Me,ExportEndpoint:Ee,ImportEndpoint:xe,UpsertEndpoint:Y,CloneEndpoint:Ie,BulkPatchEndpoint:ye,VersionHistoryEndpoint:we,VersionReadEndpoint:Ce,VersionCompareEndpoint:Re,VersionRollbackEndpoint:Te};export{it as DEFAULT_FTS5_PREFIX_INDEX,ot as DEFAULT_FTS5_TOKENIZE,Ot as DRIZZLE_DIALECTS,Mo as DrizzleAdapters,Me as DrizzleAggregateEndpoint,ht as DrizzleAuditLogStorage,H as DrizzleBatchCreateEndpoint,X as DrizzleBatchDeleteEndpoint,J as DrizzleBatchRestoreEndpoint,G as DrizzleBatchUpdateEndpoint,ee as DrizzleBatchUpsertEndpoint,ye as DrizzleBulkPatchEndpoint,Ie as DrizzleCloneEndpoint,U as DrizzleCreateEndpoint,K as DrizzleDeleteEndpoint,Ee as DrizzleExportEndpoint,xe as DrizzleImportEndpoint,Q as DrizzleListEndpoint,V as DrizzleReadEndpoint,W as DrizzleRestoreEndpoint,te as DrizzleSearchEndpoint,Z as DrizzleUpdateEndpoint,Y as DrizzleUpsertEndpoint,Re as DrizzleVersionCompareEndpoint,we as DrizzleVersionHistoryEndpoint,Ce as DrizzleVersionReadEndpoint,Te as DrizzleVersionRollbackEndpoint,gt as DrizzleVersioningStorage,O as batchLoadDrizzleRelations,Ne as buildFts5Match,oe as buildWhereCondition,j as cast,Wr as createDrizzleCrud,Un as createDrizzleSchemas,Ln as createInsertSchema,qn as createSelectSchema,jn as createUpdateSchema,an as defineFts5Index,p as getColumn,z as getTable,Vn as isDrizzleZodAvailable,At as loadDrizzleRelation,Pe as loadDrizzleRelations,A as readCount,$t as resolveTimestampRepresentation,S as resolveTimestampValue,zo as sqliteAuditLogTable,mo as sqliteVersionHistoryTable,L as substringMatch,st as tokenizeFts5Query};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hono-crud/drizzle",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.25",
|
|
4
4
|
"description": "Drizzle ORM CRUD adapter for hono-crud",
|
|
5
5
|
"author": "Kauan Guesser <contato@kauan.net>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"drizzle-zod": ">=0.8.0",
|
|
48
48
|
"hono": ">=4.11.7 <5",
|
|
49
49
|
"zod": ">=4.0.0",
|
|
50
|
-
"hono-crud": "^0.13.
|
|
50
|
+
"hono-crud": "^0.13.31"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"drizzle-orm": "^0.45.1",
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"tsup": "^8.4.0",
|
|
57
57
|
"typescript": "^5.8.3",
|
|
58
58
|
"zod": "^4.3.5",
|
|
59
|
-
"hono-crud": "0.13.
|
|
59
|
+
"hono-crud": "0.13.31"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
62
62
|
"drizzle-zod": {
|