@hono-crud/drizzle 0.1.20 → 0.1.22

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @hono-crud/drizzle
2
2
 
3
+ ## 0.1.22
4
+
5
+ ### Patch Changes
6
+
7
+ - 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.
8
+
9
+ ## 0.1.21
10
+
11
+ ### Patch Changes
12
+
13
+ - 60e920f: Add `DrizzleAuditLogStorage` — a durable, Drizzle-backed `AuditLogStorage` (Cloudflare D1, libsql, postgres-js, …) so audit logs survive across isolates/requests. Previously the only shipped `AuditLogStorage` was in-memory, so audit history on Workers was per-isolate and ephemeral. Ships a `sqliteAuditLogTable()` helper for D1/SQLite; one shared table backs many models (rows discriminated by the model's tableName). Semantics track `MemoryAuditLogStorage` exactly: `getAll` combines every filter (tableName, action, userId, date range) with AND, the date range is inclusive on both ends, results are oldest-first, and `limit`/`offset` slice the result. Core re-exports `AuditLogEntry`, `AuditAction`, and `AuditFieldChange` from `hono-crud/audit` so storage implementers can import them alongside the `AuditLogStorage` interface. The storage-backend contracts (`AuditLogStorage`/`AuditLogEntry`/`AuditAction`/`AuditFieldChange` and `VersioningStorage`/`VersionHistoryEntry`) are now also re-exported from `hono-crud/internal`, the curated first-party-satellite entrypoint, so `@hono-crud/*` adapters resolve them from a single internal surface instead of feature subpaths (per the Export Surface Doctrine).
14
+
3
15
  ## 0.1.20
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -46,4 +46,30 @@ const app = fromHono(new Hono());
46
46
  registerCrud(app, '/users', { create: UserCreate, read: UserRead, list: UserList });
47
47
  ```
48
48
 
49
- Exports `DrizzleAdapters` (the 22-entry adapter bundle), the `Drizzle*Endpoint` classes, `createDrizzleCrud`, `createDrizzleSchemas`, and the `DrizzleDatabaseConstraint` type.
49
+ ## Durable audit & version-history storage
50
+
51
+ Persist audit logs and version history in your database (Cloudflare D1, libsql, postgres-js, …) so they survive across isolates/requests — the durable counterparts to the in-memory `MemoryAuditLogStorage` / `MemoryVersioningStorage`. One shared table backs every model; rows are discriminated by the model's `tableName`.
52
+
53
+ ```ts
54
+ import {
55
+ DrizzleAuditLogStorage,
56
+ DrizzleVersioningStorage,
57
+ type DrizzleDatabaseConstraint,
58
+ sqliteAuditLogTable,
59
+ sqliteVersionHistoryTable,
60
+ } from '@hono-crud/drizzle';
61
+ import { setAuditStorage } from 'hono-crud/audit';
62
+ import { setVersioningStorage } from 'hono-crud/versioning';
63
+
64
+ declare const db: DrizzleDatabaseConstraint; // your drizzle instance
65
+
66
+ // `sqliteAuditLogTable()` / `sqliteVersionHistoryTable()` build the D1/SQLite
67
+ // tables with the columns each storage expects — mirror their columns for
68
+ // Postgres/MySQL. The audit table's columns are: id, table_name, record_id,
69
+ // action, timestamp (epoch ms), user_id, record, previous_record, changes,
70
+ // metadata (the last four hold JSON).
71
+ setAuditStorage(new DrizzleAuditLogStorage({ db, table: sqliteAuditLogTable() }));
72
+ setVersioningStorage(new DrizzleVersioningStorage({ db, table: sqliteVersionHistoryTable() }));
73
+ ```
74
+
75
+ Exports `DrizzleAdapters` (the 22-entry adapter bundle), the `Drizzle*Endpoint` classes, `createDrizzleCrud`, `createDrizzleSchemas`, the `DrizzleAuditLogStorage` / `DrizzleVersioningStorage` durable storages (with their `sqlite*Table` helpers), and the `DrizzleDatabaseConstraint` type.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
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, AdapterBundle } from 'hono-crud/internal';
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
3
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
4
- import { VersioningStorage, VersionHistoryEntry } from 'hono-crud/versioning';
5
4
  import { z } from 'zod';
6
5
 
7
6
  /**
@@ -150,6 +149,10 @@ type DrizzleEnv<DB = DrizzleDatabaseConstraint> = {
150
149
  };
151
150
  /**
152
151
  * Gets the Drizzle table from the model.
152
+ *
153
+ * Every call site is a per-request endpoint method, so a missing `table` is
154
+ * request-time misconfiguration — per the error-split doctrine it surfaces as
155
+ * a 500 CONFIGURATION_ERROR envelope, not an unmapped plain Error.
153
156
  */
154
157
  declare function getTable<M extends MetaInput>(meta: M): DrizzleTable;
155
158
  /**
@@ -1182,6 +1185,283 @@ declare function sqliteVersionHistoryTable(name?: string): drizzle_orm_sqlite_co
1182
1185
  dialect: "sqlite";
1183
1186
  }>;
1184
1187
 
1188
+ interface DrizzleAuditLogStorageOptions {
1189
+ /** Any Drizzle database handle (D1/libsql/postgres-js/…). */
1190
+ db: DrizzleDatabaseConstraint;
1191
+ /**
1192
+ * The audit table. Must have the property names of {@link AuditLogRow}
1193
+ * (`id`, `tableName`, `recordId`, `action`, `timestamp`, `userId`, `record`,
1194
+ * `previousRecord`, `changes`, `metadata`). Use {@link sqliteAuditLogTable}
1195
+ * for D1/SQLite, or define your own for another dialect.
1196
+ */
1197
+ table: DrizzleTable;
1198
+ }
1199
+ /**
1200
+ * Durable {@link AuditLogStorage} backed by Drizzle — the persistent
1201
+ * counterpart to the in-memory `MemoryAuditLogStorage`, suitable for
1202
+ * Cloudflare D1 and any other Drizzle-supported database. Audit entries survive
1203
+ * across isolates/requests (unlike the memory store, which is per-isolate).
1204
+ *
1205
+ * @remarks
1206
+ * JSON payloads (`record`, `previousRecord`, `changes`, `metadata`) are
1207
+ * persisted with `JSON.stringify` and rehydrated with `JSON.parse`, so non-JSON
1208
+ * values inside them are stored in their JSON form (e.g. a nested `Date` comes
1209
+ * back as an ISO string) — an encrypted `{ ct, iv, v }` envelope round-trips
1210
+ * untouched. The entry's own `timestamp` is stored as epoch milliseconds and
1211
+ * rehydrated to a `Date`. `recordId` is persisted as text (`String(recordId)`),
1212
+ * so a numeric `recordId` reads back as a string — mirroring
1213
+ * `DrizzleVersioningStorage`.
1214
+ *
1215
+ * Semantics track `MemoryAuditLogStorage` exactly: `getAll` combines every
1216
+ * filter with AND; the date range is inclusive on both ends (`>= startDate`,
1217
+ * `<= endDate`); results are returned oldest-first; `limit`/`offset` slice the
1218
+ * result, and a falsy `limit` (0 or absent) means "all remaining". The one
1219
+ * documented divergence: memory returns strict insertion order, while this
1220
+ * store orders by `timestamp` ascending with a secondary `id` ascending
1221
+ * tiebreaker — identical to memory whenever timestamps are distinct (the common
1222
+ * case, since entries are stamped at write time). For same-millisecond ties the
1223
+ * two diverge: memory yields insertion order, this store yields timestamp-then-id
1224
+ * (deterministic, not necessarily insertion order). The `id` tiebreaker is what
1225
+ * makes it deterministic at all — SQLite would otherwise break ties by rowid but
1226
+ * Postgres tie order is unspecified, so without a unique secondary key, LIMIT/
1227
+ * OFFSET pagination across a same-millisecond batch could duplicate or skip rows
1228
+ * between pages.
1229
+ *
1230
+ * @example
1231
+ * ```ts
1232
+ * import { DrizzleAuditLogStorage, sqliteAuditLogTable } from '@hono-crud/drizzle';
1233
+ * import { setAuditStorage } from 'hono-crud/audit';
1234
+ *
1235
+ * const auditLogs = sqliteAuditLogTable();
1236
+ * const db = drizzle(env.DB);
1237
+ * setAuditStorage(new DrizzleAuditLogStorage({ db, table: auditLogs }));
1238
+ * ```
1239
+ */
1240
+ declare class DrizzleAuditLogStorage implements AuditLogStorage {
1241
+ private readonly db;
1242
+ private readonly table;
1243
+ constructor(options: DrizzleAuditLogStorageOptions);
1244
+ private col;
1245
+ private toEntry;
1246
+ store(entry: AuditLogEntry): Promise<void>;
1247
+ getByRecordId(tableName: string, recordId: string | number, options?: {
1248
+ limit?: number;
1249
+ offset?: number;
1250
+ }): Promise<AuditLogEntry[]>;
1251
+ getAll(options?: {
1252
+ tableName?: string;
1253
+ action?: AuditAction;
1254
+ userId?: string;
1255
+ startDate?: Date;
1256
+ endDate?: Date;
1257
+ limit?: number;
1258
+ offset?: number;
1259
+ }): Promise<AuditLogEntry[]>;
1260
+ }
1261
+ /**
1262
+ * Build a SQLite/D1 audit table with the columns {@link DrizzleAuditLogStorage}
1263
+ * expects. `tableName`/`recordId`/`timestamp` back the per-record lookups and
1264
+ * the `getAll` filters the storage performs.
1265
+ *
1266
+ * @param name - Table name. Default `audit_logs` (matches `AuditConfig`'s
1267
+ * default `tableName`).
1268
+ */
1269
+ declare function sqliteAuditLogTable(name?: string): drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
1270
+ name: string;
1271
+ schema: undefined;
1272
+ columns: {
1273
+ id: drizzle_orm_sqlite_core.SQLiteColumn<{
1274
+ name: "id";
1275
+ tableName: string;
1276
+ dataType: "string";
1277
+ columnType: "SQLiteText";
1278
+ data: string;
1279
+ driverParam: string;
1280
+ notNull: true;
1281
+ hasDefault: false;
1282
+ isPrimaryKey: true;
1283
+ isAutoincrement: false;
1284
+ hasRuntimeDefault: false;
1285
+ enumValues: [string, ...string[]];
1286
+ baseColumn: never;
1287
+ identity: undefined;
1288
+ generated: undefined;
1289
+ }, {}, {
1290
+ length: number | undefined;
1291
+ }>;
1292
+ tableName: drizzle_orm_sqlite_core.SQLiteColumn<{
1293
+ name: "table_name";
1294
+ tableName: string;
1295
+ dataType: "string";
1296
+ columnType: "SQLiteText";
1297
+ data: string;
1298
+ driverParam: string;
1299
+ notNull: true;
1300
+ hasDefault: false;
1301
+ isPrimaryKey: false;
1302
+ isAutoincrement: false;
1303
+ hasRuntimeDefault: false;
1304
+ enumValues: [string, ...string[]];
1305
+ baseColumn: never;
1306
+ identity: undefined;
1307
+ generated: undefined;
1308
+ }, {}, {
1309
+ length: number | undefined;
1310
+ }>;
1311
+ recordId: drizzle_orm_sqlite_core.SQLiteColumn<{
1312
+ name: "record_id";
1313
+ tableName: string;
1314
+ dataType: "string";
1315
+ columnType: "SQLiteText";
1316
+ data: string;
1317
+ driverParam: string;
1318
+ notNull: true;
1319
+ hasDefault: false;
1320
+ isPrimaryKey: false;
1321
+ isAutoincrement: false;
1322
+ hasRuntimeDefault: false;
1323
+ enumValues: [string, ...string[]];
1324
+ baseColumn: never;
1325
+ identity: undefined;
1326
+ generated: undefined;
1327
+ }, {}, {
1328
+ length: number | undefined;
1329
+ }>;
1330
+ action: drizzle_orm_sqlite_core.SQLiteColumn<{
1331
+ name: "action";
1332
+ tableName: string;
1333
+ dataType: "string";
1334
+ columnType: "SQLiteText";
1335
+ data: string;
1336
+ driverParam: string;
1337
+ notNull: true;
1338
+ hasDefault: false;
1339
+ isPrimaryKey: false;
1340
+ isAutoincrement: false;
1341
+ hasRuntimeDefault: false;
1342
+ enumValues: [string, ...string[]];
1343
+ baseColumn: never;
1344
+ identity: undefined;
1345
+ generated: undefined;
1346
+ }, {}, {
1347
+ length: number | undefined;
1348
+ }>;
1349
+ timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{
1350
+ name: "timestamp";
1351
+ tableName: string;
1352
+ dataType: "number";
1353
+ columnType: "SQLiteInteger";
1354
+ data: number;
1355
+ driverParam: number;
1356
+ notNull: true;
1357
+ hasDefault: false;
1358
+ isPrimaryKey: false;
1359
+ isAutoincrement: false;
1360
+ hasRuntimeDefault: false;
1361
+ enumValues: undefined;
1362
+ baseColumn: never;
1363
+ identity: undefined;
1364
+ generated: undefined;
1365
+ }, {}, {}>;
1366
+ userId: drizzle_orm_sqlite_core.SQLiteColumn<{
1367
+ name: "user_id";
1368
+ tableName: string;
1369
+ dataType: "string";
1370
+ columnType: "SQLiteText";
1371
+ data: string;
1372
+ driverParam: string;
1373
+ notNull: false;
1374
+ hasDefault: false;
1375
+ isPrimaryKey: false;
1376
+ isAutoincrement: false;
1377
+ hasRuntimeDefault: false;
1378
+ enumValues: [string, ...string[]];
1379
+ baseColumn: never;
1380
+ identity: undefined;
1381
+ generated: undefined;
1382
+ }, {}, {
1383
+ length: number | undefined;
1384
+ }>;
1385
+ record: drizzle_orm_sqlite_core.SQLiteColumn<{
1386
+ name: "record";
1387
+ tableName: string;
1388
+ dataType: "string";
1389
+ columnType: "SQLiteText";
1390
+ data: string;
1391
+ driverParam: string;
1392
+ notNull: false;
1393
+ hasDefault: false;
1394
+ isPrimaryKey: false;
1395
+ isAutoincrement: false;
1396
+ hasRuntimeDefault: false;
1397
+ enumValues: [string, ...string[]];
1398
+ baseColumn: never;
1399
+ identity: undefined;
1400
+ generated: undefined;
1401
+ }, {}, {
1402
+ length: number | undefined;
1403
+ }>;
1404
+ previousRecord: drizzle_orm_sqlite_core.SQLiteColumn<{
1405
+ name: "previous_record";
1406
+ tableName: string;
1407
+ dataType: "string";
1408
+ columnType: "SQLiteText";
1409
+ data: string;
1410
+ driverParam: string;
1411
+ notNull: false;
1412
+ hasDefault: false;
1413
+ isPrimaryKey: false;
1414
+ isAutoincrement: false;
1415
+ hasRuntimeDefault: false;
1416
+ enumValues: [string, ...string[]];
1417
+ baseColumn: never;
1418
+ identity: undefined;
1419
+ generated: undefined;
1420
+ }, {}, {
1421
+ length: number | undefined;
1422
+ }>;
1423
+ changes: drizzle_orm_sqlite_core.SQLiteColumn<{
1424
+ name: "changes";
1425
+ tableName: string;
1426
+ dataType: "string";
1427
+ columnType: "SQLiteText";
1428
+ data: string;
1429
+ driverParam: string;
1430
+ notNull: false;
1431
+ hasDefault: false;
1432
+ isPrimaryKey: false;
1433
+ isAutoincrement: false;
1434
+ hasRuntimeDefault: false;
1435
+ enumValues: [string, ...string[]];
1436
+ baseColumn: never;
1437
+ identity: undefined;
1438
+ generated: undefined;
1439
+ }, {}, {
1440
+ length: number | undefined;
1441
+ }>;
1442
+ metadata: drizzle_orm_sqlite_core.SQLiteColumn<{
1443
+ name: "metadata";
1444
+ tableName: string;
1445
+ dataType: "string";
1446
+ columnType: "SQLiteText";
1447
+ data: string;
1448
+ driverParam: string;
1449
+ notNull: false;
1450
+ hasDefault: false;
1451
+ isPrimaryKey: false;
1452
+ isAutoincrement: false;
1453
+ hasRuntimeDefault: false;
1454
+ enumValues: [string, ...string[]];
1455
+ baseColumn: never;
1456
+ identity: undefined;
1457
+ generated: undefined;
1458
+ }, {}, {
1459
+ length: number | undefined;
1460
+ }>;
1461
+ };
1462
+ dialect: "sqlite";
1463
+ }>;
1464
+
1185
1465
  /**
1186
1466
  * Drizzle-Zod schema utilities.
1187
1467
  *
@@ -1349,4 +1629,4 @@ declare function isDrizzleZodAvailable(): boolean;
1349
1629
  */
1350
1630
  declare const DrizzleAdapters: AdapterBundle;
1351
1631
 
1352
- export { type CountRow, type CreateDrizzleCrudOptions, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, 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, sqliteVersionHistoryTable, substringMatch };
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 };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt,gte,gt,ne,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,ConfigurationException,decodeCursor}from'hono-crud/internal';import {sqliteTable,text,integer}from'drizzle-orm/sqlite-core';import {z}from'zod';function g(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:
1
+ import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt,gte,gt,ne,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,text,integer}from'drizzle-orm/sqlite-core';import {z}from'zod';function m(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 W(o){return o}function H(o,e){return g(o).transaction(async t=>{o._tx=t;try{return await e()}finally{o._tx=void 0;}})}function m(...o){return and(...o)}function ee(...o){return or(...o)}function R(o,e,t){e.enabled&&o.push(isNull(t(e.field)));}var Ye=["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 De(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 Ge(o,e,t,n){let r=n.table;if(!r)return e;let i=De(o),s=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:s}}async function fe(o,e,t,n){return loadRelationsForItem(e,t,De(o),n)}async function k(o,e,t,n){return batchLoadRelations(e,t,De(o),n)}function J(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 B(o){return Number(o[0]?.count)||0}async function X(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 S=J(t,f,r);S&&u.push(S);}if(n.options.search&&i.length>0){let f=n.options.search,S=i.map(Pe=>P(p(t,Pe),f,r));u.push(ee(...S));}u.push(...l);let d=u.length>0?m(...u):void 0,h=await e.select({count:sql`count(*)`}).from(t).where(d),M=B(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=m(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),S=n.options.order_by_direction==="desc"?desc:asc;y=y.orderBy(S(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,v=n.options.per_page||a;return {records:await y.limit(v).offset((E-1)*v),totalCount:M,page:E,perPage:v}}async function te(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(m(...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 I=class extends CreateEndpoint{db;useTransaction=false;getDb(){return g(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?H(this,()=>super.handle()):super.handle()}},_=class extends ReadEndpoint{db;getDb(){return g(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(m(...a)).limit(1);return l[0]?await fe(this.getDb(),l[0],this._meta,n):null}},A=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return g(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(m(...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(m(...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(m(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(m(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(m(eq(u,d),eq(c,e))).returning())[0]&&l.disconnected.push(d);return l}async handle(){return this.useTransaction?H(this,()=>super.handle()):super.handle()}},q=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return g(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(m(...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(m(...l)).returning())[0]||null:(await r.delete(i).where(m(...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 B(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?H(this,()=>super.handle()):super.handle()}},F=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await X({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 g(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(m(...l)).returning())[0]||null}async handle(){return this.useTransaction?H(this,()=>super.handle()):super.handle()}};var Z=class extends BatchCreateEndpoint{db;getDb(){return g(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()}},L=class extends BatchUpdateEndpoint{db;getDb(){return g(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(m(...c)).returning();u[0]?i.push(u[0]):s.push(l.id);}return {updated:i,notFound:s}}},N=class extends BatchDeleteEndpoint{db;getDb(){return g(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(m(...i)).returning():a=await this.getDb().delete(t).where(m(...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}}},V=class extends BatchRestoreEndpoint{db;getDb(){return g(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(m(...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 jt(o){return o.split(/\s+/).filter(e=>e.length>0)}var K=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return te(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}}},$=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return te(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}}},re=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return g(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=J(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(m(...t));return B(n)}async applyPatch(e,t){let n=this.buildConditions(t),r=await this.getDb().update(this.getTable()).set(this.applyManagedUpdateFields(e)).where(m(...n)).returning();return {updated:r.length,records:r}}};async function pe(o,e,t,n,r){let i=r?m(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 B(s)>0}var oe=class extends VersionHistoryEndpoint{db;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return pe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ie=class extends VersionReadEndpoint{db;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return pe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},se=class extends VersionCompareEndpoint{db;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return pe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ae=class extends VersionRollbackEndpoint{db;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return pe(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]}},le=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return g(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=J(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?m(...n):void 0,s=await this.getDb().select().from(t).where(i);return computeAggregations(s,e)}},Q=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return g(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 v=this.getColumn(y);return P(sql`CAST(${v} AS TEXT)`,E,this.dialect)}catch{return}};if(e.mode==="all"){let y=jt(e.query);if(y.length>0){let E=[];for(let v of y){let ze=s.map(f=>w(f,v)).filter(f=>f!==void 0);ze.length>0&&E.push(ee(...ze));}E.length>0&&r.push(m(...E));}}else {let y=s.map(E=>w(E,e.query)).filter(E=>E!==void 0);y.length>0&&r.push(ee(...y));}}let a=await X({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}}},de=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await X({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})}}},ce=class extends ImportEndpoint{db;getDb(){return g(this)}getTable(){return b(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return te(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]}},ue=class extends CloneEndpoint{db;getDb(){return g(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(m(...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 In(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends I{_meta=e;db=o},Read:class extends _{_meta=e;db=o},Update:class extends A{_meta=e;db=o},Delete:class extends q{_meta=e;db=o},List:class extends F{_meta=e;db=o;dialect=n},Restore:class extends U{_meta=e;db=o},Upsert:class extends K{_meta=e;db=o;dialect=n},Search:class extends Q{_meta=e;db=o;dialect=n},BatchCreate:class extends Z{_meta=e;db=o},BatchUpdate:class extends L{_meta=e;db=o},BatchDelete:class extends N{_meta=e;db=o},BatchRestore:class extends V{_meta=e;db=o},BatchUpsert:class extends ${_meta=e;db=o;dialect=n}}}var ke=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 Gn(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 me=null,Be=false,ge=null;async function be(){if(Be){if(ge)throw ge;return me}Be=true;try{return me=await import('drizzle-zod'),me}catch{throw ge=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ge}}async function _t(o,e){return (await be()).createSelectSchema(o,e)}async function At(o,e){return (await be()).createInsertSchema(o,e)}async function qt(o,e){let t=await be();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Ft(o,e){let t=await be(),n=e?.coerceDates!==false,r=n?Nt(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=je(s,r),a=je(a,r)),{select:i,insert:s,update:a}}function Ut(){return me!==null}var Zt=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()),Lt=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 Nt(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 je(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=Zt;(a||s)&&(l=Lt),s&&(l=l.optional()),n[r]=l;}else n[r]=i;return z.object(n)}var sr={CreateEndpoint:I,ListEndpoint:F,ReadEndpoint:_,UpdateEndpoint:A,DeleteEndpoint:q,RestoreEndpoint:U,BatchCreateEndpoint:Z,BatchUpdateEndpoint:L,BatchDeleteEndpoint:N,BatchRestoreEndpoint:V,BatchUpsertEndpoint:$,SearchEndpoint:Q,AggregateEndpoint:le,ExportEndpoint:de,ImportEndpoint:ce,UpsertEndpoint:K,CloneEndpoint:ue,BulkPatchEndpoint:re,VersionHistoryEndpoint:oe,VersionReadEndpoint:ie,VersionCompareEndpoint:se,VersionRollbackEndpoint:ae};export{Ye as DRIZZLE_DIALECTS,sr as DrizzleAdapters,le as DrizzleAggregateEndpoint,Z as DrizzleBatchCreateEndpoint,N as DrizzleBatchDeleteEndpoint,V as DrizzleBatchRestoreEndpoint,L as DrizzleBatchUpdateEndpoint,$ as DrizzleBatchUpsertEndpoint,re as DrizzleBulkPatchEndpoint,ue as DrizzleCloneEndpoint,I as DrizzleCreateEndpoint,q as DrizzleDeleteEndpoint,de as DrizzleExportEndpoint,ce as DrizzleImportEndpoint,F as DrizzleListEndpoint,_ as DrizzleReadEndpoint,U as DrizzleRestoreEndpoint,Q as DrizzleSearchEndpoint,A as DrizzleUpdateEndpoint,K as DrizzleUpsertEndpoint,se as DrizzleVersionCompareEndpoint,oe as DrizzleVersionHistoryEndpoint,ie as DrizzleVersionReadEndpoint,ae as DrizzleVersionRollbackEndpoint,ke as DrizzleVersioningStorage,k as batchLoadDrizzleRelations,J as buildWhereCondition,W as cast,In as createDrizzleCrud,Ft as createDrizzleSchemas,At as createInsertSchema,_t as createSelectSchema,qt as createUpdateSchema,p as getColumn,b as getTable,Ut as isDrizzleZodAvailable,Ge as loadDrizzleRelation,fe as loadDrizzleRelations,B as readCount,Gn as sqliteVersionHistoryTable,P as substringMatch};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hono-crud/drizzle",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
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.26"
50
+ "hono-crud": "^0.13.28"
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.26"
59
+ "hono-crud": "0.13.28"
60
60
  },
61
61
  "peerDependenciesMeta": {
62
62
  "drizzle-zod": {