@decaf-ts/for-typeorm 0.2.27 → 0.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,7 +34,7 @@ A thin, focused TypeORM-backed adapter that plugs Decaf.ts models, repositories
34
34
 
35
35
  Documentation available [here](https://decaf-ts.github.io/ts-workspace/)
36
36
 
37
- Minimal size: 13.5 KB kb gzipped
37
+ Minimal size: 14.5 KB kb gzipped
38
38
 
39
39
 
40
40
  # Decaf.ts for TypeORM — Detailed Description
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,n,o,s,i){"use strict";const c=/^(select|from|where|and|or|insert|update|delete|drop|create|table|index|primary|key|foreign|references|constraint|unique|check|default|null|not|as|order|by|group|having|limit|offset|join|inner|outer|left|right|full|on|using|values|returning|set|into|case|when|then|else|end|cast|coalesce|exists|any|all|some|in|between|like|ilike|similar|to|is|true|false|asc|desc|distinct|union|intersect|except|natural|lateral|window|over|partition|range|rows|unbounded|preceding|following|current|row|with|recursive|materialized|view|function|trigger|procedure|language|returns|return|declare|begin|commit|rollback|savepoint|transaction|temporary|temp|if|loop|while|for|continue|exit|raise|exception|notice|info|log|debug|assert|execute|perform|get|diagnostics|call|do|alias|comment|vacuum|analyze|explain|copy|grant|revoke|privileges|public|usage|schema|sequence|owned|owner|tablespace|storage|inherits|type|operator|collate|collation|cascade|restrict|add|alter|column|rename|to|enable|disable|force|no|instead|of|before|after|each|statement|row|execute|also|only|exclude|nulls|others|ordinality|ties|nothing|cache|cycle|increment|minvalue|maxvalue|start|restart|by|called|returns|language|immutable|stable|volatile|strict|security|definer|invoker|cost|rows|support|handler|inline|validator|options|storage|inheritance|oids|without|data|dictionary|encoding|lc_collate|lc_ctype|connection|limit|password|valid|until|superuser|nosuperuser|createdb|nocreatedb|createrole|nocreaterole|inherit|noinherit|login|nologin|replication|noreplication|bypassrls|nobypassrls|encrypted|unencrypted|new|old|session_user|current_user|current_role|current_schema|current_catalog|current_date|current_time|current_timestamp|localtime|localtimestamp|current_database|inet|cidr|macaddr|macaddr8|bit|varbit|tsvector|tsquery|uuid|xml|json|jsonb|int|integer|smallint|bigint|decimal|numeric|real|double|precision|float|boolean|bool|char|character|varchar|text|bytea|date|time|timestamp|interval|point|line|lseg|box|path|polygon|circle|money|void)$/i,l="type-orm",d={SEPARATOR:".",ID:"id",VERSION:"version",DELETED:"deleted_at",TABLE:"table_name",SCHEMA:"schema_name",SEQUENCE:"sequence_name",INDEX:"index"};class p extends n.BaseError{constructor(e){super(p.name,e,404)}}var u;e.SQLOperator=void 0,(u=e.SQLOperator||(e.SQLOperator={})).EQUAL="=",u.NOT_EQUAL="<>",u.LESS_THAN="<",u.LESS_THAN_OR_EQUAL="<=",u.GREATER_THAN=">",u.GREATER_THAN_OR_EQUAL=">=",u.IN="IN",u.NOT_IN="NOT IN",u.LIKE="LIKE",u.ILIKE="ILIKE",u.BETWEEN="BETWEEN",u.IS_NULL="IS NULL",u.IS_NOT_NULL="IS NOT NULL",u.EXISTS="EXISTS",u.NOT_EXISTS="NOT EXISTS",u.ANY="ANY",u.ALL="ALL",u.SOME="SOME";const h={EQUAL:e.SQLOperator.EQUAL,DIFFERENT:e.SQLOperator.NOT_EQUAL,BIGGER:e.SQLOperator.GREATER_THAN,BIGGER_EQ:e.SQLOperator.GREATER_THAN_OR_EQUAL,SMALLER:e.SQLOperator.LESS_THAN,SMALLER_EQ:e.SQLOperator.LESS_THAN_OR_EQUAL,BETWEEN:e.SQLOperator.BETWEEN,NOT:"NOT",IN:e.SQLOperator.IN,IS_NULL:e.SQLOperator.IS_NULL,IS_NOT_NULL:e.SQLOperator.IS_NOT_NULL,REGEXP:"~",IREGEXP:"~*",LIKE:e.SQLOperator.LIKE,ILIKE:e.SQLOperator.ILIKE,STARTS_WITH:e.SQLOperator.LIKE,ENDS_WITH:e.SQLOperator.LIKE},y={AND:"AND",OR:"OR"};class g extends a.Paginator{get total(){return this._totalPages}get count(){return this._recordCount}get repo(){return this.__repo||(this.__repo=this.adapter.client.getRepository(t.Metadata.constr(this.clazz))),this.__repo}constructor(e,t,r,a){super(e,t,r,a)}prepare(e){return{...e}}async page(e=1,...t){const{ctxArgs:r,ctx:n}=this.adapter.logCtx(t,this.page);if(this.isPreparedStatement())return this.pagePrepared(e,...r);const o={...this.statement};this._recordCount&&this._totalPages||(this._totalPages=this._recordCount=0);const i=Object.assign(o,{skip:(this.current||0)*this.size,take:this.size}),c=await this.repo.findAndCount(i);if(this._recordCount=c[1],this._totalPages=Math.ceil(this._recordCount/this.size),!this.clazz)throw new a.PagingError("No statement target defined");const l=s.Model.pk(this.clazz),d=(c[0]||[]).map(e=>this.adapter.revert(e,this.clazz,e[l],void 0,n));return this._currentPage=e,d}}function E(e){for(const t of[h,y]){const r=Object.keys(t).find(t=>t===e);if(r)return t[r]}throw new a.QueryError("Could not find adapter translation for operator "+e)}function f(e){const t=RegExp(/^\/(.+)\/(\w+)$/g);if("string"==typeof e){const r=t.exec(e);if(r){const[,t]=r;e=t}}return("string"==typeof e?RegExp(e):e).source}function m(e,r={}){const a=s.Model.relations(e);if(r[e.name]=r[e.name]||void 0,r[e.name])return r[e.name];const i=a.reduce((a,s)=>{const i=t.Metadata.relations(e,s),c=i.populate;let l=i.class;if(o.isClass(l)||(l=l()),!l)throw new n.InternalError(`Could not find class for property ${s} on model ${e.name}`);if(c?a.relations.push(s):a.nonEager.push(s),a.relations.includes(s)){const{nonEager:e,relations:t}=m(l,r);if(e.length&&a.relations.includes(s)){const t=e.map(e=>`${s}.${e}`);a.nonEager.push(...t)}if(t.length){const e=t.map(e=>`${s}.${e}`);a.relations.push(...e)}}return a},{nonEager:[],relations:[]});return r[e.name]=i,i}class A extends a.Statement{constructor(e){super(e)}build(){const e=this.log.for(this.build),r=s.Model.tableName(this.fromSelector),n={query:this.adapter.client.getRepository(t.Metadata.constr(this.fromSelector)).createQueryBuilder(r)};if(void 0!==this.countSelector){const e=null===this.countSelector?"*":`${r}.${this.countSelector}`;n.query=n.query.select(`COUNT(${e})`,"count")}else if(void 0!==this.countDistinctSelector){const e=null===this.countDistinctSelector?"*":`${r}.${this.countDistinctSelector}`;n.query=n.query.select(`COUNT(DISTINCT ${e})`,"count")}else this.sumSelector?n.query=n.query.select(`SUM(${r}.${this.sumSelector})`,"sum"):this.avgSelector?n.query=n.query.select(`AVG(${r}.${this.avgSelector})`,"avg"):this.maxSelector?n.query=n.query.select(`MAX(${r}.${this.maxSelector})`,"max"):this.minSelector?n.query=n.query.select(`MIN(${r}.${this.minSelector})`,"min"):this.distinctSelector?n.query=n.query.select(`DISTINCT ${r}.${this.distinctSelector}`,this.distinctSelector):this.selectSelector?n.query=n.query.select(this.selectSelector.map(e=>`${r}.${e}`)):n.query=n.query.select();if(this.whereCondition&&(n.query=this.parseCondition(this.whereCondition,r,n.query).query),this.groupBySelectors&&this.groupBySelectors.length){const[e,...t]=this.groupBySelectors;n.query=n.query.groupBy(`${r}.${e}`);for(const e of t)n.query=n.query.addGroupBy(`${r}.${e}`)}const o=this.hasAggregation();if(o){if(this.orderBySelectors&&this.orderBySelectors.length){const[e,t]=this.orderBySelectors[0];n.query=n.query.orderBy(`${r}.${e}`,t.toUpperCase());for(let e=1;e<this.orderBySelectors.length;e++){const[t,a]=this.orderBySelectors[e];n.query=n.query.addOrderBy(`${r}.${t}`,a.toUpperCase())}}}else if(this.orderBySelectors&&this.orderBySelectors.length){const[e,t]=this.orderBySelectors[0];n.query=n.query.orderBy(`${r}.${e}`,t.toUpperCase());for(let e=1;e<this.orderBySelectors.length;e++){const[t,a]=this.orderBySelectors[e];n.query=n.query.addOrderBy(`${r}.${t}`,a.toUpperCase())}}else n.query=n.query.orderBy(`${r}.${s.Model.pk(this.fromSelector)}`,a.OrderDirection.ASC.toUpperCase());return o?this.limitSelector&&(n.query=n.query.limit(this.limitSelector)):this.limitSelector?n.query=n.query.limit(this.limitSelector):(e.debug("No limit selector defined. Using default limit of 250"),n.query=n.query.limit(250)),this.offsetSelector&&(n.query=n.query.skip(this.offsetSelector)),n}async paginate(e){try{const t={};if(this.whereCondition&&(t.where=this.parseConditionForPagination(this.whereCondition,s.Model.tableName(this.fromSelector))),this.orderBySelectors&&this.orderBySelectors.length){const e={};for(const[t,r]of this.orderBySelectors)e[t]=r.toString().toUpperCase();t.order=e}return this.adapter.Paginator(t,e,this.fromSelector)}catch(e){throw new a.QueryError(e)}}async raw(e,...t){const{ctx:r}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new a.UnsupportedError("Raw statements are not allowed in the current configuration");const n=e.query;if(this.hasAggregation()){if(this.groupBySelectors&&this.groupBySelectors.length){const e=await n.getRawMany();return this.groupResults(e)}{const e=await n.getRawOne();return void 0!==this.countSelector||void 0!==this.countDistinctSelector?Number(e?.count||0):this.sumSelector?Number(e?.sum||0):this.avgSelector?Number(e?.avg||0):this.maxSelector?e?.max:this.minSelector?e?.min:this.distinctSelector?(await n.getRawMany()).map(e=>e[this.distinctSelector]):e}}const{nonEager:o}=m(this.fromSelector);return e.query=n.setFindOptions({loadEagerRelations:!0,loadRelationIds:{relations:o}}),await e.query.getMany()}groupResults(e){if(!this.groupBySelectors||!this.groupBySelectors.length)return e;const t=s.Model.tableName(this.fromSelector),r=this.groupBySelectors.map(e=>`${t}_${e}`),a={};for(const t of e){let e=a;for(let a=0;a<r.length-1;a++){const n=t[r[a]];e[n]||(e[n]={}),e=e[n]}const n=t[r[r.length-1]];e[n]||(e[n]=[]),e[n].push(t)}return a}parseConditionForPagination(e,t,r=0,n){const{attr1:o,operator:s,comparison:i}=e,c=()=>{if("string"!=typeof o)throw new a.QueryError("Invalid attribute for pagination condition");return{[o]:this.buildFindValue(s,i)}};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(s))return c();if(s===a.GroupOperator.OR){const e=o instanceof a.Condition?this.parseConditionForPagination(o,t,++r,n):c(),s=i instanceof a.Condition?this.parseConditionForPagination(i,t,++r,n):c(),l=e=>Array.isArray(e)?e:e?[e]:[];return[...l(e),...l(s)]}if(s===a.GroupOperator.AND){const e=o instanceof a.Condition?this.parseConditionForPagination(o,t,++r,n):c(),s=i instanceof a.Condition?this.parseConditionForPagination(i,t,++r,n):c();if(Array.isArray(e)||Array.isArray(s))throw new a.QueryError("AND conditions with OR branches are not supported in pagination");return{...e||{},...s||{}}}throw new a.QueryError("NOT operator is not supported for pagination")}buildFindValue(e,t){switch(e){case a.Operator.STARTS_WITH:return i.Like(t+"%");case a.Operator.ENDS_WITH:return i.Like("%"+t);case a.Operator.REGEXP:return i.Raw(e=>e+" ~ :regex",{regex:t});case a.Operator.IN:return i.In(Array.isArray(t)?t:[t]);case a.Operator.BETWEEN:if(!Array.isArray(t)||2!==t.length)throw new a.QueryError("BETWEEN operator requires an array with two values");return i.Between(t[0],t[1]);case a.Operator.BIGGER:return i.MoreThan(t);case a.Operator.BIGGER_EQ:return i.MoreThanOrEqual(t);case a.Operator.SMALLER:return i.LessThan(t);case a.Operator.SMALLER_EQ:return i.LessThanOrEqual(t);default:return t}}parseCondition(e,t,r,n=0,o){const{attr1:s,operator:i,comparison:c}=e;if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(i))return(()=>{const e=E(i),l=`${s}${n}`;let d,p;if(i===a.Operator.BETWEEN){const[r,a]=c,o=`${s}${n}_min`,i=`${s}${n}_max`;d=`${t}.${s} ${e} :${o} AND :${i}`,p={[o]:r,[i]:a}}else if(i===a.Operator.IN)d=`${t}.${s} ${e} (:...${l})`,p={[l]:c};else{if((i===a.Operator.STARTS_WITH||i===a.Operator.ENDS_WITH)&&"string"!=typeof c)throw new a.QueryError(`Operator ${i} requires a string comparison value`);const r=i===a.Operator.STARTS_WITH?c+"%":i===a.Operator.ENDS_WITH?"%"+c:c;d=`${t}.${s} ${e} :${l}`,p={[l]:r}}switch(o){case a.GroupOperator.AND:return{query:r.andWhere(d,p)};case a.GroupOperator.OR:return{query:r.orWhere(d,p)};case a.Operator.NOT:throw Error("NOT operator not implemented");default:return{query:r.where(d,p)}}})();if(i===a.Operator.NOT)throw Error("NOT operator not implemented");return r=this.parseCondition(s,t,r,++n).query,this.parseCondition(c,t,r,++n,i)}}class O extends a.Sequence{constructor(e,t){super(e,t)}async current(...e){const{ctx:t}=(await this.logCtx(e,n.OperationKeys.READ,!0)).for(this.current),{name:r,startWith:a}=this.options;try{if(!r)throw new n.InternalError("Sequence name is required to read current");const e=`"${r.replace(/"/g,'""')}"`,a=await this.adapter.raw({query:`SELECT last_value, is_called FROM ${e};`,values:[]},!0,t);if(!Array.isArray(a)||0===a.length)throw new n.InternalError("Failed to read current value for "+r);const o=a[0];return this.parse(o.last_value)}catch(e){if(e instanceof n.NotFoundError){if(void 0===a)throw new n.InternalError("Starting value is not defined for a non existing sequence");return this.parse(a)}throw this.adapter.parseError(e)}}async increment(e,t){const{type:r,incrementBy:a,name:o,startWith:s,minValue:i,maxValue:c,cycle:l}=this.options;if("Number"!==r&&"BigInt"!==r)throw new n.InternalError(`Cannot increment sequence of type ${r} with ${e}`);if(!o)throw new n.InternalError("Cannot increment sequence without a name: "+o);try{const s=e??a;if(s%a!==0)throw new n.InternalError("Value to increment does not consider the incrementBy setting: "+a);const i=await this.current(t),c="BigInt"===r?this.parse(i)+BigInt(s):this.parse(i)+s;return await this.adapter.raw({query:"SELECT setval($1::regclass, $2, true) AS nextval;",values:[o,c]},!0,t),c}catch(d){if(!(d instanceof n.NotFoundError))throw d;const p=`"${o.replace(/"/g,'""')}"`,u="number"==typeof s?s:a,h="number"==typeof i?" MINVALUE "+i:"number"==typeof s&&1>s?" MINVALUE "+s:"",y="number"==typeof c?" MAXVALUE "+c:"",g=l?" CYCLE":" NO CYCLE";await this.adapter.raw({query:`CREATE SEQUENCE IF NOT EXISTS ${p} START WITH ${u} INCREMENT BY ${a}${h}${y}${g};`,values:[]},!0,t);const E=e??a;if(E%a!==0)throw new n.InternalError("Value to increment does not consider the incrementBy setting: "+a);const f="number"==typeof s?s:this.parse(s),m="BigInt"===r?this.parse(f)+BigInt(E):this.parse(f)+E;return await this.adapter.raw({query:"SELECT setval($1::regclass, $2, true) AS nextval;",values:[o,m]},!0,t),m}}async next(...e){const{ctx:t}=(await this.logCtx(e,n.OperationKeys.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r}=(await this.logCtx(t,n.OperationKeys.UPDATE,!0)).for(this.range),a=await this.current(r),o=this.parse(this.options.incrementBy),s=await this.increment(this.parse(e)*o,r),i=[];for(let t=1;e>=t;t++)i.push(a+o*this.parse(t));if(i[i.length-1]!==s)throw new n.InternalError("Miscalculation of range");return i}}function w(e,t,r,a=n.DefaultSeparator){return[...e.map(e=>e===d.TABLE?"table":e),d.INDEX].join(a)}function S(e){const t=w([d.TABLE]),r={};return r[t]={query:"",values:[]},e.forEach(e=>{const t=s.Model.indexes(e);Object.entries(t).forEach(([t,o])=>{const i=Object.keys(o)[0];let{compositions:c}=o[i];const l=s.Model.tableName(e);c=c||[],(()=>{const e=[t,...c,a.PersistenceKeys.INDEX].join(n.DefaultSeparator);r[e]={query:"CREATE INDEX $1 ON $2 ($3);",values:[e,l,t]}})()});let o=[];try{o=s.Model.defaultQueryAttributes(e)}catch(e){o=[]}o.forEach(t=>{const a=w([s.Model.tableName(e),t,"defaultQuery"]);r[a]={query:`CREATE INDEX ${a} ON ${s.Model.tableName(e)} (${t});`,values:[]}})}),Object.values(r)}async function N(e,r,o,i,c,l){async function d(e,t){const o=a.Repository.forModel(e.constructor);await N(o,r,e,t||i!==n.OperationKeys.UPDATE?i:n.OperationKeys.CREATE,c,t)}await n.enforceDBDecorators(e,r,o,i,c,l);for(const e of Object.keys(o))s.Model.isPropertyModel(o,e)&&void 0!==o[e]?await d(o[e],l?l[e]:void 0):t.Metadata.validationFor(o.constructor,e,s.ValidationKeys.LIST)&&o[e]&&Array.isArray(o[e])&&await Promise.all(o[e].map((t,r)=>d(t,l&&l[e]?l[e][r]:void 0)))}class T extends a.Repository{constructor(e,t,...r){super(e,t,...r),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!1,ignoreHandlers:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1})}queryBuilder(){return this.nativeRepo().createQueryBuilder()}nativeRepo(){const e=t.Metadata.constr(this.class);return this.adapter.dataSource.getRepository(e)}async createPrefix(e,...t){const{ctx:r,ctxArgs:a,log:o}=(await this.logCtx(t,n.OperationKeys.CREATE,!0)).for(this.createPrefix),s=r.get("ignoreHandlers"),i=r.get("ignoreValidation");if(o.silly(`handlerSetting: ${s}, validationSetting: ${i}`),e=new this.class(e),s||await N(this,r,e,n.OperationKeys.CREATE,n.OperationKeys.ON),!i){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const a=await Promise.resolve(e.hasErrors(...t));if(a)throw new n.ValidationError(a.toString())}return[e,...a]}async create(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.create);n.debug(`Creating new ${this.class.name} in table ${s.Model.tableName(this.class)}`);let{record:i,id:c,transient:l}=this.adapter.prepare(e,!1,a);return i=await this.adapter.create(t.Metadata.constr(this.class),c,e,...o),this.adapter.revert(i,this.class,c,l,a)}async createSuffix(e,t){return t.get("ignoreHandlers")||await N(this,t,e,n.OperationKeys.CREATE,n.OperationKeys.AFTER),e}async readPrefix(e,...t){const{ctx:r,ctxArgs:a,log:o}=(await this.logCtx(t,n.OperationKeys.READ,!0)).for(this.readPrefix),s=r.get("ignoreHandlers");o.silly("handlerSetting: "+s);const i=new this.class;return i[this.pk]=e,s||await N(this,r,i,n.OperationKeys.READ,n.OperationKeys.ON),[e,...a]}async read(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.read);n.debug(`reading ${this.class.name} from table ${s.Model.tableName(this.class)} with pk ${this.pk}`);const i=await this.adapter.read(t.Metadata.constr(this.class),e,...o);return this.adapter.revert(i,this.class,e,void 0,a)}async readSuffix(e,t){return t.get("ignoreHandlers")||await N(this,t,e,n.OperationKeys.READ,n.OperationKeys.AFTER),e}async updatePrefix(e,...t){const{ctx:r,ctxArgs:a,log:o}=(await this.logCtx(t,n.OperationKeys.UPDATE,!0)).for(this.updatePrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${i}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new n.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=s.Model.merge(d,e,this.class))),i||await N(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const a=await Promise.resolve(e.hasErrors(d,...s.Model.relations(this.class),...t));if(a)throw new n.ValidationError(a.toString())}return[e,...a,d]}async update(e,...r){const{ctxArgs:a,log:n,ctx:o}=this.logCtx(r,this.update);let{record:i,id:c,transient:l}=this.adapter.prepare(e,!1,o);return n.debug(`updating ${this.class.name} in table ${s.Model.tableName(this.class)} with id ${c}`),i=await this.adapter.update(t.Metadata.constr(this.class),c,e,...a),this.adapter.revert(i,this.class,c,l,o)}async updateSuffix(e,t,r){return r.get("ignoreHandlers")||await N(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.AFTER,t),e}async delete(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.delete);n.debug(`deleting new ${this.class.name} in table ${s.Model.tableName(this.class)} with pk ${e}`);const i=await this.adapter.delete(t.Metadata.constr(this.class),e,...o);return this.adapter.revert(i,this.class,e,void 0,a)}async deleteSuffix(e,t){return t.get("ignoreHandlers")||await N(this,t,e,n.OperationKeys.DELETE,n.OperationKeys.AFTER),e}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a,log:o}=(await this.logCtx(t,n.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(o.silly(`handlerSetting: ${i}, validationSetting: ${c}`),!e.length)return[e,...a];const l=s.Model.sequenceFor(e[0]);let d=[];s.Model.generatedBySequence(this.class)?(l.name||(l.name=s.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...a)):s.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new n.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),i||await N(this,r,e,n.OperationKeys.CREATE,n.OperationKeys.ON),e)));const p=r.timestamp||new Date;if(e=e.map(e=>("createdAt"in e&&Object.assign(e,{createdAt:p}),"updatedAt"in e&&Object.assign(e,{updatedAt:p}),e)),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),s=n.reduceErrorsToPrint(a);if(s)throw new n.ValidationError(s)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.createAll);n.debug(`Creating ${e.length} new ${this.class.name} in table ${s.Model.tableName(this.class)}`);const i=e.map(e=>this.adapter.prepare(e,!1,a)),c=i.map(e=>e.id);let l=i.map(e=>e.record);return l=await this.adapter.createAll(t.Metadata.constr(this.class),c,e,...o),l.map((e,t)=>this.adapter.revert(e,this.class,c[t],a.get("rebuildWithTransient")?i[t].transient:void 0,a))}async createAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>N(this,t,e,n.OperationKeys.CREATE,n.OperationKeys.AFTER))),e}async readAll(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.readAll);return n.debug(`reading ${e.length} ${this.class.name} in table ${s.Model.tableName(this.class)}`),(await this.adapter.readAll(t.Metadata.constr(this.class),e,...o)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}async readAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>N(this,t,e,n.OperationKeys.READ,n.OperationKeys.AFTER))),e}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:a,log:o}=(await this.logCtx(t,n.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${i}, validationSetting: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new n.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>s.Model.merge(d[t],e,this.class)))),i||await Promise.all(e.map((e,t)=>N(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.ON,d?d[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let a;o.silly("ignored validation properties: "+t),a=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const s=n.reduceErrorsToPrint(a);if(s)throw new n.ValidationError(s)}return[e,...a,d]}async updateAll(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.updateAll);n.verbose(`Updating ${e.length} new ${this.class.name} in table ${s.Model.tableName(this.class)}`);const i=e.map(e=>this.adapter.prepare(e,!1,a));return(await this.adapter.updateAll(t.Metadata.constr(this.class),i.map(e=>e.id),e,...o)).map((e,t)=>this.adapter.revert(e,this.class,i[t].id,a.get("rebuildWithTransient")?i[t].transient:void 0,a))}async updateAllSuffix(e,t,r){if(r.get("applyUpdateValidation")&&!r.get("ignoreDevSafeGuards")&&!t)throw new n.InternalError("No previous versions of models provided");return r.get("ignoreHandlers")||await Promise.all(e.map((e,a)=>N(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.AFTER,t?t[a]:void 0))),e}async deleteAll(e,...r){const{ctx:a,log:n,ctxArgs:o}=this.logCtx(r,this.create);return n.debug(`deleting ${e.length} ${this.class.name} in table ${s.Model.tableName(this.class)}`),(await this.adapter.deleteAll(t.Metadata.constr(this.class),e,...o)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}}let b=class{constructor(e,t){if(this.adapter=e,this.handler=t,!this.adapter)throw new n.InternalError("Missing adapter. Should not be possible")}async afterInsert(e){const t=e.entity.constructor,r=await this.adapter.context(n.OperationKeys.CREATE,{},t);this.handler(t,n.OperationKeys.CREATE,e.entityId,e.entity,r)}async afterRemove(e){const t=e.metadata.target,r=await this.adapter.context(n.OperationKeys.DELETE,{},t);this.handler(t,n.OperationKeys.DELETE,"",{},r)}async afterUpdate(e){const t=e.databaseEntity.constructor,r=await this.adapter.context(n.OperationKeys.UPDATE,{},t);return this.handler(t,n.OperationKeys.UPDATE,e.entity[s.Model.pk(t)],e.entity,r)}};b=r.__decorate([i.EventSubscriber(),r.__metadata("design:paramtypes",[a.Adapter,Function])],b);class R extends a.Dispatch{constructor(){super()}async notificationHandler(e,t,r,...a){const{log:n,ctxArgs:o}=this.logCtx(a,this.notificationHandler);try{await this.updateObservers(e,t,r,...o),n.verbose(`Observer refresh dispatched by ${t} for ${e}`),n.debug("pks: "+r)}catch(e){n.error("Failed to process notification: "+e)}}async initialize(...e){const{log:t}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);(async function(){if(!this.adapter)throw new n.InternalError("No adapter/native observed for dispatch");try{this.adapter.client.isInitialized||await this.adapter.client.initialize(),this.adapter.client.subscribers.push(new b(this.adapter,this.notificationHandler.bind(this)))}catch(e){throw new n.InternalError(e)}}).call(this).then(()=>{t.info("Subscribed to TypeORM notifications")}).catch(e=>{throw new n.InternalError("Failed to subscribe to TypeORM notifications: "+e)})}async updateObservers(e,t,r,...a){if(this.adapter)return super.updateObservers(e,t,r,...a);this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${e}:${t}`)}}function C(e,t,r){let n=0;const o=r.filter((r,a)=>(n=a,r.target===e&&r.propertyName===t));return o.length?(r.splice(n,1),Object.entries(o[0].options).reduce((e,[t,r])=>{switch(t){case"nullable":e[t]=r;break;case s.ValidationKeys.TYPE:break;default:throw new a.UnsupportedError("Unsupported option for a relation: "+t)}return e},{})):{}}function M(e,t,r,a={},o="regular",s,i){const c=r.filter(r=>r.target===e&&r.propertyName===t),l=s.filter(r=>r.target===e&&r.propertyName===t);if(i&&i.filter(r=>r.target===e&&r.columns.includes(t)).forEach(e=>{Object.assign(e,a)}),c.length>1)throw new n.InternalError(`Multiple columns for ${t} found for given target: ${r.map(e=>e.propertyName).join(", ")}`);if(l.length>1)throw new n.InternalError(`Multiple relations for ${t} found for given target: ${l.map(e=>e.propertyName).join(", ")}`);let d;0!==c.length||l.length?(l.length||(d=c[0],"regular"!==o&&Object.defineProperty(d,"mode",{value:o,writable:!0,enumerable:!0,configurable:!0})),l.length&&(a=Object.entries(a).reduce((e,[t,r])=>("nullable"===t&&(e[t]=r),e),{})),d=d||l[0],Object.defineProperty(d,"options",{value:{...d.options,...a},writable:!0,enumerable:!0,configurable:!0})):r.push({target:e,propertyName:t,mode:o,options:a})}function I(e,r){return(a,n)=>{let o;"string"==typeof e||"function"==typeof e?o=e:e&&(r=e,o=e.type),r||(r={});let s=Reflect&&Reflect.getMetadata?Reflect.getMetadata("design:type",a,n):void 0;!o&&s&&(o=s);const c=t.Metadata.allowedTypes(a.constructor,n)[0];if(c!==s&&(o=c,s=c),!r.type&&o&&(r.type=o),"hstore"!==r.type||r.hstoreType||(r.hstoreType=s===Object?"object":"string"),"function"==typeof e)i.getMetadataArgsStorage().embeddeds.push({target:a.constructor,propertyName:n,isArray:s===Array||!0===r.array,prefix:void 0!==r.prefix?r.prefix:void 0,type:e});else{if(!r.type)throw new i.ColumnTypeUndefinedError(a,n);!0===r.unique&&i.getMetadataArgsStorage().uniques.push({target:a.constructor,columns:[n]});const e=i.getMetadataArgsStorage();M(a.constructor,n,e.columns,r,"regular",e.relations,r.unique?e.indices:void 0),r.generated&&i.getMetadataArgsStorage().generations.push({target:a.constructor,propertyName:n,strategy:"string"==typeof r.generated?r.generated:"increment"})}}}class L{static isObject(e){return null!==e&&"object"==typeof e}static isObjectWithName(e){return null!==e&&"object"==typeof e&&void 0!==e.name}static assign(e,...t){for(const r of t)for(const t of Object.getOwnPropertyNames(r))e[t]=r[t]}}function _(e,t){const r={};let a;return e?("string"==typeof e&&(a=e),L.isObject(e)&&(a="increment",Object.assign(r,e))):a="increment",L.isObject(t)&&Object.assign(r,t),(e,t)=>{r.type||("increment"===a||"identity"===a?r.type=Number:"uuid"===a?r.type="uuid":"rowid"===a&&(r.type="int")),r.primary=!0;const n=i.getMetadataArgsStorage();M(e.constructor,t,n.columns,r,"regular",n.relations),i.getMetadataArgsStorage().generations.push({target:e.constructor,propertyName:t,strategy:a})}}function v(e,t){const r=(L.isObject(e)?e:t)||{},a="string"==typeof e?e:r.name;return e=>{i.getMetadataArgsStorage().tables.push({target:e,name:a,type:"regular",orderBy:r.orderBy?r.orderBy:void 0,engine:r.engine?r.engine:void 0,database:r.database?r.database:void 0,schema:r.schema?r.schema:void 0,synchronize:r.synchronize,withoutRowid:r.withoutRowid,comment:r.comment?r.comment:void 0})}}async function $(e,t,r,a){try{const t=e.get("user");a[r]=t}catch(e){throw new n.InternalError("No User found in context. Please provide a user in the context")}}class D extends a.Adapter{getClient(){const e=a.Adapter.models(this.alias).map(t.Metadata.constr);return new i.DataSource(Object.assign({},this.config,{entities:e}))}constructor(e,t){super(e,l,t)}async shutdown(){await super.shutdown(),this._client&&await this._client.destroy()}async flags(e,t,r){return super.flags(e,t,Object.assign({user:this.config.username},r))}Dispatch(){return new R}repository(){return T}Statement(){return new A(this)}Paginator(e,t,r){return new g(this,e,t,r)}async Sequence(e){return new O(e,this)}async initialize(...e){const{log:t}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),r=this.client;try{await r.initialize()}catch(e){throw this.parseError(e)}t.verbose(this.toString()+" initialized")}async index(...e){const{log:t,ctx:r}=(await this.logCtx(e,a.PersistenceKeys.INDEX,!0)).for(this.index),n=S(e);try{await this.client.query("BEGIN");for(const e of n)await this.client.query(e.query,e.values);await this.client.query("COMMIT")}catch(e){throw await this.client.query("ROLLBACK"),this.parseError(e)}}async raw(e,t=!0,...r){const{log:a}=this.logCtx(r,this.raw);try{this.client.isInitialized||await this.client.initialize()}catch(e){throw this.parseError(e)}try{const{query:t,values:r}=e;return a.debug("executing query: "+("string"!=typeof t?t.getSql():t)),await this.client.query(t,r)}catch(e){throw this.parseError(e)}}prepare(e,r=!1,o){const i=super.prepare(e,o);i.record=Object.entries(i.record).reduce((e,[t,r])=>(t===a.PersistenceKeys.METADATA||this.isReserved(t)||void 0===r||(r instanceof Date?r=new Date(r.getTime()):s.Model.isModel(r)?r=this.prepare(r,!0,o).record:"string"==typeof r&&(r=""+r),e[t]=r),e),{});const c=s.Model.get(e.constructor.name);if(!c)throw new n.InternalError(`Model ${e.constructor.name} not found in registry`);const l=r?new(t.Metadata.constr(c)):new c;return r&&Object.defineProperty(l,"constructor",{configurable:!1,enumerable:!1,value:t.Metadata,writable:!1}),Object.entries(i.record).forEach(([e,t])=>l[e]=t),i.record=l,i}revert(e,t,r,a,...o){const{log:s}=this.logCtx(o,this.revert);return a&&(s.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([r,a])=>{if(r in e&&void 0!==e[r])throw new n.InternalError(`Transient property ${r} already exists on model ${"string"==typeof t?t:t.name}. should be impossible`);e[r]=a})),new t(e)}async create(e,t,r,...a){const o=this.client.getRepository(e);if(void 0!==t){const r=s.Model.pk(e);if(await o.findOne({where:{[r]:t}}))throw new n.ConflictError(`Record already exists in table ${s.Model.tableName(e)} with id: ${t}`)}try{return await o.save(r)}catch(e){throw this.parseError(e)}}async read(e,t,...r){let a;try{const r=this.client.getRepository(e),{nonEager:n,relations:o}=m(e),i=s.Model.pk(e),c={where:{[i]:t},relations:o,loadRelationIds:{relations:n}};a=await r.findOneOrFail(c)}catch(e){throw this.parseError(e)}return a}async update(e,t,r,...a){const{ctx:n}=this.logCtx(a,this.update);await this.read(e,t,n);try{return this.client.getRepository(e).save(r)}catch(e){throw this.parseError(e)}}async delete(e,t,...r){const{ctx:a}=this.logCtx(r,this.delete),n=await this.read(e,t,a);try{const r=this.client.getRepository(e);return await r.delete(t),n}catch(e){throw this.parseError(e)}}async createAll(e,t,r,...a){const{ctx:n,log:o}=this.logCtx(a,this.createAll),i=s.Model.tableName(e);o.debug(`Creating ${t.length} entries ${i} table`);try{const t=this.client.getRepository(e),a=await t.insert(r);return this.readAll(e,a.identifiers.map(e=>e.id),n)}catch(e){throw this.parseError(e)}}async readAll(e,t,...r){if(!t.length)return[];const{log:a}=this.logCtx(r,this.readAll),n=s.Model.tableName(e);a.debug(`Reading ${t.length} entries ${n} table`);try{const r=s.Model.pk(e);return this.client.getRepository(e).findBy({[r]:i.In(t)})}catch(e){throw this.parseError(e)}}async updateAll(e,t,r,...a){const{log:n,ctxArgs:o}=this.logCtx(a,this.updateAll),i=s.Model.tableName(e);n.debug(`Updating ${t.length} entries ${i} table`);const c=[],l=s.Model.pk(e);for(const t of r)c.push(await this.update(e,t[l],t,...o));return c}async deleteAll(e,t,...r){if(!t.length)return[];const{ctxArgs:a,log:n}=this.logCtx(r,this.deleteAll),o=s.Model.tableName(e);n.debug(`Deleting ${t.length} entries from ${o} table`);try{const r=this.client.getRepository(e),n=await this.readAll(e,t,...a),o=s.Model.pk(e);return await r.delete({[o]:i.In(t)}),n}catch(e){throw this.parseError(e)}}parseError(e,t){return D.parseError(e,t)}isReserved(e){return!!e.match(c)}static parseError(e,t){if(e instanceof n.BaseError)return e;const r="string"==typeof e?e:e.message;if(r.match(/duplicate key|already exists/g))return new n.ConflictError(r);if(r.match(/does not exist|not found|Could not find/g))return new n.NotFoundError(r);switch(r.toString()){case"23505":case"23503":case"42P07":return new n.ConflictError(t);case"42P01":case"42703":return new n.NotFoundError(t);case"42P16":return new p(e);default:return r.toString().match(/ECONNREFUSED/g)?new a.ConnectionError(e):new n.InternalError(e)}}static async connect(e){const t=new i.DataSource(e);return t.isInitialized||await t.initialize(),t}static async createDatabase(e,t){const r=o.Logging.for(this.createDatabase);r.verbose("Creating database "+t);try{await e.query("CREATE DATABASE "+t),r.info("Created database "+t)}catch(e){throw this.parseError(e)}}static async createNotifyFunction(e,t){const r=o.Logging.for(this.createNotifyFunction);r.verbose("Creating notify function");try{await e.query("CREATE OR REPLACE FUNCTION notify_table_changes()\nRETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'table_changes',\n json_build_object(\n 'table', TG_TABLE_NAME,\n 'action', TG_OP,\n 'data', row_to_json(NEW),\n 'old_data', row_to_json(OLD)\n )::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER\n;"),await e.query(`ALTER FUNCTION notify_table_changes() OWNER TO ${t};`),await e.query("\n GRANT EXECUTE ON FUNCTION notify_table_changes() TO public;\n "),r.info("Created notify function")}catch(e){throw this.parseError(e)}}static async deleteDatabase(e,t,r){try{r&&await e.query(`DROP OWNED BY ${r} CASCADE;`),await e.query("DROP DATABASE "+t)}catch(e){throw this.parseError(e)}}static async createUser(e,t,r,a){try{await e.query(`CREATE USER ${r} WITH PASSWORD '${a}'`),await e.query(`GRANT CONNECT ON DATABASE ${t} TO ${r}`),await e.query("GRANT USAGE ON SCHEMA public TO "+r),await e.query("GRANT CREATE ON SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO "+r),await e.query("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO "+r),await e.query("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON SEQUENCES TO "+r)}catch(e){throw this.parseError(e)}}static async deleteUser(e,t,r){try{await e.query(`REASSIGN OWNED BY ${t} TO ${r}`),await e.query("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM "+t),await e.query("REVOKE ALL ON SCHEMA public FROM "+t),await e.query("REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM "+t),await e.query("REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM "+t),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON TABLES FROM ${t}`),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON SEQUENCES FROM ${t};`),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM ${t}`),await e.query(`DROP OWNED BY ${t} CASCADE`),await e.query(`DROP USER IF EXISTS "${t}"`)}catch(e){throw this.parseError(e)}}static parseTypeToPostgres(e,r,a=!1){switch(e.toLowerCase()){case"string":return r?"TEXT PRIMARY KEY":a?"TEXT":"VARCHAR";case"number":return r?"SERIAL PRIMARY KEY":"INTEGER";case"boolean":return"BOOLEAN";case"date":return"TIMESTAMP";case"bigint":return r?"BIGINT PRIMARY KEY":"BIGINT";default:{const r=s.Model.get(e);if(r)return{model:r,pkType:t.Metadata.type(r,s.Model.pk(r))};throw new n.InternalError("Unsupported type: "+e)}}}static parseValidationToPostgres(e,t,r,a,o){switch(a){case s.ValidationKeys.REQUIRED:return"NOT NULL";case s.ValidationKeys.MAX_LENGTH:return r||!o||"string"!==t.toLowerCase()?"":`(${o[s.ValidationKeys.MAX_LENGTH]})`;case s.ValidationKeys.MIN_LENGTH:return`CONSTRAINT ${e}_min_length_check CHECK (LENGTH(${e}) >= ${o[s.ValidationKeys.MIN_LENGTH]})`;case s.ValidationKeys.PATTERN:case s.ValidationKeys.URL:case s.ValidationKeys.EMAIL:return`CONSTRAINT ${e}_pattern_check CHECK (${e} ~ '${f(o[s.ValidationKeys.PATTERN])}')`;case s.ValidationKeys.TYPE:case s.ValidationKeys.DATE:return"";case s.ValidationKeys.MIN:return`CONSTRAINT ${e}_${a}_check CHECK (${e} >= ${o[s.ValidationKeys.MIN]})`;case s.ValidationKeys.MAX:return`CONSTRAINT ${e}_${a}_check CHECK (${e} <= ${o[s.ValidationKeys.MAX]})`;case s.ValidationKeys.PASSWORD:default:throw new n.InternalError("Unsupported type: "+a)}}static parseRelationsToPostgres(e,t,r,o,i){const c=s.Model.tableName(t),{cascade:l}=i,d=`${l.update?" ON UPDATE CASCADE":""}${l.delete?" ON DELETE CASCADE":""}`;if("relations"+o===a.PersistenceKeys.ONE_TO_ONE)return`FOREIGN KEY (${e}) REFERENCES ${c}(${r})${d}`;throw new n.InternalError("Unsupported operation: "+o)}static async getCurrentUser(e){try{return(await e.query("SELECT CURRENT_USER;"))[0].current_user}catch(e){throw this.parseError(e)}}static decoration(){super.decoration(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.TABLE).extend({decorator:e=>r=>{const a=t.Metadata.constr(r),n=i.getMetadataArgsStorage().tables.find(e=>e.target===a);return n?(e&&(n.name=e),r):(v(e||(()=>{try{return s.Model.tableName(a)}catch{return a?.name}})())(a),r)}}).apply(),t.Decoration.flavouredAs(l).for(n.DBKeys.ID).define({decorator:e=>(r,o)=>{const c=t.Metadata.constr(r.constructor);i.getMetadataArgsStorage().tables.find(e=>e.target===c)||v((()=>{try{return s.Model.tableName(c)}catch{return c?.name}})()||c?.name)(c),t.prop()(r,o);const l=[s.required(),n.readonly(),t.propMetadata(t.Metadata.key(n.DBKeys.ID,o),e)];let d=e.type||t.Metadata.type(r.constructor,o);switch(d){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated;break;case Number.name||String.name.toLowerCase():case BigInt.name||BigInt.name.toLowerCase():case BigInt:case Number:e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;case!d:throw new n.InternalError(`Missing type information for property ${o} of ${r.name}`);default:throw Error("Unsupported type")}if(void 0===e.generated&&(e.generated=!0),e.generated){const t={name:e.name||s.Model.sequenceName(r.constructor,"pk")};"serial"===e.type||"uuid"===e.type?l.push(_("uuid"===e.type?e.type:"identity",t)):l.push(_(t)),l.push(a.noValidateOnCreate())}else{switch("function"==typeof d&&d?.name?d.name:d){case Number.name||Number.name.toLowerCase():d="numeric";break;case"serial":case"uuid":break;case String.name||String.name.toLowerCase():d="varchar";break;case BigInt.name||BigInt.name.toLowerCase():d="bigint";break;default:throw new n.InternalError("Unsupported type: "+d)}l.push(((e,t)=>(r,a)=>{let n;e===String||e===Boolean||e===Number?n=e:t=Object.assign({},e),t||(t={});const o=Reflect&&Reflect.getMetadata?Reflect.getMetadata("design:type",r,a):void 0;if(!n&&o&&(n=o),!t.type&&n&&(t.type=n),!t.type)throw new i.ColumnTypeUndefinedError(r,a);if(t.nullable)throw new i.PrimaryColumnCannotBeNullableError(r,a);t.primary=!0;const s=i.getMetadataArgsStorage();M(r.constructor,a,s.columns,t,"regular",s.relations),t.generated&&i.getMetadataArgsStorage().generations.push({target:r.constructor,propertyName:a,strategy:"string"==typeof t.generated?t.generated:"increment"})})({type:d,unique:!0}))}return e.generated&&l.push(n.generated()),t.apply(...l)(r,o)}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.COLUMN).extend({decorator:e=>(t,r)=>{const a={};let n;e&&(a.name=e);try{n=s.Model.pk(t.constructor)}catch(e){n=void 0}return n!==r&&(a.nullable=!0),I(a)(t,r)}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.UNIQUE).define(t.propMetadata(a.PersistenceKeys.UNIQUE,{})).extend(I({unique:!0})).apply();const e=s.Validation.key(s.ValidationKeys.REQUIRED);t.Decoration.flavouredAs(l).for(e).extend(I({nullable:!1})).apply(),t.Decoration.flavouredAs(l).for(n.DBKeys.VERSION).define(s.type(Number),i.VersionColumn(),a.noValidateOnCreate()).apply();const r=n.DBKeys.TIMESTAMP,o=(c=n.DBKeys.TIMESTAMP,n.UpdateValidationKeys.REFLECT+c);var c;t.Decoration.flavouredAs(l).for(r).define({decorator:(e,r)=>{const i=[s.date(r,n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.DATE),s.required(n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.REQUIRED),t.propMetadata(s.Validation.key(n.DBKeys.TIMESTAMP),{operation:e,format:r}),a.noValidateOnCreate()];return-1!==e.indexOf(n.OperationKeys.UPDATE)?i.push(t.propMetadata(o,{message:n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.INVALID}),a.noValidateOnCreateUpdate()):i.push(n.readonly()),t.apply(...i)}}).extend({decorator:(e,t)=>(t,r)=>-1!==e.indexOf(n.OperationKeys.UPDATE)?((e,t)=>{const r=i.getMetadataArgsStorage();M(e.constructor,t,r.columns,{},"updateDate",r.relations)})(t,r):((e,t)=>{const r=i.getMetadataArgsStorage();M(e.constructor,t,r.columns,{},"createDate",r.relations)})(t,r)}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.ONE_TO_ONE).define({decorator:(e,r,o,c,l)=>{const d={class:e,cascade:r,populate:o};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:o};return t.apply(t.prop(),a.relation(a.PersistenceKeys.ONE_TO_ONE,d),s.type([e,String,Number,BigInt]),t.propMetadata(a.PersistenceKeys.ONE_TO_ONE,d),((e,t,r)=>{let a;return L.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let o=!(!r||!0!==r.lazy);if(!o&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(o=!0)}const s=i.getMetadataArgsStorage();r=Object.assign(r,C(t.constructor,n,s.columns)),s.relations.push({target:t.constructor,propertyName:n,isLazy:o,relationType:"one-to-one",type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},t=>("function"!=typeof e||e.name||(e=e()),t[s.Model.pk(e)]),p),i.JoinColumn(c||d.name?{foreignKeyConstraintName:d.name}:void 0))}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.ONE_TO_MANY).define({decorator:(e,r,o,c,l)=>{const d={class:e,cascade:r,populate:o};c&&(d.joinTable=c),l&&(d.name=l);const p=[t.prop(),a.relation(a.PersistenceKeys.ONE_TO_MANY,d),s.list(e),t.propMetadata(a.PersistenceKeys.ONE_TO_MANY,d),(c,l)=>{const d={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:o};return(p=()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},u=r=>{"function"!=typeof e||e.name||(e=e());const o=t.Metadata.relations(e);if(!o)throw new n.InternalError("No relations found on model "+e.name);const i=o.find(r=>{const n=s.Model.relations(e,r);if(n.key!==a.PersistenceKeys.MANY_TO_ONE)return!1;const o="function"!=typeof n.class||n.class.name?n.class:n.class(),i=t.Metadata.constr(c.constructor);return o.name===i.name});if(!i)throw new n.InternalError(`Cross relation not found. Did you use @manyToOne on the ${e.name}?`);return r[i]},h=d,(e,t)=>{h||(h={});let r=h&&!0===h.lazy;if(!r&&Reflect&&Reflect.getMetadata){const a=Reflect.getMetadata("design:type",e,t);a&&"string"==typeof a.name&&"promise"===a.name.toLowerCase()&&(r=!0)}const a=i.getMetadataArgsStorage();h=Object.assign(h,C(e.constructor,t,a.columns)),a.relations.push({target:e.constructor,propertyName:t,isLazy:r,relationType:"one-to-many",type:p,inverseSideProperty:u,options:h})})(c,l);var p,u,h}];return t.apply(...p)}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.MANY_TO_ONE).define({decorator:(e,r,o,c,l)=>{const d={class:e,cascade:r,populate:o};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"NO ACTION",onUpdate:r.update?"CASCADE":"NO ACTION",nullable:!0,eager:o};return t.apply(a.relation(a.PersistenceKeys.MANY_TO_ONE,d),s.type([e,String,Number,BigInt]),t.propMetadata(a.PersistenceKeys.MANY_TO_ONE,d),(r,o)=>((e,t,r)=>{let a;return L.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let o=r&&!0===r.lazy;if(!o&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(o=!0)}const s=i.getMetadataArgsStorage();r=Object.assign(r,C(t.constructor,n,s.columns)),s.relations.push({target:t.constructor,propertyName:n,relationType:"many-to-one",isLazy:o,type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},n=>{"function"!=typeof e||e.name||(e=e());const o=t.Metadata.relations(e);let i=s.Model.pk(e);return o?(i=o.find(n=>{const o=s.Model.relations(e,n);if(o.key!==a.PersistenceKeys.ONE_TO_MANY)return!1;const i="function"!=typeof o.class||o.class.name?o.class:o.class(),c=t.Metadata.constr(r.constructor);return i.name===c.name})||i,n[i]):n[i]},p)(r,o))}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.MANY_TO_MANY).define({decorator:(e,r,o,c,l)=>{const d={class:e,cascade:r,populate:o};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:o};return t.apply(a.relation(a.PersistenceKeys.MANY_TO_MANY,d),s.list(e),t.propMetadata(a.PersistenceKeys.MANY_TO_MANY,d),((e,t,r)=>{let a;return L.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let o=!0===r.lazy;if(!o&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(o=!0)}const s=i.getMetadataArgsStorage();r=Object.assign(r,C(t.constructor,n,s.columns)),s.relations.push({target:t.constructor,propertyName:n,relationType:"many-to-many",isLazy:o,type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},t=>("function"!=typeof e||e.name||(e=e()),t[s.Model.pk(e)]),p),i.JoinTable(c))}}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.INDEX).extend({decorator:(e,t,r)=>(r,n)=>("string"==typeof e&&(e=void 0,t=void 0),"string"==typeof t&&(t=void 0),!t&&e&&e.find(e=>![a.OrderDirection.ASC,a.OrderDirection.DSC].includes(e))&&(t=e,e=void 0),t&&t.length?i.Index([n,...t])(r):i.Index()(r,n))}).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.CREATED_BY).define(n.onCreate($,{}),s.required(),t.propMetadata(a.PersistenceKeys.CREATED_BY,{}),a.noValidateOnCreate()).apply(),t.Decoration.flavouredAs(l).for(a.PersistenceKeys.UPDATED_BY).define(n.onCreateUpdate($,{}),s.required(),t.propMetadata(a.PersistenceKeys.UPDATED_BY,{}),a.noValidateOnCreateUpdate()).apply()}}r.__decorate([o.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",R)],D.prototype,"Dispatch",null),r.__decorate([o.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",Object)],D.prototype,"repository",null),r.__decorate([o.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",A)],D.prototype,"Statement",null),r.__decorate([o.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],D.prototype,"Sequence",null),r.__decorate([o.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],D.prototype,"index",null),D.decoration(),a.Adapter.setCurrent(l);const x="##VERSION##",P="##PACKAGE##";t.Metadata.registerLibrary(P,x),e.IndexError=p,e.PACKAGE_NAME=P,e.TypeORMAdapter=D,e.TypeORMConst={NULL:"NULL"},e.TypeORMDispatch=R,e.TypeORMFlavour=l,e.TypeORMGroupOperator=y,e.TypeORMKeys=d,e.TypeORMOperator=h,e.TypeORMPaginator=g,e.TypeORMQueryLimit=250,e.TypeORMRepository=T,e.TypeORMSequence=O,e.TypeORMStatement=A,e.VERSION=x,e.convertJsRegexToPostgres=f,e.enforceDbDecoratorsRecursive=N,e.generateIndexes=S,e.reservedAttributes=c,e.splitEagerRelations=m,e.translateOperators=E},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("tslib"),require("@decaf-ts/core"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("typeorm")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","tslib","@decaf-ts/core","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","typeorm"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-typeorm"]={},e.decafTsDecoration,e.tslib,e.decafTsCore,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.typeorm);
1
+ var e,t;e=this,t=function(e,t,r,a,n,s,o,i){"use strict";var c,l,d;function p(t){if(!t||!t.type)throw Error("Invalid TypeORM configuration: missing type");const r=t.type.toLowerCase();if(r===e.TypeORMDriver.POSTGRES||"postgres"===r||"pg"===r)return e.TypeORMDriver.POSTGRES;if(r===e.TypeORMDriver.MYSQL||"mysql"===r)return e.TypeORMDriver.MYSQL;if(r===e.TypeORMDriver.MARIA||"mariadb"===r||"maria"===r)return e.TypeORMDriver.MARIA;if(r===e.TypeORMDriver.SQLITE||"sqlite"===r||"better-sqlite3"===r)return e.TypeORMDriver.SQLITE;if(r===e.TypeORMDriver.SQLSERVER||"mssql"===r)return e.TypeORMDriver.SQLSERVER;throw Error("Unsupported TypeORM driver: "+t.type)}e.SQLOperator=void 0,(c=e.SQLOperator||(e.SQLOperator={})).EQUAL="=",c.NOT_EQUAL="<>",c.LESS_THAN="<",c.LESS_THAN_OR_EQUAL="<=",c.GREATER_THAN=">",c.GREATER_THAN_OR_EQUAL=">=",c.IN="IN",c.NOT_IN="NOT IN",c.LIKE="LIKE",c.ILIKE="ILIKE",c.BETWEEN="BETWEEN",c.IS_NULL="IS NULL",c.IS_NOT_NULL="IS NOT NULL",c.EXISTS="EXISTS",c.NOT_EXISTS="NOT EXISTS",c.ANY="ANY",c.ALL="ALL",c.SOME="SOME",e.TypeORMDriver=void 0,(l=e.TypeORMDriver||(e.TypeORMDriver={})).POSTGRES="postgres",l.MYSQL="mysql",l.MARIA="mariadb",l.SQLITE="sqlite",l.SQLSERVER="mssql",e.TypeORMEventMode=void 0,(d=e.TypeORMEventMode||(e.TypeORMEventMode={})).SUBSCRIBER="SUBSCRIBER",d.TRIGGER="TRIGGER";const u=/^(select|from|where|and|or|insert|update|delete|drop|create|table|index|primary|key|foreign|references|constraint|unique|check|default|null|not|as|order|by|group|having|limit|offset|join|inner|outer|left|right|full|on|using|values|returning|set|into|case|when|then|else|end|cast|coalesce|exists|any|all|some|in|between|like|ilike|similar|to|is|true|false|asc|desc|distinct|union|intersect|except|natural|lateral|window|over|partition|range|rows|unbounded|preceding|following|current|row|with|recursive|materialized|view|function|trigger|procedure|language|returns|return|declare|begin|commit|rollback|savepoint|transaction|temporary|temp|if|loop|while|for|continue|exit|raise|exception|notice|info|log|debug|assert|execute|perform|get|diagnostics|call|do|alias|comment|vacuum|analyze|explain|copy|grant|revoke|privileges|public|usage|schema|sequence|owned|owner|tablespace|storage|inherits|type|operator|collate|collation|cascade|restrict|add|alter|column|rename|to|enable|disable|force|no|instead|of|before|after|each|statement|row|execute|also|only|exclude|nulls|others|ordinality|ties|nothing|cache|cycle|increment|minvalue|maxvalue|start|restart|by|called|returns|language|immutable|stable|volatile|strict|security|definer|invoker|cost|rows|support|handler|inline|validator|options|storage|inheritance|oids|without|data|dictionary|encoding|lc_collate|lc_ctype|connection|limit|password|valid|until|superuser|nosuperuser|createdb|nocreatedb|createrole|nocreaterole|inherit|noinherit|login|nologin|replication|noreplication|bypassrls|nobypassrls|encrypted|unencrypted|new|old|session_user|current_user|current_role|current_schema|current_catalog|current_date|current_time|current_timestamp|localtime|localtimestamp|current_database|inet|cidr|macaddr|macaddr8|bit|varbit|tsvector|tsquery|uuid|xml|json|jsonb|int|integer|smallint|bigint|decimal|numeric|real|double|precision|float|boolean|bool|char|character|varchar|text|bytea|date|time|timestamp|interval|point|line|lseg|box|path|polygon|circle|money|void)$/i,y="type-orm",h={SEPARATOR:".",ID:"id",VERSION:"version",DELETED:"deleted_at",TABLE:"table_name",SCHEMA:"schema_name",SEQUENCE:"sequence_name",INDEX:"index"};class E extends n.BaseError{constructor(e){super(E.name,e,404)}}const g={EQUAL:e.SQLOperator.EQUAL,DIFFERENT:e.SQLOperator.NOT_EQUAL,BIGGER:e.SQLOperator.GREATER_THAN,BIGGER_EQ:e.SQLOperator.GREATER_THAN_OR_EQUAL,SMALLER:e.SQLOperator.LESS_THAN,SMALLER_EQ:e.SQLOperator.LESS_THAN_OR_EQUAL,BETWEEN:e.SQLOperator.BETWEEN,NOT:"NOT",IN:e.SQLOperator.IN,IS_NULL:e.SQLOperator.IS_NULL,IS_NOT_NULL:e.SQLOperator.IS_NOT_NULL,REGEXP:"~",IREGEXP:"~*",LIKE:e.SQLOperator.LIKE,ILIKE:e.SQLOperator.ILIKE,STARTS_WITH:e.SQLOperator.LIKE,ENDS_WITH:e.SQLOperator.LIKE},f={AND:"AND",OR:"OR"};class T extends a.Paginator{get total(){return this._totalPages}get count(){return this._recordCount}get repo(){return this.__repo||(this.__repo=this.adapter.client.getRepository(t.Metadata.constr(this.clazz))),this.__repo}constructor(e,t,r,a){super(e,t,r,a)}prepare(e){return{...e}}async page(e=1,...t){const{ctxArgs:r,ctx:n}=this.adapter.logCtx(t,this.page);if(this.isPreparedStatement())return this.pagePrepared(e,...r);const s={...this.statement};this._recordCount&&this._totalPages||(this._totalPages=this._recordCount=0);const i=Object.assign(s,{skip:(this.current||0)*this.size,take:this.size}),c=await this.repo.findAndCount(i);if(this._recordCount=c[1],this._totalPages=Math.ceil(this._recordCount/this.size),!this.clazz)throw new a.PagingError("No statement target defined");const l=o.Model.pk(this.clazz),d=(c[0]||[]).map(e=>this.adapter.revert(e,this.clazz,e[l],void 0,n));return this._currentPage=e,d}}function A(e){for(const t of[g,f]){const r=Object.keys(t).find(t=>t===e);if(r)return t[r]}throw new a.QueryError("Could not find adapter translation for operator "+e)}function O(e){const t=RegExp(/^\/(.+)\/(\w+)$/g);if("string"==typeof e){const r=t.exec(e);if(r){const[,t]=r;e=t}}return("string"==typeof e?RegExp(e):e).source}function R(e,r={}){const a=o.Model.relations(e);if(r[e.name]=r[e.name]||void 0,r[e.name])return r[e.name];const i=a.reduce((a,o)=>{const i=t.Metadata.relations(e,o),c=i.populate;let l=i.class;if(s.isClass(l)||(l=l()),!l)throw new n.InternalError(`Could not find class for property ${o} on model ${e.name}`);if(c?a.relations.push(o):a.nonEager.push(o),a.relations.includes(o)){const{nonEager:e,relations:t}=R(l,r);if(e.length&&a.relations.includes(o)){const t=e.map(e=>`${o}.${e}`);a.nonEager.push(...t)}if(t.length){const e=t.map(e=>`${o}.${e}`);a.relations.push(...e)}}return a},{nonEager:[],relations:[]});return r[e.name]=i,i}class m extends a.Statement{constructor(e){super(e)}build(){const e=this.log.for(this.build),r=o.Model.tableName(this.fromSelector),n={query:this.adapter.client.getRepository(t.Metadata.constr(this.fromSelector)).createQueryBuilder(r)};if(void 0!==this.countSelector){const e=null===this.countSelector?"*":`${r}.${this.countSelector}`;n.query=n.query.select(`COUNT(${e})`,"count")}else if(void 0!==this.countDistinctSelector){const e=null===this.countDistinctSelector?"*":`${r}.${this.countDistinctSelector}`;n.query=n.query.select(`COUNT(DISTINCT ${e})`,"count")}else this.sumSelector?n.query=n.query.select(`SUM(${r}.${this.sumSelector})`,"sum"):this.avgSelector?n.query=n.query.select(`AVG(${r}.${this.avgSelector})`,"avg"):this.maxSelector?n.query=n.query.select(`MAX(${r}.${this.maxSelector})`,"max"):this.minSelector?n.query=n.query.select(`MIN(${r}.${this.minSelector})`,"min"):this.distinctSelector?n.query=n.query.select(`DISTINCT ${r}.${this.distinctSelector}`,this.distinctSelector):this.selectSelector?n.query=n.query.select(this.selectSelector.map(e=>`${r}.${e}`)):n.query=n.query.select();if(this.whereCondition&&(n.query=this.parseCondition(this.whereCondition,r,n.query).query),this.groupBySelectors&&this.groupBySelectors.length){const[e,...t]=this.groupBySelectors;n.query=n.query.groupBy(`${r}.${e}`);for(const e of t)n.query=n.query.addGroupBy(`${r}.${e}`)}const s=this.hasAggregation();if(s){if(this.orderBySelectors&&this.orderBySelectors.length){const[e,t]=this.orderBySelectors[0];n.query=n.query.orderBy(`${r}.${e}`,t.toUpperCase());for(let e=1;e<this.orderBySelectors.length;e++){const[t,a]=this.orderBySelectors[e];n.query=n.query.addOrderBy(`${r}.${t}`,a.toUpperCase())}}}else if(this.orderBySelectors&&this.orderBySelectors.length){const[e,t]=this.orderBySelectors[0];n.query=n.query.orderBy(`${r}.${e}`,t.toUpperCase());for(let e=1;e<this.orderBySelectors.length;e++){const[t,a]=this.orderBySelectors[e];n.query=n.query.addOrderBy(`${r}.${t}`,a.toUpperCase())}}else n.query=n.query.orderBy(`${r}.${o.Model.pk(this.fromSelector)}`,a.OrderDirection.ASC.toUpperCase());return s?this.limitSelector&&(n.query=n.query.limit(this.limitSelector)):this.limitSelector?n.query=n.query.limit(this.limitSelector):(e.debug("No limit selector defined. Using default limit of 250"),n.query=n.query.limit(250)),this.offsetSelector&&(n.query=n.query.skip(this.offsetSelector)),n}async paginate(e){try{const t={};if(this.whereCondition&&(t.where=this.parseConditionForPagination(this.whereCondition,o.Model.tableName(this.fromSelector))),this.orderBySelectors&&this.orderBySelectors.length){const e={};for(const[t,r]of this.orderBySelectors)e[t]=r.toString().toUpperCase();t.order=e}return this.adapter.Paginator(t,e,this.fromSelector)}catch(e){throw new a.QueryError(e)}}async raw(e,...t){const{ctx:r}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new a.UnsupportedError("Raw statements are not allowed in the current configuration");const n=e.query;if(this.hasAggregation()){if(this.groupBySelectors&&this.groupBySelectors.length){const e=await n.getRawMany();return this.groupResults(e)}{const e=await n.getRawOne();return void 0!==this.countSelector||void 0!==this.countDistinctSelector?Number(e?.count||0):this.sumSelector?Number(e?.sum||0):this.avgSelector?Number(e?.avg||0):this.maxSelector?e?.max:this.minSelector?e?.min:this.distinctSelector?(await n.getRawMany()).map(e=>e[this.distinctSelector]):e}}const{nonEager:s}=R(this.fromSelector);return e.query=n.setFindOptions({loadEagerRelations:!0,loadRelationIds:{relations:s}}),await e.query.getMany()}groupResults(e){if(!this.groupBySelectors||!this.groupBySelectors.length)return e;const t=o.Model.tableName(this.fromSelector),r=this.groupBySelectors.map(e=>`${t}_${e}`),a={};for(const t of e){let e=a;for(let a=0;a<r.length-1;a++){const n=t[r[a]];e[n]||(e[n]={}),e=e[n]}const n=t[r[r.length-1]];e[n]||(e[n]=[]),e[n].push(t)}return a}parseConditionForPagination(e,t,r=0,n){const{attr1:s,operator:o,comparison:i}=e,c=()=>{if("string"!=typeof s)throw new a.QueryError("Invalid attribute for pagination condition");return{[s]:this.buildFindValue(o,i)}};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(o))return c();if(o===a.GroupOperator.OR){const e=s instanceof a.Condition?this.parseConditionForPagination(s,t,++r,n):c(),o=i instanceof a.Condition?this.parseConditionForPagination(i,t,++r,n):c(),l=e=>Array.isArray(e)?e:e?[e]:[];return[...l(e),...l(o)]}if(o===a.GroupOperator.AND){const e=s instanceof a.Condition?this.parseConditionForPagination(s,t,++r,n):c(),o=i instanceof a.Condition?this.parseConditionForPagination(i,t,++r,n):c();if(Array.isArray(e)||Array.isArray(o))throw new a.QueryError("AND conditions with OR branches are not supported in pagination");return{...e||{},...o||{}}}throw new a.QueryError("NOT operator is not supported for pagination")}buildFindValue(e,t){switch(e){case a.Operator.STARTS_WITH:return i.Like(t+"%");case a.Operator.ENDS_WITH:return i.Like("%"+t);case a.Operator.REGEXP:return i.Raw(e=>e+" ~ :regex",{regex:t});case a.Operator.IN:return i.In(Array.isArray(t)?t:[t]);case a.Operator.BETWEEN:if(!Array.isArray(t)||2!==t.length)throw new a.QueryError("BETWEEN operator requires an array with two values");return i.Between(t[0],t[1]);case a.Operator.BIGGER:return i.MoreThan(t);case a.Operator.BIGGER_EQ:return i.MoreThanOrEqual(t);case a.Operator.SMALLER:return i.LessThan(t);case a.Operator.SMALLER_EQ:return i.LessThanOrEqual(t);default:return t}}parseCondition(e,t,r,n=0,s){const{attr1:o,operator:i,comparison:c}=e;if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(i))return(()=>{const e=A(i),l=`${o}${n}`;let d,p;if(i===a.Operator.BETWEEN){const[r,a]=c,s=`${o}${n}_min`,i=`${o}${n}_max`;d=`${t}.${o} ${e} :${s} AND :${i}`,p={[s]:r,[i]:a}}else if(i===a.Operator.IN)d=`${t}.${o} ${e} (:...${l})`,p={[l]:c};else{if((i===a.Operator.STARTS_WITH||i===a.Operator.ENDS_WITH)&&"string"!=typeof c)throw new a.QueryError(`Operator ${i} requires a string comparison value`);const r=i===a.Operator.STARTS_WITH?c+"%":i===a.Operator.ENDS_WITH?"%"+c:c;d=`${t}.${o} ${e} :${l}`,p={[l]:r}}switch(s){case a.GroupOperator.AND:return{query:r.andWhere(d,p)};case a.GroupOperator.OR:return{query:r.orWhere(d,p)};case a.Operator.NOT:throw Error("NOT operator not implemented");default:return{query:r.where(d,p)}}})();if(i===a.Operator.NOT)throw Error("NOT operator not implemented");return r=this.parseCondition(o,t,r,++n).query,this.parseCondition(c,t,r,++n,i)}}class S extends a.Sequence{constructor(e,t){super(e,t)}async current(...e){const{ctx:t}=(await this.logCtx(e,n.OperationKeys.READ,!0)).for(this.current),{name:r,startWith:a}=this.options;try{if(!r)throw new n.InternalError("Sequence name is required to read current");const e=`"${r.replace(/"/g,'""')}"`,a=await this.adapter.raw({query:`SELECT last_value, is_called FROM ${e};`,values:[]},!0,t);if(!Array.isArray(a)||0===a.length)throw new n.InternalError("Failed to read current value for "+r);const s=a[0];return this.parse(s.last_value)}catch(e){if(e instanceof n.NotFoundError){if(void 0===a)throw new n.InternalError("Starting value is not defined for a non existing sequence");return this.parse(a)}throw this.adapter.parseError(e)}}async increment(e,t){const{type:r,incrementBy:a,name:s,startWith:o,minValue:i,maxValue:c,cycle:l}=this.options;if("Number"!==r&&"BigInt"!==r)throw new n.InternalError(`Cannot increment sequence of type ${r} with ${e}`);if(!s)throw new n.InternalError("Cannot increment sequence without a name: "+s);try{const o=e??a;if(o%a!==0)throw new n.InternalError("Value to increment does not consider the incrementBy setting: "+a);const i=await this.current(t),c="BigInt"===r?this.parse(i)+BigInt(o):this.parse(i)+o;return await this.adapter.raw({query:"SELECT setval($1::regclass, $2, true) AS nextval;",values:[s,c]},!0,t),c}catch(d){if(!(d instanceof n.NotFoundError))throw d;const p=`"${s.replace(/"/g,'""')}"`,u="number"==typeof o?o:a,y="number"==typeof i?" MINVALUE "+i:"number"==typeof o&&1>o?" MINVALUE "+o:"",h="number"==typeof c?" MAXVALUE "+c:"",E=l?" CYCLE":" NO CYCLE";await this.adapter.raw({query:`CREATE SEQUENCE IF NOT EXISTS ${p} START WITH ${u} INCREMENT BY ${a}${y}${h}${E};`,values:[]},!0,t);const g=e??a;if(g%a!==0)throw new n.InternalError("Value to increment does not consider the incrementBy setting: "+a);const f="number"==typeof o?o:this.parse(o),T="BigInt"===r?this.parse(f)+BigInt(g):this.parse(f)+g;return await this.adapter.raw({query:"SELECT setval($1::regclass, $2, true) AS nextval;",values:[s,T]},!0,t),T}}async next(...e){const{ctx:t}=(await this.logCtx(e,n.OperationKeys.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r}=(await this.logCtx(t,n.OperationKeys.UPDATE,!0)).for(this.range),a=await this.current(r),s=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*s,r),i=[];for(let t=1;e>=t;t++)i.push(a+s*this.parse(t));if(i[i.length-1]!==o)throw new n.InternalError("Miscalculation of range");return i}}function w(e,t,r,a=n.DefaultSeparator){return[...e.map(e=>e===h.TABLE?"table":e),h.INDEX].join(a)}function N(e){const t=w([h.TABLE]),r={};return r[t]={query:"",values:[]},e.forEach(e=>{const t=o.Model.indexes(e);Object.entries(t).forEach(([t,s])=>{const i=Object.keys(s)[0];let{compositions:c}=s[i];const l=o.Model.tableName(e);c=c||[],(()=>{const e=[t,...c,a.PersistenceKeys.INDEX].join(n.DefaultSeparator);r[e]={query:"CREATE INDEX $1 ON $2 ($3);",values:[e,l,t]}})()});let s=[];try{s=o.Model.defaultQueryAttributes(e)}catch(e){s=[]}s.forEach(t=>{const a=w([o.Model.tableName(e),t,"defaultQuery"]);r[a]={query:`CREATE INDEX ${a} ON ${o.Model.tableName(e)} (${t});`,values:[]}})}),Object.values(r)}async function M(e,r,s,i,c,l){async function d(e,t){const s=a.Repository.forModel(e.constructor);await M(s,r,e,t||i!==n.OperationKeys.UPDATE?i:n.OperationKeys.CREATE,c,t)}await n.enforceDBDecorators(e,r,s,i,c,l);for(const e of Object.keys(s))o.Model.isPropertyModel(s,e)&&void 0!==s[e]?await d(s[e],l?l[e]:void 0):t.Metadata.validationFor(s.constructor,e,o.ValidationKeys.LIST)&&s[e]&&Array.isArray(s[e])&&await Promise.all(s[e].map((t,r)=>d(t,l&&l[e]?l[e][r]:void 0)))}class I extends a.Repository{constructor(e,t,...r){super(e,t,...r),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!1,ignoreHandlers:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1})}queryBuilder(){return this.nativeRepo().createQueryBuilder()}nativeRepo(){const e=t.Metadata.constr(this.class);return this.adapter.dataSource.getRepository(e)}async createPrefix(e,...t){const{ctx:r,ctxArgs:a,log:s}=(await this.logCtx(t,n.OperationKeys.CREATE,!0)).for(this.createPrefix),o=r.get("ignoreHandlers"),i=r.get("ignoreValidation");if(s.silly(`handlerSetting: ${o}, validationSetting: ${i}`),e=new this.class(e),o||await M(this,r,e,n.OperationKeys.CREATE,n.OperationKeys.ON),!i){const t=r.get("ignoredValidationProperties")||[];s.silly("ignored validation properties: "+t);const a=await Promise.resolve(e.hasErrors(...t));if(a)throw new n.ValidationError(a.toString())}return[e,...a]}async create(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.create);n.debug(`Creating new ${this.class.name} in table ${o.Model.tableName(this.class)}`);let{record:i,id:c,transient:l}=this.adapter.prepare(e,!1,a);return i=await this.adapter.create(t.Metadata.constr(this.class),c,e,...s),this.adapter.revert(i,this.class,c,l,a)}async createSuffix(e,t){return t.get("ignoreHandlers")||await M(this,t,e,n.OperationKeys.CREATE,n.OperationKeys.AFTER),e}async readPrefix(e,...t){const{ctx:r,ctxArgs:a,log:s}=(await this.logCtx(t,n.OperationKeys.READ,!0)).for(this.readPrefix),o=r.get("ignoreHandlers");s.silly("handlerSetting: "+o);const i=new this.class;return i[this.pk]=e,o||await M(this,r,i,n.OperationKeys.READ,n.OperationKeys.ON),[e,...a]}async read(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.read);n.debug(`reading ${this.class.name} from table ${o.Model.tableName(this.class)} with pk ${this.pk}`);const i=await this.adapter.read(t.Metadata.constr(this.class),e,...s);return this.adapter.revert(i,this.class,e,void 0,a)}async readSuffix(e,t){return t.get("ignoreHandlers")||await M(this,t,e,n.OperationKeys.READ,n.OperationKeys.AFTER),e}async updatePrefix(e,...t){const{ctx:r,ctxArgs:a,log:s}=(await this.logCtx(t,n.OperationKeys.UPDATE,!0)).for(this.updatePrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");s.silly(`handlerSetting: ${i}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new n.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=o.Model.merge(d,e,this.class))),i||await M(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];s.silly("ignored validation properties: "+t);const a=await Promise.resolve(e.hasErrors(d,...o.Model.relations(this.class),...t));if(a)throw new n.ValidationError(a.toString())}return[e,...a,d]}async update(e,...r){const{ctxArgs:a,log:n,ctx:s}=this.logCtx(r,this.update);let{record:i,id:c,transient:l}=this.adapter.prepare(e,!1,s);return n.debug(`updating ${this.class.name} in table ${o.Model.tableName(this.class)} with id ${c}`),i=await this.adapter.update(t.Metadata.constr(this.class),c,e,...a),this.adapter.revert(i,this.class,c,l,s)}async updateSuffix(e,t,r){return r.get("ignoreHandlers")||await M(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.AFTER,t),e}async delete(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.delete);n.debug(`deleting new ${this.class.name} in table ${o.Model.tableName(this.class)} with pk ${e}`);const i=await this.adapter.delete(t.Metadata.constr(this.class),e,...s);return this.adapter.revert(i,this.class,e,void 0,a)}async deleteSuffix(e,t){return t.get("ignoreHandlers")||await M(this,t,e,n.OperationKeys.DELETE,n.OperationKeys.AFTER),e}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a,log:s}=(await this.logCtx(t,n.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(s.silly(`handlerSetting: ${i}, validationSetting: ${c}`),!e.length)return[e,...a];const l=o.Model.sequenceFor(e[0]);let d=[];o.Model.generatedBySequence(this.class)?(l.name||(l.name=o.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...a)):o.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new n.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),i||await M(this,r,e,n.OperationKeys.CREATE,n.OperationKeys.ON),e)));const p=r.timestamp||new Date;if(e=e.map(e=>("createdAt"in e&&Object.assign(e,{createdAt:p}),"updatedAt"in e&&Object.assign(e,{updatedAt:p}),e)),!c){const t=r.get("ignoredValidationProperties")||[];s.silly("ignored validation properties: "+t);const a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),o=n.reduceErrorsToPrint(a);if(o)throw new n.ValidationError(o)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.createAll);n.debug(`Creating ${e.length} new ${this.class.name} in table ${o.Model.tableName(this.class)}`);const i=e.map(e=>this.adapter.prepare(e,!1,a)),c=i.map(e=>e.id);let l=i.map(e=>e.record);return l=await this.adapter.createAll(t.Metadata.constr(this.class),c,e,...s),l.map((e,t)=>this.adapter.revert(e,this.class,c[t],a.get("rebuildWithTransient")?i[t].transient:void 0,a))}async createAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>M(this,t,e,n.OperationKeys.CREATE,n.OperationKeys.AFTER))),e}async readAll(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.readAll);return n.debug(`reading ${e.length} ${this.class.name} in table ${o.Model.tableName(this.class)}`),(await this.adapter.readAll(t.Metadata.constr(this.class),e,...s)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}async readAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>M(this,t,e,n.OperationKeys.READ,n.OperationKeys.AFTER))),e}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:a,log:s}=(await this.logCtx(t,n.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");s.silly(`handlerSetting: ${i}, validationSetting: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new n.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>o.Model.merge(d[t],e,this.class)))),i||await Promise.all(e.map((e,t)=>M(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.ON,d?d[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let a;s.silly("ignored validation properties: "+t),a=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const o=n.reduceErrorsToPrint(a);if(o)throw new n.ValidationError(o)}return[e,...a,d]}async updateAll(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.updateAll);n.verbose(`Updating ${e.length} new ${this.class.name} in table ${o.Model.tableName(this.class)}`);const i=e.map(e=>this.adapter.prepare(e,!1,a));return(await this.adapter.updateAll(t.Metadata.constr(this.class),i.map(e=>e.id),e,...s)).map((e,t)=>this.adapter.revert(e,this.class,i[t].id,a.get("rebuildWithTransient")?i[t].transient:void 0,a))}async updateAllSuffix(e,t,r){if(r.get("applyUpdateValidation")&&!r.get("ignoreDevSafeGuards")&&!t)throw new n.InternalError("No previous versions of models provided");return r.get("ignoreHandlers")||await Promise.all(e.map((e,a)=>M(this,r,e,n.OperationKeys.UPDATE,n.OperationKeys.AFTER,t?t[a]:void 0))),e}async deleteAll(e,...r){const{ctx:a,log:n,ctxArgs:s}=this.logCtx(r,this.create);return n.debug(`deleting ${e.length} ${this.class.name} in table ${o.Model.tableName(this.class)}`),(await this.adapter.deleteAll(t.Metadata.constr(this.class),e,...s)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}}let b=class{constructor(e,t){if(this.adapter=e,this.handler=t,!this.adapter)throw new n.InternalError("Missing adapter. Should not be possible")}async afterInsert(e){const t=e.entity.constructor,r=await this.adapter.context(n.OperationKeys.CREATE,{},t);this.handler(t,n.OperationKeys.CREATE,e.entityId,e.entity,r)}async afterRemove(e){const t=e.metadata.target,r=await this.adapter.context(n.OperationKeys.DELETE,{},t);this.handler(t,n.OperationKeys.DELETE,"",{},r)}async afterUpdate(e){const t=e.databaseEntity.constructor,r=await this.adapter.context(n.OperationKeys.UPDATE,{},t);return this.handler(t,n.OperationKeys.UPDATE,e.entity[o.Model.pk(t)],e.entity,r)}};b=r.__decorate([i.EventSubscriber(),r.__metadata("design:paramtypes",[a.Adapter,Function])],b);class C extends a.Dispatch{constructor(){super(),this.eventMode=e.TypeORMEventMode.SUBSCRIBER,this.driver=e.TypeORMDriver.POSTGRES}setEventMode(e,t){this.eventMode=e,t&&(this.driver=t)}async notificationHandler(e,t,r,...a){const{log:n,ctxArgs:s}=this.logCtx(a,this.notificationHandler);try{await this.updateObservers(e,t,r,...s),n.verbose(`Observer refresh dispatched by ${t} for ${e}`),n.debug("pks: "+r)}catch(e){n.error("Failed to process notification: "+e)}}async initialize(...t){const{log:r}=(await this.logCtx(t,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);(async function(){if(!this.adapter)throw new n.InternalError("No adapter/native observed for dispatch");try{this.adapter.client.isInitialized||await this.adapter.client.initialize();const{driver:t}=this.adapter.constructor.getDriverConfig?.(this.adapter.client)||{driver:this.driver};switch(this.driver=t,this.eventMode){case e.TypeORMEventMode.SUBSCRIBER:if(!this.subscriber){this.subscriber=new b(this.adapter,this.notificationHandler.bind(this));const e=this.adapter.client.subscribers;e&&e.push(this.subscriber)}break;case e.TypeORMEventMode.TRIGGER:switch(this.driver){case e.TypeORMDriver.POSTGRES:await this.adapter.client.query("CREATE OR REPLACE FUNCTION notify_table_changes()\nRETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'table_changes',\n json_build_object(\n 'table', TG_TABLE_NAME,\n 'action', TG_OP,\n 'data', row_to_json(NEW),\n 'old_data', row_to_json(OLD)\n )::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER;");break;case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:await this.adapter.client.query("CREATE FUNCTION notify_table_changes()\nRETURNS trigger\nBEGIN\n SELECT JSON_OBJECT('table', TG_TABLE_NAME, 'action', TG_OP, 'data', JSON_OBJECTIFY(NEW), 'old_data', JSON_OBJECTIFY(OLD)) INTO @notify_data;\n SELECT GET_LOCK('table_changes_lock', 10) INTO @lock_result;\n SELECT RELEASE_LOCK('table_changes_lock') INTO @release_result;\n RETURN NEW;\nEND;");break;case e.TypeORMDriver.SQLITE:throw Error("SQLite does not support TRIGGER mode");case e.TypeORMDriver.SQLSERVER:await this.adapter.client.query("CREATE PROCEDURE notify_table_changes\nAS\nBEGIN\n DECLARE @notify_data NVARCHAR(MAX);\n SET @notify_data = (SELECT * FROM inserted FOR JSON PATH);\n EXEC sp_notify_db_change @notify_data;\nEND;")}}}catch(e){throw new n.InternalError(e)}}).call(this).then(()=>{r.info(`Subscribed to TypeORM notifications in ${this.eventMode} mode for ${this.driver}`)}).catch(e=>{throw new n.InternalError("Failed to subscribe to TypeORM notifications: "+e)})}async close(...e){return await this.detachSubscriber(),super.close(...e)}async detachSubscriber(){if(!this.subscriber||!this.adapter)return;const e=this.adapter.client.subscribers;if(e){const t=e.indexOf(this.subscriber);0>t||e.splice(t,1)}this.subscriber=void 0}async updateObservers(e,t,r,...a){if(this.adapter)return super.updateObservers(e,t,r,...a);this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${e}:${t}`)}}function L(e,t,r){let n=0;const s=r.filter((r,a)=>(n=a,r.target===e&&r.propertyName===t));return s.length?(r.splice(n,1),Object.entries(s[0].options).reduce((e,[t,r])=>{switch(t){case"nullable":e[t]=r;break;case o.ValidationKeys.TYPE:break;default:throw new a.UnsupportedError("Unsupported option for a relation: "+t)}return e},{})):{}}function v(e,t,r,a={},s="regular",o,i){const c=r.filter(r=>r.target===e&&r.propertyName===t),l=o.filter(r=>r.target===e&&r.propertyName===t);if(i&&i.filter(r=>r.target===e&&r.columns.includes(t)).forEach(e=>{Object.assign(e,a)}),c.length>1)throw new n.InternalError(`Multiple columns for ${t} found for given target: ${r.map(e=>e.propertyName).join(", ")}`);if(l.length>1)throw new n.InternalError(`Multiple relations for ${t} found for given target: ${l.map(e=>e.propertyName).join(", ")}`);let d;0!==c.length||l.length?(l.length||(d=c[0],"regular"!==s&&Object.defineProperty(d,"mode",{value:s,writable:!0,enumerable:!0,configurable:!0})),l.length&&(a=Object.entries(a).reduce((e,[t,r])=>("nullable"===t&&(e[t]=r),e),{})),d=d||l[0],Object.defineProperty(d,"options",{value:{...d.options,...a},writable:!0,enumerable:!0,configurable:!0})):r.push({target:e,propertyName:t,mode:s,options:a})}function _(e,r){return(a,n)=>{let s;"string"==typeof e||"function"==typeof e?s=e:e&&(r=e,s=e.type),r||(r={});let o=Reflect&&Reflect.getMetadata?Reflect.getMetadata("design:type",a,n):void 0;!s&&o&&(s=o);const c=t.Metadata.allowedTypes(a.constructor,n)[0];if(c!==o&&(s=c,o=c),!r.type&&s&&(r.type=s),"hstore"!==r.type||r.hstoreType||(r.hstoreType=o===Object?"object":"string"),"function"==typeof e)i.getMetadataArgsStorage().embeddeds.push({target:a.constructor,propertyName:n,isArray:o===Array||!0===r.array,prefix:void 0!==r.prefix?r.prefix:void 0,type:e});else{if(!r.type)throw new i.ColumnTypeUndefinedError(a,n);!0===r.unique&&i.getMetadataArgsStorage().uniques.push({target:a.constructor,columns:[n]});const e=i.getMetadataArgsStorage();v(a.constructor,n,e.columns,r,"regular",e.relations,r.unique?e.indices:void 0),r.generated&&i.getMetadataArgsStorage().generations.push({target:a.constructor,propertyName:n,strategy:"string"==typeof r.generated?r.generated:"increment"})}}}class D{static isObject(e){return null!==e&&"object"==typeof e}static isObjectWithName(e){return null!==e&&"object"==typeof e&&void 0!==e.name}static assign(e,...t){for(const r of t)for(const t of Object.getOwnPropertyNames(r))e[t]=r[t]}}function $(e,t){const r={};let a;return e?("string"==typeof e&&(a=e),D.isObject(e)&&(a="increment",Object.assign(r,e))):a="increment",D.isObject(t)&&Object.assign(r,t),(e,t)=>{r.type||("increment"===a||"identity"===a?r.type=Number:"uuid"===a?r.type="uuid":"rowid"===a&&(r.type="int")),r.primary=!0;const n=i.getMetadataArgsStorage();v(e.constructor,t,n.columns,r,"regular",n.relations),i.getMetadataArgsStorage().generations.push({target:e.constructor,propertyName:t,strategy:a})}}function P(e,t){const r=(D.isObject(e)?e:t)||{},a="string"==typeof e?e:r.name;return e=>{i.getMetadataArgsStorage().tables.push({target:e,name:a,type:"regular",orderBy:r.orderBy?r.orderBy:void 0,engine:r.engine?r.engine:void 0,database:r.database?r.database:void 0,schema:r.schema?r.schema:void 0,synchronize:r.synchronize,withoutRowid:r.withoutRowid,comment:r.comment?r.comment:void 0})}}async function x(e,t,r,a){try{const t=e.get("user");a[r]=t}catch(e){throw new n.InternalError("No User found in context. Please provide a user in the context")}}class U extends a.Adapter{getClient(){const e=a.Adapter.models(this.alias).map(t.Metadata.constr);return new i.DataSource(Object.assign({},this.config,{entities:e}))}constructor(e,t){super(e,y,t),this.driver=p(e)}async shutdown(){await super.shutdown(),this._client&&await this._client.destroy()}async flags(e,t,r){return super.flags(e,t,Object.assign({user:this.config.username},r))}Dispatch(){return new C}repository(){return I}Statement(){return new m(this)}Paginator(e,t,r){return new T(this,e,t,r)}async Sequence(e){return new S(e,this)}async initialize(...e){const{log:t}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),r=this.client;try{await r.initialize()}catch(e){throw this.parseError(e)}t.verbose(this.toString()+" initialized")}async index(...e){const{log:t,ctx:r}=(await this.logCtx(e,a.PersistenceKeys.INDEX,!0)).for(this.index),n=N(e);try{await this.client.query("BEGIN");for(const e of n)await this.client.query(e.query,e.values);await this.client.query("COMMIT")}catch(e){throw await this.client.query("ROLLBACK"),this.parseError(e)}}async raw(e,t=!0,...r){const{log:a}=this.logCtx(r,this.raw);try{this.client.isInitialized||await this.client.initialize()}catch(e){throw this.parseError(e)}try{const{query:t,values:r}=e;return a.debug("executing query: "+("string"!=typeof t?t.getSql():t)),await this.client.query(t,r)}catch(e){throw this.parseError(e)}}prepare(e,r=!1,s){const i=super.prepare(e,s);i.record=Object.entries(i.record).reduce((e,[t,r])=>(t===a.PersistenceKeys.METADATA||this.isReserved(t)||void 0===r||(r instanceof Date?r=new Date(r.getTime()):o.Model.isModel(r)?r=this.prepare(r,!0,s).record:"string"==typeof r&&(r=""+r),e[t]=r),e),{});const c=o.Model.get(e.constructor.name);if(!c)throw new n.InternalError(`Model ${e.constructor.name} not found in registry`);const l=r?new(t.Metadata.constr(c)):new c;return r&&Object.defineProperty(l,"constructor",{configurable:!1,enumerable:!1,value:t.Metadata,writable:!1}),Object.entries(i.record).forEach(([e,t])=>l[e]=t),i.record=l,i}revert(e,t,r,a,...s){const{log:o}=this.logCtx(s,this.revert);return a&&(o.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([r,a])=>{if(r in e&&void 0!==e[r])throw new n.InternalError(`Transient property ${r} already exists on model ${"string"==typeof t?t:t.name}. should be impossible`);e[r]=a})),new t(e)}async create(e,t,r,...a){const s=this.client.getRepository(e);if(void 0!==t){const r=o.Model.pk(e);if(await s.findOne({where:{[r]:t}}))throw new n.ConflictError(`Record already exists in table ${o.Model.tableName(e)} with id: ${t}`)}try{return await s.save(r)}catch(e){throw this.parseError(e)}}async read(e,t,...r){let a;try{const r=this.client.getRepository(e),{nonEager:n,relations:s}=R(e),i=o.Model.pk(e),c={where:{[i]:t},relations:s,loadRelationIds:{relations:n}};a=await r.findOneOrFail(c)}catch(e){throw this.parseError(e)}return a}async update(e,t,r,...a){const{ctx:n}=this.logCtx(a,this.update);await this.read(e,t,n);try{return this.client.getRepository(e).save(r)}catch(e){throw this.parseError(e)}}async delete(e,t,...r){const{ctx:a}=this.logCtx(r,this.delete),n=await this.read(e,t,a);try{const r=this.client.getRepository(e);return await r.delete(t),n}catch(e){throw this.parseError(e)}}async createAll(e,t,r,...a){const{ctx:n,log:s}=this.logCtx(a,this.createAll),i=o.Model.tableName(e);s.debug(`Creating ${t.length} entries ${i} table`);try{const t=this.client.getRepository(e),a=await t.insert(r);return this.readAll(e,a.identifiers.map(e=>e.id),n)}catch(e){throw this.parseError(e)}}async readAll(e,t,...r){if(!t.length)return[];const{log:a}=this.logCtx(r,this.readAll),n=o.Model.tableName(e);a.debug(`Reading ${t.length} entries ${n} table`);try{const r=o.Model.pk(e);return this.client.getRepository(e).findBy({[r]:i.In(t)})}catch(e){throw this.parseError(e)}}async updateAll(e,t,r,...a){const{log:n,ctxArgs:s}=this.logCtx(a,this.updateAll),i=o.Model.tableName(e);n.debug(`Updating ${t.length} entries ${i} table`);const c=[],l=o.Model.pk(e);for(const t of r)c.push(await this.update(e,t[l],t,...s));return c}async deleteAll(e,t,...r){if(!t.length)return[];const{ctxArgs:a,log:n}=this.logCtx(r,this.deleteAll),s=o.Model.tableName(e);n.debug(`Deleting ${t.length} entries from ${s} table`);try{const r=this.client.getRepository(e),n=await this.readAll(e,t,...a),s=o.Model.pk(e);return await r.delete({[s]:i.In(t)}),n}catch(e){throw this.parseError(e)}}parseError(e,t){return U.parseError(e,t)}isReserved(e){return!!e.match(u)}static parseError(e,t){if(e instanceof n.BaseError)return e;const r="string"==typeof e?e:e.message;if(r.match(/duplicate key|already exists/g))return new n.ConflictError(r);if(r.match(/does not exist|not found|Could not find/g))return new n.NotFoundError(r);switch(r.toString()){case"23505":case"23503":case"42P07":return new n.ConflictError(t);case"42P01":case"42703":return new n.NotFoundError(t);case"42P16":return new E(e);default:return r.toString().match(/ECONNREFUSED/g)?new a.ConnectionError(e):new n.InternalError(e)}}static async connect(e){const t=new i.DataSource(e);return t.isInitialized||await t.initialize(),t}static async createDatabase(e,t){const r=s.Logging.for(this.createDatabase);r.verbose("Creating database "+t);try{await e.query("CREATE DATABASE "+t),r.info("Created database "+t)}catch(e){throw this.parseError(e)}}static async createNotifyFunction(e,t){const r=s.Logging.for(this.createNotifyFunction);r.verbose("Creating notify function");try{await e.query("CREATE OR REPLACE FUNCTION notify_table_changes()\nRETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'table_changes',\n json_build_object(\n 'table', TG_TABLE_NAME,\n 'action', TG_OP,\n 'data', row_to_json(NEW),\n 'old_data', row_to_json(OLD)\n )::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER\n;"),await e.query(`ALTER FUNCTION notify_table_changes() OWNER TO ${t};`),await e.query("\n GRANT EXECUTE ON FUNCTION notify_table_changes() TO public;\n "),r.info("Created notify function")}catch(e){throw this.parseError(e)}}static async deleteDatabase(e,t,r){try{r&&await e.query(`DROP OWNED BY ${r} CASCADE;`),await e.query("DROP DATABASE "+t)}catch(e){throw this.parseError(e)}}static async createUser(e,t,r,a){try{await e.query(`CREATE USER ${r} WITH PASSWORD '${a}'`),await e.query(`GRANT CONNECT ON DATABASE ${t} TO ${r}`),await e.query("GRANT USAGE ON SCHEMA public TO "+r),await e.query("GRANT CREATE ON SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "+r),await e.query("GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO "+r),await e.query("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO "+r),await e.query("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON SEQUENCES TO "+r)}catch(e){throw this.parseError(e)}}static async deleteUser(e,t,r){try{await e.query(`REASSIGN OWNED BY ${t} TO ${r}`),await e.query("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM "+t),await e.query("REVOKE ALL ON SCHEMA public FROM "+t),await e.query("REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM "+t),await e.query("REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM "+t),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON TABLES FROM ${t}`),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON SEQUENCES FROM ${t};`),await e.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${r} IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM ${t}`),await e.query(`DROP OWNED BY ${t} CASCADE`),await e.query(`DROP USER IF EXISTS "${t}"`)}catch(e){throw this.parseError(e)}}static parseTypeToDriver(r,a,s=!1,i){const c=r.toLowerCase();switch(i){case e.TypeORMDriver.POSTGRES:switch(c){case"string":return a?"TEXT PRIMARY KEY":s?"TEXT":"VARCHAR";case"number":return a?"SERIAL PRIMARY KEY":"INTEGER";case"boolean":return"BOOLEAN";case"date":return"TIMESTAMP";case"bigint":return a?"BIGINT PRIMARY KEY":"BIGINT";default:{const e=o.Model.get(r);if(e)return{model:e,pkType:t.Metadata.type(e,o.Model.pk(e))};throw new n.InternalError("Unsupported type: "+r)}}case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:switch(c){case"string":return a?"VARCHAR(255) PRIMARY KEY":"VARCHAR(255)";case"number":return a?"INT PRIMARY KEY AUTO_INCREMENT":"INT";case"boolean":return"TINYINT(1)";case"date":return"DATETIME";case"bigint":return a?"BIGINT PRIMARY KEY":"BIGINT";default:{const e=o.Model.get(r);if(e)return{model:e,pkType:t.Metadata.type(e,o.Model.pk(e))};throw new n.InternalError("Unsupported type: "+r)}}case e.TypeORMDriver.SQLITE:switch(c){case"string":return a?"TEXT PRIMARY KEY":"TEXT";case"number":case"bigint":return a?"INTEGER PRIMARY KEY AUTOINCREMENT":"INTEGER";case"boolean":return"INTEGER";case"date":return"DATETIME";default:{const e=o.Model.get(r);if(e)return{model:e,pkType:t.Metadata.type(e,o.Model.pk(e))};throw new n.InternalError("Unsupported type: "+r)}}case e.TypeORMDriver.SQLSERVER:switch(c){case"string":return a?"NVARCHAR(255) PRIMARY KEY":"NVARCHAR(255)";case"number":return a?"INT PRIMARY KEY IDENTITY":"INT";case"boolean":return"BIT";case"date":return"DATETIME2";case"bigint":return a?"BIGINT PRIMARY KEY IDENTITY":"BIGINT";default:{const e=o.Model.get(r);if(e)return{model:e,pkType:t.Metadata.type(e,o.Model.pk(e))};throw new n.InternalError("Unsupported type: "+r)}}}}static parseValidationToDriver(t,r,a,s,i,c){switch(s){case o.ValidationKeys.REQUIRED:return"NOT NULL";case o.ValidationKeys.MAX_LENGTH:{if(a||!i||"string"!==r.toLowerCase())return"";const t=i[o.ValidationKeys.MAX_LENGTH];switch(c){case e.TypeORMDriver.POSTGRES:case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:case e.TypeORMDriver.SQLITE:case e.TypeORMDriver.SQLSERVER:return`(${t})`}break}case o.ValidationKeys.MIN_LENGTH:{const r=i[o.ValidationKeys.MIN_LENGTH];switch(c){case e.TypeORMDriver.POSTGRES:case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:case e.TypeORMDriver.SQLITE:return`CONSTRAINT ${t}_min_length_check CHECK (LENGTH(${t}) >= ${r})`;case e.TypeORMDriver.SQLSERVER:return`CONSTRAINT ${t}_min_length_check CHECK (LEN(${t}) >= ${r})`}break}case o.ValidationKeys.PATTERN:case o.ValidationKeys.URL:case o.ValidationKeys.EMAIL:{const r=O(i[o.ValidationKeys.PATTERN]);switch(c){case e.TypeORMDriver.POSTGRES:return`CONSTRAINT ${t}_pattern_check CHECK (${t} ~ '${r}')`;case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:return`CONSTRAINT ${t}_pattern_check CHECK (${t} REGEXP '${r}')`;case e.TypeORMDriver.SQLITE:case e.TypeORMDriver.SQLSERVER:return`CONSTRAINT ${t}_pattern_check CHECK (${t} LIKE '${r}')`}break}case o.ValidationKeys.TYPE:case o.ValidationKeys.DATE:return"";case o.ValidationKeys.MIN:{const r=i[o.ValidationKeys.MIN];switch(c){case e.TypeORMDriver.POSTGRES:case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:case e.TypeORMDriver.SQLITE:case e.TypeORMDriver.SQLSERVER:return`CONSTRAINT ${t}_${s}_check CHECK (${t} >= ${r})`}}case o.ValidationKeys.MAX:{const r=i[o.ValidationKeys.MAX];switch(c){case e.TypeORMDriver.POSTGRES:case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:case e.TypeORMDriver.SQLITE:case e.TypeORMDriver.SQLSERVER:return`CONSTRAINT ${t}_${s}_check CHECK (${t} <= ${r})`}break}case o.ValidationKeys.PASSWORD:default:throw new n.InternalError("Unsupported type: "+s)}}static parseRelationsToDriver(t,r,s,i,c,l){const d=o.Model.tableName(r),{cascade:p}=c,u=`${p.update?" ON UPDATE CASCADE":""}${p.delete?" ON DELETE CASCADE":""}`;if("relations"+i===a.PersistenceKeys.ONE_TO_ONE)switch(l){case e.TypeORMDriver.POSTGRES:case e.TypeORMDriver.MYSQL:case e.TypeORMDriver.MARIA:case e.TypeORMDriver.SQLSERVER:case e.TypeORMDriver.SQLITE:return`FOREIGN KEY (${t}) REFERENCES ${d}(${s})${u}`}throw new n.InternalError("Unsupported operation: "+i)}static async getCurrentUser(e){try{return(await e.query("SELECT CURRENT_USER;"))[0].current_user}catch(e){throw this.parseError(e)}}static decoration(){super.decoration(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.TABLE).extend({decorator:e=>r=>{const a=t.Metadata.constr(r),n=i.getMetadataArgsStorage().tables.find(e=>e.target===a);return n?(e&&(n.name=e),r):(P(e||(()=>{try{return o.Model.tableName(a)}catch{return a?.name}})())(a),r)}}).apply(),t.Decoration.flavouredAs(y).for(n.DBKeys.ID).define({decorator:e=>(r,s)=>{const c=t.Metadata.constr(r.constructor);i.getMetadataArgsStorage().tables.find(e=>e.target===c)||P((()=>{try{return o.Model.tableName(c)}catch{return c?.name}})()||c?.name)(c),t.prop()(r,s);const l=[o.required(),n.readonly(),t.propMetadata(t.Metadata.key(n.DBKeys.ID,s),e)];let d=e.type||t.Metadata.type(r.constructor,s);switch(d){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated;break;case Number.name||String.name.toLowerCase():case BigInt.name||BigInt.name.toLowerCase():case BigInt:case Number:e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;case!d:throw new n.InternalError(`Missing type information for property ${s} of ${r.name}`);default:throw Error("Unsupported type")}if(void 0===e.generated&&(e.generated=!0),e.generated){const t={name:e.name||o.Model.sequenceName(r.constructor,"pk")};"serial"===e.type||"uuid"===e.type?l.push($("uuid"===e.type?e.type:"identity",t)):l.push($(t)),l.push(a.noValidateOnCreate())}else{switch("function"==typeof d&&d?.name?d.name:d){case Number.name||Number.name.toLowerCase():d="numeric";break;case"serial":case"uuid":break;case String.name||String.name.toLowerCase():d="varchar";break;case BigInt.name||BigInt.name.toLowerCase():d="bigint";break;default:throw new n.InternalError("Unsupported type: "+d)}l.push(((e,t)=>(r,a)=>{let n;e===String||e===Boolean||e===Number?n=e:t=Object.assign({},e),t||(t={});const s=Reflect&&Reflect.getMetadata?Reflect.getMetadata("design:type",r,a):void 0;if(!n&&s&&(n=s),!t.type&&n&&(t.type=n),!t.type)throw new i.ColumnTypeUndefinedError(r,a);if(t.nullable)throw new i.PrimaryColumnCannotBeNullableError(r,a);t.primary=!0;const o=i.getMetadataArgsStorage();v(r.constructor,a,o.columns,t,"regular",o.relations),t.generated&&i.getMetadataArgsStorage().generations.push({target:r.constructor,propertyName:a,strategy:"string"==typeof t.generated?t.generated:"increment"})})({type:d,unique:!0}))}return e.generated&&l.push(n.generated()),t.apply(...l)(r,s)}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.COLUMN).extend({decorator:e=>(t,r)=>{const a={};let n;e&&(a.name=e);try{n=o.Model.pk(t.constructor)}catch(e){n=void 0}return n!==r&&(a.nullable=!0),_(a)(t,r)}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.UNIQUE).define(t.propMetadata(a.PersistenceKeys.UNIQUE,{})).extend(_({unique:!0})).apply();const e=o.Validation.key(o.ValidationKeys.REQUIRED);t.Decoration.flavouredAs(y).for(e).extend(_({nullable:!1})).apply(),t.Decoration.flavouredAs(y).for(n.DBKeys.VERSION).define(o.type(Number),i.VersionColumn(),a.noValidateOnCreate()).apply();const r=n.DBKeys.TIMESTAMP,s=(c=n.DBKeys.TIMESTAMP,n.UpdateValidationKeys.REFLECT+c);var c;t.Decoration.flavouredAs(y).for(r).define({decorator:(e,r)=>{const i=[o.date(r,n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.DATE),o.required(n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.REQUIRED),t.propMetadata(o.Validation.key(n.DBKeys.TIMESTAMP),{operation:e,format:r}),a.noValidateOnCreate()];return-1!==e.indexOf(n.OperationKeys.UPDATE)?i.push(t.propMetadata(s,{message:n.DEFAULT_ERROR_MESSAGES.TIMESTAMP.INVALID}),a.noValidateOnCreateUpdate()):i.push(n.readonly()),t.apply(...i)}}).extend({decorator:(e,t)=>(t,r)=>-1!==e.indexOf(n.OperationKeys.UPDATE)?((e,t)=>{const r=i.getMetadataArgsStorage();v(e.constructor,t,r.columns,{},"updateDate",r.relations)})(t,r):((e,t)=>{const r=i.getMetadataArgsStorage();v(e.constructor,t,r.columns,{},"createDate",r.relations)})(t,r)}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.ONE_TO_ONE).define({decorator:(e,r,s,c,l)=>{const d={class:e,cascade:r,populate:s};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:s};return t.apply(t.prop(),a.relation(a.PersistenceKeys.ONE_TO_ONE,d),o.type([e,String,Number,BigInt]),t.propMetadata(a.PersistenceKeys.ONE_TO_ONE,d),((e,t,r)=>{let a;return D.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let s=!(!r||!0!==r.lazy);if(!s&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(s=!0)}const o=i.getMetadataArgsStorage();r=Object.assign(r,L(t.constructor,n,o.columns)),o.relations.push({target:t.constructor,propertyName:n,isLazy:s,relationType:"one-to-one",type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},t=>("function"!=typeof e||e.name||(e=e()),t[o.Model.pk(e)]),p),i.JoinColumn(c||d.name?{foreignKeyConstraintName:d.name}:void 0))}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.ONE_TO_MANY).define({decorator:(e,r,s,c,l)=>{const d={class:e,cascade:r,populate:s};c&&(d.joinTable=c),l&&(d.name=l);const p=[t.prop(),a.relation(a.PersistenceKeys.ONE_TO_MANY,d),o.list(e),t.propMetadata(a.PersistenceKeys.ONE_TO_MANY,d),(c,l)=>{const d={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:s};return(p=()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},u=r=>{"function"!=typeof e||e.name||(e=e());const s=t.Metadata.relations(e);if(!s)throw new n.InternalError("No relations found on model "+e.name);const i=s.find(r=>{const n=o.Model.relations(e,r);if(n.key!==a.PersistenceKeys.MANY_TO_ONE)return!1;const s="function"!=typeof n.class||n.class.name?n.class:n.class(),i=t.Metadata.constr(c.constructor);return s.name===i.name});if(!i)throw new n.InternalError(`Cross relation not found. Did you use @manyToOne on the ${e.name}?`);return r[i]},y=d,(e,t)=>{y||(y={});let r=y&&!0===y.lazy;if(!r&&Reflect&&Reflect.getMetadata){const a=Reflect.getMetadata("design:type",e,t);a&&"string"==typeof a.name&&"promise"===a.name.toLowerCase()&&(r=!0)}const a=i.getMetadataArgsStorage();y=Object.assign(y,L(e.constructor,t,a.columns)),a.relations.push({target:e.constructor,propertyName:t,isLazy:r,relationType:"one-to-many",type:p,inverseSideProperty:u,options:y})})(c,l);var p,u,y}];return t.apply(...p)}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.MANY_TO_ONE).define({decorator:(e,r,s,c,l)=>{const d={class:e,cascade:r,populate:s};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"NO ACTION",onUpdate:r.update?"CASCADE":"NO ACTION",nullable:!0,eager:s};return t.apply(a.relation(a.PersistenceKeys.MANY_TO_ONE,d),o.type([e,String,Number,BigInt]),t.propMetadata(a.PersistenceKeys.MANY_TO_ONE,d),(r,s)=>((e,t,r)=>{let a;return D.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let s=r&&!0===r.lazy;if(!s&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(s=!0)}const o=i.getMetadataArgsStorage();r=Object.assign(r,L(t.constructor,n,o.columns)),o.relations.push({target:t.constructor,propertyName:n,relationType:"many-to-one",isLazy:s,type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},n=>{"function"!=typeof e||e.name||(e=e());const s=t.Metadata.relations(e);let i=o.Model.pk(e);return s?(i=s.find(n=>{const s=o.Model.relations(e,n);if(s.key!==a.PersistenceKeys.ONE_TO_MANY)return!1;const i="function"!=typeof s.class||s.class.name?s.class:s.class(),c=t.Metadata.constr(r.constructor);return i.name===c.name})||i,n[i]):n[i]},p)(r,s))}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.MANY_TO_MANY).define({decorator:(e,r,s,c,l)=>{const d={class:e,cascade:r,populate:s};c&&(d.joinTable=c),l&&(d.name=l);const p={cascade:r.update===a.Cascade.CASCADE||r.delete===a.Cascade.CASCADE,onDelete:r.delete?"CASCADE":"DEFAULT",onUpdate:r.update?"CASCADE":"DEFAULT",nullable:!0,eager:s};return t.apply(a.relation(a.PersistenceKeys.MANY_TO_MANY,d),o.list(e),t.propMetadata(a.PersistenceKeys.MANY_TO_MANY,d),((e,t,r)=>{let a;return D.isObject(t)?r=t:a=t,(t,n)=>{r||(r={});let s=!0===r.lazy;if(!s&&Reflect&&Reflect.getMetadata){const e=Reflect.getMetadata("design:type",t,n);e&&"string"==typeof e.name&&"promise"===e.name.toLowerCase()&&(s=!0)}const o=i.getMetadataArgsStorage();r=Object.assign(r,L(t.constructor,n,o.columns)),o.relations.push({target:t.constructor,propertyName:n,relationType:"many-to-many",isLazy:s,type:e,inverseSideProperty:a,options:r})}})(()=>{"function"!=typeof e||e.name||(e=e());const r=t.Metadata.constr(e);if(r===e)throw new n.InternalError("Original Model not found in constructor");return r},t=>("function"!=typeof e||e.name||(e=e()),t[o.Model.pk(e)]),p),i.JoinTable(c))}}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.INDEX).extend({decorator:(e,t,r)=>(r,n)=>("string"==typeof e&&(e=void 0,t=void 0),"string"==typeof t&&(t=void 0),!t&&e&&e.find(e=>![a.OrderDirection.ASC,a.OrderDirection.DSC].includes(e))&&(t=e,e=void 0),t&&t.length?i.Index([n,...t])(r):i.Index()(r,n))}).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.CREATED_BY).define(n.onCreate(x,{}),o.required(),t.propMetadata(a.PersistenceKeys.CREATED_BY,{}),a.noValidateOnCreate()).apply(),t.Decoration.flavouredAs(y).for(a.PersistenceKeys.UPDATED_BY).define(n.onCreateUpdate(x,{}),o.required(),t.propMetadata(a.PersistenceKeys.UPDATED_BY,{}),a.noValidateOnCreateUpdate()).apply()}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",C)],U.prototype,"Dispatch",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",Object)],U.prototype,"repository",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",m)],U.prototype,"Statement",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],U.prototype,"Sequence",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],U.prototype,"index",null),U.decoration(),a.Adapter.setCurrent(y);const q="##VERSION##",K="##PACKAGE##";t.Metadata.registerLibrary(K,q),e.IndexError=E,e.PACKAGE_NAME=K,e.TypeORMAdapter=U,e.TypeORMConst={NULL:"NULL"},e.TypeORMDispatch=C,e.TypeORMFlavour=y,e.TypeORMGroupOperator=f,e.TypeORMKeys=h,e.TypeORMOperator=g,e.TypeORMPaginator=T,e.TypeORMQueryLimit=250,e.TypeORMRepository=I,e.TypeORMSequence=S,e.TypeORMStatement=m,e.VERSION=q,e.convertJsRegexToPostgres=O,e.detectTypeORMDriver=p,e.enforceDbDecoratorsRecursive=M,e.generateIndexes=N,e.reservedAttributes=u,e.splitEagerRelations=R,e.translateOperators=A},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("tslib"),require("@decaf-ts/core"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("typeorm")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","tslib","@decaf-ts/core","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","typeorm"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-typeorm"]={},e.decafTsDecoration,e.tslib,e.decafTsCore,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.typeorm);
2
2
  //# sourceMappingURL=for-typeorm.cjs.map