bun-query-builder 0.3.6 → 0.3.8
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/actions/index.d.ts +2 -1
- package/dist/actions/introspect-db.d.ts +8 -0
- package/dist/actions/migrate.d.ts +25 -1
- package/dist/bin/cli.js +5 -5
- package/dist/{chunk-7cgq9r40.js → chunk-3b13fc8j.js} +62 -54
- package/dist/chunk-82w0fmx3.js +2 -0
- package/dist/{chunk-xk3qn91x.js → chunk-93ny6tvm.js} +2 -2
- package/dist/{chunk-vxh8ktv7.js → chunk-9wck98bv.js} +3 -3
- package/dist/{chunk-5b51gpqw.js → chunk-bpwg9p8b.js} +15 -15
- package/dist/chunk-g7qvmctn.js +2 -0
- package/dist/{chunk-wfk6y67h.js → chunk-rzfnhh9f.js} +2 -2
- package/dist/chunk-vyqr0w2z.js +3 -0
- package/dist/drivers/decimal.d.ts +21 -0
- package/dist/drivers/postgres.d.ts +2 -0
- package/dist/migrations.d.ts +79 -5
- package/dist/schema.d.ts +2 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-cfswsgdh.js +0 -3
- package/dist/chunk-gcbgbkrf.js +0 -2
- package/dist/chunk-yzqfbfat.js +0 -2
package/dist/migrations.d.ts
CHANGED
|
@@ -18,13 +18,38 @@ export declare function migrationBody(sql: string): string;
|
|
|
18
18
|
*/
|
|
19
19
|
export declare function isLosslessTypeChange(from: NormalizedColumnType, to: NormalizedColumnType): boolean;
|
|
20
20
|
export declare function buildMigrationPlan(models: ModelRecord, options: InferenceOptions): MigrationPlan;
|
|
21
|
-
export declare function generateSql(plan: MigrationPlan, opts?: { dryRun?: boolean }): string[];
|
|
22
21
|
/**
|
|
23
|
-
*
|
|
22
|
+
* Write rendered migration files into the configured migrations directory.
|
|
23
|
+
*
|
|
24
|
+
* The only place the generator touches the disk. `deterministic` selects the
|
|
25
|
+
* naming scheme: zero-padded sequence numbers for a full-schema corpus (the
|
|
26
|
+
* same models always produce the same file names), timestamps for incremental
|
|
27
|
+
* diffs. A file whose statements the corpus already carries is skipped — see
|
|
28
|
+
* `createMigrationFile`.
|
|
29
|
+
*
|
|
30
|
+
* Returns the names of the files actually written, which is also what
|
|
31
|
+
* {@link lastCreatedMigrationFiles} reports afterwards.
|
|
32
|
+
*/
|
|
33
|
+
export declare function writeMigrationFiles(files: GeneratedMigrationFile[], opts: { deterministic: boolean }): string[];
|
|
34
|
+
/**
|
|
35
|
+
* Render the full-schema create migrations for a plan: one file per table,
|
|
36
|
+
* holding its enum types, CREATE TABLE, indexes and (on the last file) any
|
|
37
|
+
* cyclic foreign keys. Pure — nothing is written.
|
|
38
|
+
*/
|
|
39
|
+
export declare function generateSqlFiles(plan: MigrationPlan): { statements: string[], files: GeneratedMigrationFile[] };
|
|
40
|
+
/**
|
|
41
|
+
* Render the full-schema SQL for a plan.
|
|
42
|
+
*
|
|
43
|
+
* Pure unless `write: true` is passed, in which case the per-table migration
|
|
44
|
+
* files are also written (see {@link writeMigrationFiles}).
|
|
45
|
+
*/
|
|
46
|
+
export declare function generateSql(plan: MigrationPlan, opts?: GenerateSqlOptions): string[];
|
|
47
|
+
/**
|
|
48
|
+
* The full-schema SQL for a plan as one string. Pure: writes nothing.
|
|
24
49
|
*/
|
|
25
50
|
export declare function generateSqlString(plan: MigrationPlan): string;
|
|
26
51
|
/**
|
|
27
|
-
*
|
|
52
|
+
* The diff SQL between two plans as one string. Pure: writes nothing.
|
|
28
53
|
*/
|
|
29
54
|
export declare function generateDiffSqlString(previous: MigrationPlan | undefined, next: MigrationPlan): string;
|
|
30
55
|
/**
|
|
@@ -41,15 +66,44 @@ export declare function hashMigrationPlan(plan: MigrationPlan): string;
|
|
|
41
66
|
* SQLite is the lossy one (string/text/date/datetime/json all map to TEXT;
|
|
42
67
|
* boolean/integer/bigint to INTEGER; float/double/decimal to REAL). For
|
|
43
68
|
* Postgres/MySQL the normalized type round-trips faithfully enough to compare
|
|
44
|
-
* directly
|
|
69
|
+
* directly — except for the facets the normalized type does not carry, which
|
|
70
|
+
* are spelled out here: a varchar's length on every dialect that has one.
|
|
45
71
|
*/
|
|
46
72
|
export declare function canonicalStorageType(col: ColumnPlan, dialect: SupportedDialect): string;
|
|
73
|
+
/**
|
|
74
|
+
* Whether a change keeps the physical type but tightens a bound on it, so
|
|
75
|
+
* existing values may no longer fit (a varchar(100) becoming varchar(50), a
|
|
76
|
+
* decimal losing digits, an enum losing a value).
|
|
77
|
+
* Postgres and strict MySQL refuse the ALTER when a row is too long; MySQL in
|
|
78
|
+
* a permissive mode truncates. Either way it is not a free change.
|
|
79
|
+
*/
|
|
80
|
+
export declare function isNarrowingChange(from: ColumnPlan, to: ColumnPlan): boolean;
|
|
47
81
|
/**
|
|
48
82
|
* Canonical string form of a column default, so equivalent defaults expressed
|
|
49
83
|
* differently by a live DB vs a model (quoting, casts, `now()` vs
|
|
50
84
|
* `CURRENT_TIMESTAMP`, `0` vs `'0'`) compare equal.
|
|
51
85
|
*/
|
|
52
86
|
export declare function canonicalizeDefault(col: ColumnPlan, dialect?: SupportedDialect): string | undefined;
|
|
87
|
+
/**
|
|
88
|
+
* A partial-index predicate reduced to a form that compares equal however it
|
|
89
|
+
* was spelled.
|
|
90
|
+
*
|
|
91
|
+
* The predicate is part of an index's identity: changing `status = 'active'`
|
|
92
|
+
* to `status <> 'archived'` is a different index, and leaving it out of the
|
|
93
|
+
* diff key meant the change emitted nothing at all. But a predicate read back
|
|
94
|
+
* from a live database is not the string the model wrote - Postgres stores
|
|
95
|
+
* `deleted_at IS NULL` as `(deleted_at IS NULL)`, adds `::text` casts to
|
|
96
|
+
* literals, and rewrites `IN (...)` as `= ANY (ARRAY[...])` - and comparing
|
|
97
|
+
* those literally would drop and recreate every partial index on every live
|
|
98
|
+
* reconcile.
|
|
99
|
+
*
|
|
100
|
+
* So, outside string literals (which are kept verbatim): casts, identifier
|
|
101
|
+
* quotes, parentheses, brackets and whitespace are removed, keywords are
|
|
102
|
+
* lowercased, and Postgres's rewrites of IN / NOT IN (to array comparisons)
|
|
103
|
+
* and of a simple BETWEEN (to a pair of comparisons) are mapped back.
|
|
104
|
+
* Two predicates that differ only in those respects are the same index.
|
|
105
|
+
*/
|
|
106
|
+
export declare function normalizeIndexPredicate(where: string | undefined): string;
|
|
53
107
|
/**
|
|
54
108
|
* Generate comprehensive SQL to migrate from a previous plan to a new plan,
|
|
55
109
|
* plus a structured list of the operations involved (so callers can gate
|
|
@@ -118,6 +172,8 @@ export declare interface ColumnPlan {
|
|
|
118
172
|
}
|
|
119
173
|
enumValues?: string[]
|
|
120
174
|
maxLength?: number
|
|
175
|
+
precision?: number
|
|
176
|
+
scale?: number
|
|
121
177
|
enumTypeName?: string
|
|
122
178
|
}
|
|
123
179
|
export declare interface IndexPlan {
|
|
@@ -166,18 +222,35 @@ export declare interface MigrationOperation {
|
|
|
166
222
|
destructive: boolean
|
|
167
223
|
confidence?: 'high' | 'low'
|
|
168
224
|
sql: string
|
|
225
|
+
warning?: string
|
|
169
226
|
}
|
|
170
227
|
/** Result of {@link generateDiffOperations}: raw statements + structured ops. */
|
|
171
228
|
export declare interface DiffResult {
|
|
172
229
|
statements: string[]
|
|
173
230
|
operations: MigrationOperation[]
|
|
231
|
+
files: GeneratedMigrationFile[]
|
|
174
232
|
}
|
|
175
233
|
export declare interface InferenceOptions {
|
|
176
234
|
dialect: SupportedDialect
|
|
177
235
|
vitessSharded?: boolean
|
|
178
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* One migration file the generator would write: the descriptive part of its
|
|
239
|
+
* name (`create-orders-table`, `alter-orders-table`, ...) and its SQL, without
|
|
240
|
+
* the provenance header or the sequence prefix — both are added only when the
|
|
241
|
+
* file is actually written, by {@link writeMigrationFiles}.
|
|
242
|
+
*/
|
|
243
|
+
export declare interface GeneratedMigrationFile {
|
|
244
|
+
name: string
|
|
245
|
+
sql: string
|
|
246
|
+
}
|
|
247
|
+
export declare interface GenerateSqlOptions {
|
|
248
|
+
write?: boolean
|
|
249
|
+
dryRun?: boolean
|
|
250
|
+
}
|
|
179
251
|
export declare interface DiffOptions {
|
|
180
252
|
applyRenames?: boolean
|
|
253
|
+
write?: boolean
|
|
181
254
|
dryRun?: boolean
|
|
182
255
|
preserveUnknownColumns?: boolean
|
|
183
256
|
}
|
|
@@ -207,4 +280,5 @@ export type MigrationOpKind = | 'create_table'
|
|
|
207
280
|
| 'drop_index'
|
|
208
281
|
| 'add_foreign_key'
|
|
209
282
|
| 'rebuild_table'
|
|
210
|
-
| 'create_enum'
|
|
283
|
+
| 'create_enum'
|
|
284
|
+
| 'add_enum_value';
|
package/dist/schema.d.ts
CHANGED
package/dist/src/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{yn,bn,Tn,p,ot,lt,wn,We,Sn,Un}from"../chunk-93ny6tvm.js";export{ot as BrowserQueryBuilder,p as BrowserQueryError,Sn as browserAuth,lt as browserQuery,yn as configureBrowser,wn as createBrowserDb,We as createBrowserModel,Un as default,bn as getBrowserConfig,Tn as isBrowser};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{z,x,Mt,Ye,v,Me,Xe,Ze,Ne,Nt,f,Y,Oe,et,Ot,tt,tn,nn}from"../../chunk-9wck98bv.js";export{z as DynamoDBClient,Oe as DynamoDBMigrationDriver,Y as DynamoDBMigrationTracker,tt as EntityQueryBuilder,f as MIGRATIONS_TABLE,Ye as Model,Ne as buildDynamoDBMigrationPlan,Mt as configureModels,Ze as convertSchemaToDefinition,x as createClient,nn as createDynamo,et as createMigrationDriver,tn as dynamo,Xe as extractModelSchema,Me as extractTableDefinition,v as hashTableDefinition,Nt as isDefinitionEqual,Ot as migrateModels};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Z,ee,te,ne,I,re,ie,se,ae,L,oe,K,F,le,ce,j,ue,de,ct,Ue,ut,C,fe,o,me,he,ge,pe,h,dt,ft,mt,Ve,He,ht,w,R,Qe,A,ye,be,q,Te,W,we,U,V,M,H,Se,De,Ee,$e,Q,xe,ve,S,g,Dn,En,$n,gt,pt,yt,bt,Tt,xn,wt,Qt,vn,kn,Cn,Rn,St,An,Mn,Nn,ke,d,Dt,Et,$t,xt,vt,Gt,G,J,Ce,Jt,On,Pn,kt,Ge,zt,y,Je,Yt,ze,Xt,Bn,Zt,_n}from"../chunk-3b13fc8j.js";import{E,In,en,c,Ct,Rt,i,Re,Ae}from"../chunk-vyqr0w2z.js";import{At,u,z,x,Mt,Ye,v,Me,Xe,Ze,Ne,Nt,f,Y,Oe,et,Ot,tt,tn,nn}from"../chunk-9wck98bv.js";import{Pt,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un}from"../chunk-rzfnhh9f.js";import{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,_,hn,Fe,T,gn,pn,m,at}from"../chunk-bpwg9p8b.js";import{yn,bn,Tn,p,ot,lt,wn,We,Sn}from"../chunk-93ny6tvm.js";export{Lt as BelongsToManyRelationBuilder,ot as BrowserQueryBuilder,p as BrowserQueryError,Ut as DEFAULT_SQLITE_PRAGMAS,z as DynamoDBClient,At as DynamoDBDriverImpl,g as DynamoDBItemBuilder,Oe as DynamoDBMigrationDriver,Y as DynamoDBMigrationTracker,S as DynamoDBQueryBuilder,St as DynamoDBToolingAdapter,tt as EntityQueryBuilder,$t as GENERATED_MARKER,a as LibSQLError,f as MIGRATIONS_TABLE,Ye as Model,o as MySQLDriver,me as PostgresDriver,pe as SQLiteDriver,Zt as Seeder,he as SingleStoreDriver,gt as SingleTableManager,xn as SingleTablePatterns,yt as SingleTableQueryBuilder,pt as SingleTableRepository,y as UTC_CLOCK_DEFAULT,ge as VitessDriver,k as applySqliteBootstrapPragmas,Ve as auditSchemaDrift,Sn as browserAuth,lt as browserQuery,ke as buildDatabaseSchema,Ne as buildDynamoDBMigrationPlan,G as buildMigrationPlan,Dt as buildSchemaMeta,ee as cacheClear,ne as cacheConfig,te as cacheStats,Ge as canonicalStorageType,Je as canonicalizeDefault,xe as checkSchema,Bt as clearLocalModels,ln as clearModelRegistry,Re as clearQueryCache,e as config,yn as configureBrowser,Mt as configureModels,Ln as configureOrm,Ze as convertSchemaToDefinition,wn as createBrowserDb,We as createBrowserModel,x as createClient,nn as createDynamo,$n as createDynamoDBClient,u as createDynamoDBDriver,En as createDynamoDBItemBuilder,Dn as createDynamoDBQueryBuilder,An as createDynamoDBToolingAdapter,Pt as createFakerCompatLayer,Wt as createLibSQLSQL,et as createMigrationDriver,Kt as createModel,i as createQueryBuilder,Tt as createRepository,bt as createSingleTableManager,jn as createTableFromModel,L as dbInfo,K as dbOptimize,oe as dbStats,F as dbWipe,qt as decodeLibSQLValue,nt as defaultConfig,dn as defineConfig,cn as defineModel,Bn as defineModels,_n as defineSeeder,ae as dumpDatabase,tn as dynamo,jt as encodeLibSQLValue,Rt as escapeStringLiteral,R as executeMigration,Qe as executeMigrationWithReport,le as explain,U as explainAllQueries,ie as exportData,_t as extractChanges,It as extractInsertId,Xe as extractModelSchema,Me as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,ce as file,He as formatSchemaDrift,De as freshDatabase,Mn as generateAccessPatterns,V as generateDiagram,ze as generateDiffOperations,Xt as generateDiffSql,Pn as generateDiffSqlString,w as generateMigration,ut as generateModelSource,Jt as generateSql,Ce as generateSqlFiles,On as generateSqlString,sn as getAllModels,bn as getBrowserConfig,B as getConfig,Fn as getDatabase,h as getDialectDriver,rn as getModel,an as getModelRegistry,t as getPlaceholder,s as getPlaceholders,on as hasModel,kt as hashMigrationPlan,v as hashTableDefinition,se as importData,pn as inflectSingular,j as inspectTable,de as introspect,C as introspectDatabase,Tn as isBrowser,Nt as isDefinitionEqual,xt as isGeneratedMigrationSql,Wn as isLibSQLConnection,it as isLibSQLUrl,Gt as isLosslessTypeChange,n as isMysqlLike,zt as isNarrowingChange,In as iterateAllPivots,Et as lastCreatedMigrationFiles,d as loadModels,fe as makeModel,Se as makeSeeder,Cn as marshallObject,ye as migrateGenerate,Te as migrateList,Ot as migrateModels,be as migrateRollback,q as migrateStatus,vt as migrationBody,Ue as modelNameForTable,W as modelShow,rt as normalizeDialectName,Yt as normalizeIndexPredicate,K as optimizeDatabase,Qt as parseStacksModels,we as ping,U as queryExplainAll,c as quoteColumnForDialect,en as raw,un as registerBrowserModels,Ft as registerModel,V as relationDiagram,Kn as releaseOrm,hn as resetConnection,A as resetDatabase,P as resolveDialect,wt as resolveKeyPattern,fn as resolveLibSQLEndpoint,_ as resolveLibSQLTarget,E as resolvePivot,Vt as resolveSqlitePragmas,Z as runBenchmark,H as runSeeder,M as runSeeders,mt as satisfies,ht as saveMigrationSnapshot,qn as seedModel,_e as setConfig,Ae as setQueryCacheMaxSize,W as showModel,m as singularizerFor,Ee as sql,ct as sqlTypeToAttr,Nn as stacksModelToEntity,I as startConsole,gn as stripTrailingS,ue as tableInfo,T as tableNameFor,Ct as temporalLiteral,re as tinker,at as toDialectPlaceholders,vn as toDynamoDBItem,Le as toHranaStatement,Ie as toLibSQLError,mn as toLibSQLRows,kn as toModelInstance,Fe as toTableName,Rn as unmarshallItem,$e as unsafe,Q as validateSchema,ve as waitReady,F as wipeDatabase,J as writeMigrationFiles};
|
package/dist/src/runtime.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,
|
|
2
|
+
import{n,nt,e,P,rt,t,s,B,_e,dn,Ut,Vt,k,_,hn}from"../chunk-bpwg9p8b.js";import{en,c,Ct,Rt,i,Re,Ae}from"../chunk-vyqr0w2z.js";export{Ut as DEFAULT_SQLITE_PRAGMAS,k as applySqliteBootstrapPragmas,Re as clearQueryCache,e as config,i as createQueryBuilder,nt as defaultConfig,dn as defineConfig,Rt as escapeStringLiteral,B as getConfig,t as getPlaceholder,s as getPlaceholders,n as isMysqlLike,rt as normalizeDialectName,c as quoteColumnForDialect,en as raw,hn as resetConnection,P as resolveDialect,_ as resolveLibSQLTarget,Vt as resolveSqlitePragmas,_e as setConfig,Ae as setQueryCacheMaxSize,Ct as temporalLiteral};
|
package/dist/types.d.ts
CHANGED
|
@@ -287,6 +287,7 @@ export declare interface GenerateMigrationResult {
|
|
|
287
287
|
hasChanges: boolean
|
|
288
288
|
plan: import('./migrations').MigrationPlan
|
|
289
289
|
operations?: import('./migrations').MigrationOperation[]
|
|
290
|
+
files?: import('./migrations').GeneratedMigrationFile[]
|
|
290
291
|
}
|
|
291
292
|
export declare interface UnsafeOptions {
|
|
292
293
|
params?: string
|
package/package.json
CHANGED
package/dist/chunk-cfswsgdh.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{n,e,t,s,Pe,b,r,m,qt,D,l,Y,Fe,je}from"./chunk-5b51gpqw.js";import{Buffer as wt}from"buffer";import{serialize as Mt}from"v8";function vt(p){return m(e.relations?.singularizeStrategy)(p)}function E(p,B,w,U={}){let ne=U.singularize??vt,oe=p.relations?.[B]?.belongsToMany?.[w];if(oe==null)return null;let Ee=typeof oe==="object",pe=Ee?oe:null,me=Ee?pe.model:oe,He=p.modelToTable[me]||me,Ve,et;if(pe?.table)Ve=pe.table;else if(pe?.through){if(et=pe.through,Ve=p.modelToTable[pe.through],!Ve)throw Error(`[query-builder] belongsToMany relation '${w}' on '${B}' references unknown through model '${pe.through}'. Make sure '${pe.through}' is registered via defineModels({...}).`)}else{let Je=ne(B),h=ne(He);Ve=[Je,h].sort().join("_")}let tt=pe?.foreignKey??`${ne(B)}_id`,ut=pe?.relatedKey??`${ne(He)}_id`,te={};if(pe?.pivot?.columns)Object.assign(te,pe.pivot.columns);if(et&&U.models){let Je=U.models[et],h=Je?.definition??Je?.getDefinition?.()??Je,g=h?.attributes??{};for(let[d,y]of Object.entries(g)){if(d===tt||d===ut||d===(h?.primaryKey??"id"))continue;te[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let Le=Boolean(pe?.pivot?.timestamps),Ie=Object.keys(te);return{pivotTable:Ve,fkParent:tt,fkRelated:ut,pivotColumns:Ie,pivotColumnDefs:te,pivotModelName:et,timestamps:Le,relatedModelName:me,relatedTable:He,hasConfig:Ee}}function*Nn(p,B={}){let w=p.relations;if(!w)return;for(let[U,ne]of Object.entries(w)){let N=ne?.belongsToMany;if(!N)continue;for(let oe of Object.keys(N)){let Ee=E(p,U,oe,B);if(Ee)yield{parentTable:U,relationKey:oe,resolved:Ee}}}}function We(p){return typeof p==="object"&&p!==null&&"raw"in p&&typeof p.raw==="string"}function mt(p,B,w){if(Array.isArray(B)){let ne=s(B.length,w.length+1),N=l(p,B,!1,ne);return w.push(...B),N}let U=`${p} = ${t(w.length+1)}`;return w.push(B),U}function Ge(p){return typeof p==="object"&&p!==null&&"sql"in p&&typeof p.sql==="string"&&(!("parameters"in p)||Array.isArray(p.parameters))}function Wt(p,B){let[w,...U]=B;if(U.length>0||w!==void 0&&!Array.isArray(w))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let ne={sql:p,parameters:[...w??[]]};return Object.defineProperty(ne,"then",{enumerable:!1,value:(N,oe)=>{let Ee=TypeError("[query-builder] db.raw(sql, bindings) builds a fragment for set() or where(), not a query. Run SQL with db.unsafe(sql, params).");if(typeof oe==="function")return oe(Ee);throw Ee}}),ne}function ot(p){return p instanceof Promise&&typeof p.execute==="function"&&typeof p.cancel==="function"}function it(p){throw TypeError(`[query-builder] ${p}: a Bun \`sql\`...\`\` query cannot be used as a fragment, because its SQL text is not readable. Bind values with db.raw('name = ?', [value]) or { sql, parameters }, or use the exported \`raw\` tagged template.`)}function Ye(p,B){let w=p.parameters??(Array.isArray(p.values)?p.values:[]);if(e.dialect!=="postgres"||w.length===0)return{text:p.sql,parameters:w};let U=0,{text:ne}=Fe(p.sql,()=>U<w.length?t(B+U++):void 0);if(U!==w.length)throw TypeError(`[query-builder] SQL expression declares ${w.length} parameters but contains only ${U} placeholders`);return{text:ne,parameters:w}}function Rt(p,B){if(B.length===2){let[w,U]=B;if(Array.isArray(U)&&typeof w==="number"&&U[w]===p)return!1;if(U instanceof Set&&w===p&&U.has(p))return!1;if(U instanceof Map&&U.get(w)===p)return!1}return B.some((w)=>w!==void 0&&!(Array.isArray(w)&&w.length===0))}function Jt(p,...B){if(typeof p==="string"){if(!(B.length===1&&Number.isInteger(B[0])&&B[0]>=0&&!p.includes("?"))&&Rt(p,B))throw TypeError("[query-builder] raw(string) takes no values, so the argument(s) after the string would be dropped. Use raw as a tagged template instead, which interpolates each value as an escaped literal.");return{raw:p}}let w=p[0];for(let U=0;U<B.length;U++)w+=_e(B[U])+p[U+1];return{raw:w}}function De(p){return n(e.dialect)?`\`${p.replace(/`/g,"``")}\``:`"${p.replace(/"/g,'""')}"`}function gt(p,B=1){let w=Object.keys(p[0]??{}),U=[],ne=B,N=p.map((oe)=>`(${w.map((pe)=>(U.push(oe[pe]),t(ne++))).join(", ")})`);return{colsSql:w.map(De).join(", "),valuesSql:N.join(", "),params:U,nextIndex:ne}}function lt(p){return Boolean(p&&(p.onSlowQuery||p.slowQueryThresholdMs!=null&&p.slowQueryThresholdMs>=0))}function c(p,B=e.dialect){if(!n(B))return p;let w=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(p.trim());if(!w)return p;let[,U,ne,N]=w,oe=ne?`\`${U}\`.\`${ne}\``:`\`${U}\``;return N?`${oe} AS \`${N}\``:oe}function $t(p,B=e.dialect){if(!n(B)||p===null||p===void 0)return p;if(typeof p==="string"){let w=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(p);if(!w)return p;let[,U,ne]=w;return`${U} ${ne.length===5?`${ne}:00`:ne}`}if(!(p instanceof Date)||Number.isNaN(p.getTime()))return p;return p.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function St(p){if(typeof p==="string")return c(p);if(We(p))return p.raw;if(p&&typeof p==="object"){let B=p;if(typeof B.raw==="function")return String(B.raw());if(typeof B.sql==="string")return B.sql;let w=String(p);if(w!=="[object Object]")return w}throw TypeError(`[query-builder] select(): unsupported column ${String(p)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Ft(p){let B=/\(|\)|\bORDER\s+BY\b/gi,w=0,U;while(U=B.exec(p))if(U[0]==="(")w++;else if(U[0]===")")w=Math.max(0,w-1);else if(w===0)return!0;return!1}var ye={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},Bt=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function F(p,B){if(!ye.IDENTIFIER.test(p)){let w=B?` in ${B}`:"";throw Error(`[query-builder] Invalid identifier${w}: '${p}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function $e(p,B){if(typeof p!=="string")throw TypeError(`[query-builder] ${B}: operator must be a string, got ${typeof p}`);let w=p.toLowerCase();if(!Bt.has(w))throw TypeError(`[query-builder] ${B}: refusing to use '${p}' as a SQL operator \u2014 not in the allowed set (${[...Bt].join(", ")})`);return p}function Ue(p,B,w,U){let ne=B.toLowerCase();if(ne!=="is"&&ne!=="is not")return null;if(w!==null&&w!==void 0)throw TypeError(`[query-builder] ${U}: operator '${B}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return`${p} IS ${ne==="is not"?"NOT ":""}NULL`}function xe(p,B){if(typeof p!=="string"||p.length===0)throw TypeError(`[query-builder] ${B}: identifier must be a non-empty string, got ${typeof p}`);if(p.length>129)throw TypeError(`[query-builder] ${B}: identifier '${p}' too long`);let w=p.split(".");if(w.length>2)throw TypeError(`[query-builder] ${B}: identifier '${p}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let U of w)if(!/^[A-Z_][A-Z0-9_]*$/i.test(U))throw TypeError(`[query-builder] ${B}: identifier segment '${U}' contains characters outside [A-Za-z0-9_]`)}function ze(p,B,w=[]){let U=typeof p==="object"&&p!==null?p.parameters??p.values:void 0;if(Rt(p,w)||Array.isArray(U)&&U.length>0){let ne=B.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":B.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${B}: this method takes a single fragment and no bindings, so the argument(s) after it would be dropped. Interpolate values with the exported \`raw\` tagged template, which inlines them as escaped literals${ne}`)}if(typeof p==="string")return _t(B),p;if(p===null||p===void 0)throw TypeError(`[query-builder] ${B}: fragment must be a SqlFragment, got ${p}`);if(We(p))return p.raw;if(typeof p==="object"){let ne=p;if(typeof ne.raw==="string")return ne.raw;if(typeof ne.raw==="function"){let oe=ne.raw();if(typeof oe==="string")return oe}if(typeof ne.sql==="string")return ne.sql;let N=String(p);if(N!=="[object Object]"&&N!=="[object Promise]")return N}throw TypeError(`[query-builder] ${B}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function Kt(p,B){if(!B||B.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(p))return;let w=Y(p),U=`${B.length} binding${B.length===1?"":"s"}`,ne=w>0?`the query binds them with ${w} \`?\` placeholder${w===1?"":"s"}, which Postgres reads as an operator rather than a parameter`:"the query contains no $n placeholder for them to bind to";throw TypeError(`[query-builder] unsafe(): ${U} supplied, but ${ne}. Postgres numbers `+"its parameters, so write $1, $2 \u2026 in the order the bindings should bind: "+"unsafe('SELECT * FROM users WHERE email = $1 LIMIT 1', [email]). `?` is correct on SQLite and MySQL, which is why this call may work there.")}var Dt=new Set;function _t(p){if(Dt.has(p))return;Dt.add(p),console.warn(`[query-builder] ${p}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function xt(p,B=e.dialect){return n(B)?p.replace(/\\/g,"\\\\").replace(/'/g,"''"):p.replace(/'/g,"''")}function _e(p){if(p===null)return"NULL";if(typeof p==="number"&&Number.isFinite(p))return String(p);if(typeof p==="boolean")return p?"1":"0";if(typeof p==="string")return`'${xt(p)}'`;if(p instanceof Date)return`'${p.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof p}`)}function jt(p,B){let w=Array.isArray(p)?p:p?[p]:[],U=[];if(w.length)U.push(`PARTITION BY ${w.join(", ")}`);if(B&&B.length)U.push(`ORDER BY ${B.map(([ne,N])=>`${ne} ${N==="desc"?"DESC":"ASC"}`).join(", ")}`);return U.length?`OVER (${U.join(" ")})`:"OVER ()"}class kt{cache=new Map;maxSize=100;get(p){let B=this.cache.get(p);if(!B)return null;if(Date.now()>B.expiresAt)return this.cache.delete(p),null;return this.cache.delete(p),this.cache.set(p,B),B.data}set(p,B,w){if(this.cache.has(p))this.cache.delete(p);if(this.cache.size>=this.maxSize){let U=Date.now(),ne=!1;for(let[N,oe]of this.cache)if(U>oe.expiresAt){if(this.cache.delete(N),ne=!0,this.cache.size<this.maxSize)break}if(!ne){let N=this.cache.keys().next().value;if(N!==void 0)this.cache.delete(N)}}this.cache.set(p,{data:B,expiresAt:Date.now()+w})}clear(){this.cache.clear()}setMaxSize(p){this.maxSize=Math.max(0,Math.floor(p));while(this.cache.size>this.maxSize){let B=this.cache.keys().next().value;if(B===void 0)break;this.cache.delete(B)}}}var bt=new kt,Et=new WeakMap,Ut=0;function Ht(p,B,w){let U=Et.get(p);if(U===void 0)U=++Ut,Et.set(p,U);let ne=w.map((N)=>ArrayBuffer.isView(N)?["view",wt.isBuffer(N)?"Buffer":Object.prototype.toString.call(N),wt.from(N.buffer,N.byteOffset,N.byteLength).toString("base64")]:["value",Mt(N).toString("base64")]);return`${U}\x00${B}\x00${JSON.stringify(ne)}`}function Vt(p){let B=String(p?.message||"").toLowerCase();return B.includes("deadlock")||B.includes("serialization failure")||B.includes("could not serialize access")||B.includes("deadlock found when trying to get lock")||B.includes("lock wait timeout exceeded")||B.includes("database is locked")||B.includes("busy")}function Gt(p,B){if(!B||B.length===0)return!1;let w=p&&(p.code||p.sqlState||p.sqlstate);if(!w)return!1;return B.includes(w)}function Yt(p){return new Promise((B)=>setTimeout(B,p))}var ft=new Map,zt=500,Xt=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],Zt=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],en=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function Ze(p){let B=ft.get(p);if(B!==void 0)return B;let w=tn(p);if(ft.size>=zt)ft.clear();return ft.set(p,w),w}function tn(p){let B=je(p,Xt);if(B.length<=1)return p;let w=p.slice(0,B[0].start).trimEnd(),U={};for(let oe=0;oe<B.length;oe++){let Ee=B[oe].start,pe=oe+1<B.length?B[oe+1].start:p.length,me=p.slice(Ee,pe).trim();if(!U[B[oe].key])U[B[oe].key]=[];U[B[oe].key].push(me)}let N=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((oe)=>U[oe]).map((oe)=>U[oe].join(" ")).join(" ");return N?`${w} ${N}`:w}function nn(p,B){let w=Math.max(1,B?.baseMs??50),U=Math.max(1,B?.factor??2),ne=Math.max(w,B?.maxMs??2000),N=Math.min(ne,w*U**Math.max(0,p-1));if(B?.jitter)N=Math.min(ne,N*(0.9+Math.random()*0.2));return Math.floor(N)}function i(p){let B=p?.sql??b(),w=p?.meta,U=p?.schema,ne;function N(h,g){let d=B.unsafe(h,g);if(typeof d.sql!=="string")ne??=new WeakMap,ne.set(d,{sql:h,params:g?.slice()});return d}let oe,Ee=(h,g)=>{let d=w?.temporalColumns?.[h];if(!d||d.length===0||!n(e.dialect))return g;return g.map((y)=>{let A=null;for(let f of d){if(!(f in y))continue;let X=$t(y[f]);if(X!==y[f])A=A??{...y},A[f]=X}return A??y})};function pe(h){if(typeof h==="number")return h;let g=String(h),d=7;for(let y=0;y<g.length;y++)d=d*31+g.charCodeAt(y)|0;return Math.abs(d)}function me(){if(!p?.hooks)return e.hooks;return{...e.hooks,...p.hooks}}let He=new Map;function Ve(h){if(Array.isArray(h)){let[f,X,v]=h;F(f,"where(column)");let K=String(f);switch(X){case"in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} IN (${q})`,v)}return N(`${K} IN (${t(1)})`,[v]);case"not in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} NOT IN (${q})`,v)}return N(`${K} NOT IN (${t(1)})`,[v]);case"like":return N(`${K} LIKE ${t(1)}`,[v]);case"is":case"is not":{if(v!==null&&v!==void 0)throw TypeError(`[query-builder] where(..., '${X}', ?): operator '${X}' only accepts NULL/undefined as value, got ${typeof v} (${String(v)})`);return N(`${K} IS ${X==="is not"?"NOT ":""}NULL`)}case"!=":return N(`${K} <> ${t(1)}`,[v]);case"<":case">":case"<=":case">=":case"=":return N(`${K} ${X} ${t(1)}`,[v]);default:throw TypeError(`[query-builder] where(..., '${String(X)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in h)return h.raw;let g=Object.keys(h);if(g.length===0)return N("");let d=[],y=[],A=1;for(let f of g){F(f,"where(object key)");let X=h[f];if(Array.isArray(X)){let v=s(X.length,A);d.push(`${f} IN (${v})`),y.push(...X),A+=X.length}else d.push(`${f} = ${t(A++)}`),y.push(X)}return N(d.join(" AND "),y)}function et(h,g,d){if(!d)return g;let y=Ve(d);return B`${g} WHERE ${y}`}function tt(h){let g=ne?.get(h);if(g)return g.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(h);if(e.debug)e.debug.captureText=d;return y}function ut(h){let g=ne?.get(h);if(g)return g.params;if(!h||typeof h!=="object")return;if(Array.isArray(h.values))return h.values;if(Array.isArray(h.parameters))return h.parameters;if(Array.isArray(h.params))return h.params;return}function te(h,g,d){let y=me(),A=y?.slowQueryThresholdMs,f=A!=null&&A>=0,X=Boolean(y?.onSlowQuery||f),v=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||X),K=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!v&&!K)return h.execute();let q=tt(h),k=ut(h),J=Date.now(),R;try{if(y?.onQueryStart?.({sql:q,params:k,kind:g}),y?.startSpan)R=y.startSpan({sql:q,params:k,kind:g})}catch{}let I=!1,V=(H,z,Q=Boolean(H))=>{if(I)return;I=!0;let j=Date.now()-J;try{if(Q)y?.onQueryError?.({sql:q,params:k,error:H,durationMs:j,kind:g});else if(y?.onQueryEnd?.({sql:q,params:k,durationMs:j,rowCount:z,kind:g}),f&&j>=A)if(y?.onSlowQuery)y.onSlowQuery({sql:q,params:k,durationMs:j,kind:g});else console.warn(`[query-builder] slow query (${j}ms >= ${A}ms): ${q}`)}catch{}try{R?.end(H)}catch{}};if(typeof h.executeSync==="function"){let H,z,Q=!1;try{H=h.executeSync()}catch(ee){z=ee,Q=!0}if(d?.signal?.aborted){try{h.cancel?.()}catch{}z=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),Q=!0}if(Q)return V(z,void 0,!0),Promise.reject(z);let j=Array.isArray(H)?H.length:typeof H==="number"?H:void 0;return V(void 0,j),Promise.resolve(H)}let W=h.execute(),_=[W],G;if(d?.timeoutMs&&d.timeoutMs>0){let H=new Promise((z,Q)=>{G=setTimeout(()=>{try{h.cancel?.()}catch{}let j=Error(`Query timed out after ${d.timeoutMs}ms`);j.code="EBQBTIMEOUT",Q(j)},d.timeoutMs)});_.push(H)}if(d?.signal){if(d.signal.aborted){try{h.cancel?.()}catch{}let z=Error("Query aborted");return z.code="EBQBABORT",V(z),Promise.reject(z)}let H=()=>{try{h.cancel?.()}catch{}};d.signal.addEventListener("abort",H,{once:!0}),W.finally(()=>{d.signal?.removeEventListener("abort",H)})}return Promise.race(_).then((H)=>{clearTimeout(G);let z=Array.isArray(H)?H.length:typeof H==="number"?H:void 0;return V(void 0,z),H}).catch((H)=>{throw clearTimeout(G),V(H),H})}function Le(h){if(typeof h==="number")return Number.isFinite(h)?h:0;if(typeof h==="bigint")return Number(h);if(!h||typeof h!=="object")return 0;let g=h;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(g[d]!==void 0&&g[d]!==null)return Le(g[d]);if(Array.isArray(h))return h.reduce((d,y)=>d+Le(y),0);return 0}function Ie(h,g){let d=g??tt(h);return{sql:d,toString:()=>d,execute:()=>h.execute(),values:()=>h.values(),raw:()=>h.raw()}}function Je(h,g){let d=B,y=g&&g.length>0?`SELECT ${g.join(", ")} FROM ${String(h)}`:`SELECT * FROM ${String(h)}`,A=[],f=[],X=!1,v=!1,K=!1,q=null,k=()=>{if(q===null){let a=Ze(W());q=f.length>0?N(a,f):N(a)}return q},J=(a="",o="",u=[])=>N(`${a}${Ze(W())}${o}`,[...f,...u]),R=(a,o)=>{A.push({conn:a,sql:o}),q=null},I=(a,o)=>{R(a==="OR"?"OR":"AND",o)},V=(a)=>{let o=je(a,Zt,1);return o.length>0?o[0].start:-1},W=(a)=>{let o=D(a?[...A,a]:A);if(!o)return y;if(X)return`${y} ${v?"AND":"WHERE"} ${o}`;let u=V(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},_=(a,o)=>{let u=Je(h);o(u);let T=u.__whereState?.();if(!T||!T.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=f.length,O=S>0&&e.dialect==="postgres"?T.body.replace(/\$(\d+)/g,(P,L)=>`$${Number(L)+S}`):T.body;f.push(...T.params),R(a,`(${O})`)},G=(a,o,u,T,S,O)=>{if(typeof T==="string"&&S!==void 0){F(String(T),`${u}(column)`),$e(S,`${u}(operator)`);let P=Ue(String(T),String(S),O,u);if(P)return R(o,P),a;let L=f.length+1;return f.push(O),R(o,`${String(T)} ${String(S)} ${t(L)}`),a}if(Array.isArray(T)){let[P,L,M]=T,x=String(P);F(x,`${u}(column)`);let C=$e(L,`${u}(operator)`);if(C==="in"||C==="not in"){let Z=Array.isArray(M)?M:[M],ae=s(Z.length,f.length+1),we=l(c(x),Z,C==="not in",ae);f.push(...Z),R(o,we)}else{let Z=Ue(x,C,M,u);if(Z)return R(o,Z),a;let ae=f.length+1;f.push(M),R(o,`${x} ${C} ${t(ae)}`)}return a}if(typeof T==="function")return _(o,T),a;if(ot(T))it(`${u}(expr)`);if(Ge(T)){let P=Ye(T,f.length+1);return f.push(...P.parameters),R(o,P.text),a}if(T&&typeof T==="object"&&!("raw"in T)){let P=[];for(let L of Object.keys(T)){F(L,`${u}(column)`);let M=T[L];if(Array.isArray(M)){let x=s(M.length,f.length+1);P.push(l(c(L),M,!1,x)),f.push(...M)}else{let x=f.length+1;P.push(`${L} = ${t(x)}`),f.push(M)}}if(P.length>0)R(o,P.length>1?`(${P.join(" AND ")})`:P[0]);return a}if(T&&typeof T.raw<"u")return R(o,T.raw),a;return a},H=(a,o)=>{if(A.length>0)y=W(),A.length=0;X=!0;let u=o.__rawState?.();if(u){let T=f.length,S=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(O,P)=>`$${Number(P)+T}`):u.sql;y+=` ${a} ${S}`,f.push(...u.params),v=o.__hasPredicate?.()??ye.WHERE.test(S)}else{let T=String(o.toSQL());y+=` ${a} ${T}`,v=o.__hasPredicate?.()??ye.WHERE.test(T)}q=null},z=(a)=>{let o=je(y,en,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,q=null},Q=new Set,j,ee,se=!1,ce=!1,Te=!1,qe=new Map,ke=new Set,ct=60000,ge=(a)=>m(e.relations.singularizeStrategy)(a),Qe=(a)=>{if(!w)return null;return E(w,String(h),a,{singularize:ge,models:w.models})},Ke=(a)=>{if(!a||typeof a!=="object"||ke.size===0)return a;let o;for(let u of Object.keys(a))if(u.startsWith("pivot_")){if(!o)o={};o[u.slice(6)]=a[u],delete a[u]}if(o)a.pivot=o;return a},nt=(a)=>{if(ke.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)Ke(a[o]);else Ke(a);return a},rt=(a)=>{if(!w)return;if(Q.has(a.pivotTable))return;let o=String(h),u=w.primaryKeys[o]??"id";F(a.pivotTable,"wherePivot auto-join (pivot table)"),F(a.fkParent,"wherePivot auto-join (parent FK)"),F(o,"wherePivot auto-join (parent table)"),F(u,"wherePivot auto-join (parent PK)"),q=d`${k()} LEFT JOIN ${d(a.pivotTable)} ON ${d(`${a.pivotTable}.${a.fkParent}`)} = ${d(`${o}.${u}`)}`,y=`${y} LEFT JOIN ${a.pivotTable} ON ${a.pivotTable}.${a.fkParent} = ${o}.${u}`,Q.add(a.pivotTable)},st=(a)=>{if(ye.SELECT_STAR.test(y))y=y.replace(ye.SELECT_STAR,`SELECT *, ${a}`);else if(ye.SELECT.test(y))y=y.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(k());if(ye.SELECT_STAR.test(o)){let u=o.replace(ye.SELECT_STAR,`SELECT *, ${a}`);q=N(u)}else if(ye.SELECT.test(o)){if(ye.SELECT_FROM.exec(o)){let T=o.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);q=N(T)}}},ve=(a,o,u,T)=>{st(`${a} ${jt(u,T)} AS ${o}`)},dt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${a.endsWith("s")?a.slice(0,-1):a}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${S} = ${a}.${u}`;if(T){let L=T({where:(M,x,C)=>(F(M,"relationship subquery condition"),`${o}.${M} ${$e(x,"whereHas callback")} ${_e(C)}`)});if(L)O+=` AND ${L}`}return O},yt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${o.endsWith("s")?o.slice(0,-1):o}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${S}`;if(T){let L=T({where:(M,x,C)=>(F(M,"relationship subquery condition"),`${o}.${M} ${$e(x,"whereHas callback")} ${_e(C)}`)});if(L)O+=` AND ${L}`}return O},Tt=(a,o,u,T,S,O)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)"),F(T,"relationship subquery (target primary key)");let P=O&&w?E(w,a,O,{singularize:ge,models:w.models}):null,L=ge(a),M=ge(o),x=P?.pivotTable??[L,M].sort().join("_"),C=P?.fkParent??`${L}_id`,Z=P?.fkRelated??`${M}_id`;F(x,"relationship subquery (pivot table)"),F(C,"relationship subquery (foreign key A)"),F(Z,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${x} JOIN ${o} ON ${o}.${T} = ${x}.${Z} WHERE ${x}.${C} = ${a}.${u}`;if(S){let re=S({where:(Se,Oe,Ne)=>(F(Se,"relationship subquery condition"),`${o}.${Se} ${$e(Oe,"whereHas callback")} ${_e(Ne)}`)});if(re)ae+=` AND ${re}`}return ae},Ot=(a,o,u)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let T=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return F(T,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${T} = ${a}.${u})`},Nt=(a,o,u,T)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let S=T&&w?E(w,a,T,{singularize:ge,models:w.models}):null,O=ge(a),P=ge(o),L=S?.pivotTable??[O,P].sort().join("_"),M=S?.fkParent??`${O}_id`;return F(L,"withCount (pivot table)"),F(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${M} = ${a}.${u})`},ht=(a,o,u)=>{if(!w)return;F(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let T=String(h),S=w.relations?.[T];if(!S)return;let O=Object.entries(S).find(([re,Se])=>Se&&typeof Se==="object"&&(o in Se));if(!O)return;let[P,L]=O,M=L[o],x=typeof M==="string"?M:M?.model||M?.target||M,C=w.modelToTable[x]||x,Z=w.primaryKeys[T]??"id";F(C,`with${a} (target table)`);let ae=`${a}(${C}.${u})`,we;if(P==="hasMany"||P==="hasOne"){let re=`${T.endsWith("s")?T.slice(0,-1):T}_id`;F(re,`with${a} (foreign key)`),we=`(SELECT ${ae} FROM ${C} WHERE ${C}.${re} = ${T}.${Z})`}else if(P==="belongsToMany"){let re=w?E(w,T,o,{singularize:ge,models:w.models}):null,Se=ge(T),Oe=ge(C),Ne=re?.pivotTable??[Se,Oe].sort().join("_"),Be=re?.fkParent??`${Se}_id`,ie=re?.fkRelated??`${Oe}_id`,at=w.primaryKeys[C]??"id";F(Ne,`with${a} (pivot table)`),F(Be,`with${a} (foreign key)`),F(ie,`with${a} (related key)`),we=`(SELECT ${ae} FROM ${Ne} JOIN ${C} ON ${C}.${at} = ${Ne}.${ie} WHERE ${Ne}.${Be} = ${T}.${Z})`}else return;st(`${we} AS ${o}_${a.toLowerCase()}_${u}`)},pt=()=>{if(qe.size===0)return;let a=[];for(let[o,u]of qe.entries()){let T=Qe(o);if(!T)continue;for(let O of u)F(O,"withPivot");let S=u.map((O)=>`${T.pivotTable}.${O} AS pivot_${O}`);a.push(...S)}if(a.length>0){let o=a.join(", ");st(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),q=null,this},selectRaw(a,...o){let u=ze(a,"selectRaw(fragment)",o),T=y.indexOf(" FROM ");if(T!==-1)y=`${y.substring(0,T)}, ${u}${y.substring(T)}`;else y+=`, ${u}`;return q=null,this},rowNumber(a="row_number",o,u){let T=[];if(o){let L=Array.isArray(o)?o:[o];T.push(`PARTITION BY ${L.join(", ")}`)}if(u&&u.length)T.push(`ORDER BY ${u.map(([L,M])=>`${L} ${M==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${T.length?`OVER (${T.join(" ")})`:"OVER ()"} AS ${a}`,P=y.indexOf(" FROM ");if(P!==-1)y=`${y.substring(0,P)}, ${O}${y.substring(P)}`;else y+=`, ${O}`;return q=null,this},denseRank(a="dense_rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([M,x])=>`${M} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${P}${y.substring(L)}`;else y+=`, ${P}`;return q=null,this},rank(a="rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([M,x])=>`${M} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${P}${y.substring(L)}`;else y+=`, ${P}`;return q=null,this},over(a,o,u={}){return ve(a,o,u.partitionBy,u.orderBy),this},lag(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return ve(`LAG(${u.join(", ")})`,o.alias??`${a}_lag`,o.partitionBy,o.orderBy),this},lead(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return ve(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return ve(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return ve(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return ve(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return ve(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return ve(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return ve(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return ve(`LAST_VALUE(${a})`,o.alias??`${a}_last`,o.partitionBy,o.orderBy),this},selectAll(){return this},select(a){if(!a)return this;let o=Array.isArray(a)?a:[a];if(o.length===0)return this;let u=o.map(St),T=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),S=T?T[1]:"",O=y.indexOf(" FROM ");if(O!==-1)y=`SELECT ${S}${u.join(", ")}${y.substring(O)}`;else y=`SELECT ${S}${u.join(", ")} FROM ${h}`;return q=null,this},addSelect(...a){if(!a.length)return this;let o=a.map(St),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return q=null,this},with(...a){if(!w||!a||a.length===0)return this;let o=[];for(let x of a){if(!x)continue;if(typeof x==="string")o.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[C,Z]of Object.entries(x))if(typeof Z==="function")o.push({name:C,callback:Z});else o.push({name:C})}if(o.length===0)return this;let u=e.relations.maxEagerLoad??50;if(o.length>u)throw Error(`[query-builder] Too many relationships to eager load (${o.length}). Maximum allowed: ${u}`);let T=String(h),S=new Set,O=new Set,P=new Map,L=(x)=>{let C=w.relations?.[x];if(!C)return[];return[...Object.keys(C.hasOne||{}),...Object.keys(C.hasMany||{}),...Object.keys(C.belongsTo||{}),...Object.keys(C.belongsToMany||{}),...Object.keys(C.hasOneThrough||{}),...Object.keys(C.hasManyThrough||{}),...Object.keys(C.morphOne||{}),...Object.keys(C.morphMany||{}),...Object.keys(C.morphToMany||{}),...Object.keys(C.morphedByMany||{})]},M=(x,C,Z=0,ae)=>{let we=e.relations.maxDepth??10;if(Z>=we)throw Error(`[query-builder] Maximum relationship depth (${we}) exceeded at '${C}'. Consider using separate queries or increasing maxDepth.`);let re=w.relations?.[x];if(!re)return x;let Se=(le)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let ue=e.softDeletes.column||"deleted_at";return` AND ${le}.${ue} IS NULL`}return""},Oe=(le)=>{if(!ae)return"";let ue=[],fe=(de,Ae,Me)=>{F(String(de),"with() constraint column");let Xe=$e(Ae,"with() constraint operator");ue.push(`${le}.${String(de)} ${Xe} ${_e(Me)}`)},he=(de)=>()=>{throw Error(`[query-builder] with('${C}', ...): ${de} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},be={where:(de,Ae,Me)=>{if(Array.isArray(de))fe(de[0],de[1],de[2]);else if(de&&typeof de==="object")for(let Xe of Object.keys(de))fe(Xe,"=",de[Xe]);else if(Ae!==void 0&&Me!==void 0)fe(de,Ae,Me);else if(Ae!==void 0)fe(de,"=",Ae);return be},whereIn:(de,Ae)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IN (${Ae.map(_e).join(", ")})`),be),whereNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NULL`),be),whereNotNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NOT NULL`),be),orderBy:he("orderBy()"),limit:he("limit()"),offset:he("offset()"),take:he("take()")};return ae(be),ue.length?` AND ${ue.join(" AND ")}`:""},Ne=()=>{let le=(he)=>{let be=he?.[C];return be?w.modelToTable[be]:void 0},ue=(he)=>{let be=he?.[C],de=typeof be==="string"?be:be?.model;return de?w.modelToTable[de]:void 0},fe=(he)=>{let be=he?.[C];return be?.target?w.modelToTable[be.target]:void 0};return le(re?.hasOne)||le(re?.hasMany)||le(re?.belongsTo)||ue(re?.belongsToMany)||fe(re?.hasOneThrough)||fe(re?.hasManyThrough)||le(re?.morphOne)||le(re?.morphMany)||le(re?.morphToMany)||le(re?.morphedByMany)},Be=Ne()??(w.modelToTable[C]||w.tableToModel[C]?w.modelToTable[C]??C:C),ie=String(Be);if(!Be||!Ne()&&!w.modelToTable[C]&&!w.tableToModel[C]){let le=L(x);if(le.length>0&&!le.includes(C)){let ue=` Available relationships: ${le.join(", ")}`;throw Error(`[query-builder] Relationship '${C}' not found on table '${x}'.${ue}`)}}if(e.relations.detectCycles!==!1){let le=`${x}->${ie}`;if(S.has(le))throw Error(`[query-builder] Circular relationship detected: ${le}. This would cause an infinite loop.`);S.add(le)}if(!ie||ie===x)return x;let at=re?.hasOneThrough?.[C]||re?.hasManyThrough?.[C];if(at){let{through:le,target:ue}=at,fe=w.modelToTable[le]||le,he=w.modelToTable[ue]||ue,be=w.primaryKeys[x]??"id",de=w.primaryKeys[fe]??"id",Ae=`${ge(x)}_id`,Me=`${ge(fe)}_id`;return z(`LEFT JOIN ${fe} ON ${fe}.${Ae} = ${x}.${be} LEFT JOIN ${he} ON ${he}.${Me} = ${fe}.${de}`),Q.add(fe),Q.add(he),he}if(Boolean(re?.belongsToMany?.[C])){let le=E(w,x,C,{singularize:ge,models:w.models}),ue=le?.pivotTable??[ge(x),ge(ie)].sort().join("_"),fe=w.primaryKeys[x]??"id",he=w.primaryKeys[ie]??"id",be=le?.fkParent??`${ge(x)}_id`,de=le?.fkRelated??`${ge(ie)}_id`;return z(`LEFT JOIN ${ue} ON ${ue}.${be} = ${x}.${fe} LEFT JOIN ${ie} ON ${ie}.${he} = ${ue}.${de}${Oe(ie)}`),Q.add(ue),Q.add(ie),ie}if(Boolean(re?.morphToMany?.[C])){let le=C,ue=`${ge(ie)}_${le}`,fe=w.primaryKeys[x]??"id",he=w.primaryKeys[ie]??"id",be=`${le}_type`,de=`${le}_id`,Ae=`${ge(ie)}_id`,Me=_e(w.tableToModel[x]||x);return z(`LEFT JOIN ${ue} ON ${ue}.${de} = ${x}.${fe} AND ${ue}.${be} = ${Me} LEFT JOIN ${ie} ON ${ie}.${he} = ${ue}.${Ae}`),Q.add(ue),Q.add(ie),ie}if(Boolean(re?.morphedByMany?.[C])){let le=re.morphedByMany?.[C]||C,ue=w.modelToTable[le]||le,fe=ge(x),he=`${ge(ue)}_${fe}`,be=w.primaryKeys[x]??"id",de=w.primaryKeys[ue]??"id",Ae=`${fe}_type`,Me=`${fe}_id`,Xe=`${ge(ue)}_id`,Qt=_e(w.tableToModel[ue]||ue);return z(`LEFT JOIN ${he} ON ${he}.${Xe} = ${x}.${be} LEFT JOIN ${ue} ON ${ue}.${de} = ${he}.${Me} AND ${he}.${Ae} = ${Qt}`),Q.add(he),Q.add(ue),ue}if(Boolean(re?.belongsTo?.[C])){let le=`${ge(ie)}_id`,ue=w.primaryKeys[ie]??"id";return z(`LEFT JOIN ${ie} ON ${x}.${le} = ${ie}.${ue}${Oe(ie)}`),Q.add(ie),ie}let At=Boolean(re?.morphOne?.[C]),It=Boolean(re?.morphMany?.[C]);if(At||It){let le=`${C}_type`,ue=`${C}_id`,fe=w.primaryKeys[x]??"id",he=_e(w.tableToModel[x]||x);return z(`LEFT JOIN ${ie} ON ${ie}.${ue} = ${x}.${fe} AND ${ie}.${le} = ${he}`),Q.add(ie),ie}let Lt=`${ge(x)}_id`,Ct=w.primaryKeys[x]??"id",Pt=`${Se(ie)}${Oe(ie)}`;return z(`LEFT JOIN ${ie} ON ${ie}.${Lt} = ${x}.${Ct}${Pt}`),Q.add(ie),ie};for(let x of o){let C=x.name.trim();if(x.callback)P.set(C,x.callback);let Z=C.split("."),ae=T,we=0;for(let re of Z){if(!re||re.trim().length===0)continue;let Se=re.trim(),Oe=P.get(Se);ae=M(ae,Se,we,Oe)||ae,we++}O.add(C)}if(qe.size>0){let x=[];for(let[C,Z]of qe.entries()){let ae=Qe(C);if(!ae)continue;let we=Z.map((re)=>`${ae.pivotTable}.${re} AS pivot_${re}`);x.push(...we)}if(x.length>0){let C=x.join(", ");st(C)}}return q=null,this},whereHas(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([Z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,P]=S,L=P[a],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C;if(O==="hasMany"||O==="hasOne"){let Z=w.primaryKeys[u]??"id";C=dt(u,x,Z,o)}else if(O==="belongsTo"){let Z=w.primaryKeys[x]??"id";C=yt(u,x,Z,o)}else if(O==="belongsToMany"){let Z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";C=Tt(u,x,Z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return I("WHERE",`EXISTS (${C})`),this},whereDoesntHave(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([Z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,P]=S,L=P[a],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C;if(O==="hasMany"||O==="hasOne"){let Z=w.primaryKeys[u]??"id";C=dt(u,x,Z,o)}else if(O==="belongsTo"){let Z=w.primaryKeys[x]??"id";C=yt(u,x,Z,o)}else if(O==="belongsToMany"){let Z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";C=Tt(u,x,Z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return I("WHERE",`NOT EXISTS (${C})`),this},has(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([C,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,P=O[a],L=typeof P==="string"?P:P?.model||P?.target||P,M=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let C=w.primaryKeys[o]??"id";x=dt(o,M,C)}else if(S==="belongsTo"){let C=w.primaryKeys[M]??"id";x=yt(o,M,C)}else if(S==="belongsToMany"){let C=w.primaryKeys[o]??"id",Z=w.primaryKeys[M]??"id";x=Tt(o,M,C,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return I("WHERE",`EXISTS (${x})`),this},doesntHave(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([C,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,P=O[a],L=typeof P==="string"?P:P?.model||P?.target||P,M=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let C=w.primaryKeys[o]??"id";x=dt(o,M,C)}else if(S==="belongsTo"){let C=w.primaryKeys[M]??"id";x=yt(o,M,C)}else if(S==="belongsToMany"){let C=w.primaryKeys[o]??"id",Z=w.primaryKeys[M]??"id";x=Tt(o,M,C,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return I("WHERE",`NOT EXISTS (${x})`),this},withCount(...a){if(!w||!a||a.length===0)return this;let o=String(h);for(let u of a){let T=w.relations?.[o];if(!T)continue;let S=Object.entries(T).find(([we,re])=>re&&typeof re==="object"&&(u in re));if(!S)continue;let[O,P]=S,L=P[u],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C=w.primaryKeys[o]??"id",Z;if(O==="hasMany"||O==="hasOne")Z=Ot(o,x,C);else if(O==="belongsToMany")Z=Nt(o,x,C,u);else continue;let ae=`${u}_count`;st(`${Z} AS ${ae}`)}return this},withSum(a,o){return ht("SUM",a,o),this},withAvg(a,o){return ht("AVG",a,o),this},withMax(a,o){return ht("MAX",a,o),this},withMin(a,o){return ht("MIN",a,o),this},applyPivotColumns(){return pt(),this},withPivot(a,...o){if(!w)return this;let u=String(h),T=Qe(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let S=o&&o.length>0?o:T.hasConfig?T.pivotColumns:[];if(S.length===0)return this;if(qe.set(a,S),T.hasConfig)ke.add(a);return pt(),this},wherePivot(a,o,u,T){if(!w)return this;let S=Qe(a);if(!S)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(S.pivotTable,"wherePivot (pivot table)"),F(o,"wherePivot (column)"),rt(S);let O=T===void 0?"=":String(u),P=T===void 0?u:T,L=f.length+1,M=`${S.pivotTable}.${o} ${O} ${t(L)}`;if(f.push(P),R("AND",M),S.hasConfig)ke.add(a);return this},wherePivotIn(a,o,u){if(!w||!Array.isArray(u))return this;let T=Qe(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotIn (pivot table)"),F(o,"wherePivotIn (column)"),rt(T);let S=s(u.length,f.length+1),O=l(`${T.pivotTable}.${o}`,u,!1,S);if(f.push(...u),R("AND",O),T.hasConfig)ke.add(a);return this},wherePivotNotIn(a,o,u){if(!w||!Array.isArray(u)||u.length===0)return this;let T=Qe(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotNotIn (pivot table)"),F(o,"wherePivotNotIn (column)"),rt(T);let S=s(u.length,f.length+1),O=`${T.pivotTable}.${o} NOT IN (${S})`;if(f.push(...u),R("AND",O),T.hasConfig)ke.add(a);return this},wherePivotNull(a,o){if(!w)return this;let u=Qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNull (pivot table)"),F(o,"wherePivotNull (column)"),rt(u),R("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)ke.add(a);return this},wherePivotNotNull(a,o){if(!w)return this;let u=Qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNotNull (pivot table)"),F(o,"wherePivotNotNull (column)"),rt(u),R("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)ke.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){F(String(a),"where(column)"),$e(o,"where(operator)");let T=String(o).toLowerCase();if(T==="in"||T==="not in"){let P=Array.isArray(u)?u:[u],L=s(P.length,f.length+1),M=l(c(String(a)),P,T==="not in",L);return f.push(...P),R("AND",M),this}let S=Ue(c(String(a)),T,u,"where");if(S)return R("AND",S),this;let O=f.length+1;return f.push(u),R("AND",`${c(String(a))} ${String(o)} ${t(O)}`),this}if(Array.isArray(a)){let[T,S,O]=a,P=String(T);F(P,"where(column)");let L=$e(S,"where(operator)");if(L==="in"||L==="not in"){let M=Array.isArray(O)?O:[O],x=s(M.length,f.length+1),C=l(c(P),M,L==="not in",x);f.push(...M),R("AND",C)}else{let M=Ue(c(P),L,O,"where");if(M)return R("AND",M),this;let x=f.length+1;f.push(O),R("AND",`${c(P)} ${L} ${t(x)}`)}return this}if(ot(a))it("where(expr)");if(Ge(a)){let T=Ye(a,f.length+1);return f.push(...T.parameters),R("AND",T.text),this}if(a&&typeof a==="object"&&!We(a)){let T=a,S=Object.keys(T),O=[];for(let P of S){F(P,"where(column)");let L=T[P];if(Array.isArray(L)){let M=s(L.length,f.length+1);O.push(l(c(P),L,!1,M)),f.push(...L)}else{let M=f.length+1;O.push(`${c(P)} = ${t(M)}`),f.push(L)}}if(O.length>0)R("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(We(a))return R("AND",a.raw),this;if(typeof a==="function")return _("AND",a),this;if(a===void 0||a===null)throw TypeError("where() was called with no condition.");if(typeof a==="string")throw TypeError(`where(${JSON.stringify(a)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof a}.`)},whereNull(a){return F(String(a),"whereNull(column)"),R("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return F(String(a),"whereNotNull(column)"),R("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return F(String(a),"orWhereNull(column)"),R("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return F(String(a),"orWhereNotNull(column)"),R("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){F(String(a),"whereBetween(column)");let T=f.length+1;return f.push(o,u),R("AND",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},orWhereBetween(a,o,u){F(String(a),"orWhereBetween(column)");let T=f.length+1;return f.push(o,u),R("OR",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereExists(a){return R("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return R("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return _("AND",a),this},orWhereGroup(a){return _("OR",a),this},__whereState(){return{body:D(A),params:[...f]}},whereJsonContains(a,o){F(String(a),"whereJsonContains(column)");let u=e.dialect,T=f.length+1;if(u==="postgres"){let O=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(T)})`:t(T);if(e.sql?.jsonContainsMode==="function")R("AND",`jsonb_contains(${a}, ${O})`);else R("AND",`${a} @> ${O}`);f.push(o)}else if(n(u))R("AND",`JSON_CONTAINS(${a}, ${t(T)})`),f.push(JSON.stringify(o));else if(Array.isArray(o)){let S=o.map((O,P)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T+P)})`);R("AND",`(${S.join(" AND ")})`);for(let O of o)f.push(O)}else if(o!==null&&typeof o==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else R("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T)})`),f.push(o);return this},whereJsonPath(a,o,u){if($e(o,"whereJsonPath(op)"),typeof a!=="string"||a.length===0||a.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof a==="string"?`'${a.slice(0,32)}...'`:typeof a}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(a))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${a}' \u2014 contains characters outside the allowed JSON-path set`);let T=e.dialect,S=f.length+1;if(T==="postgres")R("AND",`${a} ${o} ${t(S)}`);else if(n(T))R("AND",`JSON_EXTRACT(${a}) ${o} ${t(S)}`);else R("AND",`json_extract(${a}) ${o} ${t(S)}`);return f.push(u),this},whereLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},whereNotLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} NOT ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereNotLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} NOT ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},whereAny(a,o,u){if(a.length===0)return R("AND",`(${qt})`),this;let T=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(T+P)}`);for(let O=0;O<a.length;O++)f.push(u);return R("AND",`(${S.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(T+P)}`);for(let O=0;O<a.length;O++)f.push(u);return R("AND",`(${S.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(T+P)}`);for(let O=0;O<a.length;O++)f.push(u);return R("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(a,o,u){F(String(a),"whereNotBetween(column)");let T=f.length+1;return f.push(o,u),R("AND",`${a} NOT BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereDate(a,o,u){F(a,"whereDate(column)");let T=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),S=f.length+1;return f.push(T),R("AND",`${a} ${o} ${t(S)}`),this},whereRaw(a,...o){return R("AND",ze(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return R("OR",ze(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return F(a,"whereColumn(left)"),F(u,"whereColumn(right)"),R("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return F(a,"orWhereColumn(left)"),F(u,"orWhereColumn(right)"),R("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(F(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),R("AND",T)}else R("AND",`${a} IN (${String(o.toSQL())})`);return this},orWhereIn(a,o){if(F(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),R("OR",T)}else R("OR",`${a} IN (${String(o.toSQL())})`);return this},whereNotIn(a,o){if(F(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),R("AND",T)}else R("AND",`${a} NOT IN (${String(o.toSQL())})`);return this},orWhereNotIn(a,o){if(F(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),R("OR",T)}else R("OR",`${a} NOT IN (${String(o.toSQL())})`);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return R("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return R("OR",`(${o})`),this},andWhere(a,o,u){return G(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return G(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",T=c(String(a));return y=ye.ORDER_BY.test(y)?`${y}, ${T} ${u}`:`${y} ORDER BY ${T} ${u}`,q=null,this},orderByDesc(a){return y=ye.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,q=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=ye.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,q=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,q=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,q=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,q=null,this},limit(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${a}`);return y=ye.LIMIT.test(y)?y.replace(ye.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,q=null,this},offset(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${a}`);return y=ye.OFFSET.test(y)?y.replace(ye.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,q=null,this},join(a,o,u,T){return F(a,"join(table)"),xe(o,"join(onLeft)"),xe(T,"join(onRight)"),$e(u,"join(operator)"),z(`JOIN ${a} ON ${o} ${u} ${T}`),Q.add(a),this},joinSub(a,o,u,T,S){return F(o,"joinSub(alias)"),xe(u,"joinSub(onLeft)"),xe(S,"joinSub(onRight)"),$e(T,"joinSub(operator)"),z(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),Q.add(o),this},innerJoin(a,o,u,T){return F(a,"innerJoin(table)"),xe(o,"innerJoin(onLeft)"),xe(T,"innerJoin(onRight)"),$e(u,"innerJoin(operator)"),z(`INNER JOIN ${a} ON ${o} ${u} ${T}`),Q.add(a),this},leftJoin(a,o,u,T){return F(a,"leftJoin(table)"),xe(o,"leftJoin(onLeft)"),xe(T,"leftJoin(onRight)"),$e(u,"leftJoin(operator)"),z(`LEFT JOIN ${a} ON ${o} ${u} ${T}`),Q.add(a),this},leftJoinSub(a,o,u,T,S){return F(o,"leftJoinSub(alias)"),xe(u,"leftJoinSub(onLeft)"),xe(S,"leftJoinSub(onRight)"),$e(T,"leftJoinSub(operator)"),z(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),Q.add(o),this},rightJoin(a,o,u,T){return F(a,"rightJoin(table)"),xe(o,"rightJoin(onLeft)"),xe(T,"rightJoin(onRight)"),$e(u,"rightJoin(operator)"),z(`RIGHT JOIN ${a} ON ${o} ${u} ${T}`),Q.add(a),this},crossJoin(a){return F(a,"crossJoin(table)"),z(`CROSS JOIN ${a}`),Q.add(a),this},crossJoinSub(a,o){return F(o,"crossJoinSub(alias)"),z(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),Q.add(o),this},selectAllRelations(){if(!U)return this;let a=String(h),o=Object.keys(U[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let T of Q){let S=Object.keys(U[T]?.columns??{});for(let O of S){let P=e.aliasing.relationColumnAliasFormat==="camelCase"?`${T}_${O}`.replace(/_([a-z])/g,(L,M)=>M.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${T}.${O}`:`${T}_${O}`;u.push(d`${d(`${T}.${O}`)} AS ${d(P)}`)}}if(u.length>0){let T=o.length>0?`${a}.*`:"",S=[];for(let L of Q){let M=Object.keys(U[L]?.columns??{});for(let x of M){let C=e.aliasing.relationColumnAliasFormat==="camelCase"?`${L}_${x}`.replace(/_([a-z])/g,(Z,ae)=>ae.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${L}.${x}`:`${L}_${x}`;S.push(`${L}.${x} AS ${C}`)}}let O=[T,...S].filter(Boolean).join(", "),P=y.indexOf(" FROM ");if(P!==-1)y=`SELECT ${O}${y.substring(P)}`;else y=`SELECT ${O} FROM ${a}`;q=null}return this},groupBy(...a){if(a.length)y=ye.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,q=null;return this},groupByRaw(a,...o){let u=ze(a,"groupByRaw(fragment)",o);return y=ye.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,q=null,this},having(a){let o=K?"AND":"HAVING";if(Array.isArray(a)){let u=f.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,f.push(a[2]),K=!0,q=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),T=u.length;if(T){let S=f.length,O=Array.from({length:T});for(let P=0;P<T;P++){let L=u[P];O[P]=`${L} = ${t(S+P+1)}`,f.push(a[L])}y=`${y} ${o} ${O.join(" AND ")}`,K=!0,q=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,K=!0,q=null;return this},havingRaw(a,...o){let u=ze(a,"havingRaw(fragment)",o);return y+=` ${K?"AND":"HAVING"} ${u}`,K=!0,q=null,this},orderByRaw(a,...o){let u=ze(a,"orderByRaw(fragment)",o);return y=ye.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,q=null,this},$call(a){return a(this),this},union(a){return H("UNION",a),this},unionAll(a){return H("UNION ALL",a),this},intersect(a){return H("INTERSECT",a),this},intersectAll(a){return H("INTERSECT ALL",a),this},except(a){return H("EXCEPT",a),this},exceptAll(a){return H("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),T=Math.max(1,Math.floor(o));return y+=` LIMIT ${T} OFFSET ${(u-1)*T}`,q=null,this},toSQL(){let a=Ze(W());return{sql:a,toString:()=>a,execute:()=>k().execute(),values:()=>k().values(),raw:()=>k().raw()}},async value(a){let o=J(""," LIMIT 1"),u=await te(o,"select",{signal:ee,timeoutMs:j}),[T]=u;return T?.[a]},async pluck(a,o){let u=await te(k(),"select",{signal:ee,timeoutMs:j});if(o){let T={};for(let S of u){let O=String(S?.[o]);if(Object.prototype.hasOwnProperty.call(T,O))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${O}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);T[O]=S?.[a]}return T}return u.map((T)=>T?.[a])},async exists(){let a=J("SELECT EXISTS (",") as e"),o=await te(a,"select",{signal:ee,timeoutMs:j}),[u]=o;return Boolean(u?.e)},async doesntExist(){return!await this.exists()},async paginate(a,o=1,u={}){if(typeof a==="object"&&a!==null){let Z=a;o=Z.page??1,u=Z.tx?{tx:Z.tx}:{},a=Z.perPage??10}if(!Number.isFinite(a)||a<=0||!Number.isInteger(a))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${a}`);if(!Number.isFinite(o)||o<1||!Number.isInteger(o))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${o}`);if(u.tx){let Z=Ze(W()),ae=[...f],we=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${Z}) as sub`,ae),re=Number(we?.[0]?.c??0),Se=Math.max(1,Math.ceil(re/a)),Oe=Math.max(1,Math.min(o,Se)),Ne=(Oe-1)*a;return{data:await u.tx.unsafe(`${Z} LIMIT ${a} OFFSET ${Ne}`,ae),meta:{perPage:a,page:Oe,total:re,lastPage:Se}}}let T=J("SELECT COUNT(*) as c FROM (",") as sub"),S=await te(T,"select",{signal:ee,timeoutMs:j}),[O]=S,P=Number(O?.c??0),L=Math.max(1,Math.ceil(P/a)),M=Math.max(1,Math.min(o,L)),x=(M-1)*a;return{data:await te(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a,x]),"select",{signal:ee,timeoutMs:j}),meta:{perPage:a,page:M,total:P,lastPage:L}}},async simplePaginate(a,o=1){let u=Math.max(1,o),T=(u-1)*a,S=await te(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a+1,T]),"select",{signal:ee,timeoutMs:j}),O=S.length>a;return{data:O?S.slice(0,a):S,meta:{perPage:a,page:u,hasMore:O}}},async cursorPaginate(a,o,u="id",T="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let S=(Array.isArray(u)?u:[u]).map(String);for(let Be of S)F(Be,"cursorPaginate(column)");let O=T==="asc"?">":"<",P=T==="asc"?"ASC":"DESC",L=[...f],M="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Be=o.map((ie)=>(L.push(ie),t(L.length)));M=`(${S.join(", ")}) ${O} (${Be.join(", ")})`}else L.push(o),M=`${S[0]} ${O} ${t(L.length)}`;let x=Ze(M?W({conn:"AND",sql:M}):W()),C=S.map((Be)=>`${Be} ${P}`).join(", ");if(Ft(x))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${C} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let Z=L.length>0?N(`${x} ORDER BY ${C} LIMIT ${a+1}`,L):N(`${x} ORDER BY ${C} LIMIT ${a+1}`),ae=await te(Z,"select",{signal:ee,timeoutMs:j}),we=ae.length>a,re=ae.slice(0,a),Se=re[re.length-1],Oe=we&&Se?Array.isArray(u)?u.map((Be)=>Se[Be]):Se[u]:null,Ne=re.length?Array.isArray(u)?u.map((Be)=>re[0]?.[Be]):re[0]?.[u]:null;return{data:re,meta:{perPage:a,nextCursor:Oe??null,prevCursor:Ne}}},async chunk(a,o){let u=1;while(!0){let{data:T,meta:S}=await this.paginate(a,u);if(T.length===0)break;if(await o(T),u>=S.lastPage)break;u+=1}},async chunkById(a,o="id",u){let T;while(!0){let{data:S,meta:O}=await this.cursorPaginate(a,T,o,"asc");if(S.length===0)break;if(u)await u(S);if(T=O.nextCursor,!T)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(T)=>{for(let S of T)await u?.(S)})},withTimeout(a){return j=Math.max(1,Math.floor(a)),this},abort(a){return ee=a,this},withTrashed(){return se=!0,ce=!1,this},onlyTrashed(){se=!0,ce=!0;let a=e.softDeletes?.column||"deleted_at";return R("AND",`${h}.${a} IS NOT NULL`),this},scope(a,o){let u=String(h),S=w?.scopes?.[u]?.[a];if(S)return S(this,o);return this},when(a,o,u){if(a)return o(this);if(u)return u(this);return this},tap(a){return a(this),this},dump(){return console.log(String(k())),this},dd(){throw console.log(String(k())),Error("Dump and Die")},cache(a=60000){return ct=a,Te=!0,this},async explain(){let a=J("EXPLAIN ");return await te(a,"select",{signal:ee,timeoutMs:j})},simple(){return k().simple()},toText(){return W()},async get(){let a=me(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||lt(a));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let L=B._prepareStatement;if(L){let M=L(W());return nt(f.length>0?M.all(...f):M.all())}}let u=W();if(q=f.length>0?N(u,f):N(u),!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let L=k()._stmt,M=k()._params;if(L)return nt(M&&M.length>0?L.all(...M):L.all());return nt(await k().execute())}if(!e.softDeletes?.enabled&&!Te&&!j&&!ee)return nt(await te(k(),"select"));let T=k();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!se){let L=e.softDeletes.column,M=String(h);if((U?Boolean(U[M]?.columns?.[L]):!0)&&!ye.DELETED_AT.test(W()))I("WHERE",`${String(L)} IS ${ce?"NOT ":""}NULL`),T=k()}let S=Te&&!p?.inTransaction,O=S?Ht(B,W(),f):"";if(S){let L=bt.get(O);if(L)return L}let P=await te(T,"select",{signal:ee,timeoutMs:j});if(S)bt.set(O,P,ct);return nt(P)},async executeTakeFirst(){let a=await te(k(),"select",{signal:ee,timeoutMs:j});return Ke(Array.isArray(a)?a[0]:a)},async executeTakeFirstOrThrow(){let a=await this.executeTakeFirst();if(!a)throw Error("Record not found");return a},async first(){let a=me(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||lt(a));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let S=B._prepareStatement;if(S){let O=W(),P=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,L=S(P),M=f.length>0?L.all(...f):L.all();return Ke(M[0])}}let u=await te(J(""," LIMIT 1"),"select",{signal:ee,timeoutMs:j}),[T]=u;return Ke(T)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=w?.primaryKeys[String(h)]??"id",u=await te(J("",` WHERE ${De(o)} = ${t(f.length+1)} LIMIT 1`,[a]),"select",{signal:ee,timeoutMs:j}),[T]=u;return T},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=w?.primaryKeys[String(h)]??"id";return await te(J("",` WHERE ${l(De(String(o)),a,!1,s(a.length,f.length+1))}`,a),"select",{signal:ee,timeoutMs:j})},async*lazy(){let a,o=w?.primaryKeys[String(h)]??"id";while(!0){let T=await(a==null?d`${k()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${k()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(a=T[T.length-1]?.[o],a==null)break}},async*lazyById(){let a=w?.primaryKeys[String(h)]??"id",o;while(!0){let T=await(o==null?d`${k()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${k()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(o=T[T.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=W(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),T;if(u)T=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)T=`SELECT COUNT(*) as c${a.substring(o)}`;else T=`SELECT COUNT(*) as c FROM ${h}`;let S=me(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||lt(S));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!O){let x=B._prepareStatement;if(x){let C=x(T),Z=f.length>0?C.all(...f):C.all();return Number(Z[0]?.c??0)}}let P=f.length>0?N(T,f):N(T),L=await te(P,"select",{signal:ee,timeoutMs:j}),[M]=L;return Number(M?.c??0)},async avg(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${h}`,S=me(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||lt(S));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!O){let x=B._prepareStatement;if(x){let C=x(T),Z=f.length>0?C.all(...f):C.all();return Number(Z[0]?.a??0)}}let P=f.length>0?N(T,f):N(T),L=await te(P,"select",{signal:ee,timeoutMs:j}),[M]=L;return Number(M?.a??0)},async sum(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return Number(P?.s??0)},async max(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return P?.m},async min(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return P?.m},lockForUpdate(){return y+=" FOR UPDATE",q=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,q=null,this},withCTE(a,o){return F(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},withRecursive(a,o){return F(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},execute(){return te(k(),"select",{signal:ee,timeoutMs:j})},values(){return k().values()},toParams(){return[...f]},__rawState(){return{sql:Ze(W()),params:[...f]}},__hasPredicate(){return A.length>0||v},raw(){return k().raw()},get rows(){return},get row(){return},cancel(){try{k().cancel()}catch{}}},{get(a,o,u){let T=Reflect.get(a,o,u);if(T!==void 0)return T;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let S=o.startsWith("orWhere"),O=o.startsWith("andWhere"),P=`${String(h)}|${o}`,L=He.get(P);if(L===void 0){let x=o.replace(/^(?:or|and)?where/i,"");if(!x)He.set(P,""),L="";else{let C=x.charAt(0).toLowerCase()+x.slice(1),Z=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=U?Object.keys(U[String(h)]?.columns??{}):[];L=[Z,C,C.toLowerCase()].find((we)=>ae.includes(we))??Z,He.set(P,L)}}if(L==="")return()=>u;let M=L;return(x)=>{if(Array.isArray(x)){let C=s(x.length,f.length+1);I(S?"OR":O?"AND":"WHERE",`${M} IN (${C})`),f.push(...x)}else{let C=t(f.length+1);I(S?"OR":O?"AND":"WHERE",`${M} = ${C}`),f.push(x)}return u}}return Reflect.get(a,o,u)}})}return{configure(h){return Pe(h),this},id(h){if(!ye.IDENTIFIER.test(h))throw Error(`[query-builder] Invalid identifier: '${h}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(String(h))},ids(...h){for(let g of h)if(!ye.IDENTIFIER.test(g))throw Error(`[query-builder] Invalid identifier: '${g}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(h)},select(h,...g){return Je(h,g)},selectFrom(h){return Je(h)},selectFromSub(h,g){function d(k){return()=>{throw Error(`[query-builder] selectFromSub(...).${k}() is not supported. Apply ${k}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}F(String(g),"selectFromSub(alias)");let y=typeof h.__rawState==="function"?h.__rawState():null,A=h.toSQL(),f=y?.sql??(typeof A==="string"?A:A?.sql??String(A)),X=y?.params??(Array.isArray(A?.values)?A.values:[]),v=`SELECT * FROM (${f}) AS ${String(g)}`,K=(k,J,R,I)=>{let V=[...k],W=(G,H,z)=>{F(G,"selectFromSub where(column)");let Q=$e(H,"selectFromSub where(operator)");if(Q==="in"||Q==="not in"){let ee=Array.isArray(z)?z:[z],se=s(ee.length,V.length+1);return V.push(...ee),`${G} ${Q.toUpperCase()} (${se})`}let j=t(V.length+1);return V.push(z),`${G} ${Q} ${j}`},_;if(typeof J==="string"&&R!==void 0)_=W(J,R,I);else if(Array.isArray(J)&&J.length===3)_=W(J[0],J[1],J[2]);else if(J&&typeof J==="object"){let G=Object.entries(J).map(([H,z])=>W(H,"=",z));_=G.length>1?`(${G.join(" AND ")})`:G[0]}else return{clause:null,params:k};return{clause:_,params:V}};function q(k,J,R,I=""){let V=D(J),W=V?`${k} WHERE ${V}${I}`:`${k}${I}`,_=()=>R.length>0?N(W,R):N(W),G=(Q,j,ee,se)=>{let ce=K(R,j,ee,se);return ce.clause===null?q(k,J,R,I):q(k,[...J,{conn:Q,sql:ce.clause}],ce.params,I)},H=(Q,j)=>{let ee=[],se=[...R],ce=(ke)=>(ct,ge,Qe)=>{let Ke=K(se,ct,ge,Qe);if(Ke.clause!==null)ee.push({conn:ke,sql:Ke.clause}),se=Ke.params;return Te},Te={where:ce("AND"),andWhere:ce("AND"),orWhere:ce("OR")};j(Te);let qe=D(ee);if(!qe)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return q(k,[...J,{conn:Q,sql:`(${qe})`}],se,I)},z={distinct(){return q(k.replace(/^SELECT\s+/i,"SELECT DISTINCT "),J,R,I)},distinctOn(...Q){let j=Q.map(String).join(", ");return q(k.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${j}) `),J,R,I)},selectRaw(Q,...j){let ee=ze(Q,"selectFromSub.selectRaw(fragment)",j),se=k.indexOf(" FROM "),ce=se!==-1?`${k.slice(0,se)}, ${ee}${k.slice(se)}`:`${k}, ${ee}`;return q(ce,J,R,I)},$call(Q){return Q(this)??this},where(Q,j,ee){return G("AND",Q,j,ee)},andWhere(Q,j,ee){return G("AND",Q,j,ee)},orWhere(Q,j,ee){return G("OR",Q,j,ee)},whereGroup(Q){return H("AND",Q)},orWhereGroup(Q){return H("OR",Q)},orderBy(Q,j="asc"){F(String(Q),"selectFromSub.orderBy(column)");let ee=j==="asc"?"ASC":"DESC",se=ye.ORDER_BY.test(I)?`${I}, ${Q} ${ee}`:`${I} ORDER BY ${Q} ${ee}`;return q(k,J,R,se)},limit(Q){if(!Number.isInteger(Q)||Q<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${Q}`);let j=ye.LIMIT.test(I)?I.replace(ye.LIMIT,` LIMIT ${Q}`):`${I} LIMIT ${Q}`;return q(k,J,R,j)},offset(Q){if(!Number.isInteger(Q)||Q<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${Q}`);let j=ye.OFFSET.test(I)?I.replace(ye.OFFSET,` OFFSET ${Q}`):`${I} OFFSET ${Q}`;return q(k,J,R,j)},toSQL(){return Ie(_(),W)},async execute(){return te(_(),"select")},async executeTakeFirst(){let Q=await te(_(),"select");return Array.isArray(Q)?Q[0]:Q},async executeTakeFirstOrThrow(){let Q=await te(_(),"select"),j=Array.isArray(Q)?Q[0]:Q;if(!j)throw Error("Record not found");return j},async get(){return te(_(),"select")},async first(){let Q=await te(_(),"select");return Array.isArray(Q)?Q[0]:Q},async firstOrFail(){let Q=await te(_(),"select"),j=Array.isArray(Q)?Q[0]:Q;if(!j)throw Error("No rows found");return j},async count(){let Q=R.length>0?N(`SELECT COUNT(*) as c FROM (${W}) as sub`,R):N(`SELECT COUNT(*) as c FROM (${W}) as sub`),j=await te(Q,"select");return Number(j?.[0]?.c??0)},async exists(){let Q=R.length>0?N(`SELECT EXISTS(${W}) as e`,R):N(`SELECT EXISTS(${W}) as e`),j=await te(Q,"select");return Boolean(j?.[0]?.e)},async doesntExist(){return!await z.exists()},values(){return _().values()},raw(){return _().raw()},cancel(){try{_().cancel()}catch{}},whereRaw:d("whereRaw"),whereColumn:d("whereColumn"),orWhereColumn:d("orWhereColumn"),whereIn:d("whereIn"),orWhereIn:d("orWhereIn"),whereNotIn:d("whereNotIn"),orWhereNotIn:d("orWhereNotIn"),whereLike:d("whereLike"),whereILike:d("whereILike"),orWhereLike:d("orWhereLike"),orWhereILike:d("orWhereILike"),whereNotLike:d("whereNotLike"),whereNotILike:d("whereNotILike"),orWhereNotLike:d("orWhereNotLike"),orWhereNotILike:d("orWhereNotILike"),whereAny:d("whereAny"),whereAll:d("whereAll"),whereNone:d("whereNone"),whereNested:d("whereNested"),orWhereNested:d("orWhereNested"),whereDate:d("whereDate"),whereBetween:d("whereBetween"),whereNotBetween:d("whereNotBetween"),whereJsonContains:d("whereJsonContains"),whereJsonPath:d("whereJsonPath"),whereNull:d("whereNull"),orWhereNull:d("orWhereNull"),whereNotNull:d("whereNotNull"),orWhereNotNull:d("orWhereNotNull"),whereExists:d("whereExists"),orWhereExists:d("orWhereExists"),orWhereBetween:d("orWhereBetween"),orWhereRaw:d("orWhereRaw"),whereJsonDoesntContain:d("whereJsonDoesntContain"),whereJsonContainsKey:d("whereJsonContainsKey"),whereJsonDoesntContainKey:d("whereJsonDoesntContainKey"),whereJsonLength:d("whereJsonLength"),join:d("join"),joinSub:d("joinSub"),innerJoin:d("innerJoin"),leftJoin:d("leftJoin"),leftJoinSub:d("leftJoinSub"),rightJoin:d("rightJoin"),crossJoin:d("crossJoin"),crossJoinSub:d("crossJoinSub"),groupBy:d("groupBy"),groupByRaw:d("groupByRaw"),having:d("having"),havingRaw:d("havingRaw"),addSelect:d("addSelect"),select:d("select"),selectAll:d("selectAll"),orderByDesc:d("orderByDesc"),inRandomOrder:d("inRandomOrder"),reorder:d("reorder"),orderByRaw:d("orderByRaw"),union:d("union"),unionAll:d("unionAll"),forPage:d("forPage"),selectAllRelations:d("selectAllRelations"),with:d("with"),value:d("value"),pluck:d("pluck"),cursorPaginate:d("cursorPaginate"),paginate:d("paginate"),simplePaginate:d("simplePaginate"),chunk:d("chunk"),chunkById:d("chunkById"),eachById:d("eachById"),avg:d("avg"),sum:d("sum"),max:d("max"),min:d("min"),find:d("find"),findOrFail:d("findOrFail"),findMany:d("findMany"),latest:d("latest"),oldest:d("oldest"),lazy:d("lazy"),lazyById:d("lazyById"),pipe:(Q)=>Q(z),when:d("when"),tap:()=>z,dump:()=>z,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>_().simple(),toText:()=>W,toParams:()=>[...R],withTimeout:()=>z,abort:()=>z,lockForUpdate:()=>z,sharedLock:()=>z,withCTE:()=>z,withRecursive:()=>z,cache:()=>z,clone:()=>z,withTrashed:()=>z,onlyTrashed:()=>z,scope:()=>z,get rows(){return[]},get row(){return}};return z}return q(v,[],X)},insertInto(h){let g,d="",y=[],A=[],f=!1,X=()=>K?[]:{changes:0,lastInsertRowid:0},v=()=>{let I=async()=>{return},V=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>Ie(null,""),execute:async()=>[],get:async()=>[],first:I,executeTakeFirst:I,firstOrFail:V,executeTakeFirstOrThrow:V}},K=e.dialect==="postgres",q=(I)=>{let W=I.flat(2).map(String).filter(Boolean),_=W.length>0&&!W.includes("*")?W.map((z)=>k(z)).join(", "):"*",G=async()=>{let z=await te(N(d,y),"insert"),Q=Number(z?.lastInsertRowid??0),j=Math.max(1,Number(z?.affectedRows??1)),ee=A.filter((Te)=>Te!==void 0&&Te!==null),se=Q>0?N(`SELECT ${_} FROM ${k(String(h))} WHERE ${k("id")} >= ? AND ${k("id")} < ? ORDER BY ${k("id")} ASC`,[Q,Q+j]):ee.length>0?N(`SELECT ${_} FROM ${k(String(h))} WHERE ${k("id")} IN (${ee.map(()=>"?").join(", ")}) ORDER BY ${k("id")} ASC`,ee):null;if(!se)return[];let ce=await se.execute();return Array.isArray(ce)?ce:[]},H=async()=>(await G())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ie(N(d,y),d),execute:G,get:G,first:H,executeTakeFirst:H,async firstOrFail(){let z=await H();if(!z)throw Error("Insert with RETURNING returned no rows");return z},async executeTakeFirstOrThrow(){let z=await H();if(!z)throw Error("Insert with RETURNING returned no rows");return z}}},k=K?(I)=>`"${String(I).replace(/"/g,'""')}"`:n(e.dialect)?(I)=>`\`${String(I).replace(/`/g,"``")}\``:(I)=>`"${String(I).replace(/"/g,'""')}"`,J=K?"postgres":n(e.dialect)?"mysql":"sqlite",R=K?(I)=>`$${I+1}`:(I)=>"?";return{values(I){let V=Ee(String(h),Array.isArray(I)?I:[I]),W=V.length;if(A=V.map((se)=>se?.id),W===0)return f=!0,g=null,d="",y.length=0,this;f=!1;let _=V[0],G=Object.keys(_),H=G.length,z=W*H;y.length=z;let Q=W===1&&H>0&&typeof h==="string",j=Q?oe?.get(h):void 0,ee=j?.quoteStyle===J&&j.columns.length===H;if(ee){for(let se=0;se<H;se++)if(j.columns[se]!==G[se]){ee=!1;break}}if(ee){d=j.sql;for(let se=0;se<H;se++)y[se]=_[G[se]]}else if(W===1)if(!K){let se=k(G[0]),ce="?";y[0]=_[G[0]];for(let Te=1;Te<H;Te++)se+=`,${k(G[Te])}`,ce+=",?",y[Te]=_[G[Te]];d=`INSERT INTO ${k(h)}(${se})VALUES(${ce})`}else{let se=G.map((ce)=>k(ce)).join(",");d=`INSERT INTO ${k(h)}(${se})VALUES(`;for(let ce=0;ce<H;ce++){if(ce>0)d+=",";d+=R(ce),y[ce]=_[G[ce]]}d+=")"}else{let se=G.map((Te)=>k(Te)).join(",");d=`INSERT INTO ${k(h)}(${se})VALUES`;let ce=0;for(let Te=0;Te<W;Te++){let qe=V[Te];if(Te===0)d+="(";else d+="),(";for(let ke=0;ke<H;ke++){if(ke>0)d+=",";d+=R(ce),y[ce++]=qe[G[ke]]}}d+=")"}if(Q&&!ee&&d.length<=8192){if(oe??=new Map,oe.size>=32&&!oe.has(h)){let se=oe.keys().next().value;if(se!==void 0)oe.delete(se)}oe.set(h,{columns:G,quoteStyle:J,sql:d})}if(!B._prepareStatement)g=N(d,y);return this},returning(...I){if(f)return v();if(n(e.dialect))return q(I);let V=`${d} RETURNING ${I.join(", ")}`,W=N(V,y),_=async()=>{let G=await te(W,"insert");return Array.isArray(G)?G[0]:G};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ie(W,V),execute:()=>te(W,"insert"),get:()=>te(W,"insert"),first:_,executeTakeFirst:_,async firstOrFail(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G},async executeTakeFirstOrThrow(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G}}},toSQL(){if(f)return Ie(null,"");if(!g)g=N(d,y);return Ie(g,d)},execute(){if(f)return Promise.resolve(X());let I=me();if(!(I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||I.beforeCreate||I.afterCreate||lt(I)))){let W=B._prepareStatement;if(W){let _=W(d);return y.length>0?_.run(...y):_.run()}}if(!g)g=N(d,y);return te(g,"insert")},async executeTakeFirst(){if(f)return X();if(!g)g=N(d,y);return await te(g,"insert")},async executeTakeFirstOrThrow(){if(f)throw Error("Insert failed");if(!g)g=N(d,y);let I=await te(g,"insert");if(!I)throw Error("Insert failed");return I},returningAll(){return this.returning("*")}}},updateTable(h){let g,d=[],y=(v)=>{let K=String(v);if(n(e.dialect))return`\`${K.replace(/`/g,"``")}\``;return`"${K.replace(/"/g,'""')}"`},A=`UPDATE ${y(String(h))}`,f=!1,X=(v)=>{A=`${A} ${f?"AND":"WHERE"} ${v}`,f=!0};return{set(v){let K=Ee(String(h),[v])[0],q=Object.keys(K),k=q.length,J=Array.from({length:k});for(let R=0;R<k;R++){let I=q[R],V=K[I];if(ot(V))it(`set(${I})`);if(We(V))J[R]=`${y(I)} = ${V.raw}`;else if(Ge(V)){let W=Ye(V,d.length+1);J[R]=`${y(I)} = ${W.text}`,d.push(...W.parameters)}else J[R]=`${y(I)} = ${t(d.length+1)}`,d.push(V)}return A=`${A} SET ${J.join(", ")}`,g=N(A,d),this},where(v,K,q){if(K!==void 0&&(typeof v==="string"||We(v)||Ge(v))){let k=$e(K,"updateTable.where"),J;if(typeof v==="string")J=y(v);else if(We(v))J=v.raw;else{let V=Ye(v,d.length+1);J=V.text,d.push(...V.parameters)}if(k.toLowerCase()==="in"||k.toLowerCase()==="not in"){let V=Array.isArray(q)?q:[q],W=s(V.length,d.length+1);return X(`${J} ${k.toUpperCase()} (${W})`),d.push(...V),g=N(A,d),this}let R=Ue(J,k,q,"updateTable.where");if(R)return X(R),g=N(A,d),this;let I=d.length+1;return X(`${J} ${k} ${t(I)}`),d.push(q),g=N(A,d),this}if(Array.isArray(v)){let[k,J,R]=v,I=$e(J,"updateTable.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(R)?R:[R],G=s(_.length,d.length+1);return X(`${y(String(k))} ${I.toUpperCase()} (${G})`),d.push(..._),g=N(A,d),this}let V=Ue(y(String(k)),I,R,"updateTable.where");if(V)return X(V),g=N(A,d),this;let W=d.length+1;return X(`${y(String(k))} ${I} ${t(W)}`),d.push(R),g=N(A,d),this}if(ot(v))it("updateTable.where(expr)");if(We(v))return X(v.raw),g=N(A,d),this;if(Ge(v)){let k=Ye(v,d.length+1);return X(k.text),d.push(...k.parameters),g=N(A,d),this}if(v&&typeof v==="object"){let k=Object.keys(v);if(k.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let J=k.map((R)=>mt(y(R),v[R],d));return X(J.join(" AND ")),g=N(A,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${v===null?"null":typeof v}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(v){return X(`${y(String(v))} IS NULL`),g=N(A,d),this},whereNotNull(v){return X(`${y(String(v))} IS NOT NULL`),g=N(A,d),this},returning(...v){let K=this,q=()=>`${A} RETURNING ${v.join(", ")}`,k=()=>d.length>0?N(q(),d):N(q()),J=async()=>{let _=/\sWHERE\s/i.test(A),G=_?A.slice(A.search(/\sWHERE\s/i)+1):"",H=d.slice(d.length-(G.match(/\?|\$\d+/g)?.length??0)),z=y("id"),Q=await(H.length>0?N(`SELECT ${z} FROM ${y(String(h))}${_?` ${G}`:""}`,H):N(`SELECT ${z} FROM ${y(String(h))}${_?` ${G}`:""}`)).execute().catch(()=>[]),j=(Array.isArray(Q)?Q:[]).map((ce)=>ce?.id).filter((ce)=>ce!==void 0&&ce!==null);if(await te(d.length>0?N(A,d):N(A),"update"),j.length===0)return[];let ee=`SELECT ${v.join(", ")} FROM ${y(String(h))} WHERE ${z} IN (${j.map(()=>"?").join(", ")})`,se=await N(ee,j).execute();return Array.isArray(se)?se:[]},R=()=>n(e.dialect)?J():te(k(),"update"),I=async()=>{let _=await R();return Array.isArray(_)?_[0]:_},V=(_)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${_}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},W={where:(..._)=>(K.where(..._),W),andWhere:(..._)=>(K.where(..._),W),whereNull:(..._)=>(K.whereNull(..._),W),whereNotNull:(..._)=>(K.whereNotNull(..._),W),orWhere:V("orWhere"),orderBy:V("orderBy"),limit:V("limit"),offset:V("offset"),toSQL:()=>Ie(k(),q()),execute:R,get:R,first:I,executeTakeFirst:I,async firstOrFail(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _},async executeTakeFirstOrThrow(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _}};return W},toSQL(){if(!g)g=d.length>0?N(A,d):N(A);return Ie(g,A)},async execute(){let v=await te(g,"update");return Le(v)},async executeTakeFirst(){return{numUpdatedRows:Le(await te(g,"update"))}},async executeTakeFirstOrThrow(){let v=Le(await te(g,"update"));if(v===0)throw Error("No rows updated");return{numUpdatedRows:v}},returningAll(){return this.returning("*")}}},deleteFrom(h){let g=(k)=>{let J=String(k);if(n(e.dialect))return`\`${J.replace(/`/g,"``")}\``;return`"${J.replace(/"/g,'""')}"`},y=`DELETE FROM ${g(String(h))}`,A=null,f=[],X=null,v=!1,K=(k)=>{y+=` ${v?"AND":"WHERE"} ${k}`,v=!0},q=()=>{if(A===null)A=f.length>0?N(y,f):N(y);return A};return{where(k,J,R){if(X=k,typeof k==="string"&&J!==void 0){let I=$e(J,"deleteFrom.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(R)?R:[R],G=s(_.length,f.length+1);return K(`${g(k)} ${I.toUpperCase()} (${G})`),f.push(..._),A=null,this}let V=Ue(g(k),I,R,"deleteFrom.where");if(V)return K(V),A=null,this;let W=f.length+1;return K(`${g(k)} ${I} ${t(W)}`),f.push(R),A=null,this}if(Array.isArray(k)){let[I,V,W]=k,_=$e(V,"deleteFrom.where");if(_.toLowerCase()==="in"||_.toLowerCase()==="not in"){let z=Array.isArray(W)?W:[W],Q=s(z.length,f.length+1);return K(`${g(String(I))} ${_.toUpperCase()} (${Q})`),f.push(...z),A=null,this}let G=Ue(g(String(I)),_,W,"deleteFrom.where");if(G)return K(G),A=null,this;let H=f.length+1;return K(`${g(String(I))} ${_} ${t(H)}`),f.push(W),A=null,this}if(ot(k))it("deleteFrom.where(expr)");if(We(k))return K(k.raw),A=null,this;if(Ge(k)){let I=Ye(k,f.length+1);return K(I.text),f.push(...I.parameters),A=null,this}if(k&&typeof k==="object"){let I=Object.keys(k);if(I.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let V=I.map((W)=>mt(g(W),k[W],f));return K(V.join(" AND ")),A=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${k===null?"null":typeof k}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(k){return K(`${g(String(k))} IS NULL`),A=null,this},whereNotNull(k){return K(`${g(String(k))} IS NOT NULL`),A=null,this},returning(...k){let J=this,R=()=>`${y} RETURNING ${k.join(", ")}`,I=()=>f.length>0?N(R(),f):N(R()),V=async()=>{await me()?.beforeDelete?.({table:String(h),where:X});let H=n(e.dialect)?await(async()=>{let z=y.slice(y.search(/\sFROM\s/i)+1),Q=`SELECT ${k.join(", ")} ${z}`,j=await(f.length>0?N(Q,f):N(Q)).execute();return await te(f.length>0?N(y,f):N(y),"delete"),Array.isArray(j)?j:[]})():await te(I(),"delete");try{await me()?.afterDelete?.({table:String(h),where:X,result:H})}catch{}return H},W=async()=>{let H=await V();return Array.isArray(H)?H[0]:H},_=(H)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${H}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},G={where:(...H)=>(J.where(...H),G),andWhere:(...H)=>(J.where(...H),G),whereNull:(...H)=>(J.whereNull(...H),G),whereNotNull:(...H)=>(J.whereNotNull(...H),G),orWhere:_("orWhere"),orderBy:_("orderBy"),limit:_("limit"),offset:_("offset"),toSQL:()=>Ie(I(),R()),execute:()=>V(),get:()=>V(),first:W,executeTakeFirst:W,async firstOrFail(){let H=await W();if(!H)throw Error("Delete with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await W();if(!H)throw Error("Delete with RETURNING returned no rows");return H}};return G},toSQL(){return Ie(q(),y)},async execute(){try{await me()?.beforeDelete?.({table:String(h),where:X})}catch(J){throw J}let k=Le(await te(q(),"delete"));try{await me()?.afterDelete?.({table:String(h),where:X,result:k})}catch{}return k},async executeTakeFirst(){return{numDeletedRows:Le(await te(q(),"delete"))}},async executeTakeFirstOrThrow(){let k=Le(await te(q(),"delete"));if(k===0)throw Error("No rows deleted");return{numDeletedRows:k}},returningAll(){return this.returning("*")}}},table(h){let g=this;return{insert(d){return g.insertInto(h).values(d)},update(d){return g.updateTable(h).set(d)},delete(){return g.deleteFrom(h)},select(...d){if(d.length===0)return g.selectFrom(h);return g.select(h,...d)}}},sql:B,raw(h,...g){if(typeof h==="string")return Wt(h,g);return B(h,...g)},simple(h,...g){return B(h,...g).simple()},async advisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_lock($1)",[g]);await te(d,"raw");return}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, -1) AS ok",[g]);await te(d,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_try_advisory_lock($1) as ok",[g]),y=await te(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, 0) AS ok",[g]),y=await te(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_unlock($1) as ok",[g]),y=await te(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT RELEASE_LOCK(?) AS ok",[g]),y=await te(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(h,g){return Kt(h,g),B.unsafe(h,g)},deferInsert:B.deferInsert?.bind(B),flushDeferredInserts:B.flushDeferredInserts?.bind(B),file(h,g){return B.file(h,g)},async reserve(){let h=await r.reserve(),g=i({sql:h,meta:w,schema:U,hooks:p?.hooks});return g.release=()=>h.release(),g},async close(h){await r.close(h)},async listen(h,g){},async unlisten(h){},async notify(h,g){},async copyTo(h,g){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(h,g,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let h=N("SELECT 1");return await te(h,"select"),!0}catch{return!1}},async waitForReady(h){let g=Math.max(1,h?.attempts??10),d=Math.max(10,h?.delayMs??100);for(let y=0;y<g;y++){if(await this.ping())return;await new Promise((A)=>setTimeout(A,d))}throw Error("Database not ready after waiting")},async transaction(h,g){let y={...p?.txDefaults,...g},A=p?.sql??r,f=p?.inTransaction===!0,X=f&&typeof A?.savepoint==="function"?"savepoint":"begin",v=async(J)=>{y.logger?.({type:"start",attempt:J});let R=Date.now();return await A[X](async(I)=>{let V=i({sql:I,meta:w,schema:U,hooks:p?.hooks,inTransaction:!0});if(y?.isolation&&!f){let G=y.isolation,H=G==="read committed"?"READ COMMITTED":G==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${H}`);else if(n(e.dialect))await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${H}`);else if(G!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${G}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await I.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await I.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let W=await h(V),_=Date.now()-R;return y.logger?.({type:"commit",attempt:J,durationMs:_}),W})},K=Math.max(0,y?.retries??0),q=0,k;for(;;)try{k=await v(q+1);break}catch(J){let R=Vt(J)||Gt(J,y.sqlStates);if(q<K&&R){q++,y?.onRetry?.(q,J);let I=nn(q,y.backoff);if(I>0)await Yt(I);continue}try{y.onRollback?.(J)}catch{}try{y.afterRollback?.()}catch{}throw J}return await y.afterCommit?.(),k},async savepoint(h){if(p?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let g=B;if(!g||typeof g.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await g.savepoint(async(d)=>{let y=i({sql:d,meta:w,schema:U,hooks:p?.hooks,inTransaction:!0});return await h(y)})},async beginDistributed(h,g){return await(p?.sql??r).beginDistributed(h,async(A)=>{let f=i({sql:A,meta:w,schema:U,hooks:p?.hooks});return await g(f)})},async commitDistributed(h){await r.commitDistributed(h)},async rollbackDistributed(h){await r.rollbackDistributed(h)},setTransactionDefaults(h){p={...p,txDefaults:{...p?.txDefaults,...h}}},transactional(h,g){return(...d)=>this.transaction((y)=>h(y,...d),g)},async insertOrIgnore(h,g){let d=Array.isArray(g)?g:[g];if(!d.length)return;let{colsSql:y,valuesSql:A,params:f}=gt(d),X=De(String(h)),v=n(e.dialect)?`INSERT IGNORE INTO ${X} (${y}) VALUES ${A}`:`INSERT INTO ${X} (${y}) VALUES ${A} ON CONFLICT DO NOTHING`;return N(v,f).execute()},async insertGetId(h,g,d="id"){let{colsSql:y,valuesSql:A,params:f}=gt([g]),X=De(String(h));if(n(e.dialect)){await N(`INSERT INTO ${X} (${y}) VALUES ${A}`,f).execute();let[K]=await N("SELECT LAST_INSERT_ID() as id").execute();return K?.id}if(e.dialect==="sqlite"){let K=await N(`INSERT INTO ${X} (${y}) VALUES ${A}`,f).execute();if(K?.lastInsertRowid!=null)return K.lastInsertRowid;let[q]=await N("SELECT last_insert_rowid() as id").execute();return q?.id}let[v]=await N(`INSERT INTO ${X} (${y}) VALUES ${A} RETURNING ${De(String(d))} as id`,f).execute();return v?.id},async updateOrInsert(h,g,d){let y=De(String(h)),A=Object.keys(g),f=1,X=A.map((R)=>`${De(R)} = ${t(f++)}`).join(" AND "),v=A.map((R)=>g[R]);if((await N(`SELECT 1 FROM ${y} WHERE ${X} LIMIT 1`,v).execute()).length){let R=Object.keys(d),I=1,V=R.map((G)=>`${De(G)} = ${t(I++)}`).join(", "),W=A.map((G)=>`${De(G)} = ${t(I++)}`).join(" AND "),_=[...R.map((G)=>d[G]),...A.map((G)=>g[G])];return await N(`UPDATE ${y} SET ${V} WHERE ${W}`,_).execute(),!0}let{colsSql:q,valuesSql:k,params:J}=gt([{...g,...d}]);return await N(`INSERT INTO ${y} (${q}) VALUES ${k}`,J).execute(),!0},async upsert(h,g,d,y){let A=d.map((V)=>String(V)),f=(y??[]).map((V)=>String(V)),X=g;if(!X.length)return;let{colsSql:v,valuesSql:K,params:q}=gt(X),k=De(String(h)),J=`INSERT INTO ${k} (${v}) VALUES ${K}`;if(n(e.dialect)){if(f.length===0)return N(`INSERT IGNORE INTO ${k} (${v}) VALUES ${K}`,q).execute();let V=f.map((W)=>`${De(W)} = VALUES(${De(W)})`).join(", ");return N(`${J} ON DUPLICATE KEY UPDATE ${V}`,q).execute()}let R=A.map(De).join(", ");if(f.length===0)return N(`${J} ON CONFLICT (${R}) DO NOTHING`,q).execute();let I=f.map((V)=>`${De(V)} = EXCLUDED.${De(V)}`).join(", ");return N(`${J} ON CONFLICT (${R}) DO UPDATE SET ${I}`,q).execute()},async save(h,g){let d=w?.primaryKeys[String(h)]??"id",y=g[d];if(y!=null)if(await this.selectFrom(h).find(y)){await this.updateTable(h).set(g).where({[d]:y}).execute();let f=await this.selectFrom(h).find(y);if(!f)throw Error("save() failed to retrieve updated row");return f}else return await this.create(h,g);return await this.create(h,g)},async remove(h,g){return await this.deleteFrom(h).where({id:g}).execute()},async find(h,g){return await this.selectFrom(h).find(g)},async findOrFail(h,g){return await this.selectFrom(h).findOrFail(g)},async findMany(h,g){return await this.selectFrom(h).findMany(g)},async latest(h,g){return await this.selectFrom(h).latest(g).first()},async oldest(h,g){return await this.selectFrom(h).oldest(g).first()},skip(h,g){return this.selectFrom(h).offset(g)},async rawQuery(h){let g=Date.now();try{me()?.onQueryStart?.({sql:h,kind:"raw"});let d=await B.unsafe(h);return me()?.onQueryEnd?.({sql:h,durationMs:Date.now()-g,kind:"raw"}),d}catch(d){throw me()?.onQueryError?.({sql:h,error:d,durationMs:Date.now()-g,kind:"raw"}),d}},async create(h,g){let d=w?.primaryKeys[String(h)]??"id";try{await me()?.beforeCreate?.({table:String(h),data:g})}catch(y){throw y}if(e.dialect==="postgres"){let y=B`INSERT INTO ${B(String(h))} ${B(g)} RETURNING ${B(String(d))} as id`,[A]=await y.execute();if(!A?.id)throw console.error(`create() failed to get insert ID for table ${String(h)}`),console.error("Inserted values:",g),Error(`create() failed to get insert ID for table ${String(h)}`);let f=await this.selectFrom(h).find(A.id);if(!f)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`);try{await me()?.afterCreate?.({table:String(h),data:g,result:f})}catch{}return f}else{let y=await this.insertGetId(h,g,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(h)}`);let A=await this.selectFrom(h).find(y);if(!A)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`);try{await me()?.afterCreate?.({table:String(h),data:g,result:A})}catch{}return A}},async createMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,X=Array.from({length:f*A}),v=n(e.dialect)?(k)=>`\`${String(k).replace(/`/g,"``")}\``:(k)=>`"${String(k).replace(/"/g,'""')}"`,K=`INSERT INTO ${v(String(h))}(${y.map(v).join(",")})VALUES`,q=0;for(let k=0;k<f;k++){if(k>0)K+=",";K+="(";let J=g[k];for(let R=0;R<A;R++){if(R>0)K+=",";K+=t(q+1),X[q++]=J[y[R]]}K+=")"}return N(K,X).execute()},async insertMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,X=f*A,v=Array(X),K=e.dialect==="postgres",q;if(!K){let R=Array(A);for(let I=0;I<A;I++)R[I]="?";q=`(${R.join(",")})`}else q="";let k=Array(f+2);k[0]=`INSERT INTO ${h}(${y.join(",")})VALUES`;let J=0;if(!K){for(let R=0;R<f;R++){let I=g[R];k[R+1]=q;for(let V=0;V<A;V++)v[J++]=I[y[V]]}return N(k[0]+k.slice(1,f+1).join(","),v).execute()}for(let R=0;R<f;R++){let I=g[R],V=Array(A);for(let W=0;W<A;W++)V[W]=`$${J+1}`,v[J++]=I[y[W]];k[R+1]=`(${V.join(",")})`}return N(k[0]+k.slice(1,f+1).join(","),v).execute()},async updateMany(h,g,d){let y=Object.keys(d),A=y.length;if(A===0)return 0;let f=[],X=Array.from({length:A});for(let K=0;K<A;K++)X[K]=`${y[K]}=${t(K+1)}`,f.push(d[y[K]]);let v=`UPDATE ${h} SET ${X.join(",")}`;if(Array.isArray(g)){let K=$e(String(g[1]),"updateMany");v+=` WHERE ${g[0]} ${K} ${t(f.length+1)}`,f.push(g[2])}else if(We(g))v+=` WHERE ${g.raw}`;else if(Ge(g)){let K=Ye(g,f.length+1);v+=` WHERE ${K.text}`,f.push(...K.parameters)}else if(g&&typeof g==="object"&&Object.keys(g).length>0){let K=Object.keys(g).map((q)=>mt(q,g[q],f));v+=` WHERE ${K.join(" AND ")}`}else if(g&&typeof g==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${g===null?"null":typeof g}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return N(v,f).execute()},async deleteMany(h,g){if(!Array.isArray(g)||g.length===0)return 0;let d=w?.primaryKeys[String(h)]??"id",y=g.length;if(e.dialect==="postgres"){let f=Array(y);for(let X=0;X<y;X++)f[X]=`$${X+1}`;return N(`DELETE FROM ${h} WHERE ${d} IN (${f.join(",")})`,g).execute()}let A=Array(y);for(let f=0;f<y;f++)A[f]="?";return N(`DELETE FROM ${h} WHERE ${d} IN (${A.join(",")})`,g).execute()},async firstOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y)return y;return await this.create(h,{...g,...d})},async updateOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y){await this.updateTable(h).set(d).where(g).execute();let A=w?.primaryKeys[String(h)]??"id",f=y[A],X=f!=null?await this.selectFrom(h).find(f):await this.selectFrom(h).where(g).first();if(!X)throw Error("updateOrCreate() failed to retrieve updated row");return X}return await this.create(h,{...g,...d})},async count(h,g){let d=g?B(String(g)):B`*`,y=B`SELECT COUNT(${d}) as c FROM ${B(String(h))}`,[A]=await y.execute();return Number(A?.c??0)},async sum(h,g){let d=B`SELECT SUM(${B(String(g))}) as s FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(h,g){let d=B`SELECT AVG(${B(String(g))}) as a FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.a??0)},async min(h,g){let d=B`SELECT MIN(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},async max(h,g){let d=B`SELECT MAX(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},getRelationships(h){if(!w?.relations)return{};let g=w.relations[h];if(!g)return{};let d={};for(let[y,A]of Object.entries(g))if(A&&typeof A==="object"&&Object.keys(A).length>0)d[y]=A;return d},hasRelationship(h,g){if(!w?.relations)return!1;let d=w.relations[h];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(g in y))},getRelationshipType(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A)return y;return null},getRelationshipTarget(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A){let f=A[g];if(typeof f==="string")return w.modelToTable[f]||f;else if(f&&typeof f==="object"){if("model"in f)return w.modelToTable[f.model]||f.model;if("target"in f)return w.modelToTable[f.target]||f.target}}return null}}}function Ce(){bt.clear()}function Re(p){bt.setMaxSize(p)}
|
|
3
|
-
export{E,Nn,Jt,c,$t,xt,i,Ce,Re};
|
package/dist/chunk-gcbgbkrf.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Xt,Zt,en,tn,nn,_t,rn,sn}from"./chunk-wfk6y67h.js";import"./chunk-5b51gpqw.js";import"./chunk-xk3qn91x.js";export{nn as clearModelRegistry,rn as defineModel,Zt as getAllModels,Xt as getModel,en as getModelRegistry,tn as hasModel,sn as registerBrowserModels,_t as registerModel};
|
package/dist/chunk-yzqfbfat.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ot,w,R,A}from"./chunk-7cgq9r40.js";import"./chunk-cfswsgdh.js";import"./chunk-vxh8ktv7.js";import"./chunk-wfk6y67h.js";import"./chunk-5b51gpqw.js";import"./chunk-xk3qn91x.js";export{R as executeMigration,w as generateMigration,A as resetDatabase,ot as saveMigrationSnapshot};
|