@cleverbrush/knex-schema 3.1.0 → 4.0.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.
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v}from"./chunk-V4TH6K42.js";export{b as COMPOSITE_PRIMARY_KEY_BRAND,u as EXTRA_TYPE_BRAND,v as METHOD_LITERAL_BRAND,c as POLYMORPHIC_TYPE_BRAND,a as PRIMARY_KEY_BRAND,o as any,f as applyVariantsToSchema,l as array,i as boolean,j as date,d as dbExtension,e as ddlExtension,n as func,p as getColumnName,t as getPolymorphicVariantSchemas,r as getProjections,q as getTableName,s as getVariants,h as number,k as object,g as string,m as union};
2
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,13 @@
1
- export { buildColumnMap, resolveColumnRef, resolvePropertyKey } from './columns.js';
2
- export { any, array, boolean, date, dbExtension, func, getColumnName, getTableName, number, object, string, union } from './extension.js';
1
+ export type { PrimaryKeyColumns, RowVersionColumn, RowVersionStrategy } from './columns.js';
2
+ export { buildColumnMap, getPrimaryKeyColumns, getRowVersionColumn, resolveColumnRef, resolvePropertyKey } from './columns.js';
3
+ export { generateCreatePolymorphicTables, generateCreateTable, generateCreateTableSource } from './ddl.js';
4
+ export type { EntityPropSelector, EntityRelationKeys, EntityRelations, EntitySchema, EntityVariantUnion, RelationInfo, SchemaProps, UnwrapNavSchema, VariantBranch, WithRelation } from './entity.js';
5
+ export { defineEntity, Entity } from './entity.js';
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';
3
7
  export { clearRow, MAPPERS, mapObject, mapValue } from './mappers.js';
8
+ export { applyDiff, diffSchema, entitySchemaToTableState, generateMigration, generateMigrationsForContext, introspectDatabase, isDiffEmpty, tableExistsInDb } from './migration.js';
9
+ export { rawQuery } from './raw.js';
4
10
  export type { BoundQuery } from './SchemaQueryBuilder.js';
5
11
  export { createQuery, query, SchemaQueryBuilder } from './SchemaQueryBuilder.js';
