@hono-crud/drizzle 0.1.10 → 0.1.11

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,26 @@
1
1
  # @hono-crud/drizzle
2
2
 
3
+ ## 0.1.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 66f789c: Naming + docs sweep (breaking, patch): one name per role across the whole library, and the docs now document the code that exists.
8
+
9
+ - Middleware factories: `idempotency()` → `createIdempotencyMiddleware()`. (`multiTenant()`/`apiVersion()` keep their feature-named forms — each anchors an accessor family sharing its prefix; the doctrine in CLAUDE.md documents the rule and the exceptions.)
10
+ - Surface packages are Hono-idiomatic factories you mount yourself: swagger's `setupSwaggerUI`/`setupReDoc`/`setupDocsIndex` (app mutators) become `swaggerUI()`/`redocUI()`/`docsIndex()` returning `MiddlewareHandler` with `SwaggerUIConfig`/`RedocUIConfig`/`DocsIndexConfig` (adopting scalar's `specUrl`/`pageTitle` vocabulary; `UIOptions` deleted); scalar's `setupScalar` is deleted (`app.get(path, scalarUI(config))`); health's `createHealthEndpoints`/`createHealthHandler` collapse into `createHealthRoutes(config): Hono` mounted via `app.route()`.
11
+ - The word "Versioning" now means record history only: HTTP negotiation renames to `ApiVersioningConfig` (was `VersioningMiddlewareConfig`), `ApiVersionStrategy`, `ApiVersionTransformer`, `apiVersionedResponse()`.
12
+ - Multi-tenant has one source-of-truth union: new exported `TenantIdSource` owned by the model-level `MultiTenantConfig`; the middleware config derives from it and renames to `MultiTenantMiddlewareConfig` (was `*Options`). Runtime defaults unchanged.
13
+ - `CrudMcpOptions` → `CrudMcpConfig` per the now-documented Config-vs-Options rule.
14
+ - Rate-limit key prefix unified: one exported `DEFAULT_RATE_LIMIT_KEY_PREFIX = 'rl'`; the KV and Redis storage prefixes no longer add their own divergent defaults ('rl:'/'ratelimit:'), so all backends build identical keys. In-flight rate-limit windows under old prefixes expire naturally.
15
+ - Vestigial `RouterOptions.base`/`docs_url`/`redoc_url` deleted (UI paths live in the swagger/scalar packages; `openapi_url` stays).
16
+ - One API-key hasher: the canonical `hashAPIKey` moves to `auth/hash.ts` and `defaultHashAPIKey` is now an alias of it — hashing is byte-identical, stored keys keep matching.
17
+ - Sorting aliases removed from the functional config: `orderByFields`/`defaultOrderBy`/`defaultOrderDirection` and `SortingConfig.defaultDirection` are gone — canonical `sortFields`/`defaultSort`/`defaultOrder` only.
18
+ - Drizzle's stale 5-verb `DrizzleAdapters` bundle in factory.ts is deleted; the 17-entry bundle in the package barrel is the only one, mirroring prisma and memory.
19
+ - Docs: CLAUDE.md/AGENTS.md gain the naming doctrine and a corrected Drizzle Adapter Pattern section using the real type names (`DrizzleDatabaseConstraint`, `Database<Row>`, `QueryBuilder<Row>`, `cast<Row>()`); all docs/READMEs/examples migrated to the new names and call patterns.
20
+
21
+ - Updated dependencies [66f789c]
22
+ - hono-crud@0.13.13
23
+
3
24
  ## 0.1.10
4
25
 
5
26
  ### Patch Changes
package/README.md CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  DrizzleCreateEndpoint,
17
17
  DrizzleReadEndpoint,
18
18
  DrizzleListEndpoint,
19
- type DrizzleDatabase,
19
+ type DrizzleDatabaseConstraint,
20
20
  } from '@hono-crud/drizzle';
21
21
 
22
22
  const app = fromHono(new Hono());
@@ -27,4 +27,4 @@ registerCrud(app, '/users', {
27
27
  });
28
28
  ```
29
29
 
30
- Exports `DrizzleAdapters`, the `Drizzle*Endpoint` classes, `createDrizzleCrud`, `createDrizzleSchemas`, and the `DrizzleDatabase` type.
30
+ Exports `DrizzleAdapters` (the 17-entry adapter bundle), the `Drizzle*Endpoint` classes, `createDrizzleCrud`, `createDrizzleSchemas`, and the `DrizzleDatabaseConstraint` type.
package/dist/index.d.ts CHANGED
@@ -123,7 +123,7 @@ type DrizzleDialect = (typeof DRIZZLE_DIALECTS)[number];
123
123
  *
124
124
  * @example
125
125
  * ```ts
126
- * import { DrizzleEnv } from 'hono-crud/adapters/drizzle';
126
+ * import { DrizzleEnv } from '@hono-crud/drizzle';
127
127
  *
128
128
  * type AppEnv = DrizzleEnv<typeof db>;
129
129
  *
