@cleverbrush/knex-schema 4.3.2 → 4.4.0
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/README.md +77 -0
- package/dist/SchemaQueryBuilder.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/dist/migration.d.ts +34 -0
- package/dist/operations/insert.d.ts +47 -3
- package/dist/types.d.ts +24 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -100,6 +100,65 @@ const newUsers = await query(db, UserSchema).insertMany([
|
|
|
100
100
|
]);
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
+
### Guarded upsert for imports
|
|
104
|
+
|
|
105
|
+
Use `onConflict().merge()` when an import or sync job should insert a row if it
|
|
106
|
+
does not exist, but update it only when the incoming data is newer than the row
|
|
107
|
+
already stored in PostgreSQL.
|
|
108
|
+
|
|
109
|
+
In this example, products are imported from an external system. The `sku` is the
|
|
110
|
+
unique key. If the product already exists, the price is updated only when the
|
|
111
|
+
incoming `sourceUpdatedAt` timestamp is newer:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
await query(db, ProductSchema)
|
|
115
|
+
.onConflict(t => t.sku)
|
|
116
|
+
.merge(
|
|
117
|
+
{
|
|
118
|
+
sku: 'SKU-123',
|
|
119
|
+
price: 1999,
|
|
120
|
+
sourceUpdatedAt: new Date('2026-01-15T10:00:00Z'),
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
price: ({ excluded }) => excluded(t => t.price),
|
|
124
|
+
sourceUpdatedAt: ({ excluded }) =>
|
|
125
|
+
excluded(t => t.sourceUpdatedAt),
|
|
126
|
+
syncedAt: ({ knex }) => knex.fn.now(),
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
where: (qb, { column }) => {
|
|
130
|
+
qb.whereRaw('?? < excluded.??', [
|
|
131
|
+
column(t => t.sourceUpdatedAt),
|
|
132
|
+
column(t => t.sourceUpdatedAt),
|
|
133
|
+
]);
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
);
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
What each helper does:
|
|
140
|
+
|
|
141
|
+
- `excluded(t => t.price)` means "use the incoming value from the failed
|
|
142
|
+
insert", producing `excluded."price"` in SQL.
|
|
143
|
+
- `knex.fn.now()` sets `synced_at` to the database current timestamp.
|
|
144
|
+
- `column(t => t.sourceUpdatedAt)` resolves the schema property to the mapped
|
|
145
|
+
SQL column name, for example `source_updated_at`.
|
|
146
|
+
- `where` attaches a PostgreSQL `ON CONFLICT DO UPDATE WHERE ...` guard. If the
|
|
147
|
+
guard is false, PostgreSQL leaves the existing row unchanged.
|
|
148
|
+
|
|
149
|
+
Approximate SQL:
|
|
150
|
+
|
|
151
|
+
```sql
|
|
152
|
+
insert into "products" ("sku", "price", "source_updated_at")
|
|
153
|
+
values (?, ?, ?)
|
|
154
|
+
on conflict ("sku") do update set
|
|
155
|
+
"price" = excluded."price",
|
|
156
|
+
"source_updated_at" = excluded."source_updated_at",
|
|
157
|
+
"synced_at" = CURRENT_TIMESTAMP
|
|
158
|
+
where "source_updated_at" < excluded."source_updated_at"
|
|
159
|
+
returning *
|
|
160
|
+
```
|
|
161
|
+
|
|
103
162
|
### Update
|
|
104
163
|
|
|
105
164
|
```typescript
|
|
@@ -326,6 +385,12 @@ export const PostEntity = defineEntity(PostSchema)
|
|
|
326
385
|
The returned `Entity` carries the relation map in its type, so downstream `query(db, entity)`
|
|
327
386
|
calls (and `@cleverbrush/orm`'s `DbSet.include()`) get full inference.
|
|
328
387
|
|
|
388
|
+
For many-to-many replacement flows, use the link table directly: delete the
|
|
389
|
+
current links in a transaction, `insertMany()` the desired links, and use
|
|
390
|
+
`onConflict(...).ignore()` when inserts may race with another writer. This keeps
|
|
391
|
+
the framework primitive generic while still covering tag/category sync
|
|
392
|
+
workflows.
|
|
393
|
+
|
|
329
394
|
### Polymorphism (STI / CTI)
|
|
330
395
|
|
|
331
396
|
Mark a schema as polymorphic to support single-table or class-table inheritance — variants
|
|
@@ -346,12 +411,24 @@ See the `@cleverbrush/orm` docs for the full inheritance API (`.ofVariant()` etc
|
|
|
346
411
|
| `generateMigrationsForContext(entities, prevSnapshot)` | Diff entities against the snapshot and emit a TS migration source plus the next snapshot |
|
|
347
412
|
| `generateMigration(snapshotA, snapshotB)` | Lower-level snapshot-vs-snapshot diff |
|
|
348
413
|
| `diffSchema(schema, dbState)` / `applyDiff(knex, diff, table)` | Live-database diff/apply (used by `cb-orm db push`) |
|
|
414
|
+
| `validateEntitiesAgainstDatabase(knex, entities)` | Read-only live-database validation for CI drift checks |
|
|
349
415
|
| `introspectDatabase(knex, table)` / `tableExistsInDb(knex, table)` | Database introspection helpers |
|
|
350
416
|
| `generateCreateTable(schema)` / `generateCreatePolymorphicTables(schema)` | Knex-statement builders for fresh `CREATE TABLE` |
|
|
351
417
|
|
|
352
418
|
Most users invoke these indirectly through the [`cb-orm`](https://www.npmjs.com/package/@cleverbrush/orm-cli)
|
|
353
419
|
CLI (`cb-orm migrate generate`, `cb-orm db push`).
|
|
354
420
|
|
|
421
|
+
### Row typing helpers
|
|
422
|
+
|
|
423
|
+
Use `InferDatabaseRow<typeof Schema>` when a raw row or mapper can receive SQL
|
|
424
|
+
`NULL` for optional schema properties:
|
|
425
|
+
|
|
426
|
+
```typescript
|
|
427
|
+
import type { InferDatabaseRow } from '@cleverbrush/knex-schema';
|
|
428
|
+
|
|
429
|
+
type UserRow = InferDatabaseRow<typeof UserSchema>;
|
|
430
|
+
```
|
|
431
|
+
|
|
355
432
|
### Row-version optimistic concurrency
|
|
356
433
|
|
|
357
434
|
Mark a column as a row version with `.rowVersion()` to opt-in to optimistic concurrency
|
|
@@ -3,7 +3,7 @@ import { EXTRA_TYPE_BRAND, METHOD_LITERAL_BRAND, type ObjectSchemaBuilder } from
|
|
|
3
3
|
import type { Knex } from 'knex';
|
|
4
4
|
import { POLYMORPHIC_TYPE_BRAND } from './extension.js';
|
|
5
5
|
import type { ColumnRef, CursorPaginationResult, InsertType, JoinManySpec, JoinOneSpec, PaginationResult, SelectProjection, SelectSelector } from './types.js';
|
|
6
|
-
export { OnConflictBuilder } from './operations/insert.js';
|
|
6
|
+
export { OnConflictBuilder, type OnConflictMergeHelpers, type OnConflictMergeOptions, type OnConflictUpdateData, type OnConflictUpdateValue } from './operations/insert.js';
|
|
7
7
|
type ScopesOf<S> = S extends {
|
|
8
8
|
readonly [METHOD_LITERAL_BRAND]?: infer N;
|
|
9
9
|
} ? Extract<N, string> : never;
|
package/dist/index.d.ts
CHANGED
|
@@ -5,9 +5,9 @@ export type { EntityPropSelector, EntityRelationKeys, EntityRelations, EntitySch
|
|
|
5
5
|
export { defineEntity, Entity } from './entity.js';
|
|
6
6
|
export { any, array, boolean, COMPOSITE_PRIMARY_KEY_BRAND, date, dbExtension, ddlExtension, EXTRA_TYPE_BRAND, func, getColumnName, getPolymorphicVariantSchemas, getProjections, getTableName, getVariants, METHOD_LITERAL_BRAND, number, object, POLYMORPHIC_TYPE_BRAND, PRIMARY_KEY_BRAND, string, union } from './extension.js';
|
|
7
7
|
export { clearRow, MAPPERS, mapObject, mapValue } from './mappers.js';
|
|
8
|
-
export { applyDiff, diffSchema, entitySchemaToTableState, generateMigration, generateMigrationsForContext, introspectDatabase, isDiffEmpty, tableExistsInDb } from './migration.js';
|
|
8
|
+
export { applyDiff, diffSchema, type EntitySchemaValidationIssue, type EntitySchemaValidationResult, entitySchemaToTableState, generateMigration, generateMigrationsForContext, introspectDatabase, isDiffEmpty, tableExistsInDb, validateEntitiesAgainstDatabase } from './migration.js';
|
|
9
9
|
export { rawQuery } from './raw.js';
|
|
10
10
|
export type { BoundQuery } from './SchemaQueryBuilder.js';
|
|
11
11
|
export { createQuery, query, SchemaQueryBuilder } from './SchemaQueryBuilder.js';
|
|
12
12
|
export { entitiesToSnapshot, loadSnapshot, writeSnapshot } from './snapshot.js';
|
|
13
|
-
export type { AddColumnDiff, AddForeignKeyDiff, AddIndexDiff, AlterColumnDiff, ColumnRef, CursorPaginationResult, DatabaseCheckInfo, DatabaseColumnInfo, DatabaseForeignKeyInfo, DatabaseIndexInfo, DatabaseTableState, InsertType, JoinManySpec, JoinOneSpec, MigrationDiff, PaginationResult, PrimaryKeyOf, PrimaryKeyValueOf, RelationSpec, ResolvedVariantConfig, ResolvedVariantSpec, SchemaKeys, SchemaSnapshot, SelectProjection, SelectSelector, ValidatedJoinManySpec, ValidatedJoinOneSpec, ValidatedSpec, VariantStorageType, WithJoinedMany, WithJoinedOne } from './types.js';
|
|
13
|
+
export type { AddColumnDiff, AddForeignKeyDiff, AddIndexDiff, AlterColumnDiff, ColumnRef, CursorPaginationResult, DatabaseCheckInfo, DatabaseColumnInfo, DatabaseForeignKeyInfo, DatabaseIndexInfo, DatabaseTableState, InferDatabaseRow, InferDatabaseValue, InsertType, JoinManySpec, JoinOneSpec, MigrationDiff, PaginationResult, PrimaryKeyOf, PrimaryKeyValueOf, RelationSpec, ResolvedVariantConfig, ResolvedVariantSpec, SchemaKeys, SchemaSnapshot, SelectProjection, SelectSelector, ValidatedJoinManySpec, ValidatedJoinOneSpec, ValidatedSpec, VariantStorageType, WithJoinedMany, WithJoinedOne } from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as Hn,b as Yn,c as zn,d as Gn,e as Xn,f as Ke,g as Zn,h as et,i as nt,j as tt,k as at,l as ot,m as rt,n as st,o as it,p as Q,q as C,r as se,s as ie,t as j,u as ct,v as lt}from"./chunk-V4TH6K42.js";import{ObjectSchemaBuilder as ve,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as W}from"@cleverbrush/schema";var Qe=new WeakMap;function R(e){let n=Qe.get(e);if(n)return n;let a=e.introspect().properties??{},o=new Map,r=new Map;for(let s of Object.keys(a)){let c=a[s],l=Q(c,s);o.set(s,l),r.set(l,s)}let i={propToCol:o,colToProp:r};return Qe.set(e,i),i}function Ie(e,n,t){if(t.length===1)return e.raw("??->>?",[n,t[0]]);let a=`{${t.join(",")}}`;return e.raw("??#>>?",[n,a])}function K(e,n,t,a){if(typeof e=="string"){if(!e)throw new Error(`${t} must be a non-empty string`);if(e.includes(".")){let[i,...s]=e.split("."),{propToCol:c}=R(n),l=c.get(i)??i;if(!a)throw new Error(`${t}: a Knex instance is required to resolve nested JSON path '${e}'`);return Ie(a,l,s)}let{propToCol:o}=R(n);return o.get(e)??e}if(typeof e=="function"){let o=ve.getPropertiesFor(n),r=e(o);if(!r||typeof r!="object"||!(W in r))throw new Error(`${t} accessor must return a valid property descriptor`);let s=r[W].toJsonPointer();if(!s)throw new Error(`${t} accessor returned the root descriptor`);let c=s.slice(1).split("/").map(h=>h.replace(/~1/g,"/").replace(/~0/g,"~"));if(c.length===0)throw new Error(`${t} accessor returned the root descriptor`);let[l,...y]=c,{propToCol:u}=R(n),f=u.get(l)??l;if(y.length===0)return f;if(!a)throw new Error(`${t}: a Knex instance is required to resolve nested JSON path '${s}'`);return Ie(a,f,y)}throw new Error(`${t} must be a string or a property descriptor accessor function`)}function ce(e,n,t){if(typeof e=="string"){if(!e)throw new Error(`${t} must be a non-empty string`);return e}if(typeof e=="function"){let a=ve.getPropertiesFor(n),o=e(a);if(!o||typeof o!="object"||!(W in o))throw new Error(`${t} accessor must return a valid property descriptor`);let i=o[W].toJsonPointer();if(!i)throw new Error(`${t} accessor returned the root descriptor`);return i.slice(1).split("/")[0].replace(/~1/g,"/").replace(/~0/g,"~")}throw new Error(`${t} must be a string or a property descriptor accessor function`)}function J(e){let n=e.introspect(),t=n.properties??{},a=n.extensions??{},{propToCol:o,colToProp:r}=R(e),i=a.compositePrimaryKey;if(i&&i.length>0){let s=[],c=[];for(let l of i)o.has(l)?(s.push(l),c.push(o.get(l))):r.has(l)?(c.push(l),s.push(r.get(l))):(s.push(l),c.push(l));return{propertyKeys:s,columnNames:c}}for(let[s,c]of Object.entries(t))if((c.introspect?.().extensions??{}).primaryKey)return{propertyKeys:[s],columnNames:[o.get(s)??s]};return{propertyKeys:[],columnNames:[]}}function yt(e){let t=e.introspect().properties??{},{propToCol:a}=R(e);for(let[o,r]of Object.entries(t)){let s=(r.introspect?.()?.extensions??{}).rowVersion;if(s)return{propertyKey:o,columnName:a.get(o)??o,strategy:s.strategy??"increment"}}return null}function ut(e,n,t,a){if(a.columnType)return e.specificType(n,a.columnType);switch(t.type){case"string":{let o=a.maxLength??t.maxLength??void 0;return o?e.string(n,o):e.string(n)}case"number":return t.isInteger!==!1?e.integer(n):e.float(n);case"boolean":return e.boolean(n);case"date":return e.timestamp(n);case"object":return e.specificType(n,"jsonb");default:return e.specificType(n,"text")}}function mt(e,n,t){return n==="now"?e.defaultTo(t.fn.now()):n==="auto_increment"?e:typeof n=="object"&&n!==null&&n.raw?e.defaultTo(t.raw(n.raw)):e.defaultTo(n)}function le(e){let n=C(e),t=e.introspect(),a=t.extensions??{},o=new Set;return a.timestamps&&(o.add(a.timestamps.createdAt),o.add(a.timestamps.updatedAt)),a.softDelete&&o.add(a.softDelete.column),r=>{let i=r.schema.createTable(n,c=>{let l=t.properties??{};for(let[y,u]of Object.entries(l)){let f=Q(u,y),h=u.introspect(),g=h.extensions??{};if(h.type==="array"&&!g.columnType||o.has(f))continue;let m;if(g.primaryKey?.autoIncrement?m=c.increments(f):m=ut(c,f,h,g),g.primaryKey&&!g.primaryKey.autoIncrement&&(m=m.primary()),g.unique&&(m=m.unique(typeof g.unique=="string"?{indexName:g.unique}:void 0)),g.index&&(m=m.index(typeof g.index=="string"?g.index:void 0)),g.defaultTo!==void 0&&(m=mt(m,g.defaultTo,r)),h.isRequired&&!g.primaryKey?.autoIncrement?m=m.notNullable():h.isRequired||(m=m.nullable()),g.references){let d=m.references(g.references.column).inTable(g.references.table);g.onDelete&&d.onDelete(g.onDelete),g.onUpdate&&d.onUpdate(g.onUpdate)}g.check&&c.check(g.check)}for(let y of a.indexes??[])y.unique?c.unique(y.columns,{indexName:y.name??void 0}):c.index(y.columns,y.name??void 0);for(let y of a.uniques??[])c.unique(y.columns,{indexName:y.name??void 0});for(let y of a.checks??[])c.check(y);a.compositePrimaryKey&&c.primary(a.compositePrimaryKey);for(let y of a.rawColumns??[])c.specificType(y.name,y.definition);a.timestamps&&(c.timestamp(a.timestamps.createdAt).defaultTo(r.fn.now()).notNullable(),c.timestamp(a.timestamps.updatedAt).defaultTo(r.fn.now()).notNullable()),a.softDelete&&c.timestamp(a.softDelete.column).nullable()}),s=a.rawIndexes??[];return s.length>0?i.then(async()=>{for(let c of s)await r.raw(c)}):i}}function ye(e){let n=C(e),t=e.introspect(),a=t.extensions??{},o=t.properties??{},r=[],i=new Set;a.timestamps&&(i.add(a.timestamps.createdAt),i.add(a.timestamps.updatedAt)),a.softDelete&&i.add(a.softDelete.column);for(let[u,f]of Object.entries(o)){let h=Q(f,u),g=f.introspect(),m=g.extensions??{};if((g.type==="object"||g.type==="array")&&!m.columnType||i.has(h))continue;let d;m.primaryKey?.autoIncrement?d=` table.increments('${h}')`:d=` ${pt(h,g,m)}`,m.primaryKey&&!m.primaryKey.autoIncrement&&(d+=".primary()"),m.unique&&(typeof m.unique=="string"?d+=`.unique({ indexName: '${m.unique}' })`:d+=".unique()"),m.index&&(typeof m.index=="string"?d+=`.index('${m.index}')`:d+=".index()"),m.defaultTo!==void 0&&(d+=`.defaultTo(${ft(m.defaultTo)})`),g.isRequired&&!m.primaryKey?.autoIncrement?d+=".notNullable()":g.isRequired||(d+=".nullable()"),m.references&&(d+=`.references('${m.references.column}').inTable('${m.references.table}')`,m.onDelete&&(d+=`.onDelete('${m.onDelete}')`),m.onUpdate&&(d+=`.onUpdate('${m.onUpdate}')`)),r.push(d+";"),m.check&&r.push(` table.check(${JSON.stringify(m.check)});`)}for(let u of a.indexes??[]){let f=JSON.stringify(u.columns);u.unique?r.push(` table.unique(${f}${u.name?`, { indexName: '${u.name}' }`:""});`):r.push(` table.index(${f}${u.name?`, '${u.name}'`:""});`)}for(let u of a.uniques??[]){let f=JSON.stringify(u.columns);r.push(` table.unique(${f}${u.name?`, { indexName: '${u.name}' }`:""});`)}for(let u of a.checks??[])r.push(` table.check(${JSON.stringify(u)});`);a.compositePrimaryKey&&r.push(` table.primary(${JSON.stringify(a.compositePrimaryKey)});`);for(let u of a.rawColumns??[])r.push(` table.specificType('${u.name}', '${u.definition}');`);a.timestamps&&(r.push(` table.timestamp('${a.timestamps.createdAt}').notNullable().defaultTo(knex.fn.now());`),r.push(` table.timestamp('${a.timestamps.updatedAt}').notNullable().defaultTo(knex.fn.now());`)),a.softDelete&&r.push(` table.timestamp('${a.softDelete.column}').nullable();`);let c=(a.rawIndexes??[]).map(u=>` await knex.raw(${JSON.stringify(u)});`),l=` await knex.schema.createTable('${n}', (table) => {
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}
|
|
4
4
|
});`+(c.length>0?`
|
|
5
5
|
`+c.join(`
|
|
6
|
-
`):""),y=` await knex.schema.dropTableIfExists('${n}');`;return{up:l,down:y}}function
|
|
6
|
+
`):""),y=` await knex.schema.dropTableIfExists('${n}');`;return{up:l,down:y}}function pt(e,n,t){if(t.columnType)return`table.specificType('${e}', '${t.columnType}')`;switch(n.type){case"string":{let a=t.maxLength??n.maxLength??void 0;return a?`table.string('${e}', ${a})`:`table.string('${e}')`}case"number":return n.isInteger!==!1?`table.integer('${e}')`:`table.float('${e}')`;case"boolean":return`table.boolean('${e}')`;case"date":return`table.timestamp('${e}')`;case"object":return`table.specificType('${e}', 'jsonb')`;default:return`table.specificType('${e}', 'text')`}}function ft(e){return e==="now"?"knex.fn.now()":typeof e=="object"&&e!==null&&e.raw?`knex.raw('${String(e.raw).replace(/'/g,"\\'")}')`:typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:String(e)}function ht(e){let n=[le(e)],t=j(e);for(let a of t)a.getExtension("tableName")&&n.push(le(a));return n}import{ObjectSchemaBuilder as ue,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as H}from"@cleverbrush/schema";var Y=class e{schema;constructor(n){this.schema=n}_addRelation(n){let t=this.schema.getExtension?.("relations")??[],a=this.schema.withExtension("relations",[...t,n]);return new e(a)}hasOne(n,t,a,o){let r=this._resolvePropName(n,this.schema),i=this._resolveForeignSchema(r),s=this._resolvePropName(a,i);return this._addRelation({type:"hasOne",name:r,schema:i,foreignKey:s,optional:o?.optional})}hasMany(n,t,a){let o=this._resolvePropName(n,this.schema),r=this._resolveForeignSchema(o),i=this._resolvePropName(a,r);return this._addRelation({type:"hasMany",name:o,schema:r,foreignKey:i})}belongsTo(n,t,a,o){let r=this._resolvePropName(n,this.schema),i=this._resolveForeignSchema(r),s=this._resolvePropName(t,this.schema);return this._addRelation({type:"belongsTo",name:r,schema:i,foreignKey:s,optional:o?.optional})}belongsToMany(n,t){let a=this._resolvePropName(n,this.schema),o=this._resolveForeignSchema(a);return this._addRelation({type:"belongsToMany",name:a,schema:o,through:t})}discriminator(n){let t=typeof n=="string"?n:this._resolvePropName(n,this.schema),a=new e(this.schema);return a._variantBuilder={discKey:t,variants:{}},a}ctiVariant(n,t,a,o){let r=this._variantBuilder;if(!r)throw new Error("ctiVariant: call `.discriminator(...)` first to begin a polymorphic builder chain");let i=dt(t.schema,a),s={...r.variants,[n]:{schema:t.schema,storage:"cti",foreignKeyColumn:i,allowOrphan:o?.allowOrphan,relations:[...Pe(t),...ke(t.schema,o?.relations)]}};return this._withVariantBuilder(r.discKey,s)}stiVariant(n,t,a){let o=this._variantBuilder;if(!o)throw new Error("stiVariant: call `.discriminator(...)` first to begin a polymorphic builder chain");let r=t instanceof e,i=r?t.schema:t,s={...o.variants,[n]:{schema:i,storage:"sti",enforceCheck:a?.enforceCheck,relations:[...r?Pe(t):[],...ke(i,a?.relations)]}};return this._withVariantBuilder(o.discKey,s)}_withVariantBuilder(n,t){let a=Ke(this.schema,n,t),o=this.schema.getExtension?.("relations")??[];o.length&&(a=a.withExtension("relations",o));let r=new e(a);return r._variantBuilder={discKey:n,variants:t},r}_resolvePropName(n,t){let a=ue.getPropertiesFor(t),o=n(a);if(!o||typeof o!="object"||!(H in o))throw new Error("Entity relation selector must return a property descriptor, e.g. `t => t.author`.");let r=o[H];if(typeof r.propertyName!="string")throw new Error("Entity relation selector must return a top-level property descriptor.");return r.propertyName}_resolveForeignSchema(n){let a=(this.schema.introspect?.()?.properties??{})[n];if(!a)throw new Error(`Entity.relation: navigation property "${n}" not found on schema`);let o=a.introspect?.()??a;return o.type==="array"&&o.elementSchema?o.elementSchema:(o.type==="object"||a.constructor?.name==="ObjectSchemaBuilder",a)}};function Pe(e){let n=e.schema.getExtension?.("relations")??[];if(n.length===0)return[];let{propToCol:t}=R(e.schema);return n.map(a=>{let o=typeof a.foreignKey=="string"?a.foreignKey:void 0,r=o?t.get(o)??o:void 0;return{name:a.name,type:a.type,schema:a.schema,foreignKey:r,through:a.through}})}function dt(e,n){let t=ue.getPropertiesFor(e),o=n(t)?.[H];if(!o?.propertyName)throw new Error("ctiVariant: foreignKey accessor must return a top-level property descriptor on the variant schema");let r=o.propertyName,s=(e.introspect?.()?.properties??{})[r];if(!s)throw new Error(`ctiVariant: foreignKey property "${r}" not found on variant schema`);return Q(s,r)}function ke(e,n){if(!n)return[];let{propToCol:t}=R(e),a=[],o=ue.getPropertiesFor(e);for(let[r,i]of Object.entries(n)){let s;if(i.foreignKey){let y=i.foreignKey(o)?.[H];if(!y?.propertyName)throw new Error(`variant relation "${r}": foreignKey accessor must return a top-level property descriptor on the variant schema`);let u=y.propertyName;s=t.get(u)??u}let c=i.entity?i.entity.schema:i.schema;a.push({name:r,type:i.type,schema:c,foreignKey:s,through:i.through})}return a}function gt(e){return new Y(e)}var D={date_from_json:e=>e&&new Date(Date.parse(e))};function Oe(e,n){if(typeof e=="string"){if(typeof D[e]!="function")throw new Error(`unknown mapper "${e}"`);return D[e](n)}if(typeof e=="function")return e(n);throw new Error("couldn't map value")}function me(e,n){if(!n)throw new Error("mappers should be an object");if(!e||typeof e!="object"||e===null)return e;let t={};for(let a of Object.keys(e))t[a]=n[a]?Oe(n[a],e[a]):e[a];return t}function pe(e,n,t){for(let a of n){let o=a.as;a.mappers&&typeof e[o]<"u"&&e[o]!==null&&(e[o]=me(e[o],a.mappers))}for(let a of t){let o=a.as;if(Array.isArray(e[o]))for(let r=0;r<e[o].length;r++)e[o][r]&&a.mappers&&(e[o][r]=me(e[o][r],a.mappers))}return e}function St(e,n,t,a){let o={};for(let c of e)o[c.column_name]={name:c.column_name,type:c.data_type,nullable:c.is_nullable==="YES",defaultValue:c.column_default??null,maxLength:c.character_maximum_length??null,numericPrecision:c.numeric_precision??null};let r=n.map(c=>({name:c.indexname,columns:Array.isArray(c.columns)?c.columns:[],unique:(c.indexdef??"").toUpperCase().includes("UNIQUE"),definition:c.indexdef??""})),i=t.map(c=>({constraintName:c.constraint_name,columnName:c.column_name,foreignTable:c.foreign_table,foreignColumn:c.foreign_column,deleteRule:c.delete_rule,updateRule:c.update_rule})),s=a.map(c=>({name:c.conname,definition:c.definition}));return{columns:o,indexes:r,foreignKeys:i,checks:s}}async function Ee(e,n){let[t,a,o,r]=await Promise.all([e.raw(`SELECT column_name, data_type, is_nullable, column_default,
|
|
7
7
|
character_maximum_length, numeric_precision
|
|
8
8
|
FROM information_schema.columns
|
|
9
9
|
WHERE table_name = ? AND table_schema = 'public'
|
|
@@ -24,7 +24,7 @@ ${r.join(`
|
|
|
24
24
|
JOIN information_schema.referential_constraints rc USING (constraint_name, constraint_schema)
|
|
25
25
|
WHERE tc.table_name = ? AND tc.constraint_type = 'FOREIGN KEY'`,[n]),e.raw(`SELECT conname, pg_get_constraintdef(oid) as definition
|
|
26
26
|
FROM pg_constraint
|
|
27
|
-
WHERE conrelid = ?::regclass AND contype = 'c'`,[n])]);return
|
|
27
|
+
WHERE conrelid = ?::regclass AND contype = 'c'`,[n])]);return St(t.rows,a.rows,o.rows,r.rows)}function je(e,n){if(n.columnType)return n.columnType;if(n.primaryKey?.autoIncrement)return"integer";switch(e.type){case"string":return"character varying";case"number":return e.isInteger!==!1?"integer":"double precision";case"boolean":return"boolean";case"date":return"timestamp without time zone";default:return"text"}}function L(e){let n=C(e),t=e.introspect(),a=t.properties??{},o=t.extensions??{},r={},i=[],s=[],c=[];for(let[l,y]of Object.entries(a)){let u=Q(y,l),f=y.introspect(),h=f.extensions??{};(f.type==="object"||f.type==="array")&&!h.columnType||(r[u]={name:u,type:je(f,h),nullable:!f.isRequired,defaultValue:h.defaultTo??null,maxLength:h.maxLength??f.maxLength??null,numericPrecision:null},h.references&&s.push({constraintName:`${n}_${u}_foreign`,columnName:u,foreignTable:h.references.table,foreignColumn:h.references.column,deleteRule:(h.onDelete??"NO ACTION").toUpperCase(),updateRule:(h.onUpdate??"NO ACTION").toUpperCase()}))}if(o.timestamps){let l=o.timestamps,y=l.createdAt??"created_at",u=l.updatedAt??"updated_at";r[y]={name:y,type:"timestamp without time zone",nullable:!1,defaultValue:"now",maxLength:null,numericPrecision:null},r[u]={name:u,type:"timestamp without time zone",nullable:!1,defaultValue:"now",maxLength:null,numericPrecision:null}}if(o.softDelete){let l=o.softDelete.column??"deleted_at";r[l]={name:l,type:"timestamp without time zone",nullable:!0,defaultValue:null,maxLength:null,numericPrecision:null}}for(let l of o.indexes??[]){let y=l.name??`idx_${l.columns.join("_")}`;i.push({name:y,columns:l.columns,unique:l.unique??!1,definition:""})}for(let l of o.uniques??[]){let y=l.name??`unq_${l.columns.join("_")}`;i.push({name:y,columns:l.columns,unique:!0,definition:""})}return{columns:r,indexes:i,foreignKeys:s,checks:c}}function fe(e,n){let t=e.introspect(),a=t.properties??{},o=t.extensions??{},r=[],i=[],s=[],c=[],l=[],y=[],u=[],f=new Set;o.timestamps&&(f.add(o.timestamps.createdAt),f.add(o.timestamps.updatedAt));let h=new Set;for(let[m,d]of Object.entries(a)){let x=Q(d,m),T=d.introspect(),w=T.extensions??{};if((T.type==="object"||T.type==="array")&&!w.columnType)continue;h.add(x);let N=n.columns[x];if(!N)r.push({name:x,type:je(T,w),nullable:!T.isRequired,defaultValue:w.defaultTo,references:w.references,onDelete:w.onDelete,onUpdate:w.onUpdate});else{let v={},U=!T.isRequired;if(N.nullable!==U&&(v.nullable={from:N.nullable,to:U}),!f.has(x)&&!w.primaryKey?.autoIncrement){let Be=N.defaultValue??null,Ne=w.defaultTo??null;Be!==Ne&&(v.defaultValue={from:Be,to:Ne})}Object.keys(v).length>0&&s.push({name:x,changes:v})}w.references&&(n.foreignKeys.find(U=>U.columnName===x)||y.push({column:x,foreignTable:w.references.table,foreignColumn:w.references.column,onDelete:w.onDelete,onUpdate:w.onUpdate}))}o.timestamps&&(h.add(o.timestamps.createdAt),h.add(o.timestamps.updatedAt)),o.softDelete&&h.add(o.softDelete.column);for(let m of Object.keys(n.columns))h.has(m)||i.push(m);let g=new Set;for(let m of o.indexes??[]){let d=m.name??`idx_${m.columns.join("_")}`;g.add(d),n.indexes.find(T=>T.name===d)||c.push({columns:m.columns,name:m.name,unique:m.unique})}for(let m of o.uniques??[]){let d=m.name??`unq_${m.columns.join("_")}`;g.add(d),n.indexes.find(T=>T.name===d)||c.push({columns:m.columns,name:m.name,unique:!0})}for(let m of n.foreignKeys){let d=Object.entries(a).find(([x,T])=>Q(T,x)===m.columnName);d&&(d[1].introspect().extensions??{}).references||u.push(m.constraintName)}return{addColumns:r,dropColumns:i,alterColumns:s,addIndexes:c,dropIndexes:l,addForeignKeys:y,dropForeignKeys:u}}function xt(e,n){let{up:t,down:a}=$e(e,n),o=`import type { Knex } from 'knex';
|
|
28
28
|
|
|
29
29
|
export async function up(knex: Knex): Promise<void> {
|
|
30
30
|
${t}
|
|
@@ -33,29 +33,29 @@ ${t}
|
|
|
33
33
|
export async function down(knex: Knex): Promise<void> {
|
|
34
34
|
${a}
|
|
35
35
|
}
|
|
36
|
-
`;return{up:t,down:a,full:o}}async function
|
|
36
|
+
`;return{up:t,down:a,full:o}}async function _e(e,n){return e.schema.hasTable(n)}async function Tt(e,n){let t=De(n),a=[];for(let{schema:o,tableName:r}of t){if(!await _e(e,r)){a.push({type:"missing-table",tableName:r});continue}let s=await Ee(e,r),c=fe(o,s);z(c)||a.push({type:"schema-drift",tableName:r,diff:c})}return{valid:a.length===0,checkedTables:t.map(o=>o.tableName),issues:a}}function z(e){return e.addColumns.length===0&&e.dropColumns.length===0&&e.alterColumns.length===0&&e.addIndexes.length===0&&e.dropIndexes.length===0&&e.addForeignKeys.length===0&&e.dropForeignKeys.length===0}async function wt(e,n,t){if(z(n))return;for(let o of n.dropForeignKeys)await e.raw("ALTER TABLE ?? DROP CONSTRAINT ??",[t,o]);(n.addColumns.length>0||n.dropColumns.length>0||n.alterColumns.length>0||n.addIndexes.length>0||n.dropIndexes.length>0||n.addForeignKeys.length>0)&&await e.schema.alterTable(t,o=>{for(let r of n.addColumns){let i=Ct(o,r.name,r.type);if(r.nullable?i=i.nullable():i=i.notNullable(),r.defaultValue!==void 0&&(r.defaultValue==="now"?i=i.defaultTo(e.fn.now()):typeof r.defaultValue=="object"&&r.defaultValue!==null&&r.defaultValue.raw?i=i.defaultTo(e.raw(r.defaultValue.raw)):i=i.defaultTo(r.defaultValue)),r.references){let s=i.references(r.references.column).inTable(r.references.table);r.onDelete&&s.onDelete(r.onDelete),r.onUpdate&&s.onUpdate(r.onUpdate)}}for(let r of n.dropColumns)o.dropColumn(r);for(let r of n.alterColumns)for(let[i,s]of Object.entries(r.changes))i==="nullable"?s.to?o.setNullable(r.name):o.dropNullable(r.name):i==="defaultValue"&&s.to===null&&o.dropColumn(r.name);for(let r of n.addIndexes)r.unique?o.unique(r.columns,r.name?{indexName:r.name}:void 0):o.index(r.columns,r.name);for(let r of n.dropIndexes)o.dropIndex([],r);for(let r of n.addForeignKeys){let i=o.foreign(r.column).references(r.foreignColumn).inTable(r.foreignTable);r.onDelete&&(i=i.onDelete(r.onDelete)),r.onUpdate&&(i=i.onUpdate(r.onUpdate))}})}function Rt(e,n){let t=De(e),a=Bt(t),o=[],r=[],i=new Set(a.map(h=>h.tableName));for(let{schema:h,tableName:g}of a){let m=n.tables[g];if(m){let d=fe(h,m);if(!z(d)){let{up:x,down:T}=$e(d,g);o.push(x),r.push(T)}}else{let{up:d,down:x}=ye(h);o.push(d),r.push(x)}}for(let h of Object.keys(n.tables))if(!i.has(h)){let g=n.tables[h],{up:m,down:d}=bt(h,g);o.push(m),r.unshift(d)}let s=o.length===0,c=o.join(`
|
|
37
37
|
|
|
38
|
-
`),
|
|
38
|
+
`),l=[...r].reverse().join(`
|
|
39
39
|
|
|
40
|
-
`),
|
|
40
|
+
`),y=`import type { Knex } from 'knex';
|
|
41
41
|
|
|
42
42
|
export async function up(knex: Knex): Promise<void> {
|
|
43
|
-
${
|
|
43
|
+
${s?" // No changes needed":c}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export async function down(knex: Knex): Promise<void> {
|
|
47
|
-
${
|
|
47
|
+
${s?" // No changes needed":l}
|
|
48
48
|
}
|
|
49
|
-
`,
|
|
49
|
+
`,u={};for(let{schema:h,tableName:g}of a)u[g]=L(h);return{up:c,down:l,full:y,isEmpty:s,nextSnapshot:{version:1,tables:u}}}function bt(e,n){let t=` // TODO: review destructive change \u2014 dropped table '${e}'
|
|
50
50
|
await knex.schema.dropTableIfExists(${JSON.stringify(e)});`,a=[];for(let[r,i]of Object.entries(n.columns)){let s=` table.specificType(${JSON.stringify(r)}, ${JSON.stringify(i.type)})`;i.nullable?s+=".nullable()":s+=".notNullable()",i.defaultValue!==null&&i.defaultValue!==void 0&&(s+=`.defaultTo(${JSON.stringify(i.defaultValue)})`),a.push(s+";")}for(let r of n.foreignKeys)a.push(` table.foreign(${JSON.stringify(r.columnName)}).references(${JSON.stringify(r.foreignColumn)}).inTable(${JSON.stringify(r.foreignTable)}).onDelete(${JSON.stringify(r.deleteRule)}).onUpdate(${JSON.stringify(r.updateRule)});`);for(let r of n.indexes)r.unique?a.push(` table.unique(${JSON.stringify(r.columns)}, { indexName: ${JSON.stringify(r.name)} });`):a.push(` table.index(${JSON.stringify(r.columns)}, ${JSON.stringify(r.name)});`);let o=` await knex.schema.createTable(${JSON.stringify(e)}, (table) => {
|
|
51
51
|
`+a.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
});`;return{up:t,down:o}}function
|
|
53
|
+
});`;return{up:t,down:o}}function $e(e,n){let t=[],a=[];for(let s of e.addColumns){let l=` ${s.type.includes(" ")?`table.specificType('${s.name}', '${s.type}')`:`table.${Nt(s.type)}('${s.name}')`}`;s.nullable?l+=".nullable()":l+=".notNullable()",s.defaultValue!==void 0&&(l+=`.defaultTo(${Kt(s.defaultValue)})`),l+=";",t.push(l),a.push(` table.dropColumn('${s.name}');`)}for(let s of e.dropColumns)t.push(` table.dropColumn('${s}');`),a.push(` // TODO: recreate column '${s}' with original definition`);for(let s of e.alterColumns)for(let[c,l]of Object.entries(s.changes))if(c==="nullable")l.to?(t.push(` table.setNullable('${s.name}');`),a.push(` table.dropNullable('${s.name}');`)):(t.push(` table.dropNullable('${s.name}');`),a.push(` table.setNullable('${s.name}');`));else if(c==="defaultValue"){let y=l.to,u=l.from;y===null?(t.push(` table.timestamp('${s.name}').alter(); // DROP DEFAULT`),a.push(` table.timestamp('${s.name}').defaultTo(knex.fn.now()).alter();`)):(t.push(` table.timestamp('${s.name}').notNullable().defaultTo(knex.fn.now()).alter();`),a.push(u===null?` table.timestamp('${s.name}').notNullable().alter();`:` table.timestamp('${s.name}').notNullable().defaultTo(knex.fn.now()).alter();`))}for(let s of e.addIndexes){let c=JSON.stringify(s.columns);s.unique?(t.push(` table.unique(${c}${s.name?`, { indexName: '${s.name}' }`:""});`),a.push(` table.dropUnique(${c}${s.name?`, '${s.name}'`:""});`)):(t.push(` table.index(${c}${s.name?`, '${s.name}'`:""});`),a.push(` table.dropIndex([]${s.name?`, '${s.name}'`:""});`))}for(let s of e.dropIndexes)t.push(` table.dropIndex([], '${s}');`),a.push(` // TODO: recreate index '${s}' with original definition`);for(let s of e.addForeignKeys){let c=` table.foreign('${s.column}').references('${s.foreignColumn}').inTable('${s.foreignTable}')`;s.onDelete&&(c+=`.onDelete('${s.onDelete}')`),s.onUpdate&&(c+=`.onUpdate('${s.onUpdate}')`),c+=";",t.push(c),a.push(` table.dropForeign('${s.column}');`)}for(let s of e.dropForeignKeys)t.push(` // TODO: drop foreign key constraint '${s}'`);let o=t.length===0,r=o?" // No changes needed":` await knex.schema.alterTable('${n}', (table) => {
|
|
54
54
|
${t.join(`
|
|
55
55
|
`)}
|
|
56
56
|
});`,i=o?" // No changes needed":` await knex.schema.alterTable('${n}', (table) => {
|
|
57
57
|
${a.join(`
|
|
58
58
|
`)}
|
|
59
|
-
});`;return{up:r,down:i}}function Rt(e,n,t){switch(t){case"integer":return e.integer(n);case"character varying":return e.string(n);case"text":return e.text(n);case"boolean":return e.boolean(n);case"timestamp without time zone":case"timestamp":return e.timestamp(n);case"double precision":case"float":return e.float(n);case"jsonb":case"json":return e.specificType(n,"jsonb");case"uuid":return e.uuid(n);default:return e.specificType(n,t)}}function bt(e){let n=new Set(e.map(y=>y.tableName)),t=new Map;for(let{schema:y,tableName:u}of e){let f=new Set,h=y.introspect().properties??{};for(let[,d]of Object.entries(h)){let m=d.introspect?.()?.extensions??{};m.references?.table&&n.has(m.references.table)&&f.add(m.references.table)}t.set(u,f)}let a=new Map,o=new Map;for(let{tableName:y}of e)a.set(y,0),o.set(y,[]);for(let{tableName:y}of e)for(let u of t.get(y)??[])o.get(u).push(y),a.set(y,(a.get(y)??0)+1);let r=[];for(let[y,u]of a)u===0&&r.push(y);let i=[];for(;r.length>0;){let y=r.shift();i.push(y);for(let u of o.get(y)??[]){let f=a.get(u)-1;a.set(u,f),f===0&&r.push(u)}}let s=new Set(i),c=e.filter(y=>!s.has(y.tableName)),l=new Map(e.map(y=>[y.tableName,y]));return[...i.map(y=>l.get(y)),...c]}function Ct(e){switch(e){case"integer":return"integer";case"character varying":return"string";case"text":return"text";case"boolean":return"boolean";case"timestamp without time zone":case"timestamp":return"timestamp";case"double precision":case"float":return"float";case"jsonb":case"json":return"jsonb";case"uuid":return"uuid";default:return`specificType('${e}')`}}function Bt(e){return e==="now"?"knex.fn.now()":typeof e=="object"&&e!==null&&e.raw?`knex.raw('${e.raw.replace(/'/g,"\\'")}')`:typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:String(e)}async function Nt(e,n,t,a){let o;if(typeof t=="string"){let i=await e.raw(t,a??[]);o=i.rows??i}else o=await t;if(!o||!Array.isArray(o))return[];let{colToProp:r}=R(n);return o.map(i=>{let s={};for(let[c,l]of Object.entries(i)){let y=r.get(c);s[y??c]=l}return s})}import{ObjectSchemaBuilder as _t,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as Ae}from"@cleverbrush/schema";import{ObjectSchemaBuilder as Qt,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as Kt}from"@cleverbrush/schema";var $e=new WeakMap;function p(e){let n=$e.get(e);if(!n)throw new Error("SchemaQueryBuilder state not found \u2014 builder was not properly initialized");return n}function Oe(e,n){$e.set(e,n)}function b(e,n,t="column"){let a=p(e);return Q(n,a.localSchema,t,a.knex)}function S(e){p(e).cachedBuiltQuery=null}function z(e){return p(e).localSchema.getExtension?.("softDelete")??null}function It(e){let t=p(e).localSchema.getExtension?.("defaultScope");return typeof t=="function"?t:null}function $(e){return p(e).localSchema.getExtension?.("timestamps")??null}var fe=new Set(["=","!=","<>","<",">","<=",">=","like","not like","ilike","not ilike","in","not in","is","is not"]);function j(e){let n=p(e);if(n.variantConfig!==void 0)return n.variantConfig;let t=se(n.localSchema);if(!t)return n.variantConfig=null,null;let{propToCol:a}=R(n.localSchema),o=a.get(t.discriminatorKey)??t.discriminatorKey;return n.variantConfig={...t,discriminatorColumn:o},n.variantConfig}function vt(e,n,t){let a=p(e),o=a.knex,r=a.tableName,i=P(e,a.localSchema),s=t.discriminatorColumn,c=n.clone().select(`${r}.*`);for(let[l,y]of Object.entries(t.variants))if(!(a.enabledVariants!==null&&!a.enabledVariants.has(l))&&y.storage==="cti"){let u=`__v_${l}`,f=y.tableName,h=y.foreignKey;c.leftJoin(`${f} as ${u}`,o.raw("?? = ?? AND ?? = ?",[`${u}.${h}`,`${r}.${i}`,`${r}.${s}`,l]));let{propToCol:d}=R(y.schema),g=y.schema.introspect().properties??{};for(let x of Object.keys(g)){let T=d.get(x)??x;c.select(o.raw("?? as ??",[`${u}.${T}`,`${u}__${T}`]))}}for(let l of a.variantRelationIncludes){let y=t.variants[l.variantKey];if(!y)continue;let u=y.relations.find(m=>m.name===l.relationName);if(!u)continue;let f=X(e,u.schema),h=C(f),d=`__v_${l.variantKey}__rel_${l.relationName}`;if(u.type==="belongsTo"||u.type==="hasOne"){let m,g;u.type==="belongsTo"?(m=u.foreignKey??(()=>{throw new Error(`includeVariant: relation "${l.relationName}" on variant "${l.variantKey}" requires foreignKey`)})(),g=P(e,f)):(m=P(e,a.localSchema),g=u.foreignKey??(()=>{throw new Error(`includeVariant: relation "${l.relationName}" on variant "${l.variantKey}" requires foreignKey`)})());let x,T=`__v_${l.variantKey}`;y.storage==="cti"?u.type==="belongsTo"?x=`${d}.${g} = ${T}.${m} AND ${r}.${s} = '${l.variantKey}'`:x=`${d}.${g} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`:u.type==="belongsTo"?x=`${d}.${g} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`:x=`${d}.${g} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`;let w=a.knex(h),B=Pt(e,f,d,h,l.customize);c.leftJoin(o.raw("?? as ??",[h,d]),o.raw(x));for(let v of B)c.select(v)}}for(let l of a.variantWhereFilters){let y=`${r}.${s}`;c.where(function(){this.where(y,l.key).andWhere(l.qualifiedColumn,l.op,l.value).orWhere(y,"!=",l.key)})}return a.enabledVariants!==null&&c.whereIn(`${r}.${s}`,[...a.enabledVariants]),c}var G=null;function De(e){G=e}function L(){return G}function Pt(e,n,t,a,o){let r=p(e),i=r.knex,{propToCol:s}=R(n),l=n.introspect().properties??{},y;if(o){let u=new G(r.knex,n,r.knex(a));o(u);let h=p(u).explicitSelects;h&&h.length>0?y=h:y=Object.keys(l).map(d=>s.get(d)??d)}else y=Object.keys(l).map(u=>s.get(u)??u);return y.map(u=>i.raw("?? as ??",[`${t}.${u}`,`${t}__${u}`]))}function kt(e,n,t){let a=p(e),{colToProp:o}=R(a.localSchema),r={};for(let[c,l]of Object.entries(n)){if(c.startsWith("__v_"))continue;let y=o.get(c);y?r[y]=l:r[c]=l}let i=t.discriminatorKey,s=r[i];if(s!=null){let c=t.variants[s];if(c)if(c.storage==="cti"){let{colToProp:l}=R(c.schema),u=`${`__v_${s}`}__`,f=c.foreignKey;if(f){let h=`${u}${f}`;if(!c.allowOrphan&&n[h]==null)throw new Error(`Polymorphic orphan: "${i}" = "${s}" but no matching row found in variant table "${c.tableName}". Set allowOrphan: true on this variant to suppress.`)}for(let[h,d]of Object.entries(n)){if(!h.startsWith(u))continue;let m=h.slice(u.length);if(m===f)continue;let g=l.get(m)??m;r[g]=d}}else{let{colToProp:l}=R(c.schema);for(let[y,u]of Object.entries(n)){if(y.startsWith("__v_")||o.has(y))continue;let f=l.get(y);f&&(r[f]=u)}}}if(a.variantRelationIncludes.length>0&&s!=null){let c=t.variants[s];if(c)for(let l of a.variantRelationIncludes){if(l.variantKey!==s)continue;let y=c.relations.find(u=>u.name===l.relationName);if(y&&(y.type==="belongsTo"||y.type==="hasOne")){let f=`${`__v_${s}__rel_${l.relationName}`}__`,h=X(e,y.schema),{colToProp:d}=R(h),m={},g=!1;for(let[x,T]of Object.entries(n)){if(!x.startsWith(f))continue;let w=x.slice(f.length),B=d.get(w)??w;m[B]=T,T!=null&&(g=!0)}r[l.relationName]=g?m:null}}}return r}function X(e,n){return typeof n=="function"?n():n}function P(e,n){let t=J(n);return t.columnNames.length>0?t.columnNames[0]:"id"}function Ve(e){let n=p(e),t=J(n.localSchema);if(t.columnNames.length===0)throw new Error("No primary key declared on this schema. Use `.primaryKey()` on a column or `.hasPrimaryKey([...])` on the schema.");return t}function he(e){let n=p(e),t=n.baseQuery,a=!1,o=z(e);if(o&&n.onlyDeleted?(a||(t=t.clone(),a=!0),t.whereNotNull(o.column)):o&&!n.includeDeleted&&(a||(t=t.clone(),a=!0),t.whereNull(o.column)),!n.skipDefaultScope){let r=It(e);if(r){a||(t=t.clone(),a=!0);let i=new G(n.knex,n.localSchema,t),s=p(i);s.skipDefaultScope=!0,r(i)}}return t}function Et(e,n,t,a){let r=p(e).knex,i=t.foreignQuery,s=i._single?.table;if(!s)throw new Error(`Could not determine table name from foreignQuery for "${t.as}". Make sure foreignQuery is created via knex("tableName").`);n.select(r.raw(":relationAlias:.:as:->0 as :as:",{relationAlias:a,as:t.as}));let c=r.from(i.as(s)).select(r.raw(":foreignTable:.:foreignColumn:",{foreignTable:s,foreignColumn:t.foreignColumn})).select(r.raw("jsonb_agg(:foreignTable:) as :as:",{foreignTable:s,as:t.as})).groupByRaw(":foreignTable:.:foreignColumn:",{foreignTable:s,foreignColumn:t.foreignColumn}).as(a),l=t.required?"join":"leftJoin";n[l](c,function(){this.on(r.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{originalQuery:"originalQuery",relationAlias:a,foreignColumn:t.foreignColumn,localColumn:t.localColumn}))})}function jt(e,n,t,a,o){let i=p(e).knex,s=`withFilter${o}`,c=t.limit!==null&&t.limit>0||t.offset!==null&&t.offset>0,l=t.orderBy?t.orderBy.column:t.foreignColumn,y=t.orderBy?t.orderBy.direction:"asc";c?n.with(s,i.from(t.foreignQuery.clone().whereIn(t.foreignColumn,i.from(i.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(t.localColumn).as(`__wf_inner_${o}`)).as(`__wf_inner_${o}`)).select(`__wf_inner_${o}.*`).select(i.raw(`row_number() over(partition by :foreignColumn: order by :orderByColumn: ${y}) as "__rn__"`,{foreignColumn:t.foreignColumn,orderByColumn:l}))):n.with(s,t.foreignQuery.clone().whereIn(t.foreignColumn,i.from(i.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(t.localColumn)));let u=i.from(s);if(c){let h=t.limit!==null&&t.limit>0,d=t.offset!==null&&t.offset>0,m=t.offset??0,g=m+(t.limit??0),x=h&&d?'"__rn__" > :offset and "__rn__" <= :limit':h?'"__rn__" <= :limit':'"__rn__" > :offset';u.whereRaw(x,{limit:g,offset:m}),u.select(i.raw(":foreignColumn:",{foreignColumn:t.foreignColumn})),u.select(i.raw(`coalesce(jsonb_agg(to_jsonb(:filterName:) - '__rn__' order by "__rn__"), '[]'::jsonb) as :as:`,{filterName:s,as:t.as}))}else{u.select(i.raw(":foreignColumn:",{foreignColumn:t.foreignColumn}));let h=t.orderBy?`jsonb_agg(:filterName: order by :filterName:.:orderByColumn: ${y})`:"jsonb_agg(:filterName:)";u.select(i.raw(`coalesce(${h}, '[]'::jsonb) as :as:`,t.orderBy?{filterName:s,orderByColumn:l,as:t.as}:{filterName:s,as:t.as}))}u.groupByRaw(":foreignColumn:",{foreignColumn:t.foreignColumn});let f=u.as(a);n.select(i.raw("coalesce(:relationAlias:.:as:, '[]'::jsonb) as :as:",{relationAlias:a,as:t.as})),n.leftJoin(f,function(){this.on(i.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{relationAlias:a,foreignColumn:t.foreignColumn,originalQuery:"originalQuery",localColumn:t.localColumn}))})}function de(e){let n=p(e),t=he(e),a=j(e),o=a?vt(e,t,a):t;if(n.specs.length===0)return o;let r=n.knex,i=n.specs,s=[...new Set(i.map(u=>u.localColumn))],c=o,l=[];if(n.explicitSelects!==null){let u=new Set(n.explicitSelects);if(l=s.filter(f=>!u.has(f)),l.length>0){c=o.clone();for(let f of l)c.column(f)}}let y=r.queryBuilder().with("originalQuery",c);if(l.length>0&&n.explicitSelects!==null)for(let u of n.explicitSelects)y.select(r.raw(":originalQuery:.:col: as :col:",{originalQuery:"originalQuery",col:u}));else y.select("originalQuery.*");y.from(r.raw(":originalQuery:",{originalQuery:"originalQuery"}));for(let u=0;u<i.length;u++){let f=i[u],h=`eagerRelation${u}`;f.type==="one"?Et(e,y,f,h):jt(e,y,f,h,u)}return y}function O(e){let n=p(e);return n.cachedBuiltQuery||(n.cachedBuiltQuery=de(e)),n.cachedBuiltQuery}function I(e,n){if(!n)return n;let t=j(e);if(t)return kt(e,n,t);let a=p(e),{colToProp:o}=R(a.localSchema),r={};for(let[i,s]of Object.entries(n)){let c=o.get(i);c?r[c]=s:r[i]=s}return r}function A(e,n){let t=p(e),a=t.specs.filter(i=>i.type==="one"),o=t.specs.filter(i=>i.type==="many"),r=me(n,a,o);return I(e,r)}function k(e,n){let t=p(e),{propToCol:a}=R(t.localSchema),o={};for(let[r,i]of Object.entries(n)){let s=a.get(r);s?o[s]=i:o[r]=i}return o}function M(e,n){return k(e,n)}function N(e,n){return typeof n=="string"||typeof n=="function"?b(e,n,"column"):n}function F(e,n){let t=p(e);try{let a=Qt.getPropertiesFor(t.localSchema),o=n(a);if(o&&typeof o=="object"&&Kt in o)return!0}catch{}return!1}function E(e,n){let t=p(e);if(t.selectionMode==="projection")throw new Error(`Cannot call .${n}() after .projected('${t.appliedProjection}'). Choose one column-selection mode per query.`)}function Le(e,n){let t=p(e);if(t.selectionMode==="select")throw new Error(`Cannot call .${n}() after .select(). Choose one column-selection mode per query.`);if(t.selectionMode==="aggregate")throw new Error(`Cannot call .${n}() after an aggregate method. Choose one column-selection mode per query.`);if(t.selectionMode==="projection")throw new Error(`Cannot call .${n}() after .projected('${t.appliedProjection}'). Choose one column-selection mode per query.`)}function Me(e,...n){let t=p(e);if(n.length===1&&typeof n[0]=="function"){let o=n[0],r=_t.getPropertiesFor(t.localSchema),i=o(r);if(i&&typeof i=="object"&&!(Ae in i)){S(e),E(e,"select"),t.selectionMode="projection",t.appliedProjection="<inline>";let s={};t.explicitSelects??=[];for(let[c,l]of Object.entries(i)){if(!l||typeof l!="object"||!(Ae in l))throw new Error(`select(selector): value for alias "${c}" must be a property descriptor (e.g. \`t.someProp\`).`);let y=b(e,(()=>l),`select(selector).${c}`);s[c]=y,t.explicitSelects.push(y)}return t.baseQuery.select(s),e}}S(e),E(e,"select"),t.selectionMode="select";let a=n.map(o=>N(e,o));t.baseQuery.select(...a),t.explicitSelects??=[];for(let o of a)typeof o=="string"&&t.explicitSelects.push(o);return e}function Fe(e,...n){S(e);let t=n.map(a=>N(e,a));return p(e).baseQuery.distinct(...t),e}function qe(e,n){let t=p(e);return S(e),E(e,"count"),t.selectionMode="aggregate",n?t.baseQuery.count(N(e,n)):t.baseQuery.count(),e}function Ue(e,n){let t=p(e);return S(e),E(e,"countDistinct"),t.selectionMode="aggregate",n?t.baseQuery.countDistinct(N(e,n)):t.baseQuery.countDistinct(),e}function We(e,n){let t=p(e);return S(e),E(e,"min"),t.selectionMode="aggregate",t.baseQuery.min(N(e,n)),e}function Je(e,n){let t=p(e);return S(e),E(e,"max"),t.selectionMode="aggregate",t.baseQuery.max(N(e,n)),e}function Ye(e,n){let t=p(e);return S(e),E(e,"sum"),t.selectionMode="aggregate",t.baseQuery.sum(N(e,n)),e}function He(e,n){let t=p(e);return S(e),E(e,"avg"),t.selectionMode="aggregate",t.baseQuery.avg(N(e,n)),e}function ze(e,n,t){let a=p(e);return S(e),t?a.baseQuery.select(a.knex.raw(n,t)):a.baseQuery.select(a.knex.raw(n)),e}function Ge(e,n){let t=p(e);if(Le(e,"projected"),t.selectionMode==="projection")throw new Error(`Cannot call .projected('${n}') \u2014 .projected('${t.appliedProjection}') was already applied. Only one projection per query.`);let o=re(t.localSchema)[n];if(!o)throw new Error(`Unknown projection "${n}" on schema for table "${t.tableName}"`);let{propToCol:r}=R(t.localSchema),i=o.keys.map(s=>r.get(s)??s);t.baseQuery.select(...i),t.explicitSelects??=[];for(let s of i)t.explicitSelects.push(s);return t.selectionMode="projection",t.appliedProjection=n,S(e),e}function Xe(e,n){let t=p(e);S(e);let o=t.localSchema.getExtension?.("scopes")?.[n];if(!o)throw new Error(`Unknown scope "${n}" on schema for table "${t.tableName}"`);return o(e),e}function Ze(e){let n=p(e);return S(e),n.skipDefaultScope=!0,n.includeDeleted=!0,e}var ge=class{#n;#e;#t;constructor(n,t,a,o){this.#n=n,this.#e=t,this.#t=o}async merge(n,t){return this.#a(n,"merge",t)}async ignore(n){return this.#a(n,"ignore")}async#a(n,t,a){let o=C(this.#e),r=this.#e.getExtension?.("timestamps")??null,i=this.#e.getExtension?.("beforeInsert")??[],s={...n};for(let d of i)s=await d(s)??s;let{propToCol:c}=R(this.#e),l={};for(let[d,m]of Object.entries(s))l[c.get(d)??d]=m;r&&(l[r.createdAt]=this.#n.fn.now(),l[r.updatedAt]=this.#n.fn.now());let y=this.#n(o).insert(l).onConflict(this.#t);if(t==="ignore")y=y.ignore();else{let d;if(a){d={};for(let[m,g]of Object.entries(a))d[c.get(m)??m]=g}else d={...l},r&&(delete d[r.createdAt],d[r.updatedAt]=this.#n.fn.now());y=y.merge(d)}let u=await y.returning("*");if(!u||u.length===0)return;let{colToProp:f}=R(this.#e),h={};for(let[d,m]of Object.entries(u[0]))h[f.get(d)??d]=m;return h}};async function en(e,n){let t=p(e),a={...n},o=t.localSchema.getExtension?.("beforeInsert")??[];for(let y of o)a=await y(a)??a;let r=k(e,a),i=$(e);i&&(r[i.createdAt]=t.knex.fn.now(),r[i.updatedAt]=t.knex.fn.now());let[s]=await t.knex(t.tableName).insert(r).returning("*"),c=I(e,s),l=t.localSchema.getExtension?.("afterInsert")??[];for(let y of l)await y(c);return c}async function nn(e,n){let t=p(e),a=$(e),o=t.localSchema.getExtension?.("beforeInsert")??[],r=[];for(let l of n){let y={...l};for(let f of o)y=await f(y)??y;let u=k(e,y);a&&(u[a.createdAt]=t.knex.fn.now(),u[a.updatedAt]=t.knex.fn.now()),r.push(u)}let s=(await t.knex(t.tableName).insert(r).returning("*")).map(l=>I(e,l)),c=t.localSchema.getExtension?.("afterInsert")??[];for(let l of s)for(let y of c)await y(l);return s}function tn(e,...n){let t=p(e),a=n.map(o=>b(e,o,"onConflict"));return new ge(t.knex,t.localSchema,e,a)}async function an(e,n,t){let a=p(e),o=t.conflictColumns.map(s=>b(e,s,"upsert")),r=a.knex(a.tableName).insert(k(e,n)).onConflict(o);if(t.updateColumns&&t.updateColumns.length>0){let s=t.updateColumns.map(c=>b(e,c,"upsert"));r.merge(s)}else r.merge();let[i]=await r.returning("*");return I(e,i)}async function Se(e,n,t){if(n.length===0)return[];let a=p(e),o=t?.chunkSize??500,r=Object.keys(n[0]).length||1,i=Math.max(1,Math.floor(6e4/Math.max(1,r))),s=Math.max(1,Math.min(o,i)),c=$(e),l=a.localSchema.getExtension?.("beforeInsert")??[],y=a.localSchema.getExtension?.("afterInsert")??[],u=t?.onConflict&&t.conflictColumns?t.conflictColumns.map(h=>b(e,h,"bulkInsert.onConflict")):null;if(t?.onConflict&&(!u||u.length===0))throw new Error("bulkInsert: `conflictColumns` is required when `onConflict` is set.");let f=[];for(let h=0;h<n.length;h+=s){let d=n.slice(h,h+s),m=[];for(let T of d){let w={...T};for(let v of l)w=await v(w)??w;let B=k(e,w);c&&(B[c.createdAt]=a.knex.fn.now(),B[c.updatedAt]=a.knex.fn.now()),m.push(B)}let g=a.knex(a.tableName).insert(m);if(u)if(g=g.onConflict(u),t.onConflict==="ignore")g=g.ignore();else{let T=new Set;for(let w of m)for(let B of Object.keys(w))T.add(B);for(let w of u)T.delete(w);c&&(T.delete(c.createdAt),T.add(c.updatedAt)),g=g.merge(Array.from(T))}let x=await g.returning("*");for(let T of x){let w=I(e,T);for(let B of y)await B(w);f.push(w)}}return f}async function on(e,n,t){return Se(e,n,{chunkSize:t.chunkSize,onConflict:"merge",conflictColumns:t.conflictColumns})}async function rn(e){let n=p(e),t=n.localSchema.getExtension?.("beforeDelete")??[];for(let o of t)await o(e);let a=z(e);return a?n.baseQuery.update({[a.column]:n.knex.fn.now()}):n.baseQuery.delete()}function sn(e){let n=p(e);return S(e),n.includeDeleted=!0,e}function cn(e){let n=p(e);return S(e),n.onlyDeleted=!0,n.includeDeleted=!0,e}async function ln(e){let n=p(e),t=n.localSchema.getExtension?.("beforeDelete")??[];for(let a of t)await a(e);return n.baseQuery.delete()}async function yn(e){let n=p(e),t=z(e);if(!t)throw new Error("Schema does not have soft delete enabled. Use .softDelete() on the schema.");return(await n.baseQuery.update({[t.column]:null}).returning("*")).map(o=>I(e,o))}function un(e,n){if(e.foreignQuery)return"toKnexQuery"in e.foreignQuery?e.foreignQuery.toKnexQuery():e.foreignQuery;let t=C(e.foreignSchema);return n(t)}function mn(e,n,t){let a=Q(e.localColumn,n,"localColumn"),o=Q(e.foreignColumn,e.foreignSchema,"foreignColumn");if(typeof e.as!="string"||!e.as)throw new Error("as must be a non-empty string");let r=un(e,t),i=e.required!==!1;return e.mappers!==void 0&&fn(e.mappers),{localColumn:a,foreignColumn:o,as:e.as,required:i,foreignQuery:r,mappers:e.mappers}}function pn(e,n,t){let a=Q(e.localColumn,n,"localColumn"),o=Q(e.foreignColumn,e.foreignSchema,"foreignColumn");if(typeof e.as!="string"||!e.as)throw new Error("as must be a non-empty string");let r=un(e,t);e.mappers!==void 0&&fn(e.mappers);let i=Number.isFinite(e.limit)&&e.limit>0?e.limit:null,s=Number.isFinite(e.offset)&&e.offset>0?e.offset:null,c=e.orderBy?{column:Q(e.orderBy.column,e.foreignSchema,"orderBy.column"),direction:e.orderBy.direction??"asc"}:null;return{localColumn:a,foreignColumn:o,as:e.as,foreignQuery:r,limit:i,offset:s,orderBy:c,mappers:e.mappers}}function fn(e){if(typeof e!="object"||e===null)throw new Error("mappers must be an object");for(let n of Object.keys(e)){let t=e[n];if(typeof t=="string"){if(typeof D[t]!="function")throw new Error(`mapper for "${n}": unknown built-in mapper name "${t}"`)}else if(typeof t!="function")throw new Error(`mapper for "${n}" must be a function or a built-in mapper name`)}}function xe(e){let n=new Set;for(let t of e){if(n.has(t.as))throw new Error(`duplicate field name: ${t.as}`);n.add(t.as)}}function Z(e,n){let t=p(e),a=mn(n,t.localSchema,t.knex);return t.specs.push({type:"one",...a}),xe(t.specs),S(e),e}function ee(e,n){let t=p(e),a=pn(n,t.localSchema,t.knex);return t.specs.push({type:"many",...a}),xe(t.specs),S(e),e}function hn(e,n,t){let a=p(e);S(e);let r=(a.localSchema.getExtension?.("relations")??[]).find(c=>c.name===n);if(!r){let c=j(e);if(c){let l=[];for(let[y,u]of Object.entries(c.variants))u.relations.some(f=>f.name===n)&&l.push({variantKey:y});if(l.length===1)return Te(e,l[0].variantKey,n,t);if(l.length>1)throw new Error(`Ambiguous relation "${n}" \u2014 found on variants: ${l.map(y=>y.variantKey).join(", ")}. Use .includeVariant(key, name) to be explicit.`)}throw new Error(`Unknown relation "${n}" on schema for table "${a.tableName}"`)}let i=X(e,r.schema),s=C(i);switch(r.type){case"belongsTo":{let c=Q(r.foreignKey,a.localSchema,"foreignKey"),l=P(e,i),y=a.knex(s);if(t){let u=L(),f=new u(a.knex,i,y);t(f)}Z(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,foreignQuery:y});break}case"hasOne":{let c=P(e,a.localSchema),l=Q(r.foreignKey,i,"foreignKey"),y=a.knex(s);if(t){let u=L(),f=new u(a.knex,i,y);t(f)}Z(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,required:!1,foreignQuery:y});break}case"hasMany":{let c=P(e,a.localSchema),l=Q(r.foreignKey,i,"foreignKey"),y=a.knex(s);if(t){let u=L(),f=new u(a.knex,i,y);t(f)}ee(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,foreignQuery:y});break}case"belongsToMany":{let c=r.through,l=P(e,a.localSchema),y=a.knex(s).join(c.table,`${c.table}.${c.foreignKey}`,`${s}.${P(e,i)}`).select(`${s}.*`,`${c.table}.${c.localKey}`);if(t){let u=L(),f=new u(a.knex,i,y);t(f)}ee(e,{foreignSchema:i,localColumn:l,foreignColumn:c.localKey,as:n,foreignQuery:y});break}}return e}function Te(e,n,t,a){let o=p(e);S(e);let r=j(e);if(!r)throw new Error(`includeVariant: schema for table "${o.tableName}" is not polymorphic (no .withVariants() config found)`);let i=r.variants[n];if(!i)throw new Error(`includeVariant: unknown variant key "${n}" on schema for table "${o.tableName}"`);if(!i.relations.find(c=>c.name===t))throw new Error(`includeVariant: unknown relation "${t}" on variant "${n}" of table "${o.tableName}"`);return o.variantRelationIncludes.push({variantKey:n,relationName:t,customize:a}),e}function ne(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.where(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.where(o,...t)}else{let o=N(e,n);a.baseQuery.where(o,...t)}return e}function dn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.andWhere(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.andWhere(o,...t)}else{let o=N(e,n);a.baseQuery.andWhere(o,...t)}return e}function gn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.orWhere(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.orWhere(o,...t)}else{let o=N(e,n);a.baseQuery.orWhere(o,...t)}return e}function Sn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.whereNot(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.whereNot(o,...t)}else{let o=N(e,n);a.baseQuery.whereNot(o,...t)}return e}function xn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereIn(b(e,n,"whereIn"),t),e}function Tn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereNotIn(b(e,n,"whereNotIn"),t),e}function wn(e,n,t){let a=p(e);return S(e),a.baseQuery.orWhereIn(b(e,n,"orWhereIn"),t),e}function Rn(e,n,t){let a=p(e);return S(e),a.baseQuery.orWhereNotIn(b(e,n,"orWhereNotIn"),t),e}function bn(e,n){let t=p(e);return S(e),t.baseQuery.whereNull(b(e,n,"whereNull")),e}function Cn(e,n){let t=p(e);return S(e),t.baseQuery.whereNotNull(b(e,n,"whereNotNull")),e}function Bn(e,n){let t=p(e);return S(e),t.baseQuery.orWhereNull(b(e,n,"orWhereNull")),e}function Nn(e,n){let t=p(e);return S(e),t.baseQuery.orWhereNotNull(b(e,n,"orWhereNotNull")),e}function Qn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereBetween(b(e,n,"whereBetween"),t),e}function Kn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereNotBetween(b(e,n,"whereNotBetween"),t),e}function In(e,n,t){let a=p(e);return S(e),a.baseQuery.whereLike(b(e,n,"whereLike"),t),e}function vn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereILike(b(e,n,"whereILike"),t),e}function Pn(e,n,...t){let a=p(e);return S(e),a.baseQuery.whereRaw(n,...t),e}function kn(e,n){let t=p(e);return S(e),t.baseQuery.whereExists(n),e}function En(e,n){let t=p(e);return S(e),t.baseQuery.whereNotExists(n),e}function jn(e,n,t,a,o){let r=p(e);S(e);let i=r.knex.client?.config?.client;if(i!=="pg"&&i!=="postgresql"&&i!=="postgres")throw new Error(`whereJsonPath() is only supported on PostgreSQL (got client: "${i??"unknown"}")`);let s=b(e,n,"whereJsonPath"),c=a??"=";if(c==="@?"||c==="@@"){let l=c==="@?"?"@\\?":"@@";r.baseQuery.whereRaw(`?? ${l} ?`,[s,t])}else{let l=t.startsWith("$")?t:`$.${t.replace(/\./g,".")}`;r.baseQuery.whereRaw(`jsonb_path_query_first(??, ?) ${c} ?::jsonb`,[s,l,JSON.stringify(o)])}return e}function te(e,n,t){let a=p(e);S(e);let o=N(e,n);return a.baseQuery.orderBy(o,t),e}function _n(e,n,...t){let a=p(e);return S(e),a.baseQuery.orderByRaw(n,...t),e}function $n(e,...n){let t=p(e);S(e);let a=n.map(o=>N(e,o));return t.baseQuery.groupBy(...a),e}function On(e,n,...t){let a=p(e);return S(e),a.baseQuery.groupByRaw(n,...t),e}function Dn(e,n,t,a){let o=p(e);S(e);let r=N(e,n);return o.baseQuery.having(r,t,a),e}function Vn(e,n,...t){let a=p(e);return S(e),a.baseQuery.havingRaw(n,...t),e}function ae(e,n){let t=p(e);return S(e),t.baseQuery.limit(n),e}function we(e,n){let t=p(e);return S(e),t.baseQuery.offset(n),e}async function Ln(e,n){let{page:t,pageSize:a}=n,o=p(e),i=await he(e).clone().clearSelect().clearOrder().count("* as count").first(),s=Number(i?.count??0);ae(e,a),we(e,(t-1)*a);let c=await oe(e),l=Math.ceil(s/a);return{data:c,total:s,page:t,pageSize:a,totalPages:l,hasNextPage:t<l,hasPreviousPage:t>1}}async function An(e,n){let t=n.direction??"desc",a=n.column??"id",o=p(e);n.cursor!=null&&ne(e,a,t==="desc"?"<":">",n.cursor),te(e,a,t),ae(e,n.limit+1);let r=await oe(e),i=r.length>n.limit,s=i?r.slice(0,n.limit):r,c=typeof a=="string"?a:ie(a,o.localSchema,"cursor"),l=i&&s.length>0?String(s[s.length-1][c]):null;return{data:s,nextCursor:l,hasMore:i}}async function oe(e){let t=await O(e);return t?Array.isArray(t)?t.map(a=>A(e,a)):[A(e,t)]:[]}async function Mn(e,n){let t=p(e),a={...n},o=t.localSchema.getExtension?.("beforeUpdate")??[];for(let c of o)a=await c(a)??a;let r=k(e,a),i=$(e);return i&&(r[i.updatedAt]=t.knex.fn.now()),(await t.baseQuery.update(r).returning("*")).map(c=>I(e,c))}async function Fn(e,n){if(n.length===0)return 0;let t=p(e),a=Ve(e),{propToCol:o}=R(t.localSchema),r=t.localSchema.getExtension?.("beforeUpdate")??[],i=$(e),s=[];for(let f of n){let h={...f.set};for(let x of r)h=await x(h)??h;let d=k(e,h);i&&(d[i.updatedAt]=t.knex.fn.now());let m=f.where,g=[];for(let x of a.propertyKeys){let T=x in m?m[x]:m[o.get(x)??x];if(T===void 0)throw new Error(`bulkUpdate: each \`where\` clause must include the entity's primary key (missing "${x}").`);g.push(T)}s.push({pkValues:g,set:d})}let c=new Set;for(let f of s)for(let h of Object.keys(f.set))c.add(h);if(c.size===0)return 0;let l=t.knex,y={};for(let f of c){let h=[],d=[];for(let m of s)if(f in m.set)if(a.columnNames.length===1)h.push("WHEN ?? = ? THEN ?"),d.push(a.columnNames[0],m.pkValues[0],m.set[f]);else{let g=a.columnNames.map(()=>"?? = ?").join(" AND ");h.push(`WHEN ${g} THEN ?`);for(let x=0;x<a.columnNames.length;x++)d.push(a.columnNames[x],m.pkValues[x]);d.push(m.set[f])}h.length!==0&&(y[f]=l.raw(`CASE ${h.join(" ")} ELSE ?? END`,[...d,f]))}let u=l(t.tableName).update(y);return a.columnNames.length===1?u=u.whereIn(a.columnNames[0],s.map(f=>f.pkValues[0])):u=u.where(function(){for(let f of s)this.orWhere(function(){for(let h=0;h<a.columnNames.length;h++)this.andWhere(a.columnNames[h],f.pkValues[h])})}),await u}var q=class e{constructor(n,t,a){let o=C(t);Oe(this,{knex:n,baseQuery:a??n(o),localSchema:t,specs:[],tableName:o,explicitSelects:null,selectionMode:null,appliedProjection:null,includeDeleted:!1,onlyDeleted:!1,skipDefaultScope:!1,variantConfig:void 0,enabledVariants:null,variantWhereFilters:[],variantRelationIncludes:[],cachedBuiltQuery:null})}select(...n){return Me(this,...n)}distinct(...n){return Fe(this,...n)}count(n){return qe(this,n)}countDistinct(n){return Ue(this,n)}min(n){return We(this,n)}max(n){return Je(this,n)}sum(n){return Ye(this,n)}avg(n){return He(this,n)}selectRaw(n,t){return ze(this,n,t)}projected(n){return Ge(this,n)}scoped(n){return Xe(this,n)}unscoped(){return Ze(this)}where(n,...t){return ne(this,n,...t)}andWhere(n,...t){return dn(this,n,...t)}orWhere(n,...t){return gn(this,n,...t)}whereNot(n,...t){return Sn(this,n,...t)}whereIn(n,t){return xn(this,n,t)}whereNotIn(n,t){return Tn(this,n,t)}orWhereIn(n,t){return wn(this,n,t)}orWhereNotIn(n,t){return Rn(this,n,t)}whereNull(n){return bn(this,n)}whereNotNull(n){return Cn(this,n)}orWhereNull(n){return Bn(this,n)}orWhereNotNull(n){return Nn(this,n)}whereBetween(n,t){return Qn(this,n,t)}whereNotBetween(n,t){return Kn(this,n,t)}whereLike(n,t){return In(this,n,t)}whereILike(n,t){return vn(this,n,t)}whereRaw(n,...t){return Pn(this,n,...t)}whereExists(n){return kn(this,n)}whereNotExists(n){return En(this,n)}whereJsonPath(n,t,a,o){return jn(this,n,t,a,o)}orderBy(n,t){return te(this,n,t)}orderByRaw(n,...t){return _n(this,n,...t)}groupBy(...n){return $n(this,...n)}groupByRaw(n,...t){return On(this,n,...t)}having(n,t,a){return Dn(this,n,t,a)}havingRaw(n,...t){return Vn(this,n,...t)}limit(n){return ae(this,n)}offset(n){return we(this,n)}async paginate(n){return Ln(this,n)}async paginateAfter(n){return An(this,n)}async insert(n){return en(this,n)}async insertMany(n){return nn(this,n)}onConflict(...n){return tn(this,...n)}async upsert(n,t){return an(this,n,t)}async bulkInsert(n,t){return Se(this,n,t)}async bulkUpsert(n,t){return on(this,n,t)}async update(n){return Mn(this,n)}async bulkUpdate(n){return Fn(this,n)}async delete(){return rn(this)}withDeleted(){return sn(this)}onlyDeleted(){return cn(this)}async hardDelete(){return ln(this)}async restore(){return yn(this)}joinOne(n){return Z(this,n)}joinMany(n){return ee(this,n)}include(n,t){return hn(this,n,t)}includeVariant(n,t,a){return Te(this,n,t,a)}whereVariant(n,t,a,o){let r=p(this),i=j(this);if(!i)throw new Error("whereVariant() can only be used on a polymorphic schema (created with .withVariants())");let s=i.variants[n];if(!s)throw new Error(`whereVariant: unknown variant key "${n}". Valid keys: ${Object.keys(i.variants).join(", ")}`);let c=a.toLowerCase();if(!fe.has(c))throw new Error(`whereVariant: operator "${a}" is not allowed. Allowed operators: ${[...fe].join(", ")}`);let{propToCol:l}=R(s.schema),y=l.get(t)??t,u;return s.storage==="cti"?u=`__v_${n}.${y}`:u=`${r.tableName}.${y}`,r.variantWhereFilters.push({key:n,qualifiedColumn:u,op:c,value:o}),S(this),this}selectVariants(n){let t=p(this);if(!j(this))throw new Error("selectVariants() can only be used on a polymorphic schema (created with .withVariants())");return t.enabledVariants=new Set(n),S(this),this}apply(n){let t=p(this);return S(this),n(t.baseQuery),this}transacting(n){let t=p(this),a=new e(n,t.localSchema,t.baseQuery.clone().transacting(n)),o=p(a);for(let r of t.specs)o.specs.push({...r,foreignQuery:r.foreignQuery.clone().transacting(n)});return o.explicitSelects=t.explicitSelects?[...t.explicitSelects]:null,o.selectionMode=t.selectionMode,o.appliedProjection=t.appliedProjection,o.includeDeleted=t.includeDeleted,o.onlyDeleted=t.onlyDeleted,o.skipDefaultScope=t.skipDefaultScope,o.variantConfig=t.variantConfig,o.enabledVariants=t.enabledVariants!==null?new Set(t.enabledVariants):null,o.variantWhereFilters=[...t.variantWhereFilters],o.variantRelationIncludes=[...t.variantRelationIncludes],a}toQuery(){return O(this).toQuery()}toKnexQuery(){return O(this)}toString(){return O(this).toString()}async execute(){return oe(this)}async first(){let t=await O(this).first();if(t)return A(this,t)}async pluck(n){let t=p(this),a=b(this,n,"pluck");return(await de(this).select(a)).map(r=>r[a]??r[n])}then(n,t){return this.execute().then(n,t)}};De(q);function Re(e,n,t){return new q(e,n,t)}function be(e){function n(t,a){return a?Re(e,t,a):Re(e,t)}return n.withTransaction=t=>be(t),n.transaction=t=>e.transaction(a=>t(be(a))),n}import{readFileSync as $t,renameSync as Ot,writeFileSync as Dt}from"fs";import{resolve as qn}from"path";function Vt(e){let n={};for(let t of e){let a=t.schema,o=C(a);n[o]||(n[o]=V(a));for(let r of _(a)){let i=r.getExtension("tableName");i&&!n[i]&&(n[i]=V(r))}}return{version:1,tables:n}}function Lt(e){try{let n=$t(qn(e),"utf-8"),t=JSON.parse(n);return t.version!==1||t.tables==null||typeof t.tables!="object"?{version:1,tables:{}}:t}catch{return{version:1,tables:{}}}}function At(e,n){let t=qn(e),a=t+".tmp";Dt(a,JSON.stringify(Mt(n),null,2)+`
|
|
60
|
-
`,"utf-8"),
|
|
59
|
+
});`;return{up:r,down:i}}function Ct(e,n,t){switch(t){case"integer":return e.integer(n);case"character varying":return e.string(n);case"text":return e.text(n);case"boolean":return e.boolean(n);case"timestamp without time zone":case"timestamp":return e.timestamp(n);case"double precision":case"float":return e.float(n);case"jsonb":case"json":return e.specificType(n,"jsonb");case"uuid":return e.uuid(n);default:return e.specificType(n,t)}}function De(e){let n=[];for(let a of e){let o=a.schema,r=C(o);n.push({schema:o,tableName:r});for(let i of j(o)){let s=i.getExtension("tableName");s&&n.push({schema:i,tableName:s})}}let t=new Set;return n.filter(a=>t.has(a.tableName)?!1:(t.add(a.tableName),!0))}function Bt(e){let n=new Set(e.map(y=>y.tableName)),t=new Map;for(let{schema:y,tableName:u}of e){let f=new Set,h=y.introspect().properties??{};for(let[,g]of Object.entries(h)){let m=g.introspect?.()?.extensions??{};m.references?.table&&n.has(m.references.table)&&f.add(m.references.table)}t.set(u,f)}let a=new Map,o=new Map;for(let{tableName:y}of e)a.set(y,0),o.set(y,[]);for(let{tableName:y}of e)for(let u of t.get(y)??[])o.get(u).push(y),a.set(y,(a.get(y)??0)+1);let r=[];for(let[y,u]of a)u===0&&r.push(y);let i=[];for(;r.length>0;){let y=r.shift();i.push(y);for(let u of o.get(y)??[]){let f=a.get(u)-1;a.set(u,f),f===0&&r.push(u)}}let s=new Set(i),c=e.filter(y=>!s.has(y.tableName)),l=new Map(e.map(y=>[y.tableName,y]));return[...i.map(y=>l.get(y)),...c]}function Nt(e){switch(e){case"integer":return"integer";case"character varying":return"string";case"text":return"text";case"boolean":return"boolean";case"timestamp without time zone":case"timestamp":return"timestamp";case"double precision":case"float":return"float";case"jsonb":case"json":return"jsonb";case"uuid":return"uuid";default:return`specificType('${e}')`}}function Kt(e){return e==="now"?"knex.fn.now()":typeof e=="object"&&e!==null&&e.raw?`knex.raw('${e.raw.replace(/'/g,"\\'")}')`:typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:String(e)}async function Qt(e,n,t,a){let o;if(typeof t=="string"){let i=await e.raw(t,a??[]);o=i.rows??i}else o=await t;if(!o||!Array.isArray(o))return[];let{colToProp:r}=R(n);return o.map(i=>{let s={};for(let[c,l]of Object.entries(i)){let y=r.get(c);s[y??c]=l}return s})}import{ObjectSchemaBuilder as $t,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as qe}from"@cleverbrush/schema";import{ObjectSchemaBuilder as It,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as vt}from"@cleverbrush/schema";var Le=new WeakMap;function p(e){let n=Le.get(e);if(!n)throw new Error("SchemaQueryBuilder state not found \u2014 builder was not properly initialized");return n}function Ve(e,n){Le.set(e,n)}function b(e,n,t="column"){let a=p(e);return K(n,a.localSchema,t,a.knex)}function S(e){p(e).cachedBuiltQuery=null}function G(e){return p(e).localSchema.getExtension?.("softDelete")??null}function Pt(e){let t=p(e).localSchema.getExtension?.("defaultScope");return typeof t=="function"?t:null}function _(e){return p(e).localSchema.getExtension?.("timestamps")??null}var he=new Set(["=","!=","<>","<",">","<=",">=","like","not like","ilike","not ilike","in","not in","is","is not"]);function E(e){let n=p(e);if(n.variantConfig!==void 0)return n.variantConfig;let t=ie(n.localSchema);if(!t)return n.variantConfig=null,null;let{propToCol:a}=R(n.localSchema),o=a.get(t.discriminatorKey)??t.discriminatorKey;return n.variantConfig={...t,discriminatorColumn:o},n.variantConfig}function kt(e,n,t){let a=p(e),o=a.knex,r=a.tableName,i=P(e,a.localSchema),s=t.discriminatorColumn,c=n.clone().select(`${r}.*`);for(let[l,y]of Object.entries(t.variants))if(!(a.enabledVariants!==null&&!a.enabledVariants.has(l))&&y.storage==="cti"){let u=`__v_${l}`,f=y.tableName,h=y.foreignKey;c.leftJoin(`${f} as ${u}`,o.raw("?? = ?? AND ?? = ?",[`${u}.${h}`,`${r}.${i}`,`${r}.${s}`,l]));let{propToCol:g}=R(y.schema),d=y.schema.introspect().properties??{};for(let x of Object.keys(d)){let T=g.get(x)??x;c.select(o.raw("?? as ??",[`${u}.${T}`,`${u}__${T}`]))}}for(let l of a.variantRelationIncludes){let y=t.variants[l.variantKey];if(!y)continue;let u=y.relations.find(m=>m.name===l.relationName);if(!u)continue;let f=Z(e,u.schema),h=C(f),g=`__v_${l.variantKey}__rel_${l.relationName}`;if(u.type==="belongsTo"||u.type==="hasOne"){let m,d;u.type==="belongsTo"?(m=u.foreignKey??(()=>{throw new Error(`includeVariant: relation "${l.relationName}" on variant "${l.variantKey}" requires foreignKey`)})(),d=P(e,f)):(m=P(e,a.localSchema),d=u.foreignKey??(()=>{throw new Error(`includeVariant: relation "${l.relationName}" on variant "${l.variantKey}" requires foreignKey`)})());let x,T=`__v_${l.variantKey}`;y.storage==="cti"?u.type==="belongsTo"?x=`${g}.${d} = ${T}.${m} AND ${r}.${s} = '${l.variantKey}'`:x=`${g}.${d} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`:u.type==="belongsTo"?x=`${g}.${d} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`:x=`${g}.${d} = ${r}.${m} AND ${r}.${s} = '${l.variantKey}'`;let w=a.knex(h),N=Ot(e,f,g,h,l.customize);c.leftJoin(o.raw("?? as ??",[h,g]),o.raw(x));for(let v of N)c.select(v)}}for(let l of a.variantWhereFilters){let y=`${r}.${s}`;c.where(function(){this.where(y,l.key).andWhere(l.qualifiedColumn,l.op,l.value).orWhere(y,"!=",l.key)})}return a.enabledVariants!==null&&c.whereIn(`${r}.${s}`,[...a.enabledVariants]),c}var X=null;function Ae(e){X=e}function V(){return X}function Ot(e,n,t,a,o){let r=p(e),i=r.knex,{propToCol:s}=R(n),l=n.introspect().properties??{},y;if(o){let u=new X(r.knex,n,r.knex(a));o(u);let h=p(u).explicitSelects;h&&h.length>0?y=h:y=Object.keys(l).map(g=>s.get(g)??g)}else y=Object.keys(l).map(u=>s.get(u)??u);return y.map(u=>i.raw("?? as ??",[`${t}.${u}`,`${t}__${u}`]))}function Et(e,n,t){let a=p(e),{colToProp:o}=R(a.localSchema),r={};for(let[c,l]of Object.entries(n)){if(c.startsWith("__v_"))continue;let y=o.get(c);y?r[y]=l:r[c]=l}let i=t.discriminatorKey,s=r[i];if(s!=null){let c=t.variants[s];if(c)if(c.storage==="cti"){let{colToProp:l}=R(c.schema),u=`${`__v_${s}`}__`,f=c.foreignKey;if(f){let h=`${u}${f}`;if(!c.allowOrphan&&n[h]==null)throw new Error(`Polymorphic orphan: "${i}" = "${s}" but no matching row found in variant table "${c.tableName}". Set allowOrphan: true on this variant to suppress.`)}for(let[h,g]of Object.entries(n)){if(!h.startsWith(u))continue;let m=h.slice(u.length);if(m===f)continue;let d=l.get(m)??m;r[d]=g}}else{let{colToProp:l}=R(c.schema);for(let[y,u]of Object.entries(n)){if(y.startsWith("__v_")||o.has(y))continue;let f=l.get(y);f&&(r[f]=u)}}}if(a.variantRelationIncludes.length>0&&s!=null){let c=t.variants[s];if(c)for(let l of a.variantRelationIncludes){if(l.variantKey!==s)continue;let y=c.relations.find(u=>u.name===l.relationName);if(y&&(y.type==="belongsTo"||y.type==="hasOne")){let f=`${`__v_${s}__rel_${l.relationName}`}__`,h=Z(e,y.schema),{colToProp:g}=R(h),m={},d=!1;for(let[x,T]of Object.entries(n)){if(!x.startsWith(f))continue;let w=x.slice(f.length),N=g.get(w)??w;m[N]=T,T!=null&&(d=!0)}r[l.relationName]=d?m:null}}}return r}function Z(e,n){return typeof n=="function"?n():n}function P(e,n){let t=J(n);return t.columnNames.length>0?t.columnNames[0]:"id"}function Me(e){let n=p(e),t=J(n.localSchema);if(t.columnNames.length===0)throw new Error("No primary key declared on this schema. Use `.primaryKey()` on a column or `.hasPrimaryKey([...])` on the schema.");return t}function de(e){let n=p(e),t=n.baseQuery,a=!1,o=G(e);if(o&&n.onlyDeleted?(a||(t=t.clone(),a=!0),t.whereNotNull(o.column)):o&&!n.includeDeleted&&(a||(t=t.clone(),a=!0),t.whereNull(o.column)),!n.skipDefaultScope){let r=Pt(e);if(r){a||(t=t.clone(),a=!0);let i=new X(n.knex,n.localSchema,t),s=p(i);s.skipDefaultScope=!0,r(i)}}return t}function jt(e,n,t,a){let r=p(e).knex,i=t.foreignQuery,s=i._single?.table;if(!s)throw new Error(`Could not determine table name from foreignQuery for "${t.as}". Make sure foreignQuery is created via knex("tableName").`);n.select(r.raw(":relationAlias:.:as:->0 as :as:",{relationAlias:a,as:t.as}));let c=r.from(i.as(s)).select(r.raw(":foreignTable:.:foreignColumn:",{foreignTable:s,foreignColumn:t.foreignColumn})).select(r.raw("jsonb_agg(:foreignTable:) as :as:",{foreignTable:s,as:t.as})).groupByRaw(":foreignTable:.:foreignColumn:",{foreignTable:s,foreignColumn:t.foreignColumn}).as(a),l=t.required?"join":"leftJoin";n[l](c,function(){this.on(r.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{originalQuery:"originalQuery",relationAlias:a,foreignColumn:t.foreignColumn,localColumn:t.localColumn}))})}function _t(e,n,t,a,o){let i=p(e).knex,s=`withFilter${o}`,c=t.limit!==null&&t.limit>0||t.offset!==null&&t.offset>0,l=t.orderBy?t.orderBy.column:t.foreignColumn,y=t.orderBy?t.orderBy.direction:"asc";c?n.with(s,i.from(t.foreignQuery.clone().whereIn(t.foreignColumn,i.from(i.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(t.localColumn).as(`__wf_inner_${o}`)).as(`__wf_inner_${o}`)).select(`__wf_inner_${o}.*`).select(i.raw(`row_number() over(partition by :foreignColumn: order by :orderByColumn: ${y}) as "__rn__"`,{foreignColumn:t.foreignColumn,orderByColumn:l}))):n.with(s,t.foreignQuery.clone().whereIn(t.foreignColumn,i.from(i.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(t.localColumn)));let u=i.from(s);if(c){let h=t.limit!==null&&t.limit>0,g=t.offset!==null&&t.offset>0,m=t.offset??0,d=m+(t.limit??0),x=h&&g?'"__rn__" > :offset and "__rn__" <= :limit':h?'"__rn__" <= :limit':'"__rn__" > :offset';u.whereRaw(x,{limit:d,offset:m}),u.select(i.raw(":foreignColumn:",{foreignColumn:t.foreignColumn})),u.select(i.raw(`coalesce(jsonb_agg(to_jsonb(:filterName:) - '__rn__' order by "__rn__"), '[]'::jsonb) as :as:`,{filterName:s,as:t.as}))}else{u.select(i.raw(":foreignColumn:",{foreignColumn:t.foreignColumn}));let h=t.orderBy?`jsonb_agg(:filterName: order by :filterName:.:orderByColumn: ${y})`:"jsonb_agg(:filterName:)";u.select(i.raw(`coalesce(${h}, '[]'::jsonb) as :as:`,t.orderBy?{filterName:s,orderByColumn:l,as:t.as}:{filterName:s,as:t.as}))}u.groupByRaw(":foreignColumn:",{foreignColumn:t.foreignColumn});let f=u.as(a);n.select(i.raw("coalesce(:relationAlias:.:as:, '[]'::jsonb) as :as:",{relationAlias:a,as:t.as})),n.leftJoin(f,function(){this.on(i.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{relationAlias:a,foreignColumn:t.foreignColumn,originalQuery:"originalQuery",localColumn:t.localColumn}))})}function ge(e){let n=p(e),t=de(e),a=E(e),o=a?kt(e,t,a):t;if(n.specs.length===0)return o;let r=n.knex,i=n.specs,s=[...new Set(i.map(u=>u.localColumn))],c=o,l=[];if(n.explicitSelects!==null){let u=new Set(n.explicitSelects);if(l=s.filter(f=>!u.has(f)),l.length>0){c=o.clone();for(let f of l)c.column(f)}}let y=r.queryBuilder().with("originalQuery",c);if(l.length>0&&n.explicitSelects!==null)for(let u of n.explicitSelects)y.select(r.raw(":originalQuery:.:col: as :col:",{originalQuery:"originalQuery",col:u}));else y.select("originalQuery.*");y.from(r.raw(":originalQuery:",{originalQuery:"originalQuery"}));for(let u=0;u<i.length;u++){let f=i[u],h=`eagerRelation${u}`;f.type==="one"?jt(e,y,f,h):_t(e,y,f,h,u)}return y}function $(e){let n=p(e);return n.cachedBuiltQuery||(n.cachedBuiltQuery=ge(e)),n.cachedBuiltQuery}function I(e,n){if(!n)return n;let t=E(e);if(t)return Et(e,n,t);let a=p(e),{colToProp:o}=R(a.localSchema),r={};for(let[i,s]of Object.entries(n)){let c=o.get(i);c?r[c]=s:r[i]=s}return r}function A(e,n){let t=p(e),a=t.specs.filter(i=>i.type==="one"),o=t.specs.filter(i=>i.type==="many"),r=pe(n,a,o);return I(e,r)}function k(e,n){let t=p(e),{propToCol:a}=R(t.localSchema),o={};for(let[r,i]of Object.entries(n)){let s=a.get(r);s?o[s]=i:o[r]=i}return o}function M(e,n){return k(e,n)}function B(e,n){return typeof n=="string"||typeof n=="function"?b(e,n,"column"):n}function F(e,n){let t=p(e);try{let a=It.getPropertiesFor(t.localSchema),o=n(a);if(o&&typeof o=="object"&&vt in o)return!0}catch{}return!1}function O(e,n){let t=p(e);if(t.selectionMode==="projection")throw new Error(`Cannot call .${n}() after .projected('${t.appliedProjection}'). Choose one column-selection mode per query.`)}function Fe(e,n){let t=p(e);if(t.selectionMode==="select")throw new Error(`Cannot call .${n}() after .select(). Choose one column-selection mode per query.`);if(t.selectionMode==="aggregate")throw new Error(`Cannot call .${n}() after an aggregate method. Choose one column-selection mode per query.`);if(t.selectionMode==="projection")throw new Error(`Cannot call .${n}() after .projected('${t.appliedProjection}'). Choose one column-selection mode per query.`)}function Ue(e,...n){let t=p(e);if(n.length===1&&typeof n[0]=="function"){let o=n[0],r=$t.getPropertiesFor(t.localSchema),i=o(r);if(i&&typeof i=="object"&&!(qe in i)){S(e),O(e,"select"),t.selectionMode="projection",t.appliedProjection="<inline>";let s={};t.explicitSelects??=[];for(let[c,l]of Object.entries(i)){if(!l||typeof l!="object"||!(qe in l))throw new Error(`select(selector): value for alias "${c}" must be a property descriptor (e.g. \`t.someProp\`).`);let y=b(e,(()=>l),`select(selector).${c}`);s[c]=y,t.explicitSelects.push(y)}return t.baseQuery.select(s),e}}S(e),O(e,"select"),t.selectionMode="select";let a=n.map(o=>B(e,o));t.baseQuery.select(...a),t.explicitSelects??=[];for(let o of a)typeof o=="string"&&t.explicitSelects.push(o);return e}function We(e,...n){S(e);let t=n.map(a=>B(e,a));return p(e).baseQuery.distinct(...t),e}function Je(e,n){let t=p(e);return S(e),O(e,"count"),t.selectionMode="aggregate",n?t.baseQuery.count(B(e,n)):t.baseQuery.count(),e}function He(e,n){let t=p(e);return S(e),O(e,"countDistinct"),t.selectionMode="aggregate",n?t.baseQuery.countDistinct(B(e,n)):t.baseQuery.countDistinct(),e}function Ye(e,n){let t=p(e);return S(e),O(e,"min"),t.selectionMode="aggregate",t.baseQuery.min(B(e,n)),e}function ze(e,n){let t=p(e);return S(e),O(e,"max"),t.selectionMode="aggregate",t.baseQuery.max(B(e,n)),e}function Ge(e,n){let t=p(e);return S(e),O(e,"sum"),t.selectionMode="aggregate",t.baseQuery.sum(B(e,n)),e}function Xe(e,n){let t=p(e);return S(e),O(e,"avg"),t.selectionMode="aggregate",t.baseQuery.avg(B(e,n)),e}function Ze(e,n,t){let a=p(e);return S(e),t?a.baseQuery.select(a.knex.raw(n,t)):a.baseQuery.select(a.knex.raw(n)),e}function en(e,n){let t=p(e);if(Fe(e,"projected"),t.selectionMode==="projection")throw new Error(`Cannot call .projected('${n}') \u2014 .projected('${t.appliedProjection}') was already applied. Only one projection per query.`);let o=se(t.localSchema)[n];if(!o)throw new Error(`Unknown projection "${n}" on schema for table "${t.tableName}"`);let{propToCol:r}=R(t.localSchema),i=o.keys.map(s=>r.get(s)??s);t.baseQuery.select(...i),t.explicitSelects??=[];for(let s of i)t.explicitSelects.push(s);return t.selectionMode="projection",t.appliedProjection=n,S(e),e}function nn(e,n){let t=p(e);S(e);let o=t.localSchema.getExtension?.("scopes")?.[n];if(!o)throw new Error(`Unknown scope "${n}" on schema for table "${t.tableName}"`);return o(e),e}function tn(e){let n=p(e);return S(e),n.skipDefaultScope=!0,n.includeDeleted=!0,e}var Se=class{#e;#n;#t;constructor(n,t,a,o){this.#e=n,this.#n=t,this.#t=o}async merge(n,t,a){let o,r=a;return a===void 0&&Dt(t)?r=t:o=t,this.#a(n,"merge",o,r)}async ignore(n){return this.#a(n,"ignore")}async#a(n,t,a,o){let r=C(this.#n),i=this.#n.getExtension?.("timestamps")??null,s=this.#n.getExtension?.("beforeInsert")??[],c={...n};for(let m of s)c=await m(c)??c;let{propToCol:l}=R(this.#n),y={};for(let[m,d]of Object.entries(c))y[l.get(m)??m]=d;i&&(y[i.createdAt]=this.#e.fn.now(),y[i.updatedAt]=this.#e.fn.now());let u=this.#e(r).insert(y).onConflict(this.#t);if(t==="ignore")u=u.ignore();else{let m=this.#r(),d;if(a){d={};for(let[x,T]of Object.entries(a))d[l.get(x)??x]=typeof T=="function"?T(m):T}else d={...y},i&&(delete d[i.createdAt],d[i.updatedAt]=this.#e.fn.now());u=u.merge(d),o?.where?.(u,m)}let f=await u.returning("*");if(!f||f.length===0)return;let{colToProp:h}=R(this.#n),g={};for(let[m,d]of Object.entries(f[0]))g[h.get(m)??m]=d;return g}#r(){return{knex:this.#e,column:n=>this.#o(n),raw:(n,t=[])=>this.#e.raw(n,t),excluded:n=>this.#e.raw("excluded.??",[this.#o(n)])}}#o(n){let t=K(n,this.#n,"onConflict.merge",this.#e);if(typeof t!="string")throw new Error("onConflict.merge only accepts top-level column references");return t}};function Dt(e){if(!e||typeof e!="object")return!1;let n=Object.keys(e);return n.length>0&&n.every(t=>t==="where")}async function an(e,n){let t=p(e),a={...n},o=t.localSchema.getExtension?.("beforeInsert")??[];for(let y of o)a=await y(a)??a;let r=k(e,a),i=_(e);i&&(r[i.createdAt]=t.knex.fn.now(),r[i.updatedAt]=t.knex.fn.now());let[s]=await t.knex(t.tableName).insert(r).returning("*"),c=I(e,s),l=t.localSchema.getExtension?.("afterInsert")??[];for(let y of l)await y(c);return c}async function on(e,n){let t=p(e),a=_(e),o=t.localSchema.getExtension?.("beforeInsert")??[],r=[];for(let l of n){let y={...l};for(let f of o)y=await f(y)??y;let u=k(e,y);a&&(u[a.createdAt]=t.knex.fn.now(),u[a.updatedAt]=t.knex.fn.now()),r.push(u)}let s=(await t.knex(t.tableName).insert(r).returning("*")).map(l=>I(e,l)),c=t.localSchema.getExtension?.("afterInsert")??[];for(let l of s)for(let y of c)await y(l);return s}function rn(e,...n){let t=p(e),a=n.map(o=>b(e,o,"onConflict"));return new Se(t.knex,t.localSchema,e,a)}async function sn(e,n,t){let a=p(e),o=t.conflictColumns.map(s=>b(e,s,"upsert")),r=a.knex(a.tableName).insert(k(e,n)).onConflict(o);if(t.updateColumns&&t.updateColumns.length>0){let s=t.updateColumns.map(c=>b(e,c,"upsert"));r.merge(s)}else r.merge();let[i]=await r.returning("*");return I(e,i)}async function xe(e,n,t){if(n.length===0)return[];let a=p(e),o=t?.chunkSize??500,r=Object.keys(n[0]).length||1,i=Math.max(1,Math.floor(6e4/Math.max(1,r))),s=Math.max(1,Math.min(o,i)),c=_(e),l=a.localSchema.getExtension?.("beforeInsert")??[],y=a.localSchema.getExtension?.("afterInsert")??[],u=t?.onConflict&&t.conflictColumns?t.conflictColumns.map(h=>b(e,h,"bulkInsert.onConflict")):null;if(t?.onConflict&&(!u||u.length===0))throw new Error("bulkInsert: `conflictColumns` is required when `onConflict` is set.");let f=[];for(let h=0;h<n.length;h+=s){let g=n.slice(h,h+s),m=[];for(let T of g){let w={...T};for(let v of l)w=await v(w)??w;let N=k(e,w);c&&(N[c.createdAt]=a.knex.fn.now(),N[c.updatedAt]=a.knex.fn.now()),m.push(N)}let d=a.knex(a.tableName).insert(m);if(u)if(d=d.onConflict(u),t.onConflict==="ignore")d=d.ignore();else{let T=new Set;for(let w of m)for(let N of Object.keys(w))T.add(N);for(let w of u)T.delete(w);c&&(T.delete(c.createdAt),T.add(c.updatedAt)),d=d.merge(Array.from(T))}let x=await d.returning("*");for(let T of x){let w=I(e,T);for(let N of y)await N(w);f.push(w)}}return f}async function cn(e,n,t){return xe(e,n,{chunkSize:t.chunkSize,onConflict:"merge",conflictColumns:t.conflictColumns})}async function ln(e){let n=p(e),t=n.localSchema.getExtension?.("beforeDelete")??[];for(let o of t)await o(e);let a=G(e);return a?n.baseQuery.update({[a.column]:n.knex.fn.now()}):n.baseQuery.delete()}function yn(e){let n=p(e);return S(e),n.includeDeleted=!0,e}function un(e){let n=p(e);return S(e),n.onlyDeleted=!0,n.includeDeleted=!0,e}async function mn(e){let n=p(e),t=n.localSchema.getExtension?.("beforeDelete")??[];for(let a of t)await a(e);return n.baseQuery.delete()}async function pn(e){let n=p(e),t=G(e);if(!t)throw new Error("Schema does not have soft delete enabled. Use .softDelete() on the schema.");return(await n.baseQuery.update({[t.column]:null}).returning("*")).map(o=>I(e,o))}function fn(e,n){if(e.foreignQuery)return"toKnexQuery"in e.foreignQuery?e.foreignQuery.toKnexQuery():e.foreignQuery;let t=C(e.foreignSchema);return n(t)}function hn(e,n,t){let a=K(e.localColumn,n,"localColumn"),o=K(e.foreignColumn,e.foreignSchema,"foreignColumn");if(typeof e.as!="string"||!e.as)throw new Error("as must be a non-empty string");let r=fn(e,t),i=e.required!==!1;return e.mappers!==void 0&&gn(e.mappers),{localColumn:a,foreignColumn:o,as:e.as,required:i,foreignQuery:r,mappers:e.mappers}}function dn(e,n,t){let a=K(e.localColumn,n,"localColumn"),o=K(e.foreignColumn,e.foreignSchema,"foreignColumn");if(typeof e.as!="string"||!e.as)throw new Error("as must be a non-empty string");let r=fn(e,t);e.mappers!==void 0&&gn(e.mappers);let i=Number.isFinite(e.limit)&&e.limit>0?e.limit:null,s=Number.isFinite(e.offset)&&e.offset>0?e.offset:null,c=e.orderBy?{column:K(e.orderBy.column,e.foreignSchema,"orderBy.column"),direction:e.orderBy.direction??"asc"}:null;return{localColumn:a,foreignColumn:o,as:e.as,foreignQuery:r,limit:i,offset:s,orderBy:c,mappers:e.mappers}}function gn(e){if(typeof e!="object"||e===null)throw new Error("mappers must be an object");for(let n of Object.keys(e)){let t=e[n];if(typeof t=="string"){if(typeof D[t]!="function")throw new Error(`mapper for "${n}": unknown built-in mapper name "${t}"`)}else if(typeof t!="function")throw new Error(`mapper for "${n}" must be a function or a built-in mapper name`)}}function Te(e){let n=new Set;for(let t of e){if(n.has(t.as))throw new Error(`duplicate field name: ${t.as}`);n.add(t.as)}}function ee(e,n){let t=p(e),a=hn(n,t.localSchema,t.knex);return t.specs.push({type:"one",...a}),Te(t.specs),S(e),e}function ne(e,n){let t=p(e),a=dn(n,t.localSchema,t.knex);return t.specs.push({type:"many",...a}),Te(t.specs),S(e),e}function Sn(e,n,t){let a=p(e);S(e);let r=(a.localSchema.getExtension?.("relations")??[]).find(c=>c.name===n);if(!r){let c=E(e);if(c){let l=[];for(let[y,u]of Object.entries(c.variants))u.relations.some(f=>f.name===n)&&l.push({variantKey:y});if(l.length===1)return we(e,l[0].variantKey,n,t);if(l.length>1)throw new Error(`Ambiguous relation "${n}" \u2014 found on variants: ${l.map(y=>y.variantKey).join(", ")}. Use .includeVariant(key, name) to be explicit.`)}throw new Error(`Unknown relation "${n}" on schema for table "${a.tableName}"`)}let i=Z(e,r.schema),s=C(i);switch(r.type){case"belongsTo":{let c=K(r.foreignKey,a.localSchema,"foreignKey"),l=P(e,i),y=a.knex(s);if(t){let u=V(),f=new u(a.knex,i,y);t(f)}ee(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,foreignQuery:y});break}case"hasOne":{let c=P(e,a.localSchema),l=K(r.foreignKey,i,"foreignKey"),y=a.knex(s);if(t){let u=V(),f=new u(a.knex,i,y);t(f)}ee(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,required:!1,foreignQuery:y});break}case"hasMany":{let c=P(e,a.localSchema),l=K(r.foreignKey,i,"foreignKey"),y=a.knex(s);if(t){let u=V(),f=new u(a.knex,i,y);t(f)}ne(e,{foreignSchema:i,localColumn:c,foreignColumn:l,as:n,foreignQuery:y});break}case"belongsToMany":{let c=r.through,l=P(e,a.localSchema),y=a.knex(s).join(c.table,`${c.table}.${c.foreignKey}`,`${s}.${P(e,i)}`).select(`${s}.*`,`${c.table}.${c.localKey}`);if(t){let u=V(),f=new u(a.knex,i,y);t(f)}ne(e,{foreignSchema:i,localColumn:l,foreignColumn:c.localKey,as:n,foreignQuery:y});break}}return e}function we(e,n,t,a){let o=p(e);S(e);let r=E(e);if(!r)throw new Error(`includeVariant: schema for table "${o.tableName}" is not polymorphic (no .withVariants() config found)`);let i=r.variants[n];if(!i)throw new Error(`includeVariant: unknown variant key "${n}" on schema for table "${o.tableName}"`);if(!i.relations.find(c=>c.name===t))throw new Error(`includeVariant: unknown relation "${t}" on variant "${n}" of table "${o.tableName}"`);return o.variantRelationIncludes.push({variantKey:n,relationName:t,customize:a}),e}function te(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.where(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.where(o,...t)}else{let o=B(e,n);a.baseQuery.where(o,...t)}return e}function xn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.andWhere(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.andWhere(o,...t)}else{let o=B(e,n);a.baseQuery.andWhere(o,...t)}return e}function Tn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.orWhere(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.orWhere(o,...t)}else{let o=B(e,n);a.baseQuery.orWhere(o,...t)}return e}function wn(e,n,...t){let a=p(e);if(S(e),typeof n=="function"&&!F(e,n))a.baseQuery.whereNot(n,...t);else if(typeof n=="object"&&n!==null&&!("toSQL"in n)){let o=M(e,n);a.baseQuery.whereNot(o,...t)}else{let o=B(e,n);a.baseQuery.whereNot(o,...t)}return e}function Rn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereIn(b(e,n,"whereIn"),t),e}function bn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereNotIn(b(e,n,"whereNotIn"),t),e}function Cn(e,n,t){let a=p(e);return S(e),a.baseQuery.orWhereIn(b(e,n,"orWhereIn"),t),e}function Bn(e,n,t){let a=p(e);return S(e),a.baseQuery.orWhereNotIn(b(e,n,"orWhereNotIn"),t),e}function Nn(e,n){let t=p(e);return S(e),t.baseQuery.whereNull(b(e,n,"whereNull")),e}function Kn(e,n){let t=p(e);return S(e),t.baseQuery.whereNotNull(b(e,n,"whereNotNull")),e}function Qn(e,n){let t=p(e);return S(e),t.baseQuery.orWhereNull(b(e,n,"orWhereNull")),e}function In(e,n){let t=p(e);return S(e),t.baseQuery.orWhereNotNull(b(e,n,"orWhereNotNull")),e}function vn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereBetween(b(e,n,"whereBetween"),t),e}function Pn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereNotBetween(b(e,n,"whereNotBetween"),t),e}function kn(e,n,t){let a=p(e);return S(e),a.baseQuery.whereLike(b(e,n,"whereLike"),t),e}function On(e,n,t){let a=p(e);return S(e),a.baseQuery.whereILike(b(e,n,"whereILike"),t),e}function En(e,n,...t){let a=p(e);return S(e),a.baseQuery.whereRaw(n,...t),e}function jn(e,n){let t=p(e);return S(e),t.baseQuery.whereExists(n),e}function _n(e,n){let t=p(e);return S(e),t.baseQuery.whereNotExists(n),e}function $n(e,n,t,a,o){let r=p(e);S(e);let i=r.knex.client?.config?.client;if(i!=="pg"&&i!=="postgresql"&&i!=="postgres")throw new Error(`whereJsonPath() is only supported on PostgreSQL (got client: "${i??"unknown"}")`);let s=b(e,n,"whereJsonPath"),c=a??"=";if(c==="@?"||c==="@@"){let l=c==="@?"?"@\\?":"@@";r.baseQuery.whereRaw(`?? ${l} ?`,[s,t])}else{let l=t.startsWith("$")?t:`$.${t.replace(/\./g,".")}`;r.baseQuery.whereRaw(`jsonb_path_query_first(??, ?) ${c} ?::jsonb`,[s,l,JSON.stringify(o)])}return e}function ae(e,n,t){let a=p(e);S(e);let o=B(e,n);return a.baseQuery.orderBy(o,t),e}function Dn(e,n,...t){let a=p(e);return S(e),a.baseQuery.orderByRaw(n,...t),e}function Ln(e,...n){let t=p(e);S(e);let a=n.map(o=>B(e,o));return t.baseQuery.groupBy(...a),e}function Vn(e,n,...t){let a=p(e);return S(e),a.baseQuery.groupByRaw(n,...t),e}function An(e,n,t,a){let o=p(e);S(e);let r=B(e,n);return o.baseQuery.having(r,t,a),e}function Mn(e,n,...t){let a=p(e);return S(e),a.baseQuery.havingRaw(n,...t),e}function oe(e,n){let t=p(e);return S(e),t.baseQuery.limit(n),e}function Re(e,n){let t=p(e);return S(e),t.baseQuery.offset(n),e}async function Fn(e,n){let{page:t,pageSize:a}=n,o=p(e),i=await de(e).clone().clearSelect().clearOrder().count("* as count").first(),s=Number(i?.count??0);oe(e,a),Re(e,(t-1)*a);let c=await re(e),l=Math.ceil(s/a);return{data:c,total:s,page:t,pageSize:a,totalPages:l,hasNextPage:t<l,hasPreviousPage:t>1}}async function qn(e,n){let t=n.direction??"desc",a=n.column??"id",o=p(e);n.cursor!=null&&te(e,a,t==="desc"?"<":">",n.cursor),ae(e,a,t),oe(e,n.limit+1);let r=await re(e),i=r.length>n.limit,s=i?r.slice(0,n.limit):r,c=typeof a=="string"?a:ce(a,o.localSchema,"cursor"),l=i&&s.length>0?String(s[s.length-1][c]):null;return{data:s,nextCursor:l,hasMore:i}}async function re(e){let t=await $(e);return t?Array.isArray(t)?t.map(a=>A(e,a)):[A(e,t)]:[]}async function Un(e,n){let t=p(e),a={...n},o=t.localSchema.getExtension?.("beforeUpdate")??[];for(let c of o)a=await c(a)??a;let r=k(e,a),i=_(e);return i&&(r[i.updatedAt]=t.knex.fn.now()),(await t.baseQuery.update(r).returning("*")).map(c=>I(e,c))}async function Wn(e,n){if(n.length===0)return 0;let t=p(e),a=Me(e),{propToCol:o}=R(t.localSchema),r=t.localSchema.getExtension?.("beforeUpdate")??[],i=_(e),s=[];for(let f of n){let h={...f.set};for(let x of r)h=await x(h)??h;let g=k(e,h);i&&(g[i.updatedAt]=t.knex.fn.now());let m=f.where,d=[];for(let x of a.propertyKeys){let T=x in m?m[x]:m[o.get(x)??x];if(T===void 0)throw new Error(`bulkUpdate: each \`where\` clause must include the entity's primary key (missing "${x}").`);d.push(T)}s.push({pkValues:d,set:g})}let c=new Set;for(let f of s)for(let h of Object.keys(f.set))c.add(h);if(c.size===0)return 0;let l=t.knex,y={};for(let f of c){let h=[],g=[];for(let m of s)if(f in m.set)if(a.columnNames.length===1)h.push("WHEN ?? = ? THEN ?"),g.push(a.columnNames[0],m.pkValues[0],m.set[f]);else{let d=a.columnNames.map(()=>"?? = ?").join(" AND ");h.push(`WHEN ${d} THEN ?`);for(let x=0;x<a.columnNames.length;x++)g.push(a.columnNames[x],m.pkValues[x]);g.push(m.set[f])}h.length!==0&&(y[f]=l.raw(`CASE ${h.join(" ")} ELSE ?? END`,[...g,f]))}let u=l(t.tableName).update(y);return a.columnNames.length===1?u=u.whereIn(a.columnNames[0],s.map(f=>f.pkValues[0])):u=u.where(function(){for(let f of s)this.orWhere(function(){for(let h=0;h<a.columnNames.length;h++)this.andWhere(a.columnNames[h],f.pkValues[h])})}),await u}var q=class e{constructor(n,t,a){let o=C(t);Ve(this,{knex:n,baseQuery:a??n(o),localSchema:t,specs:[],tableName:o,explicitSelects:null,selectionMode:null,appliedProjection:null,includeDeleted:!1,onlyDeleted:!1,skipDefaultScope:!1,variantConfig:void 0,enabledVariants:null,variantWhereFilters:[],variantRelationIncludes:[],cachedBuiltQuery:null})}select(...n){return Ue(this,...n)}distinct(...n){return We(this,...n)}count(n){return Je(this,n)}countDistinct(n){return He(this,n)}min(n){return Ye(this,n)}max(n){return ze(this,n)}sum(n){return Ge(this,n)}avg(n){return Xe(this,n)}selectRaw(n,t){return Ze(this,n,t)}projected(n){return en(this,n)}scoped(n){return nn(this,n)}unscoped(){return tn(this)}where(n,...t){return te(this,n,...t)}andWhere(n,...t){return xn(this,n,...t)}orWhere(n,...t){return Tn(this,n,...t)}whereNot(n,...t){return wn(this,n,...t)}whereIn(n,t){return Rn(this,n,t)}whereNotIn(n,t){return bn(this,n,t)}orWhereIn(n,t){return Cn(this,n,t)}orWhereNotIn(n,t){return Bn(this,n,t)}whereNull(n){return Nn(this,n)}whereNotNull(n){return Kn(this,n)}orWhereNull(n){return Qn(this,n)}orWhereNotNull(n){return In(this,n)}whereBetween(n,t){return vn(this,n,t)}whereNotBetween(n,t){return Pn(this,n,t)}whereLike(n,t){return kn(this,n,t)}whereILike(n,t){return On(this,n,t)}whereRaw(n,...t){return En(this,n,...t)}whereExists(n){return jn(this,n)}whereNotExists(n){return _n(this,n)}whereJsonPath(n,t,a,o){return $n(this,n,t,a,o)}orderBy(n,t){return ae(this,n,t)}orderByRaw(n,...t){return Dn(this,n,...t)}groupBy(...n){return Ln(this,...n)}groupByRaw(n,...t){return Vn(this,n,...t)}having(n,t,a){return An(this,n,t,a)}havingRaw(n,...t){return Mn(this,n,...t)}limit(n){return oe(this,n)}offset(n){return Re(this,n)}async paginate(n){return Fn(this,n)}async paginateAfter(n){return qn(this,n)}async insert(n){return an(this,n)}async insertMany(n){return on(this,n)}onConflict(...n){return rn(this,...n)}async upsert(n,t){return sn(this,n,t)}async bulkInsert(n,t){return xe(this,n,t)}async bulkUpsert(n,t){return cn(this,n,t)}async update(n){return Un(this,n)}async bulkUpdate(n){return Wn(this,n)}async delete(){return ln(this)}withDeleted(){return yn(this)}onlyDeleted(){return un(this)}async hardDelete(){return mn(this)}async restore(){return pn(this)}joinOne(n){return ee(this,n)}joinMany(n){return ne(this,n)}include(n,t){return Sn(this,n,t)}includeVariant(n,t,a){return we(this,n,t,a)}whereVariant(n,t,a,o){let r=p(this),i=E(this);if(!i)throw new Error("whereVariant() can only be used on a polymorphic schema (created with .withVariants())");let s=i.variants[n];if(!s)throw new Error(`whereVariant: unknown variant key "${n}". Valid keys: ${Object.keys(i.variants).join(", ")}`);let c=a.toLowerCase();if(!he.has(c))throw new Error(`whereVariant: operator "${a}" is not allowed. Allowed operators: ${[...he].join(", ")}`);let{propToCol:l}=R(s.schema),y=l.get(t)??t,u;return s.storage==="cti"?u=`__v_${n}.${y}`:u=`${r.tableName}.${y}`,r.variantWhereFilters.push({key:n,qualifiedColumn:u,op:c,value:o}),S(this),this}selectVariants(n){let t=p(this);if(!E(this))throw new Error("selectVariants() can only be used on a polymorphic schema (created with .withVariants())");return t.enabledVariants=new Set(n),S(this),this}apply(n){let t=p(this);return S(this),n(t.baseQuery),this}transacting(n){let t=p(this),a=new e(n,t.localSchema,t.baseQuery.clone().transacting(n)),o=p(a);for(let r of t.specs)o.specs.push({...r,foreignQuery:r.foreignQuery.clone().transacting(n)});return o.explicitSelects=t.explicitSelects?[...t.explicitSelects]:null,o.selectionMode=t.selectionMode,o.appliedProjection=t.appliedProjection,o.includeDeleted=t.includeDeleted,o.onlyDeleted=t.onlyDeleted,o.skipDefaultScope=t.skipDefaultScope,o.variantConfig=t.variantConfig,o.enabledVariants=t.enabledVariants!==null?new Set(t.enabledVariants):null,o.variantWhereFilters=[...t.variantWhereFilters],o.variantRelationIncludes=[...t.variantRelationIncludes],a}toQuery(){return $(this).toQuery()}toKnexQuery(){return $(this)}toString(){return $(this).toString()}async execute(){return re(this)}async first(){let t=await $(this).first();if(t)return A(this,t)}async pluck(n){let t=p(this),a=b(this,n,"pluck");return(await ge(this).select(a)).map(r=>r[a]??r[n])}then(n,t){return this.execute().then(n,t)}};Ae(q);function be(e,n,t){return new q(e,n,t)}function Ce(e){function n(t,a){return a?be(e,t,a):be(e,t)}return n.withTransaction=t=>Ce(t),n.transaction=t=>e.transaction(a=>t(Ce(a))),n}import{readFileSync as Lt,renameSync as Vt,writeFileSync as At}from"fs";import{resolve as Jn}from"path";function Mt(e){let n={};for(let t of e){let a=t.schema,o=C(a);n[o]||(n[o]=L(a));for(let r of j(a)){let i=r.getExtension("tableName");i&&!n[i]&&(n[i]=L(r))}}return{version:1,tables:n}}function Ft(e){try{let n=Lt(Jn(e),"utf-8"),t=JSON.parse(n);return t.version!==1||t.tables==null||typeof t.tables!="object"?{version:1,tables:{}}:t}catch{return{version:1,tables:{}}}}function qt(e,n){let t=Jn(e),a=t+".tmp";At(a,JSON.stringify(Ut(n),null,2)+`
|
|
60
|
+
`,"utf-8"),Vt(a,t)}function Ut(e){let n={};for(let t of Object.keys(e.tables).sort()){let a=e.tables[t];n[t]={columns:Object.fromEntries(Object.entries(a.columns).sort(([o],[r])=>o.localeCompare(r))),indexes:[...a.indexes].sort((o,r)=>o.name.localeCompare(r.name)),foreignKeys:[...a.foreignKeys].sort((o,r)=>o.constraintName.localeCompare(r.constraintName)),checks:[...a.checks].sort((o,r)=>o.name.localeCompare(r.name))}}return{version:1,tables:n}}export{Yn as COMPOSITE_PRIMARY_KEY_BRAND,ct as EXTRA_TYPE_BRAND,Y as Entity,D as MAPPERS,lt as METHOD_LITERAL_BRAND,zn as POLYMORPHIC_TYPE_BRAND,Hn as PRIMARY_KEY_BRAND,q as SchemaQueryBuilder,it as any,wt as applyDiff,ot as array,nt as boolean,R as buildColumnMap,pe as clearRow,Ce as createQuery,tt as date,Gn as dbExtension,Xn as ddlExtension,gt as defineEntity,fe as diffSchema,Mt as entitiesToSnapshot,L as entitySchemaToTableState,st as func,ht as generateCreatePolymorphicTables,le as generateCreateTable,ye as generateCreateTableSource,xt as generateMigration,Rt as generateMigrationsForContext,Q as getColumnName,j as getPolymorphicVariantSchemas,J as getPrimaryKeyColumns,se as getProjections,yt as getRowVersionColumn,C as getTableName,ie as getVariants,Ee as introspectDatabase,z as isDiffEmpty,Ft as loadSnapshot,me as mapObject,Oe as mapValue,et as number,at as object,be as query,Qt as rawQuery,K as resolveColumnRef,ce as resolvePropertyKey,Zn as string,_e as tableExistsInDb,rt as union,Tt as validateEntitiesAgainstDatabase,qt as writeSnapshot};
|
|
61
61
|
//# sourceMappingURL=index.js.map
|