6
- export type { ColumnRef, InsertType, JoinManySpec, JoinOneSpec, SchemaKeys, ValidatedJoinManySpec, ValidatedJoinOneSpec, ValidatedSpec, WithJoinedMany, WithJoinedOne } from './types.js';
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';
package/dist/index.js CHANGED
@@ -1,2 +1,61 @@
1
- import{ObjectSchemaBuilder as K,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as f}from"@cleverbrush/schema";import{arrayExtensions as J,defineExtension as O,numberExtensions as F,stringExtensions as q,withExtensions as $}from"@cleverbrush/schema";function y(r){return this.withExtension("columnName",r)}function A(r){return this.withExtension("tableName",r)}var L=O({string:{hasColumnName(r){return y.call(this,r)}},number:{hasColumnName(r){return y.call(this,r)}},boolean:{hasColumnName(r){return y.call(this,r)}},date:{hasColumnName(r){return y.call(this,r)}},any:{hasColumnName(r){return y.call(this,r)}},func:{hasColumnName(r){return y.call(this,r)}},array:{hasColumnName(r){return y.call(this,r)}},union:{hasColumnName(r){return y.call(this,r)}},generic:{hasColumnName(r){return y.call(this,r)}},object:{hasTableName(r){return A.call(this,r)}}}),h=$(q,F,J,L),V=h.string,D=h.number,U=h.boolean,Y=h.date,G=h.object,H=h.array,z=h.union,X=h.func,Z=h.any;function w(r,e){let n=r.getExtension("columnName");return typeof n=="string"?n:e}function g(r){let e=r.getExtension("tableName");if(typeof e!="string")throw new Error('Schema does not have a table name. Use .hasTableName("table_name") to set one.');return e}var N=new WeakMap;function d(r){let e=N.get(r);if(e)return e;let t=r.introspect().properties??{},a=new Map,o=new Map;for(let s of Object.keys(t)){let l=t[s],u=w(l,s);a.set(s,u),o.set(u,s)}let i={propToCol:a,colToProp:o};return N.set(r,i),i}function m(r,e,n){if(typeof r=="string"){if(!r)throw new Error(`${n} must be a non-empty string`);let{propToCol:t}=d(e);return t.get(r)??r}if(typeof r=="function"){let t=K.getPropertiesFor(e),a=r(t);if(!a||typeof a!="object"||!(f in a))throw new Error(`${n} accessor must return a valid property descriptor`);let o=a[f],s=e.introspect().properties??{};for(let l of Object.keys(s)){let u=t[l];if(u&&u[f]===o){let{propToCol:c}=d(e);return c.get(l)??l}}throw new Error(`${n} accessor did not match any property in the schema`)}throw new Error(`${n} must be a string or a property descriptor accessor function`)}function ee(r,e,n){if(typeof r=="string"){if(!r)throw new Error(`${n} must be a non-empty string`);return r}if(typeof r=="function"){let t=K.getPropertiesFor(e),a=r(t);if(!a||typeof a!="object"||!(f in a))throw new Error(`${n} accessor must return a valid property descriptor`);let o=a[f],s=e.introspect().properties??{};for(let l of Object.keys(s)){let u=t[l];if(u&&u[f]===o)return l}throw new Error(`${n} accessor did not match any property in the schema`)}throw new Error(`${n} must be a string or a property descriptor accessor function`)}var p={date_from_json:r=>r&&new Date(Date.parse(r))};function v(r,e){if(typeof r=="string"){if(typeof p[r]!="function")throw new Error(`unknown mapper "${r}"`);return p[r](e)}if(typeof r=="function")return r(e);throw new Error("couldn't map value")}function b(r,e){if(!e)throw new Error("mappers should be an object");if(!r||typeof r!="object"||r===null)return r;let n={};for(let t of Object.keys(r))n[t]=e[t]?v(e[t],r[t]):r[t];return n}function x(r,e,n){for(let t of e){let a=t.as;t.mappers&&typeof r[a]<"u"&&r[a]!==null&&(r[a]=b(r[a],t.mappers))}for(let t of n){let a=t.as;if(Array.isArray(r[a]))for(let o=0;o<r[a].length;o++)r[a][o]&&t.mappers&&(r[a][o]=b(r[a][o],t.mappers))}return r}import{ObjectSchemaBuilder as ne,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as re}from"@cleverbrush/schema";function j(r,e){if(r.foreignQuery)return"toKnexQuery"in r.foreignQuery?r.foreignQuery.toKnexQuery():r.foreignQuery;let n=g(r.foreignSchema);return e(n)}function _(r,e,n){let t=m(r.localColumn,e,"localColumn"),a=m(r.foreignColumn,r.foreignSchema,"foreignColumn");if(typeof r.as!="string"||!r.as)throw new Error("as must be a non-empty string");let o=j(r,n),i=r.required!==!1;return r.mappers!==void 0&&M(r.mappers),{localColumn:t,foreignColumn:a,as:r.as,required:i,foreignQuery:o,mappers:r.mappers}}function E(r,e,n){let t=m(r.localColumn,e,"localColumn"),a=m(r.foreignColumn,r.foreignSchema,"foreignColumn");if(typeof r.as!="string"||!r.as)throw new Error("as must be a non-empty string");let o=j(r,n);r.mappers!==void 0&&M(r.mappers);let i=Number.isFinite(r.limit)&&r.limit>0?r.limit:null,s=Number.isFinite(r.offset)&&r.offset>0?r.offset:null,l=r.orderBy?{column:m(r.orderBy.column,r.foreignSchema,"orderBy.column"),direction:r.orderBy.direction??"asc"}:null;return{localColumn:t,foreignColumn:a,as:r.as,foreignQuery:o,limit:i,offset:s,orderBy:l,mappers:r.mappers}}function M(r){if(typeof r!="object"||r===null)throw new Error("mappers must be an object");for(let e of Object.keys(r)){let n=r[e];if(typeof n=="string"){if(typeof p[n]!="function")throw new Error(`mapper for "${e}": unknown built-in mapper name "${n}"`)}else if(typeof n!="function")throw new Error(`mapper for "${e}" must be a function or a built-in mapper name`)}}function C(r){let e=new Set;for(let n of r){if(e.has(n.as))throw new Error(`duplicate field name: ${n.as}`);e.add(n.as)}}var T=class r{#o;#e;#i;#t=[];#l;#a=null;constructor(e,n,t){this.#o=e,this.#i=n,this.#l=g(n),this.#e=t??e(this.#l)}#r(e,n="column"){return m(e,this.#i,n)}joinOne(e){let n=_(e,this.#i,this.#o);return this.#t.push({type:"one",...n}),C(this.#t),this}joinMany(e){let n=E(e,this.#i,this.#o);return this.#t.push({type:"many",...n}),C(this.#t),this}where(e,...n){if(typeof e=="function"&&!this.#h(e))this.#e.where(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#y(e);this.#e.where(t,...n)}else{let t=this.#n(e);this.#e.where(t,...n)}return this}andWhere(e,...n){if(typeof e=="function"&&!this.#h(e))this.#e.andWhere(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#y(e);this.#e.andWhere(t,...n)}else{let t=this.#n(e);this.#e.andWhere(t,...n)}return this}orWhere(e,...n){if(typeof e=="function"&&!this.#h(e))this.#e.orWhere(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#y(e);this.#e.orWhere(t,...n)}else{let t=this.#n(e);this.#e.orWhere(t,...n)}return this}whereNot(e,...n){if(typeof e=="function"&&!this.#h(e))this.#e.whereNot(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#y(e);this.#e.whereNot(t,...n)}else{let t=this.#n(e);this.#e.whereNot(t,...n)}return this}whereIn(e,n){return this.#e.whereIn(this.#r(e,"whereIn"),n),this}whereNotIn(e,n){return this.#e.whereNotIn(this.#r(e,"whereNotIn"),n),this}orWhereIn(e,n){return this.#e.orWhereIn(this.#r(e,"orWhereIn"),n),this}orWhereNotIn(e,n){return this.#e.orWhereNotIn(this.#r(e,"orWhereNotIn"),n),this}whereNull(e){return this.#e.whereNull(this.#r(e,"whereNull")),this}whereNotNull(e){return this.#e.whereNotNull(this.#r(e,"whereNotNull")),this}orWhereNull(e){return this.#e.orWhereNull(this.#r(e,"orWhereNull")),this}orWhereNotNull(e){return this.#e.orWhereNotNull(this.#r(e,"orWhereNotNull")),this}whereBetween(e,n){return this.#e.whereBetween(this.#r(e,"whereBetween"),n),this}whereNotBetween(e,n){return this.#e.whereNotBetween(this.#r(e,"whereNotBetween"),n),this}whereLike(e,n){return this.#e.whereLike(this.#r(e,"whereLike"),n),this}whereILike(e,n){return this.#e.whereILike(this.#r(e,"whereILike"),n),this}whereRaw(e,...n){return this.#e.whereRaw(e,...n),this}whereExists(e){return this.#e.whereExists(e),this}orderBy(e,n){let t=this.#n(e);return this.#e.orderBy(t,n),this}orderByRaw(e,...n){return this.#e.orderByRaw(e,...n),this}groupBy(...e){let n=e.map(t=>this.#n(t));return this.#e.groupBy(...n),this}groupByRaw(e,...n){return this.#e.groupByRaw(e,...n),this}having(e,n,t){let a=this.#n(e);return this.#e.having(a,n,t),this}havingRaw(e,...n){return this.#e.havingRaw(e,...n),this}limit(e){return this.#e.limit(e),this}offset(e){return this.#e.offset(e),this}select(...e){let n=e.map(t=>this.#n(t));this.#e.select(...n),this.#a??=[];for(let t of n)typeof t=="string"&&this.#a.push(t);return this}distinct(...e){let n=e.map(t=>this.#n(t));return this.#e.distinct(...n),this}count(e){return e?this.#e.count(this.#n(e)):this.#e.count(),this}countDistinct(e){return e?this.#e.countDistinct(this.#n(e)):this.#e.countDistinct(),this}min(e){return this.#e.min(this.#n(e)),this}max(e){return this.#e.max(this.#n(e)),this}sum(e){return this.#e.sum(this.#n(e)),this}avg(e){return this.#e.avg(this.#n(e)),this}async insert(e){let n=this.#c(e),[t]=await this.#o(this.#l).insert(n).returning("*");return this.#u(t)}async insertMany(e){let n=e.map(a=>this.#c(a));return(await this.#o(this.#l).insert(n).returning("*")).map(a=>this.#u(a))}async update(e){let n=this.#c(e);return(await this.#e.update(n).returning("*")).map(a=>this.#u(a))}async delete(){return this.#e.delete()}apply(e){return e(this.#e),this}transacting(e){let n=new r(e,this.#i,this.#e.clone().transacting(e));for(let t of this.#t)n.#t.push({...t,foreignQuery:t.foreignQuery.clone().transacting(e)});return n.#a=this.#a?[...this.#a]:null,n}#s(){if(this.#t.length===0)return this.#e;let e=this.#o,n=this.#t,t=[...new Set(n.map(s=>s.localColumn))],a=this.#e,o=[];if(this.#a!==null){let s=new Set(this.#a);if(o=t.filter(l=>!s.has(l)),o.length>0){a=this.#e.clone();for(let l of o)a.column(l)}}let i=e.queryBuilder().with("originalQuery",a);if(o.length>0&&this.#a!==null)for(let s of this.#a)i.select(e.raw(":originalQuery:.:col: as :col:",{originalQuery:"originalQuery",col:s}));else i.select("originalQuery.*");i.from(e.raw(":originalQuery:",{originalQuery:"originalQuery"}));for(let s=0;s<n.length;s++){let l=n[s],u=`eagerRelation${s}`;l.type==="one"?this.#f(i,l,u):this.#d(i,l,u,s)}return i}#f(e,n,t){let a=this.#o,o=n.foreignQuery,i=o._single?.table;if(!i)throw new Error(`Could not determine table name from foreignQuery for "${n.as}". Make sure foreignQuery is created via knex("tableName").`);e.select(a.raw(":relationAlias:.:as:->0 as :as:",{relationAlias:t,as:n.as}));let s=a.from(o.as(i)).select(a.raw(":foreignTable:.:foreignColumn:",{foreignTable:i,foreignColumn:n.foreignColumn})).select(a.raw("jsonb_agg(:foreignTable:) as :as:",{foreignTable:i,as:n.as})).groupByRaw(":foreignTable:.:foreignColumn:",{foreignTable:i,foreignColumn:n.foreignColumn}).as(t),l=n.required?"join":"leftJoin";e[l](s,function(){this.on(a.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{originalQuery:"originalQuery",relationAlias:t,foreignColumn:n.foreignColumn,localColumn:n.localColumn}))})}#d(e,n,t,a){let o=this.#o,i=`withFilter${a}`,s=n.limit!==null&&n.limit>0||n.offset!==null&&n.offset>0,l=n.orderBy?n.orderBy.column:n.foreignColumn,u=n.orderBy?n.orderBy.direction:"asc";s?e.with(i,o.from(n.foreignQuery.clone().whereIn(n.foreignColumn,o.from(o.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(n.localColumn)).as(`__wf_inner_${a}`)).select(`__wf_inner_${a}.*`).select(o.raw(`row_number() over(partition by :foreignColumn: order by :orderByColumn: ${u}) as "__rn__"`,{foreignColumn:n.foreignColumn,orderByColumn:l}))):e.with(i,n.foreignQuery.clone().whereIn(n.foreignColumn,o.from(o.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(n.localColumn)));let c=o.from(i);if(s){let S=n.limit!==null&&n.limit>0,W=n.offset!==null&&n.offset>0,Q=n.offset??0,P=Q+(n.limit??0),I=S&&W?'"__rn__" > :offset and "__rn__" <= :limit':S?'"__rn__" <= :limit':'"__rn__" > :offset';c.whereRaw(I,{limit:P,offset:Q}),c.select(o.raw(":foreignColumn:",{foreignColumn:n.foreignColumn})),c.select(o.raw(`coalesce(jsonb_agg(to_jsonb(:filterName:) - '__rn__' order by "__rn__"), '[]'::jsonb) as :as:`,{filterName:i,as:n.as}))}else{c.select(o.raw(":foreignColumn:",{foreignColumn:n.foreignColumn}));let S=n.orderBy?`jsonb_agg(:filterName: order by :filterName:.:orderByColumn: ${u})`:"jsonb_agg(:filterName:)";c.select(o.raw(`coalesce(${S}, '[]'::jsonb) as :as:`,n.orderBy?{filterName:i,orderByColumn:l,as:n.as}:{filterName:i,as:n.as}))}c.groupByRaw(":foreignColumn:",{foreignColumn:n.foreignColumn});let k=c.as(t);e.select(o.raw("coalesce(:relationAlias:.:as:, '[]'::jsonb) as :as:",{relationAlias:t,as:n.as})),e.leftJoin(k,function(){this.on(o.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{relationAlias:t,foreignColumn:n.foreignColumn,originalQuery:"originalQuery",localColumn:n.localColumn}))})}#u(e){if(!e)return e;let{colToProp:n}=d(this.#i),t={};for(let[a,o]of Object.entries(e)){let i=n.get(a);i?t[i]=o:t[a]=o}return t}#m(e){let n=this.#t.filter(o=>o.type==="one"),t=this.#t.filter(o=>o.type==="many"),a=x(e,n,t);return this.#u(a)}#c(e){let{propToCol:n}=d(this.#i),t={};for(let[a,o]of Object.entries(e)){let i=n.get(a);i?t[i]=o:t[a]=o}return t}#y(e){return this.#c(e)}#n(e){return typeof e=="string"?this.#r(e,"column"):typeof e=="function"?this.#r(e,"column"):e}#h(e){try{let n=ne.getPropertiesFor(this.#i),t=e(n);if(t&&typeof t=="object"&&re in t)return!0}catch{}return!1}toQuery(){return this.#s().toQuery()}toKnexQuery(){return this.#s()}toString(){return this.#s().toString()}async execute(){let n=await this.#s();return n?Array.isArray(n)?n.map(t=>this.#m(t)):[this.#m(n)]:[]}async first(){let n=await this.#s().first();if(n)return this.#m(n)}then(e,n){return this.execute().then(e,n)}};function R(r,e,n){return new T(r,e,n)}function B(r){function e(n,t){return t?R(r,n,t):R(r,n)}return e.withTransaction=n=>B(n),e.transaction=n=>r.transaction(t=>n(B(t))),e}export{p as MAPPERS,T as SchemaQueryBuilder,Z as any,H as array,U as boolean,d as buildColumnMap,x as clearRow,B as createQuery,Y as date,L as dbExtension,X as func,w as getColumnName,g as getTableName,b as mapObject,v as mapValue,D as number,G as object,R as query,m as resolveColumnRef,ee as resolvePropertyKey,V as string,z as union};
1
+ import{a as me,b as fe,c as pe,d as de,e as ge,f as G,g as Se,h as Te,i as be,j as xe,k as we,l as Re,m as Ce,n as Ke,o as Ne,p as w,q as x,r as O,s as L,t as K,u as $e,v as ve}from"./chunk-V4TH6K42.js";import{ObjectSchemaBuilder as ee,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as B}from"@cleverbrush/schema";var X=new WeakMap;function b(o){let e=X.get(o);if(e)return e;let t=o.introspect().properties??{},r=new Map,a=new Map;for(let s of Object.keys(t)){let c=t[s],u=w(c,s);r.set(s,u),a.set(u,s)}let i={propToCol:r,colToProp:a};return X.set(o,i),i}function Z(o,e,n){if(n.length===1)return o.raw("??->>?",[e,n[0]]);let t=`{${n.join(",")}}`;return o.raw("??#>>?",[e,t])}function R(o,e,n,t){if(typeof o=="string"){if(!o)throw new Error(`${n} must be a non-empty string`);if(o.includes(".")){let[i,...s]=o.split("."),{propToCol:c}=b(e),u=c.get(i)??i;if(!t)throw new Error(`${n}: a Knex instance is required to resolve nested JSON path '${o}'`);return Z(t,u,s)}let{propToCol:r}=b(e);return r.get(o)??o}if(typeof o=="function"){let r=ee.getPropertiesFor(e),a=o(r);if(!a||typeof a!="object"||!(B in a))throw new Error(`${n} accessor must return a valid property descriptor`);let s=a[B].toJsonPointer();if(!s)throw new Error(`${n} accessor returned the root descriptor`);let c=s.slice(1).split("/").map(d=>d.replace(/~1/g,"/").replace(/~0/g,"~"));if(c.length===0)throw new Error(`${n} accessor returned the root descriptor`);let[u,...l]=c,{propToCol:h}=b(e),m=h.get(u)??u;if(l.length===0)return m;if(!t)throw new Error(`${n}: a Knex instance is required to resolve nested JSON path '${s}'`);return Z(t,m,l)}throw new Error(`${n} must be a string or a property descriptor accessor function`)}function I(o,e,n){if(typeof o=="string"){if(!o)throw new Error(`${n} must be a non-empty string`);return o}if(typeof o=="function"){let t=ee.getPropertiesFor(e),r=o(t);if(!r||typeof r!="object"||!(B in r))throw new Error(`${n} accessor must return a valid property descriptor`);let i=r[B].toJsonPointer();if(!i)throw new Error(`${n} accessor returned the root descriptor`);return i.slice(1).split("/")[0].replace(/~1/g,"/").replace(/~0/g,"~")}throw new Error(`${n} must be a string or a property descriptor accessor function`)}function P(o){let e=o.introspect(),n=e.properties??{},t=e.extensions??{},{propToCol:r,colToProp:a}=b(o),i=t.compositePrimaryKey;if(i&&i.length>0){let s=[],c=[];for(let u of i)r.has(u)?(s.push(u),c.push(r.get(u))):a.has(u)?(c.push(u),s.push(a.get(u))):(s.push(u),c.push(u));return{propertyKeys:s,columnNames:c}}for(let[s,c]of Object.entries(n))if((c.introspect?.().extensions??{}).primaryKey)return{propertyKeys:[s],columnNames:[r.get(s)??s]};return{propertyKeys:[],columnNames:[]}}function Ee(o){let n=o.introspect().properties??{},{propToCol:t}=b(o);for(let[r,a]of Object.entries(n)){let s=(a.introspect?.()?.extensions??{}).rowVersion;if(s)return{propertyKey:r,columnName:t.get(r)??r,strategy:s.strategy??"increment"}}return null}function Be(o,e,n,t){if(t.columnType)return o.specificType(e,t.columnType);switch(n.type){case"string":{let r=t.maxLength??n.maxLength??void 0;return r?o.string(e,r):o.string(e)}case"number":return n.isInteger!==!1?o.integer(e):o.float(e);case"boolean":return o.boolean(e);case"date":return o.timestamp(e);case"object":return o.specificType(e,"jsonb");default:return o.specificType(e,"text")}}function Pe(o,e,n){return e==="now"?o.defaultTo(n.fn.now()):e==="auto_increment"?o:typeof e=="object"&&e!==null&&e.raw?o.defaultTo(n.raw(e.raw)):o.defaultTo(e)}function D(o){let e=x(o),n=o.introspect(),t=n.extensions??{},r=new Set;return t.timestamps&&(r.add(t.timestamps.createdAt),r.add(t.timestamps.updatedAt)),t.softDelete&&r.add(t.softDelete.column),a=>{let i=a.schema.createTable(e,c=>{let u=n.properties??{};for(let[l,h]of Object.entries(u)){let m=w(h,l),d=h.introspect(),f=d.extensions??{};if(d.type==="array"&&!f.columnType||r.has(m))continue;let y;if(f.primaryKey?.autoIncrement?y=c.increments(m):y=Be(c,m,d,f),f.primaryKey&&!f.primaryKey.autoIncrement&&(y=y.primary()),f.unique&&(y=y.unique(typeof f.unique=="string"?{indexName:f.unique}:void 0)),f.index&&(y=y.index(typeof f.index=="string"?f.index:void 0)),f.defaultTo!==void 0&&(y=Pe(y,f.defaultTo,a)),d.isRequired&&!f.primaryKey?.autoIncrement?y=y.notNullable():d.isRequired||(y=y.nullable()),f.references){let p=y.references(f.references.column).inTable(f.references.table);f.onDelete&&p.onDelete(f.onDelete),f.onUpdate&&p.onUpdate(f.onUpdate)}f.check&&c.check(f.check)}for(let l of t.indexes??[])l.unique?c.unique(l.columns,{indexName:l.name??void 0}):c.index(l.columns,l.name??void 0);for(let l of t.uniques??[])c.unique(l.columns,{indexName:l.name??void 0});for(let l of t.checks??[])c.check(l);t.compositePrimaryKey&&c.primary(t.compositePrimaryKey);for(let l of t.rawColumns??[])c.specificType(l.name,l.definition);t.timestamps&&(c.timestamp(t.timestamps.createdAt).defaultTo(a.fn.now()).notNullable(),c.timestamp(t.timestamps.updatedAt).defaultTo(a.fn.now()).notNullable()),t.softDelete&&c.timestamp(t.softDelete.column).nullable()}),s=t.rawIndexes??[];return s.length>0?i.then(async()=>{for(let c of s)await a.raw(c)}):i}}function V(o){let e=x(o),n=o.introspect(),t=n.extensions??{},r=n.properties??{},a=[],i=new Set;t.timestamps&&(i.add(t.timestamps.createdAt),i.add(t.timestamps.updatedAt)),t.softDelete&&i.add(t.softDelete.column);for(let[h,m]of Object.entries(r)){let d=w(m,h),f=m.introspect(),y=f.extensions??{};if((f.type==="object"||f.type==="array")&&!y.columnType||i.has(d))continue;let p;y.primaryKey?.autoIncrement?p=` table.increments('${d}')`:p=` ${_e(d,f,y)}`,y.primaryKey&&!y.primaryKey.autoIncrement&&(p+=".primary()"),y.unique&&(typeof y.unique=="string"?p+=`.unique({ indexName: '${y.unique}' })`:p+=".unique()"),y.index&&(typeof y.index=="string"?p+=`.index('${y.index}')`:p+=".index()"),y.defaultTo!==void 0&&(p+=`.defaultTo(${je(y.defaultTo)})`),f.isRequired&&!y.primaryKey?.autoIncrement?p+=".notNullable()":f.isRequired||(p+=".nullable()"),y.references&&(p+=`.references('${y.references.column}').inTable('${y.references.table}')`,y.onDelete&&(p+=`.onDelete('${y.onDelete}')`),y.onUpdate&&(p+=`.onUpdate('${y.onUpdate}')`)),a.push(p+";"),y.check&&a.push(` table.check(${JSON.stringify(y.check)});`)}for(let h of t.indexes??[]){let m=JSON.stringify(h.columns);h.unique?a.push(` table.unique(${m}${h.name?`, { indexName: '${h.name}' }`:""});`):a.push(` table.index(${m}${h.name?`, '${h.name}'`:""});`)}for(let h of t.uniques??[]){let m=JSON.stringify(h.columns);a.push(` table.unique(${m}${h.name?`, { indexName: '${h.name}' }`:""});`)}for(let h of t.checks??[])a.push(` table.check(${JSON.stringify(h)});`);t.compositePrimaryKey&&a.push(` table.primary(${JSON.stringify(t.compositePrimaryKey)});`);for(let h of t.rawColumns??[])a.push(` table.specificType('${h.name}', '${h.definition}');`);t.timestamps&&(a.push(` table.timestamp('${t.timestamps.createdAt}').notNullable().defaultTo(knex.fn.now());`),a.push(` table.timestamp('${t.timestamps.updatedAt}').notNullable().defaultTo(knex.fn.now());`)),t.softDelete&&a.push(` table.timestamp('${t.softDelete.column}').nullable();`);let c=(t.rawIndexes??[]).map(h=>` await knex.raw(${JSON.stringify(h)});`),u=` await knex.schema.createTable('${e}', (table) => {
2
+ ${a.join(`
3
+ `)}
4
+ });`+(c.length>0?`
5
+ `+c.join(`
6
+ `):""),l=` await knex.schema.dropTableIfExists('${e}');`;return{up:u,down:l}}function _e(o,e,n){if(n.columnType)return`table.specificType('${o}', '${n.columnType}')`;switch(e.type){case"string":{let t=n.maxLength??e.maxLength??void 0;return t?`table.string('${o}', ${t})`:`table.string('${o}')`}case"number":return e.isInteger!==!1?`table.integer('${o}')`:`table.float('${o}')`;case"boolean":return`table.boolean('${o}')`;case"date":return`table.timestamp('${o}')`;case"object":return`table.specificType('${o}', 'jsonb')`;default:return`table.specificType('${o}', 'text')`}}function je(o){return o==="now"?"knex.fn.now()":typeof o=="object"&&o!==null&&o.raw?`knex.raw('${String(o.raw).replace(/'/g,"\\'")}')`:typeof o=="string"?`'${o.replace(/'/g,"\\'")}'`:String(o)}function ke(o){let e=[D(o)],n=K(o);for(let t of n)t.getExtension("tableName")&&e.push(D(t));return e}import{ObjectSchemaBuilder as Q,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as _}from"@cleverbrush/schema";var j=class o{schema;constructor(e){this.schema=e}_addRelation(e){let n=this.schema.getExtension?.("relations")??[],t=this.schema.withExtension("relations",[...n,e]);return new o(t)}hasOne(e,n,t,r){let a=this._resolvePropName(e,this.schema),i=this._resolveForeignSchema(a),s=this._resolvePropName(t,i);return this._addRelation({type:"hasOne",name:a,schema:i,foreignKey:s,optional:r?.optional})}hasMany(e,n,t){let r=this._resolvePropName(e,this.schema),a=this._resolveForeignSchema(r),i=this._resolvePropName(t,a);return this._addRelation({type:"hasMany",name:r,schema:a,foreignKey:i})}belongsTo(e,n,t,r){let a=this._resolvePropName(e,this.schema),i=this._resolveForeignSchema(a),s=this._resolvePropName(n,this.schema);return this._addRelation({type:"belongsTo",name:a,schema:i,foreignKey:s,optional:r?.optional})}belongsToMany(e,n){let t=this._resolvePropName(e,this.schema),r=this._resolveForeignSchema(t);return this._addRelation({type:"belongsToMany",name:t,schema:r,through:n})}discriminator(e){let n=typeof e=="string"?e:this._resolvePropName(e,this.schema),t=new o(this.schema);return t._variantBuilder={discKey:n,variants:{}},t}ctiVariant(e,n,t,r){let a=this._variantBuilder;if(!a)throw new Error("ctiVariant: call `.discriminator(...)` first to begin a polymorphic builder chain");let i=Oe(n.schema,t),s={...a.variants,[e]:{schema:n.schema,storage:"cti",foreignKeyColumn:i,allowOrphan:r?.allowOrphan,relations:[...ne(n),...te(n.schema,r?.relations)]}};return this._withVariantBuilder(a.discKey,s)}stiVariant(e,n,t){let r=this._variantBuilder;if(!r)throw new Error("stiVariant: call `.discriminator(...)` first to begin a polymorphic builder chain");let a=n instanceof o,i=a?n.schema:n,s={...r.variants,[e]:{schema:i,storage:"sti",enforceCheck:t?.enforceCheck,relations:[...a?ne(n):[],...te(i,t?.relations)]}};return this._withVariantBuilder(r.discKey,s)}_withVariantBuilder(e,n){let t=G(this.schema,e,n),r=this.schema.getExtension?.("relations")??[];r.length&&(t=t.withExtension("relations",r));let a=new o(t);return a._variantBuilder={discKey:e,variants:n},a}_resolvePropName(e,n){let t=Q.getPropertiesFor(n),r=e(t);if(!r||typeof r!="object"||!(_ in r))throw new Error("Entity relation selector must return a property descriptor, e.g. `t => t.author`.");let a=r[_];if(typeof a.propertyName!="string")throw new Error("Entity relation selector must return a top-level property descriptor.");return a.propertyName}_resolveForeignSchema(e){let t=(this.schema.introspect?.()?.properties??{})[e];if(!t)throw new Error(`Entity.relation: navigation property "${e}" not found on schema`);let r=t.introspect?.()??t;return r.type==="array"&&r.elementSchema?r.elementSchema:(r.type==="object"||t.constructor?.name==="ObjectSchemaBuilder",t)}};function ne(o){let e=o.schema.getExtension?.("relations")??[];if(e.length===0)return[];let{propToCol:n}=b(o.schema);return e.map(t=>{let r=typeof t.foreignKey=="string"?t.foreignKey:void 0,a=r?n.get(r)??r:void 0;return{name:t.name,type:t.type,schema:t.schema,foreignKey:a,through:t.through}})}function Oe(o,e){let n=Q.getPropertiesFor(o),r=e(n)?.[_];if(!r?.propertyName)throw new Error("ctiVariant: foreignKey accessor must return a top-level property descriptor on the variant schema");let a=r.propertyName,s=(o.introspect?.()?.properties??{})[a];if(!s)throw new Error(`ctiVariant: foreignKey property "${a}" not found on variant schema`);return w(s,a)}function te(o,e){if(!e)return[];let{propToCol:n}=b(o),t=[],r=Q.getPropertiesFor(o);for(let[a,i]of Object.entries(e)){let s;if(i.foreignKey){let l=i.foreignKey(r)?.[_];if(!l?.propertyName)throw new Error(`variant relation "${a}": foreignKey accessor must return a top-level property descriptor on the variant schema`);let h=l.propertyName;s=n.get(h)??h}let c=i.entity?i.entity.schema:i.schema;t.push({name:a,type:i.type,schema:c,foreignKey:s,through:i.through})}return t}function Le(o){return new j(o)}var $={date_from_json:o=>o&&new Date(Date.parse(o))};function ae(o,e){if(typeof o=="string"){if(typeof $[o]!="function")throw new Error(`unknown mapper "${o}"`);return $[o](e)}if(typeof o=="function")return o(e);throw new Error("couldn't map value")}function A(o,e){if(!e)throw new Error("mappers should be an object");if(!o||typeof o!="object"||o===null)return o;let n={};for(let t of Object.keys(o))n[t]=e[t]?ae(e[t],o[t]):o[t];return n}function M(o,e,n){for(let t of e){let r=t.as;t.mappers&&typeof o[r]<"u"&&o[r]!==null&&(o[r]=A(o[r],t.mappers))}for(let t of n){let r=t.as;if(Array.isArray(o[r]))for(let a=0;a<o[r].length;a++)o[r][a]&&t.mappers&&(o[r][a]=A(o[r][a],t.mappers))}return o}function Ie(o,e,n,t){let r={};for(let c of o)r[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 a=e.map(c=>({name:c.indexname,columns:Array.isArray(c.columns)?c.columns:[],unique:(c.indexdef??"").toUpperCase().includes("UNIQUE"),definition:c.indexdef??""})),i=n.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=t.map(c=>({name:c.conname,definition:c.definition}));return{columns:r,indexes:a,foreignKeys:i,checks:s}}async function De(o,e){let[n,t,r,a]=await Promise.all([o.raw(`SELECT column_name, data_type, is_nullable, column_default,
7
+ character_maximum_length, numeric_precision
8
+ FROM information_schema.columns
9
+ WHERE table_name = ? AND table_schema = 'public'
10
+ ORDER BY ordinal_position`,[e]),o.raw(`SELECT indexname, indexdef,
11
+ array_agg(a.attname ORDER BY array_position(ix.indkey, a.attnum)) as columns
12
+ FROM pg_indexes
13
+ JOIN pg_class t ON t.relname = ?
14
+ JOIN pg_index ix ON ix.indrelid = t.oid
15
+ JOIN pg_class i ON i.oid = ix.indexrelid AND i.relname = pg_indexes.indexname
16
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
17
+ WHERE pg_indexes.tablename = ?
18
+ GROUP BY indexname, indexdef`,[e,e]),o.raw(`SELECT tc.constraint_name, kcu.column_name,
19
+ ccu.table_name AS foreign_table, ccu.column_name AS foreign_column,
20
+ rc.delete_rule, rc.update_rule
21
+ FROM information_schema.table_constraints tc
22
+ JOIN information_schema.key_column_usage kcu USING (constraint_name, table_schema)
23
+ JOIN information_schema.constraint_column_usage ccu USING (constraint_name, table_schema)
24
+ JOIN information_schema.referential_constraints rc USING (constraint_name, constraint_schema)
25
+ WHERE tc.table_name = ? AND tc.constraint_type = 'FOREIGN KEY'`,[e]),o.raw(`SELECT conname, pg_get_constraintdef(oid) as definition
26
+ FROM pg_constraint
27
+ WHERE conrelid = ?::regclass AND contype = 'c'`,[e])]);return Ie(n.rows,t.rows,r.rows,a.rows)}function oe(o,e){if(e.columnType)return e.columnType;if(e.primaryKey?.autoIncrement)return"integer";switch(o.type){case"string":return"character varying";case"number":return o.isInteger!==!1?"integer":"double precision";case"boolean":return"boolean";case"date":return"timestamp without time zone";default:return"text"}}function v(o){let e=x(o),n=o.introspect(),t=n.properties??{},r=n.extensions??{},a={},i=[],s=[],c=[];for(let[u,l]of Object.entries(t)){let h=w(l,u),m=l.introspect(),d=m.extensions??{};(m.type==="object"||m.type==="array")&&!d.columnType||(a[h]={name:h,type:oe(m,d),nullable:!m.isRequired,defaultValue:d.defaultTo??null,maxLength:d.maxLength??m.maxLength??null,numericPrecision:null},d.references&&s.push({constraintName:`${e}_${h}_foreign`,columnName:h,foreignTable:d.references.table,foreignColumn:d.references.column,deleteRule:(d.onDelete??"NO ACTION").toUpperCase(),updateRule:(d.onUpdate??"NO ACTION").toUpperCase()}))}if(r.timestamps){let u=r.timestamps,l=u.createdAt??"created_at",h=u.updatedAt??"updated_at";a[l]={name:l,type:"timestamp without time zone",nullable:!1,defaultValue:"now",maxLength:null,numericPrecision:null},a[h]={name:h,type:"timestamp without time zone",nullable:!1,defaultValue:"now",maxLength:null,numericPrecision:null}}if(r.softDelete){let u=r.softDelete.column??"deleted_at";a[u]={name:u,type:"timestamp without time zone",nullable:!0,defaultValue:null,maxLength:null,numericPrecision:null}}for(let u of r.indexes??[]){let l=u.name??`idx_${u.columns.join("_")}`;i.push({name:l,columns:u.columns,unique:u.unique??!1,definition:""})}for(let u of r.uniques??[]){let l=u.name??`unq_${u.columns.join("_")}`;i.push({name:l,columns:u.columns,unique:!0,definition:""})}return{columns:a,indexes:i,foreignKeys:s,checks:c}}function re(o,e){let n=o.introspect(),t=n.properties??{},r=n.extensions??{},a=[],i=[],s=[],c=[],u=[],l=[],h=[],m=new Set;r.timestamps&&(m.add(r.timestamps.createdAt),m.add(r.timestamps.updatedAt));let d=new Set;for(let[y,p]of Object.entries(t)){let g=w(p,y),S=p.introspect(),T=S.extensions??{};if((S.type==="object"||S.type==="array")&&!T.columnType)continue;d.add(g);let C=e.columns[g];if(!C)a.push({name:g,type:oe(S,T),nullable:!S.isRequired,defaultValue:T.defaultTo,references:T.references,onDelete:T.onDelete,onUpdate:T.onUpdate});else{let N={},E=!S.isRequired;if(C.nullable!==E&&(N.nullable={from:C.nullable,to:E}),!m.has(g)&&!T.primaryKey?.autoIncrement){let Y=C.defaultValue??null,z=T.defaultTo??null;Y!==z&&(N.defaultValue={from:Y,to:z})}Object.keys(N).length>0&&s.push({name:g,changes:N})}T.references&&(e.foreignKeys.find(E=>E.columnName===g)||l.push({column:g,foreignTable:T.references.table,foreignColumn:T.references.column,onDelete:T.onDelete,onUpdate:T.onUpdate}))}r.timestamps&&(d.add(r.timestamps.createdAt),d.add(r.timestamps.updatedAt)),r.softDelete&&d.add(r.softDelete.column);for(let y of Object.keys(e.columns))d.has(y)||i.push(y);let f=new Set;for(let y of r.indexes??[]){let p=y.name??`idx_${y.columns.join("_")}`;f.add(p),e.indexes.find(S=>S.name===p)||c.push({columns:y.columns,name:y.name,unique:y.unique})}for(let y of r.uniques??[]){let p=y.name??`unq_${y.columns.join("_")}`;f.add(p),e.indexes.find(S=>S.name===p)||c.push({columns:y.columns,name:y.name,unique:!0})}for(let y of e.foreignKeys){let p=Object.entries(t).find(([g,S])=>w(S,g)===y.columnName);p&&(p[1].introspect().extensions??{}).references||h.push(y.constraintName)}return{addColumns:a,dropColumns:i,alterColumns:s,addIndexes:c,dropIndexes:u,addForeignKeys:l,dropForeignKeys:h}}function Ve(o,e){let{up:n,down:t}=se(o,e),r=`import type { Knex } from 'knex';
28
+
29
+ export async function up(knex: Knex): Promise<void> {
30
+ ${n}
31
+ }
32
+
33
+ export async function down(knex: Knex): Promise<void> {
34
+ ${t}
35
+ }
36
+ `;return{up:n,down:t,full:r}}async function Qe(o,e){return o.schema.hasTable(e)}function F(o){return o.addColumns.length===0&&o.dropColumns.length===0&&o.alterColumns.length===0&&o.addIndexes.length===0&&o.dropIndexes.length===0&&o.addForeignKeys.length===0&&o.dropForeignKeys.length===0}async function Ae(o,e,n){if(F(e))return;for(let r of e.dropForeignKeys)await o.raw("ALTER TABLE ?? DROP CONSTRAINT ??",[n,r]);(e.addColumns.length>0||e.dropColumns.length>0||e.alterColumns.length>0||e.addIndexes.length>0||e.dropIndexes.length>0||e.addForeignKeys.length>0)&&await o.schema.alterTable(n,r=>{for(let a of e.addColumns){let i=qe(r,a.name,a.type);if(a.nullable?i=i.nullable():i=i.notNullable(),a.defaultValue!==void 0&&(a.defaultValue==="now"?i=i.defaultTo(o.fn.now()):typeof a.defaultValue=="object"&&a.defaultValue!==null&&a.defaultValue.raw?i=i.defaultTo(o.raw(a.defaultValue.raw)):i=i.defaultTo(a.defaultValue)),a.references){let s=i.references(a.references.column).inTable(a.references.table);a.onDelete&&s.onDelete(a.onDelete),a.onUpdate&&s.onUpdate(a.onUpdate)}}for(let a of e.dropColumns)r.dropColumn(a);for(let a of e.alterColumns)for(let[i,s]of Object.entries(a.changes))i==="nullable"?s.to?r.setNullable(a.name):r.dropNullable(a.name):i==="defaultValue"&&s.to===null&&r.dropColumn(a.name);for(let a of e.addIndexes)a.unique?r.unique(a.columns,a.name?{indexName:a.name}:void 0):r.index(a.columns,a.name);for(let a of e.dropIndexes)r.dropIndex([],a);for(let a of e.addForeignKeys){let i=r.foreign(a.column).references(a.foreignColumn).inTable(a.foreignTable);a.onDelete&&(i=i.onDelete(a.onDelete)),a.onUpdate&&(i=i.onUpdate(a.onUpdate))}})}function Me(o,e){let n=[];for(let y of o){let p=y.schema,g=x(p);n.push({schema:p,tableName:g});for(let S of K(p)){let T=S.getExtension("tableName");T&&n.push({schema:S,tableName:T})}}let t=new Set,r=n.filter(y=>t.has(y.tableName)?!1:(t.add(y.tableName),!0)),a=Ue(r),i=[],s=[],c=new Set(a.map(y=>y.tableName));for(let{schema:y,tableName:p}of a){let g=e.tables[p];if(g){let S=re(y,g);if(!F(S)){let{up:T,down:C}=se(S,p);i.push(T),s.push(C)}}else{let{up:S,down:T}=V(y);i.push(S),s.push(T)}}for(let y of Object.keys(e.tables))if(!c.has(y)){let p=e.tables[y],{up:g,down:S}=Fe(y,p);i.push(g),s.unshift(S)}let u=i.length===0,l=i.join(`
37
+
38
+ `),h=[...s].reverse().join(`
39
+
40
+ `),m=`import type { Knex } from 'knex';
41
+
42
+ export async function up(knex: Knex): Promise<void> {
43
+ ${u?" // No changes needed":l}
44
+ }
45
+
46
+ export async function down(knex: Knex): Promise<void> {
47
+ ${u?" // No changes needed":h}
48
+ }
49
+ `,d={};for(let{schema:y,tableName:p}of a)d[p]=v(y);return{up:l,down:h,full:m,isEmpty:u,nextSnapshot:{version:1,tables:d}}}function Fe(o,e){let n=` // TODO: review destructive change \u2014 dropped table '${o}'
50
+ await knex.schema.dropTableIfExists(${JSON.stringify(o)});`,t=[];for(let[a,i]of Object.entries(e.columns)){let s=` table.specificType(${JSON.stringify(a)}, ${JSON.stringify(i.type)})`;i.nullable?s+=".nullable()":s+=".notNullable()",i.defaultValue!==null&&i.defaultValue!==void 0&&(s+=`.defaultTo(${JSON.stringify(i.defaultValue)})`),t.push(s+";")}for(let a of e.foreignKeys)t.push(` table.foreign(${JSON.stringify(a.columnName)}).references(${JSON.stringify(a.foreignColumn)}).inTable(${JSON.stringify(a.foreignTable)}).onDelete(${JSON.stringify(a.deleteRule)}).onUpdate(${JSON.stringify(a.updateRule)});`);for(let a of e.indexes)a.unique?t.push(` table.unique(${JSON.stringify(a.columns)}, { indexName: ${JSON.stringify(a.name)} });`):t.push(` table.index(${JSON.stringify(a.columns)}, ${JSON.stringify(a.name)});`);let r=` await knex.schema.createTable(${JSON.stringify(o)}, (table) => {
51
+ `+t.join(`
52
+ `)+`
53
+ });`;return{up:n,down:r}}function se(o,e){let n=[],t=[];for(let s of o.addColumns){let u=` ${s.type.includes(" ")?`table.specificType('${s.name}', '${s.type}')`:`table.${Je(s.type)}('${s.name}')`}`;s.nullable?u+=".nullable()":u+=".notNullable()",s.defaultValue!==void 0&&(u+=`.defaultTo(${We(s.defaultValue)})`),u+=";",n.push(u),t.push(` table.dropColumn('${s.name}');`)}for(let s of o.dropColumns)n.push(` table.dropColumn('${s}');`),t.push(` // TODO: recreate column '${s}' with original definition`);for(let s of o.alterColumns)for(let[c,u]of Object.entries(s.changes))if(c==="nullable")u.to?(n.push(` table.setNullable('${s.name}');`),t.push(` table.dropNullable('${s.name}');`)):(n.push(` table.dropNullable('${s.name}');`),t.push(` table.setNullable('${s.name}');`));else if(c==="defaultValue"){let l=u.to,h=u.from;l===null?(n.push(` table.timestamp('${s.name}').alter(); // DROP DEFAULT`),t.push(` table.timestamp('${s.name}').defaultTo(knex.fn.now()).alter();`)):(n.push(` table.timestamp('${s.name}').notNullable().defaultTo(knex.fn.now()).alter();`),t.push(h===null?` table.timestamp('${s.name}').notNullable().alter();`:` table.timestamp('${s.name}').notNullable().defaultTo(knex.fn.now()).alter();`))}for(let s of o.addIndexes){let c=JSON.stringify(s.columns);s.unique?(n.push(` table.unique(${c}${s.name?`, { indexName: '${s.name}' }`:""});`),t.push(` table.dropUnique(${c}${s.name?`, '${s.name}'`:""});`)):(n.push(` table.index(${c}${s.name?`, '${s.name}'`:""});`),t.push(` table.dropIndex([]${s.name?`, '${s.name}'`:""});`))}for(let s of o.dropIndexes)n.push(` table.dropIndex([], '${s}');`),t.push(` // TODO: recreate index '${s}' with original definition`);for(let s of o.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+=";",n.push(c),t.push(` table.dropForeign('${s.column}');`)}for(let s of o.dropForeignKeys)n.push(` // TODO: drop foreign key constraint '${s}'`);let r=n.length===0,a=r?" // No changes needed":` await knex.schema.alterTable('${e}', (table) => {
54
+ ${n.join(`
55
+ `)}
56
+ });`,i=r?" // No changes needed":` await knex.schema.alterTable('${e}', (table) => {
57
+ ${t.join(`
58
+ `)}
59
+ });`;return{up:a,down:i}}function qe(o,e,n){switch(n){case"integer":return o.integer(e);case"character varying":return o.string(e);case"text":return o.text(e);case"boolean":return o.boolean(e);case"timestamp without time zone":case"timestamp":return o.timestamp(e);case"double precision":case"float":return o.float(e);case"jsonb":case"json":return o.specificType(e,"jsonb");case"uuid":return o.uuid(e);default:return o.specificType(e,n)}}function Ue(o){let e=new Set(o.map(l=>l.tableName)),n=new Map;for(let{schema:l,tableName:h}of o){let m=new Set,d=l.introspect().properties??{};for(let[,f]of Object.entries(d)){let y=f.introspect?.()?.extensions??{};y.references?.table&&e.has(y.references.table)&&m.add(y.references.table)}n.set(h,m)}let t=new Map,r=new Map;for(let{tableName:l}of o)t.set(l,0),r.set(l,[]);for(let{tableName:l}of o)for(let h of n.get(l)??[])r.get(h).push(l),t.set(l,(t.get(l)??0)+1);let a=[];for(let[l,h]of t)h===0&&a.push(l);let i=[];for(;a.length>0;){let l=a.shift();i.push(l);for(let h of r.get(l)??[]){let m=t.get(h)-1;t.set(h,m),m===0&&a.push(h)}}let s=new Set(i),c=o.filter(l=>!s.has(l.tableName)),u=new Map(o.map(l=>[l.tableName,l]));return[...i.map(l=>u.get(l)),...c]}function Je(o){switch(o){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('${o}')`}}function We(o){return o==="now"?"knex.fn.now()":typeof o=="object"&&o!==null&&o.raw?`knex.raw('${o.raw.replace(/'/g,"\\'")}')`:typeof o=="string"?`'${o.replace(/'/g,"\\'")}'`:String(o)}async function He(o,e,n,t){let r;if(typeof n=="string"){let i=await o.raw(n,t??[]);r=i.rows??i}else r=await n;if(!r||!Array.isArray(r))return[];let{colToProp:a}=b(e);return r.map(i=>{let s={};for(let[c,u]of Object.entries(i)){let l=a.get(c);s[l??c]=u}return s})}import{ObjectSchemaBuilder as ye,SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR as U}from"@cleverbrush/schema";function ie(o,e){if(o.foreignQuery)return"toKnexQuery"in o.foreignQuery?o.foreignQuery.toKnexQuery():o.foreignQuery;let n=x(o.foreignSchema);return e(n)}function ce(o,e,n){let t=R(o.localColumn,e,"localColumn"),r=R(o.foreignColumn,o.foreignSchema,"foreignColumn");if(typeof o.as!="string"||!o.as)throw new Error("as must be a non-empty string");let a=ie(o,n),i=o.required!==!1;return o.mappers!==void 0&&ue(o.mappers),{localColumn:t,foreignColumn:r,as:o.as,required:i,foreignQuery:a,mappers:o.mappers}}function le(o,e,n){let t=R(o.localColumn,e,"localColumn"),r=R(o.foreignColumn,o.foreignSchema,"foreignColumn");if(typeof o.as!="string"||!o.as)throw new Error("as must be a non-empty string");let a=ie(o,n);o.mappers!==void 0&&ue(o.mappers);let i=Number.isFinite(o.limit)&&o.limit>0?o.limit:null,s=Number.isFinite(o.offset)&&o.offset>0?o.offset:null,c=o.orderBy?{column:R(o.orderBy.column,o.foreignSchema,"orderBy.column"),direction:o.orderBy.direction??"asc"}:null;return{localColumn:t,foreignColumn:r,as:o.as,foreignQuery:a,limit:i,offset:s,orderBy:c,mappers:o.mappers}}function ue(o){if(typeof o!="object"||o===null)throw new Error("mappers must be an object");for(let e of Object.keys(o)){let n=o[e];if(typeof n=="string"){if(typeof $[n]!="function")throw new Error(`mapper for "${e}": unknown built-in mapper name "${n}"`)}else if(typeof n!="function")throw new Error(`mapper for "${e}" must be a function or a built-in mapper name`)}}function q(o){let e=new Set;for(let n of o){if(e.has(n.as))throw new Error(`duplicate field name: ${n.as}`);e.add(n.as)}}var J=class{#t;#e;#a;constructor(e,n,t,r){this.#t=e,this.#e=n,this.#a=r}async merge(e,n){return this.#l(e,"merge",n)}async ignore(e){return this.#l(e,"ignore")}async#l(e,n,t){let r=x(this.#e),a=this.#e.getExtension?.("timestamps")??null,i=this.#e.getExtension?.("beforeInsert")??[],s={...e};for(let f of i)s=await f(s)??s;let{propToCol:c}=b(this.#e),u={};for(let[f,y]of Object.entries(s))u[c.get(f)??f]=y;a&&(u[a.createdAt]=this.#t.fn.now(),u[a.updatedAt]=this.#t.fn.now());let l=this.#t(r).insert(u).onConflict(this.#a);if(n==="ignore")l=l.ignore();else{let f;if(t){f={};for(let[y,p]of Object.entries(t))f[c.get(y)??y]=p}else f={...u},a&&(delete f[a.createdAt],f[a.updatedAt]=this.#t.fn.now());l=l.merge(f)}let h=await l.returning("*");if(!h||h.length===0)return;let{colToProp:m}=b(this.#e),d={};for(let[f,y]of Object.entries(h[0]))d[m.get(f)??f]=y;return d}},k=class o{#t;#e;#a;#l=[];#s;#c=null;#r=null;#m=null;#g=!1;#R=!1;#x=!1;#f=void 0;#u=null;#C=[];#S=[];#K=null;#n(){this.#K=null}#w(){return this.#K||(this.#K=this.#j()),this.#K}constructor(e,n,t){this.#t=e,this.#a=n,this.#s=x(n),this.#e=t??e(this.#s)}#o(e,n="column"){return R(e,this.#a,n,this.#t)}#v(){return this.#a.getExtension?.("softDelete")??null}#k(){let e=this.#a.getExtension?.("defaultScope");return typeof e=="function"?e:null}#T(){return this.#a.getExtension?.("timestamps")??null}#b(){if(this.#f!==void 0)return this.#f;let e=L(this.#a);if(!e)return this.#f=null,null;let{propToCol:n}=b(this.#a),t=n.get(e.discriminatorKey)??e.discriminatorKey;return this.#f={...e,discriminatorColumn:t},this.#f}static#P=new Set(["=","!=","<>","<",">","<=",">=","like","not like","ilike","not ilike","in","not in","is","is not"]);#O(e,n){let t=this.#t,r=this.#s,a=this.#y(this.#a),i=n.discriminatorColumn,s=e.clone().select(`${r}.*`);for(let[c,u]of Object.entries(n.variants))if(!(this.#u!==null&&!this.#u.has(c))&&u.storage==="cti"){let l=`__v_${c}`,h=u.tableName,m=u.foreignKey;s.leftJoin(`${h} as ${l}`,t.raw("?? = ?? AND ?? = ?",[`${l}.${m}`,`${r}.${a}`,`${r}.${i}`,c]));let{propToCol:d}=b(u.schema),y=u.schema.introspect().properties??{};for(let p of Object.keys(y)){let g=d.get(p)??p;s.select(t.raw("?? as ??",[`${l}.${g}`,`${l}__${g}`]))}}for(let c of this.#S){let u=n.variants[c.variantKey];if(!u)continue;let l=u.relations.find(f=>f.name===c.relationName);if(!l)continue;let h=this.#E(l.schema),m=x(h),d=`__v_${c.variantKey}__rel_${c.relationName}`;if(l.type==="belongsTo"||l.type==="hasOne"){let f,y;l.type==="belongsTo"?(f=l.foreignKey??(()=>{throw new Error(`includeVariant: relation "${c.relationName}" on variant "${c.variantKey}" requires foreignKey`)})(),y=this.#y(h)):(f=this.#y(this.#a),y=l.foreignKey??(()=>{throw new Error(`includeVariant: relation "${c.relationName}" on variant "${c.variantKey}" requires foreignKey`)})());let p,g=`__v_${c.variantKey}`;u.storage==="cti"?l.type==="belongsTo"?p=`${d}.${y} = ${g}.${f} AND ${r}.${i} = '${c.variantKey}'`:p=`${d}.${y} = ${r}.${f} AND ${r}.${i} = '${c.variantKey}'`:l.type==="belongsTo"?p=`${d}.${y} = ${r}.${f} AND ${r}.${i} = '${c.variantKey}'`:p=`${d}.${y} = ${r}.${f} AND ${r}.${i} = '${c.variantKey}'`;let S=this.#t(m),T=this.#L(h,d,m,c.customize);s.leftJoin(t.raw("?? as ??",[m,d]),t.raw(p));for(let C of T)s.select(C)}}for(let c of this.#C){let u=`${r}.${i}`;s.where(function(){this.where(u,c.key).andWhere(c.qualifiedColumn,c.op,c.value).orWhere(u,"!=",c.key)})}return this.#u!==null&&s.whereIn(`${r}.${i}`,[...this.#u]),s}#L(e,n,t,r){let a=this.#t,{propToCol:i}=b(e),c=e.introspect().properties??{},u;if(r){let l=new o(this.#t,e,this.#t(t));r(l);let h=l.#c;h&&h.length>0?u=h:u=Object.keys(c).map(m=>i.get(m)??m)}else u=Object.keys(c).map(l=>i.get(l)??l);return u.map(l=>a.raw("?? as ??",[`${n}.${l}`,`${n}__${l}`]))}#I(e,n){let{colToProp:t}=b(this.#a),r={};for(let[s,c]of Object.entries(e)){if(s.startsWith("__v_"))continue;let u=t.get(s);u?r[u]=c:r[s]=c}let a=n.discriminatorKey,i=r[a];if(i!=null){let s=n.variants[i];if(s)if(s.storage==="cti"){let{colToProp:c}=b(s.schema),l=`${`__v_${i}`}__`,h=s.foreignKey;if(h){let m=`${l}${h}`;if(!s.allowOrphan&&e[m]==null)throw new Error(`Polymorphic orphan: "${a}" = "${i}" but no matching row found in variant table "${s.tableName}". Set allowOrphan: true on this variant to suppress.`)}for(let[m,d]of Object.entries(e)){if(!m.startsWith(l))continue;let f=m.slice(l.length);if(f===h)continue;let y=c.get(f)??f;r[y]=d}}else{let{colToProp:c}=b(s.schema);for(let[u,l]of Object.entries(e)){if(u.startsWith("__v_")||t.has(u))continue;let h=c.get(u);h&&(r[h]=l)}}}if(this.#S.length>0&&i!=null){let s=n.variants[i];if(s)for(let c of this.#S){if(c.variantKey!==i)continue;let u=s.relations.find(l=>l.name===c.relationName);if(u&&(u.type==="belongsTo"||u.type==="hasOne")){let h=`${`__v_${i}__rel_${c.relationName}`}__`,m=this.#E(u.schema),{colToProp:d}=b(m),f={},y=!1;for(let[p,g]of Object.entries(e)){if(!p.startsWith(h))continue;let S=p.slice(h.length),T=d.get(S)??S;f[T]=g,g!=null&&(y=!0)}r[c.relationName]=y?f:null}}}return r}#_(){let e=this.#e,n=!1,t=this.#v();if(t&&this.#R?(n||(e=e.clone(),n=!0),e.whereNotNull(t.column)):t&&!this.#g&&(n||(e=e.clone(),n=!0),e.whereNull(t.column)),!this.#x){let r=this.#k();if(r){n||(e=e.clone(),n=!0);let a=new o(this.#t,this.#a,e);a.#x=!0,r(a)}}return e}#E(e){return typeof e=="function"?e():e}#y(e){let n=P(e);return n.columnNames.length>0?n.columnNames[0]:"id"}joinOne(e){let n=ce(e,this.#a,this.#t);return this.#l.push({type:"one",...n}),q(this.#l),this.#n(),this}joinMany(e){let n=le(e,this.#a,this.#t);return this.#l.push({type:"many",...n}),q(this.#l),this.#n(),this}where(e,...n){if(this.#n(),typeof e=="function"&&!this.#$(e))this.#e.where(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#N(e);this.#e.where(t,...n)}else{let t=this.#i(e);this.#e.where(t,...n)}return this}andWhere(e,...n){if(this.#n(),typeof e=="function"&&!this.#$(e))this.#e.andWhere(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#N(e);this.#e.andWhere(t,...n)}else{let t=this.#i(e);this.#e.andWhere(t,...n)}return this}orWhere(e,...n){if(this.#n(),typeof e=="function"&&!this.#$(e))this.#e.orWhere(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#N(e);this.#e.orWhere(t,...n)}else{let t=this.#i(e);this.#e.orWhere(t,...n)}return this}whereNot(e,...n){if(this.#n(),typeof e=="function"&&!this.#$(e))this.#e.whereNot(e,...n);else if(typeof e=="object"&&e!==null&&!("toSQL"in e)){let t=this.#N(e);this.#e.whereNot(t,...n)}else{let t=this.#i(e);this.#e.whereNot(t,...n)}return this}whereIn(e,n){return this.#n(),this.#e.whereIn(this.#o(e,"whereIn"),n),this}whereNotIn(e,n){return this.#n(),this.#e.whereNotIn(this.#o(e,"whereNotIn"),n),this}orWhereIn(e,n){return this.#n(),this.#e.orWhereIn(this.#o(e,"orWhereIn"),n),this}orWhereNotIn(e,n){return this.#n(),this.#e.orWhereNotIn(this.#o(e,"orWhereNotIn"),n),this}whereNull(e){return this.#n(),this.#e.whereNull(this.#o(e,"whereNull")),this}whereNotNull(e){return this.#n(),this.#e.whereNotNull(this.#o(e,"whereNotNull")),this}orWhereNull(e){return this.#n(),this.#e.orWhereNull(this.#o(e,"orWhereNull")),this}orWhereNotNull(e){return this.#n(),this.#e.orWhereNotNull(this.#o(e,"orWhereNotNull")),this}whereBetween(e,n){return this.#n(),this.#e.whereBetween(this.#o(e,"whereBetween"),n),this}whereNotBetween(e,n){return this.#n(),this.#e.whereNotBetween(this.#o(e,"whereNotBetween"),n),this}whereLike(e,n){return this.#n(),this.#e.whereLike(this.#o(e,"whereLike"),n),this}whereILike(e,n){return this.#n(),this.#e.whereILike(this.#o(e,"whereILike"),n),this}whereRaw(e,...n){return this.#n(),this.#e.whereRaw(e,...n),this}whereExists(e){return this.#n(),this.#e.whereExists(e),this}whereNotExists(e){return this.#n(),this.#e.whereNotExists(e),this}whereJsonPath(e,n,t,r){this.#n();let a=this.#t.client?.config?.client;if(a!=="pg"&&a!=="postgresql"&&a!=="postgres")throw new Error(`whereJsonPath() is only supported on PostgreSQL (got client: "${a??"unknown"}")`);let i=this.#o(e,"whereJsonPath"),s=t??"=";if(s==="@?"||s==="@@"){let c=s==="@?"?"@\\?":"@@";this.#e.whereRaw(`?? ${c} ?`,[i,n])}else{let c=n.startsWith("$")?n:`$.${n.replace(/\./g,".")}`;this.#e.whereRaw(`jsonb_path_query_first(??, ?) ${s} ?::jsonb`,[i,c,JSON.stringify(r)])}return this}orderBy(e,n){this.#n();let t=this.#i(e);return this.#e.orderBy(t,n),this}orderByRaw(e,...n){return this.#n(),this.#e.orderByRaw(e,...n),this}groupBy(...e){this.#n();let n=e.map(t=>this.#i(t));return this.#e.groupBy(...n),this}groupByRaw(e,...n){return this.#n(),this.#e.groupByRaw(e,...n),this}having(e,n,t){this.#n();let r=this.#i(e);return this.#e.having(r,n,t),this}havingRaw(e,...n){return this.#n(),this.#e.havingRaw(e,...n),this}limit(e){return this.#n(),this.#e.limit(e),this}offset(e){return this.#n(),this.#e.offset(e),this}select(...e){if(e.length===1&&typeof e[0]=="function"){let t=e[0],r=ye.getPropertiesFor(this.#a),a=t(r);if(a&&typeof a=="object"&&!(U in a)){this.#n(),this.#h("select"),this.#r="projection",this.#m="<inline>";let i={};this.#c??=[];for(let[s,c]of Object.entries(a)){if(!c||typeof c!="object"||!(U in c))throw new Error(`select(selector): value for alias "${s}" must be a property descriptor (e.g. \`t.someProp\`).`);let u=this.#o((()=>c),`select(selector).${s}`);i[s]=u,this.#c.push(u)}return this.#e.select(i),this}}this.#n(),this.#h("select"),this.#r="select";let n=e.map(t=>this.#i(t));this.#e.select(...n),this.#c??=[];for(let t of n)typeof t=="string"&&this.#c.push(t);return this}#h(e){if(this.#r==="projection")throw new Error(`Cannot call .${e}() after .projected('${this.#m}'). Choose one column-selection mode per query.`)}#D(e){if(this.#r==="select")throw new Error(`Cannot call .${e}() after .select(). Choose one column-selection mode per query.`);if(this.#r==="aggregate")throw new Error(`Cannot call .${e}() after an aggregate method. Choose one column-selection mode per query.`);if(this.#r==="projection")throw new Error(`Cannot call .${e}() after .projected('${this.#m}'). Choose one column-selection mode per query.`)}distinct(...e){this.#n();let n=e.map(t=>this.#i(t));return this.#e.distinct(...n),this}count(e){return this.#n(),this.#h("count"),this.#r="aggregate",e?this.#e.count(this.#i(e)):this.#e.count(),this}countDistinct(e){return this.#n(),this.#h("countDistinct"),this.#r="aggregate",e?this.#e.countDistinct(this.#i(e)):this.#e.countDistinct(),this}min(e){return this.#n(),this.#h("min"),this.#r="aggregate",this.#e.min(this.#i(e)),this}max(e){return this.#n(),this.#h("max"),this.#r="aggregate",this.#e.max(this.#i(e)),this}sum(e){return this.#n(),this.#h("sum"),this.#r="aggregate",this.#e.sum(this.#i(e)),this}avg(e){return this.#n(),this.#h("avg"),this.#r="aggregate",this.#e.avg(this.#i(e)),this}async insert(e){let n={...e},t=this.#a.getExtension?.("beforeInsert")??[];for(let u of t)n=await u(n)??n;let r=this.#d(n),a=this.#T();a&&(r[a.createdAt]=this.#t.fn.now(),r[a.updatedAt]=this.#t.fn.now());let[i]=await this.#t(this.#s).insert(r).returning("*"),s=this.#p(i),c=this.#a.getExtension?.("afterInsert")??[];for(let u of c)await u(s);return s}async insertMany(e){let n=this.#T(),t=this.#a.getExtension?.("beforeInsert")??[],r=[];for(let c of e){let u={...c};for(let h of t)u=await h(u)??u;let l=this.#d(u);n&&(l[n.createdAt]=this.#t.fn.now(),l[n.updatedAt]=this.#t.fn.now()),r.push(l)}let i=(await this.#t(this.#s).insert(r).returning("*")).map(c=>this.#p(c)),s=this.#a.getExtension?.("afterInsert")??[];for(let c of i)for(let u of s)await u(c);return i}onConflict(...e){let n=e.map(t=>this.#o(t,"onConflict"));return new J(this.#t,this.#a,this,n)}async upsert(e,n){let t=this.#T(),r=this.#a.getExtension?.("beforeInsert")??[],a={...e};for(let l of r)a=await l(a)??a;let i=this.#d(a);t&&(i[t.createdAt]=this.#t.fn.now(),i[t.updatedAt]=this.#t.fn.now());let s=n.conflictColumns.map(l=>this.#o(l,"upsert conflict")),c=this.#t(this.#s).insert(i).onConflict(s);if(n.updateColumns&&n.updateColumns.length>0){let l=n.updateColumns.map(m=>this.#o(m,"upsert update")),h={};for(let m of l)m in i&&(h[m]=i[m]);t&&(h[t.updatedAt]=this.#t.fn.now()),c=c.merge(h)}else{let l={...i};t&&(delete l[t.createdAt],l[t.updatedAt]=this.#t.fn.now()),c=c.merge(l)}let[u]=await c.returning("*");return this.#p(u)}async update(e){let n={...e},t=this.#a.getExtension?.("beforeUpdate")??[];for(let s of t)n=await s(n)??n;let r=this.#d(n),a=this.#T();return a&&(r[a.updatedAt]=this.#t.fn.now()),(await this.#e.update(r).returning("*")).map(s=>this.#p(s))}async delete(){let e=this.#a.getExtension?.("beforeDelete")??[];for(let t of e)await t(this);let n=this.#v();return n?this.#e.update({[n.column]:this.#t.fn.now()}):this.#e.delete()}async bulkInsert(e,n){if(e.length===0)return[];let t=n?.chunkSize??500,r=Object.keys(e[0]).length||1,a=Math.max(1,Math.floor(6e4/Math.max(1,r))),i=Math.max(1,Math.min(t,a)),s=this.#T(),c=this.#a.getExtension?.("beforeInsert")??[],u=this.#a.getExtension?.("afterInsert")??[],l=n?.onConflict&&n.conflictColumns?n.conflictColumns.map(m=>this.#o(m,"bulkInsert.onConflict")):null;if(n?.onConflict&&(!l||l.length===0))throw new Error("bulkInsert: `conflictColumns` is required when `onConflict` is set.");let h=[];for(let m=0;m<e.length;m+=i){let d=e.slice(m,m+i),f=[];for(let g of d){let S={...g};for(let C of c)S=await C(S)??S;let T=this.#d(S);s&&(T[s.createdAt]=this.#t.fn.now(),T[s.updatedAt]=this.#t.fn.now()),f.push(T)}let y=this.#t(this.#s).insert(f);if(l)if(y=y.onConflict(l),n.onConflict==="ignore")y=y.ignore();else{let g=new Set;for(let S of f)for(let T of Object.keys(S))g.add(T);for(let S of l)g.delete(S);s&&(g.delete(s.createdAt),g.add(s.updatedAt)),y=y.merge(Array.from(g))}let p=await y.returning("*");for(let g of p){let S=this.#p(g);for(let T of u)await T(S);h.push(S)}}return h}async bulkUpsert(e,n){return this.bulkInsert(e,{chunkSize:n.chunkSize,onConflict:"merge",conflictColumns:n.conflictColumns})}async bulkUpdate(e){if(e.length===0)return 0;let n=this.#V(),{propToCol:t}=b(this.#a),r=this.#a.getExtension?.("beforeUpdate")??[],a=this.#T(),i=[];for(let h of e){let m={...h.set};for(let p of r)m=await p(m)??m;let d=this.#d(m);a&&(d[a.updatedAt]=this.#t.fn.now());let f=h.where,y=[];for(let p of n.propertyKeys){let g=p in f?f[p]:f[t.get(p)??p];if(g===void 0)throw new Error(`bulkUpdate: each \`where\` clause must include the entity's primary key (missing "${p}").`);y.push(g)}i.push({pkValues:y,set:d})}let s=new Set;for(let h of i)for(let m of Object.keys(h.set))s.add(m);if(s.size===0)return 0;let c=this.#t,u={};for(let h of s){let m=[],d=[];for(let f of i)if(h in f.set)if(n.columnNames.length===1)m.push("WHEN ?? = ? THEN ?"),d.push(n.columnNames[0],f.pkValues[0],f.set[h]);else{let y=n.columnNames.map(()=>"?? = ?").join(" AND ");m.push(`WHEN ${y} THEN ?`);for(let p=0;p<n.columnNames.length;p++)d.push(n.columnNames[p],f.pkValues[p]);d.push(f.set[h])}m.length!==0&&(u[h]=c.raw(`CASE ${m.join(" ")} ELSE ?? END`,[...d,h]))}let l=c(this.#s).update(u);return n.columnNames.length===1?l=l.whereIn(n.columnNames[0],i.map(h=>h.pkValues[0])):l=l.where(function(){for(let h of i)this.orWhere(function(){for(let m=0;m<n.columnNames.length;m++)this.andWhere(n.columnNames[m],h.pkValues[m])})}),await l}#V(){let e=P(this.#a);if(e.columnNames.length===0)throw new Error("No primary key declared on this schema. Use `.primaryKey()` on a column or `.hasPrimaryKey([...])` on the schema.");return e}apply(e){return this.#n(),e(this.#e),this}transacting(e){let n=new o(e,this.#a,this.#e.clone().transacting(e));for(let t of this.#l)n.#l.push({...t,foreignQuery:t.foreignQuery.clone().transacting(e)});return n.#c=this.#c?[...this.#c]:null,n.#r=this.#r,n.#m=this.#m,n.#g=this.#g,n.#R=this.#R,n.#x=this.#x,n.#f=this.#f,n.#u=this.#u!==null?new Set(this.#u):null,n.#C=[...this.#C],n.#S=[...this.#S],n}include(e,n){this.#n();let r=(this.#a.getExtension?.("relations")??[]).find(s=>s.name===e);if(!r){let s=this.#b();if(s){let c=[];for(let[u,l]of Object.entries(s.variants))l.relations.some(h=>h.name===e)&&c.push({variantKey:u});if(c.length===1)return this.includeVariant(c[0].variantKey,e,n);if(c.length>1)throw new Error(`Ambiguous relation "${e}" \u2014 found on variants: ${c.map(u=>u.variantKey).join(", ")}. Use .includeVariant(key, name) to be explicit.`)}throw new Error(`Unknown relation "${e}" on schema for table "${this.#s}"`)}let a=this.#E(r.schema),i=x(a);switch(r.type){case"belongsTo":{let s=R(r.foreignKey,this.#a,"foreignKey"),c=this.#y(a),u=this.#t(i);if(n){let l=new o(this.#t,a,u);n(l)}this.joinOne({foreignSchema:a,localColumn:s,foreignColumn:c,as:e,foreignQuery:u});break}case"hasOne":{let s=this.#y(this.#a),c=R(r.foreignKey,a,"foreignKey"),u=this.#t(i);if(n){let l=new o(this.#t,a,u);n(l)}this.joinOne({foreignSchema:a,localColumn:s,foreignColumn:c,as:e,required:!1,foreignQuery:u});break}case"hasMany":{let s=this.#y(this.#a),c=R(r.foreignKey,a,"foreignKey"),u=this.#t(i);if(n){let l=new o(this.#t,a,u);n(l)}this.joinMany({foreignSchema:a,localColumn:s,foreignColumn:c,as:e,foreignQuery:u});break}case"belongsToMany":{let s=r.through,c=this.#y(this.#a),u=this.#t(i).join(s.table,`${s.table}.${s.foreignKey}`,`${i}.${this.#y(a)}`).select(`${i}.*`,`${s.table}.${s.localKey}`);if(n){let l=new o(this.#t,a,u);n(l)}this.joinMany({foreignSchema:a,localColumn:c,foreignColumn:s.localKey,as:e,foreignQuery:u});break}}return this}includeVariant(e,n,t){this.#n();let r=this.#b();if(!r)throw new Error(`includeVariant: schema for table "${this.#s}" is not polymorphic (no .withVariants() config found)`);let a=r.variants[e];if(!a)throw new Error(`includeVariant: unknown variant key "${e}" on schema for table "${this.#s}"`);if(!a.relations.find(s=>s.name===n))throw new Error(`includeVariant: unknown relation "${n}" on variant "${e}" of table "${this.#s}"`);return this.#S.push({variantKey:e,relationName:n,customize:t}),this}projected(e){if(this.#D("projected"),this.#r==="projection")throw new Error(`Cannot call .projected('${e}') \u2014 .projected('${this.#m}') was already applied. Only one projection per query.`);let t=O(this.#a)[e];if(!t)throw new Error(`Unknown projection "${e}" on schema for table "${this.#s}"`);let{propToCol:r}=b(this.#a),a=t.keys.map(i=>r.get(i)??i);this.#e.select(...a),this.#c??=[];for(let i of a)this.#c.push(i);return this.#r="projection",this.#m=e,this.#n(),this}scoped(e){this.#n();let t=this.#a.getExtension?.("scopes")?.[e];if(!t)throw new Error(`Unknown scope "${e}" on schema for table "${this.#s}"`);return t(this),this}unscoped(){return this.#n(),this.#x=!0,this.#g=!0,this}whereVariant(e,n,t,r){let a=this.#b();if(!a)throw new Error("whereVariant() can only be used on a polymorphic schema (created with .withVariants())");let i=a.variants[e];if(!i)throw new Error(`whereVariant: unknown variant key "${e}". Valid keys: ${Object.keys(a.variants).join(", ")}`);let s=t.toLowerCase();if(!o.#P.has(s))throw new Error(`whereVariant: operator "${t}" is not allowed. Allowed operators: ${[...o.#P].join(", ")}`);let{propToCol:c}=b(i.schema),u=c.get(n)??n,l;return i.storage==="cti"?l=`__v_${e}.${u}`:l=`${this.#s}.${u}`,this.#C.push({key:e,qualifiedColumn:l,op:s,value:r}),this.#n(),this}selectVariants(e){if(!this.#b())throw new Error("selectVariants() can only be used on a polymorphic schema (created with .withVariants())");return this.#u=new Set(e),this.#n(),this}withDeleted(){return this.#n(),this.#g=!0,this}onlyDeleted(){return this.#n(),this.#R=!0,this.#g=!0,this}async hardDelete(){let e=this.#a.getExtension?.("beforeDelete")??[];for(let n of e)await n(this);return this.#e.delete()}async restore(){let e=this.#v();if(!e)throw new Error("Schema does not have soft delete enabled. Use .softDelete() on the schema.");return(await this.#e.update({[e.column]:null}).returning("*")).map(t=>this.#p(t))}async paginate(e){let{page:n,pageSize:t}=e,a=await this.#_().clone().clearSelect().clearOrder().count("* as count").first(),i=Number(a?.count??0);this.limit(t).offset((n-1)*t);let s=await this.execute(),c=Math.ceil(i/t);return{data:s,total:i,page:n,pageSize:t,totalPages:c,hasNextPage:n<c,hasPreviousPage:n>1}}async paginateAfter(e){let n=e.direction??"desc",t=e.column??"id";if(e.cursor!=null){let u=n==="desc"?"<":">";this.where(t,u,e.cursor)}this.orderBy(t,n).limit(e.limit+1);let r=await this.execute(),a=r.length>e.limit,i=a?r.slice(0,e.limit):r,s=typeof t=="string"?t:I(t,this.#a,"cursor"),c=a&&i.length>0?String(i[i.length-1][s]):null;return{data:i,nextCursor:c,hasMore:a}}selectRaw(e,n){return this.#n(),n?this.#e.select(this.#t.raw(e,n)):this.#e.select(this.#t.raw(e)),this}#j(){let e=this.#_(),n=this.#b(),t=n?this.#O(e,n):e;if(this.#l.length===0)return t;let r=this.#t,a=this.#l,i=[...new Set(a.map(l=>l.localColumn))],s=t,c=[];if(this.#c!==null){let l=new Set(this.#c);if(c=i.filter(h=>!l.has(h)),c.length>0){s=t.clone();for(let h of c)s.column(h)}}let u=r.queryBuilder().with("originalQuery",s);if(c.length>0&&this.#c!==null)for(let l of this.#c)u.select(r.raw(":originalQuery:.:col: as :col:",{originalQuery:"originalQuery",col:l}));else u.select("originalQuery.*");u.from(r.raw(":originalQuery:",{originalQuery:"originalQuery"}));for(let l=0;l<a.length;l++){let h=a[l],m=`eagerRelation${l}`;h.type==="one"?this.#Q(u,h,m):this.#A(u,h,m,l)}return u}#Q(e,n,t){let r=this.#t,a=n.foreignQuery,i=a._single?.table;if(!i)throw new Error(`Could not determine table name from foreignQuery for "${n.as}". Make sure foreignQuery is created via knex("tableName").`);e.select(r.raw(":relationAlias:.:as:->0 as :as:",{relationAlias:t,as:n.as}));let s=r.from(a.as(i)).select(r.raw(":foreignTable:.:foreignColumn:",{foreignTable:i,foreignColumn:n.foreignColumn})).select(r.raw("jsonb_agg(:foreignTable:) as :as:",{foreignTable:i,as:n.as})).groupByRaw(":foreignTable:.:foreignColumn:",{foreignTable:i,foreignColumn:n.foreignColumn}).as(t),c=n.required?"join":"leftJoin";e[c](s,function(){this.on(r.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{originalQuery:"originalQuery",relationAlias:t,foreignColumn:n.foreignColumn,localColumn:n.localColumn}))})}#A(e,n,t,r){let a=this.#t,i=`withFilter${r}`,s=n.limit!==null&&n.limit>0||n.offset!==null&&n.offset>0,c=n.orderBy?n.orderBy.column:n.foreignColumn,u=n.orderBy?n.orderBy.direction:"asc";s?e.with(i,a.from(n.foreignQuery.clone().whereIn(n.foreignColumn,a.from(a.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(n.localColumn)).as(`__wf_inner_${r}`)).select(`__wf_inner_${r}.*`).select(a.raw(`row_number() over(partition by :foreignColumn: order by :orderByColumn: ${u}) as "__rn__"`,{foreignColumn:n.foreignColumn,orderByColumn:c}))):e.with(i,n.foreignQuery.clone().whereIn(n.foreignColumn,a.from(a.raw(":originalQuery:",{originalQuery:"originalQuery"})).distinct(n.localColumn)));let l=a.from(i);if(s){let m=n.limit!==null&&n.limit>0,d=n.offset!==null&&n.offset>0,f=n.offset??0,y=f+(n.limit??0),p=m&&d?'"__rn__" > :offset and "__rn__" <= :limit':m?'"__rn__" <= :limit':'"__rn__" > :offset';l.whereRaw(p,{limit:y,offset:f}),l.select(a.raw(":foreignColumn:",{foreignColumn:n.foreignColumn})),l.select(a.raw(`coalesce(jsonb_agg(to_jsonb(:filterName:) - '__rn__' order by "__rn__"), '[]'::jsonb) as :as:`,{filterName:i,as:n.as}))}else{l.select(a.raw(":foreignColumn:",{foreignColumn:n.foreignColumn}));let m=n.orderBy?`jsonb_agg(:filterName: order by :filterName:.:orderByColumn: ${u})`:"jsonb_agg(:filterName:)";l.select(a.raw(`coalesce(${m}, '[]'::jsonb) as :as:`,n.orderBy?{filterName:i,orderByColumn:c,as:n.as}:{filterName:i,as:n.as}))}l.groupByRaw(":foreignColumn:",{foreignColumn:n.foreignColumn});let h=l.as(t);e.select(a.raw("coalesce(:relationAlias:.:as:, '[]'::jsonb) as :as:",{relationAlias:t,as:n.as})),e.leftJoin(h,function(){this.on(a.raw(":relationAlias:.:foreignColumn: = :originalQuery:.:localColumn:",{relationAlias:t,foreignColumn:n.foreignColumn,originalQuery:"originalQuery",localColumn:n.localColumn}))})}#p(e){if(!e)return e;let n=this.#b();if(n)return this.#I(e,n);let{colToProp:t}=b(this.#a),r={};for(let[a,i]of Object.entries(e)){let s=t.get(a);s?r[s]=i:r[a]=i}return r}#B(e){let n=this.#l.filter(a=>a.type==="one"),t=this.#l.filter(a=>a.type==="many"),r=M(e,n,t);return this.#p(r)}#d(e){let{propToCol:n}=b(this.#a),t={};for(let[r,a]of Object.entries(e)){let i=n.get(r);i?t[i]=a:t[r]=a}return t}#N(e){return this.#d(e)}#i(e){return typeof e=="string"?this.#o(e,"column"):typeof e=="function"?this.#o(e,"column"):e}#$(e){try{let n=ye.getPropertiesFor(this.#a),t=e(n);if(t&&typeof t=="object"&&U in t)return!0}catch{}return!1}toQuery(){return this.#w().toQuery()}toKnexQuery(){return this.#w()}toString(){return this.#w().toString()}async execute(){let n=await this.#w();return n?Array.isArray(n)?n.map(t=>this.#B(t)):[this.#B(n)]:[]}async first(){let n=await this.#w().first();if(n)return this.#B(n)}async pluck(e){let n=this.#o(e,"pluck");return(await this.#j().select(n)).map(r=>r[n]??r[e])}then(e,n){return this.execute().then(e,n)}};function W(o,e,n){return new k(o,e,n)}function H(o){function e(n,t){return t?W(o,n,t):W(o,n)}return e.withTransaction=n=>H(n),e.transaction=n=>o.transaction(t=>n(H(t))),e}import{readFileSync as Ye,renameSync as ze,writeFileSync as Ge}from"fs";import{resolve as he}from"path";function Xe(o){let e={};for(let n of o){let t=n.schema,r=x(t);e[r]||(e[r]=v(t));for(let a of K(t)){let i=a.getExtension("tableName");i&&!e[i]&&(e[i]=v(a))}}return{version:1,tables:e}}function Ze(o){try{let e=Ye(he(o),"utf-8"),n=JSON.parse(e);return n.version!==1||n.tables==null||typeof n.tables!="object"?{version:1,tables:{}}:n}catch{return{version:1,tables:{}}}}function en(o,e){let n=he(o),t=n+".tmp";Ge(t,JSON.stringify(nn(e),null,2)+`
60
+ `,"utf-8"),ze(t,n)}function nn(o){let e={};for(let n of Object.keys(o.tables).sort()){let t=o.tables[n];e[n]={columns:Object.fromEntries(Object.entries(t.columns).sort(([r],[a])=>r.localeCompare(a))),indexes:[...t.indexes].sort((r,a)=>r.name.localeCompare(a.name)),foreignKeys:[...t.foreignKeys].sort((r,a)=>r.constraintName.localeCompare(a.constraintName)),checks:[...t.checks].sort((r,a)=>r.name.localeCompare(a.name))}}return{version:1,tables:e}}export{fe as COMPOSITE_PRIMARY_KEY_BRAND,$e as EXTRA_TYPE_BRAND,j as Entity,$ as MAPPERS,ve as METHOD_LITERAL_BRAND,pe as POLYMORPHIC_TYPE_BRAND,me as PRIMARY_KEY_BRAND,k as SchemaQueryBuilder,Ne as any,Ae as applyDiff,Re as array,be as boolean,b as buildColumnMap,M as clearRow,H as createQuery,xe as date,de as dbExtension,ge as ddlExtension,Le as defineEntity,re as diffSchema,Xe as entitiesToSnapshot,v as entitySchemaToTableState,Ke as func,ke as generateCreatePolymorphicTables,D as generateCreateTable,V as generateCreateTableSource,Ve as generateMigration,Me as generateMigrationsForContext,w as getColumnName,K as getPolymorphicVariantSchemas,P as getPrimaryKeyColumns,O as getProjections,Ee as getRowVersionColumn,x as getTableName,L as getVariants,De as introspectDatabase,F as isDiffEmpty,Ze as loadSnapshot,A as mapObject,ae as mapValue,Te as number,we as object,W as query,He as rawQuery,R as resolveColumnRef,I as resolvePropertyKey,Se as string,Qe as tableExistsInDb,Ce as union,en as writeSnapshot};
2
61
  //# sourceMappingURL=index.js.map