@@ -847,7 +847,7 @@ interface CreateDrizzleCrudOptions {
847
847
  *
848
848
  * @example
849
849
  * ```ts
850
- * import { createDrizzleCrud } from 'hono-crud/adapters/drizzle';
850
+ * import { createDrizzleCrud } from '@hono-crud/drizzle';
851
851
  *
852
852
  * const projectMeta = defineMeta({ model: ProjectModel, fields: projectSchemas.insert });
853
853
  * const Project = createDrizzleCrud(db, projectMeta, { dialect: 'pg' });
@@ -878,7 +878,7 @@ declare function createDrizzleCrud<M extends MetaInput, E extends Env = Env>(db:
878
878
  * @example
879
879
  * ```ts
880
880
  * import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
881
- * import { createDrizzleSchemas } from 'hono-crud/adapters/drizzle';
881
+ * import { createDrizzleSchemas } from '@hono-crud/drizzle';
882
882
  *
883
883
  * const users = pgTable('users', {
884
884
  * id: uuid('id').primaryKey().defaultRandom(),
@@ -902,7 +902,7 @@ declare function createDrizzleCrud<M extends MetaInput, E extends Env = Env>(db:
902
902
  * @example
903
903
  * ```ts
904
904
  * import { users } from './schema';
905
- * import { createSelectSchema } from 'hono-crud/adapters/drizzle';
905
+ * import { createSelectSchema } from '@hono-crud/drizzle';
906
906
  *
907
907
  * const UserSchema = await createSelectSchema(users);
908
908
  * type User = z.infer<typeof UserSchema>;
@@ -920,7 +920,7 @@ declare function createSelectSchema<T extends DrizzleTable>(table: T, refine?: R
920
920
  * @example
921
921
  * ```ts
922
922
  * import { users } from './schema';
923
- * import { createInsertSchema } from 'hono-crud/adapters/drizzle';
923
+ * import { createInsertSchema } from '@hono-crud/drizzle';
924
924
  *
925
925
  * const CreateUserSchema = await createInsertSchema(users);
926
926
  * type CreateUser = z.infer<typeof CreateUserSchema>;
@@ -941,7 +941,7 @@ declare function createInsertSchema<T extends DrizzleTable>(table: T, refine?: R
941
941
  * @example
942
942
  * ```ts
943
943
  * import { users } from './schema';
944
- * import { createUpdateSchema } from 'hono-crud/adapters/drizzle';
944
+ * import { createUpdateSchema } from '@hono-crud/drizzle';
945
945
  *
946
946
  * const UpdateUserSchema = await createUpdateSchema(users);
947
947
  * type UpdateUser = z.infer<typeof UpdateUserSchema>;
@@ -981,7 +981,7 @@ interface DrizzleSchemas {
981
981
  * @example
982
982
  * ```ts
983
983
  * import { pgTable, text, uuid } from 'drizzle-orm/pg-core';
984
- * import { createDrizzleSchemas, defineModel, defineMeta } from 'hono-crud/adapters/drizzle';
984
+ * import { createDrizzleSchemas, defineModel, defineMeta } from '@hono-crud/drizzle';
985
985
  * import { z } from 'zod';
986
986
  *
987
987
  * const users = pgTable('users', {
@@ -1023,7 +1023,7 @@ declare function isDrizzleZodAvailable(): boolean;
1023
1023
  /**
1024
1024
  * Drizzle adapter bundle for use with `defineEndpoints`.
1025
1025
  *
1026
- * Populates the 11 verbs Drizzle implements natively plus a stub
1026
+ * Populates the 16 verbs Drizzle implements natively plus a stub
1027
1027
  * `CloneEndpoint` (throws on request — subclass to implement).
1028
1028
  *
1029
1029
  * @example
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import {getTableColumns,between,isNull,isNotNull,ilike,like,notInArray,inArray,lte,lt,gte,gt,ne as ne$1,eq,sql,desc,asc,and,or}from'drizzle-orm';import {resolveRelationValueAsync,loadRelationsForItem,batchLoadRelations,assertNever,UpsertEndpoint,BatchUpsertEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,isFilterOperator,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint,CONTEXT_KEYS}from'hono-crud/internal';import {z}from'zod';function X(o){return o}function m(...o){return and(...o)}function S(...o){return or(...o)}var Ke=["sqlite","pg","mysql"];function h(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 ae(o){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n)=>o.select().from(e).where(inArray(p(e,t),n))}}async function $e(o,e,t,n){let r=n.table;if(!r)return e;let i=ae(o),a=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:a}}async function le(o,e,t,n){return loadRelationsForItem(e,t,ae(o),n)}async function B(o,e,t,n){return batchLoadRelations(e,t,ae(o),n)}function k(o,e){let t=p(o,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[n,r]=e.value;return between(t,n,r)}default:return assertNever(e.operator)}}function O(o){return Number(o[0]?.count)||0}function f(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 Error(`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 ee(o,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${o})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${o})) > 0`;default:return sql`INSTR(LOWER(${o}), LOWER(${e})) > 0`}}function at(o){return o.split(/\s+/).filter(e=>e.length>0)}var j=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=this.getSoftDeleteConfig(),i=[];for(let s of n){let l=e[s];l!==void 0&&i.push(eq(this.getColumn(s),l));}return r.enabled&&i.push(isNull(this.getColumn(r.field))),i.length===0?null:(await this.getDb().select().from(t).where(m(...i)).limit(1))[0]||null}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],a=this.getSoftDeleteConfig(),s=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[g,C]of Object.entries(e))!r.includes(g)&&g!==i&&(this.createOnlyFields?.includes(g)||(d[g]=C));s.enabled&&(d[s.updatedAt]=Date.now());let u=r.map(g=>this.getColumn(g)),c;a.enabled&&(c=isNull(this.getColumn(a.field)));let b=Object.keys(d).length>0?d:{[i]:sql`${this.getColumn(i)}`},M=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await M.onDuplicateKeyUpdate({set:b}).returning())[0],created:false}:{data:(await M.onConflictDoUpdate({target:u,set:b,where:c}).returning())[0],created:false}}},_=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=[];for(let a of n){let s=e[a];s!==void 0&&r.push(eq(this.getColumn(a),s));}return r.length===0?null:(await this.getDb().select().from(t).where(m(...r)).limit(1))[0]||null}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],a=this.getTimestampsConfig(),s=e.map(z=>this.applyManagedInsertFields(z,"drizzle")),l={},d=e[0];for(let z of Object.keys(d))!r.includes(z)&&z!==i&&(this.createOnlyFields?.includes(z)||(l[z]=sql`excluded.${sql.identifier(z)}`));a.enabled&&(l[a.updatedAt]=Date.now());let u=r.map(z=>this.getColumn(z)),c=Object.keys(l).length>0?l:{[i]:sql`${this.getColumn(i)}`},b=this.getDb().insert(n).values(s),M=await(this.dialect==="mysql"?b.onDuplicateKeyUpdate({set:c}):b.onConflictDoUpdate({target:u,set:c})).returning();return {items:M.map((z,g)=>({data:z,created:false,index:g})),createdCount:0,updatedCount:M.length,totalCount:M.length}}},ue=class extends VersionHistoryEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e){let t=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return O(n)>0}},pe=class extends VersionReadEndpoint{},ge=class extends VersionCompareEndpoint{},me=class extends VersionRollbackEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}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]}},Y=class extends AggregateEndpoint{db;getDb(){return f(this)}getTable(){return h(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:s}=await this.getValidatedData();s?.withDeleted===true||s?.withDeleted==="true"||n.push(isNull(this.getColumn(r.field)));}if(e.filters)for(let[s,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){if(!isFilterOperator(d)){n.push(sql`1 = 0`);continue}let c=k(t,{field:s,operator:d,value:u});c&&n.push(c);}else n.push(eq(this.getColumn(s),l));let i=n.length>0?m(...n):void 0,a=await this.getDb().select().from(t).where(i);return computeAggregations(a,e)}},I=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return f(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async search(e,t){let n=this.getTable(),r=[],i=this.getSoftDeleteConfig();i.enabled&&(t.options.onlyDeleted?r.push(isNotNull(this.getColumn(i.field))):t.options.withDeleted||r.push(isNull(this.getColumn(i.field))));for(let E of t.filters){let y=k(n,E);y&&r.push(y);}let a=this.getSearchableFields(),s=e.fields||Object.keys(a);if(this.useNativeSearch&&this.vectorColumn){let E=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`${E} @@ ${y}`);}else {let E=(y,x)=>{try{let se=this.getColumn(y);return ee(sql`CAST(${se} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let y=at(e.query);if(y.length>0){let x=[];for(let se of y){let de=s.map(ie=>E(ie,se)).filter(ie=>ie!==void 0);de.length>0&&x.push(S(...de));}x.length>0&&r.push(m(...x));}}else {let y=s.map(x=>E(x,e.query)).filter(x=>x!==void 0);y.length>0&&r.push(S(...y));}}let l=r.length>0?m(...r):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(n).where(l),u=O(d),c=this.getDb().select().from(n).where(l);if(t.options.order_by){let E=this.getColumn(t.options.order_by),y=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(y(E));}let b=t.options.page||1,M=t.options.per_page||this.defaultPerPage;c=c.limit(M).offset((b-1)*M);let z=await c,g=e.mode==="all"?{...e,mode:"any"}:e,C=searchInMemory(z,g,a),R={relations:t.options.include||[]},W=C.map(E=>E.item),oe=await B(this.getDb(),W,this._meta,R);return {items:C.map((E,y)=>({...E,item:oe[y]})),totalCount:u}}},G=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let g=this.getColumn(r.field);e.options.onlyDeleted?n.push(isNotNull(g)):e.options.withDeleted||n.push(isNull(g));}for(let g of e.filters){let C=k(t,g);C&&n.push(C);}if(e.options.search&&this.searchFields.length>0){let g=e.options.search,C=this.searchFields.map(R=>{let W=this.getColumn(R);return ee(W,g,this.dialect)});n.push(S(...C));}let i=n.length>0?m(...n):void 0,a=await this.getDb().select({count:sql`count(*)`}).from(t).where(i),s=O(a),l=this.getDb().select().from(t).where(i);if(e.options.order_by){let g=this.getColumn(e.options.order_by),C=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(C(g));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,b={relations:e.options.include||[]},M=await B(this.getDb(),c,this._meta,b),z=Math.ceil(s/u);return {result:M,result_info:{page:d,per_page:u,total_count:s,total_pages:z,has_next_page:d<z,has_prev_page:d>1}}}},H=class extends ImportEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=this.getSoftDeleteConfig(),i=[];for(let s of n){let l=e[s];l!==void 0&&i.push(eq(this.getColumn(s),l));}return r.enabled&&i.push(isNull(this.getColumn(r.field))),i.length===0?null:(await this.getDb().select().from(t).where(m(...i)).limit(1))[0]||null}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]}},J=class extends CloneEndpoint{db;getDb(){return f(this)}getTable(){return h(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(),a=[eq(r,e)];if(t)for(let[l,d]of Object.entries(t))a.push(eq(this.getColumn(l),d));i.enabled&&a.push(isNull(this.getColumn(i.field)));let s=await this.getDb().select().from(n).where(m(...a)).limit(1);return s[0]?s[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]}};var A=class extends CreateEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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 a=i??this.getDb(),s=this.getRelatedTable(n);if(!s)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[n.foreignKey]:e},b=await a.insert(s).values(c).returning();b[0]&&d.push(b[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},q=class extends ReadEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),s=[eq(i,e)];if(t)for(let[u,c]of Object.entries(t))s.push(eq(this.getColumn(u),c));a.enabled&&s.push(isNull(this.getColumn(a.field)));let l=await this.getDb().select().from(r).where(m(...s)).limit(1);return l[0]?await le(this.getDb(),l[0],this._meta,n):null}},U=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return s.enabled&&l.push(isNull(this.getColumn(s.field))),(await r.select().from(i).where(m(...l)).limit(1))[0]||null}async update(e,t,n,r){let i=r??this.getDb(),a=this.getTable(),s=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(s,e)];if(n)for(let[c,b]of Object.entries(n))d.push(eq(this.getColumn(c),b));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await i.update(a).set(this.applyManagedUpdateFields(t)).where(m(...d)).returning())[0]||null}async processNestedWrites(e,t,n,r,i){let a=i??this.getDb(),s=this.getRelatedTable(n);if(!s)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=p(s,n.foreignKey),u=p(s,"id");if(r.create){let c=Array.isArray(r.create)?r.create:[r.create];for(let b of c){if(typeof b!="object"||b===null)continue;let M={...b,id:crypto.randomUUID(),[n.foreignKey]:e},z=await a.insert(s).values(M).returning();z[0]&&l.created.push(z[0]);}}if(r.update)for(let c of r.update){if(!c.id||!(await a.select().from(s).where(m(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:M,...z}=c,g=await a.update(s).set(z).where(eq(u,M)).returning();g[0]&&l.updated.push(g[0]);}if(r.delete)for(let c of r.delete)(await a.delete(s).where(m(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(r.connect)for(let c of r.connect)(await a.update(s).set({[n.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(r.disconnect)for(let c of r.disconnect)(await a.update(s).set({[n.foreignKey]:null}).where(m(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},Z=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return s.enabled&&l.push(isNull(this.getColumn(s.field))),(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return s.enabled&&l.push(isNull(this.getColumn(s.field))),s.enabled?(await r.update(i).set({[s.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(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey),l=await i.select({count:sql`count(*)`}).from(a).where(eq(s,e));return O(l)}async deleteRelated(e,t,n,r){let i=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey);return (await i.delete(a).where(eq(s,e)).returning()).length}async nullifyRelated(e,t,n,r){let i=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey);return (await i.update(a).set({[n.foreignKey]:null}).where(eq(s,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},F=class extends ListEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let C=this.getColumn(r.field);e.options.onlyDeleted?n.push(isNotNull(C)):e.options.withDeleted||n.push(isNull(C));}for(let C of e.filters){let R=k(t,C);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let C=e.options.search,R=this.searchFields.map(W=>{let oe=this.getColumn(W);return ee(oe,C,this.dialect)});n.push(S(...R));}let i=n.length>0?m(...n):void 0,a=this.getDb(),s=await a.select({count:sql`count(*)`}).from(t).where(i),l=O(s),d=a.select().from(t).where(i);if(e.options.order_by){let C=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(C));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let b=await d,M={relations:e.options.include||[]},z=await B(this.getDb(),b,this._meta,M),g=Math.ceil(l/c);return {result:z,result_info:{page:u,per_page:c,total_count:l,total_pages:g,has_next_page:u<g,has_prev_page:u>1}}}},N=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),i=this.getTable(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(s.field))),(await r.update(i).set({[s.field]:null}).where(m(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var L=class extends BatchCreateEndpoint{db;getDb(){return f(this)}getTable(){return h(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()}},K=class extends BatchUpdateEndpoint{db;getDb(){return f(this)}getTable(){return h(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=[],a=[];for(let s of e){let l=[eq(n,s.id)];r.enabled&&l.push(isNull(this.getColumn(r.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(s.data)).where(m(...l)).returning();d[0]?i.push(d[0]):a.push(s.id);}return {updated:i,notFound:a}}},$=class extends BatchDeleteEndpoint{db;getDb(){return f(this)}getTable(){return h(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.enabled&&i.push(isNull(this.getColumn(r.field)));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 s=a,l=new Set(s.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:s,notFound:d}}},Q=class extends BatchRestoreEndpoint{db;getDb(){return f(this)}getTable(){return h(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=await this.getDb().update(t).set({[r.field]:null}).where(m(...i)).returning(),l=new Set(s.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:s,notFound:d}}};function fn(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends A{_meta=e;db=o},Read:class extends q{_meta=e;db=o},Update:class extends U{_meta=e;db=o},Delete:class extends Z{_meta=e;db=o},List:class extends F{_meta=e;db=o;dialect=n},Restore:class extends N{_meta=e;db=o},Upsert:class extends j{_meta=e;db=o;dialect=n},Search:class extends I{_meta=e;db=o;dialect=n},BatchCreate:class extends L{_meta=e;db=o},BatchUpdate:class extends K{_meta=e;db=o},BatchDelete:class extends ${_meta=e;db=o},BatchRestore:class extends Q{_meta=e;db=o},BatchUpsert:class extends _{_meta=e;db=o;dialect=n}}}var ne=null,we=false,te=null;async function re(){if(we){if(te)throw te;return ne}we=true;try{return ne=await import('drizzle-zod'),ne}catch{throw te=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),te}}async function yt(o,e){return (await re()).createSelectSchema(o,e)}async function wt(o,e){return (await re()).createInsertSchema(o,e)}async function Et(o,e){let t=await re();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Tt(o,e){let t=await re(),n=e?.coerceDates!==false,r=n?kt(o):new Set,i=t.createSelectSchema(o,e?.selectRefine),a=t.createInsertSchema(o,e?.insertRefine),s;return t.createUpdateSchema?s=t.createUpdateSchema(o,e?.updateRefine):s=t.createInsertSchema(o,e?.updateRefine).partial(),n&&r.size>0&&(a=Ee(a,r),s=Ee(s,r)),{select:i,insert:a,update:s}}function Rt(){return ne!==null}var xt=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()),Ot=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 kt(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 a=String(i.dataType??"").toLowerCase(),s=String(i.columnType??"").toLowerCase(),l=i.config,d=String(l?.dataType??"").toLowerCase();(a.includes("timestamp")||a.includes("date")||a.includes("datetime")||s.includes("pgtimestamp")||s.includes("pgdate")||s.includes("mysqltimestamp")||s.includes("mysqldate")||s.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(n);}return e}function Ee(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 a=i.isOptional?.()??false,s=i.isNullable?.()??false,l=xt;(s||a)&&(l=Ot),a&&(l=l.optional()),n[r]=l;}else n[r]=i;return z.object(n)}var Un={CreateEndpoint:A,ListEndpoint:F,ReadEndpoint:q,UpdateEndpoint:U,DeleteEndpoint:Z,RestoreEndpoint:N,BatchCreateEndpoint:L,BatchUpdateEndpoint:K,BatchDeleteEndpoint:$,BatchRestoreEndpoint:Q,BatchUpsertEndpoint:_,SearchEndpoint:I,AggregateEndpoint:Y,ExportEndpoint:G,ImportEndpoint:H,UpsertEndpoint:j,CloneEndpoint:J};export{Ke as DRIZZLE_DIALECTS,Un as DrizzleAdapters,Y as DrizzleAggregateEndpoint,L as DrizzleBatchCreateEndpoint,$ as DrizzleBatchDeleteEndpoint,Q as DrizzleBatchRestoreEndpoint,K as DrizzleBatchUpdateEndpoint,_ as DrizzleBatchUpsertEndpoint,J as DrizzleCloneEndpoint,A as DrizzleCreateEndpoint,Z as DrizzleDeleteEndpoint,G as DrizzleExportEndpoint,H as DrizzleImportEndpoint,F as DrizzleListEndpoint,q as DrizzleReadEndpoint,N as DrizzleRestoreEndpoint,I as DrizzleSearchEndpoint,U as DrizzleUpdateEndpoint,j as DrizzleUpsertEndpoint,ge as DrizzleVersionCompareEndpoint,ue as DrizzleVersionHistoryEndpoint,pe as DrizzleVersionReadEndpoint,me as DrizzleVersionRollbackEndpoint,B as batchLoadDrizzleRelations,k as buildWhereCondition,X as cast,fn as createDrizzleCrud,Tt as createDrizzleSchemas,wt as createInsertSchema,yt as createSelectSchema,Et as createUpdateSchema,p as getColumn,h as getTable,Rt as isDrizzleZodAvailable,$e as loadDrizzleRelation,le as loadDrizzleRelations,O as readCount,ee as substringMatch};
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}function ee(o,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${o})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${o})) > 0`;default:return sql`INSTR(LOWER(${o}), LOWER(${e})) > 0`}}function at(o){return o.split(/\s+/).filter(e=>e.length>0)}var j=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=this.getSoftDeleteConfig(),i=[];for(let s of n){let l=e[s];l!==void 0&&i.push(eq(this.getColumn(s),l));}return r.enabled&&i.push(isNull(this.getColumn(r.field))),i.length===0?null:(await this.getDb().select().from(t).where(m(...i)).limit(1))[0]||null}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],a=this.getSoftDeleteConfig(),s=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[g,C]of Object.entries(e))!r.includes(g)&&g!==i&&(this.createOnlyFields?.includes(g)||(d[g]=C));s.enabled&&(d[s.updatedAt]=Date.now());let u=r.map(g=>this.getColumn(g)),c;a.enabled&&(c=isNull(this.getColumn(a.field)));let b=Object.keys(d).length>0?d:{[i]:sql`${this.getColumn(i)}`},M=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await M.onDuplicateKeyUpdate({set:b}).returning())[0],created:false}:{data:(await M.onConflictDoUpdate({target:u,set:b,where:c}).returning())[0],created:false}}},_=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=[];for(let a of n){let s=e[a];s!==void 0&&r.push(eq(this.getColumn(a),s));}return r.length===0?null:(await this.getDb().select().from(t).where(m(...r)).limit(1))[0]||null}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],a=this.getTimestampsConfig(),s=e.map(z=>this.applyManagedInsertFields(z,"drizzle")),l={},d=e[0];for(let z of Object.keys(d))!r.includes(z)&&z!==i&&(this.createOnlyFields?.includes(z)||(l[z]=sql`excluded.${sql.identifier(z)}`));a.enabled&&(l[a.updatedAt]=Date.now());let u=r.map(z=>this.getColumn(z)),c=Object.keys(l).length>0?l:{[i]:sql`${this.getColumn(i)}`},b=this.getDb().insert(n).values(s),M=await(this.dialect==="mysql"?b.onDuplicateKeyUpdate({set:c}):b.onConflictDoUpdate({target:u,set:c})).returning();return {items:M.map((z,g)=>({data:z,created:false,index:g})),createdCount:0,updatedCount:M.length,totalCount:M.length}}},ue=class extends VersionHistoryEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e){let t=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return O(n)>0}},pe=class extends VersionReadEndpoint{},ge=class extends VersionCompareEndpoint{},me=class extends VersionRollbackEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}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]}},Y=class extends AggregateEndpoint{db;getDb(){return f(this)}getTable(){return h(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:s}=await this.getValidatedData();s?.withDeleted===true||s?.withDeleted==="true"||n.push(isNull(this.getColumn(r.field)));}if(e.filters)for(let[s,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){if(!isFilterOperator(d)){n.push(sql`1 = 0`);continue}let c=k(t,{field:s,operator:d,value:u});c&&n.push(c);}else n.push(eq(this.getColumn(s),l));let i=n.length>0?m(...n):void 0,a=await this.getDb().select().from(t).where(i);return computeAggregations(a,e)}},I=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return f(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async search(e,t){let n=this.getTable(),r=[],i=this.getSoftDeleteConfig();i.enabled&&(t.options.onlyDeleted?r.push(isNotNull(this.getColumn(i.field))):t.options.withDeleted||r.push(isNull(this.getColumn(i.field))));for(let E of t.filters){let y=k(n,E);y&&r.push(y);}let a=this.getSearchableFields(),s=e.fields||Object.keys(a);if(this.useNativeSearch&&this.vectorColumn){let E=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`${E} @@ ${y}`);}else {let E=(y,x)=>{try{let se=this.getColumn(y);return ee(sql`CAST(${se} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let y=at(e.query);if(y.length>0){let x=[];for(let se of y){let de=s.map(ie=>E(ie,se)).filter(ie=>ie!==void 0);de.length>0&&x.push(S(...de));}x.length>0&&r.push(m(...x));}}else {let y=s.map(x=>E(x,e.query)).filter(x=>x!==void 0);y.length>0&&r.push(S(...y));}}let l=r.length>0?m(...r):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(n).where(l),u=O(d),c=this.getDb().select().from(n).where(l);if(t.options.order_by){let E=this.getColumn(t.options.order_by),y=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(y(E));}let b=t.options.page||1,M=t.options.per_page||this.defaultPerPage;c=c.limit(M).offset((b-1)*M);let z=await c,g=e.mode==="all"?{...e,mode:"any"}:e,C=searchInMemory(z,g,a),R={relations:t.options.include||[]},W=C.map(E=>E.item),oe=await B(this.getDb(),W,this._meta,R);return {items:C.map((E,y)=>({...E,item:oe[y]})),totalCount:u}}},G=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let g=this.getColumn(r.field);e.options.onlyDeleted?n.push(isNotNull(g)):e.options.withDeleted||n.push(isNull(g));}for(let g of e.filters){let C=k(t,g);C&&n.push(C);}if(e.options.search&&this.searchFields.length>0){let g=e.options.search,C=this.searchFields.map(R=>{let W=this.getColumn(R);return ee(W,g,this.dialect)});n.push(S(...C));}let i=n.length>0?m(...n):void 0,a=await this.getDb().select({count:sql`count(*)`}).from(t).where(i),s=O(a),l=this.getDb().select().from(t).where(i);if(e.options.order_by){let g=this.getColumn(e.options.order_by),C=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(C(g));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,b={relations:e.options.include||[]},M=await B(this.getDb(),c,this._meta,b),z=Math.ceil(s/u);return {result:M,result_info:{page:d,per_page:u,total_count:s,total_pages:z,has_next_page:d<z,has_prev_page:d>1}}}},H=class extends ImportEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async findExisting(e){let t=this.getTable(),n=this.getUpsertKeys(),r=this.getSoftDeleteConfig(),i=[];for(let s of n){let l=e[s];l!==void 0&&i.push(eq(this.getColumn(s),l));}return r.enabled&&i.push(isNull(this.getColumn(r.field))),i.length===0?null:(await this.getDb().select().from(t).where(m(...i)).limit(1))[0]||null}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]}},J=class extends CloneEndpoint{db;getDb(){return f(this)}getTable(){return h(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(),a=[eq(r,e)];if(t)for(let[l,d]of Object.entries(t))a.push(eq(this.getColumn(l),d));i.enabled&&a.push(isNull(this.getColumn(i.field)));let s=await this.getDb().select().from(n).where(m(...a)).limit(1);return s[0]?s[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]}};var q=class extends CreateEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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 a=i??this.getDb(),s=this.getRelatedTable(n);if(!s)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[n.foreignKey]:e},b=await a.insert(s).values(c).returning();b[0]&&d.push(b[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},A=class extends ReadEndpoint{db;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),s=[eq(i,e)];if(t)for(let[u,c]of Object.entries(t))s.push(eq(this.getColumn(u),c));a.enabled&&s.push(isNull(this.getColumn(a.field)));let l=await this.getDb().select().from(r).where(m(...s)).limit(1);return l[0]?await le(this.getDb(),l[0],this._meta,n):null}},U=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return s.enabled&&l.push(isNull(this.getColumn(s.field))),(await r.select().from(i).where(m(...l)).limit(1))[0]||null}async update(e,t,n,r){let i=r??this.getDb(),a=this.getTable(),s=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(s,e)];if(n)for(let[c,b]of Object.entries(n))d.push(eq(this.getColumn(c),b));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await i.update(a).set(this.applyManagedUpdateFields(t)).where(m(...d)).returning())[0]||null}async processNestedWrites(e,t,n,r,i){let a=i??this.getDb(),s=this.getRelatedTable(n);if(!s)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=p(s,n.foreignKey),u=p(s,"id");if(r.create){let c=Array.isArray(r.create)?r.create:[r.create];for(let b of c){if(typeof b!="object"||b===null)continue;let M={...b,id:crypto.randomUUID(),[n.foreignKey]:e},z=await a.insert(s).values(M).returning();z[0]&&l.created.push(z[0]);}}if(r.update)for(let c of r.update){if(!c.id||!(await a.select().from(s).where(m(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:M,...z}=c,g=await a.update(s).set(z).where(eq(u,M)).returning();g[0]&&l.updated.push(g[0]);}if(r.delete)for(let c of r.delete)(await a.delete(s).where(m(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(r.connect)for(let c of r.connect)(await a.update(s).set({[n.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(r.disconnect)for(let c of r.disconnect)(await a.update(s).set({[n.foreignKey]:null}).where(m(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},Z=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return s.enabled&&l.push(isNull(this.getColumn(s.field))),(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(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return s.enabled&&l.push(isNull(this.getColumn(s.field))),s.enabled?(await r.update(i).set({[s.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(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey),l=await i.select({count:sql`count(*)`}).from(a).where(eq(s,e));return O(l)}async deleteRelated(e,t,n,r){let i=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey);return (await i.delete(a).where(eq(s,e)).returning()).length}async nullifyRelated(e,t,n,r){let i=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return 0;let s=p(a,n.foreignKey);return (await i.update(a).set({[n.foreignKey]:null}).where(eq(s,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},F=class extends ListEndpoint{db;dialect="sqlite";getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let C=this.getColumn(r.field);e.options.onlyDeleted?n.push(isNotNull(C)):e.options.withDeleted||n.push(isNull(C));}for(let C of e.filters){let R=k(t,C);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let C=e.options.search,R=this.searchFields.map(W=>{let oe=this.getColumn(W);return ee(oe,C,this.dialect)});n.push(S(...R));}let i=n.length>0?m(...n):void 0,a=this.getDb(),s=await a.select({count:sql`count(*)`}).from(t).where(i),l=O(s),d=a.select().from(t).where(i);if(e.options.order_by){let C=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(C));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let b=await d,M={relations:e.options.include||[]},z=await B(this.getDb(),b,this._meta,M),g=Math.ceil(l/c);return {result:z,result_info:{page:u,per_page:c,total_count:l,total_pages:g,has_next_page:u<g,has_prev_page:u>1}}}},N=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return f(this)}getTable(){return h(this._meta)}getColumn(e){return p(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),i=this.getTable(),a=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),l=[eq(a,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(s.field))),(await r.update(i).set({[s.field]:null}).where(m(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var L=class extends BatchCreateEndpoint{db;getDb(){return f(this)}getTable(){return h(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()}},K=class extends BatchUpdateEndpoint{db;getDb(){return f(this)}getTable(){return h(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=[],a=[];for(let s of e){let l=[eq(n,s.id)];r.enabled&&l.push(isNull(this.getColumn(r.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(s.data)).where(m(...l)).returning();d[0]?i.push(d[0]):a.push(s.id);}return {updated:i,notFound:a}}},$=class extends BatchDeleteEndpoint{db;getDb(){return f(this)}getTable(){return h(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.enabled&&i.push(isNull(this.getColumn(r.field)));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 s=a,l=new Set(s.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:s,notFound:d}}},Q=class extends BatchRestoreEndpoint{db;getDb(){return f(this)}getTable(){return h(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=await this.getDb().update(t).set({[r.field]:null}).where(m(...i)).returning(),l=new Set(s.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:s,notFound:d}}};function fn(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends q{_meta=e;db=o},Read:class extends A{_meta=e;db=o},Update:class extends U{_meta=e;db=o},Delete:class extends Z{_meta=e;db=o},List:class extends F{_meta=e;db=o;dialect=n},Restore:class extends N{_meta=e;db=o},Upsert:class extends j{_meta=e;db=o;dialect=n},Search:class extends I{_meta=e;db=o;dialect=n},BatchCreate:class extends L{_meta=e;db=o},BatchUpdate:class extends K{_meta=e;db=o},BatchDelete:class extends ${_meta=e;db=o},BatchRestore:class extends Q{_meta=e;db=o},BatchUpsert:class extends _{_meta=e;db=o;dialect=n}}}var ne=null,we=false,te=null;async function re(){if(we){if(te)throw te;return ne}we=true;try{return ne=await import('drizzle-zod'),ne}catch{throw te=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),te}}async function yt(o,e){return (await re()).createSelectSchema(o,e)}async function wt(o,e){return (await re()).createInsertSchema(o,e)}async function Et(o,e){let t=await re();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Tt(o,e){let t=await re(),n=e?.coerceDates!==false,r=n?kt(o):new Set,i=t.createSelectSchema(o,e?.selectRefine),a=t.createInsertSchema(o,e?.insertRefine),s;return t.createUpdateSchema?s=t.createUpdateSchema(o,e?.updateRefine):s=t.createInsertSchema(o,e?.updateRefine).partial(),n&&r.size>0&&(a=Ee(a,r),s=Ee(s,r)),{select:i,insert:a,update:s}}function Rt(){return ne!==null}var xt=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()),Ot=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 kt(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 a=String(i.dataType??"").toLowerCase(),s=String(i.columnType??"").toLowerCase(),l=i.config,d=String(l?.dataType??"").toLowerCase();(a.includes("timestamp")||a.includes("date")||a.includes("datetime")||s.includes("pgtimestamp")||s.includes("pgdate")||s.includes("mysqltimestamp")||s.includes("mysqldate")||s.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(n);}return e}function Ee(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 a=i.isOptional?.()??false,s=i.isNullable?.()??false,l=xt;(s||a)&&(l=Ot),a&&(l=l.optional()),n[r]=l;}else n[r]=i;return z.object(n)}var Un={CreateEndpoint:q,ListEndpoint:F,ReadEndpoint:A,UpdateEndpoint:U,DeleteEndpoint:Z,RestoreEndpoint:N,BatchCreateEndpoint:L,BatchUpdateEndpoint:K,BatchDeleteEndpoint:$,BatchRestoreEndpoint:Q,BatchUpsertEndpoint:_,SearchEndpoint:I,AggregateEndpoint:Y,ExportEndpoint:G,ImportEndpoint:H,UpsertEndpoint:j,CloneEndpoint:J};export{Ke as DRIZZLE_DIALECTS,Un as DrizzleAdapters,Y as DrizzleAggregateEndpoint,L as DrizzleBatchCreateEndpoint,$ as DrizzleBatchDeleteEndpoint,Q as DrizzleBatchRestoreEndpoint,K as DrizzleBatchUpdateEndpoint,_ as DrizzleBatchUpsertEndpoint,J as DrizzleCloneEndpoint,q as DrizzleCreateEndpoint,Z as DrizzleDeleteEndpoint,G as DrizzleExportEndpoint,H as DrizzleImportEndpoint,F as DrizzleListEndpoint,A as DrizzleReadEndpoint,N as DrizzleRestoreEndpoint,I as DrizzleSearchEndpoint,U as DrizzleUpdateEndpoint,j as DrizzleUpsertEndpoint,ge as DrizzleVersionCompareEndpoint,ue as DrizzleVersionHistoryEndpoint,pe as DrizzleVersionReadEndpoint,me as DrizzleVersionRollbackEndpoint,B as batchLoadDrizzleRelations,k as buildWhereCondition,X as cast,fn as createDrizzleCrud,Tt as createDrizzleSchemas,wt as createInsertSchema,yt as createSelectSchema,Et as createUpdateSchema,p as getColumn,h as getTable,Rt as isDrizzleZodAvailable,$e as loadDrizzleRelation,le as loadDrizzleRelations,O as readCount,ee as substringMatch};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hono-crud/drizzle",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Drizzle ORM CRUD adapter for hono-crud",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "hono-crud": "0.13.12"
46
+ "hono-crud": "0.13.13"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "drizzle-orm": ">=0.30.0",