@hono-crud/drizzle 0.1.3 → 0.1.5

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/dist/index.d.ts CHANGED
@@ -86,7 +86,8 @@ type DrizzleDB = DrizzleDatabaseConstraint;
86
86
  * pre-existing portable behavior). Set explicitly when targeting PostgreSQL
87
87
  * or MySQL to enable the appropriate code paths.
88
88
  */
89
- type DrizzleDialect = 'sqlite' | 'pg' | 'mysql';
89
+ declare const DRIZZLE_DIALECTS: readonly ["sqlite", "pg", "mysql"];
90
+ type DrizzleDialect = (typeof DRIZZLE_DIALECTS)[number];
90
91
  /**
91
92
  * Type helper for defining Hono Env with database in Variables.
92
93
  * Use this when injecting the database via middleware.
@@ -148,6 +149,21 @@ declare function batchLoadDrizzleRelations<T extends Record<string, unknown>, M
148
149
  * Builds a where condition from filter conditions.
149
150
  */
150
151
  declare function buildWhereCondition(table: Table, filter: FilterCondition): SQL | undefined;
152
+ /**
153
+ * Shape of a `SELECT count(*) AS count` row produced by the Drizzle query
154
+ * builder. The builder returns rows as `unknown`, so this names the one row
155
+ * shape the count queries rely on.
156
+ */
157
+ interface CountRow {
158
+ count: number;
159
+ }
160
+ /**
161
+ * Read the scalar total from a `SELECT count(*) AS count` result, coercing the
162
+ * driver's value to a number and defaulting to `0` when the result is empty.
163
+ * Centralizes the `as CountRow[]` cast that the count/exists/pagination paths
164
+ * would otherwise repeat at every call site.
165
+ */
166
+ declare function readCount(result: unknown): number;
151
167
 
152
168
  /**
153
169
  * Drizzle Create endpoint.
@@ -988,4 +1004,4 @@ declare function isDrizzleZodAvailable(): boolean;
988
1004
  */
989
1005
  declare const DrizzleAdapters: AdapterBundle;
990
1006
 
