appos 0.1.11-0 → 0.1.13-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/build/exports/db.d.mts +2 -3
- package/build/exports/db.mjs +4 -5
- package/build/exports/zod.d.ts +2 -1
- package/build/exports/zod.js +4 -4
- package/package.json +3 -3
package/build/exports/db.mjs
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
const e=Symbol.for(`drizzle:entityKind`),t=Symbol.for(`drizzle:hasOwnEntityKind`);function n(t,n){if(!t||typeof t!=`object`)return!1;if(t instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,e))throw Error(`Class "${n.name??`<unknown>`}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(t).constructor;if(r)for(;r;){if(e in r&&r[e]===n[e])return!0;r=Object.getPrototypeOf(r)}return!1}var r=class{static[e]=`Column`;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}};function i(e){return e.table}function a(e){let[t,n]=e.dataType.split(` `);return{type:t,constraint:n}}var o=class{static[e]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===``&&(this.config.name=e)}};const s=Symbol.for(`drizzle:Name`);var c=class{static[e]=`PgForeignKeyBuilder`;reference;_onUpdate=`no action`;_onDelete=`no action`;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?`no action`:e,this}onDelete(e){return this._onDelete=e===void 0?`no action`:e,this}build(e){return new l(e,this)}},l=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[e]=`PgForeignKey`;reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[s],...r,n[0].table[s],...i];return e??`${a.join(`_`)}_fk`}};function u(e){function t(){let{name:t,columns:n,foreignColumns:r}=e;return{name:t,columns:n,foreignColumns:r}}return new c(t)}function d(e,...t){return e(...t)}function f(e){return new h(e)}function p(e,t){return`${e[s]}_${t.join(`_`)}_unique`}var m=class{constructor(e,t){this.name=t,this.columns=e}static[e]=`PgUniqueConstraintBuilder`;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new g(e,this.columns,this.nullsNotDistinctConfig,this.name)}},h=class{static[e]=`PgUniqueOnConstraintBuilder`;name;constructor(e){this.name=e}on(...e){return new m(e,this.name)}},g=class{constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??p(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[e]=`PgUniqueConstraint`;columns;name;nullsNotDistinct=!1;getName(){return this.name}};function _(e,t,n){for(let r=t;r<e.length;r++){let i=e[r];if(i===`\\`){r++;continue}if(i===`"`)return[e.slice(t,r).replace(/\\/g,``),r+1];if(!n&&(i===`,`||i===`}`))return[e.slice(t,r).replace(/\\/g,``),r]}return[e.slice(t).replace(/\\/g,``),e.length]}function v(e,t=0){let n=[],r=t,i=!1;for(;r<e.length;){let a=e[r];if(a===`,`){(i||r===t)&&n.push(``),i=!0,r++;continue}if(i=!1,a===`\\`){r+=2;continue}if(a===`"`){let[t,i]=_(e,r+1,!0);n.push(t),r=i;continue}if(a===`}`)return[n,r+1];if(a===`{`){let[t,i]=v(e,r+1);n.push(t),r=i;continue}let[o,s]=_(e,r,!1);n.push(o),r=s}return[n,r]}function y(e){let[t]=v(e,1);return t}function b(e){return`{${e.map(e=>Array.isArray(e)?b(e):typeof e==`string`?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:`${e}`).join(`,`)}}`}var x=class extends o{foreignKeyConfigs=[];static[e]=`PgColumnBuilder`;array(e){return new ne(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:`always`,mode:`stored`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>d((n,r)=>{let i=new c(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)},n,r))}buildExtraConfigColumn(e){return new ee(e,this.config)}},S=class extends r{static[e]=`PgColumn`;table;constructor(e,t){t.uniqueName||=p(e,[t.name]),super(e,t),this.table=e}},ee=class extends S{static[e]=`ExtraConfigColumn`;getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??`asc`,nulls:this.config.nulls??`last`,opClass:this.config.opClass};defaultConfig={order:`asc`,nulls:`last`,opClass:void 0};asc(){return this.indexConfig.order=`asc`,this}desc(){return this.indexConfig.order=`desc`,this}nullsFirst(){return this.indexConfig.nulls=`first`,this}nullsLast(){return this.indexConfig.nulls=`last`,this}op(e){return this.indexConfig.opClass=e,this}},te=class{static[e]=`IndexedColumn`;constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},ne=class extends x{static[e]=`PgArrayBuilder`;constructor(e,t,n){super(e,`array basecolumn`,`PgArray`),this.config.baseBuilder=t,this.config.length=n}build(e){let t=this.config.baseBuilder.build(e);return new re(e,this.config,t)}},re=class t extends S{constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r}static[e]=`PgArray`;getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.length==`number`?this.length:``}]`}mapFromDriverValue(e){return typeof e==`string`&&(e=y(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapFromJsonValue(e){typeof e==`string`&&(e=y(e));let t=this.baseColumn;return`mapFromJsonValue`in t?e.map(e=>t.mapFromJsonValue(e)):e.map(e=>t.mapFromDriverValue(e))}mapToDriverValue(e,r=!1){let i=e.map(e=>e===null?null:n(this.baseColumn,t)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return r?i:b(i)}},ie=class extends x{static[e]=`PgEnumObjectColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumObjectColumn`),this.config.enum=t}build(e){return new ae(e,this.config)}},ae=class extends S{static[e]=`PgEnumObjectColumn`;enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};const oe=Symbol.for(`drizzle:isPgEnum`);function se(e){return!!e&&typeof e==`function`&&oe in e&&e[oe]===!0}var ce=class extends x{static[e]=`PgEnumColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumColumn`),this.config.enum=t}build(e){return new le(e,this.config)}},le=class extends S{static[e]=`PgEnumColumn`;enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};function ue(e,t){return Array.isArray(t)?de(e,[...t],void 0):fe(e,t,void 0)}function de(e,t,n){let r=Object.assign(e=>new ce(e??``,r),{enumName:e,enumValues:t,schema:n,[oe]:!0});return r}function fe(e,t,n){let r=Object.assign(e=>new ie(e??``,r),{enumName:e,enumValues:Object.values(t),schema:n,[oe]:!0});return r}var C=class{static[e]=`Subquery`;constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},pe=class extends C{static[e]=`WithSubquery`};const w={startActiveSpan(e,t){return t()}},T=Symbol.for(`drizzle:ViewBaseConfig`),E=Symbol.for(`drizzle:Schema`),D=Symbol.for(`drizzle:Columns`),me=Symbol.for(`drizzle:ExtraConfigColumns`),he=Symbol.for(`drizzle:OriginalName`),ge=Symbol.for(`drizzle:BaseName`),O=Symbol.for(`drizzle:IsAlias`),_e=Symbol.for(`drizzle:ExtraConfigBuilder`),ve=Symbol.for(`drizzle:IsDrizzleTable`);var k=class{static[e]=`Table`;static Symbol={Name:s,Schema:E,OriginalName:he,Columns:D,ExtraConfigColumns:me,BaseName:ge,IsAlias:O,ExtraConfigBuilder:_e};[s];[he];[E];[D];[me];[ge];[O]=!1;[ve]=!0;[_e]=void 0;constructor(e,t,n){this[s]=this[he]=e,this[E]=t,this[ge]=n}getSQL=void 0};function ye(e){return typeof e==`object`&&!!e&&ve in e}function A(e){return e[s]}function be(e){return`${e[E]??`public`}.${e[s]}`}var xe=class{static[e]=`FakePrimitiveParam`};function Se(e){return e!=null&&typeof e.getSQL==`function`}function Ce(e){let t={sql:``,params:[]};for(let n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||=[],t.typings.push(...n.typings));return t}var j=class{static[e]=`StringChunk`;value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new M([this])}},M=class t{constructor(e){this.queryChunks=e;for(let t of e)if(n(t,k)){let e=t[k.Symbol.Schema];this.usedTables.push(e===void 0?t[k.Symbol.Name]:e+`.`+t[k.Symbol.Name])}}static[e]=`SQL`;decoder=De;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return w.startActiveSpan(`drizzle.buildSQL`,t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let a=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:o,escapeName:s,escapeParam:c,prepareTyping:l,inlineParams:u,paramStartIndex:d}=a;return Ce(e.map(e=>{if(n(e,j))return{sql:e.value.join(``),params:[]};if(n(e,we))return{sql:s(e.value),params:[]};if(e===void 0)return{sql:``,params:[]};if(Array.isArray(e)){let t=[new j(`(`)];for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new j(`, `));return t.push(new j(`)`)),this.buildQueryFromSourceParams(t,a)}if(n(e,t))return this.buildQueryFromSourceParams(e.queryChunks,{...a,inlineParams:u||e.shouldInlineParams});if(n(e,k)){let t=e[k.Symbol.Schema],n=e[k.Symbol.Name];return{sql:t===void 0||e[O]?s(n):s(t)+`.`+s(n),params:[]}}if(n(e,r)){let t=o.getColumnCasing(e);if(i.invokeSource===`indexes`)return{sql:s(t),params:[]};let n=e.table[k.Symbol.Schema];return{sql:e.table[O]||n===void 0?s(e.table[k.Symbol.Name])+`.`+s(t):s(n)+`.`+s(e.table[k.Symbol.Name])+`.`+s(t),params:[]}}if(n(e,I)){let t=e[T].schema,n=e[T].name;return{sql:t===void 0||e[T].isAlias?s(n):s(t)+`.`+s(n),params:[]}}if(n(e,N)){if(n(e.value,F))return{sql:c(d.value++,e),params:[e],typings:[`none`]};let r=e.value===null?null:e.encoder.mapToDriverValue(e.value);if(n(r,t))return this.buildQueryFromSourceParams([r],a);if(u)return{sql:this.mapInlineParam(r,a),params:[]};let i=[`none`];return l&&(i=[l(e.encoder)]),{sql:c(d.value++,r),params:[r],typings:i}}return n(e,F)?{sql:c(d.value++,e),params:[e],typings:[`none`]}:n(e,t.Aliased)&&e.fieldAlias!==void 0?{sql:s(e.fieldAlias),params:[]}:n(e,C)?e._.isWith?{sql:s(e._.alias),params:[]}:this.buildQueryFromSourceParams([new j(`(`),e._.sql,new j(`) `),new we(e._.alias)],a):se(e)?e.schema?{sql:s(e.schema)+`.`+s(e.enumName),params:[]}:{sql:s(e.enumName),params:[]}:Se(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],a):this.buildQueryFromSourceParams([new j(`(`),e.getSQL(),new j(`)`)],a):u?{sql:this.mapInlineParam(e,a),params:[]}:{sql:c(d.value++,e),params:[e],typings:[`none`]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(e){return e===void 0?this:new t.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},we=class{constructor(e){this.value=e}static[e]=`Name`;brand;getSQL(){return new M([this])}};function Te(e){return new we(e)}function Ee(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}const De={mapFromDriverValue:e=>e},Oe={mapToDriverValue:e=>e},ke={...De,...Oe};var N=class{constructor(e,t=Oe){this.value=e,this.encoder=t}static[e]=`Param`;brand;getSQL(){return new M([this])}};function Ae(e,t){return new N(e,t)}function P(e,...t){let n=[];(t.length>0||e.length>0&&e[0]!==``)&&n.push(new j(e[0]));for(let[r,i]of t.entries())n.push(i,new j(e[r+1]));return new M(n)}(e=>{function t(){return new M([])}e.empty=t;function n(e){return new M(e)}e.fromList=n;function r(e){return new M([new j(e)])}e.raw=r;function i(e,t){let n=[];for(let[r,i]of e.entries())r>0&&t!==void 0&&n.push(t),n.push(i);return new M(n)}e.join=i;function a(e){return new we(e)}e.identifier=a;function o(e){return new F(e)}e.placeholder=o;function s(e,t){return new N(e,t)}e.param=s})(P||={}),(t=>{class n{constructor(e,t){this.sql=e,this.fieldAlias=t}static[e]=`SQL.Aliased`;isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}t.Aliased=n})(M||={});var F=class{constructor(e){this.name=e}static[e]=`Placeholder`;getSQL(){return new M([this])}};function je(e){return new F(e)}function Me(e,t){return e.map(e=>{if(n(e,F)){if(!(e.name in t))throw Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(n(e,N)&&n(e.value,F)){if(!(e.value.name in t))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}const Ne=Symbol.for(`drizzle:IsDrizzleView`);var I=class{static[e]=`View`;[T];[Ne]=!0;get[s](){return this[T].name}get[E](){return this[T].schema}get[O](){return this[T].isAlias}get[he](){return this[T].originalName}get[D](){return this[T].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[T]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new M([this])}};function Pe(e){return typeof e==`object`&&!!e&&Ne in e}function Fe(e){return e[T].name}r.prototype.getSQL=function(){return new M([this])},k.prototype.getSQL=function(){return new M([this])},C.prototype.getSQL=function(){return new M([this])};var Ie=class{constructor(e){this.table=e}static[e]=`ColumnAliasProxyHandler`;get(e,t){return t===`table`?this.table:e[t]}},Le=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[e]=`TableAliasProxyHandler`;get(e,t){if(t===k.Symbol.IsAlias)return!0;if(t===k.Symbol.Name||this.replaceOriginalName&&t===k.Symbol.OriginalName)return this.alias;if(t===T)return{...e[T],name:this.alias,isAlias:!0};if(t===k.Symbol.Columns){let t=e[k.Symbol.Columns];if(!t)return t;let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new Ie(new Proxy(e,this)))}),n}let i=e[t];return n(i,r)?new Proxy(i,new Ie(new Proxy(e,this))):i}},Re=class{constructor(e){this.alias=e}static[e]=`RelationTableAliasProxyHandler`;get(e,t){return t===`sourceTable`?L(e.sourceTable,this.alias):e[t]}};function L(e,t){return new Proxy(e,new Le(t,!1))}function ze(e,t){return new Proxy(e,new Re(t))}function R(e,t){return new Proxy(e,new Ie(new Proxy(e.table,new Le(t,!1))))}function Be(e,t){return new M.Aliased(Ve(e.sql,t),e.fieldAlias)}function Ve(e,t){return P.join(e.queryChunks.map(e=>n(e,r)?R(e,t):n(e,M)?Ve(e,t):n(e,M.Aliased)?Be(e,t):e))}var He=class extends Error{static[e]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},Ue=class t extends Error{constructor(e,n,r){super(`Failed query: ${e}
|
|
2
|
-
params: ${n}`),this.query=e,this.params=n,this.cause=r,Error.captureStackTrace(this,t),r&&(this.cause=r)}static[e]=`DrizzleQueryError`},We=class extends He{static[e]=`TransactionRollbackError`;constructor(){super({message:`Rollback`})}},Ge=class{static[e]=`ConsoleLogWriter`;write(e){console.log(e)}},Ke=class{static[e]=`DefaultLogger`;writer;constructor(e){this.writer=e?.writer??new Ge}logQuery(e,t){let n=t.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),r=n.length?` -- params: [${n.join(`, `)}]`:``;this.writer.write(`Query: ${e}${r}`)}},qe=class{static[e]=`NoopLogger`;logQuery(){}},z=class{static[e]=`QueryPromise`;[Symbol.toStringTag]=`QueryPromise`;catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function B(e,t){return Ee(t)&&!Se(e)&&!n(e,N)&&!n(e,F)&&!n(e,r)&&!n(e,k)&&!n(e,I)?new N(e,t):e}const V=(e,t)=>P`${e} = ${B(t,e)}`,Je=(e,t)=>P`${e} <> ${B(t,e)}`;function H(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new M(t):new M([new j(`(`),P.join(t,new j(` and `)),new j(`)`)])}function Ye(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new M(t):new M([new j(`(`),P.join(t,new j(` or `)),new j(`)`)])}function Xe(e){return P`not ${e}`}const Ze=(e,t)=>P`${e} > ${B(t,e)}`,Qe=(e,t)=>P`${e} >= ${B(t,e)}`,$e=(e,t)=>P`${e} < ${B(t,e)}`,et=(e,t)=>P`${e} <= ${B(t,e)}`;function tt(e,t){return Array.isArray(t)?t.length===0?P`false`:P`${e} in ${t.map(t=>B(t,e))}`:P`${e} in ${B(t,e)}`}function nt(e,t){return Array.isArray(t)?t.length===0?P`true`:P`${e} not in ${t.map(t=>B(t,e))}`:P`${e} not in ${B(t,e)}`}function rt(e){return P`${e} is null`}function it(e){return P`${e} is not null`}function at(e){return P`exists ${e}`}function ot(e){return P`not exists ${e}`}function st(e,t,n){return P`${e} between ${B(t,e)} and ${B(n,e)}`}function ct(e,t,n){return P`${e} not between ${B(t,e)} and ${B(n,e)}`}function lt(e,t){return P`${e} like ${t}`}function ut(e,t){return P`${e} not like ${t}`}function dt(e,t){return P`${e} ilike ${t}`}function ft(e,t){return P`${e} not ilike ${t}`}function pt(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);return P`${e} @> ${P`${B(t,e)}`}`}return P`${e} @> ${B(t,e)}`}function mt(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);return P`${e} <@ ${P`${B(t,e)}`}`}return P`${e} <@ ${B(t,e)}`}function ht(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);return P`${e} && ${P`${B(t,e)}`}`}return P`${e} && ${B(t,e)}`}function gt(e){return P`${e} asc`}function _t(e){return P`${e} desc`}function vt(e,t){for(let t of Object.values(e))for(let[e,r]of Object.entries(t.relations))n(r,U)&&(r.sourceTable=t.table,r.fieldName=e);for(let[r,i]of Object.entries(e))for(let[a,o]of Object.entries(i.relations)){if(!n(o,U))continue;let s,{targetTableName:c,alias:l,sourceColumns:u,targetColumns:d,throughTable:f,sourceTable:p,through:m,targetTable:h,where:g,sourceColumnTableNames:_,targetColumnTableNames:v}=o,y=`relations -> ${i.name}: { ${a}: r.${n(o,xt)?`one`:`many`}.${c}(...) }`;if(a in i.table[D])throw Error(`${y}: relation name collides with column "${a}" of table "${i.name}"`);if(typeof l==`string`&&!l)throw Error(`${y}: "alias" cannot be an empty string - omit it if you don't need it`);if(u?.length===0)throw Error(`${y}: "from" cannot be empty`);if(d?.length===0)throw Error(`${y}: "to" cannot be empty`);if(u&&d){if(u.length!==d.length&&!f)throw Error(`${y}: "from" and "to" fields without "through" must have the same length`);for(let e of _)if(e!==r)throw Error(`${y}: all "from" columns must belong to table "${r}", found column of table "${e}"`);for(let e of v)if(e!==c)throw Error(`${y}: all "to" columns must belong to table "${h}", found column of table "${e}"`);if(m){if(m.source.length!==u.length||m.target.length!==d.length)throw Error(`${y}: ".through(column)" must be used either on all columns in "from" and "to" or not defined on any of them`);for(let e of m.source)if(t[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`);for(let e of m.target)if(t[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`)}continue}if(u||d)throw Error(`${y}: relation must have either both "from" and "to" defined, or none of them`);let b=e[c];if(!b)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relations of table "${c}" were found"`);if(l){let e=Object.values(b.relations).filter(e=>n(e,U)&&e.alias===l&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations with alias "${l}" found in table "${c}": ${e.map(e=>`"${e.fieldName}"`).join(`, `)}`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and there is no reverse relation of table "${c}" with alias "${l}"`)}else{let e=Object.values(b.relations).filter(e=>n(e,U)&&e.targetTable===p&&!e.alias&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations between "${c}" and "${r}" were found.
|
|
3
|
-
Hint: you can specify "alias" on both sides of the relation with the same value`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relation of table "${c}" with target table "${r}" was found`)}if(!s.sourceColumns||!s.targetColumns)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and reverse relation "${c}.${s.fieldName}" does not have "from"/"to" defined`);o.sourceColumns=s.targetColumns,o.targetColumns=s.sourceColumns,o.through=s.through?{source:s.through.target,target:s.through.source}:void 0,o.throughTable=s.throughTable,o.isReversed=!g,o.where=g??s.where}return e}function yt(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]={table:i,name:r,relations:t[r]??{}};return vt(n,e)}function bt(e,t){let n={};for(let[r,i]of Object.entries(t))!i||!e[r]||(n[r]={table:e[r],name:r,relations:i});return vt(n,e)}var U=class{constructor(e,t){this.targetTableName=t,this.targetTable=e}static[e]=`RelationV2`;fieldName;sourceColumns;targetColumns;alias;where;sourceTable;targetTable;through;throughTable;isReversed;sourceColumnTableNames=[];targetColumnTableNames=[]},xt=class extends U{static[e]=`OneV2`;relationType=`one`;optional;constructor(e,t,n,r){super(t,n),this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)}),this.optional=r?.optional??!0}},St=class extends U{constructor(e,t,n,r){super(t,n),this.config=r,this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)})}static[e]=`ManyV2`;relationType=`many`},Ct=class{static[e]=`AggregatedField`;table;onTable(e){return this.table=e,this}},wt=class extends Ct{static[e]=`AggregatedFieldCount`;query;getSQL(){if(!this.query){if(!this.table)throw Error(`Table must be set before building aggregate field`);this.query=P`select count(*) as ${P.identifier(`r`)} from ${Vt(this.table)}`.mapWith(Number)}return this.query}};const W={and:H,between:st,eq:V,exists:at,gt:Ze,gte:Qe,ilike:dt,inArray:tt,arrayContains:pt,arrayContained:mt,arrayOverlaps:ht,isNull:rt,isNotNull:it,like:lt,lt:$e,lte:et,ne:Je,not:Xe,notBetween:ct,notExists:ot,notLike:ut,notIlike:ft,notInArray:nt,or:Ye,sql:P},Tt={sql:P,asc:gt,desc:_t};function Et(){return Tt}function Dt(e,t,i=e=>e,a=!1,o=!1,s){for(let c of t){if(c.selection){let t=`${s?`${s}.`:``}${c.key}`;if(e[c.key]===null)continue;if(a&&(e[c.key]=JSON.parse(e[c.key])),o&&typeof e[c.key]==`string`&&(e[c.key]=JSON.parse(e[c.key])),c.isArray){for(let n of e[c.key])Dt(n,c.selection,i,!1,o,t);continue}Dt(e[c.key],c.selection,i,!1,o,t);continue}let t=c.field,l=i(e[c.key]);if(l===null)continue;let u;u=n(t,r)?t:n(t,M)?t.decoder:n(t,M.Aliased)?t.sql.decoder:t.getSQL().decoder,e[c.key]=`mapFromJsonValue`in u?u.mapFromJsonValue(l):u.mapFromDriverValue(l)}return e}var Ot=class{static[e]=`RelationsBuilderTable`;_;constructor(e,t){this._={name:t,table:e}}},kt=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n){this._={tableName:t,column:e,key:n}}through(e){return new At(this._.column,this._.tableName,this._.key,e)}},At=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n,r){this._={tableName:t,column:e,through:r,key:n}}},jt=class{static[e]=`RelationsHelperStatic`;_;constructor(e){this._={tables:e};let t={},n={};for(let[r,i]of Object.entries(e))t[r]=t=>new xt(e,i,r,t),n[r]=t=>new St(e,i,r,t);this.one=t,this.many=n}one;many;aggs={count(){return new wt}}};function Mt(e){let t=new jt(e),n=Object.entries(e).reduce((e,[t,n])=>{let r=new Ot(n,t),i=Object.entries(n[D]).reduce((e,[n,r])=>(e[n]=new kt(r,t,n),e),{});return e[t]=Object.assign(r,i),e},{});return Object.assign(t,n)}function Nt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>n(t,k)||n(t,I)))}function Pt(e,t){let n=Nt(e);return yt(n,t?t(Mt(n)):{})}function Ft(e,t){let n=Nt(e);return bt(n,t?t(Mt(n)):Object.fromEntries(Object.keys(n).map(e=>[e,{}])))}function It(e,t){let i=e[D][t];return i?n(i,r)?i:n(i,M.Aliased)?P`${e}.${P.identifier(i.fieldAlias)}`:P`${e}.${P.identifier(t)}`:P`${e}.${P.identifier(t)}`}function Lt(e,t){if(typeof t!=`object`||n(t,F))return V(e,t);let r=Object.entries(t);if(!r.length)return;let i=[];for(let[t,n]of r)if(n!==void 0)switch(t){case`NOT`:{let t=Lt(e,n);if(!t)continue;i.push(Xe(t));continue}case`OR`:if(!n.length)continue;i.push(Ye(...n.map(t=>Lt(e,t))));continue;case`AND`:if(!n.length)continue;i.push(H(...n.map(t=>Lt(e,t))));continue;case`isNotNull`:case`isNull`:if(!n)continue;i.push(W[t](e));continue;case`in`:i.push(W.inArray(e,n));continue;case`notIn`:i.push(W.notInArray(e,n));continue;default:i.push(W[t](e,n));continue}if(i.length)return H(...i)}function G(e,t,n={},r={},i,a=0){let o=Object.entries(t);if(!o.length)return;let s=[];for(let[t,c]of o)if(c!==void 0)switch(t){case`RAW`:{let t=typeof c==`function`?c(e,W):c.getSQL();s.push(t);continue}case`OR`:if(!c?.length)continue;s.push(Ye(...c.map(t=>G(e,t,n,r,i,a))));continue;case`AND`:if(!c?.length)continue;s.push(H(...c.map(t=>G(e,t,n,r,i,a))));continue;case`NOT`:{if(c===void 0)continue;let t=G(e,c,n,r,i,a);if(!t)continue;s.push(Xe(t));continue}default:{if(e[D][t]){let n=Lt(It(e,t),c);n&&s.push(n);continue}let o=n[t];if(!o)throw new He({message:`Unknown relational filter field: "${t}"`});let l=L(o.targetTable,`f${a}`),u=o.throughTable?L(o.throughTable,`ft${a}`):void 0,d=r[o.targetTableName],{filter:f,joinCondition:p}=Bt(i,o,e,l,u),m=H(f,typeof c==`boolean`?void 0:G(l,c,d.relations,r,i,a+1)),h=u?P`(select * from ${Vt(l)} inner join ${Vt(u)} on ${p}${P` where ${m}`.if(m)} limit 1)`:P`(select * from ${Vt(l)}${P` where ${m}`.if(m)} limit 1)`;m&&s.push((c?at:ot)(h))}}return H(...s)}function Rt(e,t){if(typeof t==`function`){let i=t(e,Tt);return n(i,M)?i:Array.isArray(i)?i.length?P.join(i.map(e=>n(e,M)?e:gt(e)),P`, `):void 0:n(i,r)?gt(i):void 0}let i=Object.entries(t).filter(([e,t])=>t);if(i.length)return P.join(i.map(([t,n])=>(n===`asc`?gt:_t)(It(e,t))),P`, `)}function zt(e,t){let n=[],r=[];for(let[i,a]of Object.entries(t)){if(!a)continue;let t=typeof a==`function`?a(e,{sql:W.sql}):a,o=P`(${t.getSQL()}) as ${P.identifier(i)}`;o.decoder=t.getSQL().decoder,n.push(o),r.push({key:i,field:o})}return{sql:n.length?P.join(n,P`, `):void 0,selection:r}}function Bt(e,t,i,a,o){if(t.through){let s=t.sourceColumns.map((a,s)=>{let c=t.through.source[s];return V(P`${i}.${P.identifier(e.getColumnCasing(a))}`,P`${o}.${P.identifier(n(c._.column,r)?e.getColumnCasing(c._.column):c._.key)}`)}),c=t.targetColumns.map((i,s)=>{let c=t.through.target[s];return V(P`${o}.${P.identifier(n(c._.column,r)?e.getColumnCasing(c._.column):c._.key)}`,P`${a}.${P.identifier(e.getColumnCasing(i))}`)});return{filter:H(t.where?G(t.isReversed?i:a,t.where):void 0,...s),joinCondition:H(...c)}}return{filter:H(...t.sourceColumns.map((n,r)=>{let o=t.targetColumns[r];return V(P`${i}.${P.identifier(e.getColumnCasing(n))}`,P`${a}.${P.identifier(e.getColumnCasing(o))}`)}),t.where?G(t.isReversed?i:a,t.where):void 0)}}function Vt(e){return P`${e[O]?P`${P`${P.identifier(e[E]??``)}.`.if(e[E])}${P.identifier(e[he])} as ${e}`:e}`}function Ht(e){return P`count(${e||P.raw(`*`)})`.mapWith(Number)}function Ut(e){return P`count(distinct ${e})`.mapWith(Number)}function Wt(e){return P`avg(${e})`.mapWith(String)}function Gt(e){return P`avg(distinct ${e})`.mapWith(String)}function Kt(e){return P`sum(${e})`.mapWith(String)}function qt(e){return P`sum(distinct ${e})`.mapWith(String)}function Jt(e){return P`max(${e})`.mapWith(n(e,r)?e:String)}function Yt(e){return P`min(${e})`.mapWith(n(e,r)?e:String)}function Xt(e){return JSON.stringify(e)}function Zt(e,t){return Array.isArray(t)?P`${e} <-> ${Xt(t)}`:P`${e} <-> ${t}`}function Qt(e,t){return Array.isArray(t)?P`${e} <+> ${Xt(t)}`:P`${e} <+> ${t}`}function $t(e,t){return Array.isArray(t)?P`${e} <#> ${Xt(t)}`:P`${e} <#> ${t}`}function en(e,t){return Array.isArray(t)?P`${e} <=> ${Xt(t)}`:P`${e} <=> ${t}`}function tn(e,t){return Array.isArray(t)?P`${e} <~> ${Xt(t)}`:P`${e} <~> ${t}`}function nn(e,t){return Array.isArray(t)?P`${e} <%> ${Xt(t)}`:P`${e} <%> ${t}`}function rn(e,t,i){let a={},o=e.reduce((e,{path:o,field:s},c)=>{let l;l=n(s,r)?s:n(s,M)?s.decoder:s.sql.decoder;let u=e;for(let[e,d]of o.entries())if(e<o.length-1)d in u||(u[d]={}),u=u[d];else{let e=t[c],f=u[d]=e===null?null:l.mapFromDriverValue(e);if(i&&n(s,r)&&o.length===2){let e=o[0];e in a?typeof a[e]==`string`&&a[e]!==A(s.table)&&(a[e]=!1):a[e]=f===null?A(s.table):!1}}return e},{});if(i&&Object.keys(a).length>0)for(let[e,t]of Object.entries(a))typeof t==`string`&&!i[t]&&(o[e]=null);return o}function K(e,t){return Object.entries(e).reduce((e,[i,a])=>{if(typeof i!=`string`)return e;let o=t?[...t,i]:[i];return n(a,r)||n(a,M)||n(a,M.Aliased)?e.push({path:o,field:a}):n(a,k)?e.push(...K(a[k.Symbol.Columns],o)):e.push(...K(a,o)),e},[])}function an(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function on(e,t){let i=Object.entries(t).filter(([,e])=>e!==void 0).map(([t,i])=>n(i,M)||n(i,r)?[t,i]:[t,new N(i,e[k.Symbol.Columns][t])]);if(i.length===0)throw Error(`No values to set`);return Object.fromEntries(i)}function sn(e,t){for(let n of t)for(let t of Object.getOwnPropertyNames(n.prototype))t!==`constructor`&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function cn(e){return e[k.Symbol.Columns]}function ln(e){return e[T].selectedFields}function q(e){return n(e,C)?e._.alias:n(e,I)?e[T].name:n(e,M)?void 0:e[k.Symbol.IsAlias]?e[k.Symbol.Name]:e[k.Symbol.BaseName]}function J(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}function un(e){if(typeof e!=`object`||!e||e.constructor.name!==`Object`)return!1;if(`logger`in e){let t=typeof e.logger;return!(t!==`boolean`&&(t!==`object`||typeof e.logger.logQuery!=`function`)&&t!==`undefined`)}if(`schema`in e){let t=typeof e.schema;return!(t!==`object`&&t!==`undefined`)}if(`relations`in e){let t=typeof e.relations;return!(t!==`object`&&t!==`undefined`)}if(`casing`in e){let t=typeof e.casing;return!(t!==`string`&&t!==`undefined`)}if(`mode`in e)return!(e.mode!==`default`||e.mode!==`planetscale`||e.mode!==void 0);if(`connection`in e){let t=typeof e.connection;return!(t!==`string`&&t!==`object`&&t!==`undefined`)}if(`client`in e){let t=typeof e.client;return!(t!==`object`&&t!==`function`&&t!==`undefined`)}return Object.keys(e).length===0}const dn=typeof TextDecoder>`u`?null:new TextDecoder;function fn(e,t){return new Proxy(e,new Le(t,!1))}var pn=class{constructor(e,t){this.name=e,this.value=t}static[e]=`PgCheckBuilder`;brand;build(e){return new mn(e,this)}},mn=class{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[e]=`PgCheck`;name;value};function hn(e,t){return new pn(e,t)}var gn=class extends x{static[e]=`PgIntColumnBaseBuilder`;generatedAlwaysAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`always`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`always`};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`byDefault`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`byDefault`};return this.config.hasDefault=!0,this.config.notNull=!0,this}},_n=class extends gn{static[e]=`PgBigInt53Builder`;constructor(e){super(e,`number int53`,`PgBigInt53`)}build(e){return new vn(e,this.config)}},vn=class extends S{static[e]=`PgBigInt53`;getSQLType(){return`bigint`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},yn=class extends gn{static[e]=`PgBigInt64Builder`;constructor(e){super(e,`bigint int64`,`PgBigInt64`)}build(e){return new bn(e,this.config)}},bn=class extends S{static[e]=`PgBigInt64`;getSQLType(){return`bigint`}mapFromDriverValue(e){return BigInt(e)}};function xn(e,t){let{name:n,config:r}=J(e,t);return r.mode===`number`?new _n(n):new yn(n)}var Sn=class extends x{static[e]=`PgBigSerial53Builder`;constructor(e){super(e,`number int53`,`PgBigSerial53`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Cn(e,this.config)}},Cn=class extends S{static[e]=`PgBigSerial53`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},wn=class extends x{static[e]=`PgBigSerial64Builder`;constructor(e){super(e,`bigint int64`,`PgBigSerial64`),this.config.hasDefault=!0}build(e){return new Tn(e,this.config)}},Tn=class extends S{static[e]=`PgBigSerial64`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return BigInt(e)}};function En(e,t){let{name:n,config:r}=J(e,t);return r.mode===`number`?new Sn(n):new wn(n)}var Dn=class extends x{static[e]=`PgBooleanBuilder`;constructor(e){super(e,`boolean`,`PgBoolean`)}build(e){return new On(e,this.config)}},On=class extends S{static[e]=`PgBoolean`;getSQLType(){return`boolean`}};function kn(e){return new Dn(e??``)}var An=class extends x{static[e]=`PgByteaBuilder`;constructor(e){super(e,`object buffer`,`PgBytea`)}build(e){return new jn(e,this.config)}},jn=class extends S{static[e]=`PgBytea`;mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;if(typeof e==`string`){let t=e.slice(2,e.length);return Buffer.from(t,`hex`)}return Buffer.from(e)}getSQLType(){return`bytea`}};function Mn(e){return new An(e??``)}var Nn=class extends x{static[e]=`PgCharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgChar`),this.config.length=t.length??1,this.config.setLength=t.length!==void 0,this.config.enumValues=t.enum,this.config.isLengthExact=!0}build(e){return new Pn(e,this.config)}},Pn=class extends S{static[e]=`PgChar`;enumValues=this.config.enumValues;getSQLType(){return this.config.setLength?`char(${this.length})`:`char`}};function Fn(e,t={}){let{name:n,config:r}=J(e,t);return new Nn(n,r)}var In=class extends x{static[e]=`PgCidrBuilder`;constructor(e){super(e,`string cidr`,`PgCidr`)}build(e){return new Ln(e,this.config)}},Ln=class extends S{static[e]=`PgCidr`;getSQLType(){return`cidr`}};function Rn(e){return new In(e??``)}var zn=class extends x{static[e]=`PgCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`PgCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new Bn(e,this.config)}},Bn=class extends S{static[e]=`PgCustomColumn`;sqlName;mapTo;mapFrom;mapJson;forJsonSelect;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver,this.mapJson=t.customTypeParams.fromJson,this.forJsonSelect=t.customTypeParams.forJsonSelect}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==`function`?this.mapFrom(e):e}mapFromJsonValue(e){return typeof this.mapJson==`function`?this.mapJson(e):this.mapFromDriverValue(e)}jsonSelectIdentifier(e,t,n){if(typeof this.forJsonSelect==`function`)return this.forJsonSelect(e,t,n);let r=this.getSQLType().toLowerCase(),i=r.indexOf(`(`);switch(i+1?r.slice(0,i):r){case`bytea`:case`geometry`:case`timestamp`:case`numeric`:case`bigint`:{let r=`[]`.repeat(n??0);return t`${e}::text${t.raw(r).if(n)}`}default:return e}}mapToDriverValue(e){return typeof this.mapTo==`function`?this.mapTo(e):e}};function Vn(e){return(t,n)=>{let{name:r,config:i}=J(t,n);return new zn(r,i,e)}}var Hn=class extends x{static[e]=`PgDateColumnBaseBuilder`;defaultNow(){return this.default(P`now()`)}},Un=class extends Hn{static[e]=`PgDateBuilder`;constructor(e){super(e,`object date`,`PgDate`)}build(e){return new Wn(e,this.config)}},Wn=class extends S{static[e]=`PgDate`;getSQLType(){return`date`}mapFromDriverValue(e){return new Date(e)}mapToDriverValue(e){return e.toISOString()}},Gn=class extends Hn{static[e]=`PgDateStringBuilder`;constructor(e){super(e,`string date`,`PgDateString`)}build(e){return new Kn(e,this.config)}},Kn=class extends S{static[e]=`PgDateString`;getSQLType(){return`date`}};function qn(e,t){let{name:n,config:r}=J(e,t);return r?.mode===`date`?new Un(n):new Gn(n)}var Jn=class extends x{static[e]=`PgDoublePrecisionBuilder`;constructor(e){super(e,`number double`,`PgDoublePrecision`)}build(e){return new Yn(e,this.config)}},Yn=class extends S{static[e]=`PgDoublePrecision`;getSQLType(){return`double precision`}mapFromDriverValue(e){return typeof e==`string`?Number.parseFloat(e):e}};function Xn(e){return new Jn(e??``)}var Zn=class extends x{static[e]=`PgInetBuilder`;constructor(e){super(e,`string inet`,`PgInet`)}build(e){return new Qn(e,this.config)}},Qn=class extends S{static[e]=`PgInet`;getSQLType(){return`inet`}};function $n(e){return new Zn(e??``)}var er=class extends gn{static[e]=`PgIntegerBuilder`;constructor(e){super(e,`number int32`,`PgInteger`)}build(e){return new tr(e,this.config)}},tr=class extends S{static[e]=`PgInteger`;getSQLType(){return`integer`}mapFromDriverValue(e){return typeof e==`string`?Number.parseInt(e):e}};function nr(e){return new er(e??``)}var rr=class extends x{static[e]=`PgIntervalBuilder`;constructor(e,t){super(e,`string interval`,`PgInterval`),this.config.intervalConfig=t}build(e){return new ir(e,this.config)}},ir=class extends S{static[e]=`PgInterval`;fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:``}${this.precision?`(${this.precision})`:``}`}};function ar(e,t={}){let{name:n,config:r}=J(e,t);return new rr(n,r)}var or=class extends x{static[e]=`PgJsonBuilder`;constructor(e){super(e,`object json`,`PgJson`)}build(e){return new sr(e,this.config)}},sr=class extends S{static[e]=`PgJson`;constructor(e,t){super(e,t)}getSQLType(){return`json`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function cr(e){return new or(e??``)}var lr=class extends x{static[e]=`PgJsonbBuilder`;constructor(e){super(e,`object json`,`PgJsonb`)}build(e){return new ur(e,this.config)}},ur=class extends S{static[e]=`PgJsonb`;constructor(e,t){super(e,t)}getSQLType(){return`jsonb`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function dr(e){return new lr(e??``)}var fr=class extends x{static[e]=`PgLineBuilder`;constructor(e){super(e,`array line`,`PgLine`)}build(e){return new pr(e,this.config)}},pr=class extends S{static[e]=`PgLine`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},mr=class extends x{static[e]=`PgLineABCBuilder`;constructor(e){super(e,`object line`,`PgLineABC`)}build(e){return new hr(e,this.config)}},hr=class extends S{static[e]=`PgLineABC`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function gr(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new fr(n):new mr(n)}var _r=class extends x{static[e]=`PgMacaddrBuilder`;constructor(e){super(e,`string macaddr`,`PgMacaddr`)}build(e){return new vr(e,this.config)}},vr=class extends S{static[e]=`PgMacaddr`;getSQLType(){return`macaddr`}};function yr(e){return new _r(e??``)}var br=class extends x{static[e]=`PgMacaddr8Builder`;constructor(e){super(e,`string macaddr8`,`PgMacaddr8`)}build(e){return new xr(e,this.config)}},xr=class extends S{static[e]=`PgMacaddr8`;getSQLType(){return`macaddr8`}};function Sr(e){return new br(e??``)}var Cr=class extends x{static[e]=`PgNumericBuilder`;constructor(e,t,n){super(e,`string numeric`,`PgNumeric`),this.config.precision=t,this.config.scale=n}build(e){return new wr(e,this.config)}},wr=class extends S{static[e]=`PgNumeric`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`string`?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Tr=class extends x{static[e]=`PgNumericNumberBuilder`;constructor(e,t,n){super(e,`number`,`PgNumericNumber`),this.config.precision=t,this.config.scale=n}build(e){return new Er(e,this.config)}},Er=class extends S{static[e]=`PgNumericNumber`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Dr=class extends x{static[e]=`PgNumericBigIntBuilder`;constructor(e,t,n){super(e,`bigint int64`,`PgNumericBigInt`),this.config.precision=t,this.config.scale=n}build(e){return new Or(e,this.config)}},Or=class extends S{static[e]=`PgNumericBigInt`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}};function kr(e,t){let{name:n,config:r}=J(e,t),i=r?.mode;return i===`number`?new Tr(n,r?.precision,r?.scale):i===`bigint`?new Dr(n,r?.precision,r?.scale):new Cr(n,r?.precision,r?.scale)}const Ar=kr;var jr=class extends x{static[e]=`PgPointTupleBuilder`;constructor(e){super(e,`array point`,`PgPointTuple`)}build(e){return new Mr(e,this.config)}},Mr=class extends S{static[e]=`PgPointTuple`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Nr=class extends x{static[e]=`PgPointObjectBuilder`;constructor(e){super(e,`object point`,`PgPointObject`)}build(e){return new Pr(e,this.config)}},Pr=class extends S{static[e]=`PgPointObject`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function Fr(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new jr(n):new Nr(n)}function Ir(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function Lr(e,t){let n=new ArrayBuffer(8),r=new DataView(n);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function Rr(e){let t=Ir(e),n=0,r=t[n];n+=1;let i=new DataView(t.buffer),a=i.getUint32(n,r===1);if(n+=4,a&536870912&&(i.getUint32(n,r===1),n+=4),(a&65535)==1){let e=Lr(t,n);n+=8;let r=Lr(t,n);return n+=8,[e,r]}throw Error(`Unsupported geometry type`)}var zr=class extends x{static[e]=`PgGeometryBuilder`;constructor(e){super(e,`array geometry`,`PgGeometry`)}build(e){return new Br(e,this.config)}},Br=class extends S{static[e]=`PgGeometry`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){return typeof e==`string`?Rr(e):e}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},Vr=class extends x{static[e]=`PgGeometryObjectBuilder`;constructor(e){super(e,`object geometry`,`PgGeometryObject`)}build(e){return new Hr(e,this.config)}},Hr=class extends S{static[e]=`PgGeometryObject`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){let t=Rr(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function Ur(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new zr(n):new Vr(n)}var Wr=class extends x{static[e]=`PgRealBuilder`;constructor(e,t){super(e,`number float`,`PgReal`),this.config.length=t}build(e){return new Gr(e,this.config)}},Gr=class extends S{static[e]=`PgReal`;constructor(e,t){super(e,t)}getSQLType(){return`real`}mapFromDriverValue=e=>typeof e==`string`?Number.parseFloat(e):e};function Kr(e){return new Wr(e??``)}var qr=class extends x{static[e]=`PgSerialBuilder`;constructor(e){super(e,`number int32`,`PgSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Jr(e,this.config)}},Jr=class extends S{static[e]=`PgSerial`;getSQLType(){return`serial`}};function Yr(e){return new qr(e??``)}var Xr=class extends gn{static[e]=`PgSmallIntBuilder`;constructor(e){super(e,`number int16`,`PgSmallInt`)}build(e){return new Zr(e,this.config)}},Zr=class extends S{static[e]=`PgSmallInt`;getSQLType(){return`smallint`}mapFromDriverValue=e=>typeof e==`string`?Number(e):e};function Qr(e){return new Xr(e??``)}var $r=class extends x{static[e]=`PgSmallSerialBuilder`;constructor(e){super(e,`number int16`,`PgSmallSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new ei(e,this.config)}},ei=class extends S{static[e]=`PgSmallSerial`;getSQLType(){return`smallserial`}};function ti(e){return new $r(e??``)}var ni=class extends x{static[e]=`PgTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgText`),this.config.enumValues=t.enum}build(e){return new ri(e,this.config,this.config.enumValues)}},ri=class extends S{static[e]=`PgText`;enumValues;constructor(e,t,n){super(e,t),this.enumValues=n}getSQLType(){return`text`}};function ii(e,t={}){let{name:n,config:r}=J(e,t);return new ni(n,r)}var ai=class extends Hn{constructor(e,t,n){super(e,`string time`,`PgTime`),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[e]=`PgTimeBuilder`;build(e){return new oi(e,this.config)}},oi=class extends S{static[e]=`PgTime`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function si(e,t={}){let{name:n,config:r}=J(e,t);return new ai(n,r.withTimezone??!1,r.precision)}var ci=class extends Hn{static[e]=`PgTimestampBuilder`;constructor(e,t,n){super(e,`object date`,`PgTimestamp`),this.config.withTimezone=t,this.config.precision=n}build(e){return new li(e,this.config)}},li=class extends S{static[e]=`PgTimestamp`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:` (${this.precision})`}${this.withTimezone?` with time zone`:``}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+`+0000`);mapToDriverValue=e=>e.toISOString()},ui=class extends Hn{static[e]=`PgTimestampStringBuilder`;constructor(e,t,n){super(e,`string timestamp`,`PgTimestampString`),this.config.withTimezone=t,this.config.precision=n}build(e){return new di(e,this.config)}},di=class extends S{static[e]=`PgTimestampString`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function fi(e,t={}){let{name:n,config:r}=J(e,t);return r?.mode===`string`?new ui(n,r.withTimezone??!1,r.precision):new ci(n,r?.withTimezone??!1,r?.precision)}var pi=class extends x{static[e]=`PgUUIDBuilder`;constructor(e){super(e,`string uuid`,`PgUUID`)}defaultRandom(){return this.default(P`gen_random_uuid()`)}build(e){return new mi(e,this.config)}},mi=class extends S{static[e]=`PgUUID`;getSQLType(){return`uuid`}};function hi(e){return new pi(e??``)}var gi=class extends x{static[e]=`PgVarcharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgVarchar`),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new _i(e,this.config)}},_i=class extends S{static[e]=`PgVarchar`;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?`varchar`:`varchar(${this.length})`}};function vi(e,t={}){let{name:n,config:r}=J(e,t);return new gi(n,r)}var yi=class extends x{static[e]=`PgBinaryVectorBuilder`;constructor(e,t){super(e,`string binary`,`PgBinaryVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new bi(e,this.config)}},bi=class extends S{static[e]=`PgBinaryVector`;getSQLType(){return`bit(${this.length})`}};function xi(e,t){let{name:n,config:r}=J(e,t);return new yi(n,r)}var Si=class extends x{static[e]=`PgHalfVectorBuilder`;constructor(e,t){super(e,`array halfvector`,`PgHalfVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new Ci(e,this.config)}},Ci=class extends S{static[e]=`PgHalfVector`;getSQLType(){return`halfvec(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function wi(e,t){let{name:n,config:r}=J(e,t);return new Si(n,r)}var Ti=class extends x{static[e]=`PgSparseVectorBuilder`;constructor(e,t){super(e,`string sparsevec`,`PgSparseVector`),this.config.dimensions=t.dimensions}build(e){return new Ei(e,this.config)}},Ei=class extends S{static[e]=`PgSparseVector`;dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function Di(e,t){let{name:n,config:r}=J(e,t);return new Ti(n,r)}var Oi=class extends x{static[e]=`PgVectorBuilder`;constructor(e,t){super(e,`array vector`,`PgVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new ki(e,this.config)}},ki=class extends S{static[e]=`PgVector`;getSQLType(){return`vector(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function Ai(e,t){let{name:n,config:r}=J(e,t);return new Oi(n,r)}var Y=class t{static[e]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(e,i){if(i===`_`)return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(i===T)return{...e[T],selectedFields:new Proxy(e[T].selectedFields,this)};if(typeof i==`symbol`)return e[i];let a=(n(e,C)?e._.selectedFields:n(e,I)?e[T].selectedFields:e)[i];if(n(a,M.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!a.isSelectionField)return a.sql;let e=a.clone();return e.isSelectionField=!0,e}if(n(a,M)){if(this.config.sqlBehavior===`sql`)return a;throw Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return n(a,r)?this.config.alias?new Proxy(a,new Ie(new Proxy(a.table,new Le(this.config.alias,this.config.replaceOriginalName??!1)))):a:typeof a!=`object`||!a?a:new Proxy(a,new t(this.config))}};function ji(){return{bigint:xn,bigserial:En,boolean:kn,char:Fn,cidr:Rn,customType:Vn,date:qn,doublePrecision:Xn,inet:$n,integer:nr,interval:ar,json:cr,jsonb:dr,line:gr,macaddr:yr,macaddr8:Sr,numeric:kr,point:Fr,geometry:Ur,real:Kr,serial:Yr,smallint:Qr,smallserial:ti,text:ii,time:si,timestamp:fi,uuid:hi,varchar:vi,bit:xi,halfvec:wi,sparsevec:Di,vector:Ai}}const Mi=Symbol.for(`drizzle:PgInlineForeignKeys`),Ni=Symbol.for(`drizzle:EnableRLS`);var X=class extends k{static[e]=`PgTable`;static Symbol=Object.assign({},k.Symbol,{InlineForeignKeys:Mi,EnableRLS:Ni});[Mi]=[];[Ni]=!1;[k.Symbol.ExtraConfigBuilder]=void 0;[k.Symbol.ExtraConfigColumns]={}};function Pi(e,t,n,r,i=e){let a=new X(e,r,i),o=typeof t==`function`?t(ji()):t,s=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;n.setName(e);let r=n.build(a);return a[Mi].push(...n.buildForeignKeys(r,a)),[e,r]})),c=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;return n.setName(e),[e,n.buildExtraConfigColumn(a)]})),l=Object.assign(a,s);return l[k.Symbol.Columns]=s,l[k.Symbol.ExtraConfigColumns]=c,n&&(l[X.Symbol.ExtraConfigBuilder]=n),Object.assign(l,{enableRLS:()=>(l[X.Symbol.EnableRLS]=!0,l)})}const Z=(e,t,n)=>Pi(e,t,n,void 0);function Fi(e){return(t,n,r)=>Pi(e(t),n,r,void 0,t)}var Ii=class{constructor(e,t){this.unique=e,this.name=t}static[e]=`PgIndexBuilderOn`;on(...e){return new Li(e.map(e=>{if(n(e,M))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new Li(e.map(e=>{if(n(e,M))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new Li(t.map(e=>{if(n(e,M))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}},Li=class{static[e]=`PgIndexBuilder`;config;constructor(e,t,n,r,i=`btree`){this.config={name:r,columns:e,unique:t,only:n,method:i}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new Ri(this.config,e)}},Ri=class{static[e]=`PgIndex`;config;constructor(e,t){this.config={...e,table:t}}};function zi(e){return new Ii(!1,e)}function Bi(e){return new Ii(!0,e)}var Vi=class{constructor(e,t){this.name=e,t&&(this.as=t.as,this.for=t.for,this.to=t.to,this.using=t.using,this.withCheck=t.withCheck)}static[e]=`PgPolicy`;as;for;to;using;withCheck;_linkedTable;link(e){return this._linkedTable=e,this}};function Hi(e,t){return new Vi(e,t)}function Ui(...e){return e[0].columns?new Wi(e[0].columns,e[0].name):new Wi(e)}var Wi=class{static[e]=`PgPrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Gi(e,this.columns,this.name)}},Gi=class{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[e]=`PgPrimaryKey`;columns;name;getName(){return this.name??`${this.table[X.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}};const Ki=Symbol.for(`drizzle:PgViewConfig`);var qi=class{constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[k.Symbol.Name]}static[e]=`Relation`;referencedTableName;fieldName},Ji=class t extends qi{constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[e]=`One`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=e,n}},Yi=class t extends qi{constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[e]=`Many`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config);return n.fieldName=e,n}};function Xi(){return{and:H,between:st,eq:V,exists:at,gt:Ze,gte:Qe,ilike:dt,inArray:tt,isNull:rt,isNotNull:it,like:lt,lt:$e,lte:et,ne:Je,not:Xe,notBetween:ct,notExists:ot,notLike:ut,notIlike:ft,notInArray:nt,or:Ye,sql:P}}function Zi(){return{sql:P,asc:gt,desc:_t}}function Qi(e,t,r){if(n(r,Ji)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[be(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[k.Symbol.Name]}" not found in schema`);let a=e[i];if(!a)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[be(o)];if(!s)throw Error(`Table "${o[k.Symbol.Name]}" not found in schema`);let c=[];for(let e of Object.values(a.relations))(r.relationName&&r!==e&&e.relationName===r.relationName||!r.relationName&&e.referencedTable===r.sourceTable)&&c.push(e);if(c.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[k.Symbol.Name]}". Please specify relation name`);if(c[0]&&n(c[0],Ji)&&c[0].config)return{fields:c[0].config.references,references:c[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function $i(e,t,i,a,o=e=>e){let s={};for(let[c,l]of a.entries())if(l.isJson){let r=t.relations[l.tsKey],a=i[c],u=typeof a==`string`?JSON.parse(a):a;s[l.tsKey]=n(r,Ji)?u&&$i(e,e[l.relationTableTsKey],u,l.selection,o):u.map(t=>$i(e,e[l.relationTableTsKey],t,l.selection,o))}else{let e=o(i[c]),t=l.field,a;a=n(t,r)?t:n(t,M)?t.decoder:t.sql.decoder,s[l.tsKey]=e===null?null:a.mapFromDriverValue(e)}return s}function ea(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join(`_`)}function ta(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function na(e){return e}var ra=class{static[e]=`CasingCache`;cache={};cachedTables={};convert;constructor(e){this.convert=e===`snake_case`?ea:e===`camelCase`?ta:na}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=`${e.table[k.Symbol.Schema]??`public`}.${e.table[k.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let t=`${e[k.Symbol.Schema]??`public`}.${e[k.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(let i of Object.values(e[k.Symbol.Columns])){if(!n(i,r))continue;let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}},ia=class extends I{static[e]=`PgViewBase`},aa=class{static[e]=`PgDialect`;casing;constructor(e){this.casing=new ra(e?.casing)}async migrate(e,t,n){let r=typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=typeof n==`string`?`drizzle`:n.migrationsSchema??`drizzle`,a=P`
|
|
4
|
-
CREATE TABLE IF NOT EXISTS ${P.identifier(i)}.${P.identifier(r)} (
|
|
1
|
+
const e=Symbol.for(`drizzle:entityKind`),t=Symbol.for(`drizzle:hasOwnEntityKind`);function n(t,n){if(!t||typeof t!=`object`)return!1;if(t instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,e))throw Error(`Class "${n.name??`<unknown>`}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(t).constructor;if(r)for(;r;){if(e in r&&r[e]===n[e])return!0;r=Object.getPrototypeOf(r)}return!1}var r=class{static[e]=`Column`;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}};function i(e){return e.table}function a(e){let[t,n]=e.dataType.split(` `);return{type:t,constraint:n}}var o=class{static[e]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===``&&(this.config.name=e)}};const s=Symbol.for(`drizzle:Name`);var c=class{static[e]=`PgForeignKeyBuilder`;reference;_onUpdate=`no action`;_onDelete=`no action`;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?`no action`:e,this}onDelete(e){return this._onDelete=e===void 0?`no action`:e,this}build(e){return new l(e,this)}},l=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[e]=`PgForeignKey`;reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[s],...r,n[0].table[s],...i];return e??`${a.join(`_`)}_fk`}};function u(e){function t(){let{name:t,columns:n,foreignColumns:r}=e;return{name:t,columns:n,foreignColumns:r}}return new c(t)}function d(e,...t){return e(...t)}function f(e){return new h(e)}function p(e,t){return`${e[s]}_${t.join(`_`)}_unique`}var m=class{constructor(e,t){this.name=t,this.columns=e}static[e]=`PgUniqueConstraintBuilder`;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new g(e,this.columns,this.nullsNotDistinctConfig,this.name)}},h=class{static[e]=`PgUniqueOnConstraintBuilder`;name;constructor(e){this.name=e}on(...e){return new m(e,this.name)}},g=class{constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??p(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[e]=`PgUniqueConstraint`;columns;name;nullsNotDistinct=!1;getName(){return this.name}};function _(e,t,n){for(let r=t;r<e.length;r++){let i=e[r];if(i===`\\`){r++;continue}if(i===`"`)return[e.slice(t,r).replace(/\\/g,``),r+1];if(!n&&(i===`,`||i===`}`))return[e.slice(t,r).replace(/\\/g,``),r]}return[e.slice(t).replace(/\\/g,``),e.length]}function v(e,t=0){let n=[],r=t,i=!1;for(;r<e.length;){let a=e[r];if(a===`,`){(i||r===t)&&n.push(``),i=!0,r++;continue}if(i=!1,a===`\\`){r+=2;continue}if(a===`"`){let[t,i]=_(e,r+1,!0);n.push(t),r=i;continue}if(a===`}`)return[n,r+1];if(a===`{`){let[t,i]=v(e,r+1);n.push(t),r=i;continue}let[o,s]=_(e,r,!1);n.push(o),r=s}return[n,r]}function y(e){let[t]=v(e,1);return t}function b(e){return`{${e.map(e=>Array.isArray(e)?b(e):typeof e==`string`?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:`${e}`).join(`,`)}}`}var x=class extends o{foreignKeyConfigs=[];static[e]=`PgColumnBuilder`;array(e){return new ne(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:`always`,mode:`stored`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>d((n,r)=>{let i=new c(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)},n,r))}buildExtraConfigColumn(e){return new ee(e,this.config)}},S=class extends r{static[e]=`PgColumn`;table;constructor(e,t){t.uniqueName||=p(e,[t.name]),super(e,t),this.table=e}},ee=class extends S{static[e]=`ExtraConfigColumn`;getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??`asc`,nulls:this.config.nulls??`last`,opClass:this.config.opClass};defaultConfig={order:`asc`,nulls:`last`,opClass:void 0};asc(){return this.indexConfig.order=`asc`,this}desc(){return this.indexConfig.order=`desc`,this}nullsFirst(){return this.indexConfig.nulls=`first`,this}nullsLast(){return this.indexConfig.nulls=`last`,this}op(e){return this.indexConfig.opClass=e,this}},te=class{static[e]=`IndexedColumn`;constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},ne=class extends x{static[e]=`PgArrayBuilder`;constructor(e,t,n){super(e,`array basecolumn`,`PgArray`),this.config.baseBuilder=t,this.config.length=n}build(e){let t=this.config.baseBuilder.build(e);return new re(e,this.config,t)}},re=class t extends S{constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r}static[e]=`PgArray`;getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.length==`number`?this.length:``}]`}mapFromDriverValue(e){return typeof e==`string`&&(e=y(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapFromJsonValue(e){typeof e==`string`&&(e=y(e));let t=this.baseColumn;return`mapFromJsonValue`in t?e.map(e=>t.mapFromJsonValue(e)):e.map(e=>t.mapFromDriverValue(e))}mapToDriverValue(e,r=!1){let i=e.map(e=>e===null?null:n(this.baseColumn,t)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return r?i:b(i)}},ie=class extends x{static[e]=`PgEnumObjectColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumObjectColumn`),this.config.enum=t}build(e){return new ae(e,this.config)}},ae=class extends S{static[e]=`PgEnumObjectColumn`;enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};const oe=Symbol.for(`drizzle:isPgEnum`);function se(e){return!!e&&typeof e==`function`&&oe in e&&e[oe]===!0}var ce=class extends x{static[e]=`PgEnumColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumColumn`),this.config.enum=t}build(e){return new le(e,this.config)}},le=class extends S{static[e]=`PgEnumColumn`;enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};function ue(e,t){return Array.isArray(t)?de(e,[...t],void 0):fe(e,t,void 0)}function de(e,t,n){let r=Object.assign(e=>new ce(e??``,r),{enumName:e,enumValues:t,schema:n,[oe]:!0});return r}function fe(e,t,n){let r=Object.assign(e=>new ie(e??``,r),{enumName:e,enumValues:Object.values(t),schema:n,[oe]:!0});return r}var C=class{static[e]=`Subquery`;constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},pe=class extends C{static[e]=`WithSubquery`};const w={startActiveSpan(e,t){return t()}},T=Symbol.for(`drizzle:ViewBaseConfig`),E=Symbol.for(`drizzle:Schema`),D=Symbol.for(`drizzle:Columns`),me=Symbol.for(`drizzle:ExtraConfigColumns`),he=Symbol.for(`drizzle:OriginalName`),ge=Symbol.for(`drizzle:BaseName`),_e=Symbol.for(`drizzle:IsAlias`),ve=Symbol.for(`drizzle:ExtraConfigBuilder`),ye=Symbol.for(`drizzle:IsDrizzleTable`);var O=class{static[e]=`Table`;static Symbol={Name:s,Schema:E,OriginalName:he,Columns:D,ExtraConfigColumns:me,BaseName:ge,IsAlias:_e,ExtraConfigBuilder:ve};[s];[he];[E];[D];[me];[ge];[_e]=!1;[ye]=!0;[ve]=void 0;constructor(e,t,n){this[s]=this[he]=e,this[E]=t,this[ge]=n}getSQL=void 0};function be(e){return typeof e==`object`&&!!e&&ye in e}function k(e){return e[s]}function xe(e){return`${e[E]??`public`}.${e[s]}`}function Se(e){return e!=null&&typeof e.getSQL==`function`}function Ce(e){let t={sql:``,params:[]};for(let n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||=[],t.typings.push(...n.typings));return t}var A=class{static[e]=`StringChunk`;value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new j([this])}},j=class t{constructor(e){this.queryChunks=e;for(let t of e)if(n(t,O)){let e=t[O.Symbol.Schema];this.usedTables.push(e===void 0?t[O.Symbol.Name]:e+`.`+t[O.Symbol.Name])}}static[e]=`SQL`;decoder=Ee;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return w.startActiveSpan(`drizzle.buildSQL`,t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let a=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:o,escapeName:s,escapeParam:c,prepareTyping:l,inlineParams:u,paramStartIndex:d}=a;return Ce(e.map(e=>{if(n(e,A))return{sql:e.value.join(``),params:[]};if(n(e,we))return{sql:s(e.value),params:[]};if(e===void 0)return{sql:``,params:[]};if(Array.isArray(e)){let t=[new A(`(`)];for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new A(`, `));return t.push(new A(`)`)),this.buildQueryFromSourceParams(t,a)}if(n(e,t))return this.buildQueryFromSourceParams(e.queryChunks,{...a,inlineParams:u||e.shouldInlineParams});if(n(e,O)){let t=e[O.Symbol.Schema],n=e[O.Symbol.Name];return{sql:t===void 0||e[_e]?s(n):s(t)+`.`+s(n),params:[]}}if(n(e,r)){let t=o.getColumnCasing(e);if(i.invokeSource===`indexes`)return{sql:s(t),params:[]};let n=e.table[O.Symbol.Schema];return{sql:e.table[_e]||n===void 0?s(e.table[O.Symbol.Name])+`.`+s(t):s(n)+`.`+s(e.table[O.Symbol.Name])+`.`+s(t),params:[]}}if(n(e,F)){let t=e[T].schema,n=e[T].name;return{sql:t===void 0||e[T].isAlias?s(n):s(t)+`.`+s(n),params:[]}}if(n(e,M)){if(n(e.value,P))return{sql:c(d.value++,e),params:[e],typings:[`none`]};let r=e.value===null?null:e.encoder.mapToDriverValue(e.value);if(n(r,t))return this.buildQueryFromSourceParams([r],a);if(u)return{sql:this.mapInlineParam(r,a),params:[]};let i=[`none`];return l&&(i=[l(e.encoder)]),{sql:c(d.value++,r),params:[r],typings:i}}return n(e,P)?{sql:c(d.value++,e),params:[e],typings:[`none`]}:n(e,t.Aliased)&&e.fieldAlias!==void 0?{sql:s(e.fieldAlias),params:[]}:n(e,C)?e._.isWith?{sql:s(e._.alias),params:[]}:this.buildQueryFromSourceParams([new A(`(`),e._.sql,new A(`) `),new we(e._.alias)],a):se(e)?e.schema?{sql:s(e.schema)+`.`+s(e.enumName),params:[]}:{sql:s(e.enumName),params:[]}:Se(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],a):this.buildQueryFromSourceParams([new A(`(`),e.getSQL(),new A(`)`)],a):u?{sql:this.mapInlineParam(e,a),params:[]}:{sql:c(d.value++,e),params:[e],typings:[`none`]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(e){return e===void 0?this:new t.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},we=class{constructor(e){this.value=e}static[e]=`Name`;brand;getSQL(){return new j([this])}};function Te(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}const Ee={mapFromDriverValue:e=>e},De={mapToDriverValue:e=>e},Oe={...Ee,...De};var M=class{constructor(e,t=De){this.value=e,this.encoder=t}static[e]=`Param`;brand;getSQL(){return new j([this])}};function N(e,...t){let n=[];(t.length>0||e.length>0&&e[0]!==``)&&n.push(new A(e[0]));for(let[r,i]of t.entries())n.push(i,new A(e[r+1]));return new j(n)}(e=>{function t(){return new j([])}e.empty=t;function n(e){return new j(e)}e.fromList=n;function r(e){return new j([new A(e)])}e.raw=r;function i(e,t){let n=[];for(let[r,i]of e.entries())r>0&&t!==void 0&&n.push(t),n.push(i);return new j(n)}e.join=i;function a(e){return new we(e)}e.identifier=a;function o(e){return new P(e)}e.placeholder=o;function s(e,t){return new M(e,t)}e.param=s})(N||={}),(t=>{class n{constructor(e,t){this.sql=e,this.fieldAlias=t}static[e]=`SQL.Aliased`;isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}t.Aliased=n})(j||={});var P=class{constructor(e){this.name=e}static[e]=`Placeholder`;getSQL(){return new j([this])}};function ke(e,t){return e.map(e=>{if(n(e,P)){if(!(e.name in t))throw Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(n(e,M)&&n(e.value,P)){if(!(e.value.name in t))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}const Ae=Symbol.for(`drizzle:IsDrizzleView`);var F=class{static[e]=`View`;[T];[Ae]=!0;get[s](){return this[T].name}get[E](){return this[T].schema}get[_e](){return this[T].isAlias}get[he](){return this[T].originalName}get[D](){return this[T].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[T]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new j([this])}};function je(e){return typeof e==`object`&&!!e&&Ae in e}function Me(e){return e[T].name}r.prototype.getSQL=function(){return new j([this])},O.prototype.getSQL=function(){return new j([this])},C.prototype.getSQL=function(){return new j([this])};var Ne=class{constructor(e){this.table=e}static[e]=`ColumnAliasProxyHandler`;get(e,t){return t===`table`?this.table:e[t]}},Pe=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[e]=`TableAliasProxyHandler`;get(e,t){if(t===O.Symbol.IsAlias)return!0;if(t===O.Symbol.Name||this.replaceOriginalName&&t===O.Symbol.OriginalName)return this.alias;if(t===T)return{...e[T],name:this.alias,isAlias:!0};if(t===O.Symbol.Columns){let t=e[O.Symbol.Columns];if(!t)return t;let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new Ne(new Proxy(e,this)))}),n}let i=e[t];return n(i,r)?new Proxy(i,new Ne(new Proxy(e,this))):i}},Fe=class{constructor(e){this.alias=e}static[e]=`RelationTableAliasProxyHandler`;get(e,t){return t===`sourceTable`?I(e.sourceTable,this.alias):e[t]}};function I(e,t){return new Proxy(e,new Pe(t,!1))}function Ie(e,t){return new Proxy(e,new Fe(t))}function L(e,t){return new Proxy(e,new Ne(new Proxy(e.table,new Pe(t,!1))))}function Le(e,t){return new j.Aliased(Re(e.sql,t),e.fieldAlias)}function Re(e,t){return N.join(e.queryChunks.map(e=>n(e,r)?L(e,t):n(e,j)?Re(e,t):n(e,j.Aliased)?Le(e,t):e))}var ze=class extends Error{static[e]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}};Error;var R=class{static[e]=`QueryPromise`;[Symbol.toStringTag]=`QueryPromise`;catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function z(e,t){return Te(t)&&!Se(e)&&!n(e,M)&&!n(e,P)&&!n(e,r)&&!n(e,O)&&!n(e,F)?new M(e,t):e}const B=(e,t)=>N`${e} = ${z(t,e)}`,Be=(e,t)=>N`${e} <> ${z(t,e)}`;function V(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new j(t):new j([new A(`(`),N.join(t,new A(` and `)),new A(`)`)])}function Ve(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new j(t):new j([new A(`(`),N.join(t,new A(` or `)),new A(`)`)])}function He(e){return N`not ${e}`}const Ue=(e,t)=>N`${e} > ${z(t,e)}`,We=(e,t)=>N`${e} >= ${z(t,e)}`,Ge=(e,t)=>N`${e} < ${z(t,e)}`,Ke=(e,t)=>N`${e} <= ${z(t,e)}`;function qe(e,t){return Array.isArray(t)?t.length===0?N`false`:N`${e} in ${t.map(t=>z(t,e))}`:N`${e} in ${z(t,e)}`}function Je(e,t){return Array.isArray(t)?t.length===0?N`true`:N`${e} not in ${t.map(t=>z(t,e))}`:N`${e} not in ${z(t,e)}`}function Ye(e){return N`${e} is null`}function Xe(e){return N`${e} is not null`}function Ze(e){return N`exists ${e}`}function Qe(e){return N`not exists ${e}`}function $e(e,t,n){return N`${e} between ${z(t,e)} and ${z(n,e)}`}function et(e,t,n){return N`${e} not between ${z(t,e)} and ${z(n,e)}`}function tt(e,t){return N`${e} like ${t}`}function nt(e,t){return N`${e} not like ${t}`}function rt(e,t){return N`${e} ilike ${t}`}function it(e,t){return N`${e} not ilike ${t}`}function at(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);return N`${e} @> ${N`${z(t,e)}`}`}return N`${e} @> ${z(t,e)}`}function ot(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);return N`${e} <@ ${N`${z(t,e)}`}`}return N`${e} <@ ${z(t,e)}`}function st(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);return N`${e} && ${N`${z(t,e)}`}`}return N`${e} && ${z(t,e)}`}function ct(e){return N`${e} asc`}function lt(e){return N`${e} desc`}function ut(e,t){for(let t of Object.values(e))for(let[e,r]of Object.entries(t.relations))n(r,H)&&(r.sourceTable=t.table,r.fieldName=e);for(let[r,i]of Object.entries(e))for(let[a,o]of Object.entries(i.relations)){if(!n(o,H))continue;let s,{targetTableName:c,alias:l,sourceColumns:u,targetColumns:d,throughTable:f,sourceTable:p,through:m,targetTable:h,where:g,sourceColumnTableNames:_,targetColumnTableNames:v}=o,y=`relations -> ${i.name}: { ${a}: r.${n(o,pt)?`one`:`many`}.${c}(...) }`;if(a in i.table[D])throw Error(`${y}: relation name collides with column "${a}" of table "${i.name}"`);if(typeof l==`string`&&!l)throw Error(`${y}: "alias" cannot be an empty string - omit it if you don't need it`);if(u?.length===0)throw Error(`${y}: "from" cannot be empty`);if(d?.length===0)throw Error(`${y}: "to" cannot be empty`);if(u&&d){if(u.length!==d.length&&!f)throw Error(`${y}: "from" and "to" fields without "through" must have the same length`);for(let e of _)if(e!==r)throw Error(`${y}: all "from" columns must belong to table "${r}", found column of table "${e}"`);for(let e of v)if(e!==c)throw Error(`${y}: all "to" columns must belong to table "${h}", found column of table "${e}"`);if(m){if(m.source.length!==u.length||m.target.length!==d.length)throw Error(`${y}: ".through(column)" must be used either on all columns in "from" and "to" or not defined on any of them`);for(let e of m.source)if(t[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`);for(let e of m.target)if(t[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`)}continue}if(u||d)throw Error(`${y}: relation must have either both "from" and "to" defined, or none of them`);let b=e[c];if(!b)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relations of table "${c}" were found"`);if(l){let e=Object.values(b.relations).filter(e=>n(e,H)&&e.alias===l&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations with alias "${l}" found in table "${c}": ${e.map(e=>`"${e.fieldName}"`).join(`, `)}`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and there is no reverse relation of table "${c}" with alias "${l}"`)}else{let e=Object.values(b.relations).filter(e=>n(e,H)&&e.targetTable===p&&!e.alias&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations between "${c}" and "${r}" were found.
|
|
2
|
+
Hint: you can specify "alias" on both sides of the relation with the same value`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relation of table "${c}" with target table "${r}" was found`)}if(!s.sourceColumns||!s.targetColumns)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and reverse relation "${c}.${s.fieldName}" does not have "from"/"to" defined`);o.sourceColumns=s.targetColumns,o.targetColumns=s.sourceColumns,o.through=s.through?{source:s.through.target,target:s.through.source}:void 0,o.throughTable=s.throughTable,o.isReversed=!g,o.where=g??s.where}return e}function dt(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]={table:i,name:r,relations:t[r]??{}};return ut(n,e)}function ft(e,t){let n={};for(let[r,i]of Object.entries(t))!i||!e[r]||(n[r]={table:e[r],name:r,relations:i});return ut(n,e)}var H=class{constructor(e,t){this.targetTableName=t,this.targetTable=e}static[e]=`RelationV2`;fieldName;sourceColumns;targetColumns;alias;where;sourceTable;targetTable;through;throughTable;isReversed;sourceColumnTableNames=[];targetColumnTableNames=[]},pt=class extends H{static[e]=`OneV2`;relationType=`one`;optional;constructor(e,t,n,r){super(t,n),this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)}),this.optional=r?.optional??!0}},mt=class extends H{constructor(e,t,n,r){super(t,n),this.config=r,this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)})}static[e]=`ManyV2`;relationType=`many`},ht=class{static[e]=`AggregatedField`;table;onTable(e){return this.table=e,this}},gt=class extends ht{static[e]=`AggregatedFieldCount`;query;getSQL(){if(!this.query){if(!this.table)throw Error(`Table must be set before building aggregate field`);this.query=N`select count(*) as ${N.identifier(`r`)} from ${G(this.table)}`.mapWith(Number)}return this.query}};const U={and:V,between:$e,eq:B,exists:Ze,gt:Ue,gte:We,ilike:rt,inArray:qe,arrayContains:at,arrayContained:ot,arrayOverlaps:st,isNull:Ye,isNotNull:Xe,like:tt,lt:Ge,lte:Ke,ne:Be,not:He,notBetween:et,notExists:Qe,notLike:nt,notIlike:it,notInArray:Je,or:Ve,sql:N},_t={sql:N,asc:ct,desc:lt};function vt(){return _t}function yt(e,t,i=e=>e,a=!1,o=!1,s){for(let c of t){if(c.selection){let t=`${s?`${s}.`:``}${c.key}`;if(e[c.key]===null)continue;if(a&&(e[c.key]=JSON.parse(e[c.key])),o&&typeof e[c.key]==`string`&&(e[c.key]=JSON.parse(e[c.key])),c.isArray){for(let n of e[c.key])yt(n,c.selection,i,!1,o,t);continue}yt(e[c.key],c.selection,i,!1,o,t);continue}let t=c.field,l=i(e[c.key]);if(l===null)continue;let u;u=n(t,r)?t:n(t,j)?t.decoder:n(t,j.Aliased)?t.sql.decoder:t.getSQL().decoder,e[c.key]=`mapFromJsonValue`in u?u.mapFromJsonValue(l):u.mapFromDriverValue(l)}return e}var bt=class{static[e]=`RelationsBuilderTable`;_;constructor(e,t){this._={name:t,table:e}}},xt=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n){this._={tableName:t,column:e,key:n}}through(e){return new St(this._.column,this._.tableName,this._.key,e)}},St=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n,r){this._={tableName:t,column:e,through:r,key:n}}},Ct=class{static[e]=`RelationsHelperStatic`;_;constructor(e){this._={tables:e};let t={},n={};for(let[r,i]of Object.entries(e))t[r]=t=>new pt(e,i,r,t),n[r]=t=>new mt(e,i,r,t);this.one=t,this.many=n}one;many;aggs={count(){return new gt}}};function wt(e){let t=new Ct(e),n=Object.entries(e).reduce((e,[t,n])=>{let r=new bt(n,t),i=Object.entries(n[D]).reduce((e,[n,r])=>(e[n]=new xt(r,t,n),e),{});return e[t]=Object.assign(r,i),e},{});return Object.assign(t,n)}function Tt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>n(t,O)||n(t,F)))}function Et(e,t){let n=Tt(e);return dt(n,t?t(wt(n)):{})}function Dt(e,t){let n=Tt(e);return ft(n,t?t(wt(n)):Object.fromEntries(Object.keys(n).map(e=>[e,{}])))}function Ot(e,t){let i=e[D][t];return i?n(i,r)?i:n(i,j.Aliased)?N`${e}.${N.identifier(i.fieldAlias)}`:N`${e}.${N.identifier(t)}`:N`${e}.${N.identifier(t)}`}function kt(e,t){if(typeof t!=`object`||n(t,P))return B(e,t);let r=Object.entries(t);if(!r.length)return;let i=[];for(let[t,n]of r)if(n!==void 0)switch(t){case`NOT`:{let t=kt(e,n);if(!t)continue;i.push(He(t));continue}case`OR`:if(!n.length)continue;i.push(Ve(...n.map(t=>kt(e,t))));continue;case`AND`:if(!n.length)continue;i.push(V(...n.map(t=>kt(e,t))));continue;case`isNotNull`:case`isNull`:if(!n)continue;i.push(U[t](e));continue;case`in`:i.push(U.inArray(e,n));continue;case`notIn`:i.push(U.notInArray(e,n));continue;default:i.push(U[t](e,n));continue}if(i.length)return V(...i)}function W(e,t,n={},r={},i,a=0){let o=Object.entries(t);if(!o.length)return;let s=[];for(let[t,c]of o)if(c!==void 0)switch(t){case`RAW`:{let t=typeof c==`function`?c(e,U):c.getSQL();s.push(t);continue}case`OR`:if(!c?.length)continue;s.push(Ve(...c.map(t=>W(e,t,n,r,i,a))));continue;case`AND`:if(!c?.length)continue;s.push(V(...c.map(t=>W(e,t,n,r,i,a))));continue;case`NOT`:{if(c===void 0)continue;let t=W(e,c,n,r,i,a);if(!t)continue;s.push(He(t));continue}default:{if(e[D][t]){let n=kt(Ot(e,t),c);n&&s.push(n);continue}let o=n[t];if(!o)throw new ze({message:`Unknown relational filter field: "${t}"`});let l=I(o.targetTable,`f${a}`),u=o.throughTable?I(o.throughTable,`ft${a}`):void 0,d=r[o.targetTableName],{filter:f,joinCondition:p}=Mt(i,o,e,l,u),m=V(f,typeof c==`boolean`?void 0:W(l,c,d.relations,r,i,a+1)),h=u?N`(select * from ${G(l)} inner join ${G(u)} on ${p}${N` where ${m}`.if(m)} limit 1)`:N`(select * from ${G(l)}${N` where ${m}`.if(m)} limit 1)`;m&&s.push((c?Ze:Qe)(h))}}return V(...s)}function At(e,t){if(typeof t==`function`){let i=t(e,_t);return n(i,j)?i:Array.isArray(i)?i.length?N.join(i.map(e=>n(e,j)?e:ct(e)),N`, `):void 0:n(i,r)?ct(i):void 0}let i=Object.entries(t).filter(([e,t])=>t);if(i.length)return N.join(i.map(([t,n])=>(n===`asc`?ct:lt)(Ot(e,t))),N`, `)}function jt(e,t){let n=[],r=[];for(let[i,a]of Object.entries(t)){if(!a)continue;let t=typeof a==`function`?a(e,{sql:U.sql}):a,o=N`(${t.getSQL()}) as ${N.identifier(i)}`;o.decoder=t.getSQL().decoder,n.push(o),r.push({key:i,field:o})}return{sql:n.length?N.join(n,N`, `):void 0,selection:r}}function Mt(e,t,i,a,o){if(t.through){let s=t.sourceColumns.map((a,s)=>{let c=t.through.source[s];return B(N`${i}.${N.identifier(e.getColumnCasing(a))}`,N`${o}.${N.identifier(n(c._.column,r)?e.getColumnCasing(c._.column):c._.key)}`)}),c=t.targetColumns.map((i,s)=>{let c=t.through.target[s];return B(N`${o}.${N.identifier(n(c._.column,r)?e.getColumnCasing(c._.column):c._.key)}`,N`${a}.${N.identifier(e.getColumnCasing(i))}`)});return{filter:V(t.where?W(t.isReversed?i:a,t.where):void 0,...s),joinCondition:V(...c)}}return{filter:V(...t.sourceColumns.map((n,r)=>{let o=t.targetColumns[r];return B(N`${i}.${N.identifier(e.getColumnCasing(n))}`,N`${a}.${N.identifier(e.getColumnCasing(o))}`)}),t.where?W(t.isReversed?i:a,t.where):void 0)}}function G(e){return N`${e[_e]?N`${N`${N.identifier(e[E]??``)}.`.if(e[E])}${N.identifier(e[he])} as ${e}`:e}`}function Nt(e){return N`count(${e||N.raw(`*`)})`.mapWith(Number)}function Pt(e){return N`count(distinct ${e})`.mapWith(Number)}function Ft(e){return N`avg(${e})`.mapWith(String)}function It(e){return N`avg(distinct ${e})`.mapWith(String)}function Lt(e){return N`sum(${e})`.mapWith(String)}function Rt(e){return N`sum(distinct ${e})`.mapWith(String)}function zt(e){return JSON.stringify(e)}function Bt(e,t){return Array.isArray(t)?N`${e} <-> ${zt(t)}`:N`${e} <-> ${t}`}function Vt(e,t){return Array.isArray(t)?N`${e} <+> ${zt(t)}`:N`${e} <+> ${t}`}function Ht(e,t){return Array.isArray(t)?N`${e} <#> ${zt(t)}`:N`${e} <#> ${t}`}function Ut(e,t){return Array.isArray(t)?N`${e} <=> ${zt(t)}`:N`${e} <=> ${t}`}function Wt(e,t){return Array.isArray(t)?N`${e} <~> ${zt(t)}`:N`${e} <~> ${t}`}function Gt(e,t){return Array.isArray(t)?N`${e} <%> ${zt(t)}`:N`${e} <%> ${t}`}function K(e,t){return Object.entries(e).reduce((e,[i,a])=>{if(typeof i!=`string`)return e;let o=t?[...t,i]:[i];return n(a,r)||n(a,j)||n(a,j.Aliased)?e.push({path:o,field:a}):n(a,O)?e.push(...K(a[O.Symbol.Columns],o)):e.push(...K(a,o)),e},[])}function Kt(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function qt(e,t){let i=Object.entries(t).filter(([,e])=>e!==void 0).map(([t,i])=>n(i,j)||n(i,r)?[t,i]:[t,new M(i,e[O.Symbol.Columns][t])]);if(i.length===0)throw Error(`No values to set`);return Object.fromEntries(i)}function Jt(e,t){for(let n of t)for(let t of Object.getOwnPropertyNames(n.prototype))t!==`constructor`&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function Yt(e){return e[O.Symbol.Columns]}function Xt(e){return e[T].selectedFields}function q(e){return n(e,C)?e._.alias:n(e,F)?e[T].name:n(e,j)?void 0:e[O.Symbol.IsAlias]?e[O.Symbol.Name]:e[O.Symbol.BaseName]}function J(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}function Zt(e){if(typeof e!=`object`||!e||e.constructor.name!==`Object`)return!1;if(`logger`in e){let t=typeof e.logger;return!(t!==`boolean`&&(t!==`object`||typeof e.logger.logQuery!=`function`)&&t!==`undefined`)}if(`schema`in e){let t=typeof e.schema;return!(t!==`object`&&t!==`undefined`)}if(`relations`in e){let t=typeof e.relations;return!(t!==`object`&&t!==`undefined`)}if(`casing`in e){let t=typeof e.casing;return!(t!==`string`&&t!==`undefined`)}if(`mode`in e)return!(e.mode!==`default`||e.mode!==`planetscale`||e.mode!==void 0);if(`connection`in e){let t=typeof e.connection;return!(t!==`string`&&t!==`object`&&t!==`undefined`)}if(`client`in e){let t=typeof e.client;return!(t!==`object`&&t!==`function`&&t!==`undefined`)}return Object.keys(e).length===0}const Qt=typeof TextDecoder>`u`?null:new TextDecoder;function $t(e,t){return new Proxy(e,new Pe(t,!1))}var en=class{constructor(e,t){this.name=e,this.value=t}static[e]=`PgCheckBuilder`;brand;build(e){return new tn(e,this)}},tn=class{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[e]=`PgCheck`;name;value};function nn(e,t){return new en(e,t)}var rn=class extends x{static[e]=`PgIntColumnBaseBuilder`;generatedAlwaysAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`always`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`always`};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`byDefault`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`byDefault`};return this.config.hasDefault=!0,this.config.notNull=!0,this}},an=class extends rn{static[e]=`PgBigInt53Builder`;constructor(e){super(e,`number int53`,`PgBigInt53`)}build(e){return new on(e,this.config)}},on=class extends S{static[e]=`PgBigInt53`;getSQLType(){return`bigint`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},sn=class extends rn{static[e]=`PgBigInt64Builder`;constructor(e){super(e,`bigint int64`,`PgBigInt64`)}build(e){return new cn(e,this.config)}},cn=class extends S{static[e]=`PgBigInt64`;getSQLType(){return`bigint`}mapFromDriverValue(e){return BigInt(e)}};function ln(e,t){let{name:n,config:r}=J(e,t);return r.mode===`number`?new an(n):new sn(n)}var un=class extends x{static[e]=`PgBigSerial53Builder`;constructor(e){super(e,`number int53`,`PgBigSerial53`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new dn(e,this.config)}},dn=class extends S{static[e]=`PgBigSerial53`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},fn=class extends x{static[e]=`PgBigSerial64Builder`;constructor(e){super(e,`bigint int64`,`PgBigSerial64`),this.config.hasDefault=!0}build(e){return new pn(e,this.config)}},pn=class extends S{static[e]=`PgBigSerial64`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return BigInt(e)}};function mn(e,t){let{name:n,config:r}=J(e,t);return r.mode===`number`?new un(n):new fn(n)}var hn=class extends x{static[e]=`PgBooleanBuilder`;constructor(e){super(e,`boolean`,`PgBoolean`)}build(e){return new gn(e,this.config)}},gn=class extends S{static[e]=`PgBoolean`;getSQLType(){return`boolean`}};function _n(e){return new hn(e??``)}var vn=class extends x{static[e]=`PgByteaBuilder`;constructor(e){super(e,`object buffer`,`PgBytea`)}build(e){return new yn(e,this.config)}},yn=class extends S{static[e]=`PgBytea`;mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;if(typeof e==`string`){let t=e.slice(2,e.length);return Buffer.from(t,`hex`)}return Buffer.from(e)}getSQLType(){return`bytea`}};function bn(e){return new vn(e??``)}var xn=class extends x{static[e]=`PgCharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgChar`),this.config.length=t.length??1,this.config.setLength=t.length!==void 0,this.config.enumValues=t.enum,this.config.isLengthExact=!0}build(e){return new Sn(e,this.config)}},Sn=class extends S{static[e]=`PgChar`;enumValues=this.config.enumValues;getSQLType(){return this.config.setLength?`char(${this.length})`:`char`}};function Cn(e,t={}){let{name:n,config:r}=J(e,t);return new xn(n,r)}var wn=class extends x{static[e]=`PgCidrBuilder`;constructor(e){super(e,`string cidr`,`PgCidr`)}build(e){return new Tn(e,this.config)}},Tn=class extends S{static[e]=`PgCidr`;getSQLType(){return`cidr`}};function En(e){return new wn(e??``)}var Dn=class extends x{static[e]=`PgCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`PgCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new On(e,this.config)}},On=class extends S{static[e]=`PgCustomColumn`;sqlName;mapTo;mapFrom;mapJson;forJsonSelect;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver,this.mapJson=t.customTypeParams.fromJson,this.forJsonSelect=t.customTypeParams.forJsonSelect}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==`function`?this.mapFrom(e):e}mapFromJsonValue(e){return typeof this.mapJson==`function`?this.mapJson(e):this.mapFromDriverValue(e)}jsonSelectIdentifier(e,t,n){if(typeof this.forJsonSelect==`function`)return this.forJsonSelect(e,t,n);let r=this.getSQLType().toLowerCase(),i=r.indexOf(`(`);switch(i+1?r.slice(0,i):r){case`bytea`:case`geometry`:case`timestamp`:case`numeric`:case`bigint`:{let r=`[]`.repeat(n??0);return t`${e}::text${t.raw(r).if(n)}`}default:return e}}mapToDriverValue(e){return typeof this.mapTo==`function`?this.mapTo(e):e}};function kn(e){return(t,n)=>{let{name:r,config:i}=J(t,n);return new Dn(r,i,e)}}var An=class extends x{static[e]=`PgDateColumnBaseBuilder`;defaultNow(){return this.default(N`now()`)}},jn=class extends An{static[e]=`PgDateBuilder`;constructor(e){super(e,`object date`,`PgDate`)}build(e){return new Mn(e,this.config)}},Mn=class extends S{static[e]=`PgDate`;getSQLType(){return`date`}mapFromDriverValue(e){return new Date(e)}mapToDriverValue(e){return e.toISOString()}},Nn=class extends An{static[e]=`PgDateStringBuilder`;constructor(e){super(e,`string date`,`PgDateString`)}build(e){return new Pn(e,this.config)}},Pn=class extends S{static[e]=`PgDateString`;getSQLType(){return`date`}};function Fn(e,t){let{name:n,config:r}=J(e,t);return r?.mode===`date`?new jn(n):new Nn(n)}var In=class extends x{static[e]=`PgDoublePrecisionBuilder`;constructor(e){super(e,`number double`,`PgDoublePrecision`)}build(e){return new Ln(e,this.config)}},Ln=class extends S{static[e]=`PgDoublePrecision`;getSQLType(){return`double precision`}mapFromDriverValue(e){return typeof e==`string`?Number.parseFloat(e):e}};function Rn(e){return new In(e??``)}var zn=class extends x{static[e]=`PgInetBuilder`;constructor(e){super(e,`string inet`,`PgInet`)}build(e){return new Bn(e,this.config)}},Bn=class extends S{static[e]=`PgInet`;getSQLType(){return`inet`}};function Vn(e){return new zn(e??``)}var Hn=class extends rn{static[e]=`PgIntegerBuilder`;constructor(e){super(e,`number int32`,`PgInteger`)}build(e){return new Un(e,this.config)}},Un=class extends S{static[e]=`PgInteger`;getSQLType(){return`integer`}mapFromDriverValue(e){return typeof e==`string`?Number.parseInt(e):e}};function Wn(e){return new Hn(e??``)}var Gn=class extends x{static[e]=`PgIntervalBuilder`;constructor(e,t){super(e,`string interval`,`PgInterval`),this.config.intervalConfig=t}build(e){return new Kn(e,this.config)}},Kn=class extends S{static[e]=`PgInterval`;fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:``}${this.precision?`(${this.precision})`:``}`}};function qn(e,t={}){let{name:n,config:r}=J(e,t);return new Gn(n,r)}var Jn=class extends x{static[e]=`PgJsonBuilder`;constructor(e){super(e,`object json`,`PgJson`)}build(e){return new Yn(e,this.config)}},Yn=class extends S{static[e]=`PgJson`;constructor(e,t){super(e,t)}getSQLType(){return`json`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function Xn(e){return new Jn(e??``)}var Zn=class extends x{static[e]=`PgJsonbBuilder`;constructor(e){super(e,`object json`,`PgJsonb`)}build(e){return new Qn(e,this.config)}},Qn=class extends S{static[e]=`PgJsonb`;constructor(e,t){super(e,t)}getSQLType(){return`jsonb`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function $n(e){return new Zn(e??``)}var er=class extends x{static[e]=`PgLineBuilder`;constructor(e){super(e,`array line`,`PgLine`)}build(e){return new tr(e,this.config)}},tr=class extends S{static[e]=`PgLine`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},nr=class extends x{static[e]=`PgLineABCBuilder`;constructor(e){super(e,`object line`,`PgLineABC`)}build(e){return new rr(e,this.config)}},rr=class extends S{static[e]=`PgLineABC`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function ir(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new er(n):new nr(n)}var ar=class extends x{static[e]=`PgMacaddrBuilder`;constructor(e){super(e,`string macaddr`,`PgMacaddr`)}build(e){return new or(e,this.config)}},or=class extends S{static[e]=`PgMacaddr`;getSQLType(){return`macaddr`}};function sr(e){return new ar(e??``)}var cr=class extends x{static[e]=`PgMacaddr8Builder`;constructor(e){super(e,`string macaddr8`,`PgMacaddr8`)}build(e){return new lr(e,this.config)}},lr=class extends S{static[e]=`PgMacaddr8`;getSQLType(){return`macaddr8`}};function ur(e){return new cr(e??``)}var dr=class extends x{static[e]=`PgNumericBuilder`;constructor(e,t,n){super(e,`string numeric`,`PgNumeric`),this.config.precision=t,this.config.scale=n}build(e){return new fr(e,this.config)}},fr=class extends S{static[e]=`PgNumeric`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`string`?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},pr=class extends x{static[e]=`PgNumericNumberBuilder`;constructor(e,t,n){super(e,`number`,`PgNumericNumber`),this.config.precision=t,this.config.scale=n}build(e){return new mr(e,this.config)}},mr=class extends S{static[e]=`PgNumericNumber`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},hr=class extends x{static[e]=`PgNumericBigIntBuilder`;constructor(e,t,n){super(e,`bigint int64`,`PgNumericBigInt`),this.config.precision=t,this.config.scale=n}build(e){return new gr(e,this.config)}},gr=class extends S{static[e]=`PgNumericBigInt`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}};function _r(e,t){let{name:n,config:r}=J(e,t),i=r?.mode;return i===`number`?new pr(n,r?.precision,r?.scale):i===`bigint`?new hr(n,r?.precision,r?.scale):new dr(n,r?.precision,r?.scale)}const vr=_r;var yr=class extends x{static[e]=`PgPointTupleBuilder`;constructor(e){super(e,`array point`,`PgPointTuple`)}build(e){return new br(e,this.config)}},br=class extends S{static[e]=`PgPointTuple`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},xr=class extends x{static[e]=`PgPointObjectBuilder`;constructor(e){super(e,`object point`,`PgPointObject`)}build(e){return new Sr(e,this.config)}},Sr=class extends S{static[e]=`PgPointObject`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function Cr(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new yr(n):new xr(n)}function wr(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function Tr(e,t){let n=new ArrayBuffer(8),r=new DataView(n);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function Er(e){let t=wr(e),n=0,r=t[n];n+=1;let i=new DataView(t.buffer),a=i.getUint32(n,r===1);if(n+=4,a&536870912&&(i.getUint32(n,r===1),n+=4),(a&65535)==1){let e=Tr(t,n);n+=8;let r=Tr(t,n);return n+=8,[e,r]}throw Error(`Unsupported geometry type`)}var Dr=class extends x{static[e]=`PgGeometryBuilder`;constructor(e){super(e,`array geometry`,`PgGeometry`)}build(e){return new Or(e,this.config)}},Or=class extends S{static[e]=`PgGeometry`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){return typeof e==`string`?Er(e):e}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},kr=class extends x{static[e]=`PgGeometryObjectBuilder`;constructor(e){super(e,`object geometry`,`PgGeometryObject`)}build(e){return new Ar(e,this.config)}},Ar=class extends S{static[e]=`PgGeometryObject`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){let t=Er(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function jr(e,t){let{name:n,config:r}=J(e,t);return!r?.mode||r.mode===`tuple`?new Dr(n):new kr(n)}var Mr=class extends x{static[e]=`PgRealBuilder`;constructor(e,t){super(e,`number float`,`PgReal`),this.config.length=t}build(e){return new Nr(e,this.config)}},Nr=class extends S{static[e]=`PgReal`;constructor(e,t){super(e,t)}getSQLType(){return`real`}mapFromDriverValue=e=>typeof e==`string`?Number.parseFloat(e):e};function Pr(e){return new Mr(e??``)}var Fr=class extends x{static[e]=`PgSerialBuilder`;constructor(e){super(e,`number int32`,`PgSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Ir(e,this.config)}},Ir=class extends S{static[e]=`PgSerial`;getSQLType(){return`serial`}};function Lr(e){return new Fr(e??``)}var Rr=class extends rn{static[e]=`PgSmallIntBuilder`;constructor(e){super(e,`number int16`,`PgSmallInt`)}build(e){return new zr(e,this.config)}},zr=class extends S{static[e]=`PgSmallInt`;getSQLType(){return`smallint`}mapFromDriverValue=e=>typeof e==`string`?Number(e):e};function Br(e){return new Rr(e??``)}var Vr=class extends x{static[e]=`PgSmallSerialBuilder`;constructor(e){super(e,`number int16`,`PgSmallSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Hr(e,this.config)}},Hr=class extends S{static[e]=`PgSmallSerial`;getSQLType(){return`smallserial`}};function Ur(e){return new Vr(e??``)}var Wr=class extends x{static[e]=`PgTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgText`),this.config.enumValues=t.enum}build(e){return new Gr(e,this.config,this.config.enumValues)}},Gr=class extends S{static[e]=`PgText`;enumValues;constructor(e,t,n){super(e,t),this.enumValues=n}getSQLType(){return`text`}};function Kr(e,t={}){let{name:n,config:r}=J(e,t);return new Wr(n,r)}var qr=class extends An{constructor(e,t,n){super(e,`string time`,`PgTime`),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[e]=`PgTimeBuilder`;build(e){return new Jr(e,this.config)}},Jr=class extends S{static[e]=`PgTime`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function Yr(e,t={}){let{name:n,config:r}=J(e,t);return new qr(n,r.withTimezone??!1,r.precision)}var Xr=class extends An{static[e]=`PgTimestampBuilder`;constructor(e,t,n){super(e,`object date`,`PgTimestamp`),this.config.withTimezone=t,this.config.precision=n}build(e){return new Zr(e,this.config)}},Zr=class extends S{static[e]=`PgTimestamp`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:` (${this.precision})`}${this.withTimezone?` with time zone`:``}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+`+0000`);mapToDriverValue=e=>e.toISOString()},Qr=class extends An{static[e]=`PgTimestampStringBuilder`;constructor(e,t,n){super(e,`string timestamp`,`PgTimestampString`),this.config.withTimezone=t,this.config.precision=n}build(e){return new $r(e,this.config)}},$r=class extends S{static[e]=`PgTimestampString`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function ei(e,t={}){let{name:n,config:r}=J(e,t);return r?.mode===`string`?new Qr(n,r.withTimezone??!1,r.precision):new Xr(n,r?.withTimezone??!1,r?.precision)}var ti=class extends x{static[e]=`PgUUIDBuilder`;constructor(e){super(e,`string uuid`,`PgUUID`)}defaultRandom(){return this.default(N`gen_random_uuid()`)}build(e){return new ni(e,this.config)}},ni=class extends S{static[e]=`PgUUID`;getSQLType(){return`uuid`}};function ri(e){return new ti(e??``)}var ii=class extends x{static[e]=`PgVarcharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgVarchar`),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new ai(e,this.config)}},ai=class extends S{static[e]=`PgVarchar`;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?`varchar`:`varchar(${this.length})`}};function oi(e,t={}){let{name:n,config:r}=J(e,t);return new ii(n,r)}var si=class extends x{static[e]=`PgBinaryVectorBuilder`;constructor(e,t){super(e,`string binary`,`PgBinaryVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new ci(e,this.config)}},ci=class extends S{static[e]=`PgBinaryVector`;getSQLType(){return`bit(${this.length})`}};function li(e,t){let{name:n,config:r}=J(e,t);return new si(n,r)}var ui=class extends x{static[e]=`PgHalfVectorBuilder`;constructor(e,t){super(e,`array halfvector`,`PgHalfVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new di(e,this.config)}},di=class extends S{static[e]=`PgHalfVector`;getSQLType(){return`halfvec(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function fi(e,t){let{name:n,config:r}=J(e,t);return new ui(n,r)}var pi=class extends x{static[e]=`PgSparseVectorBuilder`;constructor(e,t){super(e,`string sparsevec`,`PgSparseVector`),this.config.dimensions=t.dimensions}build(e){return new mi(e,this.config)}},mi=class extends S{static[e]=`PgSparseVector`;dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function hi(e,t){let{name:n,config:r}=J(e,t);return new pi(n,r)}var gi=class extends x{static[e]=`PgVectorBuilder`;constructor(e,t){super(e,`array vector`,`PgVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new _i(e,this.config)}},_i=class extends S{static[e]=`PgVector`;getSQLType(){return`vector(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function vi(e,t){let{name:n,config:r}=J(e,t);return new gi(n,r)}var Y=class t{static[e]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(e,i){if(i===`_`)return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(i===T)return{...e[T],selectedFields:new Proxy(e[T].selectedFields,this)};if(typeof i==`symbol`)return e[i];let a=(n(e,C)?e._.selectedFields:n(e,F)?e[T].selectedFields:e)[i];if(n(a,j.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!a.isSelectionField)return a.sql;let e=a.clone();return e.isSelectionField=!0,e}if(n(a,j)){if(this.config.sqlBehavior===`sql`)return a;throw Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return n(a,r)?this.config.alias?new Proxy(a,new Ne(new Proxy(a.table,new Pe(this.config.alias,this.config.replaceOriginalName??!1)))):a:typeof a!=`object`||!a?a:new Proxy(a,new t(this.config))}};function yi(){return{bigint:ln,bigserial:mn,boolean:_n,char:Cn,cidr:En,customType:kn,date:Fn,doublePrecision:Rn,inet:Vn,integer:Wn,interval:qn,json:Xn,jsonb:$n,line:ir,macaddr:sr,macaddr8:ur,numeric:_r,point:Cr,geometry:jr,real:Pr,serial:Lr,smallint:Br,smallserial:Ur,text:Kr,time:Yr,timestamp:ei,uuid:ri,varchar:oi,bit:li,halfvec:fi,sparsevec:hi,vector:vi}}const bi=Symbol.for(`drizzle:PgInlineForeignKeys`),xi=Symbol.for(`drizzle:EnableRLS`);var X=class extends O{static[e]=`PgTable`;static Symbol=Object.assign({},O.Symbol,{InlineForeignKeys:bi,EnableRLS:xi});[bi]=[];[xi]=!1;[O.Symbol.ExtraConfigBuilder]=void 0;[O.Symbol.ExtraConfigColumns]={}};function Si(e,t,n,r,i=e){let a=new X(e,r,i),o=typeof t==`function`?t(yi()):t,s=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;n.setName(e);let r=n.build(a);return a[bi].push(...n.buildForeignKeys(r,a)),[e,r]})),c=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;return n.setName(e),[e,n.buildExtraConfigColumn(a)]})),l=Object.assign(a,s);return l[O.Symbol.Columns]=s,l[O.Symbol.ExtraConfigColumns]=c,n&&(l[X.Symbol.ExtraConfigBuilder]=n),Object.assign(l,{enableRLS:()=>(l[X.Symbol.EnableRLS]=!0,l)})}const Z=(e,t,n)=>Si(e,t,n,void 0);function Ci(e){return(t,n,r)=>Si(e(t),n,r,void 0,t)}var wi=class{constructor(e,t){this.unique=e,this.name=t}static[e]=`PgIndexBuilderOn`;on(...e){return new Ti(e.map(e=>{if(n(e,j))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new Ti(e.map(e=>{if(n(e,j))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new Ti(t.map(e=>{if(n(e,j))return e;e=e;let t=new te(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}},Ti=class{static[e]=`PgIndexBuilder`;config;constructor(e,t,n,r,i=`btree`){this.config={name:r,columns:e,unique:t,only:n,method:i}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new Ei(this.config,e)}},Ei=class{static[e]=`PgIndex`;config;constructor(e,t){this.config={...e,table:t}}};function Di(e){return new wi(!1,e)}function Oi(e){return new wi(!0,e)}var ki=class{constructor(e,t){this.name=e,t&&(this.as=t.as,this.for=t.for,this.to=t.to,this.using=t.using,this.withCheck=t.withCheck)}static[e]=`PgPolicy`;as;for;to;using;withCheck;_linkedTable;link(e){return this._linkedTable=e,this}};function Ai(e,t){return new ki(e,t)}function ji(...e){return e[0].columns?new Mi(e[0].columns,e[0].name):new Mi(e)}var Mi=class{static[e]=`PgPrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Ni(e,this.columns,this.name)}},Ni=class{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[e]=`PgPrimaryKey`;columns;name;getName(){return this.name??`${this.table[X.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}};const Pi=Symbol.for(`drizzle:PgViewConfig`);var Fi=class{constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[O.Symbol.Name]}static[e]=`Relation`;referencedTableName;fieldName},Ii=class t extends Fi{constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[e]=`One`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=e,n}},Li=class t extends Fi{constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[e]=`Many`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config);return n.fieldName=e,n}};function Ri(){return{and:V,between:$e,eq:B,exists:Ze,gt:Ue,gte:We,ilike:rt,inArray:qe,isNull:Ye,isNotNull:Xe,like:tt,lt:Ge,lte:Ke,ne:Be,not:He,notBetween:et,notExists:Qe,notLike:nt,notIlike:it,notInArray:Je,or:Ve,sql:N}}function zi(){return{sql:N,asc:ct,desc:lt}}function Bi(e,t,r){if(n(r,Ii)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[xe(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[O.Symbol.Name]}" not found in schema`);let a=e[i];if(!a)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[xe(o)];if(!s)throw Error(`Table "${o[O.Symbol.Name]}" not found in schema`);let c=[];for(let e of Object.values(a.relations))(r.relationName&&r!==e&&e.relationName===r.relationName||!r.relationName&&e.referencedTable===r.sourceTable)&&c.push(e);if(c.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[O.Symbol.Name]}". Please specify relation name`);if(c[0]&&n(c[0],Ii)&&c[0].config)return{fields:c[0].config.references,references:c[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function Vi(e,t,i,a,o=e=>e){let s={};for(let[c,l]of a.entries())if(l.isJson){let r=t.relations[l.tsKey],a=i[c],u=typeof a==`string`?JSON.parse(a):a;s[l.tsKey]=n(r,Ii)?u&&Vi(e,e[l.relationTableTsKey],u,l.selection,o):u.map(t=>Vi(e,e[l.relationTableTsKey],t,l.selection,o))}else{let e=o(i[c]),t=l.field,a;a=n(t,r)?t:n(t,j)?t.decoder:t.sql.decoder,s[l.tsKey]=e===null?null:a.mapFromDriverValue(e)}return s}function Hi(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join(`_`)}function Ui(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function Wi(e){return e}var Gi=class{static[e]=`CasingCache`;cache={};cachedTables={};convert;constructor(e){this.convert=e===`snake_case`?Hi:e===`camelCase`?Ui:Wi}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=`${e.table[O.Symbol.Schema]??`public`}.${e.table[O.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let t=`${e[O.Symbol.Schema]??`public`}.${e[O.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(let i of Object.values(e[O.Symbol.Columns])){if(!n(i,r))continue;let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}},Ki=class extends F{static[e]=`PgViewBase`},qi=class{static[e]=`PgDialect`;casing;constructor(e){this.casing=new Gi(e?.casing)}async migrate(e,t,n){let r=typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=typeof n==`string`?`drizzle`:n.migrationsSchema??`drizzle`,a=N`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS ${N.identifier(i)}.${N.identifier(r)} (
|
|
5
4
|
id SERIAL PRIMARY KEY,
|
|
6
5
|
hash text NOT NULL,
|
|
7
6
|
created_at bigint
|
|
8
7
|
)
|
|
9
|
-
`;await t.execute(P`CREATE SCHEMA IF NOT EXISTS ${P.identifier(i)}`),await t.execute(a);let o=(await t.all(P`select id, hash, created_at from ${P.identifier(i)}.${P.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(P.raw(e));await t.execute(P`insert into ${P.identifier(i)}.${P.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[P`with `];for(let[n,r]of e.entries())t.push(P`${P.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(P`, `);return t.push(P` `),P.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?P` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return P`${i}delete from ${e}${t?P` where ${t}`:void 0}${a}`}buildUpdateSet(e,t){let n=e[k.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return P.join(r.flatMap((e,r)=>{let a=n[e],o=t[e]??P.param(a.onUpdateFn(),a),s=P`${P.identifier(this.casing.getColumnCasing(a))} = ${o}`;return r<i-1?[s,P.raw(`, `)]:[s]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[X.Symbol.Name],l=e[X.Symbol.Schema],u=e[X.Symbol.OriginalName],d=c===u?void 0:c,f=P`${l?P`${P.identifier(l)}.`:void 0}${P.identifier(u)}${d&&P` ${P.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&P.join([P.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?P` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0;return P`${s}update ${f} set ${p}${m}${h}${n?P` where ${n}`:void 0}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let i=e.length,a=e.flatMap(({field:e},a)=>{let o=[];if(n(e,M.Aliased)&&e.isSelectionField)o.push(P.identifier(e.fieldAlias));else if(n(e,M.Aliased)||n(e,M)){let r=n(e,M.Aliased)?e.sql:e;t?o.push(new M(r.queryChunks.map(e=>n(e,S)?P.identifier(this.casing.getColumnCasing(e)):e))):o.push(r),n(e,M.Aliased)&&o.push(P` as ${P.identifier(e.fieldAlias)}`)}else n(e,r)&&(t?o.push(P.identifier(this.casing.getColumnCasing(e))):o.push(e));return a<i-1&&o.push(P`, `),o});return P.join(a)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[r,i]of e.entries()){r===0&&t.push(P` `);let a=i.table,o=i.lateral?P` lateral`:void 0,s=i.on?P` on ${i.on}`:void 0;if(n(a,X)){let e=a[X.Symbol.Name],n=a[X.Symbol.Schema],r=a[X.Symbol.OriginalName],c=e===r?void 0:i.alias;t.push(P`${P.raw(i.joinType)} join${o} ${n?P`${P.identifier(n)}.`:void 0}${P.identifier(r)}${c&&P` ${P.identifier(c)}`}${s}`)}else if(n(a,I)){let e=a[T].name,n=a[T].schema,r=a[T].originalName,c=e===r?void 0:i.alias;t.push(P`${P.raw(i.joinType)} join${o} ${n?P`${P.identifier(n)}.`:void 0}${P.identifier(r)}${c&&P` ${P.identifier(c)}`}${s}`)}else t.push(P`${P.raw(i.joinType)} join${o} ${a}${s}`);r<e.length-1&&t.push(P` `)}return P.join(t)}buildFromTable(e){if(n(e,k)&&e[k.Symbol.IsAlias]){let t=P`${P.identifier(e[k.Symbol.OriginalName])}`;return e[k.Symbol.Schema]&&(t=P`${P.identifier(e[k.Symbol.Schema])}.${t}`),P`${t} ${P.identifier(e[k.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:i,where:a,having:o,table:s,joins:c,orderBy:l,groupBy:u,limit:d,offset:f,lockingClause:p,distinct:m,setOperators:h}){let g=i??K(t);for(let e of g)if(n(e.field,r)&&A(e.field.table)!==(n(s,C)?s._.alias:n(s,ia)?s[T].name:n(s,M)?void 0:A(s))&&!(e=>c?.some(({alias:t})=>t===(e[k.Symbol.IsAlias]?A(e):e[k.Symbol.BaseName])))(e.field.table)){let t=A(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!c||c.length===0,v=this.buildWithCTE(e),y;m&&(y=m===!0?P` distinct`:P` distinct on (${P.join(m.on,P`, `)})`);let b=this.buildSelection(g,{isSingleTable:_}),x=this.buildFromTable(s),S=this.buildJoins(c),ee=a?P` where ${a}`:void 0,te=o?P` having ${o}`:void 0,ne;l&&l.length>0&&(ne=P` order by ${P.join(l,P`, `)}`);let re;u&&u.length>0&&(re=P` group by ${P.join(u,P`, `)}`);let ie=typeof d==`object`||typeof d==`number`&&d>=0?P` limit ${d}`:void 0,ae=f?P` offset ${f}`:void 0,oe=P.empty();if(p){let e=P` for ${P.raw(p.strength)}`;p.config.of&&e.append(P` of ${P.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],P`, `)}`),p.config.noWait?e.append(P` nowait`):p.config.skipLocked&&e.append(P` skip locked`),oe.append(e)}let se=P`${v}select${y} ${b} from ${x}${S}${ee}${re}${te}${ne}${ie}${ae}${oe}`;return h.length>0?this.buildSetOperations(se,h):se}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:a,orderBy:o,offset:s}}){let c=P`(${e.getSQL()}) `,l=P`(${i.getSQL()})`,u;if(o&&o.length>0){let e=[];for(let t of o)if(n(t,S))e.push(P.identifier(t.name));else if(n(t,M)){for(let e=0;e<t.queryChunks.length;e++){let r=t.queryChunks[e];n(r,S)&&(t.queryChunks[e]=P.identifier(r.name))}e.push(P`${t}`)}else e.push(P`${t}`);u=P` order by ${P.join(e,P`, `)} `}let d=typeof a==`object`||typeof a==`number`&&a>=0?P` limit ${a}`:void 0,f=P.raw(`${t} ${r?`all `:``}`),p=s?P` offset ${s}`:void 0;return P`${c}${f}${l}${u}${d}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:a,select:o,overridingSystemValue_:s}){let c=[],l=e[k.Symbol.Columns],u=Object.entries(l).filter(([e,t])=>!t.shouldDisableInsert()),d=u.map(([,e])=>P.identifier(this.casing.getColumnCasing(e)));if(o){let e=t;n(e,M)?c.push(e):c.push(e.getSQL())}else{let e=t;c.push(P.raw(`values `));for(let[t,r]of e.entries()){let i=[];for(let[e,t]of u){let a=r[e];if(a===void 0||n(a,N)&&a.value===void 0)if(t.defaultFn!==void 0){let e=t.defaultFn(),r=n(e,M)?e:P.param(e,t);i.push(r)}else if(!t.default&&t.onUpdateFn!==void 0){let e=t.onUpdateFn(),r=n(e,M)?e:P.param(e,t);i.push(r)}else i.push(P`default`);else i.push(a)}c.push(i),t<e.length-1&&c.push(P`, `)}}let f=this.buildWithCTE(a),p=P.join(c),m=i?P` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,h=r?P` on conflict ${r}`:void 0;return P`${f}insert into ${e} ${d} ${s===!0?P`overriding system value `:void 0}${p}${h}${m}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){return P`refresh materialized view${t?P` concurrently`:void 0} ${e}${n?P` with no data`:void 0}`}prepareTyping(e){return n(e,ur)||n(e,sr)?`json`:n(e,wr)?`decimal`:n(e,oi)?`time`:n(e,li)||n(e,di)?`timestamp`:n(e,Wn)||n(e,Kn)?`date`:n(e,mi)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}_buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:i,table:a,tableConfig:o,queryConfig:s,tableAlias:c,nestedQueryRelation:l,joinOn:u}){let d=[],f,p,m=[],h,g=[];if(s===!0)d=Object.entries(o.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:R(t,c),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let a=Object.fromEntries(Object.entries(o.columns).map(([e,t])=>[e,R(t,c)]));if(s.where){let e=typeof s.where==`function`?s.where(a,Xi()):s.where;h=e&&Ve(e,c)}let l=[],u=[];if(s.columns){let e=!1;for(let[t,n]of Object.entries(s.columns))n!==void 0&&t in o.columns&&(!e&&n===!0&&(e=!0),u.push(t));u.length>0&&(u=e?u.filter(e=>s.columns?.[e]===!0):Object.keys(o.columns).filter(e=>!u.includes(e)))}else u=Object.keys(o.columns);for(let e of u){let t=o.columns[e];l.push({tsKey:e,value:t})}let _=[];s.with&&(_=Object.entries(s.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:o.relations[e]})));let v;if(s.extras){v=typeof s.extras==`function`?s.extras(a,{sql:P}):s.extras;for(let[e,t]of Object.entries(v))l.push({tsKey:e,value:Be(t,c)})}for(let{tsKey:e,value:t}of l)d.push({dbKey:n(t,M.Aliased)?t.fieldAlias:o.columns[e].name,tsKey:e,field:n(t,r)?R(t,c):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let y=typeof s.orderBy==`function`?s.orderBy(a,Zi()):s.orderBy??[];Array.isArray(y)||(y=[y]),m=y.map(e=>n(e,r)?R(e,c):Ve(e,c)),f=s.limit,p=s.offset;for(let{tsKey:r,queryConfig:a,relation:o}of _){let s=Qi(t,i,o),l=i[be(o.referencedTable)],u=`${c}_${r}`,f=H(...s.fields.map((e,t)=>V(R(s.references[t],u),R(e,c)))),p=this._buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:i,table:e[l],tableConfig:t[l],queryConfig:n(o,Ji)?a===!0?{limit:1}:{...a,limit:1}:a,tableAlias:u,joinOn:f,nestedQueryRelation:o}),m=P`${P.identifier(u)}.${P.identifier(`data`)}`.as(r);g.push({on:P`true`,table:new C(p.sql,{},u),alias:u,joinType:`left`,lateral:!0}),d.push({dbKey:r,tsKey:r,field:m,relationTableTsKey:l,isJson:!0,selection:p.selection})}}if(d.length===0)throw new He({message:`No fields selected for table "${o.tsName}" ("${c}")`});let _;if(h=H(u,h),l){let e=P`json_build_array(${P.join(d.map(({field:e,tsKey:t,isJson:r})=>r?P`${P.identifier(`${c}_${t}`)}.${P.identifier(`data`)}`:n(e,M.Aliased)?e.sql:e),P`, `)})`;n(l,Yi)&&(e=P`coalesce(json_agg(${e}${m.length>0?P` order by ${P.join(m,P`, `)}`:void 0}), '[]'::json)`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:o.tsName,selection:d}];f!==void 0||p!==void 0||m.length>0?(_=this.buildSelectQuery({table:L(a,c),fields:{},fieldsFlat:[{path:[],field:P.raw(`*`)}],where:h,limit:f,offset:p,orderBy:m,setOperators:[]}),h=void 0,f=void 0,p=void 0,m=[]):_=L(a,c),_=this.buildSelectQuery({table:n(_,X)?_:new C(_,{},c),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:n(e,r)?R(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]})}else _=this.buildSelectQuery({table:L(a,c),fields:{},fieldsFlat:d.map(({field:e})=>({path:[],field:n(e,r)?R(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:o.tsName,sql:_,selection:d}}nestedSelectionerror(){throw new He({message:`Views with nested selections are not supported by the relational query builder`})}buildRqbColumn(e,t,i){if(n(t,r)){let r=P`${e}.${P.identifier(this.casing.getColumnCasing(t))}`,a=t.columnType,o=t,s=0;for(;n(o,re);)o=o.baseColumn,a=o.columnType,++s;switch(a){case`PgNumeric`:case`PgNumericNumber`:case`PgNumericBigInt`:case`PgBigInt64`:case`PgBigSerial64`:case`PgTimestampString`:case`PgGeometry`:case`PgGeometryObject`:case`PgBytea`:{let e=`[]`.repeat(s);return P`${r}::text${P.raw(e).if(e)} as ${P.identifier(i)}`}case`PgCustomColumn`:return P`${o.jsonSelectIdentifier(r,P,s>0?s:void 0)} as ${P.identifier(i)}`;default:return P`${r} as ${P.identifier(i)}`}}return P`${e}.${n(t,M.Aliased)?P.identifier(t.fieldAlias):Se(t)?P.identifier(i):this.nestedSelectionerror()} as ${P.identifier(i)}`}unwrapAllColumns=(e,t)=>P.join(Object.entries(e[D]).map(([n,r])=>(t.push({key:n,field:r}),this.buildRqbColumn(e,r,n))),P`, `);buildColumns=(e,t,n)=>n?.columns?(()=>{let r=Object.entries(n.columns),i=e[D],a=[],o;for(let[n,s]of r)if(s!==void 0&&(o||=s,s)){let r=i[n];a.push(this.buildRqbColumn(e,r,n)),t.push({key:n,field:r})}if(o===!1)for(let[r,o]of Object.entries(i))n.columns[r]!==!1&&(a.push(this.buildRqbColumn(e,o,r)),t.push({key:r,field:o}));return a.length?P.join(a,P`, `):void 0})():this.unwrapAllColumns(e,t);buildRelationalQuery({schema:e,table:t,tableConfig:r,queryConfig:i,relationWhere:a,mode:o,errorPath:s,depth:c,throughJoin:l}){let u=[],d=o===`first`,f=i===!0?void 0:i,p=s??``,m=c??0;m||(t=L(t,`d${m}`));let h=d?1:f?.limit,g=f?.offset,_=f?.where&&a?H(G(t,f.where,r.relations,e,this.casing),a):f?.where?G(t,f.where,r.relations,e,this.casing):a,v=f?.orderBy?Rt(t,f.orderBy):void 0,y=this.buildColumns(t,u,f),b=f?.extras?zt(t,f.extras):void 0;b&&u.push(...b.selection);let x=y?[y]:[],S=f?(()=>{let{with:i}=f;if(!i)return;let a=Object.entries(i).filter(([e,t])=>t);if(a.length)return P.join(a.map(([i,a])=>{let o=r.relations[i],s=n(o,xt),c=L(o.targetTable,`d${m+1}`),l=o.throughTable?L(o.throughTable,`tr${m}`):void 0,{filter:d,joinCondition:f}=Bt(this.casing,o,t,c,l);x.push(P`${P.identifier(i)}.${P.identifier(`r`)} as ${P.identifier(i)}`);let h=l?P` inner join ${Vt(l)} on ${f}`:void 0,g=this.buildRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:a,tableConfig:e[o.targetTableName],relationWhere:d,errorPath:`${p.length?`${p}.`:``}${i}`,depth:m+1,throughJoin:h});return u.push({field:c,key:i,selection:g.selection,isArray:!s,isOptional:(o.optional??!1)||a!==!0&&!!a.where}),P`left join lateral(select ${s?P`row_to_json(${P.identifier(`t`)}.*) ${P.identifier(`r`)}`:P`coalesce(json_agg(row_to_json(${P.identifier(`t`)}.*)), '[]') as ${P.identifier(`r`)}`} from (${g.sql}) as ${P.identifier(`t`)}) as ${P.identifier(i)} on true`}),P` `)})():void 0;if(b?.sql&&x.push(b.sql),!x.length)throw new He({message:`No fields selected for table "${r.name}"${p?` ("${p}")`:``}`});return{sql:P`select ${P.join(x.filter(e=>e!==void 0),P`, `)} from ${Vt(t)}${l}${P` ${S}`.if(S)}${P` where ${_}`.if(_)}${P` order by ${v}`.if(v)}${P` limit ${h}`.if(h!==void 0)}${P` offset ${g}`.if(g!==void 0)}`,selection:u}}},oa=class{static[e]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},Q=class{static[e]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,r=e,i;return i=this.fields?this.fields:n(r,C)?Object.fromEntries(Object.keys(r._.selectedFields).map(e=>[e,r[e]])):n(r,ia)?r[T].selectedFields:n(r,M)?{}:cn(r),new ca({table:r,fields:i,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},sa=class extends oa{static[e]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=q(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of $(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(r,i)=>{let a=this.tableName,o=q(r);for(let e of $(r))this.usedTables.add(e);if(typeof o==`string`&&this.config.joins?.some(e=>e.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof a==`string`&&(this.config.fields={[a]:this.config.fields}),typeof o==`string`&&!n(r,M))){let e=n(r,C)?r._.selectedFields:n(r,I)?r[T].selectedFields:r[k.Symbol.Columns];this.config.fields[o]=e}if(typeof i==`function`&&(i=i(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:r,joinType:e,alias:o,lateral:t}),typeof o==`string`)switch(e){case`left`:this.joinsNotNullableMap[o]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[o]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!1;break}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(ua()):n;if(!an(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...$(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...$(e.table));return new Proxy(new C(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new Y({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},ca=class extends sa{static[e]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=K(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};sn(ca,[z]);function la(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!an(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}const ua=()=>({union:da,unionAll:fa,intersect:pa,intersectAll:ma,except:ha,exceptAll:ga}),da=la(`union`,!1),fa=la(`union`,!0),pa=la(`intersect`,!1),ma=la(`intersect`,!0),ha=la(`except`,!1),ga=la(`except`,!0);var _a=class{static[e]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=n(e,aa)?e:void 0,this.dialectConfig=n(e,aa)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new pe(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new Q({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new aa(this.dialectConfig),this.dialect}},va=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},ya=class extends va{static[e]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new _a));let t=new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new wa({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},ba=class extends va{static[e]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=cn(Z(e,t))}existing(){return new Proxy(new wa({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new wa({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},xa=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},Sa=class extends xa{static[e]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new _a));let t=new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Ea({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Ca=class extends xa{static[e]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=cn(Z(e,t))}existing(){return new Proxy(new Ea({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Ea({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},wa=class extends ia{static[e]=`PgView`;[Ki];constructor({pgConfig:e,config:t}){super(t),e&&(this[Ki]={with:e.with})}};const Ta=Symbol.for(`drizzle:PgMaterializedViewConfig`);var Ea=class extends ia{static[e]=`PgMaterializedView`;[Ta];constructor({pgConfig:e,config:t}){super(t),this[Ta]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function Da(e,t,n){return t?new ba(e,t,n):new ya(e,n)}function Oa(e,t,n){return t?new Ca(e,t,n):new Sa(e,n)}function ka(e,t){return Da(e,t,void 0)}function Aa(e,t){return Oa(e,t,void 0)}function ja(e){return n(e,wa)}function Ma(e){return n(e,Ea)}function Na(e){let t=Object.values(e[k.Symbol.Columns]),r=[],i=[],a=[],o=Object.values(e[X.Symbol.InlineForeignKeys]),s=[],l=e[k.Symbol.Name],u=e[k.Symbol.Schema],d=[],f=e[X.Symbol.EnableRLS],p=e[X.Symbol.ExtraConfigBuilder];if(p!==void 0){let t=p(e[k.Symbol.ExtraConfigColumns]),l=Array.isArray(t)?t.flat(1):Object.values(t);for(let t of l)n(t,Li)?r.push(t.build(e)):n(t,pn)?i.push(t.build(e)):n(t,m)?s.push(t.build(e)):n(t,Wi)?a.push(t.build(e)):n(t,c)?o.push(t.build(e)):n(t,Vi)&&d.push(t)}return{columns:t,indexes:r,foreignKeys:o,checks:i,primaryKeys:a,uniqueConstraints:s,name:l,schema:u,policies:d,enableRLS:f}}function $(e){return n(e,X)?[e[E]?`${e[E]}.${e[k.Symbol.BaseName]}`:e[k.Symbol.BaseName]]:n(e,C)?e._.usedTables??[]:n(e,M)?e.usedTables??[]:[]}function Pa(e){return{...e[T],...e[Ki]}}function Fa(e){return{...e[T],...e[Ta]}}var Ia=class extends z{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[e]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[k.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=K(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:A(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},La=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[e]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},r=this.table[k.Symbol.Columns];for(let i of Object.keys(e)){let a=e[i];t[i]=n(a,M)?a:new N(a,r[i])}return t});return new Ra(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e==`function`?e(new _a):e;if(!n(t,M)&&!an(this.table[D],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new Ra(this.table,t,this.session,this.dialect,this.withList,!0)}},Ra=class extends z{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[e]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[k.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=K(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=P`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?P` where ${e.where}`:void 0;this.config.onConflict=P`(${P.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?P` where ${e.where}`:void 0,n=e.targetWhere?P` where ${e.targetWhere}`:void 0,r=e.setWhere?P` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,on(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=P`(${P.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:A(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},za=class extends z{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[e]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},Ba=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[e]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new Va(this.table,on(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},Va=class extends z{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=q(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[e]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=q(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return n(e,X)?e[k.Symbol.Columns]:n(e,C)?e._.selectedFields:e[T].selectedFields}createJoin(e){return(t,r)=>{let i=q(t);if(typeof i==`string`&&this.config.joins.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==`function`){let e=this.config.from&&!n(this.config.from,M)?this.getTableLikeFields(this.config.from):void 0;r=r(new Proxy(this.config.table[k.Symbol.Columns],new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:r,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1;break}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[k.Symbol.Columns]),this.config.from)){let t=q(this.config.from);typeof t==`string`&&this.config.from&&!n(this.config.from,M)&&(e[t]=this.getTableLikeFields(this.config.from));for(let t of this.config.joins){let r=q(t.table);typeof r==`string`&&!n(t.table,M)&&(e[r]=this.getTableLikeFields(t.table))}}return this.config.returningFields=e,this.config.returning=K(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:A(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Ha=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[e]=`PgRelationalQueryBuilder`;findMany(e){return new Ua(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new Ua(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},Ua=class extends z{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[e]=`PgRelationalQuery`;_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>$i(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect._buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Wa=class t extends M{constructor(e){super(t.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=t.buildCount(e.source,e.filters)}sql;token;static[e]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return P`(select count(*) from ${e}${P.raw(` where `).if(t)}${t})`}static buildCount(e,t){return P`select count(*) as count from ${e}${P.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},Ga=class{constructor(e,t,n,r,i){this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i}static[e]=`PgRelationalQueryBuilderV2`;findMany(e){return new Ka(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`many`)}findFirst(e){return new Ka(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`first`)}},Ka=class extends z{constructor(e,t,n,r,i,a,o){super(),this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i,this.config=a,this.mode=o}static[e]=`PgRelationalQueryV2`;_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareRelationalQuery(n,void 0,e,(e,n)=>{let r=e.map(e=>Dt(e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQuery({schema:this.schema,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,mode:this.mode})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},qa=class extends z{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[e]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},Ja=class{constructor(e,t,n,r){if(this.dialect=e,this.session=t,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap,relations:n,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},relations:n,session:t},this._query={},this._.schema)for(let[n,i]of Object.entries(this._.schema))this._query[n]=new Ha(r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[n],i,e,t);this.query={};for(let[r,i]of Object.entries(n))this.query[r]=new Ga(n,n[i.name].table,i,e,t);this.$cache={invalidate:async e=>{}}}static[e]=`PgDatabase`;_query;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new _a(n.dialect))),new Proxy(new pe(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new Wa({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new Q({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new Ba(n,t.session,t.dialect,e)}function o(n){return new La(n,t.session,t.dialect,e)}function s(n){return new Ia(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Ba(e,this.session,this.dialect)}insert(e){return new La(e,this.session,this.dialect)}delete(e){return new Ia(e,this.session,this.dialect)}refreshMaterializedView(e){return new za(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?P.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new qa(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}};const Ya=(e,t,n=()=>t[Math.floor(Math.random()*t.length)])=>{let r=(...e)=>n(t).select(...e),i=(...e)=>n(t).selectDistinct(...e),a=(...e)=>n(t).selectDistinctOn(...e),o=(...e)=>n(t).$count(...e),s=(...e)=>n(t).with(...e),c=e=>n(t).$with(e),l=(...t)=>e.update(...t),u=(...t)=>e.insert(...t),d=(...t)=>e.delete(...t),f=(...t)=>e.execute(...t),p=(...t)=>e.transaction(...t),m=(...t)=>e.refreshMaterializedView(...t);return{...e,update:l,insert:u,delete:d,execute:f,transaction:p,refreshMaterializedView:m,$primary:e,select:r,selectDistinct:i,selectDistinctOn:a,$count:o,$with:c,with:s,get _query(){return n(t)._query},get query(){return n(t).query}}};var Xa=class{constructor(e,t){this.name=e,t&&(this.createDb=t.createDb,this.createRole=t.createRole,this.inherit=t.inherit)}static[e]=`PgRole`;_existing;createDb;createRole;inherit;existing(){return this._existing=!0,this}};function Za(e,t){return new Xa(e,t)}var Qa=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[e]=`PgSequence`};function $a(e,t){return eo(e,t,void 0)}function eo(e,t,n){return new Qa(e,t,n)}function to(e){return n(e,Qa)}var no=class{constructor(e){this.schemaName=e}static[e]=`PgSchema`;table=(e,t,n)=>Pi(e,t,n,this.schemaName);view=(e,t)=>Da(e,t,this.schemaName);materializedView=(e,t)=>Oa(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?de(e,[...t],this.schemaName):fe(e,t,this.schemaName)}sequence=(e,t)=>eo(e,t,this.schemaName);getSQL(){return new M([P.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function ro(e){return n(e,no)}function io(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new no(e)}function ao(){let e=Z(`accounts`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),accessToken:e.text(`access_token`),accessTokenExpiresAt:e.timestamp(`access_token_expires_at`,{withTimezone:!0}),accountId:e.text(`account_id`).notNull(),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),idToken:e.text(`id_token`),providerId:e.text(`provider_id`).notNull(),password:e.text(`password`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),refreshToken:e.text(`refresh_token`),refreshTokenExpiresAt:e.timestamp(`refresh_token_expires_at`,{withTimezone:!0}),scope:e.text(`scope`),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]),t=Z(`api_keys`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),name:e.text(`name`),enabled:e.boolean(`enabled`).default(!0),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}),key:e.text(`key`).notNull(),lastRefillAt:e.timestamp(`last_refill_at`,{withTimezone:!0}),lastRequest:e.timestamp(`last_request`,{withTimezone:!0}),lastUsedAt:e.timestamp(`last_used_at`,{withTimezone:!0}),metadata:e.text(`metadata`),permissions:e.text(`permissions`),prefix:e.text(`prefix`),rateLimitEnabled:e.boolean(`rate_limit_enabled`).default(!0),rateLimitTimeWindow:e.integer(`rate_limit_time_window`).default(864e5),rateLimitMax:e.integer(`rate_limit_max`).default(10),refillInterval:e.integer(`refill_interval`),refillAmount:e.integer(`refill_amount`),requestCount:e.integer(`request_count`),remaining:e.integer(`remaining`),start:e.text(`start`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]),n=Z(`invitations`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),email:e.text(`email`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),inviterId:e.text(`inviter_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`),status:e.text(`status`).default(`pending`).notNull(),teamId:e.text(`team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]),r=Z(`members`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`).default(`member`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]),i=Z(`organizations`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),name:e.text(`name`).notNull(),slug:e.text(`slug`).unique(),logo:e.text(`logo`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),metadata:e.text(`metadata`)}),e=>[]),a=Z(`sessions`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),activeOrganizationId:e.text(`active_organization_id`).references(()=>i.id,{onDelete:`set null`}),activeTeamId:e.text(`active_team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),impersonatedBy:e.text(`impersonated_by`).references(()=>s.id,{onDelete:`set null`}),ipAddress:e.text(`ip_address`),token:e.text(`token`).notNull().unique(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),userAgent:e.text(`user_agent`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),o=Z(`sso_providers`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),domain:e.text(`domain`).notNull(),issuer:e.text(`issuer`).notNull(),oidcConfig:e.text(`oidc_config`),organizationId:e.text(`organization_id`).references(()=>i.id,{onDelete:`cascade`}),providerId:e.text(`provider_id`).notNull().unique(),samlConfig:e.text(`saml_config`),userId:e.text(`user_id`).references(()=>s.id,{onDelete:`cascade`})}),e=>[]),s=Z(`users`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),banExpires:e.timestamp(`ban_expires`,{withTimezone:!0}),banReason:e.text(`ban_reason`),banned:e.boolean(`banned`).default(!1),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),displayUsername:e.text(`display_username`),email:e.text(`email`).notNull().unique(),emailVerified:e.boolean(`email_verified`).default(!1).notNull(),image:e.text(`image`),isAnonymous:e.boolean(`is_anonymous`),lastLoginMethod:e.text(`last_login_method`),name:e.text(`name`).notNull(),phoneNumber:e.text(`phone_number`).unique(),phoneNumberVerified:e.boolean(`phone_number_verified`),role:e.text(`role`),twoFactorEnabled:e.boolean(`two_factor_enabled`).default(!1),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),username:e.text(`username`).unique()}),e=>[]),c=Z(`teams`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),name:e.text(`name`).notNull(),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]);return{tables:{accounts:e,apiKeys:t,invitations:n,members:r,organizations:i,sessions:a,ssoProviders:o,teams:c,teamMembers:Z(`team_members`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),teamId:e.text(`team_id`).notNull().references(()=>c.id,{onDelete:`cascade`}),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[]),twoFactors:Z(`two_factors`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),secret:e.text(`secret`).notNull(),backupCodes:e.text(`backup_codes`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),users:s,verifications:Z(`verifications`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),identifier:e.text(`identifier`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(P`NOW()`).notNull(),value:e.text(`value`).notNull()}),e=>[])},relations:e=>({users:{sessions:e.many.sessions({from:e.users.id,to:e.sessions.userId}),accounts:e.many.accounts({from:e.users.id,to:e.accounts.userId}),apiKeys:e.many.apiKeys({from:e.users.id,to:e.apiKeys.userId}),memberships:e.many.members({from:e.users.id,to:e.members.userId}),invitations:e.many.invitations({from:e.users.id,to:e.invitations.inviterId}),ssoProvider:e.one.ssoProviders({from:e.users.id,to:e.ssoProviders.userId}),twoFactor:e.one.twoFactors({from:e.users.id,to:e.twoFactors.userId})},sessions:{user:e.one.users({from:e.sessions.userId,to:e.users.id})},accounts:{user:e.one.users({from:e.accounts.userId,to:e.users.id})},apiKeys:{user:e.one.users({from:e.apiKeys.userId,to:e.users.id})},organizations:{members:e.many.members({from:e.organizations.id,to:e.members.organizationId}),invitations:e.many.invitations({from:e.organizations.id,to:e.invitations.organizationId}),teams:e.many.teams({from:e.organizations.id,to:e.teams.organizationId})},members:{organization:e.one.organizations({from:e.members.organizationId,to:e.organizations.id}),user:e.one.users({from:e.members.userId,to:e.users.id})},invitations:{organization:e.one.organizations({from:e.invitations.organizationId,to:e.organizations.id}),inviter:e.one.users({from:e.invitations.inviterId,to:e.users.id})},teams:{organization:e.one.organizations({from:e.teams.organizationId,to:e.organizations.id})},ssoProviders:{user:e.one.users({from:e.ssoProviders.userId,to:e.users.id})},verifications:{},twoFactors:{user:e.one.users({from:e.twoFactors.userId,to:e.users.id})}})}}function oo(){let e=Z(`storage_blobs`,e=>({id:e.text(`id`).primaryKey().default(P`uuidv7()`),key:e.text(`key`).notNull().unique(),filename:e.text(`filename`).notNull(),contentType:e.text(`content_type`),metadata:e.jsonb(`metadata`),serviceName:e.text(`service_name`).notNull().default(`private`),byteSize:e.bigint(`byte_size`,{mode:`number`}).notNull(),checksum:e.text(`checksum`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[zi(`storage_blobs_key_idx`).on(e.key),zi(`storage_blobs_service_name_idx`).on(e.serviceName)]);return{tables:{storageBlobs:e,storageAttachments:Z(`storage_attachments`,t=>({id:t.text(`id`).primaryKey().default(P`uuidv7()`),name:t.text(`name`).notNull(),recordType:t.text(`record_type`).notNull(),recordId:t.text(`record_id`).notNull(),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).notNull().default(P`NOW()`)}),e=>[zi(`storage_attachments_record_idx`).on(e.recordType,e.recordId),zi(`storage_attachments_blob_id_idx`).on(e.blobId)]),storageVariantRecords:Z(`storage_variant_records`,t=>({id:t.text(`id`).primaryKey().default(P`uuidv7()`),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),variationDigest:t.text(`variation_digest`).notNull(),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).default(P`NOW()`).notNull()}),e=>[zi(`storage_variant_records_blob_id_idx`).on(e.blobId),f(`storage_variant_records_unique`).on(e.blobId,e.variationDigest)])},relations:e=>({storageBlobs:{attachments:e.many.storageAttachments({from:e.storageBlobs.id,to:e.storageAttachments.blobId}),variantRecords:e.many.storageVariantRecords({from:e.storageBlobs.id,to:e.storageVariantRecords.blobId})},storageAttachments:{blob:e.one.storageBlobs({from:e.storageAttachments.blobId,to:e.storageBlobs.id})},storageVariantRecords:{blob:e.one.storageBlobs({from:e.storageVariantRecords.blobId,to:e.storageBlobs.id})}})}}oo();export{Ct as AggregatedField,ge as BaseName,mn as Check,pn as CheckBuilder,r as Column,Ie as ColumnAliasProxyHandler,o as ColumnBuilder,Ge as ConsoleLogWriter,wt as Count,Ke as DefaultLogger,He as DrizzleError,Ue as DrizzleQueryError,_e as ExtraConfigBuilder,me as ExtraConfigColumns,xe as FakePrimitiveParam,l as ForeignKey,c as ForeignKeyBuilder,Ri as Index,Li as IndexBuilder,Ii as IndexBuilderOn,te as IndexedColumn,O as IsAlias,St as Many,we as Name,qe as NoopLogger,xt as One,he as OriginalName,N as Param,re as PgArray,ne as PgArrayBuilder,vn as PgBigInt53,_n as PgBigInt53Builder,bn as PgBigInt64,yn as PgBigInt64Builder,Cn as PgBigSerial53,Sn as PgBigSerial53Builder,Tn as PgBigSerial64,wn as PgBigSerial64Builder,bi as PgBinaryVector,yi as PgBinaryVectorBuilder,On as PgBoolean,Dn as PgBooleanBuilder,jn as PgBytea,An as PgByteaBuilder,Pn as PgChar,Nn as PgCharBuilder,Ln as PgCidr,In as PgCidrBuilder,S as PgColumn,x as PgColumnBuilder,Bn as PgCustomColumn,zn as PgCustomColumnBuilder,Ja as PgDatabase,Wn as PgDate,Un as PgDateBuilder,Kn as PgDateString,Gn as PgDateStringBuilder,Ia as PgDeleteBase,aa as PgDialect,Br as PgGeometry,zr as PgGeometryBuilder,Hr as PgGeometryObject,Vr as PgGeometryObjectBuilder,Ci as PgHalfVector,Si as PgHalfVectorBuilder,La as PgInsertBuilder,tr as PgInteger,er as PgIntegerBuilder,sr as PgJson,or as PgJsonBuilder,ur as PgJsonb,lr as PgJsonbBuilder,hr as PgLineABC,mr as PgLineABCBuilder,fr as PgLineBuilder,vr as PgMacaddr,xr as PgMacaddr8,br as PgMacaddr8Builder,_r as PgMacaddrBuilder,Ta as PgMaterializedViewConfig,wr as PgNumeric,Or as PgNumericBigInt,Dr as PgNumericBigIntBuilder,Cr as PgNumericBuilder,Er as PgNumericNumber,Tr as PgNumericNumberBuilder,Gr as PgReal,Wr as PgRealBuilder,X as PgTable,ri as PgText,ni as PgTextBuilder,F as Placeholder,Gi as PrimaryKey,_a as QueryBuilder,z as QueryPromise,U as Relation,Re as RelationTableAliasProxyHandler,kt as RelationsBuilderColumn,At as RelationsBuilderJunctionColumn,Ot as RelationsBuilderTable,jt as RelationsHelperStatic,M as SQL,j as StringChunk,C as Subquery,k as Table,Le as TableAliasProxyHandler,D as TableColumns,E as TableSchema,We as TransactionRollbackError,g as UniqueConstraint,m as UniqueConstraintBuilder,h as UniqueOnConstraintBuilder,I as View,T as ViewBaseConfig,pe as WithSubquery,fn as alias,ze as aliasedRelation,L as aliasedTable,R as aliasedTableColumn,H as and,sn as applyMixins,mt as arrayContained,pt as arrayContains,ht as arrayOverlaps,gt as asc,Wt as avg,Gt as avgDistinct,st as between,xn as bigint,En as bigserial,B as bindIfParam,xi as bit,kn as boolean,yt as buildRelations,bt as buildRelationsParts,Mn as bytea,Fn as char,hn as check,Rn as cidr,en as cosineDistance,Ht as count,Ut as countDistinct,Mt as createRelationsHelper,Vn as customType,qn as date,Ar as decimal,ao as defineAuthSchema,Pt as defineRelations,Ft as defineRelationsPart,oo as defineStorageSchema,_t as desc,Xn as doublePrecision,e as entityKind,V as eq,ha as except,ga as exceptAll,at as exists,a as extractExtendedColumnType,Nt as extractTablesFromSchema,$ as extractUsedTable,It as fieldSelectionToSQL,Me as fillPlaceholders,u as foreignKey,Ur as geometry,J as getColumnNameAndConfig,i as getColumnTable,Fa as getMaterializedViewConfig,Et as getOrderByOperators,Vt as getTableAsAliasSQL,cn as getTableColumns,Na as getTableConfig,q as getTableLikeName,A as getTableName,be as getTableUniqueName,Pa as getViewConfig,Fe as getViewName,ln as getViewSelectedFields,Ze as gt,Qe as gte,wi as halfvec,tn as hammingDistance,t as hasOwnEntityKind,an as haveSameKeys,dt as ilike,tt as inArray,zi as index,$n as inet,$t as innerProduct,nr as integer,pa as intersect,ma as intersectAll,ar as interval,n as is,un as isConfig,Ee as isDriverValueEncoder,it as isNotNull,rt as isNull,se as isPgEnum,Ma as isPgMaterializedView,ro as isPgSchema,to as isPgSequence,ja as isPgView,Se as isSQLWrapper,ye as isTable,Pe as isView,nn as jaccardDistance,cr as json,dr as jsonb,Qt as l1Distance,Zt as l2Distance,lt as like,gr as line,$e as lt,et as lte,yr as macaddr,Sr as macaddr8,b as makePgArray,Be as mapColumnsInAliasedSQLToAlias,Ve as mapColumnsInSQLToAlias,Dt as mapRelationalRow,rn as mapResultRow,on as mapUpdateSet,Jt as max,Yt as min,Te as name,Je as ne,De as noopDecoder,Oe as noopEncoder,ke as noopMapper,Xe as not,ct as notBetween,ot as notExists,ft as notIlike,nt as notInArray,ut as notLike,kr as numeric,W as operators,Ye as or,Tt as orderByOperators,K as orderSelectedFields,Ae as param,y as parsePgArray,v as parsePgNestedArray,ue as pgEnum,Aa as pgMaterializedView,Hi as pgPolicy,Za as pgRole,io as pgSchema,$a as pgSequence,Z as pgTable,Fi as pgTableCreator,ka as pgView,je as placeholder,Fr as point,Ui as primaryKey,vt as processRelations,Kr as real,zt as relationExtrasToSQL,Bt as relationToSQL,G as relationsFilterToSQL,Rt as relationsOrderToSQL,Yr as serial,Qr as smallint,ti as smallserial,Di as sparsevec,P as sql,Kt as sum,qt as sumDistinct,ii as text,dn as textDecoder,si as time,fi as timestamp,da as union,fa as unionAll,f as unique,Bi as uniqueIndex,p as uniqueKeyName,hi as uuid,Ya as withReplicas};
|
|
8
|
+
`;await t.execute(N`CREATE SCHEMA IF NOT EXISTS ${N.identifier(i)}`),await t.execute(a);let o=(await t.all(N`select id, hash, created_at from ${N.identifier(i)}.${N.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(N.raw(e));await t.execute(N`insert into ${N.identifier(i)}.${N.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[N`with `];for(let[n,r]of e.entries())t.push(N`${N.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(N`, `);return t.push(N` `),N.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?N` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return N`${i}delete from ${e}${t?N` where ${t}`:void 0}${a}`}buildUpdateSet(e,t){let n=e[O.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return N.join(r.flatMap((e,r)=>{let a=n[e],o=t[e]??N.param(a.onUpdateFn(),a),s=N`${N.identifier(this.casing.getColumnCasing(a))} = ${o}`;return r<i-1?[s,N.raw(`, `)]:[s]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[X.Symbol.Name],l=e[X.Symbol.Schema],u=e[X.Symbol.OriginalName],d=c===u?void 0:c,f=N`${l?N`${N.identifier(l)}.`:void 0}${N.identifier(u)}${d&&N` ${N.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&N.join([N.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?N` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0;return N`${s}update ${f} set ${p}${m}${h}${n?N` where ${n}`:void 0}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let i=e.length,a=e.flatMap(({field:e},a)=>{let o=[];if(n(e,j.Aliased)&&e.isSelectionField)o.push(N.identifier(e.fieldAlias));else if(n(e,j.Aliased)||n(e,j)){let r=n(e,j.Aliased)?e.sql:e;t?o.push(new j(r.queryChunks.map(e=>n(e,S)?N.identifier(this.casing.getColumnCasing(e)):e))):o.push(r),n(e,j.Aliased)&&o.push(N` as ${N.identifier(e.fieldAlias)}`)}else n(e,r)&&(t?o.push(N.identifier(this.casing.getColumnCasing(e))):o.push(e));return a<i-1&&o.push(N`, `),o});return N.join(a)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[r,i]of e.entries()){r===0&&t.push(N` `);let a=i.table,o=i.lateral?N` lateral`:void 0,s=i.on?N` on ${i.on}`:void 0;if(n(a,X)){let e=a[X.Symbol.Name],n=a[X.Symbol.Schema],r=a[X.Symbol.OriginalName],c=e===r?void 0:i.alias;t.push(N`${N.raw(i.joinType)} join${o} ${n?N`${N.identifier(n)}.`:void 0}${N.identifier(r)}${c&&N` ${N.identifier(c)}`}${s}`)}else if(n(a,F)){let e=a[T].name,n=a[T].schema,r=a[T].originalName,c=e===r?void 0:i.alias;t.push(N`${N.raw(i.joinType)} join${o} ${n?N`${N.identifier(n)}.`:void 0}${N.identifier(r)}${c&&N` ${N.identifier(c)}`}${s}`)}else t.push(N`${N.raw(i.joinType)} join${o} ${a}${s}`);r<e.length-1&&t.push(N` `)}return N.join(t)}buildFromTable(e){if(n(e,O)&&e[O.Symbol.IsAlias]){let t=N`${N.identifier(e[O.Symbol.OriginalName])}`;return e[O.Symbol.Schema]&&(t=N`${N.identifier(e[O.Symbol.Schema])}.${t}`),N`${t} ${N.identifier(e[O.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:i,where:a,having:o,table:s,joins:c,orderBy:l,groupBy:u,limit:d,offset:f,lockingClause:p,distinct:m,setOperators:h}){let g=i??K(t);for(let e of g)if(n(e.field,r)&&k(e.field.table)!==(n(s,C)?s._.alias:n(s,Ki)?s[T].name:n(s,j)?void 0:k(s))&&!(e=>c?.some(({alias:t})=>t===(e[O.Symbol.IsAlias]?k(e):e[O.Symbol.BaseName])))(e.field.table)){let t=k(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!c||c.length===0,v=this.buildWithCTE(e),y;m&&(y=m===!0?N` distinct`:N` distinct on (${N.join(m.on,N`, `)})`);let b=this.buildSelection(g,{isSingleTable:_}),x=this.buildFromTable(s),S=this.buildJoins(c),ee=a?N` where ${a}`:void 0,te=o?N` having ${o}`:void 0,ne;l&&l.length>0&&(ne=N` order by ${N.join(l,N`, `)}`);let re;u&&u.length>0&&(re=N` group by ${N.join(u,N`, `)}`);let ie=typeof d==`object`||typeof d==`number`&&d>=0?N` limit ${d}`:void 0,ae=f?N` offset ${f}`:void 0,oe=N.empty();if(p){let e=N` for ${N.raw(p.strength)}`;p.config.of&&e.append(N` of ${N.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],N`, `)}`),p.config.noWait?e.append(N` nowait`):p.config.skipLocked&&e.append(N` skip locked`),oe.append(e)}let se=N`${v}select${y} ${b} from ${x}${S}${ee}${re}${te}${ne}${ie}${ae}${oe}`;return h.length>0?this.buildSetOperations(se,h):se}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:a,orderBy:o,offset:s}}){let c=N`(${e.getSQL()}) `,l=N`(${i.getSQL()})`,u;if(o&&o.length>0){let e=[];for(let t of o)if(n(t,S))e.push(N.identifier(t.name));else if(n(t,j)){for(let e=0;e<t.queryChunks.length;e++){let r=t.queryChunks[e];n(r,S)&&(t.queryChunks[e]=N.identifier(r.name))}e.push(N`${t}`)}else e.push(N`${t}`);u=N` order by ${N.join(e,N`, `)} `}let d=typeof a==`object`||typeof a==`number`&&a>=0?N` limit ${a}`:void 0,f=N.raw(`${t} ${r?`all `:``}`),p=s?N` offset ${s}`:void 0;return N`${c}${f}${l}${u}${d}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:a,select:o,overridingSystemValue_:s}){let c=[],l=e[O.Symbol.Columns],u=Object.entries(l).filter(([e,t])=>!t.shouldDisableInsert()),d=u.map(([,e])=>N.identifier(this.casing.getColumnCasing(e)));if(o){let e=t;n(e,j)?c.push(e):c.push(e.getSQL())}else{let e=t;c.push(N.raw(`values `));for(let[t,r]of e.entries()){let i=[];for(let[e,t]of u){let a=r[e];if(a===void 0||n(a,M)&&a.value===void 0)if(t.defaultFn!==void 0){let e=t.defaultFn(),r=n(e,j)?e:N.param(e,t);i.push(r)}else if(!t.default&&t.onUpdateFn!==void 0){let e=t.onUpdateFn(),r=n(e,j)?e:N.param(e,t);i.push(r)}else i.push(N`default`);else i.push(a)}c.push(i),t<e.length-1&&c.push(N`, `)}}let f=this.buildWithCTE(a),p=N.join(c),m=i?N` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,h=r?N` on conflict ${r}`:void 0;return N`${f}insert into ${e} ${d} ${s===!0?N`overriding system value `:void 0}${p}${h}${m}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){return N`refresh materialized view${t?N` concurrently`:void 0} ${e}${n?N` with no data`:void 0}`}prepareTyping(e){return n(e,Qn)||n(e,Yn)?`json`:n(e,fr)?`decimal`:n(e,Jr)?`time`:n(e,Zr)||n(e,$r)?`timestamp`:n(e,Mn)||n(e,Pn)?`date`:n(e,ni)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}_buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:i,table:a,tableConfig:o,queryConfig:s,tableAlias:c,nestedQueryRelation:l,joinOn:u}){let d=[],f,p,m=[],h,g=[];if(s===!0)d=Object.entries(o.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:L(t,c),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let a=Object.fromEntries(Object.entries(o.columns).map(([e,t])=>[e,L(t,c)]));if(s.where){let e=typeof s.where==`function`?s.where(a,Ri()):s.where;h=e&&Re(e,c)}let l=[],u=[];if(s.columns){let e=!1;for(let[t,n]of Object.entries(s.columns))n!==void 0&&t in o.columns&&(!e&&n===!0&&(e=!0),u.push(t));u.length>0&&(u=e?u.filter(e=>s.columns?.[e]===!0):Object.keys(o.columns).filter(e=>!u.includes(e)))}else u=Object.keys(o.columns);for(let e of u){let t=o.columns[e];l.push({tsKey:e,value:t})}let _=[];s.with&&(_=Object.entries(s.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:o.relations[e]})));let v;if(s.extras){v=typeof s.extras==`function`?s.extras(a,{sql:N}):s.extras;for(let[e,t]of Object.entries(v))l.push({tsKey:e,value:Le(t,c)})}for(let{tsKey:e,value:t}of l)d.push({dbKey:n(t,j.Aliased)?t.fieldAlias:o.columns[e].name,tsKey:e,field:n(t,r)?L(t,c):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let y=typeof s.orderBy==`function`?s.orderBy(a,zi()):s.orderBy??[];Array.isArray(y)||(y=[y]),m=y.map(e=>n(e,r)?L(e,c):Re(e,c)),f=s.limit,p=s.offset;for(let{tsKey:r,queryConfig:a,relation:o}of _){let s=Bi(t,i,o),l=i[xe(o.referencedTable)],u=`${c}_${r}`,f=V(...s.fields.map((e,t)=>B(L(s.references[t],u),L(e,c)))),p=this._buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:i,table:e[l],tableConfig:t[l],queryConfig:n(o,Ii)?a===!0?{limit:1}:{...a,limit:1}:a,tableAlias:u,joinOn:f,nestedQueryRelation:o}),m=N`${N.identifier(u)}.${N.identifier(`data`)}`.as(r);g.push({on:N`true`,table:new C(p.sql,{},u),alias:u,joinType:`left`,lateral:!0}),d.push({dbKey:r,tsKey:r,field:m,relationTableTsKey:l,isJson:!0,selection:p.selection})}}if(d.length===0)throw new ze({message:`No fields selected for table "${o.tsName}" ("${c}")`});let _;if(h=V(u,h),l){let e=N`json_build_array(${N.join(d.map(({field:e,tsKey:t,isJson:r})=>r?N`${N.identifier(`${c}_${t}`)}.${N.identifier(`data`)}`:n(e,j.Aliased)?e.sql:e),N`, `)})`;n(l,Li)&&(e=N`coalesce(json_agg(${e}${m.length>0?N` order by ${N.join(m,N`, `)}`:void 0}), '[]'::json)`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:o.tsName,selection:d}];f!==void 0||p!==void 0||m.length>0?(_=this.buildSelectQuery({table:I(a,c),fields:{},fieldsFlat:[{path:[],field:N.raw(`*`)}],where:h,limit:f,offset:p,orderBy:m,setOperators:[]}),h=void 0,f=void 0,p=void 0,m=[]):_=I(a,c),_=this.buildSelectQuery({table:n(_,X)?_:new C(_,{},c),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:n(e,r)?L(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]})}else _=this.buildSelectQuery({table:I(a,c),fields:{},fieldsFlat:d.map(({field:e})=>({path:[],field:n(e,r)?L(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:o.tsName,sql:_,selection:d}}nestedSelectionerror(){throw new ze({message:`Views with nested selections are not supported by the relational query builder`})}buildRqbColumn(e,t,i){if(n(t,r)){let r=N`${e}.${N.identifier(this.casing.getColumnCasing(t))}`,a=t.columnType,o=t,s=0;for(;n(o,re);)o=o.baseColumn,a=o.columnType,++s;switch(a){case`PgNumeric`:case`PgNumericNumber`:case`PgNumericBigInt`:case`PgBigInt64`:case`PgBigSerial64`:case`PgTimestampString`:case`PgGeometry`:case`PgGeometryObject`:case`PgBytea`:{let e=`[]`.repeat(s);return N`${r}::text${N.raw(e).if(e)} as ${N.identifier(i)}`}case`PgCustomColumn`:return N`${o.jsonSelectIdentifier(r,N,s>0?s:void 0)} as ${N.identifier(i)}`;default:return N`${r} as ${N.identifier(i)}`}}return N`${e}.${n(t,j.Aliased)?N.identifier(t.fieldAlias):Se(t)?N.identifier(i):this.nestedSelectionerror()} as ${N.identifier(i)}`}unwrapAllColumns=(e,t)=>N.join(Object.entries(e[D]).map(([n,r])=>(t.push({key:n,field:r}),this.buildRqbColumn(e,r,n))),N`, `);buildColumns=(e,t,n)=>n?.columns?(()=>{let r=Object.entries(n.columns),i=e[D],a=[],o;for(let[n,s]of r)if(s!==void 0&&(o||=s,s)){let r=i[n];a.push(this.buildRqbColumn(e,r,n)),t.push({key:n,field:r})}if(o===!1)for(let[r,o]of Object.entries(i))n.columns[r]!==!1&&(a.push(this.buildRqbColumn(e,o,r)),t.push({key:r,field:o}));return a.length?N.join(a,N`, `):void 0})():this.unwrapAllColumns(e,t);buildRelationalQuery({schema:e,table:t,tableConfig:r,queryConfig:i,relationWhere:a,mode:o,errorPath:s,depth:c,throughJoin:l}){let u=[],d=o===`first`,f=i===!0?void 0:i,p=s??``,m=c??0;m||(t=I(t,`d${m}`));let h=d?1:f?.limit,g=f?.offset,_=f?.where&&a?V(W(t,f.where,r.relations,e,this.casing),a):f?.where?W(t,f.where,r.relations,e,this.casing):a,v=f?.orderBy?At(t,f.orderBy):void 0,y=this.buildColumns(t,u,f),b=f?.extras?jt(t,f.extras):void 0;b&&u.push(...b.selection);let x=y?[y]:[],S=f?(()=>{let{with:i}=f;if(!i)return;let a=Object.entries(i).filter(([e,t])=>t);if(a.length)return N.join(a.map(([i,a])=>{let o=r.relations[i],s=n(o,pt),c=I(o.targetTable,`d${m+1}`),l=o.throughTable?I(o.throughTable,`tr${m}`):void 0,{filter:d,joinCondition:f}=Mt(this.casing,o,t,c,l);x.push(N`${N.identifier(i)}.${N.identifier(`r`)} as ${N.identifier(i)}`);let h=l?N` inner join ${G(l)} on ${f}`:void 0,g=this.buildRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:a,tableConfig:e[o.targetTableName],relationWhere:d,errorPath:`${p.length?`${p}.`:``}${i}`,depth:m+1,throughJoin:h});return u.push({field:c,key:i,selection:g.selection,isArray:!s,isOptional:(o.optional??!1)||a!==!0&&!!a.where}),N`left join lateral(select ${s?N`row_to_json(${N.identifier(`t`)}.*) ${N.identifier(`r`)}`:N`coalesce(json_agg(row_to_json(${N.identifier(`t`)}.*)), '[]') as ${N.identifier(`r`)}`} from (${g.sql}) as ${N.identifier(`t`)}) as ${N.identifier(i)} on true`}),N` `)})():void 0;if(b?.sql&&x.push(b.sql),!x.length)throw new ze({message:`No fields selected for table "${r.name}"${p?` ("${p}")`:``}`});return{sql:N`select ${N.join(x.filter(e=>e!==void 0),N`, `)} from ${G(t)}${l}${N` ${S}`.if(S)}${N` where ${_}`.if(_)}${N` order by ${v}`.if(v)}${N` limit ${h}`.if(h!==void 0)}${N` offset ${g}`.if(g!==void 0)}`,selection:u}}},Ji=class{static[e]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},Q=class{static[e]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,r=e,i;return i=this.fields?this.fields:n(r,C)?Object.fromEntries(Object.keys(r._.selectedFields).map(e=>[e,r[e]])):n(r,Ki)?r[T].selectedFields:n(r,j)?{}:Yt(r),new Xi({table:r,fields:i,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},Yi=class extends Ji{static[e]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=q(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of $(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(r,i)=>{let a=this.tableName,o=q(r);for(let e of $(r))this.usedTables.add(e);if(typeof o==`string`&&this.config.joins?.some(e=>e.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof a==`string`&&(this.config.fields={[a]:this.config.fields}),typeof o==`string`&&!n(r,j))){let e=n(r,C)?r._.selectedFields:n(r,F)?r[T].selectedFields:r[O.Symbol.Columns];this.config.fields[o]=e}if(typeof i==`function`&&(i=i(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:r,joinType:e,alias:o,lateral:t}),typeof o==`string`)switch(e){case`left`:this.joinsNotNullableMap[o]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[o]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!1;break}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(Qi()):n;if(!Kt(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Y({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...$(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...$(e.table));return new Proxy(new C(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new Y({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Xi=class extends Yi{static[e]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=K(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};Jt(Xi,[R]);function Zi(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Kt(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}const Qi=()=>({union:$i,unionAll:ea,intersect:ta,intersectAll:na,except:ra,exceptAll:ia}),$i=Zi(`union`,!1),ea=Zi(`union`,!0),ta=Zi(`intersect`,!1),na=Zi(`intersect`,!0),ra=Zi(`except`,!1),ia=Zi(`except`,!0);var aa=class{static[e]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=n(e,qi)?e:void 0,this.dialectConfig=n(e,qi)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new pe(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new Q({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new qi(this.dialectConfig),this.dialect}},oa=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},sa=class extends oa{static[e]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new aa));let t=new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new fa({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},ca=class extends oa{static[e]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Yt(Z(e,t))}existing(){return new Proxy(new fa({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new fa({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},la=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},ua=class extends la{static[e]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new aa));let t=new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new ma({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},da=class extends la{static[e]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Yt(Z(e,t))}existing(){return new Proxy(new ma({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new ma({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Y({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},fa=class extends Ki{static[e]=`PgView`;[Pi];constructor({pgConfig:e,config:t}){super(t),e&&(this[Pi]={with:e.with})}};const pa=Symbol.for(`drizzle:PgMaterializedViewConfig`);var ma=class extends Ki{static[e]=`PgMaterializedView`;[pa];constructor({pgConfig:e,config:t}){super(t),this[pa]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function ha(e,t,n){return t?new ca(e,t,n):new sa(e,n)}function ga(e,t,n){return t?new da(e,t,n):new ua(e,n)}function _a(e,t){return ha(e,t,void 0)}function va(e,t){return ga(e,t,void 0)}function ya(e){return n(e,fa)}function ba(e){return n(e,ma)}function xa(e){let t=Object.values(e[O.Symbol.Columns]),r=[],i=[],a=[],o=Object.values(e[X.Symbol.InlineForeignKeys]),s=[],l=e[O.Symbol.Name],u=e[O.Symbol.Schema],d=[],f=e[X.Symbol.EnableRLS],p=e[X.Symbol.ExtraConfigBuilder];if(p!==void 0){let t=p(e[O.Symbol.ExtraConfigColumns]),l=Array.isArray(t)?t.flat(1):Object.values(t);for(let t of l)n(t,Ti)?r.push(t.build(e)):n(t,en)?i.push(t.build(e)):n(t,m)?s.push(t.build(e)):n(t,Mi)?a.push(t.build(e)):n(t,c)?o.push(t.build(e)):n(t,ki)&&d.push(t)}return{columns:t,indexes:r,foreignKeys:o,checks:i,primaryKeys:a,uniqueConstraints:s,name:l,schema:u,policies:d,enableRLS:f}}function $(e){return n(e,X)?[e[E]?`${e[E]}.${e[O.Symbol.BaseName]}`:e[O.Symbol.BaseName]]:n(e,C)?e._.usedTables??[]:n(e,j)?e.usedTables??[]:[]}function Sa(e){return{...e[T],...e[Pi]}}function Ca(e){return{...e[T],...e[pa]}}var wa=class extends R{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[e]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[O.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=K(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Ta=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[e]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},r=this.table[O.Symbol.Columns];for(let i of Object.keys(e)){let a=e[i];t[i]=n(a,j)?a:new M(a,r[i])}return t});return new Ea(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e==`function`?e(new aa):e;if(!n(t,j)&&!Kt(this.table[D],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new Ea(this.table,t,this.session,this.dialect,this.withList,!0)}},Ea=class extends R{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[e]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[O.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=K(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=N`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?N` where ${e.where}`:void 0;this.config.onConflict=N`(${N.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?N` where ${e.where}`:void 0,n=e.targetWhere?N` where ${e.targetWhere}`:void 0,r=e.setWhere?N` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,qt(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=N`(${N.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Da=class extends R{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[e]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},Oa=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[e]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new ka(this.table,qt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},ka=class extends R{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=q(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[e]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=q(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return n(e,X)?e[O.Symbol.Columns]:n(e,C)?e._.selectedFields:e[T].selectedFields}createJoin(e){return(t,r)=>{let i=q(t);if(typeof i==`string`&&this.config.joins.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==`function`){let e=this.config.from&&!n(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;r=r(new Proxy(this.config.table[O.Symbol.Columns],new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new Y({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:r,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1;break}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[O.Symbol.Columns]),this.config.from)){let t=q(this.config.from);typeof t==`string`&&this.config.from&&!n(this.config.from,j)&&(e[t]=this.getTableLikeFields(this.config.from));for(let t of this.config.joins){let r=q(t.table);typeof r==`string`&&!n(t.table,j)&&(e[r]=this.getTableLikeFields(t.table))}}return this.config.returningFields=e,this.config.returning=K(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Y({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Aa=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[e]=`PgRelationalQueryBuilder`;findMany(e){return new ja(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new ja(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},ja=class extends R{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[e]=`PgRelationalQuery`;_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>Vi(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect._buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Ma=class t extends j{constructor(e){super(t.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=t.buildCount(e.source,e.filters)}sql;token;static[e]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return N`(select count(*) from ${e}${N.raw(` where `).if(t)}${t})`}static buildCount(e,t){return N`select count(*) as count from ${e}${N.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},Na=class{constructor(e,t,n,r,i){this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i}static[e]=`PgRelationalQueryBuilderV2`;findMany(e){return new Pa(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`many`)}findFirst(e){return new Pa(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`first`)}},Pa=class extends R{constructor(e,t,n,r,i,a,o){super(),this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i,this.config=a,this.mode=o}static[e]=`PgRelationalQueryV2`;_prepare(e){return w.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareRelationalQuery(n,void 0,e,(e,n)=>{let r=e.map(e=>yt(e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQuery({schema:this.schema,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,mode:this.mode})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return w.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Fa=class extends R{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[e]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},Ia=class{constructor(e,t,n,r){if(this.dialect=e,this.session=t,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap,relations:n,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},relations:n,session:t},this._query={},this._.schema)for(let[n,i]of Object.entries(this._.schema))this._query[n]=new Aa(r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[n],i,e,t);this.query={};for(let[r,i]of Object.entries(n))this.query[r]=new Na(n,n[i.name].table,i,e,t);this.$cache={invalidate:async e=>{}}}static[e]=`PgDatabase`;_query;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new aa(n.dialect))),new Proxy(new pe(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Y({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new Ma({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new Q({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new Oa(n,t.session,t.dialect,e)}function o(n){return new Ta(n,t.session,t.dialect,e)}function s(n){return new wa(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Oa(e,this.session,this.dialect)}insert(e){return new Ta(e,this.session,this.dialect)}delete(e){return new wa(e,this.session,this.dialect)}refreshMaterializedView(e){return new Da(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?N.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new Fa(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}};const La=(e,t,n=()=>t[Math.floor(Math.random()*t.length)])=>{let r=(...e)=>n(t).select(...e),i=(...e)=>n(t).selectDistinct(...e),a=(...e)=>n(t).selectDistinctOn(...e),o=(...e)=>n(t).$count(...e),s=(...e)=>n(t).with(...e),c=e=>n(t).$with(e),l=(...t)=>e.update(...t),u=(...t)=>e.insert(...t),d=(...t)=>e.delete(...t),f=(...t)=>e.execute(...t),p=(...t)=>e.transaction(...t),m=(...t)=>e.refreshMaterializedView(...t);return{...e,update:l,insert:u,delete:d,execute:f,transaction:p,refreshMaterializedView:m,$primary:e,select:r,selectDistinct:i,selectDistinctOn:a,$count:o,$with:c,with:s,get _query(){return n(t)._query},get query(){return n(t).query}}};var Ra=class{constructor(e,t){this.name=e,t&&(this.createDb=t.createDb,this.createRole=t.createRole,this.inherit=t.inherit)}static[e]=`PgRole`;_existing;createDb;createRole;inherit;existing(){return this._existing=!0,this}};function za(e,t){return new Ra(e,t)}var Ba=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[e]=`PgSequence`};function Va(e,t){return Ha(e,t,void 0)}function Ha(e,t,n){return new Ba(e,t,n)}function Ua(e){return n(e,Ba)}var Wa=class{constructor(e){this.schemaName=e}static[e]=`PgSchema`;table=(e,t,n)=>Si(e,t,n,this.schemaName);view=(e,t)=>ha(e,t,this.schemaName);materializedView=(e,t)=>ga(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?de(e,[...t],this.schemaName):fe(e,t,this.schemaName)}sequence=(e,t)=>Ha(e,t,this.schemaName);getSQL(){return new j([N.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function Ga(e){return n(e,Wa)}function Ka(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new Wa(e)}function qa(){let e=Z(`accounts`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),accessToken:e.text(`access_token`),accessTokenExpiresAt:e.timestamp(`access_token_expires_at`,{withTimezone:!0}),accountId:e.text(`account_id`).notNull(),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),idToken:e.text(`id_token`),providerId:e.text(`provider_id`).notNull(),password:e.text(`password`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),refreshToken:e.text(`refresh_token`),refreshTokenExpiresAt:e.timestamp(`refresh_token_expires_at`,{withTimezone:!0}),scope:e.text(`scope`),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),t=Z(`api_keys`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`),enabled:e.boolean(`enabled`).default(!0),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}),key:e.text(`key`).notNull(),lastRefillAt:e.timestamp(`last_refill_at`,{withTimezone:!0}),lastRequest:e.timestamp(`last_request`,{withTimezone:!0}),lastUsedAt:e.timestamp(`last_used_at`,{withTimezone:!0}),metadata:e.text(`metadata`),permissions:e.text(`permissions`),prefix:e.text(`prefix`),rateLimitEnabled:e.boolean(`rate_limit_enabled`).default(!0),rateLimitTimeWindow:e.integer(`rate_limit_time_window`).default(864e5),rateLimitMax:e.integer(`rate_limit_max`).default(10),refillInterval:e.integer(`refill_interval`),refillAmount:e.integer(`refill_amount`),requestCount:e.integer(`request_count`),remaining:e.integer(`remaining`),start:e.text(`start`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),n=Z(`invitations`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),email:e.text(`email`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),inviterId:e.text(`inviter_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`),status:e.text(`status`).default(`pending`).notNull(),teamId:e.text(`team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),r=Z(`members`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`).default(`member`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),i=Z(`organizations`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`).notNull(),slug:e.text(`slug`).unique(),logo:e.text(`logo`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),metadata:e.text(`metadata`)}),e=>[]),a=Z(`sessions`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),activeOrganizationId:e.text(`active_organization_id`).references(()=>i.id,{onDelete:`set null`}),activeTeamId:e.text(`active_team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),impersonatedBy:e.text(`impersonated_by`).references(()=>s.id,{onDelete:`set null`}),ipAddress:e.text(`ip_address`),token:e.text(`token`).notNull().unique(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),userAgent:e.text(`user_agent`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),o=Z(`sso_providers`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),domain:e.text(`domain`).notNull(),issuer:e.text(`issuer`).notNull(),oidcConfig:e.text(`oidc_config`),organizationId:e.text(`organization_id`).references(()=>i.id,{onDelete:`cascade`}),providerId:e.text(`provider_id`).notNull().unique(),samlConfig:e.text(`saml_config`),userId:e.text(`user_id`).references(()=>s.id,{onDelete:`cascade`})}),e=>[]),s=Z(`users`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),banExpires:e.timestamp(`ban_expires`,{withTimezone:!0}),banReason:e.text(`ban_reason`),banned:e.boolean(`banned`).default(!1),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),displayUsername:e.text(`display_username`),email:e.text(`email`).notNull().unique(),emailVerified:e.boolean(`email_verified`).default(!1).notNull(),image:e.text(`image`),isAnonymous:e.boolean(`is_anonymous`),lastLoginMethod:e.text(`last_login_method`),name:e.text(`name`).notNull(),phoneNumber:e.text(`phone_number`).unique(),phoneNumberVerified:e.boolean(`phone_number_verified`),role:e.text(`role`),twoFactorEnabled:e.boolean(`two_factor_enabled`).default(!1),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),username:e.text(`username`).unique()}),e=>[]),c=Z(`teams`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`).notNull(),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]);return{tables:{accounts:e,apiKeys:t,invitations:n,members:r,organizations:i,sessions:a,ssoProviders:o,teams:c,teamMembers:Z(`team_members`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),teamId:e.text(`team_id`).notNull().references(()=>c.id,{onDelete:`cascade`}),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),twoFactors:Z(`two_factors`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),secret:e.text(`secret`).notNull(),backupCodes:e.text(`backup_codes`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),users:s,verifications:Z(`verifications`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),identifier:e.text(`identifier`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),value:e.text(`value`).notNull()}),e=>[])},relations:e=>({users:{sessions:e.many.sessions({from:e.users.id,to:e.sessions.userId}),accounts:e.many.accounts({from:e.users.id,to:e.accounts.userId}),apiKeys:e.many.apiKeys({from:e.users.id,to:e.apiKeys.userId}),memberships:e.many.members({from:e.users.id,to:e.members.userId}),invitations:e.many.invitations({from:e.users.id,to:e.invitations.inviterId}),ssoProvider:e.one.ssoProviders({from:e.users.id,to:e.ssoProviders.userId}),twoFactor:e.one.twoFactors({from:e.users.id,to:e.twoFactors.userId})},sessions:{user:e.one.users({from:e.sessions.userId,to:e.users.id})},accounts:{user:e.one.users({from:e.accounts.userId,to:e.users.id})},apiKeys:{user:e.one.users({from:e.apiKeys.userId,to:e.users.id})},organizations:{members:e.many.members({from:e.organizations.id,to:e.members.organizationId}),invitations:e.many.invitations({from:e.organizations.id,to:e.invitations.organizationId}),teams:e.many.teams({from:e.organizations.id,to:e.teams.organizationId})},members:{organization:e.one.organizations({from:e.members.organizationId,to:e.organizations.id}),user:e.one.users({from:e.members.userId,to:e.users.id})},invitations:{organization:e.one.organizations({from:e.invitations.organizationId,to:e.organizations.id}),inviter:e.one.users({from:e.invitations.inviterId,to:e.users.id})},teams:{organization:e.one.organizations({from:e.teams.organizationId,to:e.organizations.id})},ssoProviders:{user:e.one.users({from:e.ssoProviders.userId,to:e.users.id})},verifications:{},twoFactors:{user:e.one.users({from:e.twoFactors.userId,to:e.users.id})}})}}function Ja(){let e=Z(`storage_blobs`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),key:e.text(`key`).notNull().unique(),filename:e.text(`filename`).notNull(),contentType:e.text(`content_type`),metadata:e.jsonb(`metadata`),serviceName:e.text(`service_name`).notNull().default(`private`),byteSize:e.bigint(`byte_size`,{mode:`number`}).notNull(),checksum:e.text(`checksum`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[Di(`storage_blobs_key_idx`).on(e.key),Di(`storage_blobs_service_name_idx`).on(e.serviceName)]);return{tables:{storageBlobs:e,storageAttachments:Z(`storage_attachments`,t=>({id:t.text(`id`).primaryKey().default(N`uuidv7()`),name:t.text(`name`).notNull(),recordType:t.text(`record_type`).notNull(),recordId:t.text(`record_id`).notNull(),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).notNull().default(N`NOW()`)}),e=>[Di(`storage_attachments_record_idx`).on(e.recordType,e.recordId),Di(`storage_attachments_blob_id_idx`).on(e.blobId)]),storageVariantRecords:Z(`storage_variant_records`,t=>({id:t.text(`id`).primaryKey().default(N`uuidv7()`),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),variationDigest:t.text(`variation_digest`).notNull(),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[Di(`storage_variant_records_blob_id_idx`).on(e.blobId),f(`storage_variant_records_unique`).on(e.blobId,e.variationDigest)])},relations:e=>({storageBlobs:{attachments:e.many.storageAttachments({from:e.storageBlobs.id,to:e.storageAttachments.blobId}),variantRecords:e.many.storageVariantRecords({from:e.storageBlobs.id,to:e.storageVariantRecords.blobId})},storageAttachments:{blob:e.one.storageBlobs({from:e.storageAttachments.blobId,to:e.storageBlobs.id})},storageVariantRecords:{blob:e.one.storageBlobs({from:e.storageVariantRecords.blobId,to:e.storageBlobs.id})}})}}Ja();export{ht as AggregatedField,tn as Check,en as CheckBuilder,l as ForeignKey,c as ForeignKeyBuilder,Ei as Index,Ti as IndexBuilder,wi as IndexBuilderOn,te as IndexedColumn,M as Param,re as PgArray,ne as PgArrayBuilder,on as PgBigInt53,an as PgBigInt53Builder,cn as PgBigInt64,sn as PgBigInt64Builder,dn as PgBigSerial53,un as PgBigSerial53Builder,pn as PgBigSerial64,fn as PgBigSerial64Builder,ci as PgBinaryVector,si as PgBinaryVectorBuilder,gn as PgBoolean,hn as PgBooleanBuilder,yn as PgBytea,vn as PgByteaBuilder,Sn as PgChar,xn as PgCharBuilder,Tn as PgCidr,wn as PgCidrBuilder,S as PgColumn,x as PgColumnBuilder,On as PgCustomColumn,Dn as PgCustomColumnBuilder,Ia as PgDatabase,Mn as PgDate,jn as PgDateBuilder,Pn as PgDateString,Nn as PgDateStringBuilder,wa as PgDeleteBase,qi as PgDialect,Or as PgGeometry,Dr as PgGeometryBuilder,Ar as PgGeometryObject,kr as PgGeometryObjectBuilder,di as PgHalfVector,ui as PgHalfVectorBuilder,Ta as PgInsertBuilder,Un as PgInteger,Hn as PgIntegerBuilder,Yn as PgJson,Jn as PgJsonBuilder,Qn as PgJsonb,Zn as PgJsonbBuilder,rr as PgLineABC,nr as PgLineABCBuilder,er as PgLineBuilder,or as PgMacaddr,lr as PgMacaddr8,cr as PgMacaddr8Builder,ar as PgMacaddrBuilder,pa as PgMaterializedViewConfig,fr as PgNumeric,gr as PgNumericBigInt,hr as PgNumericBigIntBuilder,dr as PgNumericBuilder,mr as PgNumericNumber,pr as PgNumericNumberBuilder,Nr as PgReal,Mr as PgRealBuilder,X as PgTable,Gr as PgText,Wr as PgTextBuilder,P as Placeholder,Ni as PrimaryKey,aa as QueryBuilder,H as Relation,j as SQL,C as Subquery,O as Table,Pe as TableAliasProxyHandler,g as UniqueConstraint,m as UniqueConstraintBuilder,h as UniqueOnConstraintBuilder,T as ViewBaseConfig,pe as WithSubquery,$t as alias,Ie as aliasedRelation,I as aliasedTable,L as aliasedTableColumn,V as and,ot as arrayContained,at as arrayContains,st as arrayOverlaps,ct as asc,Ft as avg,It as avgDistinct,$e as between,ln as bigint,mn as bigserial,z as bindIfParam,li as bit,_n as boolean,dt as buildRelations,ft as buildRelationsParts,bn as bytea,Cn as char,nn as check,En as cidr,Ut as cosineDistance,Nt as count,Pt as countDistinct,wt as createRelationsHelper,kn as customType,Fn as date,vr as decimal,qa as defineAuthSchema,Et as defineRelations,Dt as defineRelationsPart,Ja as defineStorageSchema,lt as desc,Rn as doublePrecision,e as entityKind,B as eq,ra as except,ia as exceptAll,Ze as exists,a as extractExtendedColumnType,Tt as extractTablesFromSchema,$ as extractUsedTable,ke as fillPlaceholders,u as foreignKey,jr as geometry,i as getColumnTable,Ca as getMaterializedViewConfig,vt as getOrderByOperators,G as getTableAsAliasSQL,Yt as getTableColumns,xa as getTableConfig,k as getTableName,xe as getTableUniqueName,Sa as getViewConfig,Me as getViewName,Xt as getViewSelectedFields,Ue as gt,We as gte,fi as halfvec,Wt as hammingDistance,t as hasOwnEntityKind,Kt as haveSameKeys,rt as ilike,qe as inArray,Di as index,Vn as inet,Ht as innerProduct,Wn as integer,ta as intersect,na as intersectAll,qn as interval,n as is,Zt as isConfig,Te as isDriverValueEncoder,Xe as isNotNull,Ye as isNull,se as isPgEnum,ba as isPgMaterializedView,Ga as isPgSchema,Ua as isPgSequence,ya as isPgView,Se as isSQLWrapper,be as isTable,je as isView,Gt as jaccardDistance,Xn as json,$n as jsonb,Vt as l1Distance,Bt as l2Distance,tt as like,ir as line,Ge as lt,Ke as lte,sr as macaddr,ur as macaddr8,b as makePgArray,Le as mapColumnsInAliasedSQLToAlias,Re as mapColumnsInSQLToAlias,Be as ne,Ee as noopDecoder,De as noopEncoder,Oe as noopMapper,He as not,et as notBetween,Qe as notExists,it as notIlike,Je as notInArray,nt as notLike,_r as numeric,U as operators,Ve as or,_t as orderByOperators,y as parsePgArray,v as parsePgNestedArray,ue as pgEnum,va as pgMaterializedView,Ai as pgPolicy,za as pgRole,Ka as pgSchema,Va as pgSequence,Z as pgTable,Ci as pgTableCreator,_a as pgView,Cr as point,ji as primaryKey,ut as processRelations,Pr as real,jt as relationExtrasToSQL,Mt as relationToSQL,W as relationsFilterToSQL,At as relationsOrderToSQL,Lr as serial,Br as smallint,Ur as smallserial,hi as sparsevec,N as sql,Lt as sum,Rt as sumDistinct,Kr as text,Qt as textDecoder,Yr as time,ei as timestamp,$i as union,ea as unionAll,f as unique,Oi as uniqueIndex,p as uniqueKeyName,ri as uuid,La as withReplicas};
|
package/build/exports/zod.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export { z };
|