@hono-crud/drizzle 0.1.21 → 0.1.24
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 +26 -0
- package/dist/index.d.ts +100 -6
- package/dist/index.js +2 -2
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# @hono-crud/drizzle
|
|
2
2
|
|
|
3
|
+
## 0.1.24
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
## 0.1.23
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- fabc720: Cloudflare ergonomics:
|
|
14
|
+
|
|
15
|
+
- `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.
|
|
16
|
+
- 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.
|
|
17
|
+
- `AuthType` gains `'session'` for sessions resolved by an external auth library and mapped with `setAuthContext`.
|
|
18
|
+
- `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.
|
|
19
|
+
- New `docs/cloudflare.md`: wrangler template, per-request binding injection, column conventions that keep D1 happy, and the D1/KV limits to design around.
|
|
20
|
+
|
|
21
|
+
- 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`.
|
|
22
|
+
|
|
23
|
+
## 0.1.22
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- ee9989e: Adapter tightening: drizzle's lazy drizzle-zod loader now has a non-null return type — the 10 caller-side `!` assertions are gone, and a concurrent first call no longer crashes on a not-yet-populated cache (it re-imports idempotently); `getTable` throws `ConfigurationException` (500 `CONFIGURATION_ERROR` envelope) instead of a plain `Error` for a model without a table reference, per the error-split doctrine; the drizzle/prisma connection duck-types use an honest `(key: string)` context getter instead of `(key: never)` + `as never` casts; memory's `queryMemoryStore`/`findByUpsertKeys` are bounded `<T extends Record<string, unknown>>`, removing seven internal widening casts.
|
|
28
|
+
|
|
3
29
|
## 0.1.21
|
|
4
30
|
|
|
5
31
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
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';
|
|
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
|
/**
|
|
@@ -149,6 +152,10 @@ type DrizzleEnv<DB = DrizzleDatabaseConstraint> = {
|
|
|
149
152
|
};
|
|
150
153
|
/**
|
|
151
154
|
* Gets the Drizzle table from the model.
|
|
155
|
+
*
|
|
156
|
+
* Every call site is a per-request endpoint method, so a missing `table` is
|
|
157
|
+
* request-time misconfiguration — per the error-split doctrine it surfaces as
|
|
158
|
+
* a 500 CONFIGURATION_ERROR envelope, not an unmapped plain Error.
|
|
152
159
|
*/
|
|
153
160
|
declare function getTable<M extends MetaInput>(meta: M): DrizzleTable;
|
|
154
161
|
/**
|
|
@@ -278,6 +285,8 @@ declare abstract class DrizzleCreateEndpoint<E extends Env = Env, M extends Meta
|
|
|
278
285
|
*/
|
|
279
286
|
protected getDb(): DB;
|
|
280
287
|
protected getTable(): DrizzleTable;
|
|
288
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
289
|
+
protected managedTimestampValue(field: string): unknown;
|
|
281
290
|
/**
|
|
282
291
|
* Gets a related table from the relation config.
|
|
283
292
|
*/
|
|
@@ -331,6 +340,8 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
|
|
|
331
340
|
/** Gets the database instance from property, transaction, or context */
|
|
332
341
|
protected getDb(): DB;
|
|
333
342
|
protected getTable(): DrizzleTable;
|
|
343
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
344
|
+
protected managedTimestampValue(field: string): unknown;
|
|
334
345
|
protected getColumn(field: string): DrizzleColumn;
|
|
335
346
|
/**
|
|
336
347
|
* Gets a related table from the relation config.
|
|
@@ -371,6 +382,8 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
|
|
|
371
382
|
/** Gets the database instance from property, transaction, or context */
|
|
372
383
|
protected getDb(): DB;
|
|
373
384
|
protected getTable(): DrizzleTable;
|
|
385
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
386
|
+
protected managedTimestampValue(field: string): unknown;
|
|
374
387
|
protected getColumn(field: string): DrizzleColumn;
|
|
375
388
|
/**
|
|
376
389
|
* Gets a related table from the relation config.
|
|
@@ -471,6 +484,8 @@ declare abstract class DrizzleBatchCreateEndpoint<E extends Env = Env, M extends
|
|
|
471
484
|
/** Gets the database instance from property or context */
|
|
472
485
|
protected getDb(): DB;
|
|
473
486
|
protected getTable(): DrizzleTable;
|
|
487
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
488
|
+
protected managedTimestampValue(field: string): unknown;
|
|
474
489
|
batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<ModelObject<M['model']>[]>;
|
|
475
490
|
}
|
|
476
491
|
/**
|
|
@@ -485,6 +500,8 @@ declare abstract class DrizzleBatchUpdateEndpoint<E extends Env = Env, M extends
|
|
|
485
500
|
/** Gets the database instance from property or context */
|
|
486
501
|
protected getDb(): DB;
|
|
487
502
|
protected getTable(): DrizzleTable;
|
|
503
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
504
|
+
protected managedTimestampValue(field: string): unknown;
|
|
488
505
|
protected getColumn(field: string): DrizzleColumn;
|
|
489
506
|
batchUpdate(items: BatchUpdateItem<ModelObject<M['model']>>[]): Promise<{
|
|
490
507
|
updated: ModelObject<M['model']>[];
|
|
@@ -503,6 +520,8 @@ declare abstract class DrizzleBatchDeleteEndpoint<E extends Env = Env, M extends
|
|
|
503
520
|
/** Gets the database instance from property or context. */
|
|
504
521
|
protected getDb(): DB;
|
|
505
522
|
protected getTable(): DrizzleTable;
|
|
523
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
524
|
+
protected managedTimestampValue(field: string): unknown;
|
|
506
525
|
protected getColumn(field: string): DrizzleColumn;
|
|
507
526
|
batchDelete(ids: string[]): Promise<{
|
|
508
527
|
deleted: ModelObject<M['model']>[];
|
|
@@ -548,6 +567,8 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
|
|
|
548
567
|
/** Gets the database instance from property or context. */
|
|
549
568
|
protected getDb(): DB;
|
|
550
569
|
protected getTable(): DrizzleTable;
|
|
570
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
571
|
+
protected managedTimestampValue(field: string): unknown;
|
|
551
572
|
protected getColumn(field: string): DrizzleColumn;
|
|
552
573
|
findExisting(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']> | null>;
|
|
553
574
|
create(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
|
|
@@ -586,6 +607,8 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
586
607
|
/** Gets the database instance from property or context. */
|
|
587
608
|
protected getDb(): DB;
|
|
588
609
|
protected getTable(): DrizzleTable;
|
|
610
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
611
|
+
protected managedTimestampValue(field: string): unknown;
|
|
589
612
|
protected getColumn(field: string): DrizzleColumn;
|
|
590
613
|
findExisting(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']> | null>;
|
|
591
614
|
create(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
|
|
@@ -639,6 +662,8 @@ declare abstract class DrizzleBulkPatchEndpoint<E extends Env = Env, M extends M
|
|
|
639
662
|
/** Gets the database instance from property or context. */
|
|
640
663
|
protected getDb(): DB;
|
|
641
664
|
protected getTable(): DrizzleTable;
|
|
665
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
666
|
+
protected managedTimestampValue(field: string): unknown;
|
|
642
667
|
protected getColumn(field: string): DrizzleColumn;
|
|
643
668
|
/** WHERE clause shared by countMatching/applyPatch: filters + soft-delete guard. */
|
|
644
669
|
private buildConditions;
|
|
@@ -827,6 +852,8 @@ declare abstract class DrizzleImportEndpoint<E extends Env = Env, M extends Meta
|
|
|
827
852
|
/** Gets the database instance from property or context. */
|
|
828
853
|
protected getDb(): DB;
|
|
829
854
|
protected getTable(): DrizzleTable;
|
|
855
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
856
|
+
protected managedTimestampValue(field: string): unknown;
|
|
830
857
|
protected getColumn(field: string): DrizzleColumn;
|
|
831
858
|
/**
|
|
832
859
|
* Finds an existing record by upsert keys.
|
|
@@ -865,6 +892,8 @@ declare abstract class DrizzleCloneEndpoint<E extends Env = Env, M extends MetaI
|
|
|
865
892
|
/** Gets the database instance from property or context. */
|
|
866
893
|
protected getDb(): DB;
|
|
867
894
|
protected getTable(): DrizzleTable;
|
|
895
|
+
/** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
|
|
896
|
+
protected managedTimestampValue(field: string): unknown;
|
|
868
897
|
protected getColumn(field: string): DrizzleColumn;
|
|
869
898
|
/** Generates the primary-key value for the cloned row. Defaults to UUIDv4. */
|
|
870
899
|
protected generateId(): string;
|
|
@@ -999,14 +1028,30 @@ declare class DrizzleVersioningStorage implements VersioningStorage {
|
|
|
999
1028
|
pruneVersions(tableName: string, recordId: string | number, keepCount: number): Promise<number>;
|
|
1000
1029
|
deleteAllVersions(tableName: string, recordId: string | number): Promise<number>;
|
|
1001
1030
|
}
|
|
1031
|
+
/** Column builders of {@link sqliteVersionHistoryTable} (fresh per call — builders are single-use). */
|
|
1032
|
+
declare function versionHistoryColumns(): {
|
|
1033
|
+
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
1034
|
+
resourceTable: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"resource_table", [string, ...string[]], number | undefined>>;
|
|
1035
|
+
recordId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record_id", [string, ...string[]], number | undefined>>;
|
|
1036
|
+
version: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"version">>;
|
|
1037
|
+
data: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"data", [string, ...string[]], number | undefined>>;
|
|
1038
|
+
createdAt: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"created_at">>;
|
|
1039
|
+
changedBy: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changed_by", [string, ...string[]], number | undefined>;
|
|
1040
|
+
changeReason: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"change_reason", [string, ...string[]], number | undefined>;
|
|
1041
|
+
changes: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changes", [string, ...string[]], number | undefined>;
|
|
1042
|
+
};
|
|
1043
|
+
/** The built columns handed to an `extraConfig` callback of {@link sqliteVersionHistoryTable}. */
|
|
1044
|
+
type SqliteVersionHistoryColumns = BuildColumns<string, ReturnType<typeof versionHistoryColumns>, 'sqlite'>;
|
|
1002
1045
|
/**
|
|
1003
1046
|
* Build a SQLite/D1 history table with the columns
|
|
1004
|
-
* {@link DrizzleVersioningStorage} expects.
|
|
1005
|
-
*
|
|
1047
|
+
* {@link DrizzleVersioningStorage} expects. Ships with an index on
|
|
1048
|
+
* `(resource_table, record_id, version)`, which backs every per-record
|
|
1049
|
+
* lookup the storage performs.
|
|
1006
1050
|
*
|
|
1007
1051
|
* @param name - Table name. Default `version_history`.
|
|
1052
|
+
* @param extraConfig - Additional indexes/constraints, appended to the default.
|
|
1008
1053
|
*/
|
|
1009
|
-
declare function sqliteVersionHistoryTable(name?: string): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1054
|
+
declare function sqliteVersionHistoryTable(name?: string, extraConfig?: (table: SqliteVersionHistoryColumns) => SQLiteTableExtraConfigValue[]): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1010
1055
|
name: string;
|
|
1011
1056
|
schema: undefined;
|
|
1012
1057
|
columns: {
|
|
@@ -1254,15 +1299,34 @@ declare class DrizzleAuditLogStorage implements AuditLogStorage {
|
|
|
1254
1299
|
offset?: number;
|
|
1255
1300
|
}): Promise<AuditLogEntry[]>;
|
|
1256
1301
|
}
|
|
1302
|
+
/** Column builders of {@link sqliteAuditLogTable} (fresh per call — builders are single-use). */
|
|
1303
|
+
declare function auditLogColumns(): {
|
|
1304
|
+
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
1305
|
+
tableName: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"table_name", [string, ...string[]], number | undefined>>;
|
|
1306
|
+
recordId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record_id", [string, ...string[]], number | undefined>>;
|
|
1307
|
+
action: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"action", [string, ...string[]], number | undefined>>;
|
|
1308
|
+
timestamp: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"timestamp">>;
|
|
1309
|
+
userId: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"user_id", [string, ...string[]], number | undefined>;
|
|
1310
|
+
record: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"record", [string, ...string[]], number | undefined>;
|
|
1311
|
+
previousRecord: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"previous_record", [string, ...string[]], number | undefined>;
|
|
1312
|
+
changes: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"changes", [string, ...string[]], number | undefined>;
|
|
1313
|
+
metadata: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"metadata", [string, ...string[]], number | undefined>;
|
|
1314
|
+
};
|
|
1315
|
+
/** The built columns handed to an `extraConfig` callback of {@link sqliteAuditLogTable}. */
|
|
1316
|
+
type SqliteAuditLogColumns = BuildColumns<string, ReturnType<typeof auditLogColumns>, 'sqlite'>;
|
|
1257
1317
|
/**
|
|
1258
1318
|
* Build a SQLite/D1 audit table with the columns {@link DrizzleAuditLogStorage}
|
|
1259
1319
|
* expects. `tableName`/`recordId`/`timestamp` back the per-record lookups and
|
|
1260
|
-
* the `getAll` filters the storage performs
|
|
1320
|
+
* the `getAll` filters the storage performs, so the table ships with indexes
|
|
1321
|
+
* on `(table_name, record_id)` and `(timestamp)` — D1 charges per row
|
|
1322
|
+
* scanned, and an unindexed audit table grows without bound.
|
|
1261
1323
|
*
|
|
1262
1324
|
* @param name - Table name. Default `audit_logs` (matches `AuditConfig`'s
|
|
1263
1325
|
* default `tableName`).
|
|
1326
|
+
* @param extraConfig - Additional indexes/constraints, appended to the
|
|
1327
|
+
* defaults (`(t) => [index('audit_user_idx').on(t.userId)]`).
|
|
1264
1328
|
*/
|
|
1265
|
-
declare function sqliteAuditLogTable(name?: string): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1329
|
+
declare function sqliteAuditLogTable(name?: string, extraConfig?: (table: SqliteAuditLogColumns) => SQLiteTableExtraConfigValue[]): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
1266
1330
|
name: string;
|
|
1267
1331
|
schema: undefined;
|
|
1268
1332
|
columns: {
|
|
@@ -1458,6 +1522,36 @@ declare function sqliteAuditLogTable(name?: string): drizzle_orm_sqlite_core.SQL
|
|
|
1458
1522
|
dialect: "sqlite";
|
|
1459
1523
|
}>;
|
|
1460
1524
|
|
|
1525
|
+
/**
|
|
1526
|
+
* Column-aware timestamp values for engine-managed writes.
|
|
1527
|
+
*
|
|
1528
|
+
* Core stamps `createdAt` / `updatedAt` / the soft-delete marker at the
|
|
1529
|
+
* write site, but the value a SQL driver can bind depends on how the column
|
|
1530
|
+
* was declared: a Drizzle `integer({ mode: 'timestamp' | 'timestamp_ms' })` or
|
|
1531
|
+
* `timestamp()` column expects a `Date` (Drizzle converts it), a plain
|
|
1532
|
+
* `integer()` expects epoch milliseconds, and a `text()` column expects a
|
|
1533
|
+
* string. Cloudflare D1 makes the distinction matter: its `bind()` rejects
|
|
1534
|
+
* objects outright, so a `Date` against a plain integer column fails with
|
|
1535
|
+
* `D1_TYPE_ERROR`, while libsql silently accepts it.
|
|
1536
|
+
*
|
|
1537
|
+
* The representation is read structurally from the column's `dataType`
|
|
1538
|
+
* (`'date' | 'number' | 'string' | …`), which every Drizzle column exposes
|
|
1539
|
+
* regardless of dialect, so this module needs no drizzle-orm import.
|
|
1540
|
+
*/
|
|
1541
|
+
/** How a column stores a point in time. */
|
|
1542
|
+
type TimestampRepresentation = 'date' | 'number' | 'string';
|
|
1543
|
+
/**
|
|
1544
|
+
* The representation a Drizzle column expects for a timestamp write.
|
|
1545
|
+
* Unknown or non-column values fall back to `'date'` (Drizzle's own
|
|
1546
|
+
* timestamp column shape).
|
|
1547
|
+
*/
|
|
1548
|
+
declare function resolveTimestampRepresentation(column: unknown): TimestampRepresentation;
|
|
1549
|
+
/**
|
|
1550
|
+
* `now` in the representation the column can bind: a `Date`, epoch
|
|
1551
|
+
* milliseconds, or an ISO-8601 string.
|
|
1552
|
+
*/
|
|
1553
|
+
declare function resolveTimestampValue(column: unknown, now?: Date): Date | number | string;
|
|
1554
|
+
|
|
1461
1555
|
/**
|
|
1462
1556
|
* Drizzle-Zod schema utilities.
|
|
1463
1557
|
*
|
|
@@ -1625,4 +1719,4 @@ declare function isDrizzleZodAvailable(): boolean;
|
|
|
1625
1719
|
*/
|
|
1626
1720
|
declare const DrizzleAdapters: AdapterBundle;
|
|
1627
1721
|
|
|
1628
|
-
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 };
|
|
1722
|
+
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, type SqliteAuditLogColumns, type SqliteVersionHistoryColumns, type TimestampRepresentation, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, resolveTimestampRepresentation, resolveTimestampValue, sqliteAuditLogTable, sqliteVersionHistoryTable, substringMatch };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt,gte,gt,ne as ne$1,eq,sql,and,desc,asc,or}from'drizzle-orm';import {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,
|
|
1
|
+
import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt as lt$1,gte,gt,ne as ne$1,eq,sql,and,desc,asc,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,decodeCursor}from'hono-crud/internal';import {sqliteTable,index,text,integer}from'drizzle-orm/sqlite-core';import {z}from'zod';function m(i){let e=i;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 ne(...o){return or(...o)}function R(o,e,t){e.enabled&&o.push(isNull(t(e.field)));}var nt=["sqlite","pg","mysql"];function b(o){if(!o.model.table)throw new Error(`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 Ce(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 rt(o,e,t,n){let r=n.table;if(!r)return e;let i=Ce(o),s=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:s}}async function Me(o,e,t,n){return loadRelationsForItem(e,t,Ce(o),n)}async function k(o,e,t,n){return batchLoadRelations(e,t,Ce(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$1(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(ne(...O));}u.push(...l);let d=u.length>0?g(...u):void 0,z=await e.select({count:sql`count(*)`}).from(t).where(d),M=I(z),D=c!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0),y=d,w=false;if(D&&n.options.cursor){let f=decodeCursor(n.options.cursor);f!==null&&(y=g(d,gt(p(t,c),f)),w=true);}let C=e.select().from(t).where(y);if(n.options.order_by){let f=p(t,n.options.order_by),O=n.options.order_by_direction==="desc"?desc:asc;C=C.orderBy(O(f));}if(D){let f=n.options.limit||n.options.per_page||a;return {records:await C.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 C.limit(S).offset((E-1)*S),totalCount:M,page:E,perPage:S}}async function re(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},z=await s.insert(a).values(d).returning();z[0]&&c.push(z[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,z]of Object.entries(n))c.push(eq(this.getColumn(d),z));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 z of d){if(typeof z!="object"||z===null)continue;let M={...z,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,y=await s.update(a).set(D).where(eq(u,M)).returning();y[0]&&l.updated.push(y[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 _t(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 re(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[y,w]of Object.entries(e))!r.includes(y)&&y!==i&&(this.createOnlyFields?.includes(y)||(c[y]=w));a.enabled&&(c[a.updatedAt]=Date.now());let u=r.map(y=>this.getColumn(y)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));let z=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:z}).returning())[0],created:false}:{data:(await M.onConflictDoUpdate({target:u,set:z,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 re(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)}`},z=this.getDb().insert(n).values(a),M=await(this.dialect==="mysql"?z.onDuplicateKeyUpdate({set:d}):z.onConflictDoUpdate({target:u,set:d})).returning();return {items:M.map((D,y)=>({data:D,created:false,index:y})),createdCount:0,updatedCount:M.length,totalCount:M.length}}},ie=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 me(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 se=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 me(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ae=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 me(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},le=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 me(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},de=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 me(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]}},ce=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),C=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} @@ ${C}`);}else {let w=(C,E)=>{try{let S=this.getColumn(C);return P(sql`CAST(${S} AS TEXT)`,E,this.dialect)}catch{return}};if(e.mode==="all"){let C=_t(e.query);if(C.length>0){let E=[];for(let S of C){let fe=s.map(f=>w(f,S)).filter(f=>f!==void 0);fe.length>0&&E.push(ne(...fe));}E.length>0&&r.push(g(...E));}}else {let C=s.map(E=>w(E,e.query)).filter(E=>E!==void 0);C.length>0&&r.push(ne(...C));}}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),z=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),M=d.map(w=>w.item),D=await k(this.getDb(),M,this._meta,z);return {items:d.map((w,C)=>({...w,item:D[C]})),totalCount:c}}},ue=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})}}},pe=class extends ImportEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return re(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]}},ge=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 Zn(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 ar(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 pr(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 ze=null,Ae=false,he=null;async function De(){if(Ae){if(he)throw he;return ze}Ae=true;try{return ze=await import('drizzle-zod'),ze}catch{throw he=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),he}}async function Vt(o,e){return (await De()).createSelectSchema(o,e)}async function Kt(o,e){return (await De()).createInsertSchema(o,e)}async function $t(o,e){let t=await De();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Qt(o,e){let t=await De(),n=e?.coerceDates!==false,r=n?Xt(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 Wt(){return ze!==null}var Ht=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()),Jt=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 Xt(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=Ht;(a||s)&&(l=Jt),s&&(l=l.optional()),n[r]=l;}else n[r]=i;return z.object(n)}var fr={CreateEndpoint:_,ListEndpoint:L,ReadEndpoint:q,UpdateEndpoint:N,DeleteEndpoint:F,RestoreEndpoint:U,BatchCreateEndpoint:Z,BatchUpdateEndpoint:V,BatchDeleteEndpoint:K,BatchRestoreEndpoint:$,BatchUpsertEndpoint:W,SearchEndpoint:H,AggregateEndpoint:ce,ExportEndpoint:ue,ImportEndpoint:pe,UpsertEndpoint:Q,CloneEndpoint:ge,BulkPatchEndpoint:ie,VersionHistoryEndpoint:se,VersionReadEndpoint:ae,VersionCompareEndpoint:le,VersionRollbackEndpoint:de};export{nt as DRIZZLE_DIALECTS,fr as DrizzleAdapters,ce as DrizzleAggregateEndpoint,Pe as DrizzleAuditLogStorage,Z as DrizzleBatchCreateEndpoint,K as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,V as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,ie as DrizzleBulkPatchEndpoint,ge as DrizzleCloneEndpoint,_ as DrizzleCreateEndpoint,F as DrizzleDeleteEndpoint,ue as DrizzleExportEndpoint,pe as DrizzleImportEndpoint,L as DrizzleListEndpoint,q as DrizzleReadEndpoint,U as DrizzleRestoreEndpoint,H as DrizzleSearchEndpoint,N as DrizzleUpdateEndpoint,Q as DrizzleUpsertEndpoint,le as DrizzleVersionCompareEndpoint,se as DrizzleVersionHistoryEndpoint,ae as DrizzleVersionReadEndpoint,de as DrizzleVersionRollbackEndpoint,je as DrizzleVersioningStorage,k as batchLoadDrizzleRelations,X as buildWhereCondition,A as cast,Zn as createDrizzleCrud,Qt as createDrizzleSchemas,Kt as createInsertSchema,Vt as createSelectSchema,$t as createUpdateSchema,p as getColumn,b as getTable,Wt as isDrizzleZodAvailable,rt as loadDrizzleRelation,Me as loadDrizzleRelations,I as readCount,pr as sqliteAuditLogTable,ar as sqliteVersionHistoryTable,P as substringMatch};
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}function q(i){return i}function ee(i,e){return m(i).transaction(async t=>{i._tx=t;try{return await e()}finally{i._tx=void 0;}})}function g(...i){return and(...i)}function ae(...i){return or(...i)}function E(i,e,t){e.enabled&&i.push(isNull(t(e.field)));}var st=["sqlite","pg","mysql"];function b(i){if(!i.model.table)throw new ConfigurationException(`Model ${i.model.tableName} does not have a table reference`);return i.model.table}function c(i,e){let t=getTableColumns(i),n=t[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return n}function we(i){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n,r)=>{let o=[inArray(c(e,t),n)];return r?.tenantField!=null&&r.tenantValue!=null&&o.push(eq(c(e,r.tenantField),r.tenantValue)),r?.excludeDeletedField!=null&&o.push(isNull(c(e,r.excludeDeletedField))),i.select().from(e).where(o.length===1?o[0]:and(...o))}}}async function at(i,e,t,n){let r=n.table;if(!r)return e;let o=we(i),s=await resolveRelationValueAsync(e,n,r,o.fetchRelated);return {...e,[t]:s}}async function Re(i,e,t,n){return loadRelationsForItem(e,t,we(i),n)}async function j(i,e,t,n){return batchLoadRelations(e,t,we(i),n)}function te(i,e,t="sqlite"){let n=c(i,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt(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 A(n,String(e.value).replace(/%/g,""),t,{caseSensitive:true});case "ilike":return A(n,String(e.value).replace(/%/g,""),t);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[r,o]=e.value;return between(n,r,o)}default:return assertNever(e.operator)}}function P(i){return Number(i[0]?.count)||0}async function ne(i){let{db:e,table:t,filters:n,dialect:r,searchFields:o=[],softDeleteConfig:s,defaultPerPage:a=20,primaryKeys:l,extraConditions:u=[],cursorField:p}=i,d=[];if(s?.enabled){let y=c(t,s.field);n.options.onlyDeleted?d.push(isNotNull(y)):n.options.withDeleted||d.push(isNull(y));}for(let y of n.filters){let B=te(t,y,r);B&&d.push(B);}if(n.options.search&&o.length>0){let y=n.options.search,B=o.map(Y=>A(c(t,Y),y,r));d.push(ae(...B));}d.push(...u);let h=d.length>0?g(...d):void 0,C=await e.select({count:sql`count(*)`}).from(t).where(h),D=P(C),f=p!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0),R=h,M=false;if(f&&n.options.cursor){let y=decodeCursor(n.options.cursor);y!==null&&(R=g(h,gt(c(t,p),y)),M=true);}let T=e.select().from(t).where(R),O=n.options.order_by;if(O){let y=n.options.order_by_direction==="desc"?desc:asc,B=[O,...l.filter(Y=>Y!==O)];T=T.orderBy(...B.map(Y=>y(c(t,Y))));}if(f){let y=n.options.limit||n.options.per_page||a;return {records:await T.limit(y+1),totalCount:D,page:0,perPage:y,cursor:{limit:y,applied:M}}}let G=n.options.page||1,k=n.options.per_page||a;return {records:await T.limit(k).offset((G-1)*k),totalCount:D,page:G,perPage:k}}async function le(i,e,t,n,r){let o=[];for(let a of r){let l=n[a];l!==void 0&&o.push(eq(t(a),l));}return o.length===0?null:(await i.select().from(e).where(g(...o)).limit(1))[0]||null}function A(i,e,t,n){if(n?.caseSensitive)switch(t){case "pg":return sql`POSITION(${e} IN ${i}) > 0`;case "mysql":return sql`LOCATE(${e}, ${i}) > 0`;default:return sql`INSTR(${i}, ${e}) > 0`}switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${i})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${i})) > 0`;default:return sql`INSTR(LOWER(${i}), LOWER(${e})) > 0`}}function lt(i){if(!i||typeof i!="object")return "date";let e=String(i.dataType??"").toLowerCase();return e==="number"?"number":e==="string"?"string":"date"}function w(i,e=new Date){switch(lt(i)){case "number":return e.getTime();case "string":return e.toISOString();default:return e}}var L=class extends CreateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getRelatedTable(e){return e.table}async create(e,t){let n=t??this.getDb(),r=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await n.insert(r).values(o).returning())[0]}async createNested(e,t,n,r,o){let s=o??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],u=[];for(let p of l){if(typeof p!="object"||p===null)continue;let d={...p,id:crypto.randomUUID(),[n.foreignKey]:e},h=await s.insert(a).values(d).returning();h[0]&&u.push(h[0]);}return u}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},N=class extends ReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),o=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(o,e)];if(t)for(let[p,d]of Object.entries(t))a.push(eq(this.getColumn(p),d));E(a,s,p=>this.getColumn(p));let l=await this.getDb().select().from(r).where(g(...a)).limit(1);return l[0]?await Re(this.getDb(),l[0],this._meta,n):null}},F=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return E(l,a,p=>this.getColumn(p)),(await r.select().from(o).where(g(...l)).limit(1))[0]||null}async update(e,t,n,r){let o=r??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[d,h]of Object.entries(n))u.push(eq(this.getColumn(d),h));return E(u,l,d=>this.getColumn(d)),(await o.update(s).set(this.applyManagedUpdateFields(t)).where(g(...u)).returning())[0]||null}async processNestedWrites(e,t,n,r,o){let s=o??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:[]},u=c(a,n.foreignKey),p=c(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 C={...h,id:crypto.randomUUID(),[n.foreignKey]:e},D=await s.insert(a).values(C).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(p,d.id),eq(u,e))).limit(1))[0])continue;let{id:C,...D}=d,f=await s.update(a).set(D).where(eq(p,C)).returning();f[0]&&l.updated.push(f[0]);}if(r.delete)for(let d of r.delete)(await s.delete(a).where(g(eq(p,d),eq(u,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(p,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(p,d),eq(u,e))).returning())[0]&&l.disconnected.push(d);return l}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},U=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return E(l,a,p=>this.getColumn(p)),(await r.select().from(o).where(g(...l)).limit(1))[0]||null}async delete(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,p]of Object.entries(t))l.push(eq(this.getColumn(u),p));return E(l,a,u=>this.getColumn(u)),a.enabled?(await r.update(o).set({[a.field]:this.managedTimestampValue(a.field)}).where(g(...l)).returning())[0]||null:(await r.delete(o).where(g(...l)).returning())[0]||null}async countRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey),l=await o.select({count:sql`count(*)`}).from(s).where(eq(a,e));return P(l)}async deleteRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey);return (await o.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey);return (await o.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},V=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async list(e){let t=await ne({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:o,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 j(this.getDb(),o,this._meta,n),result_info:s}}return {result:await j(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},Z=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return l.push(isNotNull(this.getColumn(a.field))),(await r.update(o).set({[a.field]:null}).where(g(...l)).returning())[0]||null}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}};var K=class extends BatchCreateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}async batchCreate(e){let t=this.getTable(),n=e.map(o=>this.applyManagedInsertFields(o,"drizzle"));return await this.getDb().insert(t).values(n).returning()}},$=class extends BatchUpdateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[],s=[],a=this.getTenantScopeFilter();for(let l of e){let u=[eq(n,l.id)];E(u,r,d=>this.getColumn(d)),a&&u.push(eq(this.getColumn(a.field),a.value));let p=await this.getDb().update(t).set(this.applyManagedUpdateFields(l.data)).where(g(...u)).returning();p[0]?o.push(p[0]):s.push(l.id);}return {updated:o,notFound:s}}},Q=class extends BatchDeleteEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[inArray(n,e)];E(o,r,d=>this.getColumn(d));let s=this.getTenantScopeFilter();s&&o.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(g(...o)).returning():a=await this.getDb().delete(t).where(g(...o)).returning();let l=a,u=new Set(l.map(d=>String(d[this.lookupField]))),p=e.filter(d=>!u.has(d));return {deleted:l,notFound:p}}},W=class extends BatchRestoreEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[inArray(n,e),isNotNull(this.getColumn(r.field))],s=this.getTenantScopeFilter();s&&o.push(eq(this.getColumn(s.field),s.value));let l=await this.getDb().update(t).set({[r.field]:null}).where(g(...o)).returning(),u=new Set(l.map(d=>String(d[this.lookupField]))),p=e.filter(d=>!u.has(d));return {restored:l,notFound:p}}};function Ut(i){return i.split(/\s+/).filter(e=>e.length>0)}var H=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(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],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).returning())[0]}async nativeUpsert(e,t){let n=this.getTable(),r=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),u={};for(let[f,R]of Object.entries(e))!r.includes(f)&&f!==o&&(this.createOnlyFields?.includes(f)||(u[f]=R));a.enabled&&(u[a.updatedAt]=Date.now());let p=r.map(f=>this.getColumn(f)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));let h=Object.keys(u).length>0?u:{[o]:sql`${this.getColumn(o)}`},C=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await C.onDuplicateKeyUpdate({set:h}).returning())[0],created:false}:{data:(await C.onConflictDoUpdate({target:p,set:h,where:d}).returning())[0],created:false}}},J=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(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],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).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(),o=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),a=e.map(D=>this.applyManagedInsertFields(D,"drizzle")),l={},u=e[0];for(let D of Object.keys(u))!r.includes(D)&&D!==o&&(this.createOnlyFields?.includes(D)||(l[D]=sql`excluded.${sql.identifier(D)}`));s.enabled&&(l[s.updatedAt]=Date.now());let p=r.map(D=>this.getColumn(D)),d=Object.keys(l).length>0?l:{[o]:sql`${this.getColumn(o)}`},h=this.getDb().insert(n).values(a),C=await(this.dialect==="mysql"?h.onDuplicateKeyUpdate({set:d}):h.onConflictDoUpdate({target:p,set:d})).returning();return {items:C.map((D,f)=>({data:D,created:false,index:f})),createdCount:0,updatedCount:C.length,totalCount:C.length}}},ce=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}buildConditions(e){let t=this.getTable(),n=[];for(let o of e.filters){let s=te(t,o,this.dialect);s&&n.push(s);}let r=this.getSoftDeleteConfig();return E(n,r,o=>this.getColumn(o)),n}async countMatching(e){let t=this.buildConditions(e),n=await this.getDb().select({count:sql`count(*)`}).from(this.getTable()).where(g(...t));return P(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 fe(i,e,t,n,r){let o=r?g(eq(t,n),eq(c(e,r.field),r.value)):eq(t,n),s=await i.select({count:sql`count(*)`}).from(e).where(o);return P(s)>0}var ue=class extends VersionHistoryEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},pe=class extends VersionReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ge=class extends VersionCompareEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},me=class extends VersionRollbackEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}async rollback(e,t,n){let r=this.getTable(),o=this.getVersioningConfig().field;return (await this.getDb().update(r).set({...t,[o]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},be=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(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"||E(n,r,u=>this.getColumn(u));}if(e.filters)for(let[a,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[u,p]of Object.entries(l)){if(!isFilterOperator(u)){n.push(sql`1 = 0`);continue}let d=te(t,{field:a,operator:u,value:p},this.dialect);d&&n.push(d);}else n.push(eq(this.getColumn(a),l));let o=n.length>0?g(...n):void 0,s=await this.getDb().select().from(t).where(o);return computeAggregations(s,e)}},X=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return m(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async search(e,t){let n=this.getTable(),r=[],o=this.getSearchableFields(),s=e.fields||Object.keys(o);if(this.useNativeSearch&&this.vectorColumn){let R=this.getColumn(this.vectorColumn),M=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} @@ ${M}`);}else {let R=(M,T)=>{try{let O=this.getColumn(M);return A(sql`CAST(${O} AS TEXT)`,T,this.dialect)}catch{return}};if(e.mode==="all"){let M=Ut(e.query);if(M.length>0){let T=[];for(let O of M){let G=s.map(k=>R(k,O)).filter(k=>k!==void 0);G.length>0&&T.push(ae(...G));}T.length>0&&r.push(g(...T));}}else {let M=s.map(T=>R(T,e.query)).filter(T=>T!==void 0);M.length>0&&r.push(ae(...M));}}let a=await ne({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,u=a.totalCount,p=e.mode==="all"?{...e,mode:"any"}:e,d=searchInMemory(l,p,o),h=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),C=d.map(R=>R.item),D=await j(this.getDb(),C,this._meta,h);return {items:d.map((R,M)=>({...R,item:D[M]})),totalCount:u}}},he=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async list(e){let t=await ne({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 j(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},ze=class extends ImportEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(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],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).returning())[0]}},De=class extends CloneEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let n=this.getTable(),r=this.getColumn(this.lookupField),o=this.getSoftDeleteConfig(),s=[eq(r,e)];if(t)for(let[l,u]of Object.entries(t))s.push(eq(this.getColumn(l),u));E(s,o,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 nr(i,e,t){let n=t?.dialect??"sqlite";return {Create:class extends L{_meta=e;db=i},Read:class extends N{_meta=e;db=i},Update:class extends F{_meta=e;db=i},Delete:class extends U{_meta=e;db=i},List:class extends V{_meta=e;db=i;dialect=n},Restore:class extends Z{_meta=e;db=i},Upsert:class extends H{_meta=e;db=i;dialect=n},Search:class extends X{_meta=e;db=i;dialect=n},BatchCreate:class extends K{_meta=e;db=i},BatchUpdate:class extends ${_meta=e;db=i},BatchDelete:class extends Q{_meta=e;db=i},BatchRestore:class extends W{_meta=e;db=i},BatchUpsert:class extends J{_meta=e;db=i;dialect=n}}}var Ae=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return c(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 o=r[n-1].version;return (await this.db.delete(this.table).where(and(this.recordScope(e,t),lt$1(this.col("version"),o))).returning()).length}async deleteAllVersions(e,t){return (await this.db.delete(this.table).where(this.recordScope(e,t)).returning()).length}};function $t(){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 yr(i="version_history",e){return sqliteTable(i,$t(),t=>[index(`${i}_record_version_idx`).on(t.resourceTable,t.recordId,t.version),...e?.(t)??[]])}var Le=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return c(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"))),o=n?.offset||0,s=n?.limit||0;return s>0?(r=r.limit(s),o>0&&(r=r.offset(o))):o>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(o)),(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"))),o=e?.offset||0,s=e?.limit||0;return s>0?(r=r.limit(s),o>0&&(r=r.offset(o))):o>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(o)),(await r).map(l=>this.toEntry(l))}};function Xt(){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 Rr(i="audit_logs",e){return sqliteTable(i,Xt(),t=>[index(`${i}_record_idx`).on(t.tableName,t.recordId),index(`${i}_timestamp_idx`).on(t.timestamp),...e?.(t)??[]])}var ie=null,Ne=false,Ce=null;async function Me(){if(Ne){if(Ce)throw Ce;if(ie)return ie}Ne=true;try{return ie=await import('drizzle-zod'),ie}catch{throw Ce=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),Ce}}async function Gt(i,e){return (await Me()).createSelectSchema(i,e)}async function Yt(i,e){return (await Me()).createInsertSchema(i,e)}async function en(i,e){let t=await Me();return t.createUpdateSchema?t.createUpdateSchema(i,e):t.createInsertSchema(i,e).partial()}async function tn(i,e){let t=await Me(),n=e?.coerceDates!==false,r=n?sn(i):new Set,o=t.createSelectSchema(i,e?.selectRefine),s=t.createInsertSchema(i,e?.insertRefine),a;return t.createUpdateSchema?a=t.createUpdateSchema(i,e?.updateRefine):a=t.createInsertSchema(i,e?.updateRefine).partial(),n&&r.size>0&&(s=Fe(s,r),a=Fe(a,r)),{select:o,insert:s,update:a}}function nn(){return ie!==null}var rn=z.preprocess(i=>{if(i instanceof Date)return i;if(typeof i=="string"){let e=new Date(i);if(!isNaN(e.getTime()))return e}return i},z.date()),on=z.preprocess(i=>{if(i==null)return null;if(i instanceof Date)return i;if(typeof i=="string"){let e=new Date(i);if(!isNaN(e.getTime()))return e}return i},z.date().nullable());function sn(i){let e=new Set,t=i;for(let[n,r]of Object.entries(t)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let o=r;if(!o||typeof o!="object")continue;let s=String(o.dataType??"").toLowerCase(),a=String(o.columnType??"").toLowerCase(),l=o.config,u=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")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Fe(i,e){if(e.size===0)return i;let t=i.shape,n={};for(let[r,o]of Object.entries(t))if(e.has(r)){let s=o.isOptional?.()??false,a=o.isNullable?.()??false,l=rn;(a||s)&&(l=on),s&&(l=l.optional()),n[r]=l;}else n[r]=o;return z.object(n)}var Br={CreateEndpoint:L,ListEndpoint:V,ReadEndpoint:N,UpdateEndpoint:F,DeleteEndpoint:U,RestoreEndpoint:Z,BatchCreateEndpoint:K,BatchUpdateEndpoint:$,BatchDeleteEndpoint:Q,BatchRestoreEndpoint:W,BatchUpsertEndpoint:J,SearchEndpoint:X,AggregateEndpoint:be,ExportEndpoint:he,ImportEndpoint:ze,UpsertEndpoint:H,CloneEndpoint:De,BulkPatchEndpoint:ce,VersionHistoryEndpoint:ue,VersionReadEndpoint:pe,VersionCompareEndpoint:ge,VersionRollbackEndpoint:me};export{st as DRIZZLE_DIALECTS,Br as DrizzleAdapters,be as DrizzleAggregateEndpoint,Le as DrizzleAuditLogStorage,K as DrizzleBatchCreateEndpoint,Q as DrizzleBatchDeleteEndpoint,W as DrizzleBatchRestoreEndpoint,$ as DrizzleBatchUpdateEndpoint,J as DrizzleBatchUpsertEndpoint,ce as DrizzleBulkPatchEndpoint,De as DrizzleCloneEndpoint,L as DrizzleCreateEndpoint,U as DrizzleDeleteEndpoint,he as DrizzleExportEndpoint,ze as DrizzleImportEndpoint,V as DrizzleListEndpoint,N as DrizzleReadEndpoint,Z as DrizzleRestoreEndpoint,X as DrizzleSearchEndpoint,F as DrizzleUpdateEndpoint,H as DrizzleUpsertEndpoint,ge as DrizzleVersionCompareEndpoint,ue as DrizzleVersionHistoryEndpoint,pe as DrizzleVersionReadEndpoint,me as DrizzleVersionRollbackEndpoint,Ae as DrizzleVersioningStorage,j as batchLoadDrizzleRelations,te as buildWhereCondition,q as cast,nr as createDrizzleCrud,tn as createDrizzleSchemas,Yt as createInsertSchema,Gt as createSelectSchema,en as createUpdateSchema,c as getColumn,b as getTable,nn as isDrizzleZodAvailable,at as loadDrizzleRelation,Re as loadDrizzleRelations,P as readCount,lt as resolveTimestampRepresentation,w as resolveTimestampValue,Rr as sqliteAuditLogTable,yr as sqliteVersionHistoryTable,A as substringMatch};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hono-crud/drizzle",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.24",
|
|
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.30"
|
|
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.30"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
62
62
|
"drizzle-zod": {
|