991
- export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, substringMatch };
1007
+ export { type CountRow, type CreateDrizzleCrudOptions, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, substringMatch };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt,ne as ne$1,sql,and,or,desc,asc}from'drizzle-orm';import {UpsertEndpoint,BatchUpsertEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint}from'hono-crud/internal';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function pe(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function de(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await pe(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,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[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
1
+ import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt,ne,sql,and,or,desc,asc}from'drizzle-orm';import {assertNever,UpsertEndpoint,BatchUpsertEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint}from'hono-crud/internal';import {z as z$1}from'zod';function G(a){return a}var Ke=["sqlite","pg","mysql"];function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function ge(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function ce(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await ge(a,n,r,s));}return n}async function j(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function v(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne(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[o,n]=e.value;return between(t,o,n)}default:return assertNever(e.operator)}}function k(a){return Number(a[0]?.count)||0}function z(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("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("db", myDb);
4
- 3. Use factory: createDrizzleCrud(db, meta)`)}function ee(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function Je(a){return a.split(/\s+/).filter(e=>e.length>0)}var j=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},_=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},ge=class extends VersionHistoryEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},me=class extends VersionReadEndpoint{},be=class extends VersionCompareEndpoint{},he=class extends VersionRollbackEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},G=class extends AggregateEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return computeAggregations(s,e)}},I=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let ie=this.getColumn(M);return ee(sql`CAST(${ie} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=Je(e.query);if(M.length>0){let x=[];for(let ie of M){let ue=i.map(ae=>w(ae,ie)).filter(ae=>ae!==void 0);ue.length>0&&x.push(or(...ue));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=searchInMemory(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),se=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:se[M]})),totalCount:u}}},H=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return ee($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}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,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},J=class extends ImportEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},Y=class extends CloneEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};var U=class extends CreateEndpoint{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[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()}},B=class extends ReadEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await de(this.getDb(),l[0],this._meta,o):null}},A=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)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=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(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()}},L=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,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()}},K=class extends ListEndpoint{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=e.options.search,R=this.searchFields.map($=>{let se=this.getColumn($);return ee(se,y,this.dialect)});o.push(or(...R));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},Z=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...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 F=class extends BatchCreateEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},Q=class extends BatchUpdateEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},N=class extends BatchDeleteEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},q=class extends BatchRestoreEndpoint{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function ln(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=a},Read:class extends B{_meta=e;db=a},Update:class extends A{_meta=e;db=a},Delete:class extends L{_meta=e;db=a},List:class extends K{_meta=e;db=a;dialect=o},Restore:class extends Z{_meta=e;db=a},Upsert:class extends j{_meta=e;db=a;dialect=o},Search:class extends I{_meta=e;db=a;dialect=o},BatchCreate:class extends F{_meta=e;db=a},BatchUpdate:class extends Q{_meta=e;db=a},BatchDelete:class extends N{_meta=e;db=a},BatchRestore:class extends q{_meta=e;db=a},BatchUpsert:class extends _{_meta=e;db=a;dialect=o}}}var oe=null,Te=false,ne=null;async function re(){if(Te){if(ne)throw ne;return oe}Te=true;try{return oe=await import('drizzle-zod'),oe}catch{throw ne=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ne}}async function mt(a,e){return (await re()).createSelectSchema(a,e)}async function bt(a,e){return (await re()).createInsertSchema(a,e)}async function ht(a,e){let t=await re();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await re(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Re(s,n),i=Re(i,n)),{select:r,insert:s,update:i}}function zt(){return oe!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Re(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var kn={CreateEndpoint:U,ListEndpoint:K,ReadEndpoint:B,UpdateEndpoint:A,DeleteEndpoint:L,RestoreEndpoint:Z,BatchCreateEndpoint:F,BatchUpdateEndpoint:Q,BatchDeleteEndpoint:N,BatchRestoreEndpoint:q,BatchUpsertEndpoint:_,SearchEndpoint:I,AggregateEndpoint:G,ExportEndpoint:H,ImportEndpoint:J,UpsertEndpoint:j,CloneEndpoint:Y};export{kn as DrizzleAdapters,G as DrizzleAggregateEndpoint,F as DrizzleBatchCreateEndpoint,N as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,Q as DrizzleBatchUpdateEndpoint,_ as DrizzleBatchUpsertEndpoint,Y as DrizzleCloneEndpoint,U as DrizzleCreateEndpoint,L as DrizzleDeleteEndpoint,H as DrizzleExportEndpoint,J as DrizzleImportEndpoint,K as DrizzleListEndpoint,B as DrizzleReadEndpoint,Z as DrizzleRestoreEndpoint,I as DrizzleSearchEndpoint,A as DrizzleUpdateEndpoint,j as DrizzleUpsertEndpoint,be as DrizzleVersionCompareEndpoint,ge as DrizzleVersionHistoryEndpoint,me as DrizzleVersionReadEndpoint,he as DrizzleVersionRollbackEndpoint,S as batchLoadDrizzleRelations,O as buildWhereCondition,X as cast,ln as createDrizzleCrud,ft as createDrizzleSchemas,bt as createInsertSchema,mt as createSelectSchema,ht as createUpdateSchema,b as getColumn,f as getTable,zt as isDrizzleZodAvailable,pe as loadDrizzleRelation,de as loadDrizzleRelations,ee as substringMatch};
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}function te(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function tt(a){return a.split(/\s+/).filter(e=>e.length>0)}var _=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},I=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},me=class extends VersionHistoryEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return k(o)>0}},be=class extends VersionReadEndpoint{},he=class extends VersionCompareEndpoint{},fe=class extends VersionRollbackEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends AggregateEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=v(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return computeAggregations(s,e)}},P=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return z(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=v(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let ae=this.getColumn(M);return te(sql`CAST(${ae} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=tt(e.query);if(M.length>0){let x=[];for(let ae of M){let pe=i.map(le=>w(le,ae)).filter(le=>le!==void 0);pe.length>0&&x.push(or(...pe));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=k(d),c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=searchInMemory(g,h,s),R={relations:t.options.include||[]},W=y.map(w=>w.item),ie=await j(this.getDb(),W,this._meta,R);return {items:y.map((w,M)=>({...w,item:ie[M]})),totalCount:u}}},J=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=v(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let W=this.getColumn(R);return te(W,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=k(s),l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}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,m={relations:e.options.include||[]},p=await j(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},Y=class extends ImportEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},ee=class extends CloneEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};var U=class extends CreateEndpoint{db;useTransaction=false;getDb(){return z(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[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 z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await ce(this.getDb(),l[0],this._meta,o):null}},B=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)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=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(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 z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return k(l)}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,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()}},K=class extends ListEndpoint{db;dialect="sqlite";getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=v(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=e.options.search,R=this.searchFields.map(W=>{let ie=this.getColumn(W);return te(ie,y,this.dialect)});o.push(or(...R));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=k(i),d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await j(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},F=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...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 Q=class extends BatchCreateEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},N=class extends BatchUpdateEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},q=class extends BatchDeleteEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},$=class extends BatchRestoreEndpoint{db;getDb(){return z(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function pn(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=a},Read:class extends A{_meta=e;db=a},Update:class extends B{_meta=e;db=a},Delete:class extends Z{_meta=e;db=a},List:class extends K{_meta=e;db=a;dialect=o},Restore:class extends F{_meta=e;db=a},Upsert:class extends _{_meta=e;db=a;dialect=o},Search:class extends P{_meta=e;db=a;dialect=o},BatchCreate:class extends Q{_meta=e;db=a},BatchUpdate:class extends N{_meta=e;db=a},BatchDelete:class extends q{_meta=e;db=a},BatchRestore:class extends ${_meta=e;db=a},BatchUpsert:class extends I{_meta=e;db=a;dialect=o}}}var re=null,Re=false,oe=null;async function se(){if(Re){if(oe)throw oe;return re}Re=true;try{return re=await import('drizzle-zod'),re}catch{throw oe=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),oe}}async function ft(a,e){return (await se()).createSelectSchema(a,e)}async function Dt(a,e){return (await se()).createInsertSchema(a,e)}async function zt(a,e){let t=await se();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function yt(a,e){let t=await se(),o=e?.coerceDates!==false,n=o?Et(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=xe(s,n),i=xe(i,n)),{select:r,insert:s,update:i}}function Mt(){return re!==null}var Ct=z$1.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z$1.date()),wt=z$1.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z$1.date().nullable());function Et(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function xe(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Ct;(i||s)&&(l=wt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z$1.object(o)}var jn={CreateEndpoint:U,ListEndpoint:K,ReadEndpoint:A,UpdateEndpoint:B,DeleteEndpoint:Z,RestoreEndpoint:F,BatchCreateEndpoint:Q,BatchUpdateEndpoint:N,BatchDeleteEndpoint:q,BatchRestoreEndpoint:$,BatchUpsertEndpoint:I,SearchEndpoint:P,AggregateEndpoint:H,ExportEndpoint:J,ImportEndpoint:Y,UpsertEndpoint:_,CloneEndpoint:ee};export{Ke as DRIZZLE_DIALECTS,jn as DrizzleAdapters,H as DrizzleAggregateEndpoint,Q as DrizzleBatchCreateEndpoint,q as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,N as DrizzleBatchUpdateEndpoint,I as DrizzleBatchUpsertEndpoint,ee as DrizzleCloneEndpoint,U as DrizzleCreateEndpoint,Z as DrizzleDeleteEndpoint,J as DrizzleExportEndpoint,Y as DrizzleImportEndpoint,K as DrizzleListEndpoint,A as DrizzleReadEndpoint,F as DrizzleRestoreEndpoint,P as DrizzleSearchEndpoint,B as DrizzleUpdateEndpoint,_ as DrizzleUpsertEndpoint,he as DrizzleVersionCompareEndpoint,me as DrizzleVersionHistoryEndpoint,be as DrizzleVersionReadEndpoint,fe as DrizzleVersionRollbackEndpoint,j as batchLoadDrizzleRelations,v as buildWhereCondition,G as cast,pn as createDrizzleCrud,yt as createDrizzleSchemas,Dt as createInsertSchema,ft as createSelectSchema,zt as createUpdateSchema,b as getColumn,f as getTable,Mt as isDrizzleZodAvailable,ge as loadDrizzleRelation,ce as loadDrizzleRelations,k as readCount,te as substringMatch};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hono-crud/drizzle",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Drizzle ORM CRUD adapter for hono-crud",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -42,7 +42,7 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "hono-crud": "0.13.6"
45
+ "hono-crud": "0.13.8"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "drizzle-orm": ">=0.30.0",