lakutata
Version:
An IoC-based universal application framework.
48,301 lines • 1.89 MB
JavaScript
/* Build Date: Mon Jan 05 2026 23:52:23 GMT+0800 (China Standard Time) */
import { r as e } from "./Package.internal.310.mjs";
import { a as t, r as n, s as a } from "./Package.internal.52.mjs";
import { c as r, g as i } from "./Package.internal.2.mjs";
import { c as s } from "./Package.internal.6.mjs";
import o from "fs";
import c from "path";
import l from "os";
import u from "crypto";
import h from "events";
import d from "stream";
import p from "module";
import m from "fs/promises";
import f from "url";
import y from "util";
import E from "node:url";
import T from "node:path";
import g from "node:fs";
import N from "node:fs/promises";
import A from "node:events";
import b from "node:stream";
import C from "node:string_decoder";
// -- Shims --
import cjsUrl from 'node:url';
import cjsPath from 'node:path';
import cjsModule from 'node:module';
const __filename = cjsUrl.fileURLToPath(import.meta.url);
const __dirname = cjsPath.dirname(__filename);
const require = cjsModule.createRequire(import.meta.url);
var R = {};
var S = {};
var w = {};
var M = {};
var O = {};
var v = {};
var I = {};
Object.defineProperty(I, "__esModule", {
value: true
});
I.ObjectUtils = void 0;
class ObjectUtils {
static isObject(e) {
return e !== null && typeof e === "object";
}
static isObjectWithName(e) {
return e !== null && typeof e === "object" && e["name"] !== undefined;
}
static assign(e, ...t) {
for (const n of t) {
for (const t of Object.getOwnPropertyNames(n)) {
e[t] = n[t];
}
}
}
static mixedListToArray(e) {
if (e !== null && typeof e === "object") {
return Object.keys(e).map(t => e[t]);
} else {
return e;
}
}
}
I.ObjectUtils = ObjectUtils;
var P = {};
var L = {};
var D = {};
Object.defineProperty(D, "__esModule", {
value: true
});
D.TypeORMError = void 0;
class TypeORMError extends Error {
get name() {
return this.constructor.name;
}
constructor(e) {
super(e);
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, new.target.prototype);
} else {
this.__proto__ = new.target.prototype;
}
}
}
D.TypeORMError = TypeORMError;
var _;
function $() {
if (_) return L;
_ = 1;
Object.defineProperty(L, "__esModule", {
value: true
});
L.CannotReflectMethodParameterTypeError = void 0;
const e = D;
let t = class CannotReflectMethodParameterTypeError extends e.TypeORMError {
constructor(e, t) {
super(`Cannot get reflected type for a "${t}" method's parameter of "${e.name}" class. ` + `Make sure you have turned on an "emitDecoratorMetadata": true option in tsconfig.json. ` + `Also make sure you have imported "reflect-metadata" on top of the main entry file in your application.`);
}
};
L.CannotReflectMethodParameterTypeError = t;
return L;
}
var x = {};
var q;
function U() {
if (q) return x;
q = 1;
Object.defineProperty(x, "__esModule", {
value: true
});
x.AlreadyHasActiveConnectionError = void 0;
const e = D;
let t = class AlreadyHasActiveConnectionError extends e.TypeORMError {
constructor(e) {
super(`Cannot create a new connection named "${e}", because connection with such name ` + `already exist and it now has an active connection session.`);
}
};
x.AlreadyHasActiveConnectionError = t;
return x;
}
var B = {};
var F;
function j() {
if (F) return B;
F = 1;
Object.defineProperty(B, "__esModule", {
value: true
});
B.SubjectWithoutIdentifierError = void 0;
const e = D;
let t = class SubjectWithoutIdentifierError extends e.TypeORMError {
constructor(e) {
super(`Internal error. Subject ${e.metadata.targetName} must have an identifier to perform operation.`);
}
};
B.SubjectWithoutIdentifierError = t;
return B;
}
var k = {};
var Q;
function V() {
if (Q) return k;
Q = 1;
Object.defineProperty(k, "__esModule", {
value: true
});
k.CannotConnectAlreadyConnectedError = void 0;
const e = D;
let t = class CannotConnectAlreadyConnectedError extends e.TypeORMError {
constructor(e) {
super(`Cannot create a "${e}" connection because connection to the database already established.`);
}
};
k.CannotConnectAlreadyConnectedError = t;
return k;
}
var K = {};
Object.defineProperty(K, "__esModule", {
value: true
});
K.LockNotSupportedOnGivenDriverError = void 0;
const W = D;
class LockNotSupportedOnGivenDriverError extends W.TypeORMError {
constructor() {
super(`Locking not supported on given driver.`);
}
}
K.LockNotSupportedOnGivenDriverError = LockNotSupportedOnGivenDriverError;
var H = {};
var G;
function Y() {
if (G) return H;
G = 1;
Object.defineProperty(H, "__esModule", {
value: true
});
H.ConnectionIsNotSetError = void 0;
const e = D;
let t = class ConnectionIsNotSetError extends e.TypeORMError {
constructor(e) {
super(`Connection with ${e} database is not established. Check connection configuration.`);
}
};
H.ConnectionIsNotSetError = t;
return H;
}
var z = {};
Object.defineProperty(z, "__esModule", {
value: true
});
z.CannotCreateEntityIdMapError = void 0;
const J = D;
class CannotCreateEntityIdMapError extends J.TypeORMError {
constructor(e, t) {
super();
const n = e.primaryColumns.reduce((e, t, n) => {
t.setEntityValue(e, n + 1);
return e;
}, {});
this.message = `Cannot use given entity id "${t}" because "${e.targetName}" contains multiple primary columns, you must provide object in following form: ${JSON.stringify(n)} as an id.`;
}
}
z.CannotCreateEntityIdMapError = CannotCreateEntityIdMapError;
var X = {};
var Z;
function ee() {
if (Z) return X;
Z = 1;
Object.defineProperty(X, "__esModule", {
value: true
});
X.MetadataAlreadyExistsError = void 0;
const e = D;
let t = class MetadataAlreadyExistsError extends e.TypeORMError {
constructor(e, t, n) {
super(e + " metadata already exists for the class constructor " + JSON.stringify(t) + (n ? " on property " + n : ". If you previously renamed or moved entity class, make sure" + " that compiled version of old entity class source wasn't left in the compiler output directory."));
}
};
X.MetadataAlreadyExistsError = t;
return X;
}
var te = {};
var ne;
function ae() {
if (ne) return te;
ne = 1;
Object.defineProperty(te, "__esModule", {
value: true
});
te.CannotDetermineEntityError = void 0;
const e = D;
let t = class CannotDetermineEntityError extends e.TypeORMError {
constructor(e) {
super(`Cannot ${e}, given value must be instance of entity class, ` + `instead object literal is given. Or you must specify an entity target to method call.`);
}
};
te.CannotDetermineEntityError = t;
return te;
}
var re = {};
Object.defineProperty(re, "__esModule", {
value: true
});
re.UpdateValuesMissingError = void 0;
const ie = D;
class UpdateValuesMissingError extends ie.TypeORMError {
constructor() {
super(`Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values.`);
}
}
re.UpdateValuesMissingError = UpdateValuesMissingError;
var se = {};
var oe;
function ce() {
if (oe) return se;
oe = 1;
Object.defineProperty(se, "__esModule", {
value: true
});
se.TreeRepositoryNotSupportedError = void 0;
const e = D;
let t = class TreeRepositoryNotSupportedError extends e.TypeORMError {
constructor(e) {
super(`Tree repositories are not supported in ${e.options.type} driver.`);
}
};
se.TreeRepositoryNotSupportedError = t;
return se;
}
var le = {};
Object.defineProperty(le, "__esModule", {
value: true
});
le.CustomRepositoryNotFoundError = void 0;
const ue = D;
class CustomRepositoryNotFoundError extends ue.TypeORMError {
constructor(e) {
super(`Custom repository ${typeof e === "function" ? e.name : e.constructor.name} was not found. ` + `Did you forgot to put @EntityRepository decorator on it?`);
}
}
le.CustomRepositoryNotFoundError = CustomRepositoryNotFoundError;
var he = {};
var de;
function pe() {
if (de) return he;
de = 1;
Object.defineProperty(he, "__esModule", {
value: true
});
he.TransactionNotStartedError = void 0;
const e = D;
let t = class TransactionNotStartedError extends e.TypeORMError {
constructor() {
super(`Transaction is not started yet, start transaction before committing or rolling it back.`);
}
};
he.TransactionNotStartedError = t;
return he;
}
var me = {};
var fe;
function ye() {
if (fe) return me;
fe = 1;
Object.defineProperty(me, "__esModule", {
value: true
});
me.TransactionAlreadyStartedError = void 0;
const e = D;
let t = class TransactionAlreadyStartedError extends e.TypeORMError {
constructor() {
super(`Transaction already started for the given connection, commit current transaction before starting a new one.`);
}
};
me.TransactionAlreadyStartedError = t;
return me;
}
var Ee = {};
var Te = {};
Object.defineProperty(Te, "__esModule", {
value: true
});
var ge = Te.InstanceChecker = void 0;
class InstanceChecker {
static isMssqlParameter(e) {
return this.check(e, "MssqlParameter");
}
static isEntityMetadata(e) {
return this.check(e, "EntityMetadata");
}
static isColumnMetadata(e) {
return this.check(e, "ColumnMetadata");
}
static isSelectQueryBuilder(e) {
return this.check(e, "SelectQueryBuilder");
}
static isInsertQueryBuilder(e) {
return this.check(e, "InsertQueryBuilder");
}
static isDeleteQueryBuilder(e) {
return this.check(e, "DeleteQueryBuilder");
}
static isUpdateQueryBuilder(e) {
return this.check(e, "UpdateQueryBuilder");
}
static isSoftDeleteQueryBuilder(e) {
return this.check(e, "SoftDeleteQueryBuilder");
}
static isRelationQueryBuilder(e) {
return this.check(e, "RelationQueryBuilder");
}
static isBrackets(e) {
return this.check(e, "Brackets") || this.check(e, "NotBrackets");
}
static isNotBrackets(e) {
return this.check(e, "NotBrackets");
}
static isSubject(e) {
return this.check(e, "Subject");
}
static isRdbmsSchemaBuilder(e) {
return this.check(e, "RdbmsSchemaBuilder");
}
static isMongoEntityManager(e) {
return this.check(e, "MongoEntityManager");
}
static isSqljsEntityManager(e) {
return this.check(e, "SqljsEntityManager");
}
static isEntitySchema(e) {
return this.check(e, "EntitySchema");
}
static isBaseEntityConstructor(e) {
return typeof e === "function" && typeof e.hasId === "function" && typeof e.save === "function" && typeof e.useDataSource === "function";
}
static isFindOperator(e) {
return this.check(e, "FindOperator") || this.check(e, "EqualOperator");
}
static isEqualOperator(e) {
return this.check(e, "EqualOperator");
}
static isQuery(e) {
return this.check(e, "Query");
}
static isTable(e) {
return this.check(e, "Table");
}
static isTableCheck(e) {
return this.check(e, "TableCheck");
}
static isTableColumn(e) {
return this.check(e, "TableColumn");
}
static isTableExclusion(e) {
return this.check(e, "TableExclusion");
}
static isTableForeignKey(e) {
return this.check(e, "TableForeignKey");
}
static isTableIndex(e) {
return this.check(e, "TableIndex");
}
static isTableUnique(e) {
return this.check(e, "TableUnique");
}
static isView(e) {
return this.check(e, "View");
}
static isDataSource(e) {
return this.check(e, "DataSource");
}
static check(e, t) {
return typeof e === "object" && e !== null && e["@instanceof"] === Symbol.for(t);
}
}
ge = Te.InstanceChecker = InstanceChecker;
Object.defineProperty(Ee, "__esModule", {
value: true
});
Ee.EntityNotFoundError = void 0;
const Ne = D;
const Ae = I;
const be = Te;
class EntityNotFoundError extends Ne.TypeORMError {
constructor(e, t) {
super();
this.entityClass = e;
this.criteria = t;
this.message = `Could not find any entity of type "${this.stringifyTarget(e)}" ` + `matching: ${this.stringifyCriteria(t)}`;
}
stringifyTarget(e) {
if (be.InstanceChecker.isEntitySchema(e)) {
return e.options.name;
} else if (typeof e === "function") {
return e.name;
} else if (Ae.ObjectUtils.isObject(e) && "name" in e) {
return e.name;
} else {
return e;
}
}
stringifyCriteria(e) {
try {
return JSON.stringify(e, null, 4);
} catch (e) {}
return "" + e;
}
}
Ee.EntityNotFoundError = EntityNotFoundError;
var Ce = {};
var Re;
function Se() {
if (Re) return Ce;
Re = 1;
Object.defineProperty(Ce, "__esModule", {
value: true
});
Ce.EntityMetadataNotFoundError = void 0;
const e = D;
const t = I;
const n = Te;
let a = class EntityMetadataNotFoundError extends e.TypeORMError {
constructor(e) {
super();
this.message = `No metadata for "${this.stringifyTarget(e)}" was found.`;
}
stringifyTarget(e) {
if (n.InstanceChecker.isEntitySchema(e)) {
return e.options.name;
} else if (typeof e === "function") {
return e.name;
} else if (t.ObjectUtils.isObject(e) && "name" in e) {
return e.name;
} else {
return e;
}
}
};
Ce.EntityMetadataNotFoundError = a;
return Ce;
}
var we = {};
var Me;
function Oe() {
if (Me) return we;
Me = 1;
Object.defineProperty(we, "__esModule", {
value: true
});
we.MustBeEntityError = void 0;
const e = D;
let t = class MustBeEntityError extends e.TypeORMError {
constructor(e, t) {
super(`Cannot ${e}, given value must be an entity, instead "${t}" is given.`);
}
};
we.MustBeEntityError = t;
return we;
}
var ve = {};
Object.defineProperty(ve, "__esModule", {
value: true
});
ve.OptimisticLockVersionMismatchError = void 0;
const Ie = D;
class OptimisticLockVersionMismatchError extends Ie.TypeORMError {
constructor(e, t, n) {
super(`The optimistic lock on entity ${e} failed, version ${t} was expected, but is actually ${n}.`);
}
}
ve.OptimisticLockVersionMismatchError = OptimisticLockVersionMismatchError;
var Pe = {};
Object.defineProperty(Pe, "__esModule", {
value: true
});
Pe.LimitOnUpdateNotSupportedError = void 0;
const Le = D;
class LimitOnUpdateNotSupportedError extends Le.TypeORMError {
constructor() {
super(`Your database does not support LIMIT on UPDATE statements.`);
}
}
Pe.LimitOnUpdateNotSupportedError = LimitOnUpdateNotSupportedError;
var De = {};
Object.defineProperty(De, "__esModule", {
value: true
});
De.PrimaryColumnCannotBeNullableError = void 0;
const _e = D;
class PrimaryColumnCannotBeNullableError extends _e.TypeORMError {
constructor(e, t) {
super(`Primary column ${e.constructor.name}#${t} cannot be nullable. ` + `Its not allowed for primary keys. Try to remove nullable option.`);
}
}
De.PrimaryColumnCannotBeNullableError = PrimaryColumnCannotBeNullableError;
var $e = {};
var xe;
function qe() {
if (xe) return $e;
xe = 1;
Object.defineProperty($e, "__esModule", {
value: true
});
$e.CustomRepositoryCannotInheritRepositoryError = void 0;
const e = D;
let t = class CustomRepositoryCannotInheritRepositoryError extends e.TypeORMError {
constructor(e) {
super(`Custom entity repository ${typeof e === "function" ? e.name : e.constructor.name} ` + ` cannot inherit Repository class without entity being set in the @EntityRepository decorator.`);
}
};
$e.CustomRepositoryCannotInheritRepositoryError = t;
return $e;
}
var Ue = {};
Object.defineProperty(Ue, "__esModule", {
value: true
});
Ue.QueryRunnerProviderAlreadyReleasedError = void 0;
const Be = D;
class QueryRunnerProviderAlreadyReleasedError extends Be.TypeORMError {
constructor() {
super(`Database connection provided by a query runner was already ` + `released, cannot continue to use its querying methods anymore.`);
}
}
Ue.QueryRunnerProviderAlreadyReleasedError = QueryRunnerProviderAlreadyReleasedError;
var Fe = {};
var je;
function ke() {
if (je) return Fe;
je = 1;
Object.defineProperty(Fe, "__esModule", {
value: true
});
Fe.CannotAttachTreeChildrenEntityError = void 0;
const e = D;
let t = class CannotAttachTreeChildrenEntityError extends e.TypeORMError {
constructor(e) {
super(`Cannot attach entity "${e}" to its parent. Please make sure parent ` + `is saved in the database before saving children nodes.`);
}
};
Fe.CannotAttachTreeChildrenEntityError = t;
return Fe;
}
var Qe = {};
Object.defineProperty(Qe, "__esModule", {
value: true
});
Qe.CustomRepositoryDoesNotHaveEntityError = void 0;
const Ve = D;
class CustomRepositoryDoesNotHaveEntityError extends Ve.TypeORMError {
constructor(e) {
super(`Custom repository ${typeof e === "function" ? e.name : e.constructor.name} does not have managed entity. ` + `Did you forget to specify entity for it @EntityRepository(MyEntity)? `);
}
}
Qe.CustomRepositoryDoesNotHaveEntityError = CustomRepositoryDoesNotHaveEntityError;
var Ke = {};
var We;
function He() {
if (We) return Ke;
We = 1;
Object.defineProperty(Ke, "__esModule", {
value: true
});
Ke.MissingDeleteDateColumnError = void 0;
const e = D;
let t = class MissingDeleteDateColumnError extends e.TypeORMError {
constructor(e) {
super(`Entity "${e.name}" does not have delete date columns.`);
}
};
Ke.MissingDeleteDateColumnError = t;
return Ke;
}
var Ge = {};
var Ye;
function ze() {
if (Ye) return Ge;
Ye = 1;
Object.defineProperty(Ge, "__esModule", {
value: true
});
Ge.NoConnectionForRepositoryError = void 0;
const e = D;
let t = class NoConnectionForRepositoryError extends e.TypeORMError {
constructor(e) {
super(`Cannot get a Repository for "${e} connection, because connection with the database ` + `is not established yet. Call connection#connect method to establish connection.`);
}
};
Ge.NoConnectionForRepositoryError = t;
return Ge;
}
var Je = {};
var Xe;
function Ze() {
if (Xe) return Je;
Xe = 1;
Object.defineProperty(Je, "__esModule", {
value: true
});
Je.CircularRelationsError = void 0;
const e = D;
let t = class CircularRelationsError extends e.TypeORMError {
constructor(e) {
super(`Circular relations detected: ${e}. To resolve this issue you need to ` + `set nullable: true somewhere in this dependency structure.`);
}
};
Je.CircularRelationsError = t;
return Je;
}
var et = {};
Object.defineProperty(et, "__esModule", {
value: true
});
et.ReturningStatementNotSupportedError = void 0;
const tt = D;
class ReturningStatementNotSupportedError extends tt.TypeORMError {
constructor() {
super(`OUTPUT or RETURNING clause only supported by PostgreSQL, MariaDB, Microsoft SqlServer or Google Spanner.`);
}
}
et.ReturningStatementNotSupportedError = ReturningStatementNotSupportedError;
var nt = {};
var at;
function rt() {
if (at) return nt;
at = 1;
Object.defineProperty(nt, "__esModule", {
value: true
});
nt.UsingJoinTableIsNotAllowedError = void 0;
const e = D;
let t = class UsingJoinTableIsNotAllowedError extends e.TypeORMError {
constructor(e, t) {
super(`Using JoinTable on ${e.name}#${t.propertyName} is wrong. ` + `${e.name}#${t.propertyName} has ${t.relationType} relation, ` + `however you can use JoinTable only on many-to-many relations.`);
}
};
nt.UsingJoinTableIsNotAllowedError = t;
return nt;
}
var it = {};
var st;
function ot() {
if (st) return it;
st = 1;
Object.defineProperty(it, "__esModule", {
value: true
});
it.MissingJoinColumnError = void 0;
const e = D;
let t = class MissingJoinColumnError extends e.TypeORMError {
constructor(e, t) {
super();
if (t.inverseRelation) {
this.message = `JoinColumn is missing on both sides of ${e.name}#${t.propertyName} and ` + `${t.inverseEntityMetadata.name}#${t.inverseRelation.propertyName} one-to-one relationship. ` + `You need to put JoinColumn decorator on one of the sides.`;
} else {
this.message = `JoinColumn is missing on ${e.name}#${t.propertyName} one-to-one relationship. ` + `You need to put JoinColumn decorator on it.`;
}
}
};
it.MissingJoinColumnError = t;
return it;
}
var ct = {};
var lt;
function ut() {
if (lt) return ct;
lt = 1;
Object.defineProperty(ct, "__esModule", {
value: true
});
ct.MissingPrimaryColumnError = void 0;
const e = D;
let t = class MissingPrimaryColumnError extends e.TypeORMError {
constructor(e) {
super(`Entity "${e.name}" does not have a primary column. Primary column is required to ` + `have in all your entities. Use @PrimaryColumn decorator to add a primary column to your entity.`);
}
};
ct.MissingPrimaryColumnError = t;
return ct;
}
var ht = {};
Object.defineProperty(ht, "__esModule", {
value: true
});
ht.EntityPropertyNotFoundError = void 0;
const dt = D;
class EntityPropertyNotFoundError extends dt.TypeORMError {
constructor(e, t) {
super(e);
Object.setPrototypeOf(this, EntityPropertyNotFoundError.prototype);
this.message = `Property "${e}" was not found in "${t.targetName}". Make sure your query is correct.`;
}
}
ht.EntityPropertyNotFoundError = EntityPropertyNotFoundError;
var pt = {};
var mt;
function ft() {
if (mt) return pt;
mt = 1;
Object.defineProperty(pt, "__esModule", {
value: true
});
pt.MissingDriverError = void 0;
const e = D;
let t = class MissingDriverError extends e.TypeORMError {
constructor(e, t = []) {
super(`Wrong driver: "${e}" given. Supported drivers are: ` + `${t.map(e => `"${e}"`).join(", ")}.`);
}
};
pt.MissingDriverError = t;
return pt;
}
var yt = {};
var Et;
function Tt() {
if (Et) return yt;
Et = 1;
Object.defineProperty(yt, "__esModule", {
value: true
});
yt.DriverPackageNotInstalledError = void 0;
const e = D;
let t = class DriverPackageNotInstalledError extends e.TypeORMError {
constructor(e, t) {
super(`${e} package has not been found installed. ` + `Try to install it: npm install ${t} --save`);
}
};
yt.DriverPackageNotInstalledError = t;
return yt;
}
var gt = {};
var Nt;
function At() {
if (Nt) return gt;
Nt = 1;
Object.defineProperty(gt, "__esModule", {
value: true
});
gt.CannotGetEntityManagerNotConnectedError = void 0;
const e = D;
let t = class CannotGetEntityManagerNotConnectedError extends e.TypeORMError {
constructor(e) {
super(`Cannot get entity manager for "${e}" connection because connection is not yet established.`);
}
};
gt.CannotGetEntityManagerNotConnectedError = t;
return gt;
}
var bt = {};
var Ct;
function Rt() {
if (Ct) return bt;
Ct = 1;
Object.defineProperty(bt, "__esModule", {
value: true
});
bt.ConnectionNotFoundError = void 0;
const e = D;
let t = class ConnectionNotFoundError extends e.TypeORMError {
constructor(e) {
super(`Connection "${e}" was not found.`);
}
};
bt.ConnectionNotFoundError = t;
return bt;
}
var St = {};
Object.defineProperty(St, "__esModule", {
value: true
});
St.NoVersionOrUpdateDateColumnError = void 0;
const wt = D;
class NoVersionOrUpdateDateColumnError extends wt.TypeORMError {
constructor(e) {
super(`Entity ${e} does not have version or update date columns.`);
}
}
St.NoVersionOrUpdateDateColumnError = NoVersionOrUpdateDateColumnError;
var Mt = {};
Object.defineProperty(Mt, "__esModule", {
value: true
});
Mt.InsertValuesMissingError = void 0;
const Ot = D;
class InsertValuesMissingError extends Ot.TypeORMError {
constructor() {
super(`Cannot perform insert query because values are not defined. ` + `Call "qb.values(...)" method to specify inserted values.`);
}
}
Mt.InsertValuesMissingError = InsertValuesMissingError;
var vt = {};
Object.defineProperty(vt, "__esModule", {
value: true
});
vt.OptimisticLockCanNotBeUsedError = void 0;
const It = D;
class OptimisticLockCanNotBeUsedError extends It.TypeORMError {
constructor() {
super(`The optimistic lock can be used only with getOne() method.`);
}
}
vt.OptimisticLockCanNotBeUsedError = OptimisticLockCanNotBeUsedError;
var Pt = {};
var Lt;
function Dt() {
if (Lt) return Pt;
Lt = 1;
Object.defineProperty(Pt, "__esModule", {
value: true
});
Pt.MetadataWithSuchNameAlreadyExistsError = void 0;
const e = D;
let t = class MetadataWithSuchNameAlreadyExistsError extends e.TypeORMError {
constructor(e, t) {
super(e + " metadata with such name " + t + " already exists. " + "Do you apply decorator twice? Or maybe try to change a name?");
}
};
Pt.MetadataWithSuchNameAlreadyExistsError = t;
return Pt;
}
var _t = {};
var $t;
function xt() {
if ($t) return _t;
$t = 1;
Object.defineProperty(_t, "__esModule", {
value: true
});
_t.DriverOptionNotSetError = void 0;
const e = D;
let t = class DriverOptionNotSetError extends e.TypeORMError {
constructor(e) {
super(`Driver option (${e}) is not set. ` + `Please set it to perform connection to the database.`);
}
};
_t.DriverOptionNotSetError = t;
return _t;
}
var qt = {};
var Ut;
function Bt() {
if (Ut) return qt;
Ut = 1;
Object.defineProperty(qt, "__esModule", {
value: true
});
qt.FindRelationsNotFoundError = void 0;
const e = D;
let t = class FindRelationsNotFoundError extends e.TypeORMError {
constructor(e) {
super();
if (e.length === 1) {
this.message = `Relation "${e[0]}" was not found; please check if it is correct and really exists in your entity.`;
} else {
this.message = `Relations ${e.map(e => `"${e}"`).join(", ")} were not found; please check if relations are correct and they exist in your entities.`;
}
}
};
qt.FindRelationsNotFoundError = t;
return qt;
}
var Ft = {};
Object.defineProperty(Ft, "__esModule", {
value: true
});
Ft.PessimisticLockTransactionRequiredError = void 0;
const jt = D;
class PessimisticLockTransactionRequiredError extends jt.TypeORMError {
constructor() {
super(`An open transaction is required for pessimistic lock.`);
}
}
Ft.PessimisticLockTransactionRequiredError = PessimisticLockTransactionRequiredError;
var kt = {};
var Qt;
function Vt() {
if (Qt) return kt;
Qt = 1;
Object.defineProperty(kt, "__esModule", {
value: true
});
kt.RepositoryNotTreeError = void 0;
const e = D;
const t = I;
const n = Te;
let a = class RepositoryNotTreeError extends e.TypeORMError {
constructor(e) {
super();
let a;
if (n.InstanceChecker.isEntitySchema(e)) {
a = e.options.name;
} else if (typeof e === "function") {
a = e.name;
} else if (t.ObjectUtils.isObject(e) && "name" in e) {
a = e.name;
} else {
a = e;
}
this.message = `Repository of the "${a}" class is not a TreeRepository. Try to apply @Tree decorator on your entity.`;
}
};
kt.RepositoryNotTreeError = a;
return kt;
}
var Kt = {};
var Wt;
function Ht() {
if (Wt) return Kt;
Wt = 1;
Object.defineProperty(Kt, "__esModule", {
value: true
});
Kt.DataTypeNotSupportedError = void 0;
const e = D;
let t = class DataTypeNotSupportedError extends e.TypeORMError {
constructor(e, t, n) {
super();
const a = typeof t === "string" ? t : t.name;
this.message = `Data type "${a}" in "${e.entityMetadata.targetName}.${e.propertyName}" is not supported by "${n}" database.`;
}
};
Kt.DataTypeNotSupportedError = t;
return Kt;
}
var Gt = {};
var Yt;
function zt() {
if (Yt) return Gt;
Yt = 1;
Object.defineProperty(Gt, "__esModule", {
value: true
});
Gt.InitializedRelationError = void 0;
const e = D;
let t = class InitializedRelationError extends e.TypeORMError {
constructor(e) {
super(`Array initializations are not allowed in entity relations. ` + `Please remove array initialization (= []) from "${e.entityMetadata.targetName}#${e.propertyPath}". ` + `This is ORM requirement to make relations to work properly. Refer docs for more information.`);
}
};
Gt.InitializedRelationError = t;
return Gt;
}
var Jt = {};
var Xt;
function Zt() {
if (Xt) return Jt;
Xt = 1;
Object.defineProperty(Jt, "__esModule", {
value: true
});
Jt.MissingJoinTableError = void 0;
const e = D;
let t = class MissingJoinTableError extends e.TypeORMError {
constructor(e, t) {
super();
if (t.inverseRelation) {
this.message = `JoinTable is missing on both sides of ${e.name}#${t.propertyName} and ` + `${t.inverseEntityMetadata.name}#${t.inverseRelation.propertyName} many-to-many relationship. ` + `You need to put decorator decorator on one of the sides.`;
} else {
this.message = `JoinTable is missing on ${e.name}#${t.propertyName} many-to-many relationship. ` + `You need to put JoinTable decorator on it.`;
}
}
};
Jt.MissingJoinTableError = t;
return Jt;
}
var en = {};
var tn;
function nn() {
if (tn) return en;
tn = 1;
Object.defineProperty(en, "__esModule", {
value: true
});
en.QueryFailedError = void 0;
const e = I;
const t = D;
let n = class QueryFailedError extends t.TypeORMError {
constructor(t, n, a) {
super(a.toString().replace(/^error: /, "").replace(/^Error: /, "").replace(/^Request/, ""));
this.query = t;
this.parameters = n;
this.driverError = a;
if (a) {
const {name: t, ...n} = a;
e.ObjectUtils.assign(this, {
...n
});
}
}
};
en.QueryFailedError = n;
return en;
}
var an = {};
Object.defineProperty(an, "__esModule", {
value: true
});
an.NoNeedToReleaseEntityManagerError = void 0;
const rn = D;
class NoNeedToReleaseEntityManagerError extends rn.TypeORMError {
constructor() {
super(`Entity manager is not using single database connection and cannot be released. ` + `Only entity managers created by connection#createEntityManagerWithSingleDatabaseConnection ` + `methods have a single database connection and they should be released.`);
}
}
an.NoNeedToReleaseEntityManagerError = NoNeedToReleaseEntityManagerError;
var sn = {};
var on;
function cn() {
if (on) return sn;
on = 1;
Object.defineProperty(sn, "__esModule", {
value: true
});
sn.UsingJoinColumnOnlyOnOneSideAllowedError = void 0;
const e = D;
let t = class UsingJoinColumnOnlyOnOneSideAllowedError extends e.TypeORMError {
constructor(e, t) {
super(`Using JoinColumn is allowed only on one side of the one-to-one relationship. ` + `Both ${e.name}#${t.propertyName} and ${t.inverseEntityMetadata.name}#${t.inverseRelation.propertyName} ` + `has JoinTable decorators. Choose one of them and left JoinTable decorator only on it.`);
}
};
sn.UsingJoinColumnOnlyOnOneSideAllowedError = t;
return sn;
}
var ln = {};
var un;
function hn() {
if (un) return ln;
un = 1;
Object.defineProperty(ln, "__esModule", {
value: true
});
ln.UsingJoinTableOnlyOnOneSideAllowedError = void 0;
const e = D;
let t = class UsingJoinTableOnlyOnOneSideAllowedError extends e.TypeORMError {
constructor(e, t) {
super(`Using JoinTable is allowed only on one side of the many-to-many relationship. ` + `Both ${e.name}#${t.propertyName} and ${t.inverseEntityMetadata.name}#${t.inverseRelation.propertyName} ` + `has JoinTable decorators. Choose one of them and left JoinColumn decorator only on it.`);
}
};
ln.UsingJoinTableOnlyOnOneSideAllowedError = t;
return ln;
}
var dn = {};
var pn;
function mn() {
if (pn) return dn;
pn = 1;
Object.defineProperty(dn, "__esModule", {
value: true
});
dn.SubjectRemovedAndUpdatedError = void 0;
const e = D;
let t = class SubjectRemovedAndUpdatedError extends e.TypeORMError {
constructor(e) {
super(`Removed entity "${e.metadata.name}" is also scheduled for update operation. ` + `Make sure you are not updating and removing same object (note that update or remove may be executed by cascade operations).`);
}
};
dn.SubjectRemovedAndUpdatedError = t;
return dn;
}
var fn = {};
var yn;
function En() {
if (yn) return fn;
yn = 1;
Object.defineProperty(fn, "__esModule", {
value: true
});
fn.PersistedEntityNotFoundError = void 0;
const e = D;
let t = class PersistedEntityNotFoundError extends e.TypeORMError {
constructor() {
super(`Internal error. Persisted entity was not found in the list of prepared operated entities.`);
}
};
fn.PersistedEntityNotFoundError = t;
return fn;
}
var Tn = {};
var gn;
function Nn() {
if (gn) return Tn;
gn = 1;
Object.defineProperty(Tn, "__esModule", {
value: true
});
Tn.UsingJoinColumnIsNotAllowedError = void 0;
const e = D;
let t = class UsingJoinColumnIsNotAllowedError extends e.TypeORMError {
constructor(e, t) {
super(`Using JoinColumn on ${e.name}#${t.propertyName} is wrong. ` + `You can use JoinColumn only on one-to-one and many-to-one relations.`);
}
};
Tn.UsingJoinColumnIsNotAllowedError = t;
return Tn;
}
var An = {};
Object.defineProperty(An, "__esModule", {
value: true
});
An.ColumnTypeUndefinedError = void 0;
const bn = D;
class ColumnTypeUndefinedError extends bn.TypeORMError {
constructor(e, t) {
super(`Column type for ${e.constructor.name}#${t} is not defined and cannot be guessed. ` + `Make sure you have turned on an "emitDecoratorMetadata": true option in tsconfig.json. ` + `Also make sure you have imported "reflect-metadata" on top of the main entry file in your application (before any entity imported).` + `If you are using JavaScript instead of TypeScript you must explicitly provide a column type.`);
}
}
An.ColumnTypeUndefinedError = ColumnTypeUndefinedError;
var Cn = {};
var Rn;
function Sn() {
if (Rn) return Cn;
Rn = 1;
Object.defineProperty(Cn, "__esModule", {
value: true
});
Cn.QueryRunnerAlreadyReleasedError = void 0;
const e = D;
let t = class QueryRunnerAlreadyReleasedError extends e.TypeORMError {
constructor() {
super(`Query runner already released. Cannot run queries anymore.`);
}
};
Cn.QueryRunnerAlreadyReleasedError = t;
return Cn;
}
var wn = {};
Object.defineProperty(wn, "__esModule", {
value: true
});
wn.OffsetWithoutLimitNotSupportedError = void 0;
const Mn = D;
class OffsetWithoutLimitNotSupportedError extends Mn.TypeORMError {
constructor() {
super(`RDBMS does not support OFFSET without LIMIT in SELECT statements. You must use limit in ` + `conjunction with offset function (or take in conjunction with skip function if you are ` + `using pagination).`);
}
}
wn.OffsetWithoutLimitNotSupportedError = OffsetWithoutLimitNotSupportedError;
var On = {};
var vn;
function In() {
if (vn) return On;
vn = 1;
Object.defineProperty(On, "__esModule", {
value: true
});
On.CannotExecuteNotConnectedError = void 0;
const e = D;
let t = class CannotExecuteNotConnectedError extends e.TypeORMError {
constructor(e) {
super(`Cannot execute operation on "${e}" connection because connection is not yet established.`);
}
};
On.CannotExecuteNotConnectedError = t;
return On;
}
var Pn = {};
var Ln;
function Dn() {
if (Ln) return Pn;
Ln = 1;
Object.defineProperty(Pn, "__esModule", {
value: true
});
Pn.NoConnectionOptionError = void 0;
const e = D;
let t = class NoConnectionOptionError extends e.TypeORMError {
constructor(e) {
super(`Option "${e}" is not set in your connection options, please ` + `define "${e}" option in your connection options or ormconfig.json`);
}
};
Pn.NoConnectionOptionError = t;
return Pn;
}
var _n = {};
var $n;
function xn() {
if ($n) return _n;
$n = 1;
Object.defineProperty(_n, "__esModule", {
value: true
});
_n.ForbiddenTransactionModeOverrideError = void 0;
const e = D;
let t = class ForbiddenTransactionModeOverrideError extends e.TypeORMError {
constructor(e) {
const t = e.map(e => `"${e.name}"`);
super(`Migrations ${t.join(", ")} override the transaction mode, but the global transaction mode is "all"`);
}
};
_n.ForbiddenTransactionModeOverrideError = t;
return _n;
}
(function(t) {
Object.defineProperty(t, "__esModule", {
value: true
});
const n = e;
n.__exportStar($(), t);
n.__exportStar(U(), t);
n.__exportStar(j(), t);
n.__exportStar(V(), t);
n.__exportStar(K, t);
n.__exportStar(Y(), t);
n.__exportStar(z, t);
n.__exportStar(ee(), t);
n.__exportStar(ae(), t);
n.__exportStar(re, t);
n.__exportStar(ce(), t);
n.__exportStar(le, t);
n.__exportStar(pe(), t);
n.__exportStar(ye(), t);
n.__exportStar(Ee, t);
n.__exportStar(Se(), t);
n.__exportStar(Oe(), t);
n.__exportStar(ve, t);
n.__exportStar(Pe, t);
n.__exportStar(De, t);
n.__exportStar(qe(), t);
n.__exportStar(Ue, t);
n.__exportStar(ke(), t);
n.__exportStar(Qe, t);
n.__exportStar(He(), t);
n.__exportStar(ze(), t);
n.__exportStar(Ze(), t);
n.__exportStar(et, t);
n.__exportStar(rt(), t);
n.__exportStar(ot(), t);
n.__exportStar(ut(), t);
n.__exportStar(ht, t);
n.__exportStar(ft(), t);
n.__exportStar(Tt(), t);
n.__exportStar(At(), t);
n.__exportStar(Rt(), t);
n.__exportStar(St, t);
n.__exportStar(Mt, t);
n.__exportStar(vt, t);
n.__exportStar(Dt(), t);
n.__exportStar(xt(), t);
n.__exportStar(Bt(), t);
n.__exportStar(Ft, t);
n.__exportStar(Vt(), t);
n.__exportStar(Ht(), t);
n.__exportStar(zt(), t);
n.__exportStar(Zt(), t);
n.__exportStar(nn(), t);
n.__exportStar(an, t);
n.__exportStar(cn(), t);
n.__exportStar(hn(), t);
n.__exportStar(mn(), t);
n.__exportStar(En(), t);
n.__exportStar(Nn(), t);
n.__exportStar(An, t);
n.__exportStar(Sn(), t);
n.__exportStar(wn, t);
n.__exportStar(In(), t);
n.__exportStar(Dn(), t);
n.__exportStar(D, t);
n.__exportStar(xn(), t);
})(P);
Object.defineProperty(v, "__esModule", {
value: true
});
v.Alias = void 0;
const qn = I;
const Un = P;
class Alias {
constructor(e) {
qn.ObjectUtils.assign(this, e || {});
}
get target() {
return this.metadata.target;
}
get hasMetadata() {
return !!this._metadata;
}
set metadata(e) {
this._metadata = e;
}
get metadata() {
if (!this._metadata) throw new Un.TypeORMError(`Cannot get entity metadata for the given alias "${this.name}"`);
return this._metadata;
}
}
v.Alias = Alias;
var Bn = {};
var Fn = {};
Object.defineProperty(Fn, "__esModule", {
value: true
});
Fn.QueryBuilderUtils = void 0;
class QueryBuilderUtils {
static isAliasProperty(e) {
if (typeof e !== "string" || e.indexOf(".") === -1) return false;
const [t, n] = e.split(".");
if (!t || !n) return false;
if (e.indexOf("(") !== -1 || e.indexOf(")") !== -1) return false;
return true;
}
}
Fn.QueryBuilderUtils = QueryBuilderUtils;
var jn = {};
var kn = {};
var Qn = {
exports: {}
};
var Vn;
var Kn;
function Wn() {
if (Kn) return Vn;
Kn = 1;
var e = {}.toString;
Vn = Array.isArray || function(t) {
return e.call(t) == "[object Array]";
};
return Vn;
}
var Hn;
var Gn;
function Yn() {
if (Gn) return Hn;
Gn = 1;
Hn = TypeError;
return Hn;
}
var zn;
var Jn;
function Xn() {
if (Jn) return zn;
Jn = 1;
zn = Object;
return zn;
}
var Zn;
var ea;
function ta() {
if (ea) return Zn;
ea = 1;
Zn = Error;
return Zn;
}
var na;
var aa;
function ra() {
if (aa) return na;
aa = 1;
na = EvalError;
return na;
}
var ia;
var sa;
function oa() {
if (sa) return ia;
sa = 1;
ia = RangeError;
return ia;
}
var ca;
var la;
function ua() {
if (la) return ca;
la = 1;
ca = ReferenceError;
return ca;
}
var ha;
var da;
function pa() {
if (da) return ha;
da = 1;
ha = SyntaxError;
return ha;
}
var ma;
var fa;
function ya() {
if (fa) return ma;
fa = 1;
ma = URIError;
return ma;
}
var Ea;
var Ta;
function ga() {
if (Ta) return Ea;
Ta = 1;
Ea = Math.abs;
return Ea;
}
var Na;
var Aa;
function ba() {
if (Aa) return Na;
Aa = 1;
Na = Math.floor;
return Na;
}
var Ca;
var Ra;
function Sa() {
if (Ra) return Ca;
Ra = 1;
Ca = Math.max;
return Ca;
}
var wa;
var Ma;
function Oa() {
if (Ma) return wa;
Ma = 1;
wa = Math.min;
return wa;
}
var va;
var Ia;
function Pa() {
if (Ia) return va;
Ia = 1;
va = Math.pow;
return va;
}
var La;
var Da;
function _a() {
if (Da) return La;
Da = 1;
La = Math.round;
return La;
}
var $a;
var xa;
function qa() {
if (xa) return $a;
xa = 1;
$a = Number.isNaN || function e(t) {
return t !== t;
};
return $a;
}
var Ua;
var Ba;
function Fa() {
if (Ba) return Ua;
Ba = 1;
var e = qa();
Ua = function t(n) {
if (e(n) || n === 0) {
return n;
}
return n < 0 ? -1 : 1;
};
return Ua;
}
var ja;
var ka;
function Qa() {
if (ka) return ja;
ka = 1;
ja = Object.getOwnPropertyDescriptor;
return ja;
}
var Va;
var Ka;
function Wa() {
if (Ka) return Va;
Ka = 1;
var e = Qa();
if (e) {
try {
e([], "length");
} catch (t) {
e = null;
}
}
Va = e;
return Va;
}
var Ha;
var Ga;
function Ya() {
if (Ga) return Ha;
Ga = 1;
var e = Object.defineProperty || false;
if (e) {
try {
e({}, "a", {
value: 1
});
} catch (t) {
e = false;
}
}
Ha = e;
return Ha;
}
var za;
var Ja;
function Xa() {
if (Ja) return za;
Ja = 1;
za = function e() {
if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
return false;
}
if (typeof Symbol.iterator === "symbol") {
return true;
}
var t = {};
var n = Symbol("test");
var a = Object(n);
if (typeof n === "string") {
return false;
}
if (Object.prototype.toString.call(n) !== "[object Symbol]") {
return false;
}
if (Object.prototype.toString.call(a) !== "[object Symbol]") {
return false;
}
var r = 42;
t[n] = r;
for (var i in t) {
return false;
}
if (typeof Object.keys === "function" && Object.keys(t).length !== 0) {
return false;
}
if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(t).length !== 0) {
return false;
}
var s = Object.getOwnPropertySymbols(t);
if (s.length !== 1 || s[0] !== n) {
return false;
}
if (!Object.prototype.propertyIsEnumerable.call(t, n)) {
return false;
}
if (typeof Object.getOwnPropertyDescriptor === "function") {
var o = Object.getOwnPropertyDescriptor(t, n);
if (o.value !== r || o.enumerable !== true) {
return false;
}
}
return true;
};
return za;
}
var Za;
var er;
function tr() {
if (er) return Za;
er = 1;
var e = typeof Symbol !== "undefined" && Symbol;
var t = Xa();
Za = function n() {
if (typeof e !== "function") {
return false;
}
if (typeof Symbol !== "function") {
return false;
}
if (typeof e("foo") !== "symbol") {
return false;
}
if (typeof Symbol("bar") !== "symbol") {
return false;
}
return t();
};
return Za;
}
var nr;
var ar;
function rr() {
if (ar) return nr;
ar = 1;
nr = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
return nr;
}
var ir;
var sr;
function or() {
if (sr) return ir;
sr = 1;
var e = Xn();
ir = e.getPrototypeOf || null;
return ir;
}
var cr;
var lr;
function ur() {
if (lr) return cr;
lr = 1;
var e = "Function.prototype.bind called on incompatible ";
var t = Object.prototype.toString;
var n = Math.max;
var a = "[object Function]";
var r = function e(t, n) {
var a = [];
for (var r = 0; r < t.length; r += 1) {
a[r] = t[r];
}
for (var i = 0; i < n.length; i += 1) {
a[i + t.length] = n[i];
}
return a;
};
var i = function e(t, n) {
var a = [];
for (var r = n || 0, i = 0; r < t.length; r += 1, i += 1) {
a[i] = t[r];
}
return a;
};
var s = function(e, t) {
var n = "";
for (var a = 0; a < e.length; a += 1) {
n += e[a];
if (a + 1 < e.length) {
n += t;
}
}
return n;
};
cr = function o(c) {
var l = this;
if (typeof l !== "function" || t.apply(l) !== a) {
throw new TypeError(e + l);
}
var u = i(arguments, 1);
var h;
var d = function() {
if (this instanceof h) {
var e = l.apply(this, r(u, arguments));
if (Object(e) === e) {
return e;
}
return this;
}
return l.apply(c, r(u, arguments));
};
var p = n(0, l.length - u.length);
var m = [];
for (var f = 0; f < p; f++) {
m[f] = "$" + f;
}
h = Function("binder", "return function (" + s(m, ",") + "){ return binder.apply(this,arguments); }")(d);
if (l.prototype) {
var y = function e() {};
y.prototype = l.prototype;
h.prototype = new y;
y.prototype = null;
}
return h;
};
return cr;
}
var hr;
var dr;
function pr() {
if (dr) return hr;
dr = 1;
var e = ur();
hr = Function.prototype.bind || e;
return hr;
}
var mr;
var fr;
function yr() {
if (fr) return mr;
fr = 1;
mr = Function.prototype.call;
return mr;
}
var Er;
var Tr;
function gr() {
if (Tr) return Er;
Tr = 1;
Er = Function.prototype.apply;
return Er;
}
var Nr;
var Ar;
function br() {
if (Ar) return Nr;
Ar = 1;
Nr = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
return Nr;
}
var Cr;
var Rr;
function Sr() {
if (Rr) return Cr;
Rr = 1;
var e = pr();
var t = gr();
var n = yr();
var a = br();
Cr = a || e.call(n, t);
return Cr;
}
var wr;
var Mr;
function Or() {
if (Mr) return wr;
Mr = 1;
var e = pr();
var t = Yn();
var n = yr();
var a = Sr();
wr = function r(i) {
if (i.length < 1 || typeof i[0] !== "function") {
throw new t("a function is required");
}
return a(e, n, i);
};
return wr;
}
var vr;
var Ir;
function Pr() {
if (Ir) return vr;
Ir = 1;
var e = Or();
var t = Wa();
var n;
try {
n = [].__proto__ === Array.prototype;
} catch (e) {
if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
throw e;
}
}
var a = !!n && t && t(Object.prototype, "__proto__");
var r = Object;
var i = r.getPrototypeOf;
vr = a && typeof a.get === "function" ? e([ a.get ]) : typeof i === "function" ? function e(t) {
return i(t == null ? t : r(t));
} : false;
return vr;
}
var Lr;
var Dr;
function _r() {
if (Dr) return Lr;
Dr = 1;
var e = rr();
var t = or();
var n = Pr();
Lr = e ? function t(n) {
return e(n);
} : t ? function e(n) {
if (!n || typeof n !== "object" && typeof n !== "function") {
throw new TypeError("getProto: not an object");
}
return t(n);
} : n ? function e(t) {
return n(t);
} : null;
return Lr;
}
var $r;
var xr;
function qr() {
if (xr) return $r;
xr = 1;
var e = Function.prototype.call;
var t = Object.prototype.hasOwnProperty;
var n = pr();
$r = n.call(e, t);
return $r;
}
var Ur;
var Br;
function Fr() {
if (Br) return Ur;
Br = 1;
var e;
var t = Xn();
var n = ta();
var a = ra();
var r = oa();
var i = ua();
var s = pa();
var o = Yn();
var c = ya();
var l = ga();
var u = ba();
var h = Sa();
var d = Oa();
var p = Pa();
var m = _a();
var f = Fa();
var y = Function;
var E = function(e) {
try {
return y('"use strict"; return (' + e + ").constructor;")();
} catch (e) {}
};
var T = Wa();
var g = Ya();
var N = function() {
throw new o;
};
var A = T ? function() {
try {
arguments.callee;
return N;
} catch (e) {
try {
return T(arguments, "callee").get;
} catch (e) {
return N;
}
}
}() : N;
var b = tr()();
var C = _r();
var R = or();
var S = rr();
var w = gr();
var M = yr();
var O = {};
var v = typeof Uint8Array === "undefined" || !C ? e : C(Uint8Array);
var I = {
__proto__: null,
"%AggregateError%": typeof AggregateError === "undefined" ? e : AggregateError,
"%Array%": Array,
"%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? e : ArrayBuffer,
"%ArrayIteratorPrototype%": b && C ? C([][Symbol.iterator]()) : e,
"%AsyncFromSyncIteratorPrototype%": e,
"%AsyncFunction%": O,
"%AsyncGenerator%": O,
"%AsyncGeneratorFunction%": O,
"%AsyncIteratorPrototype%": O,
"%Atomics%": typeof Atomics === "undefined" ? e : Atomics,
"%BigInt%": typeof BigInt === "undefined" ? e : BigInt,
"%BigInt64Array%": typeof BigInt64Array === "undefined" ? e : BigInt64Array,
"%BigUint64Array%": typeof BigUint64Array === "undefined" ? e : BigUint64Array,
"%Boolean%": Boolean,
"%DataView%": typeof DataView === "undefined" ? e : DataView,
"%Date%": Date,
"%decodeURI%": decodeURI,
"%decodeURIComponent%": decodeURIComponent,
"%encodeURI%": encodeURI,
"%encodeURIComponent%": encodeURIComponent,
"%Error%": n,
"%eval%": eval,
"%EvalError%": a,
"%Float16Array%": typeof Float16Array === "undefined" ? e : Float16Array,
"%Float32Array%": typeof Float32Array === "undefined" ? e : Float32Array,
"%Float64Array%": typeof Float64Array === "undefined" ? e : Float64Array,
"%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? e : FinalizationRegistry,
"%Function%": y,
"%GeneratorFunction%": O,
"%Int8Array%": typeof Int8Array === "undefined" ? e : Int8Array,
"%Int16Array%": typeof Int16Array === "undefined" ? e : Int16Array,
"%Int32Array%": typeof Int32Array === "undefined" ? e : Int32Array,
"%isFinite%": isFinite,
"%isNaN%": isNaN,
"%IteratorPrototype%": b && C ? C(C([][Symbol.iterator]())) : e,
"%JSON%": typeof JSON === "object" ? JSON : e,
"%Map%": typeof Map === "undefined" ? e : Map,
"%MapIteratorPrototype%": typeof Map === "undefined" || !b || !C ? e : C((new Map)[Symbol.iterator]()),
"%Math%": Math,
"%Number%": Number,
"%Object%": t,
"%Object.getOwnPropertyDescriptor%": T,
"%parseFloat%": parseFloat,
"%parseInt%": parseInt,
"%Promise%": typeof Promise === "undefined" ? e : Promise,
"%Proxy%": typeof Proxy === "undefined" ? e : Proxy,
"%RangeError%": r,
"%ReferenceError%": i,
"%Reflect%": typeof Reflect === "undefined" ? e : Reflect,
"%RegExp%": RegExp,
"%Set%": typeof Set === "undefined" ? e : Set,
"%SetIteratorPrototype%": typeof Set === "undefined" || !b || !C ? e : C((new Set)[Symbol.iterator]()),
"%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? e : SharedArrayBuffer,
"%String%": String,
"%StringIteratorPrototype%": b && C ? C(""[Symbol.iterator]()) : e,
"%Symbol%": b ? Symbol : e,
"%SyntaxError%": s,
"%ThrowTypeError%": A,
"%TypedArray%": v,
"%TypeError%": o,
"%Uint8Array%": typeof Uint8Array === "undefined" ? e : Uint8Array,
"%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? e : Uint8ClampedArray,
"%Uint16Array%": typeof Uint16Array === "undefined" ? e : Uint16Array,
"%Uint32Array%": typeof Uint32Array === "undefined" ? e : Uint32Array,
"%URIError%": c,
"%WeakMap%": typeof WeakMap === "undefined" ? e : WeakMap,
"%WeakRef%": typeof WeakRef === "undefined" ? e : WeakRef,
"%WeakSet%": typeof WeakSet === "undefined" ? e : WeakSet,
"%Function.prototype.call%": M,
"%Function.prototype.apply%": w,
"%Object.defineProperty%": g,
"%Object.getPrototypeOf%": R,
"%Math.abs%": l,
"%Math.floor%": u,
"%Math.max%": h,
"%Math.min%": d,
"%Math.pow%": p,
"%Math.round%": m,
"%Math.sign%": f,
"%Reflect.getPrototypeOf%": S
};
if (C) {
try {
null.error;
} catch (e) {
var P = C(C(e));
I["%Error.prototype%"] = P;
}
}
var L = function e(t) {
var n;
if (t === "%AsyncFunction%") {
n = E("async function () {}");
} else if (t === "%GeneratorFunction%") {
n = E("function* () {}");
} else if (t === "%AsyncGeneratorFunction%") {
n = E("async function* () {}");
} else if (t === "%AsyncGenerator%") {
var a = e("%AsyncGeneratorFunction%");
if (a) {
n = a.prototype;
}
} else if (t === "%AsyncIteratorPrototype%") {
var r = e("%AsyncGenerator%");
if (r && C) {
n = C(r.prototype);
}
}
I[t] = n;
return n;
};
var D = {
__proto__: null,
"%ArrayBufferPrototype%": [ "ArrayBuffer", "prototype" ],
"%ArrayPrototype%": [ "Array", "prototype" ],
"%ArrayProto_entries%": [ "Array", "prototype", "entries" ],
"%ArrayProto_forEach%": [ "Array", "prototype", "forEach" ],
"%ArrayProto_keys%": [ "Array", "prototype", "keys" ],
"%ArrayProto_values%": [ "Array", "prototype", "values" ],
"%AsyncFunctionPrototype%": [ "AsyncFunction", "prototype" ],
"%AsyncGenerator%": [ "AsyncGeneratorFunction", "prototype" ],
"%AsyncGeneratorPrototype%": [ "AsyncGeneratorFunction", "prototype", "prototype" ],
"%BooleanPrototype%": [ "Boolean", "prototype" ],
"%DataViewPrototype%": [ "DataView", "prototype" ],
"%DatePrototype%": [ "Date", "prototype" ],
"%ErrorPrototype%": [ "Error", "prototype" ],
"%EvalErrorPrototype%": [ "EvalError", "prototype" ],
"%Float32ArrayPrototype%": [ "Float32Array", "prototype" ],
"%Float64ArrayPrototype%": [ "Float64Array", "prototype" ],
"%FunctionPrototype%": [ "Function", "prototype" ],
"%Generator%": [ "GeneratorFunction", "prototype" ],
"%GeneratorPrototype%": [ "GeneratorFunction", "prototype", "prototype" ],
"%Int8ArrayPrototype%": [ "Int8Array", "prototype" ],
"%Int16ArrayPrototype%": [ "Int16Array", "prototype" ],
"%Int32ArrayPrototype%": [ "Int32Array", "prototype" ],
"%JSONParse%": [ "JSON", "parse" ],
"%JSONStringify%": [ "JSON", "stringify" ],
"%MapPrototype%": [ "Map", "prototype" ],
"%NumberPrototype%": [ "Number", "prototype" ],
"%ObjectPrototype%": [ "Object", "prototype" ],
"%ObjProto_toString%": [ "Object", "prototype", "toString" ],
"%ObjProto_valueOf%": [ "Object", "prototype", "valueOf" ],
"%PromisePrototype%": [ "Promise", "prototype" ],
"%PromiseProto_then%": [ "Promise", "prototype", "then" ],
"%Promise_all%": [ "Promise", "all" ],
"%Promise_reject%": [ "Promise", "reject" ],
"%Promise_resolve%": [ "Promise", "resolve" ],
"%RangeErrorPrototype%": [ "RangeError", "prototype" ],
"%ReferenceErrorPrototype%": [ "ReferenceError", "prototype" ],
"%RegExpPrototype%": [ "RegExp", "prototype" ],
"%SetPrototype%": [ "Set", "prototype" ],
"%SharedArrayBufferPrototype%": [ "SharedArrayBuffer", "prototype" ],
"%StringPrototype%": [ "String", "prototype" ],
"%SymbolPrototype%": [ "Symbol", "prototype" ],
"%SyntaxErrorPrototype%": [ "SyntaxError", "prototype" ],
"%TypedArrayPrototype%": [ "TypedArray", "prototype" ],
"%TypeErrorPrototype%": [ "TypeError", "prototype" ],
"%Uint8ArrayPrototype%": [ "Uint8Array", "prototype" ],
"%Uint8ClampedArrayPrototype%": [ "Uint8ClampedArray", "prototype" ],
"%Uint16ArrayPrototype%": [ "Uint16Array", "prototype" ],
"%Uint32ArrayPrototype%": [ "Uint32Array", "prototype" ],
"%URIErrorPrototype%": [ "URIError", "prototype" ],
"%WeakMapPrototype%": [ "WeakMap", "prototype" ],
"%WeakSetPrototype%": [ "WeakSet", "prototype" ]
};
var _ = pr();
var $ = qr();
var x = _.call(M, Array.prototype.concat);
var q = _.call(w, Array.prototype.splice);
var U = _.call(M, String.prototype.replace);
var B = _.call(M, String.prototype.slice);
var F = _.call(M, RegExp.prototype.exec);
var j = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var k = /\\(\\)?/g;
var Q = function e(t) {
var n = B(t, 0, 1);
var a = B(t, -1);
if (n === "%" && a !== "%") {
throw new s("invalid intrinsic syntax, expected closing `%`");
} else if (a === "%" && n !== "%") {
throw new s("invalid intrinsic syntax, expected opening `%`");
}
var r = [];
U(t, j, function(e, t, n, a) {
r[r.length] = n ? U(a, k, "$1") : t || e;
});
return r;
};
var V = function e(t, n) {
var a = t;
var r;
if ($(D, a)) {
r = D[a];
a = "%" + r[0] + "%";
}
if ($(I, a)) {
var i = I[a];
if (i === O) {
i = L(a);
}
if (typeof i === "undefined" && !n) {
throw new o("intrinsic " + t + " exists, but is not available. Please file an issue!");
}
return {
alias: r,
name: a,
value: i
};
}
throw new s("intrinsic " + t + " does not exist!");
};
Ur = function t(n, a) {
if (typeof n !== "string" || n.length === 0) {
throw new o("intrinsic name must be a non-empty string");
}
if (arguments.length > 1 && typeof a !== "boolean") {
throw new o('"allowMissing" argument must be a boolean');
}
if (F(/^%?[^%]*%?$/, n) === null) {
throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
}
var r = Q(n);
var i = r.length > 0 ? r[0] : "";
var c = V("%" + i + "%", a);
var l = c.name;
var u = c.value;
var h = false;
var d = c.alias;
if (d) {
i = d[0];
q(r, x([ 0, 1 ], d));
}
for (var p = 1, m = true; p < r.length; p += 1) {
var f = r[p];
var y = B(f, 0, 1);
var E = B(f, -1);
if ((y === '"' || y === "'" || y === "`" || (E === '"' || E === "'" || E === "`")) && y !== E) {
throw new s("property names with quotes must have matching quotes");
}
if (f === "constructor" || !m) {
h = true;
}
i += "." + f;
l = "%" + i + "%";
if ($(I, l)) {
u = I[l];
} else if (u != null) {
if (!(f in u)) {
if (!a) {
throw new o("base intrinsic for " + n + " exists, but the property is not available.");
}
return void e;
}
if (T && p + 1 >= r.length) {
var g = T(u, f);
m = !!g;
if (m && "get" in g && !("originalValue" in g.get)) {
u = g.get;
} else {
u = u[f];
}
} else {
m = $(u, f);
u = u[f];
}
if (m && !h) {
I[l] = u;
}
}
}
return u;
};
return Ur;
}
var jr;
var kr;
function Qr() {
if (kr) return jr;
kr = 1;
var e = Fr();
var t = Or();
var n = t([ e("%String.prototype.indexOf%") ]);
jr = function a(r, i) {
var s = e(r, !!i);
if (typeof s === "function" && n(r, ".prototype.") > -1) {
return t([ s ]);
}
return s;
};
return jr;
}
var Vr;
var Kr;
function Wr() {
if (Kr) return Vr;
Kr = 1;
var e = Function.prototype.toString;
var t = typeof Reflect === "object" && Reflect !== null && Reflect.apply;
var n;
var a;
if (typeof t === "function" && typeof Object.defineProperty === "function") {
try {
n = Object.defineProperty({}, "length", {
get: function() {
throw a;
}
});
a = {};
t(function() {
throw 42;
}, null, n);
} catch (e) {
if (e !== a) {
t = null;
}
}
} else {
t = null;
}
var r = /^\s*class\b/;
var i = function t(n) {
try {
var a = e.call(n);
return r.test(a);
} catch (e) {
return false;
}
};
var s = function t(n) {
try {
if (i(n)) {
return false;
}
e.call(n);
return true;
} catch (e) {
return false;
}
};
var o = Object.prototype.toString;
var c = "[object Object]";
var l = "[object Function]";
var u = "[object GeneratorFunction]";
var h = "[object HTMLAllCollection]";
var d = "[object HTML document.all class]";
var p = "[object HTMLCollection]";
var m = typeof Symbol === "function" && !!Symbol.toStringTag;
var f = !(0 in [ , ]);
var y = function e() {
return false;
};
if (typeof document === "object") {
var E = document.all;
if (o.call(E) === o.call(document.all)) {
y = function e(t) {
if ((f || !t) && (typeof t === "undefined" || typeof t === "object")) {
try {
var n = o.call(t);
return (n === h || n === d || n === p || n === c) && t("") == null;
} catch (e) {}
}
return false;
};
}
}
Vr = t ? function e(r) {
if (y(r)) {
return true;
}
if (!r) {
return false;
}
if (typeof r !== "function" && typeof r !== "object") {
return false;
}
try {
t(r, null, n);
} catch (e) {
if (e !== a) {
return false;
}
}
return !i(r) && s(r);
} : function e(t) {
if (y(t)) {
return true;
}
if (!t) {
return false;
}
if (typeof t !== "function" && typeof t !== "object") {
return false;
}
if (m) {
return s(t);
}
if (i(t)) {
return false;
}
var n = o.call(t);
if (n !== l && n !== u && !/^\[object HTML/.test(n)) {
return false;
}
return s(t);
};
return Vr;
}
var Hr;
var Gr;
function Yr() {
if (Gr) return Hr;
Gr = 1;
var e = Wr();
var t = Object.prototype.toString;
var n = Object.prototype.hasOwnProperty;
var a = function e(t, a, r) {
for (var i = 0, s = t.length; i < s; i++) {
if (n.call(t, i)) {
if (r == null) {
a(t[i], i, t);
} else {
a.call(r, t[i], i, t);
}
}
}
};
var r = function e(t, n, a) {
for (var r = 0, i = t.length; r < i; r++) {
if (a == null) {
n(t.charAt(r), r, t);
} else {
n.call(a, t.charAt(r), r, t);
}
}
};
var i = function e(t, a, r) {
for (var i in t) {
if (n.call(t, i)) {
if (r == null) {
a(t[i], i, t);
} else {
a.call(r, t[i], i, t);
}
}
}
};
function s(e) {
return t.call(e) === "[object Array]";
}
Hr = function t(n, o, c) {
if (!e(o)) {
throw new TypeError("iterator must be a function");
}
var l;
if (arguments.length >= 3) {
l = c;
}
if (s(n)) {
a(n, o, l);
} else if (typeof n === "string") {
r(n, o, l);
} else {
i(n, o, l);
}
};
return Hr;
}
var zr;
var Jr;
function Xr() {
if (Jr) return zr;
Jr = 1;
zr = [ "Float16Array", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "BigInt64Array", "BigUint64Array" ];
return zr;
}
var Zr;
var ei;
function ti() {
if (ei) return Zr;
ei = 1;
var e = Xr();
var t = typeof globalThis === "undefined" ? r : globalThis;
Zr = function n() {
var a = [];
for (var r = 0; r < e.length; r++) {
if (typeof t[e[r]] === "function") {
a[a.length] = e[r];
}
}
return a;
};
return Zr;
}
var ni = {
exports: {}
};
var ai;
var ri;
function ii() {
if (ri) return ai;
ri = 1;
var e = Ya();
var t = pa();
var n = Yn();
var a = Wa();
ai = function r(i, s, o) {
if (!i || typeof i !== "object" && typeof i !== "function") {
throw new n("`obj` must be an object or a function`");
}
if (typeof s !== "string" && typeof s !== "symbol") {
throw new n("`property` must be a string or a symbol`");
}
if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) {
throw new n("`nonEnumerable`, if provided, must be a boolean or null");
}
if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) {
throw new n("`nonWritable`, if provided, must be a boolean or null");
}
if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) {
throw new n("`nonConfigurable`, if provided, must be a boolean or null");
}
if (arguments.length > 6 && typeof arguments[6] !== "boolean") {
throw new n("`loose`, if provided, must be a boolean");
}
var c = arguments.length > 3 ? arguments[3] : null;
var l = arguments.length > 4 ? arguments[4] : null;
var u = arguments.length > 5 ? arguments[5] : null;
var h = arguments.length > 6 ? arguments[6] : false;
var d = !!a && a(i, s);
if (e) {
e(i, s, {
configurable: u === null && d ? d.configurable : !u,
enumerable: c === null && d ? d.enumerable : !c,
value: o,
writable: l === null && d ? d.writable : !l
});
} else if (h || !c && !l && !u) {
i[s] = o;
} else {
throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
}
};
return ai;
}
var si;
var oi;
function ci() {
if (oi) return si;
oi = 1;
var e = Ya();
var t = function t() {
return !!e;
};
t.hasArrayLengthDefineBug = function t() {
if (!e) {
return null;
}
try {
return e([], "length", {
value: 1
}).length !== 1;
} catch (e) {
return true;
}
};
si = t;
return si;
}
var li;
var ui;
function hi() {
if (ui) return li;
ui = 1;
var e = Fr();
var t = ii();
var n = ci()();
var a = Wa();
var r = Yn();
var i = e("%Math.floor%");
li = function e(s, o) {
if (typeof s !== "function") {
throw new r("`fn` is not a function");
}
if (typeof o !== "number" || o < 0 || o > 4294967295 || i(o) !== o) {
throw new r("`length` must be a positive 32-bit integer");
}
var c = arguments.length > 2 && !!arguments[2];
var l = true;
var u = true;
if ("length" in s && a) {
var h = a(s, "length");
if (h && !h.configurable) {
l = false;
}
if (h && !h.writable) {
u = false;
}
}
if (l || u || !c) {
if (n) {
t(s, "length", o, true, true);
} else {
t(s, "length", o);
}
}
return s;
};
return li;
}
var di;
var pi;
function mi() {
if (pi) return di;
pi = 1;
var e = pr();
var t = gr();
var n = Sr();
di = function a() {
return n(e, t, arguments);
};
return di;
}
ni.exports;
var fi;
function yi() {
if (fi) return ni.exports;
fi = 1;
(function(e) {
var t = hi();
var n = Ya();
var a = Or();
var r = mi();
e.exports = function e(n) {
var r = a(arguments);
var i = n.length - (arguments.length - 1);
return t(r, 1 + (i > 0 ? i : 0), true);
};
if (n) {
n(e.exports, "apply", {
value: r
});
} else {
e.exports.apply = r;
}
})(ni);
return ni.exports;
}
var Ei;
var Ti;
function gi() {
if (Ti) return Ei;
Ti = 1;
var e = Xa();
Ei = function t() {
return e() && !!Symbol.toStringTag;
};
return Ei;
}
var Ni;
var Ai;
function bi() {
if (Ai) return Ni;
Ai = 1;
var e = Yr();
var t = ti();
var n = yi();
var a = Qr();
var i = Wa();
var s = _r();
var o = a("Object.prototype.toString");
var c = gi()();
var l = typeof globalThis === "undefined" ? r : globalThis;
var u = t();
var h = a("String.prototype.slice");
var d = a("Array.prototype.indexOf", true) || function e(t, n) {
for (var a = 0; a < t.length; a += 1) {
if (t[a] === n) {
return a;
}
}
return -1;
};
var p = {
__proto__: null
};
if (c && i && s) {
e(u, function(e) {
var t = new l[e];
if (Symbol.toStringTag in t && s) {
var a = s(t);
var r = i(a, Symbol.toStringTag);
if (!r && a) {
var o = s(a);
r = i(o, Symbol.toStringTag);
}
p["$" + e] = n(r.get);
}
});
} else {
e(u, function(e) {
var t = new l[e];
var a = t.slice || t.set;
if (a) {
p["$" + e] = n(a);
}
});
}
var m = function t(n) {
var a = false;
e(p, function(e, t) {
if (!a) {
try {
if ("$" + e(n) === t) {
a = h(t, 1);
}
} catch (e) {}
}
});
return a;
};
var f = function t(n) {
var a = false;
e(p, function(e, t) {
if (!a) {
try {
e(n);
a = h(t, 1);
} catch (e) {}
}
});
return a;
};
Ni = function e(t) {
if (!t || typeof t !== "object") {
return false;
}
if (!c) {
var n = h(o(t), 8, -1);
if (d(u, n) > -1) {
return n;
}
if (n !== "Object") {
return false;
}
return f(t);
}
if (!i) {
return null;
}
return m(t);
};
return Ni;
}
var Ci;
var Ri;
function Si() {
if (Ri) return Ci;
Ri = 1;
var e = bi();
Ci = function t(n) {
return !!e(n);
};
return Ci;
}
var wi;
var Mi;
function Oi() {
if (Mi) return wi;
Mi = 1;
var e = Yn();
var t = Qr();
var n = t("TypedArray.prototype.buffer", true);
var a = Si();
wi = n || function t(n) {
if (!a(n)) {
throw new e("Not a Typed Array");
}
return n.buffer;
};
return wi;
}
var vi;
var Ii;
function Pi() {
if (Ii) return vi;
Ii = 1;
var e = t().Buffer;
var n = Wn();
var a = Oi();
var r = ArrayBuffer.isView || function e(t) {
try {
a(t);
return true;
} catch (e) {
return false;
}
};
var i = typeof Uint8Array !== "undefined";
var s = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
var o = s && (e.prototype instanceof Uint8Array || e.TYPED_ARRAY_SUPPORT);
vi = function t(a, c) {
if (e.isBuffer(a)) {
if (a.constructor && !("isBuffer" in a)) {
return e.from(a);
}
return a;
}
if (typeof a === "string") {
return e.from(a, c);
}
if (s && r(a)) {
if (a.byteLength === 0) {
return e.alloc(0);
}
if (o) {
var l = e.from(a.buffer, a.byteOffset, a.byteLength);
if (l.byteLength === a.byteLength) {
return l;
}
}
var u = a instanceof Uint8Array ? a : new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
var h = e.from(u);
if (h.length === a.byteLength) {
return h;
}
}
if (i && a instanceof Uint8Array) {
return e.from(a);
}
var d = n(a);
if (d) {
for (var p = 0; p < a.length; p += 1) {
var m = a[p];
if (typeof m !== "number" || m < 0 || m > 255 || ~~m !== m) {
throw new RangeError("Array items must be numbers in the range 0-255.");
}
}
}
if (d || e.isBuffer(a) && a.constructor && typeof a.constructor.isBuffer === "function" && a.constructor.isBuffer(a)) {
return e.from(a);
}
throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
};
return vi;
}
var Li;
var Di;
function _i() {
if (Di) return Li;
Di = 1;
var e = t().Buffer;
var n = Pi();
function a(t, n) {
this._block = e.alloc(t);
this._finalSize = n;
this._blockSize = t;
this._len = 0;
}
a.prototype.update = function(e, t) {
e = n(e, t || "utf8");
var a = this._block;
var r = this._blockSize;
var i = e.length;
var s = this._len;
for (var o = 0; o < i; ) {
var c = s % r;
var l = Math.min(i - o, r - c);
for (var u = 0; u < l; u++) {
a[c + u] = e[o + u];
}
s += l;
o += l;
if (s % r === 0) {
this._update(a);
}
}
this._len += i;
return this;
};
a.prototype.digest = function(e) {
var t = this._len % this._blockSize;
this._block[t] = 128;
this._block.fill(0, t + 1);
if (t >= this._finalSize) {
this._update(this._block);
this._block.fill(0);
}
var n = this._len * 8;
if (n <= 4294967295) {
this._block.writeUInt32BE(n, this._blockSize - 4);
} else {
var a = (n & 4294967295) >>> 0;
var r = (n - a) / 4294967296;
this._block.writeUInt32BE(r, this._blockSize - 8);
this._block.writeUInt32BE(a, this._blockSize - 4);
}
this._update(this._block);
var i = this._hash();
return e ? i.toString(e) : i;
};
a.prototype._update = function() {
throw new Error("_update must be implemented by subclass");
};
Li = a;
return Li;
}
var $i;
var xi;
function qi() {
if (xi) return $i;
xi = 1;
var e = n();
var a = _i();
var r = t().Buffer;
var i = [ 1518500249, 1859775393, 2400959708 | 0, 3395469782 | 0 ];
var s = new Array(80);
function o() {
this.init();
this._w = s;
a.call(this, 64, 56);
}
e(o, a);
o.prototype.init = function() {
this._a = 1732584193;
this._b = 4023233417;
this._c = 2562383102;
this._d = 271733878;
this._e = 3285377520;
return this;
};
function c(e) {
return e << 5 | e >>> 27;
}
function l(e) {
return e << 30 | e >>> 2;
}
function u(e, t, n, a) {
if (e === 0) {
return t & n | ~t & a;
}
if (e === 2) {
return t & n | t & a | n & a;
}
return t ^ n ^ a;
}
o.prototype._update = function(e) {
var t = this._w;
var n = this._a | 0;
var a = this._b | 0;
var r = this._c | 0;
var s = this._d | 0;
var o = this._e | 0;
for (var h = 0; h < 16; ++h) {
t[h] = e.readInt32BE(h * 4);
}
for (;h < 80; ++h) {
t[h] = t[h - 3] ^ t[h - 8] ^ t[h - 14] ^ t[h - 16];
}
for (var d = 0; d < 80; ++d) {
var p = ~~(d / 20);
var m = c(n) + u(p, a, r, s) + o + t[d] + i[p] | 0;
o = s;
s = r;
r = l(a);
a = n;
n = m;
}
this._a = n + this._a | 0;
this._b = a + this._b | 0;
this._c = r + this._c | 0;
this._d = s + this._d | 0;
this._e = o + this._e | 0;
};
o.prototype._hash = function() {
var e = r.allocUnsafe(20);
e.writeInt32BE(this._a | 0, 0);
e.writeInt32BE(this._b | 0, 4);
e.writeInt32BE(this._c | 0, 8);
e.writeInt32BE(this._d | 0, 12);
e.writeInt32BE(this._e | 0, 16);
return e;
};
$i = o;
return $i;
}
var Ui;
var Bi;
function Fi() {
if (Bi) return Ui;
Bi = 1;
var e = n();
var a = _i();
var r = t().Buffer;
var i = [ 1518500249, 1859775393, 2400959708 | 0, 3395469782 | 0 ];
var s = new Array(80);
function o() {
this.init();
this._w = s;
a.call(this, 64, 56);
}
e(o, a);
o.prototype.init = function() {
this._a = 1732584193;
this._b = 4023233417;
this._c = 2562383102;
this._d = 271733878;
this._e = 3285377520;
return this;
};
function c(e) {
return e << 1 | e >>> 31;
}
function l(e) {
return e << 5 | e >>> 27;
}
function u(e) {
return e << 30 | e >>> 2;
}
function h(e, t, n, a) {
if (e === 0) {
return t & n | ~t & a;
}
if (e === 2) {
return t & n | t & a | n & a;
}
return t ^ n ^ a;
}
o.prototype._update = function(e) {
var t = this._w;
var n = this._a | 0;
var a = this._b | 0;
var r = this._c | 0;
var s = this._d | 0;
var o = this._e | 0;
for (var d = 0; d < 16; ++d) {
t[d] = e.readInt32BE(d * 4);
}
for (;d < 80; ++d) {
t[d] = c(t[d - 3] ^ t[d - 8] ^ t[d - 14] ^ t[d - 16]);
}
for (var p = 0; p < 80; ++p) {
var m = ~~(p / 20);
var f = l(n) + h(m, a, r, s) + o + t[p] + i[m] | 0;
o = s;
s = r;
r = u(a);
a = n;
n = f;
}
this._a = n + this._a | 0;
this._b = a + this._b | 0;
this._c = r + this._c | 0;
this._d = s + this._d | 0;
this._e = o + this._e | 0;
};
o.prototype._hash = function() {
var e = r.allocUnsafe(20);
e.writeInt32BE(this._a | 0, 0);
e.writeInt32BE(this._b | 0, 4);
e.writeInt32BE(this._c | 0, 8);
e.writeInt32BE(this._d | 0, 12);
e.writeInt32BE(this._e | 0, 16);
return e;
};
Ui = o;
return Ui;
}
var ji;
var ki;
function Qi() {
if (ki) return ji;
ki = 1;
var e = n();
var a = _i();
var r = t().Buffer;
var i = [ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ];
var s = new Array(64);
function o() {
this.init();
this._w = s;
a.call(this, 64, 56);
}
e(o, a);
o.prototype.init = function() {
this._a = 1779033703;
this._b = 3144134277;
this._c = 1013904242;
this._d = 2773480762;
this._e = 1359893119;
this._f = 2600822924;
this._g = 528734635;
this._h = 1541459225;
return this;
};
function c(e, t, n) {
return n ^ e & (t ^ n);
}
function l(e, t, n) {
return e & t | n & (e | t);
}
function u(e) {
return (e >>> 2 | e << 30) ^ (e >>> 13 | e << 19) ^ (e >>> 22 | e << 10);
}
function h(e) {
return (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
}
function d(e) {
return (e >>> 7 | e << 25) ^ (e >>> 18 | e << 14) ^ e >>> 3;
}
function p(e) {
return (e >>> 17 | e << 15) ^ (e >>> 19 | e << 13) ^ e >>> 10;
}
o.prototype._update = function(e) {
var t = this._w;
var n = this._a | 0;
var a = this._b | 0;
var r = this._c | 0;
var s = this._d | 0;
var o = this._e | 0;
var m = this._f | 0;
var f = this._g | 0;
var y = this._h | 0;
for (var E = 0; E < 16; ++E) {
t[E] = e.readInt32BE(E * 4);
}
for (;E < 64; ++E) {
t[E] = p(t[E - 2]) + t[E - 7] + d(t[E - 15]) + t[E - 16] | 0;
}
for (var T = 0; T < 64; ++T) {
var g = y + h(o) + c(o, m, f) + i[T] + t[T] | 0;
var N = u(n) + l(n, a, r) | 0;
y = f;
f = m;
m = o;
o = s + g | 0;
s = r;
r = a;
a = n;
n = g + N | 0;
}
this._a = n + this._a | 0;
this._b = a + this._b | 0;
this._c = r + this._c | 0;
this._d = s + this._d | 0;
this._e = o + this._e | 0;
this._f = m + this._f | 0;
this._g = f + this._g | 0;
this._h = y + this._h | 0;
};
o.prototype._hash = function() {
var e = r.allocUnsafe(32);
e.writeInt32BE(this._a, 0);
e.writeInt32BE(this._b, 4);
e.writeInt32BE(this._c, 8);
e.writeInt32BE(this._d, 12);
e.writeInt32BE(this._e, 16);
e.writeInt32BE(this._f, 20);
e.writeInt32BE(this._g, 24);
e.writeInt32BE(this._h, 28);
return e;
};
ji = o;
return ji;
}
var Vi;
var Ki;
function Wi() {
if (Ki) return Vi;
Ki = 1;
var e = n();
var a = Qi();
var r = _i();
var i = t().Buffer;
var s = new Array(64);
function o() {
this.init();
this._w = s;
r.call(this, 64, 56);
}
e(o, a);
o.prototype.init = function() {
this._a = 3238371032;
this._b = 914150663;
this._c = 812702999;
this._d = 4144912697;
this._e = 4290775857;
this._f = 1750603025;
this._g = 1694076839;
this._h = 3204075428;
return this;
};
o.prototype._hash = function() {
var e = i.allocUnsafe(28);
e.writeInt32BE(this._a, 0);
e.writeInt32BE(this._b, 4);
e.writeInt32BE(this._c, 8);
e.writeInt32BE(this._d, 12);
e.writeInt32BE(this._e, 16);
e.writeInt32BE(this._f, 20);
e.writeInt32BE(this._g, 24);
return e;
};
Vi = o;
return Vi;
}
var Hi;
var Gi;
function Yi() {
if (Gi) return Hi;
Gi = 1;
var e = n();
var a = _i();
var r = t().Buffer;
var i = [ 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591 ];
var s = new Array(160);
function o() {
this.init();
this._w = s;
a.call(this, 128, 112);
}
e(o, a);
o.prototype.init = function() {
this._ah = 1779033703;
this._bh = 3144134277;
this._ch = 1013904242;
this._dh = 2773480762;
this._eh = 1359893119;
this._fh = 2600822924;
this._gh = 528734635;
this._hh = 1541459225;
this._al = 4089235720;
this._bl = 2227873595;
this._cl = 4271175723;
this._dl = 1595750129;
this._el = 2917565137;
this._fl = 725511199;
this._gl = 4215389547;
this._hl = 327033209;
return this;
};
function c(e, t, n) {
return n ^ e & (t ^ n);
}
function l(e, t, n) {
return e & t | n & (e | t);
}
function u(e, t) {
return (e >>> 28 | t << 4) ^ (t >>> 2 | e << 30) ^ (t >>> 7 | e << 25);
}
function h(e, t) {
return (e >>> 14 | t << 18) ^ (e >>> 18 | t << 14) ^ (t >>> 9 | e << 23);
}
function d(e, t) {
return (e >>> 1 | t << 31) ^ (e >>> 8 | t << 24) ^ e >>> 7;
}
function p(e, t) {
return (e >>> 1 | t << 31) ^ (e >>> 8 | t << 24) ^ (e >>> 7 | t << 25);
}
function m(e, t) {
return (e >>> 19 | t << 13) ^ (t >>> 29 | e << 3) ^ e >>> 6;
}
function f(e, t) {
return (e >>> 19 | t << 13) ^ (t >>> 29 | e << 3) ^ (e >>> 6 | t << 26);
}
function y(e, t) {
return e >>> 0 < t >>> 0 ? 1 : 0;
}
o.prototype._update = function(e) {
var t = this._w;
var n = this._ah | 0;
var a = this._bh | 0;
var r = this._ch | 0;
var s = this._dh | 0;
var o = this._eh | 0;
var E = this._fh | 0;
var T = this._gh | 0;
var g = this._hh | 0;
var N = this._al | 0;
var A = this._bl | 0;
var b = this._cl | 0;
var C = this._dl | 0;
var R = this._el | 0;
var S = this._fl | 0;
var w = this._gl | 0;
var M = this._hl | 0;
for (var O = 0; O < 32; O += 2) {
t[O] = e.readInt32BE(O * 4);
t[O + 1] = e.readInt32BE(O * 4 + 4);
}
for (;O < 160; O += 2) {
var v = t[O - 15 * 2];
var I = t[O - 15 * 2 + 1];
var P = d(v, I);
var L = p(I, v);
v = t[O - 2 * 2];
I = t[O - 2 * 2 + 1];
var D = m(v, I);
var _ = f(I, v);
var $ = t[O - 7 * 2];
var x = t[O - 7 * 2 + 1];
var q = t[O - 16 * 2];
var U = t[O - 16 * 2 + 1];
var B = L + x | 0;
var F = P + $ + y(B, L) | 0;
B = B + _ | 0;
F = F + D + y(B, _) | 0;
B = B + U | 0;
F = F + q + y(B, U) | 0;
t[O] = F;
t[O + 1] = B;
}
for (var j = 0; j < 160; j += 2) {
F = t[j];
B = t[j + 1];
var k = l(n, a, r);
var Q = l(N, A, b);
var V = u(n, N);
var K = u(N, n);
var W = h(o, R);
var H = h(R, o);
var G = i[j];
var Y = i[j + 1];
var z = c(o, E, T);
var J = c(R, S, w);
var X = M + H | 0;
var Z = g + W + y(X, M) | 0;
X = X + J | 0;
Z = Z + z + y(X, J) | 0;
X = X + Y | 0;
Z = Z + G + y(X, Y) | 0;
X = X + B | 0;
Z = Z + F + y(X, B) | 0;
var ee = K + Q | 0;
var te = V + k + y(ee, K) | 0;
g = T;
M = w;
T = E;
w = S;
E = o;
S = R;
R = C + X | 0;
o = s + Z + y(R, C) | 0;
s = r;
C = b;
r = a;
b = A;
a = n;
A = N;
N = X + ee | 0;
n = Z + te + y(N, X) | 0;
}
this._al = this._al + N | 0;
this._bl = this._bl + A | 0;
this._cl = this._cl + b | 0;
this._dl = this._dl + C | 0;
this._el = this._el + R | 0;
this._fl = this._fl + S | 0;
this._gl = this._gl + w | 0;
this._hl = this._hl + M | 0;
this._ah = this._ah + n + y(this._al, N) | 0;
this._bh = this._bh + a + y(this._bl, A) | 0;
this._ch = this._ch + r + y(this._cl, b) | 0;
this._dh = this._dh + s + y(this._dl, C) | 0;
this._eh = this._eh + o + y(this._el, R) | 0;
this._fh = this._fh + E + y(this._fl, S) | 0;
this._gh = this._gh + T + y(this._gl, w) | 0;
this._hh = this._hh + g + y(this._hl, M) | 0;
};
o.prototype._hash = function() {
var e = r.allocUnsafe(64);
function t(t, n, a) {
e.writeInt32BE(t, a);
e.writeInt32BE(n, a + 4);
}
t(this._ah, this._al, 0);
t(this._bh, this._bl, 8);
t(this._ch, this._cl, 16);
t(this._dh, this._dl, 24);
t(this._eh, this._el, 32);
t(this._fh, this._fl, 40);
t(this._gh, this._gl, 48);
t(this._hh, this._hl, 56);
return e;
};
Hi = o;
return Hi;
}
var zi;
var Ji;
function Xi() {
if (Ji) return zi;
Ji = 1;
var e = n();
var a = Yi();
var r = _i();
var i = t().Buffer;
var s = new Array(160);
function o() {
this.init();
this._w = s;
r.call(this, 128, 112);
}
e(o, a);
o.prototype.init = function() {
this._ah = 3418070365;
this._bh = 1654270250;
this._ch = 2438529370;
this._dh = 355462360;
this._eh = 1731405415;
this._fh = 2394180231;
this._gh = 3675008525;
this._hh = 1203062813;
this._al = 3238371032;
this._bl = 914150663;
this._cl = 812702999;
this._dl = 4144912697;
this._el = 4290775857;
this._fl = 1750603025;
this._gl = 1694076839;
this._hl = 3204075428;
return this;
};
o.prototype._hash = function() {
var e = i.allocUnsafe(48);
function t(t, n, a) {
e.writeInt32BE(t, a);
e.writeInt32BE(n, a + 4);
}
t(this._ah, this._al, 0);
t(this._bh, this._bl, 8);
t(this._ch, this._cl, 16);
t(this._dh, this._dl, 24);
t(this._eh, this._el, 32);
t(this._fh, this._fl, 40);
return e;
};
zi = o;
return zi;
}
Qn.exports;
var Zi;
function es() {
if (Zi) return Qn.exports;
Zi = 1;
(function(e) {
e.exports = function t(n) {
var a = n.toLowerCase();
var r = e.exports[a];
if (!r) {
throw new Error(a + " is not supported (we accept pull requests)");
}
return new r;
};
e.exports.sha = qi();
e.exports.sha1 = Fi();
e.exports.sha224 = Wi();
e.exports.sha256 = Qi();
e.exports.sha384 = Xi();
e.exports.sha512 = Yi();
})(Qn);
return Qn.exports;
}
Object.defineProperty(kn, "__esModule", {
value: true
});
var ts = kn.camelCase = rs;
kn.snakeCase = is;
kn.titleCase = ss;
kn.abbreviate = os;
kn.shorten = cs;
kn.hash = ls;
const ns = e;
const as = ns.__importDefault(es());
function rs(e, t = false) {
if (t) e = " " + e;
return e.replace(/^([A-Z])|[\s-_](\w)/g, function(e, t, n) {
if (n) return n.toUpperCase();
return t.toLowerCase();
});
}
function is(e) {
return e.replace(/([A-Z])([A-Z])([a-z])/g, "$1_$2$3").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
}
function ss(e) {
return e.replace(/\w\S*/g, e => e.charAt(0).toUpperCase() + e.substr(1).toLowerCase());
}
function os(e, t = 1) {
const n = e.replace(/([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g, "$1 $2").split(" ");
return n.reduce((e, n) => {
e += n.substr(0, t);
return e;
}, "");
}
function cs(e, t = {}) {
const {segmentLength: n = 4, separator: a = "__", termLength: r = 2} = t;
const i = e.split(a);
const s = i.reduce((e, t) => {
const a = t.replace(/([a-z\xE0-\xFF])([A-Z\xC0-\xDF])/g, "$1 $2").split(" ");
const i = a.length > 1 ? r : n;
const s = a.map(e => e.substr(0, i)).join("");
e.push(s);
return e;
}, []);
return s.join(a);
}
function ls(e, t = {}) {
const n = (0, as.default)("sha1");
n.update(e, "utf8");
const a = n.digest("hex");
if (t.length) {
return a.slice(0, t.length);
}
return a;
}
var us = {};
Object.defineProperty(us, "__esModule", {
value: true
});
us.VersionUtils = void 0;
class VersionUtils {
static isGreaterOrEqual(e, t) {
if (!e) {
return false;
}
const n = hs(e);
const a = hs(t);
for (let e = 0; e < n.length && e < a.length; e++) {
if (n[e] > a[e]) {
return true;
} else if (n[e] < a[e]) {
return false;
}
}
return true;
}
}
us.VersionUtils = VersionUtils;
function hs(e) {
return e.split(".").map(e => parseInt(e, 10));
}
Object.defineProperty(jn, "__esModule", {
value: true
});
jn.DriverUtils = void 0;
const ds = kn;
const ps = us;
class DriverUtils {
static isSQLiteFamily(e) {
return [ "sqlite", "cordova", "react-native", "nativescript", "sqljs", "expo", "better-sqlite3", "capacitor" ].includes(e.options.type);
}
static isMySQLFamily(e) {
return [ "mysql", "mariadb" ].includes(e.options.type);
}
static isReleaseVersionOrGreater(e, t) {
return ps.VersionUtils.isGreaterOrEqual(e.version, t);
}
static isPostgresFamily(e) {
return [ "postgres", "aurora-postgres", "cockroachdb" ].includes(e.options.type);
}
static buildDriverOptions(e, t) {
if (e.url) {
const n = this.parseConnectionUrl(e.url);
if (t && t.useSid && n.database) {
n.sid = n.database;
}
for (const e of Object.keys(n)) {
if (typeof n[e] === "undefined") {
delete n[e];
}
}
return Object.assign({}, e, n);
}
return Object.assign({}, e);
}
static buildMongoDBDriverOptions(e, t) {
if (e.url) {
const n = this.parseMongoDBConnectionUrl(e.url);
if (t && t.useSid && n.database) {
n.sid = n.database;
}
for (const e of Object.keys(n)) {
if (typeof n[e] === "undefined") {
delete n[e];
}
}
return Object.assign({}, e, n);
}
return Object.assign({}, e);
}
static buildAlias({maxAliasLength: e}, t, ...n) {
const a = t && t.joiner ? t.joiner : "_";
const r = n.length === 1 ? n[0] : n.join(a);
if (e && e > 0 && r.length > e) {
if (t && t.shorten === true) {
const t = (0, ds.shorten)(r);
if (t.length < e) {
return t;
}
}
return (0, ds.hash)(r, {
length: e
});
}
return r;
}
static buildColumnAlias({maxAliasLength: e}, t, ...n) {
if (typeof t === "string") {
n.unshift(t);
t = {
shorten: false,
joiner: "_"
};
} else {
t = Object.assign({
shorten: false,
joiner: "_"
}, t);
}
return this.buildAlias({
maxAliasLength: e
}, t, ...n);
}
static parseConnectionUrl(e) {
const t = e.split(":")[0];
const n = e.indexOf("//");
const a = e.substr(n + 2);
const r = a.indexOf("/");
const i = r !== -1 ? a.substr(0, r) : a;
let s = r !== -1 ? a.substr(r + 1) : undefined;
if (s && s.indexOf("?") !== -1) {
s = s.substr(0, s.indexOf("?"));
}
const o = i.lastIndexOf("@");
const c = i.substr(0, o);
const l = i.substr(o + 1);
let u = c;
let h = "";
const d = c.indexOf(":");
if (d !== -1) {
u = c.substr(0, d);
h = c.substr(d + 1);
}
const [p, m] = l.split(":");
return {
type: t,
host: p,
username: decodeURIComponent(u),
password: decodeURIComponent(h),
port: m ? parseInt(m) : undefined,
database: s || undefined
};
}
static parseMongoDBConnectionUrl(e) {
const t = e.split(":")[0];
const n = e.indexOf("//");
const a = e.substr(n + 2);
const r = a.indexOf("/");
const i = r !== -1 ? a.substr(0, r) : a;
let s = r !== -1 ? a.substr(r + 1) : undefined;
let o = "";
let c = undefined;
let l = undefined;
let u = undefined;
let h = undefined;
const d = {};
if (s && s.indexOf("?") !== -1) {
o = s.substr(s.indexOf("?") + 1, s.length);
const e = o.split("&");
let t;
let n;
e.forEach(e => {
t = e.split("=")[0];
n = e.split("=")[1];
d[t] = n;
});
h = d["replicaSet"];
s = s.substr(0, s.indexOf("?"));
}
const p = i.lastIndexOf("@");
const m = i.substr(0, p);
const f = i.substr(p + 1);
let y = m;
let E = "";
const T = m.indexOf(":");
if (T !== -1) {
y = m.substr(0, T);
E = m.substr(T + 1);
}
if (h) {
u = f;
} else {
[c, l] = f.split(":");
}
const g = {
type: t,
host: c,
hostReplicaSet: u,
username: decodeURIComponent(y),
password: decodeURIComponent(E),
port: l ? parseInt(l) : undefined,
database: s || undefined
};
for (const [e, t] of Object.entries(d)) {
g[e] = t;
}
return g;
}
}
jn.DriverUtils = DriverUtils;
Object.defineProperty(Bn, "__esModule", {
value: true
});
Bn.JoinAttribute = void 0;
const ms = Fn;
const fs = I;
const ys = P;
const Es = jn;
class JoinAttribute {
constructor(e, t, n) {
this.connection = e;
this.queryExpressionMap = t;
this.isSelectedEvaluated = false;
this.relationEvaluated = false;
if (n) {
fs.ObjectUtils.assign(this, n);
}
}
get isMany() {
if (this.isMappingMany !== undefined) return this.isMappingMany;
if (this.relation) return this.relation.isManyToMany || this.relation.isOneToMany;
return false;
}
get isSelected() {
if (!this.isSelectedEvaluated) {
const e = () => {
for (const e of this.queryExpressionMap.selects) {
if (e.selection === this.alias.name) return true;
if (this.metadata && !!this.metadata.columns.find(t => e.selection === this.alias.name + "." + t.propertyPath)) return true;
}
return false;
};
this.isSelectedCache = e();
this.isSelectedEvaluated = true;
}
return this.isSelectedCache;
}
get tablePath() {
return this.metadata ? this.metadata.tablePath : this.entityOrProperty;
}
get parentAlias() {
if (!ms.QueryBuilderUtils.isAliasProperty(this.entityOrProperty)) return undefined;
return this.entityOrProperty.substr(0, this.entityOrProperty.indexOf("."));
}
get relationPropertyPath() {
if (!ms.QueryBuilderUtils.isAliasProperty(this.entityOrProperty)) return undefined;
return this.entityOrProperty.substr(this.entityOrProperty.indexOf(".") + 1);
}
get relation() {
if (!this.relationEvaluated) {
const e = () => {
if (!ms.QueryBuilderUtils.isAliasProperty(this.entityOrProperty)) return undefined;
const e = this.queryExpressionMap.findAliasByName(this.parentAlias);
let t = e.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (t) {
return t;
}
if (e.metadata.parentEntityMetadata) {
t = e.metadata.parentEntityMetadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (t) {
return t;
}
}
throw new ys.TypeORMError(`Relation with property path ${this.relationPropertyPath} in entity was not found.`);
};
this.relationCache = e.bind(this)();
this.relationEvaluated = true;
}
return this.relationCache;
}
get metadata() {
if (this.relation) return this.relation.inverseEntityMetadata;
if (this.connection.hasMetadata(this.entityOrProperty)) return this.connection.getMetadata(this.entityOrProperty);
if (this.mapAsEntity && this.connection.hasMetadata(this.mapAsEntity)) {
return this.connection.getMetadata(this.mapAsEntity);
}
return undefined;
}
get junctionAlias() {
if (!this.relation) {
throw new ys.TypeORMError(`Cannot get junction table for join without relation.`);
}
if (typeof this.entityOrProperty !== "string") {
throw new ys.TypeORMError(`Junction property is not defined.`);
}
const e = this.entityOrProperty.substr(0, this.entityOrProperty.indexOf("."));
if (this.relation.isOwning) {
return Es.DriverUtils.buildAlias(this.connection.driver, undefined, e, this.alias.name);
} else {
return Es.DriverUtils.buildAlias(this.connection.driver, undefined, this.alias.name, e);
}
}
get mapToPropertyParentAlias() {
if (!this.mapToProperty) return undefined;
return this.mapToProperty.split(".")[0];
}
get mapToPropertyPropertyName() {
if (!this.mapToProperty) return undefined;
return this.mapToProperty.split(".")[1];
}
}
Bn.JoinAttribute = JoinAttribute;
var Ts = {};
Object.defineProperty(Ts, "__esModule", {
value: true
});
Ts.RelationIdAttribute = void 0;
const gs = Fn;
const Ns = I;
const As = D;
class RelationIdAttribute {
constructor(e, t) {
this.queryExpressionMap = e;
this.disableMixedMap = false;
Ns.ObjectUtils.assign(this, t || {});
}
get joinInverseSideMetadata() {
return this.relation.inverseEntityMetadata;
}
get parentAlias() {
if (!gs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new As.TypeORMError(`Given value must be a string representation of alias property`);
return this.relationName.substr(0, this.relationName.indexOf("."));
}
get relationPropertyPath() {
if (!gs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new As.TypeORMError(`Given value must be a string representation of alias property`);
return this.relationName.substr(this.relationName.indexOf(".") + 1);
}
get relation() {
if (!gs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new As.TypeORMError(`Given value must be a string representation of alias property`);
const e = this.queryExpressionMap.findAliasByName(this.parentAlias);
const t = e.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (!t) throw new As.TypeORMError(`Relation with property path ${this.relationPropertyPath} in entity was not found.`);
return t;
}
get junctionAlias() {
const [e, t] = this.relationName.split(".");
return e + "_" + t + "_rid";
}
get junctionMetadata() {
return this.relation.junctionEntityMetadata;
}
get mapToPropertyParentAlias() {
return this.mapToProperty.substr(0, this.mapToProperty.indexOf("."));
}
get mapToPropertyPropertyPath() {
return this.mapToProperty.substr(this.mapToProperty.indexOf(".") + 1);
}
}
Ts.RelationIdAttribute = RelationIdAttribute;
var bs = {};
Object.defineProperty(bs, "__esModule", {
value: true
});
bs.RelationCountAttribute = void 0;
const Cs = Fn;
const Rs = I;
const Ss = D;
class RelationCountAttribute {
constructor(e, t) {
this.expressionMap = e;
Rs.ObjectUtils.assign(this, t || {});
}
get joinInverseSideMetadata() {
return this.relation.inverseEntityMetadata;
}
get parentAlias() {
if (!Cs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new Ss.TypeORMError(`Given value must be a string representation of alias property`);
return this.relationName.split(".")[0];
}
get relationProperty() {
if (!Cs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new Ss.TypeORMError(`Given value is a string representation of alias property`);
return this.relationName.split(".")[1];
}
get junctionAlias() {
const [e, t] = this.relationName.split(".");
return e + "_" + t + "_rc";
}
get relation() {
if (!Cs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new Ss.TypeORMError(`Given value is a string representation of alias property`);
const [e, t] = this.relationName.split(".");
const n = this.expressionMap.findAliasByName(e);
const a = n.metadata.findRelationWithPropertyPath(t);
if (!a) throw new Ss.TypeORMError(`Relation with property path ${t} in entity was not found.`);
return a;
}
get metadata() {
if (!Cs.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new Ss.TypeORMError(`Given value is a string representation of alias property`);
const e = this.relationName.split(".")[0];
const t = this.expressionMap.findAliasByName(e);
return t.metadata;
}
get mapToPropertyPropertyName() {
return this.mapToProperty.split(".")[1];
}
}
bs.RelationCountAttribute = RelationCountAttribute;
Object.defineProperty(O, "__esModule", {
value: true
});
O.QueryExpressionMap = void 0;
const ws = v;
const Ms = Bn;
const Os = Ts;
const vs = bs;
const Is = P;
class QueryExpressionMap {
constructor(e) {
this.connection = e;
this.relationLoadStrategy = "join";
this.queryEntity = false;
this.aliases = [];
this.queryType = "select";
this.selects = [];
this.maxExecutionTime = 0;
this.selectDistinct = false;
this.selectDistinctOn = [];
this.extraReturningColumns = [];
this.onConflict = "";
this.onIgnore = false;
this.joinAttributes = [];
this.relationIdAttributes = [];
this.relationCountAttributes = [];
this.wheres = [];
this.havings = [];
this.orderBys = {};
this.groupBys = [];
this.withDeleted = false;
this.parameters = {};
this.disableEscaping = true;
this.enableRelationIdValues = false;
this.extraAppendedAndWhereCondition = "";
this.subQuery = false;
this.aliasNamePrefixingEnabled = true;
this.options = [];
this.insertColumns = [];
this.whereEntities = [];
this.updateEntity = true;
this.callListeners = true;
this.useTransaction = false;
this.nativeParameters = {};
this.locallyGenerated = {};
this.commonTableExpressions = [];
if (e.options.relationLoadStrategy) {
this.relationLoadStrategy = e.options.relationLoadStrategy;
}
this.timeTravel = e.options?.timeTravelQueries || false;
}
get allOrderBys() {
if (!Object.keys(this.orderBys).length && this.mainAlias.hasMetadata && this.options.indexOf("disable-global-order") === -1) {
const e = this.mainAlias.metadata.orderBy || {};
return Object.keys(e).reduce((t, n) => {
t[this.mainAlias.name + "." + n] = e[n];
return t;
}, {});
}
return this.orderBys;
}
setMainAlias(e) {
this.mainAlias = e;
return e;
}
createAlias(e) {
let t = e.name;
if (!t && e.tablePath) t = e.tablePath;
if (!t && typeof e.target === "function") t = e.target.name;
if (!t && typeof e.target === "string") t = e.target;
const n = new ws.Alias;
n.type = e.type;
if (t) n.name = t;
if (e.metadata) n.metadata = e.metadata;
if (e.target && !n.hasMetadata) n.metadata = this.connection.getMetadata(e.target);
if (e.tablePath) n.tablePath = e.tablePath;
if (e.subQuery) n.subQuery = e.subQuery;
this.aliases.push(n);
return n;
}
findAliasByName(e) {
const t = this.aliases.find(t => t.name === e);
if (!t) throw new Is.TypeORMError(`"${e}" alias was not found. Maybe you forgot to join it?`);
return t;
}
findColumnByAliasExpression(e) {
const [t, n] = e.split(".");
const a = this.findAliasByName(t);
return a.metadata.findColumnWithPropertyName(n);
}
get relationMetadata() {
if (!this.mainAlias) throw new Is.TypeORMError(`Entity to work with is not specified!`);
const e = this.mainAlias.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (!e) throw new Is.TypeORMError(`Relation ${this.relationPropertyPath} was not found in entity ${this.mainAlias.name}`);
return e;
}
clone() {
const e = new QueryExpressionMap(this.connection);
e.queryType = this.queryType;
e.selects = this.selects.map(e => e);
e.maxExecutionTime = this.maxExecutionTime;
e.selectDistinct = this.selectDistinct;
e.selectDistinctOn = this.selectDistinctOn;
this.aliases.forEach(t => e.aliases.push(new ws.Alias(t)));
e.relationLoadStrategy = this.relationLoadStrategy;
e.mainAlias = this.mainAlias;
e.valuesSet = this.valuesSet;
e.returning = this.returning;
e.onConflict = this.onConflict;
e.onIgnore = this.onIgnore;
e.onUpdate = this.onUpdate;
e.joinAttributes = this.joinAttributes.map(e => new Ms.JoinAttribute(this.connection, this, e));
e.relationIdAttributes = this.relationIdAttributes.map(e => new Os.RelationIdAttribute(this, e));
e.relationCountAttributes = this.relationCountAttributes.map(e => new vs.RelationCountAttribute(this, e));
e.wheres = this.wheres.map(e => ({
...e
}));
e.havings = this.havings.map(e => ({
...e
}));
e.orderBys = Object.assign({}, this.orderBys);
e.groupBys = this.groupBys.map(e => e);
e.limit = this.limit;
e.offset = this.offset;
e.skip = this.skip;
e.take = this.take;
e.lockMode = this.lockMode;
e.onLocked = this.onLocked;
e.lockVersion = this.lockVersion;
e.lockTables = this.lockTables;
e.withDeleted = this.withDeleted;
e.parameters = Object.assign({}, this.parameters);
e.disableEscaping = this.disableEscaping;
e.enableRelationIdValues = this.enableRelationIdValues;
e.extraAppendedAndWhereCondition = this.extraAppendedAndWhereCondition;
e.subQuery = this.subQuery;
e.aliasNamePrefixingEnabled = this.aliasNamePrefixingEnabled;
e.cache = this.cache;
e.cacheId = this.cacheId;
e.cacheDuration = this.cacheDuration;
e.relationPropertyPath = this.relationPropertyPath;
e.of = this.of;
e.insertColumns = this.insertColumns;
e.whereEntities = this.whereEntities;
e.updateEntity = this.updateEntity;
e.callListeners = this.callListeners;
e.useTransaction = this.useTransaction;
e.timeTravel = this.timeTravel;
e.nativeParameters = Object.assign({}, this.nativeParameters);
e.comment = this.comment;
e.commonTableExpressions = this.commonTableExpressions.map(e => ({
alias: e.alias,
queryBuilder: typeof e.queryBuilder === "string" ? e.queryBuilder : e.queryBuilder.clone(),
options: e.options
}));
return e;
}
}
O.QueryExpressionMap = QueryExpressionMap;
var Ps = {};
Object.defineProperty(Ps, "__esModule", {
value: true
});
var Ls = Ps.Brackets = void 0;
class Brackets {
constructor(e) {
this["@instanceof"] = Symbol.for("Brackets");
this.whereFactory = e;
}
}
Ls = Ps.Brackets = Brackets;
var Ds = {};
var _s = {};
Object.defineProperty(_s, "__esModule", {
value: true
});
_s.ApplyValueTransformers = void 0;
class ApplyValueTransformers {
static transformFrom(e, t) {
if (Array.isArray(e)) {
const n = e.slice().reverse();
return n.reduce((e, t) => t.from(e), t);
}
return e.from(t);
}
static transformTo(e, t) {
if (Array.isArray(e)) {
return e.reduce((e, t) => t.to(e), t);
}
return e.to(t);
}
}
_s.ApplyValueTransformers = ApplyValueTransformers;
Object.defineProperty(Ds, "__esModule", {
value: true
});
var $s = Ds.FindOperator = void 0;
const xs = Te;
const qs = _s;
class FindOperator {
constructor(e, t, n = true, a = false, r, i) {
this["@instanceof"] = Symbol.for("FindOperator");
this._type = e;
this._value = t;
this._useParameter = n;
this._multipleParameters = a;
this._getSql = r;
this._objectLiteralParameters = i;
}
get useParameter() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value.useParameter;
return this._useParameter;
}
get multipleParameters() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value.multipleParameters;
return this._multipleParameters;
}
get type() {
return this._type;
}
get value() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value.value;
return this._value;
}
get objectLiteralParameters() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value.objectLiteralParameters;
return this._objectLiteralParameters;
}
get child() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value;
return undefined;
}
get getSql() {
if (xs.InstanceChecker.isFindOperator(this._value)) return this._value.getSql;
return this._getSql;
}
transformValue(e) {
if (this._value instanceof FindOperator) {
this._value.transformValue(e);
} else {
this._value = Array.isArray(this._value) && this._multipleParameters ? this._value.map(t => e && qs.ApplyValueTransformers.transformTo(e, t)) : qs.ApplyValueTransformers.transformTo(e, this._value);
}
}
}
$s = Ds.FindOperator = FindOperator;
var Us = {};
Object.defineProperty(Us, "__esModule", {
value: true
});
var Bs = Us.In = js;
const Fs = Ds;
function js(e) {
return new Fs.FindOperator("in", e, true, true);
}
var ks = {};
Object.defineProperty(ks, "__esModule", {
value: true
});
ks.escapeRegExp = void 0;
const Qs = /[.*+\-?^${}()|[\]\\]/g;
const Vs = e => e.replace(Qs, "\\$&");
ks.escapeRegExp = Vs;
Object.defineProperty(M, "__esModule", {
value: true
});
var Ks = M.QueryBuilder = void 0;
const Ws = O;
const Hs = Ps;
const Gs = Ds;
const Ys = Us;
const zs = P;
const Js = ht;
const Xs = Te;
const Zs = ks;
class QueryBuilder {
constructor(e, t) {
this["@instanceof"] = Symbol.for("QueryBuilder");
this.parameterIndex = 0;
if (Xs.InstanceChecker.isDataSource(e)) {
this.connection = e;
this.queryRunner = t;
this.expressionMap = new Ws.QueryExpressionMap(this.connection);
} else {
this.connection = e.connection;
this.queryRunner = e.queryRunner;
this.expressionMap = e.expressionMap.clone();
}
}
static registerQueryBuilderClass(e, t) {
QueryBuilder.queryBuilderRegistry[e] = t;
}
get alias() {
if (!this.expressionMap.mainAlias) throw new zs.TypeORMError(`Main alias is not set`);
return this.expressionMap.mainAlias.name;
}
select(e, t) {
this.expressionMap.queryType = "select";
if (Array.isArray(e)) {
this.expressionMap.selects = e.map(e => ({
selection: e
}));
} else if (e) {
this.expressionMap.selects = [ {
selection: e,
aliasName: t
} ];
}
if (Xs.InstanceChecker.isSelectQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["SelectQueryBuilder"](this);
}
insert() {
this.expressionMap.queryType = "insert";
if (Xs.InstanceChecker.isInsertQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["InsertQueryBuilder"](this);
}
update(e, t) {
const n = t ? t : e;
e = Xs.InstanceChecker.isEntitySchema(e) ? e.options.name : e;
if (typeof e === "function" || typeof e === "string") {
const t = this.createFromAlias(e);
this.expressionMap.setMainAlias(t);
}
this.expressionMap.queryType = "update";
this.expressionMap.valuesSet = n;
if (Xs.InstanceChecker.isUpdateQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["UpdateQueryBuilder"](this);
}
delete() {
this.expressionMap.queryType = "delete";
if (Xs.InstanceChecker.isDeleteQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["DeleteQueryBuilder"](this);
}
softDelete() {
this.expressionMap.queryType = "soft-delete";
if (Xs.InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this);
}
restore() {
this.expressionMap.queryType = "restore";
if (Xs.InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this);
}
relation(e, t) {
const n = arguments.length === 2 ? e : undefined;
const a = arguments.length === 2 ? t : e;
this.expressionMap.queryType = "relation";
this.expressionMap.relationPropertyPath = a;
if (n) {
const e = this.createFromAlias(n);
this.expressionMap.setMainAlias(e);
}
if (Xs.InstanceChecker.isRelationQueryBuilder(this)) return this;
return QueryBuilder.queryBuilderRegistry["RelationQueryBuilder"](this);
}
hasRelation(e, t) {
const n = this.connection.getMetadata(e);
const a = Array.isArray(t) ? t : [ t ];
return a.every(e => !!n.findRelationWithPropertyPath(e));
}
hasParameter(e) {
return this.parentQueryBuilder?.hasParameter(e) || e in this.expressionMap.parameters;
}
setParameter(e, t) {
if (typeof t === "function") {
throw new zs.TypeORMError(`Function parameter isn't supported in the parameters. Please check "${e}" parameter.`);
}
if (!e.match(/^([A-Za-z0-9_.]+)$/)) {
throw new zs.TypeORMError("QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.");
}
if (this.parentQueryBuilder) {
this.parentQueryBuilder.setParameter(e, t);
}
this.expressionMap.parameters[e] = t;
return this;
}
setParameters(e) {
for (const [t, n] of Object.entries(e)) {
this.setParameter(t, n);
}
return this;
}
createParameter(e) {
let t;
do {
t = `orm_param_${this.parameterIndex++}`;
} while (this.hasParameter(t));
this.setParameter(t, e);
return `:${t}`;
}
setNativeParameters(e) {
if (this.parentQueryBuilder) {
this.parentQueryBuilder.setNativeParameters(e);
}
Object.keys(e).forEach(t => {
this.expressionMap.nativeParameters[t] = e[t];
});
return this;
}
getParameters() {
const e = Object.assign({}, this.expressionMap.parameters);
if (this.expressionMap.mainAlias && this.expressionMap.mainAlias.hasMetadata) {
const t = this.expressionMap.mainAlias.metadata;
if (t.discriminatorColumn && t.parentEntityMetadata) {
const n = t.childEntityMetadatas.filter(e => e.discriminatorColumn).map(e => e.discriminatorValue);
n.push(t.discriminatorValue);
e["discriminatorColumnValues"] = n;
}
}
return e;
}
printSql() {
const [e, t] = this.getQueryAndParameters();
this.connection.logger.logQuery(e, t);
return this;
}
getSql() {
return this.getQueryAndParameters()[0];
}
getQueryAndParameters() {
const e = this.getQuery();
const t = this.getParameters();
return this.connection.driver.escapeQueryWithParameters(e, t, this.expressionMap.nativeParameters);
}
async execute() {
const [e, t] = this.getQueryAndParameters();
const n = this.obtainQueryRunner();
try {
return await n.query(e, t);
} finally {
if (n !== this.queryRunner) {
await n.release();
}
}
}
createQueryBuilder(e) {
return new this.constructor(this.connection, e ?? this.queryRunner);
}
clone() {
return new this.constructor(this);
}
comment(e) {
this.expressionMap.comment = e;
return this;
}
disableEscaping() {
this.expressionMap.disableEscaping = false;
return this;
}
escape(e) {
if (!this.expressionMap.disableEscaping) return e;
return this.connection.driver.escape(e);
}
setQueryRunner(e) {
this.queryRunner = e;
return this;
}
callListeners(e) {
this.expressionMap.callListeners = e;
return this;
}
useTransaction(e) {
this.expressionMap.useTransaction = e;
return this;
}
addCommonTableExpression(e, t, n) {
this.expressionMap.commonTableExpressions.push({
queryBuilder: e,
alias: t,
options: n || {}
});
return this;
}
getTableName(e) {
return e.split(".").map(e => {
if (e === "") return e;
return this.escape(e);
}).join(".");
}
getMainTableName() {
if (!this.expressionMap.mainAlias) throw new zs.TypeORMError(`Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`);
if (this.expressionMap.mainAlias.hasMetadata) return this.expressionMap.mainAlias.metadata.tablePath;
return this.expressionMap.mainAlias.tablePath;
}
createFromAlias(e, t) {
if (this.connection.hasMetadata(e)) {
const n = this.connection.getMetadata(e);
return this.expressionMap.createAlias({
type: "from",
name: t,
metadata: this.connection.getMetadata(e),
tablePath: n.tablePath
});
} else {
if (typeof e === "string") {
const n = e.substr(0, 1) === "(" && e.substr(-1) === ")";
return this.expressionMap.createAlias({
type: "from",
name: t,
tablePath: !n ? e : undefined,
subQuery: n ? e : undefined
});
}
const n = e(this.subQuery());
this.setParameters(n.getParameters());
const a = n.getQuery();
return this.expressionMap.createAlias({
type: "from",
name: t,
subQuery: a
});
}
}
replacePropertyNames(e) {
return e;
}
replacePropertyNamesForTheWholeQuery(e) {
const t = {};
for (const e of this.expressionMap.aliases) {
if (!e.hasMetadata) continue;
const n = this.expressionMap.aliasNamePrefixingEnabled && e.name ? `${e.name}.` : "";
if (!t[n]) {
t[n] = {};
}
for (const a of e.metadata.relations) {
if (a.joinColumns.length > 0) t[n][a.propertyPath] = a.joinColumns[0].databaseName;
}
for (const a of e.metadata.relations) {
const e = [ ...a.joinColumns, ...a.inverseJoinColumns ];
for (const r of e) {
const e = `${a.propertyPath}.${r.referencedColumn.propertyPath}`;
t[n][e] = r.databaseName;
}
}
for (const a of e.metadata.columns) {
t[n][a.databaseName] = a.databaseName;
}
for (const a of e.metadata.columns) {
t[n][a.propertyName] = a.databaseName;
}
for (const a of e.metadata.columns) {
t[n][a.propertyPath] = a.databaseName;
}
}
const n = Object.keys(t);
const a = n.map(e => (0, Zs.escapeRegExp)(e)).join("|");
if (n.length > 0) {
e = e.replace(new RegExp(`([ =(]|^.{0})` + `${a ? "(" + a + ")" : ""}([^ =(),]+)` + `(?=[ =),]|.{0}$)`, "gm"), (...e) => {
let n, r, i;
if (a) {
n = e[0];
r = e[1];
i = e[3];
if (t[e[2]][i]) {
return `${r}${this.escape(e[2].substring(0, e[2].length - 1))}.${this.escape(t[e[2]][i])}`;
}
} else {
n = e[0];
r = e[1];
i = e[2];
if (t[""][i]) {
return `${r}${this.escape(t[""][i])}`;
}
}
return n;
});
}
return e;
}
createComment() {
if (!this.expressionMap.comment) {
return "";
}
return `/* ${this.expressionMap.comment.replace(/\*\//g, "")} */ `;
}
createTimeTravelQuery() {
if (this.expressionMap.queryType === "select" && this.expressionMap.timeTravel) {
return ` AS OF SYSTEM TIME ${this.expressionMap.timeTravel}`;
}
return "";
}
createWhereExpression() {
const e = [];
const t = this.createWhereClausesExpression(this.expressionMap.wheres);
if (t.length > 0 && t !== "1=1") {
e.push(this.replacePropertyNames(t));
}
if (this.expressionMap.mainAlias.hasMetadata) {
const t = this.expressionMap.mainAlias.metadata;
if (this.expressionMap.queryType === "select" && !this.expressionMap.withDeleted && t.deleteDateColumn) {
const n = this.expressionMap.aliasNamePrefixingEnabled ? this.expressionMap.mainAlias.name + "." + t.deleteDateColumn.propertyName : t.deleteDateColumn.propertyName;
const a = `${this.replacePropertyNames(n)} IS NULL`;
e.push(a);
}
if (t.discriminatorColumn && t.parentEntityMetadata) {
const n = this.expressionMap.aliasNamePrefixingEnabled ? this.expressionMap.mainAlias.name + "." + t.discriminatorColumn.databaseName : t.discriminatorColumn.databaseName;
const a = `${this.replacePropertyNames(n)} IN (:...discriminatorColumnValues)`;
e.push(a);
}
}
if (this.expressionMap.extraAppendedAndWhereCondition) {
const t = this.replacePropertyNames(this.expressionMap.extraAppendedAndWhereCondition);
e.push(t);
}
let n = "";
n += this.createTimeTravelQuery();
if (!e.length) {
n += "";
} else if (e.length === 1) {
n += ` WHERE ${e[0]}`;
} else {
n += ` WHERE ( ${e.join(" ) AND ( ")} )`;
}
return n;
}
createReturningExpression(e) {
const t = this.getReturningColumns();
const n = this.connection.driver;
if (typeof this.expressionMap.returning !== "string" && this.expressionMap.extraReturningColumns.length > 0 && n.isReturningSqlSupported(e)) {
t.push(...this.expressionMap.extraReturningColumns.filter(e => t.indexOf(e) === -1));
}
if (t.length) {
let e = t.map(e => {
const t = this.escape(e.databaseName);
if (n.options.type === "mssql") {
if (this.expressionMap.queryType === "insert" || this.expressionMap.queryType === "update" || this.expressionMap.queryType === "soft-delete" || this.expressionMap.queryType === "restore") {
return "INSERTED." + t;
} else {
return this.escape(this.getMainTableName()) + "." + t;
}
} else {
return t;
}
}).join(", ");
if (n.options.type === "oracle") {
e += " INTO " + t.map(e => this.createParameter({
type: n.columnTypeToNativeParameter(e.type),
dir: n.oracle.BIND_OUT
})).join(", ");
}
if (n.options.type === "mssql") {
if (this.expressionMap.queryType === "insert" || this.expressionMap.queryType === "update") {
e += " INTO @OutputTable";
}
}
return e;
} else if (typeof this.expressionMap.returning === "string") {
return this.expressionMap.returning;
}
return "";
}
getReturningColumns() {
const e = [];
if (Array.isArray(this.expressionMap.returning)) {
this.expressionMap.returning.forEach(t => {
if (this.expressionMap.mainAlias.hasMetadata) {
e.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(t));
}
});
}
return e;
}
createWhereClausesExpression(e) {
return e.map((e, t) => {
const n = this.createWhereConditionExpression(e.condition);
switch (e.type) {
case "and":
return (t > 0 ? "AND " : "") + `${this.connection.options.isolateWhereStatements ? "(" : ""}${n}${this.connection.options.isolateWhereStatements ? ")" : ""}`;
case "or":
return (t > 0 ? "OR " : "") + `${this.connection.options.isolateWhereStatements ? "(" : ""}${n}${this.connection.options.isolateWhereStatements ? ")" : ""}`;
}
return n;
}).join(" ").trim();
}
createWhereConditionExpression(e, t = false) {
if (typeof e === "string") return e;
if (Array.isArray(e)) {
if (e.length === 0) {
return "1=1";
}
if (e.length === 1 && !t) {
return this.createWhereClausesExpression(e);
}
return "(" + this.createWhereClausesExpression(e) + ")";
}
const {driver: n} = this.connection;
switch (e.operator) {
case "lessThan":
return `${e.parameters[0]} < ${e.parameters[1]}`;
case "lessThanOrEqual":
return `${e.parameters[0]} <= ${e.parameters[1]}`;
case "arrayContains":
return `${e.parameters[0]} @> ${e.parameters[1]}`;
case "jsonContains":
return `${e.parameters[0]} ::jsonb @> ${e.parameters[1]}`;
case "arrayContainedBy":
return `${e.parameters[0]} <@ ${e.parameters[1]}`;
case "arrayOverlap":
return `${e.parameters[0]} && ${e.parameters[1]}`;
case "moreThan":
return `${e.parameters[0]} > ${e.parameters[1]}`;
case "moreThanOrEqual":
return `${e.parameters[0]} >= ${e.parameters[1]}`;
case "notEqual":
return `${e.parameters[0]} != ${e.parameters[1]}`;
case "equal":
return `${e.parameters[0]} = ${e.parameters[1]}`;
case "ilike":
if (n.options.type === "postgres" || n.options.type === "cockroachdb") {
return `${e.parameters[0]} ILIKE ${e.parameters[1]}`;
}
return `UPPER(${e.parameters[0]}) LIKE UPPER(${e.parameters[1]})`;
case "like":
return `${e.parameters[0]} LIKE ${e.parameters[1]}`;
case "between":
return `${e.parameters[0]} BETWEEN ${e.parameters[1]} AND ${e.parameters[2]}`;
case "in":
if (e.parameters.length <= 1) {
return "0=1";
}
return `${e.parameters[0]} IN (${e.parameters.slice(1).join(", ")})`;
case "any":
if (n.options.type === "cockroachdb") {
return `${e.parameters[0]}::STRING = ANY(${e.parameters[1]}::STRING[])`;
}
return `${e.parameters[0]} = ANY(${e.parameters[1]})`;
case "isNull":
return `${e.parameters[0]} IS NULL`;
case "not":
return `NOT(${this.createWhereConditionExpression(e.condition)})`;
case "brackets":
return `${this.createWhereConditionExpression(e.condition, true)}`;
case "and":
return "(" + e.parameters.join(" AND ") + ")";
case "or":
return "(" + e.parameters.join(" OR ") + ")";
}
throw new TypeError(`Unsupported FindOperator ${Gs.FindOperator.constructor.name}`);
}
createCteExpression() {
if (!this.hasCommonTableExpressions()) {
return "";
}
const e = this.connection.driver.cteCapabilities.requiresRecursiveHint;
const t = this.expressionMap.commonTableExpressions.map(t => {
let n = typeof t.queryBuilder === "string" ? t.queryBuilder : "";
if (typeof t.queryBuilder !== "string") {
if (t.queryBuilder.hasCommonTableExpressions()) {
throw new zs.TypeORMError(`Nested CTEs aren't supported (CTE: ${t.alias})`);
}
n = t.queryBuilder.getQuery();
if (!this.connection.driver.cteCapabilities.writable && !Xs.InstanceChecker.isSelectQueryBuilder(t.queryBuilder)) {
throw new zs.TypeORMError(`Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${t.alias})`);
}
this.setParameters(t.queryBuilder.getParameters());
}
let a = this.escape(t.alias);
if (t.options.columnNames) {
const e = t.options.columnNames.map(e => this.escape(e));
if (Xs.InstanceChecker.isSelectQueryBuilder(t.queryBuilder)) {
if (t.queryBuilder.expressionMap.selects.length && t.options.columnNames.length !== t.queryBuilder.expressionMap.selects.length) {
throw new zs.TypeORMError(`cte.options.columnNames length (${t.options.columnNames.length}) doesn't match subquery select list length ${t.queryBuilder.expressionMap.selects.length} (CTE: ${t.alias})`);
}
}
a += `(${e.join(", ")})`;
}
const r = t.options.recursive && e ? "RECURSIVE" : "";
let i = "";
if (this.connection.driver.cteCapabilities.materializedHint && t.options.materialized !== undefined) {
i = t.options.materialized ? "MATERIALIZED" : "NOT MATERIALIZED";
}
return [ r, a, "AS", i, `(${n})` ].filter(Boolean).join(" ");
});
return "WITH " + t.join(", ") + " ";
}
getWhereInIdsCondition(e) {
const t = this.expressionMap.mainAlias.metadata;
const n = (Array.isArray(e) ? e : [ e ]).map(e => t.ensureEntityIdMap(e));
if (!t.hasMultiplePrimaryKeys) {
const e = t.primaryColumns[0];
if (!e.transformer && !e.relationMetadata && !e.embeddedMetadata) {
return {
[e.propertyName]: (0, Ys.In)(n.map(t => e.getEntityValue(t, false)))
};
}
}
return new Hs.Brackets(e => {
for (const t of n) {
e.orWhere(new Hs.Brackets(e => e.where(t)));
}
});
}
getExistsCondition(e) {
const t = e.clone().orderBy().groupBy().offset(undefined).limit(undefined).skip(undefined).take(undefined).select("1").setOption("disable-global-order");
return [ `EXISTS (${t.getQuery()})`, t.getParameters() ];
}
findColumnsForPropertyPath(e) {
let t = this.expressionMap.mainAlias;
const n = [];
const a = e.split(".");
while (a.length > 1) {
const e = a[0];
if (!t?.hasMetadata) {
break;
}
if (t.metadata.hasEmbeddedWithPropertyPath(e)) {
a.unshift(`${a.shift()}.${a.shift()}`);
continue;
}
if (t.metadata.hasRelationWithPropertyPath(e)) {
const r = this.expressionMap.joinAttributes.find(t => t.relationPropertyPath === e);
if (!r?.alias) {
const t = n.length > 0 ? `${n.join(".")}.${e}` : e;
throw new Error(`Cannot find alias for relation at ${t}`);
}
t = r.alias;
n.push(...e.split("."));
a.shift();
continue;
}
break;
}
if (!t) {
throw new Error(`Cannot find alias for property ${e}`);
}
const r = a.join(".");
const i = t.metadata.findColumnsWithPropertyPath(r);
if (!i.length) {
throw new Js.EntityPropertyNotFoundError(e, t.metadata);
}
return [ t, n, i ];
}
createPropertyPath(e, t, n = "") {
const a = [];
for (const r of Object.keys(t)) {
const i = n ? `${n}.${r}` : r;
if (t[r] === null || typeof t[r] !== "object" || Xs.InstanceChecker.isFindOperator(t[r])) {
a.push(i);
continue;
}
if (e.hasEmbeddedWithPropertyPath(i)) {
const n = this.createPropertyPath(e, t[r], i);
a.push(...n);
continue;
}
if (e.hasRelationWithPropertyPath(i)) {
const n = e.findRelationWithPropertyPath(i);
if (n.relationType === "one-to-one" || n.relationType === "many-to-one") {
const e = n.joinColumns.map(e => e.referencedColumn).filter(e => !!e);
const s = e.length > 0 && e.every(e => e.getEntityValue(t[r], false));
if (s) {
a.push(i);
continue;
}
}
if (n.relationType === "one-to-many" || n.relationType === "many-to-many") {
throw new Error(`Cannot query across ${n.relationType} for property ${i}`);
}
const s = n.inverseEntityMetadata.primaryColumns;
const o = s.length > 0 && s.every(e => e.getEntityValue(t[r], false));
if (o) {
const e = s.map(e => `${i}.${e.propertyPath}`);
a.push(...e);
continue;
}
const c = this.createPropertyPath(n.inverseEntityMetadata, t[r]).map(e => `${i}.${e}`);
a.push(...c);
continue;
}
a.push(i);
}
return a;
}
* getPredicates(e) {
if (this.expressionMap.mainAlias.hasMetadata) {
const t = this.createPropertyPath(this.expressionMap.mainAlias.metadata, e);
for (const n of t) {
const [t, a, r] = this.findColumnsForPropertyPath(n);
for (const n of r) {
let r = e;
for (const e of a) {
if (!r || !(e in r)) {
r = {};
break;
}
r = r[e];
}
const i = this.expressionMap.aliasNamePrefixingEnabled ? `${t.name}.${n.propertyPath}` : n.propertyPath;
const s = n.getEntityValue(r, true);
yield [ i, s ];
}
}
} else {
for (const t of Object.keys(e)) {
const n = e[t];
const a = this.expressionMap.aliasNamePrefixingEnabled ? `${this.alias}.${t}` : t;
yield [ a, n ];
}
}
}
getWherePredicateCondition(e, t) {
if (Xs.InstanceChecker.isFindOperator(t)) {
const n = [];
if (t.useParameter) {
if (t.objectLiteralParameters) {
this.setParameters(t.objectLiteralParameters);
} else if (t.multipleParameters) {
for (const e of t.value) {
n.push(this.createParameter(e));
}
} else {
n.push(this.createParameter(t.value));
}
}
if (t.type === "raw") {
if (t.getSql) {
return t.getSql(e);
} else {
return {
operator: "equal",
parameters: [ e, t.value ]
};
}
} else if (t.type === "not") {
if (t.child) {
return {
operator: t.type,
condition: this.getWherePredicateCondition(e, t.child)
};
} else {
return {
operator: "notEqual",
parameters: [ e, ...n ]
};
}
} else if (t.type === "and") {
const n = t.value;
return {
operator: t.type,
parameters: n.map(t => this.createWhereConditionExpression(this.getWherePredicateCondition(e, t)))
};
} else if (t.type === "or") {
const n = t.value;
return {
operator: t.type,
parameters: n.map(t => this.createWhereConditionExpression(this.getWherePredicateCondition(e, t)))
};
} else {
return {
operator: t.type,
parameters: [ e, ...n ]
};
}
} else {
return {
operator: "equal",
parameters: [ e, this.createParameter(t) ]
};
}
}
getWhereCondition(e) {
if (typeof e === "string") {
return e;
}
if (Xs.InstanceChecker.isBrackets(e)) {
const t = this.createQueryBuilder();
t.parentQueryBuilder = this;
t.expressionMap.mainAlias = this.expressionMap.mainAlias;
t.expressionMap.aliasNamePrefixingEnabled = this.expressionMap.aliasNamePrefixingEnabled;
t.expressionMap.parameters = this.expressionMap.parameters;
t.expressionMap.nativeParameters = this.expressionMap.nativeParameters;
t.expressionMap.wheres = [];
e.whereFactory(t);
return {
operator: Xs.InstanceChecker.isNotBrackets(e) ? "not" : "brackets",
condition: t.expressionMap.wheres
};
}
if (typeof e === "function") {
return e(this);
}
const t = Array.isArray(e) ? e : [ e ];
const n = [];
for (const e of t) {
const t = [];
for (const [n, a] of this.getPredicates(e)) {
t.push({
type: "and",
condition: this.getWherePredicateCondition(n, a)
});
}
n.push({
type: "or",
condition: t
});
}
if (n.length === 1) {
return n[0].condition;
}
return n;
}
obtainQueryRunner() {
return this.queryRunner || this.connection.createQueryRunner();
}
hasCommonTableExpressions() {
return this.expressionMap.commonTableExpressions.length > 0;
}
}
Ks = M.QueryBuilder = QueryBuilder;
QueryBuilder.queryBuilderRegistry = {};
var eo = {};
Object.defineProperty(eo, "__esModule", {
value: true
});
var to = eo.DeleteResult = void 0;
class DeleteResult {
static from(e) {
const t = new this;
t.raw = e.records;
t.affected = e.affected;
return t;
}
}
to = eo.DeleteResult = DeleteResult;
Object.defineProperty(w, "__esModule", {
value: true
});
var no = w.DeleteQueryBuilder = void 0;
const ao = M;
const ro = eo;
const io = et;
const so = Te;
class DeleteQueryBuilder extends ao.QueryBuilder {
constructor(e, t) {
super(e, t);
this["@instanceof"] = Symbol.for("DeleteQueryBuilder");
this.expressionMap.aliasNamePrefixingEnabled = false;
}
getQuery() {
let e = this.createComment();
e += this.createCteExpression();
e += this.createDeleteExpression();
return this.replacePropertyNamesForTheWholeQuery(e.trim());
}
async execute() {
const [e, t] = this.getQueryAndParameters();
const n = this.obtainQueryRunner();
let a = false;
try {
if (this.expressionMap.useTransaction === true && n.isTransactionActive === false) {
await n.startTransaction();
a = true;
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
await n.broadcaster.broadcast("BeforeRemove", this.expressionMap.mainAlias.metadata);
}
const r = await n.query(e, t, true);
const i = ro.DeleteResult.from(r);
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
await n.broadcaster.broadcast("AfterRemove", this.expressionMap.mainAlias.metadata);
}
if (a) await n.commitTransaction();
return i;
} catch (e) {
if (a) {
try {
await n.rollbackTransaction();
} catch (e) {}
}
throw e;
} finally {
if (n !== this.queryRunner) {
await n.release();
}
}
}
from(e, t) {
e = so.InstanceChecker.isEntitySchema(e) ? e.options.name : e;
const n = this.createFromAlias(e, t);
this.expressionMap.setMainAlias(n);
return this;
}
where(e, t) {
this.expressionMap.wheres = [];
const n = this.getWhereCondition(e);
if (n) this.expressionMap.wheres = [ {
type: "simple",
condition: n
} ];
if (t) this.setParameters(t);
return this;
}
andWhere(e, t) {
this.expressionMap.wheres.push({
type: "and",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
orWhere(e, t) {
this.expressionMap.wheres.push({
type: "or",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
whereInIds(e) {
return this.where(this.getWhereInIdsCondition(e));
}
andWhereInIds(e) {
return this.andWhere(this.getWhereInIdsCondition(e));
}
orWhereInIds(e) {
return this.orWhere(this.getWhereInIdsCondition(e));
}
output(e) {
return this.returning(e);
}
returning(e) {
if (!this.connection.driver.isReturningSqlSupported("delete")) {
throw new io.ReturningStatementNotSupportedError;
}
this.expressionMap.returning = e;
return this;
}
createDeleteExpression() {
const e = this.getTableName(this.getMainTableName());
const t = this.createWhereExpression();
const n = this.createReturningExpression("delete");
if (n === "") {
return `DELETE FROM ${e}${t}`;
}
if (this.connection.driver.options.type === "mssql") {
return `DELETE FROM ${e} OUTPUT ${n}${t}`;
}
if (this.connection.driver.options.type === "spanner") {
return `DELETE FROM ${e}${t} THEN RETURN ${n}`;
}
return `DELETE FROM ${e}${t} RETURNING ${n}`;
}
}
no = w.DeleteQueryBuilder = DeleteQueryBuilder;
var oo = {};
const co = "ffffffff-ffff-ffff-ffff-ffffffffffff";
const lo = "00000000-0000-0000-0000-000000000000";
const uo = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
function ho(e) {
return typeof e === "string" && uo.test(e);
}
function po(e) {
if (!ho(e)) {
throw TypeError("Invalid UUID");
}
let t;
return Uint8Array.of((t = parseInt(e.slice(0, 8), 16)) >>> 24, t >>> 16 & 255, t >>> 8 & 255, t & 255, (t = parseInt(e.slice(9, 13), 16)) >>> 8, t & 255, (t = parseInt(e.slice(14, 18), 16)) >>> 8, t & 255, (t = parseInt(e.slice(19, 23), 16)) >>> 8, t & 255, (t = parseInt(e.slice(24, 36), 16)) / 1099511627776 & 255, t / 4294967296 & 255, t >>> 24 & 255, t >>> 16 & 255, t >>> 8 & 255, t & 255);
}
const mo = [];
for (let e = 0; e < 256; ++e) {
mo.push((e + 256).toString(16).slice(1));
}
function fo(e, t = 0) {
return (mo[e[t + 0]] + mo[e[t + 1]] + mo[e[t + 2]] + mo[e[t + 3]] + "-" + mo[e[t + 4]] + mo[e[t + 5]] + "-" + mo[e[t + 6]] + mo[e[t + 7]] + "-" + mo[e[t + 8]] + mo[e[t + 9]] + "-" + mo[e[t + 10]] + mo[e[t + 11]] + mo[e[t + 12]] + mo[e[t + 13]] + mo[e[t + 14]] + mo[e[t + 15]]).toLowerCase();
}
function yo(e, t = 0) {
const n = fo(e, t);
if (!ho(n)) {
throw TypeError("Stringified UUID is invalid");
}
return n;
}
let Eo;
const To = new Uint8Array(16);
function go() {
if (!Eo) {
if (typeof crypto === "undefined" || !crypto.getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
Eo = crypto.getRandomValues.bind(crypto);
}
return Eo(To);
}
const No = {};
function Ao(e, t, n) {
let a;
const r = e?._v6 ?? false;
if (e) {
const t = Object.keys(e);
if (t.length === 1 && t[0] === "_v6") {
e = undefined;
}
}
if (e) {
a = Co(e.random ?? e.rng?.() ?? go(), e.msecs, e.nsecs, e.clockseq, e.node, t, n);
} else {
const e = Date.now();
const i = go();
bo(No, e, i);
a = Co(i, No.msecs, No.nsecs, r ? undefined : No.clockseq, r ? undefined : No.node, t, n);
}
return t ?? fo(a);
}
function bo(e, t, n) {
e.msecs ??= -Infinity;
e.nsecs ??= 0;
if (t === e.msecs) {
e.nsecs++;
if (e.nsecs >= 1e4) {
e.node = undefined;
e.nsecs = 0;
}
} else if (t > e.msecs) {
e.nsecs = 0;
} else if (t < e.msecs) {
e.node = undefined;
}
if (!e.node) {
e.node = n.slice(10, 16);
e.node[0] |= 1;
e.clockseq = (n[8] << 8 | n[9]) & 16383;
}
e.msecs = t;
return e;
}
function Co(e, t, n, a, r, i, s = 0) {
if (e.length < 16) {
throw new Error("Random bytes length must be >= 16");
}
if (!i) {
i = new Uint8Array(16);
s = 0;
} else {
if (s < 0 || s + 16 > i.length) {
throw new RangeError(`UUID byte range ${s}:${s + 15} is out of buffer bounds`);
}
}
t ??= Date.now();
n ??= 0;
a ??= (e[8] << 8 | e[9]) & 16383;
r ??= e.slice(10, 16);
t += 122192928e5;
const o = ((t & 268435455) * 1e4 + n) % 4294967296;
i[s++] = o >>> 24 & 255;
i[s++] = o >>> 16 & 255;
i[s++] = o >>> 8 & 255;
i[s++] = o & 255;
const c = t / 4294967296 * 1e4 & 268435455;
i[s++] = c >>> 8 & 255;
i[s++] = c & 255;
i[s++] = c >>> 24 & 15 | 16;
i[s++] = c >>> 16 & 255;
i[s++] = a >>> 8 | 128;
i[s++] = a & 255;
for (let e = 0; e < 6; ++e) {
i[s++] = r[e];
}
return i;
}
function Ro(e) {
const t = typeof e === "string" ? po(e) : e;
const n = So(t);
return typeof e === "string" ? fo(n) : n;
}
function So(e) {
return Uint8Array.of((e[6] & 15) << 4 | e[7] >> 4 & 15, (e[7] & 15) << 4 | (e[4] & 240) >> 4, (e[4] & 15) << 4 | (e[5] & 240) >> 4, (e[5] & 15) << 4 | (e[0] & 240) >> 4, (e[0] & 15) << 4 | (e[1] & 240) >> 4, (e[1] & 15) << 4 | (e[2] & 240) >> 4, 96 | e[2] & 15, e[3], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]);
}
function wo(e) {
const t = Io(e);
const n = vo(t, e.length * 8);
return Mo(n);
}
function Mo(e) {
const t = new Uint8Array(e.length * 4);
for (let n = 0; n < e.length * 4; n++) {
t[n] = e[n >> 2] >>> n % 4 * 8 & 255;
}
return t;
}
function Oo(e) {
return (e + 64 >>> 9 << 4) + 14 + 1;
}
function vo(e, t) {
const n = new Uint32Array(Oo(t)).fill(0);
n.set(e);
n[t >> 5] |= 128 << t % 32;
n[n.length - 1] = t;
e = n;
let a = 1732584193;
let r = -271733879;
let i = -1732584194;
let s = 271733878;
for (let t = 0; t < e.length; t += 16) {
const n = a;
const o = r;
const c = i;
const l = s;
a = _o(a, r, i, s, e[t], 7, -680876936);
s = _o(s, a, r, i, e[t + 1], 12, -389564586);
i = _o(i, s, a, r, e[t + 2], 17, 606105819);
r = _o(r, i, s, a, e[t + 3], 22, -1044525330);
a = _o(a, r, i, s, e[t + 4], 7, -176418897);
s = _o(s, a, r, i, e[t + 5], 12, 1200080426);
i = _o(i, s, a, r, e[t + 6], 17, -1473231341);
r = _o(r, i, s, a, e[t + 7], 22, -45705983);
a = _o(a, r, i, s, e[t + 8], 7, 1770035416);
s = _o(s, a, r, i, e[t + 9], 12, -1958414417);
i = _o(i, s, a, r, e[t + 10], 17, -42063);
r = _o(r, i, s, a, e[t + 11], 22, -1990404162);
a = _o(a, r, i, s, e[t + 12], 7, 1804603682);
s = _o(s, a, r, i, e[t + 13], 12, -40341101);
i = _o(i, s, a, r, e[t + 14], 17, -1502002290);
r = _o(r, i, s, a, e[t + 15], 22, 1236535329);
a = $o(a, r, i, s, e[t + 1], 5, -165796510);
s = $o(s, a, r, i, e[t + 6], 9, -1069501632);
i = $o(i, s, a, r, e[t + 11], 14, 643717713);
r = $o(r, i, s, a, e[t], 20, -373897302);
a = $o(a, r, i, s, e[t + 5], 5, -701558691);
s = $o(s, a, r, i, e[t + 10], 9, 38016083);
i = $o(i, s, a, r, e[t + 15], 14, -660478335);
r = $o(r, i, s, a, e[t + 4], 20, -405537848);
a = $o(a, r, i, s, e[t + 9], 5, 568446438);
s = $o(s, a, r, i, e[t + 14], 9, -1019803690);
i = $o(i, s, a, r, e[t + 3], 14, -187363961);
r = $o(r, i, s, a, e[t + 8], 20, 1163531501);
a = $o(a, r, i, s, e[t + 13], 5, -1444681467);
s = $o(s, a, r, i, e[t + 2], 9, -51403784);
i = $o(i, s, a, r, e[t + 7], 14, 1735328473);
r = $o(r, i, s, a, e[t + 12], 20, -1926607734);
a = xo(a, r, i, s, e[t + 5], 4, -378558);
s = xo(s, a, r, i, e[t + 8], 11, -2022574463);
i = xo(i, s, a, r, e[t + 11], 16, 1839030562);
r = xo(r, i, s, a, e[t + 14], 23, -35309556);
a = xo(a, r, i, s, e[t + 1], 4, -1530992060);
s = xo(s, a, r, i, e[t + 4], 11, 1272893353);
i = xo(i, s, a, r, e[t + 7], 16, -155497632);
r = xo(r, i, s, a, e[t + 10], 23, -1094730640);
a = xo(a, r, i, s, e[t + 13], 4, 681279174);
s = xo(s, a, r, i, e[t], 11, -358537222);
i = xo(i, s, a, r, e[t + 3], 16, -722521979);
r = xo(r, i, s, a, e[t + 6], 23, 76029189);
a = xo(a, r, i, s, e[t + 9], 4, -640364487);
s = xo(s, a, r, i, e[t + 12], 11, -421815835);
i = xo(i, s, a, r, e[t + 15], 16, 530742520);
r = xo(r, i, s, a, e[t + 2], 23, -995338651);
a = qo(a, r, i, s, e[t], 6, -198630844);
s = qo(s, a, r, i, e[t + 7], 10, 1126891415);
i = qo(i, s, a, r, e[t + 14], 15, -1416354905);
r = qo(r, i, s, a, e[t + 5], 21, -57434055);
a = qo(a, r, i, s, e[t + 12], 6, 1700485571);
s = qo(s, a, r, i, e[t + 3], 10, -1894986606);
i = qo(i, s, a, r, e[t + 10], 15, -1051523);
r = qo(r, i, s, a, e[t + 1], 21, -2054922799);
a = qo(a, r, i, s, e[t + 8], 6, 1873313359);
s = qo(s, a, r, i, e[t + 15], 10, -30611744);
i = qo(i, s, a, r, e[t + 6], 15, -1560198380);
r = qo(r, i, s, a, e[t + 13], 21, 1309151649);
a = qo(a, r, i, s, e[t + 4], 6, -145523070);
s = qo(s, a, r, i, e[t + 11], 10, -1120210379);
i = qo(i, s, a, r, e[t + 2], 15, 718787259);
r = qo(r, i, s, a, e[t + 9], 21, -343485551);
a = Po(a, n);
r = Po(r, o);
i = Po(i, c);
s = Po(s, l);
}
return Uint32Array.of(a, r, i, s);
}
function Io(e) {
if (e.length === 0) {
return new Uint32Array;
}
const t = new Uint32Array(Oo(e.length * 8)).fill(0);
for (let n = 0; n < e.length; n++) {
t[n >> 2] |= (e[n] & 255) << n % 4 * 8;
}
return t;
}
function Po(e, t) {
const n = (e & 65535) + (t & 65535);
const a = (e >> 16) + (t >> 16) + (n >> 16);
return a << 16 | n & 65535;
}
function Lo(e, t) {
return e << t | e >>> 32 - t;
}
function Do(e, t, n, a, r, i) {
return Po(Lo(Po(Po(t, e), Po(a, i)), r), n);
}
function _o(e, t, n, a, r, i, s) {
return Do(t & n | ~t & a, e, t, r, i, s);
}
function $o(e, t, n, a, r, i, s) {
return Do(t & a | n & ~a, e, t, r, i, s);
}
function xo(e, t, n, a, r, i, s) {
return Do(t ^ n ^ a, e, t, r, i, s);
}
function qo(e, t, n, a, r, i, s) {
return Do(n ^ (t | ~a), e, t, r, i, s);
}
function Uo(e) {
e = unescape(encodeURIComponent(e));
const t = new Uint8Array(e.length);
for (let n = 0; n < e.length; ++n) {
t[n] = e.charCodeAt(n);
}
return t;
}
const Bo = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
const Fo = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
function jo(e, t, n, a, r, i) {
const s = typeof n === "string" ? Uo(n) : n;
const o = typeof a === "string" ? po(a) : a;
if (typeof a === "string") {
a = po(a);
}
if (a?.length !== 16) {
throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
}
let c = new Uint8Array(16 + s.length);
c.set(o);
c.set(s, o.length);
c = t(c);
c[6] = c[6] & 15 | e;
c[8] = c[8] & 63 | 128;
if (r) {
i = i || 0;
for (let e = 0; e < 16; ++e) {
r[i + e] = c[e];
}
return r;
}
return fo(c);
}
function ko(e, t, n, a) {
return jo(48, wo, e, t, n, a);
}
ko.DNS = Bo;
ko.URL = Fo;
const Qo = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const Vo = {
randomUUID: Qo
};
function Ko(e, t, n) {
if (Vo.randomUUID && !t && !e) {
return Vo.randomUUID();
}
e = e || {};
const a = e.random ?? e.rng?.() ?? go();
if (a.length < 16) {
throw new Error("Random bytes length must be >= 16");
}
a[6] = a[6] & 15 | 64;
a[8] = a[8] & 63 | 128;
if (t) {
n = n || 0;
if (n < 0 || n + 16 > t.length) {
throw new RangeError(`UUID byte range ${n}:${n + 15} is out of buffer bounds`);
}
for (let e = 0; e < 16; ++e) {
t[n + e] = a[e];
}
return t;
}
return fo(a);
}
function Wo(e, t, n, a) {
switch (e) {
case 0:
return t & n ^ ~t & a;
case 1:
return t ^ n ^ a;
case 2:
return t & n ^ t & a ^ n & a;
case 3:
return t ^ n ^ a;
}
}
function Ho(e, t) {
return e << t | e >>> 32 - t;
}
function Go(e) {
const t = [ 1518500249, 1859775393, 2400959708, 3395469782 ];
const n = [ 1732584193, 4023233417, 2562383102, 271733878, 3285377520 ];
const a = new Uint8Array(e.length + 1);
a.set(e);
a[e.length] = 128;
e = a;
const r = e.length / 4 + 2;
const i = Math.ceil(r / 16);
const s = new Array(i);
for (let t = 0; t < i; ++t) {
const n = new Uint32Array(16);
for (let a = 0; a < 16; ++a) {
n[a] = e[t * 64 + a * 4] << 24 | e[t * 64 + a * 4 + 1] << 16 | e[t * 64 + a * 4 + 2] << 8 | e[t * 64 + a * 4 + 3];
}
s[t] = n;
}
s[i - 1][14] = (e.length - 1) * 8 / Math.pow(2, 32);
s[i - 1][14] = Math.floor(s[i - 1][14]);
s[i - 1][15] = (e.length - 1) * 8 & 4294967295;
for (let e = 0; e < i; ++e) {
const a = new Uint32Array(80);
for (let t = 0; t < 16; ++t) {
a[t] = s[e][t];
}
for (let e = 16; e < 80; ++e) {
a[e] = Ho(a[e - 3] ^ a[e - 8] ^ a[e - 14] ^ a[e - 16], 1);
}
let r = n[0];
let i = n[1];
let o = n[2];
let c = n[3];
let l = n[4];
for (let e = 0; e < 80; ++e) {
const n = Math.floor(e / 20);
const s = Ho(r, 5) + Wo(n, i, o, c) + l + t[n] + a[e] >>> 0;
l = c;
c = o;
o = Ho(i, 30) >>> 0;
i = r;
r = s;
}
n[0] = n[0] + r >>> 0;
n[1] = n[1] + i >>> 0;
n[2] = n[2] + o >>> 0;
n[3] = n[3] + c >>> 0;
n[4] = n[4] + l >>> 0;
}
return Uint8Array.of(n[0] >> 24, n[0] >> 16, n[0] >> 8, n[0], n[1] >> 24, n[1] >> 16, n[1] >> 8, n[1], n[2] >> 24, n[2] >> 16, n[2] >> 8, n[2], n[3] >> 24, n[3] >> 16, n[3] >> 8, n[3], n[4] >> 24, n[4] >> 16, n[4] >> 8, n[4]);
}
function Yo(e, t, n, a) {
return jo(80, Go, e, t, n, a);
}
Yo.DNS = Bo;
Yo.URL = Fo;
function zo(e, t, n) {
e ??= {};
n ??= 0;
let a = Ao({
...e,
_v6: true
}, new Uint8Array(16));
a = Ro(a);
if (t) {
for (let e = 0; e < 16; e++) {
t[n + e] = a[e];
}
return t;
}
return fo(a);
}
function Jo(e) {
const t = typeof e === "string" ? po(e) : e;
const n = Xo(t);
return typeof e === "string" ? fo(n) : n;
}
function Xo(e) {
return Uint8Array.of((e[3] & 15) << 4 | e[4] >> 4 & 15, (e[4] & 15) << 4 | (e[5] & 240) >> 4, (e[5] & 15) << 4 | e[6] & 15, e[7], (e[1] & 15) << 4 | (e[2] & 240) >> 4, (e[2] & 15) << 4 | (e[3] & 240) >> 4, 16 | (e[0] & 240) >> 4, (e[0] & 15) << 4 | (e[1] & 240) >> 4, e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]);
}
const Zo = {};
function ec(e, t, n) {
let a;
if (e) {
a = nc(e.random ?? e.rng?.() ?? go(), e.msecs, e.seq, t, n);
} else {
const e = Date.now();
const r = go();
tc(Zo, e, r);
a = nc(r, Zo.msecs, Zo.seq, t, n);
}
return t ?? fo(a);
}
function tc(e, t, n) {
e.msecs ??= -Infinity;
e.seq ??= 0;
if (t > e.msecs) {
e.seq = n[6] << 23 | n[7] << 16 | n[8] << 8 | n[9];
e.msecs = t;
} else {
e.seq = e.seq + 1 | 0;
if (e.seq === 0) {
e.msecs++;
}
}
return e;
}
function nc(e, t, n, a, r = 0) {
if (e.length < 16) {
throw new Error("Random bytes length must be >= 16");
}
if (!a) {
a = new Uint8Array(16);
r = 0;
} else {
if (r < 0 || r + 16 > a.length) {
throw new RangeError(`UUID byte range ${r}:${r + 15} is out of buffer bounds`);
}
}
t ??= Date.now();
n ??= e[6] * 127 << 24 | e[7] << 16 | e[8] << 8 | e[9];
a[r++] = t / 1099511627776 & 255;
a[r++] = t / 4294967296 & 255;
a[r++] = t / 16777216 & 255;
a[r++] = t / 65536 & 255;
a[r++] = t / 256 & 255;
a[r++] = t & 255;
a[r++] = 112 | n >>> 28 & 15;
a[r++] = n >>> 20 & 255;
a[r++] = 128 | n >>> 14 & 63;
a[r++] = n >>> 6 & 255;
a[r++] = n << 2 & 255 | e[10] & 3;
a[r++] = e[11];
a[r++] = e[12];
a[r++] = e[13];
a[r++] = e[14];
a[r++] = e[15];
return a;
}
function ac(e) {
if (!ho(e)) {
throw TypeError("Invalid UUID");
}
return parseInt(e.slice(14, 15), 16);
}
const rc = Object.freeze(Object.defineProperty({
__proto__: null,
MAX: co,
NIL: lo,
parse: po,
stringify: yo,
v1: Ao,
v1ToV6: Ro,
v3: ko,
v4: Ko,
v5: Yo,
v6: zo,
v6ToV1: Jo,
v7: ec,
validate: ho,
version: ac
}, Symbol.toStringTag, {
value: "Module"
}));
const ic = i(rc);
var sc = {};
Object.defineProperty(sc, "__esModule", {
value: true
});
sc.BroadcasterResult = void 0;
class BroadcasterResult {
constructor() {
this.count = 0;
this.promises = [];
}
async wait() {
if (this.promises.length > 0) {
await Promise.all(this.promises);
}
return this;
}
}
sc.BroadcasterResult = BroadcasterResult;
var oc = {};
Object.defineProperty(oc, "__esModule", {
value: true
});
var cc = oc.InsertResult = void 0;
class InsertResult {
constructor() {
this.identifiers = [];
this.generatedMaps = [];
}
static from(e) {
const t = new this;
t.raw = e.raw;
return t;
}
}
cc = oc.InsertResult = InsertResult;
var lc = {};
Object.defineProperty(lc, "__esModule", {
value: true
});
lc.ReturningResultsEntityUpdator = void 0;
const uc = P;
class ReturningResultsEntityUpdator {
constructor(e, t) {
this.queryRunner = e;
this.expressionMap = t;
}
async update(e, t) {
const n = this.expressionMap.mainAlias.metadata;
await Promise.all(t.map(async (t, a) => {
if (this.queryRunner.connection.driver.isReturningSqlSupported("update")) {
if (this.queryRunner.connection.driver.options.type === "oracle" && Array.isArray(e.raw) && this.expressionMap.extraReturningColumns.length > 0) {
e.raw = e.raw.reduce((e, t, n) => {
e[this.expressionMap.extraReturningColumns[n].databaseName] = t[0];
return e;
}, {});
}
const r = Array.isArray(e.raw) ? e.raw[a] : e.raw;
const i = this.queryRunner.connection.driver.createGeneratedMap(n, r);
if (i) {
this.queryRunner.manager.merge(n.target, t, i);
e.generatedMaps.push(i);
}
} else {
const a = this.expressionMap.extraReturningColumns;
if (a.length > 0) {
const r = this.expressionMap.mainAlias.metadata.getEntityIdMap(t);
if (!r) throw new uc.TypeORMError(`Cannot update entity because entity id is not set in the entity.`);
const i = await this.queryRunner.manager.createQueryBuilder().select(n.primaryColumns.map(e => n.targetName + "." + e.propertyPath)).addSelect(a.map(e => n.targetName + "." + e.propertyPath)).from(n.target, n.targetName).where(r).withDeleted().setOption("create-pojo").getOne();
if (i) {
this.queryRunner.manager.merge(n.target, t, i);
e.generatedMaps.push(i);
}
}
}
}));
}
async insert(e, t) {
const n = this.expressionMap.mainAlias.metadata;
let a = n.getInsertionReturningColumns();
const r = this.queryRunner.connection.driver.isReturningSqlSupported("insert");
a = a.filter(e => {
if (!e.isGenerated) return true;
return r === true;
});
const i = t.map((a, r) => {
if (Array.isArray(e.raw) && this.expressionMap.extraReturningColumns.length > 0) {
if (this.queryRunner.connection.driver.options.type === "oracle") {
e.raw = e.raw.reduce((e, t, n) => {
e[this.expressionMap.extraReturningColumns[n].databaseName] = t[0];
return e;
}, {});
} else if (this.queryRunner.connection.driver.options.type === "spanner") {
e.raw = e.raw[0];
}
}
const i = Array.isArray(e.raw) ? e.raw[r] : e.raw;
const s = this.queryRunner.connection.driver.createGeneratedMap(n, i, r, t.length) || {};
if (r in this.expressionMap.locallyGenerated) {
this.queryRunner.manager.merge(n.target, s, this.expressionMap.locallyGenerated[r]);
}
this.queryRunner.manager.merge(n.target, a, s);
return s;
});
if (a.length > 0 && !this.queryRunner.connection.driver.isReturningSqlSupported("insert")) {
const e = t.map(e => {
const t = n.getEntityIdMap(e);
if (!t) throw new uc.TypeORMError(`Cannot update entity because entity id is not set in the entity.`);
return t;
});
const r = await this.queryRunner.manager.createQueryBuilder().select(n.primaryColumns.map(e => n.targetName + "." + e.propertyPath)).addSelect(a.map(e => n.targetName + "." + e.propertyPath)).from(n.target, n.targetName).where(e).setOption("create-pojo").getMany();
t.forEach((e, t) => {
this.queryRunner.manager.merge(n.target, i[t], r[t]);
this.queryRunner.manager.merge(n.target, e, r[t]);
});
}
t.forEach((t, a) => {
const r = n.getEntityIdMap(t);
e.identifiers.push(r);
e.generatedMaps.push(i[a]);
});
}
getUpdationReturningColumns() {
return this.expressionMap.mainAlias.metadata.columns.filter(e => e.asExpression !== undefined || e.isUpdateDate || e.isVersion);
}
getSoftDeletionReturningColumns() {
return this.expressionMap.mainAlias.metadata.columns.filter(e => e.asExpression !== undefined || e.isUpdateDate || e.isVersion || e.isDeleteDate);
}
}
lc.ReturningResultsEntityUpdator = ReturningResultsEntityUpdator;
Object.defineProperty(oo, "__esModule", {
value: true
});
var hc = oo.InsertQueryBuilder = void 0;
const dc = ic;
const pc = jn;
const mc = P;
const fc = Mt;
const yc = et;
const Ec = sc;
const Tc = Te;
const gc = I;
const Nc = M;
const Ac = oc;
const bc = lc;
class InsertQueryBuilder extends Nc.QueryBuilder {
constructor() {
super(...arguments);
this["@instanceof"] = Symbol.for("InsertQueryBuilder");
}
getQuery() {
let e = this.createComment();
e += this.createCteExpression();
e += this.createInsertExpression();
return this.replacePropertyNamesForTheWholeQuery(e.trim());
}
async execute() {
const e = this.getValueSets();
if (e.length === 0) return new Ac.InsertResult;
const t = this.obtainQueryRunner();
let n = false;
try {
if (this.expressionMap.useTransaction === true && t.isTransactionActive === false) {
await t.startTransaction();
n = true;
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
const n = new Ec.BroadcasterResult;
e.forEach(e => {
t.broadcaster.broadcastBeforeInsertEvent(n, this.expressionMap.mainAlias.metadata, e);
});
await n.wait();
}
let a = null;
let r = null;
const i = new bc.ReturningResultsEntityUpdator(t, this.expressionMap);
const s = [];
if (Array.isArray(this.expressionMap.returning) && this.expressionMap.mainAlias.hasMetadata) {
for (const e of this.expressionMap.returning) {
s.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(e));
}
}
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata) {
if (!(e.length > 1 && this.connection.driver.options.type === "oracle")) {
this.expressionMap.extraReturningColumns = this.expressionMap.mainAlias.metadata.getInsertionReturningColumns();
}
s.push(...this.expressionMap.extraReturningColumns.filter(e => !s.includes(e)));
}
if (s.length > 0 && this.connection.driver.options.type === "mssql") {
a = this.connection.driver.buildTableVariableDeclaration("@OutputTable", s);
r = `SELECT * FROM @OutputTable`;
}
const [o, c] = this.getQueryAndParameters();
const l = [ a, o, r ];
const u = l.filter(e => e != null).join(";\n\n");
const h = await t.query(u, c, true);
const d = Ac.InsertResult.from(h);
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata) {
await i.insert(d, e);
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
const n = new Ec.BroadcasterResult;
e.forEach(e => {
t.broadcaster.broadcastAfterInsertEvent(n, this.expressionMap.mainAlias.metadata, e);
});
await n.wait();
}
if (n) {
await t.commitTransaction();
}
return d;
} catch (e) {
if (n) {
try {
await t.rollbackTransaction();
} catch (e) {}
}
throw e;
} finally {
if (t !== this.queryRunner) {
await t.release();
}
}
}
into(e, t) {
e = Tc.InstanceChecker.isEntitySchema(e) ? e.options.name : e;
const n = this.createFromAlias(e);
this.expressionMap.setMainAlias(n);
this.expressionMap.insertColumns = t || [];
return this;
}
values(e) {
this.expressionMap.valuesSet = e;
return this;
}
output(e) {
return this.returning(e);
}
returning(e) {
if (!this.connection.driver.isReturningSqlSupported("insert")) {
throw new yc.ReturningStatementNotSupportedError;
}
this.expressionMap.returning = e;
return this;
}
updateEntity(e) {
this.expressionMap.updateEntity = e;
return this;
}
onConflict(e) {
this.expressionMap.onConflict = e;
return this;
}
orIgnore(e = true) {
this.expressionMap.onIgnore = !!e;
return this;
}
orUpdate(e, t, n) {
if (!Array.isArray(e)) {
this.expressionMap.onUpdate = {
conflict: e?.conflict_target,
columns: e?.columns,
overwrite: e?.overwrite,
skipUpdateIfNoValuesChanged: n?.skipUpdateIfNoValuesChanged,
upsertType: n?.upsertType
};
return this;
}
this.expressionMap.onUpdate = {
overwrite: e,
conflict: t,
skipUpdateIfNoValuesChanged: n?.skipUpdateIfNoValuesChanged,
indexPredicate: n?.indexPredicate,
upsertType: n?.upsertType
};
return this;
}
createInsertExpression() {
const e = this.getTableName(this.getMainTableName());
const t = this.createValuesExpression();
const n = this.connection.driver.options.type === "oracle" && this.getValueSets().length > 1 ? null : this.createReturningExpression("insert");
const a = this.createColumnNamesExpression();
let r = "INSERT ";
if (this.expressionMap.onUpdate?.upsertType === "primary-key") {
r = "UPSERT ";
}
if (pc.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") {
r += `${this.expressionMap.onIgnore ? " IGNORE " : ""}`;
}
r += `INTO ${e}`;
if (this.alias !== this.getMainTableName() && pc.DriverUtils.isPostgresFamily(this.connection.driver)) {
r += ` AS "${this.alias}"`;
}
if (a) {
r += `(${a})`;
} else {
if (!t && (pc.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql")) r += "()";
}
if (n && this.connection.driver.options.type === "mssql") {
r += ` OUTPUT ${n}`;
}
if (t) {
if ((this.connection.driver.options.type === "oracle" || this.connection.driver.options.type === "sap") && this.getValueSets().length > 1) {
r += ` ${t}`;
} else {
r += ` VALUES ${t}`;
}
} else {
if (pc.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") {
r += " VALUES ()";
} else {
r += ` DEFAULT VALUES`;
}
}
if (this.expressionMap.onUpdate?.upsertType !== "primary-key") {
if (this.connection.driver.supportedUpsertTypes.includes("on-conflict-do-update")) {
if (this.expressionMap.onIgnore) {
r += " ON CONFLICT DO NOTHING ";
} else if (this.expressionMap.onConflict) {
r += ` ON CONFLICT ${this.expressionMap.onConflict} `;
} else if (this.expressionMap.onUpdate) {
const {overwrite: e, columns: t, conflict: n, skipUpdateIfNoValuesChanged: a, indexPredicate: i} = this.expressionMap.onUpdate;
let s = "ON CONFLICT";
if (Array.isArray(n)) {
s += ` ( ${n.map(e => this.escape(e)).join(", ")} )`;
if (i && !pc.DriverUtils.isPostgresFamily(this.connection.driver)) {
throw new mc.TypeORMError(`indexPredicate option is not supported by the current database driver`);
}
if (i && pc.DriverUtils.isPostgresFamily(this.connection.driver)) {
s += ` WHERE ( ${i} )`;
}
} else if (n) {
s += ` ON CONSTRAINT ${this.escape(n)}`;
}
const o = [];
if (Array.isArray(e)) {
o.push(...e.map(e => `${this.escape(e)} = EXCLUDED.${this.escape(e)}`));
} else if (t) {
o.push(...t.map(e => `${this.escape(e)} = :${e}`));
}
if (o.length > 0) {
r += ` ${s} DO UPDATE SET `;
o.push(...this.expressionMap.mainAlias.metadata.columns.filter(t => t.isUpdateDate && !e?.includes(t.databaseName) && !(this.connection.driver.options.type === "oracle" && this.getValueSets().length > 1 || pc.DriverUtils.isSQLiteFamily(this.connection.driver) || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner")).map(e => `${this.escape(e.databaseName)} = DEFAULT`));
r += o.join(", ");
}
if (Array.isArray(e) && a && pc.DriverUtils.isPostgresFamily(this.connection.driver)) {
r += ` WHERE (`;
r += e.map(e => `${this.escape(this.alias)}.${this.escape(e)} IS DISTINCT FROM EXCLUDED.${this.escape(e)}`).join(" OR ");
r += ") ";
}
}
} else if (this.connection.driver.supportedUpsertTypes.includes("on-duplicate-key-update")) {
if (this.expressionMap.onUpdate) {
const {overwrite: e, columns: t} = this.expressionMap.onUpdate;
if (Array.isArray(e)) {
r += " ON DUPLICATE KEY UPDATE ";
r += e.map(e => `${this.escape(e)} = VALUES(${this.escape(e)})`).join(", ");
r += " ";
} else if (Array.isArray(t)) {
r += " ON DUPLICATE KEY UPDATE ";
r += t.map(e => `${this.escape(e)} = :${e}`).join(", ");
r += " ";
}
}
} else {
if (this.expressionMap.onUpdate) {
throw new mc.TypeORMError(`onUpdate is not supported by the current database driver`);
}
}
}
if (n && (pc.DriverUtils.isPostgresFamily(this.connection.driver) || this.connection.driver.options.type === "oracle" || this.connection.driver.options.type === "cockroachdb" || pc.DriverUtils.isMySQLFamily(this.connection.driver))) {
r += ` RETURNING ${n}`;
}
if (n && this.connection.driver.options.type === "spanner") {
r += ` THEN RETURN ${n}`;
}
if (this.connection.driver.options.type === "mssql" && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.mainAlias.metadata.columns.filter(e => this.expressionMap.insertColumns.length > 0 ? this.expressionMap.insertColumns.indexOf(e.propertyPath) !== -1 : e.isInsert).some(e => this.isOverridingAutoIncrementBehavior(e))) {
r = `SET IDENTITY_INSERT ${e} ON; ${r}; SET IDENTITY_INSERT ${e} OFF`;
}
return r;
}
getInsertedColumns() {
if (!this.expressionMap.mainAlias.hasMetadata) return [];
return this.expressionMap.mainAlias.metadata.columns.filter(e => {
if (this.expressionMap.insertColumns.length) return this.expressionMap.insertColumns.indexOf(e.propertyPath) !== -1;
if (!e.isInsert) {
return false;
}
if (e.isGenerated && e.generationStrategy === "increment" && !(this.connection.driver.options.type === "spanner") && !(this.connection.driver.options.type === "oracle") && !pc.DriverUtils.isSQLiteFamily(this.connection.driver) && !pc.DriverUtils.isMySQLFamily(this.connection.driver) && !(this.connection.driver.options.type === "aurora-mysql") && !(this.connection.driver.options.type === "mssql" && this.isOverridingAutoIncrementBehavior(e))) return false;
return true;
});
}
createColumnNamesExpression() {
const e = this.getInsertedColumns();
if (e.length > 0) return e.map(e => this.escape(e.databaseName)).join(", ");
if (!this.expressionMap.mainAlias.hasMetadata && !this.expressionMap.insertColumns.length) {
const e = this.getValueSets();
if (e.length === 1) return Object.keys(e[0]).map(e => this.escape(e)).join(", ");
}
return this.expressionMap.insertColumns.map(e => this.escape(e)).join(", ");
}
createValuesExpression() {
const e = this.getValueSets();
const t = this.getInsertedColumns();
if (t.length > 0) {
let n = "";
e.forEach((a, r) => {
t.forEach((i, s) => {
if (s === 0) {
if (this.connection.driver.options.type === "oracle" && e.length > 1) {
n += " SELECT ";
} else if (this.connection.driver.options.type === "sap" && e.length > 1) {
n += " SELECT ";
} else {
n += "(";
}
}
let o = i.getEntityValue(a);
if (!(typeof o === "function")) {
o = this.connection.driver.preparePersistentValue(o, i);
}
if (i.isVersion && o === undefined) {
n += "1";
} else if (i.isDiscriminator) {
n += this.createParameter(this.expressionMap.mainAlias.metadata.discriminatorValue);
} else if (i.isGenerated && i.generationStrategy === "uuid" && !this.connection.driver.isUUIDGenerationSupported() && o === undefined) {
o = (0, dc.v4)();
n += this.createParameter(o);
if (!(r in this.expressionMap.locallyGenerated)) {
this.expressionMap.locallyGenerated[r] = {};
}
i.setEntityValue(this.expressionMap.locallyGenerated[r], o);
} else if (o === undefined) {
if (this.connection.driver.options.type === "oracle" && e.length > 1 || pc.DriverUtils.isSQLiteFamily(this.connection.driver) || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
if (i.default !== undefined && i.default !== null) {
n += this.connection.driver.normalizeDefault(i);
} else if (this.connection.driver.options.type === "spanner" && i.isGenerated && i.generationStrategy === "uuid") {
n += "GENERATE_UUID()";
} else {
n += "NULL";
}
} else {
n += "DEFAULT";
}
} else if (o === null && (this.connection.driver.options.type === "spanner" || this.connection.driver.options.type === "oracle")) {
n += "NULL";
} else if (typeof o === "function") {
n += o();
} else {
if (this.connection.driver.options.type === "mssql") o = this.connection.driver.parametrizeValue(i, o);
const e = this.createParameter(o);
if ((pc.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.spatialTypes.indexOf(i.type) !== -1) {
const t = this.connection.driver.options.legacySpatialSupport;
const a = t ? "GeomFromText" : "ST_GeomFromText";
if (i.srid != null) {
n += `${a}(${e}, ${i.srid})`;
} else {
n += `${a}(${e})`;
}
} else if (pc.DriverUtils.isPostgresFamily(this.connection.driver) && this.connection.driver.spatialTypes.indexOf(i.type) !== -1) {
if (i.srid != null) {
n += `ST_SetSRID(ST_GeomFromGeoJSON(${e}), ${i.srid})::${i.type}`;
} else {
n += `ST_GeomFromGeoJSON(${e})::${i.type}`;
}
} else if (this.connection.driver.options.type === "mssql" && this.connection.driver.spatialTypes.indexOf(i.type) !== -1) {
n += i.type + "::STGeomFromText(" + e + ", " + (i.srid || "0") + ")";
} else {
n += e;
}
}
if (s === t.length - 1) {
if (r === e.length - 1) {
if (this.connection.driver.options.type === "oracle" && e.length > 1) {
n += " FROM DUAL ";
} else if (this.connection.driver.options.type === "sap" && e.length > 1) {
n += " FROM dummy ";
} else {
n += ")";
}
} else {
if (this.connection.driver.options.type === "oracle" && e.length > 1) {
n += " FROM DUAL UNION ALL ";
} else if (this.connection.driver.options.type === "sap" && e.length > 1) {
n += " FROM dummy UNION ALL ";
} else {
n += "), ";
}
}
} else {
n += ", ";
}
});
});
if (n === "()") return "";
return n;
} else {
let t = "";
e.forEach((n, a) => {
const r = Object.keys(n);
r.forEach((r, i) => {
if (i === 0) {
t += "(";
}
const s = n[r];
if (typeof s === "function") {
t += s();
} else if (s === undefined) {
if (this.connection.driver.options.type === "oracle" && e.length > 1 || pc.DriverUtils.isSQLiteFamily(this.connection.driver) || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
t += "NULL";
} else {
t += "DEFAULT";
}
} else if (s === null && this.connection.driver.options.type === "spanner") ; else {
t += this.createParameter(s);
}
if (i === Object.keys(n).length - 1) {
if (a === e.length - 1) {
t += ")";
} else {
t += "), ";
}
} else {
t += ", ";
}
});
});
if (t === "()") return "";
return t;
}
}
getValueSets() {
if (Array.isArray(this.expressionMap.valuesSet)) return this.expressionMap.valuesSet;
if (gc.ObjectUtils.isObject(this.expressionMap.valuesSet)) return [ this.expressionMap.valuesSet ];
throw new fc.InsertValuesMissingError;
}
isOverridingAutoIncrementBehavior(e) {
return e.isPrimary && e.isGenerated && e.generationStrategy === "increment" && this.getValueSets().some(t => e.getEntityValue(t) !== undefined && e.getEntityValue(t) !== null);
}
}
hc = oo.InsertQueryBuilder = InsertQueryBuilder;
var Cc = {};
var Rc = {};
Object.defineProperty(Rc, "__esModule", {
value: true
});
Rc.RelationUpdater = void 0;
const Sc = P;
const wc = I;
class RelationUpdater {
constructor(e, t) {
this.queryBuilder = e;
this.expressionMap = t;
}
async update(e) {
const t = this.expressionMap.relationMetadata;
if (t.isManyToOne || t.isOneToOneOwner) {
const n = t.joinColumns.reduce((t, n) => {
const a = wc.ObjectUtils.isObject(e) ? n.referencedColumn.getEntityValue(e) : e;
n.setEntityValue(t, a);
return t;
}, {});
if (!this.expressionMap.of || Array.isArray(this.expressionMap.of) && !this.expressionMap.of.length) return;
await this.queryBuilder.createQueryBuilder().update(t.entityMetadata.target).set(n).whereInIds(this.expressionMap.of).execute();
} else if ((t.isOneToOneNotOwner || t.isOneToMany) && e === null) {
const e = {};
t.inverseRelation.joinColumns.forEach(t => {
e[t.propertyName] = null;
});
const n = Array.isArray(this.expressionMap.of) ? this.expressionMap.of : [ this.expressionMap.of ];
const a = {};
const r = [];
n.forEach((e, n) => {
t.inverseRelation.joinColumns.map((t, i) => {
const s = "joinColumn_" + n + "_" + i;
a[s] = wc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
r.push(`${t.propertyPath} = :${s}`);
});
});
const i = r.map(e => "(" + e + ")").join(" OR ");
if (!i) return;
await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(e).where(i).setParameters(a).execute();
} else if (t.isOneToOneNotOwner || t.isOneToMany) {
if (Array.isArray(this.expressionMap.of)) throw new Sc.TypeORMError(`You cannot update relations of multiple entities with the same related object. Provide a single entity into .of method.`);
const n = this.expressionMap.of;
const a = t.inverseRelation.joinColumns.reduce((e, t) => {
const a = wc.ObjectUtils.isObject(n) ? t.referencedColumn.getEntityValue(n) : n;
t.setEntityValue(e, a);
return e;
}, {});
if (!e || Array.isArray(e) && !e.length) return;
await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(a).whereInIds(e).execute();
} else {
const n = t.junctionEntityMetadata;
const a = Array.isArray(this.expressionMap.of) ? this.expressionMap.of : [ this.expressionMap.of ];
const r = Array.isArray(e) ? e : [ e ];
const i = t.isManyToManyOwner ? a : r;
const s = t.isManyToManyOwner ? r : a;
const o = [];
i.forEach(e => {
s.forEach(t => {
const a = {};
n.ownerColumns.forEach(t => {
a[t.databaseName] = wc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
});
n.inverseColumns.forEach(e => {
a[e.databaseName] = wc.ObjectUtils.isObject(t) ? e.referencedColumn.getEntityValue(t) : t;
});
o.push(a);
});
});
if (!o.length) return;
if (this.queryBuilder.connection.driver.options.type === "oracle" || this.queryBuilder.connection.driver.options.type === "sap") {
await Promise.all(o.map(e => this.queryBuilder.createQueryBuilder().insert().into(n.tableName).values(e).execute()));
} else {
await this.queryBuilder.createQueryBuilder().insert().into(n.tableName).values(o).execute();
}
}
}
}
Rc.RelationUpdater = RelationUpdater;
var Mc = {};
Object.defineProperty(Mc, "__esModule", {
value: true
});
Mc.RelationRemover = void 0;
const Oc = I;
class RelationRemover {
constructor(e, t) {
this.queryBuilder = e;
this.expressionMap = t;
}
async remove(e) {
const t = this.expressionMap.relationMetadata;
if (t.isOneToMany) {
const n = Array.isArray(this.expressionMap.of) ? this.expressionMap.of : [ this.expressionMap.of ];
const a = Array.isArray(e) ? e : [ e ];
const r = {};
t.inverseRelation.joinColumns.forEach(e => {
r[e.propertyName] = null;
});
const i = {};
const s = [];
n.forEach((e, n) => {
s.push(...a.map((a, r) => [ ...t.inverseRelation.joinColumns.map((t, a) => {
const s = "joinColumn_" + n + "_" + r + "_" + a;
i[s] = Oc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
return `${t.propertyPath} = :${s}`;
}), ...t.inverseRelation.entityMetadata.primaryColumns.map((e, t) => {
const n = "primaryColumn_" + r + "_" + r + "_" + t;
i[n] = Oc.ObjectUtils.isObject(a) ? e.getEntityValue(a) : a;
return `${e.propertyPath} = :${n}`;
}) ].join(" AND ")));
});
const o = s.map(e => "(" + e + ")").join(" OR ");
if (!o) return;
await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(r).where(o).setParameters(i).execute();
} else {
const n = t.junctionEntityMetadata;
const a = Array.isArray(this.expressionMap.of) ? this.expressionMap.of : [ this.expressionMap.of ];
const r = Array.isArray(e) ? e : [ e ];
const i = t.isManyToManyOwner ? a : r;
const s = t.isManyToManyOwner ? r : a;
const o = {};
const c = [];
i.forEach((e, t) => {
c.push(...s.map((a, r) => [ ...n.ownerColumns.map((n, a) => {
const i = "firstValue_" + t + "_" + r + "_" + a;
o[i] = Oc.ObjectUtils.isObject(e) ? n.referencedColumn.getEntityValue(e) : e;
return `${n.databaseName} = :${i}`;
}), ...n.inverseColumns.map((e, n) => {
const i = "secondValue_" + t + "_" + r + "_" + n;
o[i] = Oc.ObjectUtils.isObject(a) ? e.referencedColumn.getEntityValue(a) : a;
return `${e.databaseName} = :${i}`;
}) ].join(" AND ")));
});
const l = c.map(e => "(" + e + ")").join(" OR ");
await this.queryBuilder.createQueryBuilder().delete().from(n.tableName).where(l).setParameters(o).execute();
}
}
}
Mc.RelationRemover = RelationRemover;
Object.defineProperty(Cc, "__esModule", {
value: true
});
var vc = Cc.RelationQueryBuilder = void 0;
const Ic = M;
const Pc = Rc;
const Lc = Mc;
const Dc = P;
const _c = I;
class RelationQueryBuilder extends Ic.QueryBuilder {
constructor() {
super(...arguments);
this["@instanceof"] = Symbol.for("RelationQueryBuilder");
}
getQuery() {
return "";
}
of(e) {
this.expressionMap.of = e;
return this;
}
async set(e) {
const t = this.expressionMap.relationMetadata;
if (!this.expressionMap.of) throw new Dc.TypeORMError(`Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.`);
if (t.isManyToMany || t.isOneToMany) throw new Dc.TypeORMError(`Set operation is only supported for many-to-one and one-to-one relations. ` + `However given "${t.propertyPath}" has ${t.relationType} relation. ` + `Use .add() method instead.`);
if (t.joinColumns && t.joinColumns.length > 1 && (!_c.ObjectUtils.isObject(e) || Object.keys(e).length < t.joinColumns.length)) throw new Dc.TypeORMError(`Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })`);
const n = new Pc.RelationUpdater(this, this.expressionMap);
return n.update(e);
}
async add(e) {
if (Array.isArray(e) && e.length === 0) return;
const t = this.expressionMap.relationMetadata;
if (!this.expressionMap.of) throw new Dc.TypeORMError(`Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.`);
if (t.isManyToOne || t.isOneToOne) throw new Dc.TypeORMError(`Add operation is only supported for many-to-many and one-to-many relations. ` + `However given "${t.propertyPath}" has ${t.relationType} relation. ` + `Use .set() method instead.`);
if (t.joinColumns && t.joinColumns.length > 1 && (!_c.ObjectUtils.isObject(e) || Object.keys(e).length < t.joinColumns.length)) throw new Dc.TypeORMError(`Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })`);
const n = new Pc.RelationUpdater(this, this.expressionMap);
return n.update(e);
}
async remove(e) {
if (Array.isArray(e) && e.length === 0) return;
const t = this.expressionMap.relationMetadata;
if (!this.expressionMap.of) throw new Dc.TypeORMError(`Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.`);
if (t.isManyToOne || t.isOneToOne) throw new Dc.TypeORMError(`Add operation is only supported for many-to-many and one-to-many relations. ` + `However given "${t.propertyPath}" has ${t.relationType} relation. ` + `Use .set(null) method instead.`);
const n = new Lc.RelationRemover(this, this.expressionMap);
return n.remove(e);
}
async addAndRemove(e, t) {
await this.remove(t);
await this.add(e);
}
async loadOne() {
return this.loadMany().then(e => e[0]);
}
async loadMany() {
let e = this.expressionMap.of;
if (!_c.ObjectUtils.isObject(e)) {
const t = this.expressionMap.mainAlias.metadata;
if (t.hasMultiplePrimaryKeys) throw new Dc.TypeORMError(`Cannot load entity because only one primary key was specified, however entity contains multiple primary keys`);
e = t.primaryColumns[0].createValueMap(e);
}
return this.connection.relationLoader.load(this.expressionMap.relationMetadata, e, this.queryRunner);
}
}
vc = Cc.RelationQueryBuilder = RelationQueryBuilder;
var $c = {};
var xc = {};
var qc = {};
Object.defineProperty(qc, "__esModule", {
value: true
});
qc.OrmUtils = void 0;
class OrmUtils {
static chunk(e, t) {
return Array.from(Array(Math.ceil(e.length / t)), (n, a) => e.slice(a * t, a * t + t));
}
static splitClassesAndStrings(e) {
return [ e.filter(e => typeof e !== "string"), e.filter(e => typeof e === "string") ];
}
static groupBy(e, t) {
return e.reduce((e, n) => {
const a = t(n);
let r = e.find(e => e.id === a);
if (!r) {
r = {
id: a,
items: []
};
e.push(r);
}
r.items.push(n);
return e;
}, []);
}
static uniq(e, t) {
return e.reduce((e, n) => {
let a = false;
if (typeof t === "function") {
const r = t(n);
a = !!e.find(e => t(e) === r);
} else if (typeof t === "string") {
a = !!e.find(e => e[t] === n[t]);
} else {
a = e.indexOf(n) !== -1;
}
if (!a) e.push(n);
return e;
}, []);
}
static mergeDeep(e, ...t) {
if (!t.length) {
return e;
}
for (const n of t) {
OrmUtils.merge(e, n);
}
return e;
}
static deepCompare(...e) {
let t, n, a, r;
if (arguments.length < 1) {
return true;
}
for (t = 1, n = arguments.length; t < n; t++) {
a = [];
r = [];
if (!this.compare2Objects(a, r, arguments[0], arguments[t])) {
return false;
}
}
return true;
}
static deepValue(e, t) {
const n = t.split(".");
for (let t = 0, a = n.length; t < a; t++) {
e = e[n[t]];
}
return e;
}
static replaceEmptyObjectsWithBooleans(e) {
for (const t in e) {
if (e[t] && typeof e[t] === "object") {
if (Object.keys(e[t]).length === 0) {
e[t] = true;
} else {
this.replaceEmptyObjectsWithBooleans(e[t]);
}
}
}
}
static propertyPathsToTruthyObject(e) {
const t = {};
for (const n of e) {
const e = n.split(".");
if (!e.length) continue;
if (!t[e[0]] || t[e[0]] === true) {
t[e[0]] = {};
}
let a = t[e[0]];
for (const [t, n] of e.entries()) {
if (t === 0) continue;
if (a[n]) {
a = a[n];
} else if (t === e.length - 1) {
a[n] = {};
a = null;
} else {
a[n] = {};
a = a[n];
}
}
}
this.replaceEmptyObjectsWithBooleans(t);
return t;
}
static compareIds(e, t) {
if (e === undefined || e === null || t === undefined || t === null) return false;
if ((typeof e.id === "string" && typeof t.id === "string" || typeof e.id === "number" && typeof t.id === "number") && Object.keys(e).length === 1 && Object.keys(t).length === 1) {
return e.id === t.id;
}
return OrmUtils.deepCompare(e, t);
}
static toBoolean(e) {
if (typeof e === "boolean") return e;
if (typeof e === "string") return e === "true" || e === "1";
if (typeof e === "number") return e > 0;
return false;
}
static zipObject(e, t) {
return e.reduce((e, n, a) => {
e[n] = t[a];
return e;
}, {});
}
static isArraysEqual(e, t) {
if (e.length !== t.length) return false;
return e.every(e => t.indexOf(e) !== -1);
}
static areMutuallyExclusive(...e) {
const t = e.some(t => {
const n = e.filter(e => e !== t);
return t.some(e => n.some(t => t.includes(e)));
});
return !t;
}
static parseSqlCheckExpression(e, t) {
const n = e.match(new RegExp(`"${t}" varchar CHECK\\s*\\(\\s*"${t}"\\s+IN\\s*`));
if (n && n.index) {
const t = e.substring(n.index + n[0].length);
const a = t;
let r = "";
let i = "";
const s = [];
for (let e = 0; e < a.length; e++) {
const t = a[e];
switch (t) {
case ",":
if (r == "") {
s.push(i);
i = "";
} else {
i += t;
}
break;
case "'":
if (r == t) {
const n = a[e + 1] === t;
if (n) {
i += t;
e += 1;
} else {
r = "";
}
} else {
r = t;
}
break;
case ")":
if (r == "") {
s.push(i);
return s;
} else {
i += t;
}
break;
default:
if (r != "") {
i += t;
}
}
}
}
return undefined;
}
static isCriteriaNullOrEmpty(e) {
return e === undefined || e === null || e === "" || Array.isArray(e) && e.length === 0 || this.isPlainObject(e) && Object.keys(e).length === 0;
}
static isSinglePrimitiveCriteria(e) {
return typeof e === "string" || typeof e === "number" || e instanceof Date;
}
static isPrimitiveCriteria(e) {
if (Array.isArray(e)) {
return e.every(e => this.isSinglePrimitiveCriteria(e));
}
return this.isSinglePrimitiveCriteria(e);
}
static compare2Objects(e, t, n, a) {
let r;
if (Number.isNaN(n) && Number.isNaN(a)) return true;
if (n === a) return true;
if (n === null || a === null || n === undefined || a === undefined) return false;
if ((typeof n.equals === "function" || typeof n.equals === "function") && n.equals(a)) return true;
if (typeof n === "function" && typeof a === "function" || n instanceof Date && a instanceof Date || n instanceof RegExp && a instanceof RegExp || typeof n === "string" && typeof a === "string" || typeof n === "number" && typeof a === "number") return n.toString() === a.toString();
if (!(typeof n === "object" && typeof a === "object")) return false;
if (Object.prototype.isPrototypeOf.call(n, a) || Object.prototype.isPrototypeOf.call(a, n)) return false;
if (n.constructor !== a.constructor) return false;
if (n.prototype !== a.prototype) return false;
if (e.indexOf(n) > -1 || t.indexOf(a) > -1) return false;
for (r in a) {
if (a.hasOwnProperty(r) !== n.hasOwnProperty(r)) {
return false;
} else if (typeof a[r] !== typeof n[r]) {
return false;
}
}
for (r in n) {
if (a.hasOwnProperty(r) !== n.hasOwnProperty(r)) {
return false;
} else if (typeof a[r] !== typeof n[r]) {
return false;
}
switch (typeof n[r]) {
case "object":
case "function":
e.push(n);
t.push(a);
if (!this.compare2Objects(e, t, n[r], a[r])) {
return false;
}
e.pop();
t.pop();
break;
default:
if (n[r] !== a[r]) {
return false;
}
break;
}
}
return true;
}
static isPlainObject(e) {
if (e === null || e === undefined) {
return false;
}
return !e.constructor || e.constructor === Object;
}
static mergeArrayKey(e, t, n, a) {
if (a.has(n)) {
e[t] = a.get(n);
return;
}
if (n instanceof Promise) {
return;
}
if (!this.isPlainObject(n) && !Array.isArray(n)) {
e[t] = n;
return;
}
if (!e[t]) {
e[t] = Array.isArray(n) ? [] : {};
}
a.set(n, e[t]);
this.merge(e[t], n, a);
a.delete(n);
}
static mergeObjectKey(e, t, n, a) {
if (a.has(n)) {
Object.assign(e, {
[t]: a.get(n)
});
return;
}
if (n instanceof Promise) {
return;
}
if (!this.isPlainObject(n) && !Array.isArray(n)) {
Object.assign(e, {
[t]: n
});
return;
}
if (!e[t]) {
Object.assign(e, {
[t]: Array.isArray(n) ? [] : {}
});
}
a.set(n, e[t]);
this.merge(e[t], n, a);
a.delete(n);
}
static merge(e, t, n = new Map) {
if (this.isPlainObject(e) && this.isPlainObject(t)) {
for (const a of Object.keys(t)) {
if (a === "__proto__") continue;
this.mergeObjectKey(e, a, t[a], n);
}
}
if (Array.isArray(e) && Array.isArray(t)) {
for (let a = 0; a < t.length; a++) {
this.mergeArrayKey(e, a, t[a], n);
}
}
}
}
qc.OrmUtils = OrmUtils;
Object.defineProperty(xc, "__esModule", {
value: true
});
xc.RawSqlResultsToEntityTransformer = void 0;
const Uc = qc;
const Bc = jn;
const Fc = I;
class RawSqlResultsToEntityTransformer {
constructor(e, t, n, a, r) {
this.expressionMap = e;
this.driver = t;
this.rawRelationIdResults = n;
this.rawRelationCountResults = a;
this.queryRunner = r;
this.pojo = this.expressionMap.options.includes("create-pojo");
this.selections = new Set(this.expressionMap.selects.map(e => e.selection));
this.aliasCache = new Map;
this.columnsCache = new Map;
}
transform(e, t) {
const n = this.group(e, t);
const a = [];
for (const e of n.values()) {
const n = this.transformRawResultsGroup(e, t);
if (n !== undefined) a.push(n);
}
return a;
}
buildAlias(e, t) {
let n = this.aliasCache.get(e);
if (!n) {
n = new Map;
this.aliasCache.set(e, n);
}
let a = n.get(t);
if (!a) {
a = Bc.DriverUtils.buildAlias(this.driver, undefined, e, t);
n.set(t, a);
}
return a;
}
group(e, t) {
const n = new Map;
const a = [];
if (t.metadata.tableType === "view") {
a.push(...t.metadata.columns.map(e => this.buildAlias(t.name, e.databaseName)));
} else {
a.push(...t.metadata.primaryColumns.map(e => this.buildAlias(t.name, e.databaseName)));
}
for (const t of e) {
const e = a.map(e => {
const n = t[e];
if (Buffer.isBuffer(n)) {
return n.toString("hex");
}
if (Fc.ObjectUtils.isObject(n)) {
return JSON.stringify(n);
}
return n;
}).join("_");
const r = n.get(e);
if (!r) {
n.set(e, [ t ]);
} else {
r.push(t);
}
}
return n;
}
transformRawResultsGroup(e, t) {
let n = t.metadata;
if (n.discriminatorColumn) {
const a = e.map(e => e[this.buildAlias(t.name, t.metadata.discriminatorColumn.databaseName)]);
const r = n.childEntityMetadatas.find(e => typeof a.find(t => t === e.discriminatorValue) !== "undefined");
if (r) n = r;
}
const a = n.create(this.queryRunner, {
fromDeserializer: true,
pojo: this.pojo
});
const r = this.transformColumns(e, t, a, n);
const i = this.transformJoins(e, a, t, n);
const s = this.transformRelationIds(e, t, a, n);
const o = this.transformRelationCounts(e, t, a);
if (r) return a;
const c = n.primaryColumns.every(e => e.isVirtual === true);
if (c && (i || s || o)) return a;
return undefined;
}
transformColumns(e, t, n, a) {
let r = false;
const i = e[0];
for (const [e, s] of this.getColumnsToProcess(t.name, a)) {
const t = i[e];
if (t === undefined) continue; else if (t !== null && !s.isVirtualProperty) r = true;
s.setEntityValue(n, this.driver.prepareHydratedValue(t, s));
}
return r;
}
transformJoins(e, t, n, a) {
let r = false;
for (const i of this.expressionMap.joinAttributes) {
if (!i.metadata) continue;
if (!i.isSelected) continue;
if (i.relation && !a.relations.find(e => e === i.relation)) continue;
if (i.mapToProperty) {
if (i.mapToPropertyParentAlias !== n.name) continue;
} else {
if (!i.relation || i.parentAlias !== n.name || i.relationPropertyPath !== i.relation.propertyPath) continue;
}
let s = this.transform(e, i.alias);
s = !i.isMany ? s[0] : s;
s = !i.isMany && s === undefined ? null : s;
if (s === undefined) continue;
if (i.mapToPropertyPropertyName) {
t[i.mapToPropertyPropertyName] = s;
} else {
i.relation.setEntityValue(t, s);
}
r = true;
}
return r;
}
transformRelationIds(e, t, n, a) {
let r = false;
for (const [a, i] of this.rawRelationIdResults.entries()) {
if (i.relationIdAttribute.parentAlias !== t.name) continue;
const s = i.relationIdAttribute.relation;
const o = this.createValueMapFromJoinColumns(s, i.relationIdAttribute.parentAlias, e);
if (o === undefined || o === null) {
continue;
}
this.prepareDataForTransformRelationIds();
const c = this.hashEntityIds(s, o);
const l = this.relationIdMaps[a][c] || [];
const u = i.relationIdAttribute.mapToPropertyPropertyPath.split(".");
const h = (e, t, n) => {
const a = e.shift();
if (a && e.length === 0) {
t[a] = n;
return t;
}
if (a && e.length > 0) {
h(e, t[a], n);
} else {
return t;
}
};
if (s.isOneToOne || s.isManyToOne) {
if (l[0] !== undefined) {
h(u, n, l[0]);
r = true;
}
} else {
h(u, n, l);
r = r || l.length > 0;
}
}
return r;
}
transformRelationCounts(e, t, n) {
let a = false;
for (const r of this.rawRelationCountResults) {
if (r.relationCountAttribute.parentAlias !== t.name) continue;
const i = r.relationCountAttribute.relation;
let s;
if (i.isOneToMany) {
s = i.inverseRelation.joinColumns[0].referencedColumn.databaseName;
} else {
s = i.isOwning ? i.joinColumns[0].referencedColumn.databaseName : i.inverseRelation.joinColumns[0].referencedColumn.databaseName;
}
const o = e[0][this.buildAlias(t.name, s)];
if (o !== undefined && o !== null) {
n[r.relationCountAttribute.mapToPropertyPropertyName] = 0;
for (const e of r.results) {
if (e["parentId"] !== o) continue;
n[r.relationCountAttribute.mapToPropertyPropertyName] = parseInt(e["cnt"]);
a = true;
}
}
}
return a;
}
getColumnsToProcess(e, t) {
let n = this.columnsCache.get(e);
if (!n) {
n = new Map;
this.columnsCache.set(e, n);
}
let a = n.get(t);
if (!a) {
a = t.columns.filter(n => !n.isVirtual && (this.selections.has(e) || this.selections.has(`${e}.${n.propertyPath}`)) && !t.childEntityMetadatas.some(e => e.target === n.target)).map(t => [ this.buildAlias(e, t.databaseName), t ]);
n.set(t, a);
}
return a;
}
createValueMapFromJoinColumns(e, t, n) {
let a;
if (e.isManyToOne || e.isOneToOneOwner) {
a = e.entityMetadata.primaryColumns.map(e => e);
} else if (e.isOneToMany || e.isOneToOneNotOwner) {
a = e.inverseRelation.joinColumns.map(e => e);
} else {
if (e.isOwning) {
a = e.joinColumns.map(e => e);
} else {
a = e.inverseRelation.inverseJoinColumns.map(e => e);
}
}
return a.reduce((a, r) => {
for (const i of n) {
if (e.isManyToOne || e.isOneToOneOwner) {
a[r.databaseName] = this.driver.prepareHydratedValue(i[this.buildAlias(t, r.databaseName)], r);
} else {
a[r.databaseName] = this.driver.prepareHydratedValue(i[this.buildAlias(t, r.referencedColumn.databaseName)], r.referencedColumn);
}
}
return a;
}, {});
}
extractEntityPrimaryIds(e, t) {
let n;
if (e.isManyToOne || e.isOneToOneOwner) {
n = e.entityMetadata.primaryColumns.map(e => e);
} else if (e.isOneToMany || e.isOneToOneNotOwner) {
n = e.inverseRelation.joinColumns.map(e => e);
} else {
if (e.isOwning) {
n = e.joinColumns.map(e => e);
} else {
n = e.inverseRelation.inverseJoinColumns.map(e => e);
}
}
return n.reduce((e, n) => {
e[n.databaseName] = t[n.databaseName];
return e;
}, {});
}
prepareDataForTransformRelationIds() {
if (this.relationIdMaps) {
return;
}
this.relationIdMaps = this.rawRelationIdResults.map(e => {
const t = e.relationIdAttribute.relation;
let n;
if (t.isManyToOne || t.isOneToOneOwner) {
n = t.joinColumns;
} else if (t.isOneToMany || t.isOneToOneNotOwner) {
n = t.inverseEntityMetadata.primaryColumns;
} else {
if (t.isOwning) {
n = t.inverseJoinColumns;
} else {
n = t.inverseRelation.joinColumns;
}
}
return e.results.reduce((a, r) => {
let i = n.reduce((e, n) => {
let a = r[n.databaseName];
if (t.isOneToMany || t.isOneToOneNotOwner) {
if (n.isVirtual && n.referencedColumn && n.referencedColumn.propertyName !== n.propertyName) {
a = n.referencedColumn.createValueMap(a);
}
return Uc.OrmUtils.mergeDeep(e, n.createValueMap(a));
}
if (!n.isPrimary && n.referencedColumn.referencedColumn) {
a = n.referencedColumn.referencedColumn.createValueMap(a);
}
return Uc.OrmUtils.mergeDeep(e, n.referencedColumn.createValueMap(a));
}, {});
if (n.length === 1 && !e.relationIdAttribute.disableMixedMap) {
if (t.isOneToMany || t.isOneToOneNotOwner) {
i = n[0].getEntityValue(i);
} else {
i = n[0].referencedColumn.getEntityValue(i);
}
}
if (i !== undefined) {
const e = this.hashEntityIds(t, r);
if (a[e]) {
a[e].push(i);
} else {
a[e] = [ i ];
}
}
return a;
}, {});
});
}
hashEntityIds(e, t) {
const n = this.extractEntityPrimaryIds(e, t);
return JSON.stringify(n);
}
}
xc.RawSqlResultsToEntityTransformer = RawSqlResultsToEntityTransformer;
var jc = {};
Object.defineProperty(jc, "__esModule", {
value: true
});
jc.RelationIdLoader = void 0;
const kc = jn;
const Qc = D;
const Vc = qc;
let Kc = class RelationIdLoader {
constructor(e, t, n) {
this.connection = e;
this.queryRunner = t;
this.relationIdAttributes = n;
}
async load(e) {
const t = this.relationIdAttributes.map(async t => {
if (t.relation.isManyToOne || t.relation.isOneToOneOwner) {
if (t.queryBuilderFactory) throw new Qc.TypeORMError("Additional condition can not be used with ManyToOne or OneToOne owner relations.");
const n = {};
const a = e.map(e => {
const a = {};
const r = [];
t.relation.joinColumns.forEach(n => {
a[n.databaseName] = this.connection.driver.prepareHydratedValue(e[kc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, n.databaseName)], n.referencedColumn);
const i = `${n.databaseName}:${a[n.databaseName]}`;
if (r.indexOf(i) === -1) {
r.push(i);
}
});
t.relation.entityMetadata.primaryColumns.forEach(n => {
a[n.databaseName] = this.connection.driver.prepareHydratedValue(e[kc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, n.databaseName)], n);
const i = `${n.databaseName}:${a[n.databaseName]}`;
if (r.indexOf(i) === -1) {
r.push(i);
}
});
r.sort();
const i = r.join("::");
if (n[i]) {
return null;
}
n[i] = true;
return a;
}).filter(e => e);
return {
relationIdAttribute: t,
results: a
};
} else if (t.relation.isOneToMany || t.relation.isOneToOneNotOwner) {
const n = t.relation;
const a = n.isOwning ? n.joinColumns : n.inverseRelation.joinColumns;
const r = n.inverseEntityMetadata.target;
const i = n.inverseEntityMetadata.tableName;
const s = t.alias || i;
const o = {};
const c = {};
const l = e.map((e, n) => {
const r = [];
const i = {};
const l = a.map(a => {
const o = a.databaseName + n;
const c = e[kc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, a.referencedColumn.databaseName)];
const l = `${s}:${a.propertyPath}:${c}`;
if (r.indexOf(l) !== -1) {
return "";
}
r.push(l);
i[o] = c;
return s + "." + a.propertyPath + " = :" + o;
}).filter(e => e).join(" AND ");
r.sort();
const u = r.join("::");
if (o[u]) {
return "";
}
o[u] = true;
Object.assign(c, i);
return l;
}).filter(e => e).map(e => "(" + e + ")").join(" OR ");
if (!l) return {
relationIdAttribute: t,
results: []
};
const u = this.connection.createQueryBuilder(this.queryRunner);
const h = Vc.OrmUtils.uniq([ ...a, ...n.inverseRelation.entityMetadata.primaryColumns ], e => e.propertyPath);
h.forEach(e => {
u.addSelect(s + "." + e.propertyPath, e.databaseName);
});
u.from(r, s).where("(" + l + ")").setParameters(c);
if (t.queryBuilderFactory) t.queryBuilderFactory(u);
const d = await u.getRawMany();
d.forEach(e => {
a.forEach(t => {
e[t.databaseName] = this.connection.driver.prepareHydratedValue(e[t.databaseName], t.referencedColumn);
});
n.inverseRelation.entityMetadata.primaryColumns.forEach(t => {
e[t.databaseName] = this.connection.driver.prepareHydratedValue(e[t.databaseName], t);
});
});
return {
relationIdAttribute: t,
results: d
};
} else {
const n = t.relation;
const a = n.isOwning ? n.joinColumns : n.inverseRelation.inverseJoinColumns;
const r = n.isOwning ? n.inverseJoinColumns : n.inverseRelation.joinColumns;
const i = t.junctionAlias;
const s = t.joinInverseSideMetadata.tableName;
const o = t.alias || s;
const c = n.isOwning ? n.junctionEntityMetadata.tableName : n.inverseRelation.junctionEntityMetadata.tableName;
const l = e.map(e => a.reduce((n, a) => {
n[a.propertyPath] = e[kc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, a.referencedColumn.databaseName)];
return n;
}, {}));
if (l.length === 0) return {
relationIdAttribute: t,
results: []
};
const u = {};
const h = {};
const d = l.map((e, t) => {
const n = [];
const a = {};
const r = Object.keys(e).map(r => {
const s = r + t;
const o = e[r];
const c = `${i}:${r}:${o}`;
if (n.indexOf(c) !== -1) {
return "";
}
n.push(c);
a[s] = o;
return i + "." + r + " = :" + s;
}).filter(e => e).join(" AND ");
n.sort();
const s = n.join("::");
if (h[s]) {
return "";
}
h[s] = true;
Object.assign(u, a);
return r;
}).filter(e => e);
const p = r.map(e => i + "." + e.propertyPath + " = " + o + "." + e.referencedColumn.propertyPath).join(" AND ");
const m = d.map(e => "(" + e + " AND " + p + ")").join(" OR ");
const f = this.connection.createQueryBuilder(this.queryRunner);
r.forEach(e => {
f.addSelect(i + "." + e.propertyPath, e.databaseName).addOrderBy(i + "." + e.propertyPath);
});
a.forEach(e => {
f.addSelect(i + "." + e.propertyPath, e.databaseName).addOrderBy(i + "." + e.propertyPath);
});
f.from(s, o).innerJoin(c, i, m).setParameters(u);
if (t.queryBuilderFactory) t.queryBuilderFactory(f);
const y = await f.getRawMany();
y.forEach(e => {
[ ...a, ...r ].forEach(t => {
e[t.databaseName] = this.connection.driver.prepareHydratedValue(e[t.databaseName], t.referencedColumn);
});
});
return {
relationIdAttribute: t,
results: y
};
}
});
return Promise.all(t);
}
};
jc.RelationIdLoader = Kc;
var Wc = {};
Object.defineProperty(Wc, "__esModule", {
value: true
});
Wc.RelationIdLoader = void 0;
const Hc = jn;
class RelationIdLoader {
constructor(e, t) {
this.connection = e;
this.queryRunner = t;
}
load(e, t, n) {
const a = Array.isArray(t) ? t : [ t ];
const r = Array.isArray(n) ? n : n ? [ n ] : undefined;
if (e.isManyToMany) {
return this.loadForManyToMany(e, a, r);
} else if (e.isManyToOne || e.isOneToOneOwner) {
return this.loadForManyToOneAndOneToOneOwner(e, a, r);
} else {
return this.loadForOneToManyAndOneToOneNotOwner(e, a, r);
}
}
async loadManyToManyRelationIdsAndGroup(e, t, n, a) {
const r = e.isManyToMany || e.isOneToMany;
const i = Array.isArray(t) ? t : [ t ];
if (!n) {
n = await this.connection.relationLoader.load(e, t, this.queryRunner, a);
if (!n.length) return i.map(e => ({
entity: e,
related: r ? [] : undefined
}));
}
const s = await this.load(e, t, n);
const o = Array.isArray(n) ? n : [ n ];
let c = [], l = [];
if (e.isManyToManyOwner) {
c = e.junctionEntityMetadata.inverseColumns.map(e => e.referencedColumn);
l = e.junctionEntityMetadata.ownerColumns.map(e => e.referencedColumn);
} else if (e.isManyToManyNotOwner) {
c = e.junctionEntityMetadata.ownerColumns.map(e => e.referencedColumn);
l = e.junctionEntityMetadata.inverseColumns.map(e => e.referencedColumn);
} else if (e.isManyToOne || e.isOneToOneOwner) {
c = e.joinColumns.map(e => e.referencedColumn);
l = e.entityMetadata.primaryColumns;
} else if (e.isOneToMany || e.isOneToOneNotOwner) {
c = e.inverseRelation.entityMetadata.primaryColumns;
l = e.inverseRelation.joinColumns.map(e => e.referencedColumn);
} else ;
return i.map(t => {
const n = {
entity: t,
related: r ? [] : undefined
};
const a = s.filter(e => l.every(n => n.compareEntityValue(t, e[n.entityMetadata.name + "_" + n.propertyAliasName])));
if (!a.length) return n;
o.forEach(t => {
a.forEach(a => {
const i = c.every(n => n.compareEntityValue(t, a[Hc.DriverUtils.buildAlias(this.connection.driver, undefined, n.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + n.propertyPath.replace(".", "_"))]));
if (i) {
if (r) {
n.related.push(t);
} else {
n.related = t;
}
}
});
});
return n;
});
}
loadForManyToMany(e, t, n) {
const a = e.junctionEntityMetadata;
const r = a.name;
const i = e.isOwning ? a.ownerColumns : a.inverseColumns;
const s = e.isOwning ? a.inverseColumns : a.ownerColumns;
const o = this.connection.createQueryBuilder(this.queryRunner);
i.forEach(e => {
const t = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_"));
o.addSelect(r + "." + e.propertyPath, t);
});
s.forEach(t => {
const n = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, t.referencedColumn.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + t.referencedColumn.propertyPath.replace(".", "_"));
o.addSelect(r + "." + t.propertyPath, n);
});
let c = "";
if (i.length === 1) {
const e = t.map(e => i[0].referencedColumn.getEntityValue(e));
const n = e.every(e => typeof e === "number");
if (n) {
c = `${r}.${i[0].propertyPath} IN (${e.join(", ")})`;
} else {
o.setParameter("values1", e);
c = r + "." + i[0].propertyPath + " IN (:...values1)";
}
} else {
c = "(" + t.map((e, t) => i.map(n => {
const a = "entity1_" + t + "_" + n.propertyName;
o.setParameter(a, n.referencedColumn.getEntityValue(e));
return r + "." + n.propertyPath + " = :" + a;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ") + ")";
}
let l = "";
if (n) {
if (s.length === 1) {
const e = n.map(e => s[0].referencedColumn.getEntityValue(e));
const t = e.every(e => typeof e === "number");
if (t) {
l = `${r}.${s[0].propertyPath} IN (${e.join(", ")})`;
} else {
o.setParameter("values2", e);
l = r + "." + s[0].propertyPath + " IN (:...values2)";
}
} else {
l = "(" + n.map((e, t) => s.map(n => {
const a = "entity2_" + t + "_" + n.propertyName;
o.setParameter(a, n.referencedColumn.getEntityValue(e));
return r + "." + n.propertyPath + " = :" + a;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ") + ")";
}
}
const u = [ c, l ].filter(e => e.length > 0).join(" AND ");
return o.from(a.target, r).where(u).getRawMany();
}
loadForManyToOneAndOneToOneOwner(e, t, n) {
const a = e.entityMetadata.targetName;
const r = e.joinColumns.every(t => !!e.entityMetadata.nonVirtualColumns.find(e => e === t));
if (n && r) {
const a = [];
t.forEach(t => {
const r = {};
e.entityMetadata.primaryColumns.forEach(e => {
const n = e.entityMetadata.name + "_" + e.propertyPath.replace(".", "_");
r[n] = e.getEntityValue(t);
});
n.forEach(n => {
e.joinColumns.forEach(a => {
const i = a.getEntityValue(t);
const s = a.referencedColumn.getEntityValue(n);
if (i === undefined || s === undefined) return;
if (i === s) {
const t = a.referencedColumn.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + a.referencedColumn.propertyPath.replace(".", "_");
r[t] = s;
}
});
});
if (Object.keys(r).length === e.entityMetadata.primaryColumns.length + e.joinColumns.length) {
a.push(r);
}
});
if (a.length === t.length) return Promise.resolve(a);
}
const i = this.connection.createQueryBuilder(this.queryRunner);
e.entityMetadata.primaryColumns.forEach(e => {
const t = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, e.entityMetadata.name + "_" + e.propertyPath.replace(".", "_"));
i.addSelect(a + "." + e.propertyPath, t);
});
e.joinColumns.forEach(t => {
const n = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, t.referencedColumn.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + t.referencedColumn.propertyPath.replace(".", "_"));
i.addSelect(a + "." + t.propertyPath, n);
});
let s = "";
if (e.entityMetadata.primaryColumns.length === 1) {
const n = t.map(t => e.entityMetadata.primaryColumns[0].getEntityValue(t));
const r = n.every(e => typeof e === "number");
if (r) {
s = `${a}.${e.entityMetadata.primaryColumns[0].propertyPath} IN (${n.join(", ")})`;
} else {
i.setParameter("values", n);
s = a + "." + e.entityMetadata.primaryColumns[0].propertyPath + " IN (:...values)";
}
} else {
s = t.map((t, n) => e.entityMetadata.primaryColumns.map((e, r) => {
const s = "entity" + n + "_" + r;
i.setParameter(s, e.getEntityValue(t));
return a + "." + e.propertyPath + " = :" + s;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
}
return i.from(e.entityMetadata.target, a).where(s).getRawMany();
}
loadForOneToManyAndOneToOneNotOwner(e, t, n) {
const a = e;
e = e.inverseRelation;
if (e.entityMetadata.primaryColumns.length === e.joinColumns.length) {
const n = e.entityMetadata.primaryColumns.every(t => e.joinColumns.indexOf(t) !== -1);
if (n) {
return Promise.resolve(t.map(t => {
const n = {};
e.joinColumns.forEach(function(e) {
const r = e.referencedColumn.getEntityValue(t);
const i = e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_");
const s = e.entityMetadata.name + "_" + a.propertyPath.replace(".", "_") + "_" + e.propertyPath.replace(".", "_");
n[i] = r;
n[s] = r;
});
return n;
}));
}
}
const r = e.entityMetadata.targetName;
const i = this.connection.createQueryBuilder(this.queryRunner);
e.entityMetadata.primaryColumns.forEach(e => {
const t = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, e.entityMetadata.name + "_" + a.propertyPath.replace(".", "_") + "_" + e.propertyPath.replace(".", "_"));
i.addSelect(r + "." + e.propertyPath, t);
});
e.joinColumns.forEach(e => {
const t = Hc.DriverUtils.buildAlias(this.connection.driver, undefined, e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_"));
i.addSelect(r + "." + e.propertyPath, t);
});
let s = "";
if (e.joinColumns.length === 1) {
const n = t.map(t => e.joinColumns[0].referencedColumn.getEntityValue(t));
const a = n.every(e => typeof e === "number");
if (a) {
s = `${r}.${e.joinColumns[0].propertyPath} IN (${n.join(", ")})`;
} else {
i.setParameter("values", n);
s = r + "." + e.joinColumns[0].propertyPath + " IN (:...values)";
}
} else {
s = t.map((t, n) => e.joinColumns.map((e, a) => {
const s = "entity" + n + "_" + a;
i.setParameter(s, e.referencedColumn.getEntityValue(t));
return r + "." + e.propertyPath + " = :" + s;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
}
return i.from(e.entityMetadata.target, r).where(s).getRawMany();
}
}
Wc.RelationIdLoader = RelationIdLoader;
var Gc = {};
Object.defineProperty(Gc, "__esModule", {
value: true
});
Gc.RelationIdMetadataToAttributeTransformer = void 0;
const Yc = Ts;
class RelationIdMetadataToAttributeTransformer {
constructor(e) {
this.expressionMap = e;
}
transform() {
if (this.expressionMap.mainAlias) {
this.expressionMap.mainAlias.metadata.relationIds.forEach(e => {
const t = this.metadataToAttribute(this.expressionMap.mainAlias.name, e);
this.expressionMap.relationIdAttributes.push(t);
});
}
this.expressionMap.joinAttributes.forEach(e => {
if (!e.metadata || e.metadata.isJunction) return;
e.metadata.relationIds.forEach(t => {
const n = this.metadataToAttribute(e.alias.name, t);
this.expressionMap.relationIdAttributes.push(n);
});
});
}
metadataToAttribute(e, t) {
return new Yc.RelationIdAttribute(this.expressionMap, {
relationName: e + "." + t.relation.propertyName,
mapToProperty: e + "." + t.propertyName,
alias: t.alias,
queryBuilderFactory: t.queryBuilderFactory
});
}
}
Gc.RelationIdMetadataToAttributeTransformer = RelationIdMetadataToAttributeTransformer;
var zc = {};
Object.defineProperty(zc, "__esModule", {
value: true
});
zc.RelationCountLoader = void 0;
class RelationCountLoader {
constructor(e, t, n) {
this.connection = e;
this.queryRunner = t;
this.relationCountAttributes = n;
}
async load(e) {
const t = (e, t, n) => n.indexOf(e) === t;
const n = this.relationCountAttributes.map(async n => {
if (n.relation.isOneToMany) {
const a = n.relation;
const r = a.inverseRelation;
const i = r.joinColumns[0].referencedColumn.propertyName;
const s = a.inverseEntityMetadata.target;
const o = a.inverseEntityMetadata.tableName;
const c = n.alias || o;
const l = r.propertyName;
let u = e.map(e => e[n.parentAlias + "_" + i]).filter(e => !!e);
u = u.filter(t);
if (u.length === 0) return {
relationCountAttribute: n,
results: []
};
const h = this.connection.createQueryBuilder(this.queryRunner);
h.select(c + "." + l, "parentId").addSelect("COUNT(*)", "cnt").from(s, c).where(c + "." + l + " IN (:...ids)").addGroupBy(c + "." + l).setParameter("ids", u);
if (n.queryBuilderFactory) n.queryBuilderFactory(h);
return {
relationCountAttribute: n,
results: await h.getRawMany()
};
} else {
let a;
let r;
let i;
let s;
if (n.relation.isOwning) {
a = n.relation.joinColumns[0].referencedColumn.databaseName;
r = n.relation.inverseJoinColumns[0].referencedColumn.databaseName;
i = n.relation.junctionEntityMetadata.columns[0];
s = n.relation.junctionEntityMetadata.columns[1];
} else {
a = n.relation.inverseRelation.inverseJoinColumns[0].referencedColumn.databaseName;
r = n.relation.inverseRelation.joinColumns[0].referencedColumn.databaseName;
i = n.relation.junctionEntityMetadata.columns[1];
s = n.relation.junctionEntityMetadata.columns[0];
}
let o = e.map(e => e[n.parentAlias + "_" + a]).filter(e => !!e);
o = o.filter(t);
if (o.length === 0) return {
relationCountAttribute: n,
results: []
};
const c = n.junctionAlias;
const l = n.joinInverseSideMetadata.tableName;
const u = n.alias || l;
const h = n.relation.junctionEntityMetadata.tableName;
const d = c + "." + i.propertyName + " IN (" + o.map(e => isNaN(e) ? "'" + e + "'" : e) + ")" + " AND " + c + "." + s.propertyName + " = " + u + "." + r;
const p = this.connection.createQueryBuilder(this.queryRunner);
p.select(c + "." + i.propertyName, "parentId").addSelect("COUNT(" + p.escape(u) + "." + p.escape(r) + ")", "cnt").from(l, u).innerJoin(h, c, d).addGroupBy(c + "." + i.propertyName);
if (n.queryBuilderFactory) n.queryBuilderFactory(p);
return {
relationCountAttribute: n,
results: await p.getRawMany()
};
}
});
return Promise.all(n);
}
}
zc.RelationCountLoader = RelationCountLoader;
var Jc = {};
Object.defineProperty(Jc, "__esModule", {
value: true
});
Jc.RelationCountMetadataToAttributeTransformer = void 0;
const Xc = bs;
class RelationCountMetadataToAttributeTransformer {
constructor(e) {
this.expressionMap = e;
}
transform() {
if (this.expressionMap.mainAlias) {
this.expressionMap.mainAlias.metadata.relationCounts.forEach(e => {
const t = this.metadataToAttribute(this.expressionMap.mainAlias.name, e);
this.expressionMap.relationCountAttributes.push(t);
});
}
this.expressionMap.joinAttributes.forEach(e => {
if (!e.metadata || e.metadata.isJunction) return;
e.metadata.relationCounts.forEach(t => {
const n = this.metadataToAttribute(e.alias.name, t);
this.expressionMap.relationCountAttributes.push(n);
});
});
}
metadataToAttribute(e, t) {
return new Xc.RelationCountAttribute(this.expressionMap, {
relationName: e + "." + t.relation.propertyName,
mapToProperty: e + "." + t.propertyName,
alias: t.alias,
queryBuilderFactory: t.queryBuilderFactory
});
}
}
Jc.RelationCountMetadataToAttributeTransformer = RelationCountMetadataToAttributeTransformer;
var Zc = {};
Object.defineProperty(Zc, "__esModule", {
value: true
});
var el = Zc.FindOptionsUtils = void 0;
const tl = P;
const nl = jn;
const al = P;
class FindOptionsUtils {
static isFindOneOptions(e) {
const t = e;
return t && (Array.isArray(t.select) || Array.isArray(t.relations) || typeof t.select === "object" || typeof t.relations === "object" || typeof t.where === "object" || typeof t.join === "object" || typeof t.order === "object" || typeof t.cache === "object" || typeof t.cache === "boolean" || typeof t.cache === "number" || typeof t.comment === "string" || typeof t.lock === "object" || typeof t.loadRelationIds === "object" || typeof t.loadRelationIds === "boolean" || typeof t.loadEagerRelations === "boolean" || typeof t.withDeleted === "boolean" || typeof t.relationLoadStrategy === "string" || typeof t.transaction === "boolean");
}
static isFindManyOptions(e) {
const t = e;
return t && (this.isFindOneOptions(t) || typeof t.skip === "number" || typeof t.take === "number" || typeof t.skip === "string" || typeof t.take === "string");
}
static extractFindManyOptionsAlias(e) {
if (this.isFindManyOptions(e) && e.join) return e.join.alias;
return undefined;
}
static applyOptionsToTreeQueryBuilder(e, t) {
if (t?.relations) {
const n = [ ...t.relations ];
FindOptionsUtils.applyRelationsRecursively(e, n, e.expressionMap.mainAlias.name, e.expressionMap.mainAlias.metadata, "");
if (n.length > 0) throw new tl.FindRelationsNotFoundError(n);
}
return e;
}
static applyRelationsRecursively(e, t, n, a, r) {
let i = [];
if (r) {
const e = new RegExp("^" + r.replace(".", "\\.") + "\\.");
i = t.filter(t => t.match(e)).map(t => a.findRelationWithPropertyPath(t.replace(e, ""))).filter(e => e);
} else {
i = t.map(e => a.findRelationWithPropertyPath(e)).filter(e => e);
}
i.forEach(i => {
const s = nl.DriverUtils.buildAlias(e.connection.driver, {
joiner: "__"
}, n, i.propertyPath);
const o = n + "." + i.propertyPath;
if (e.expressionMap.relationLoadStrategy === "query") {
e.concatRelationMetadata(i);
} else {
e.leftJoinAndSelect(o, s);
}
t.splice(t.indexOf(r ? r + "." + i.propertyPath : i.propertyPath), 1);
let c;
let l;
if (e.expressionMap.relationLoadStrategy === "query") {
c = i.inverseEntityMetadata;
l = s;
} else {
const t = e.expressionMap.joinAttributes.find(e => e.entityOrProperty === o);
c = t.metadata;
l = t.alias.name;
}
if (!l || !c) {
throw new al.EntityPropertyNotFoundError(i.propertyPath, a);
}
this.applyRelationsRecursively(e, t, l, c, r ? r + "." + i.propertyPath : i.propertyPath);
if (e.expressionMap.relationLoadStrategy === "join") {
const t = a.relations.find(e => e.propertyName === i.propertyPath);
if (t) {
this.joinEagerRelations(e, s, t.inverseEntityMetadata);
}
}
});
}
static joinEagerRelations(e, t, n) {
n.eagerRelations.forEach(n => {
let a = nl.DriverUtils.buildAlias(e.connection.driver, {
joiner: "__"
}, t, n.propertyName);
let r = true;
for (const i of e.expressionMap.joinAttributes) {
if (i.condition !== undefined || i.mapToProperty !== undefined || i.isMappingMany !== undefined || i.direction !== "LEFT" || i.entityOrProperty !== `${t}.${n.propertyPath}`) {
continue;
}
r = false;
a = i.alias.name;
break;
}
const i = Boolean(e.expressionMap.joinAttributes.find(e => e.alias.name === a));
if (r && !i) {
e.leftJoin(t + "." + n.propertyPath, a);
}
let s = true;
for (const t of e.expressionMap.selects) {
if (t.aliasName !== undefined || t.virtual !== undefined || t.selection !== a) {
continue;
}
s = false;
break;
}
if (s) {
e.addSelect(a);
}
this.joinEagerRelations(e, a, n.inverseEntityMetadata);
});
}
}
el = Zc.FindOptionsUtils = FindOptionsUtils;
Object.defineProperty($c, "__esModule", {
value: true
});
var rl = $c.SelectQueryBuilder = void 0;
const il = xc;
const sl = Ft;
const ol = St;
const cl = ve;
const ll = vt;
const ul = Bn;
const hl = Ts;
const dl = bs;
const pl = jc;
const ml = Wc;
const fl = Gc;
const yl = zc;
const El = Jc;
const Tl = M;
const gl = K;
const Nl = wn;
const Al = I;
const bl = jn;
const Cl = Ee;
const Rl = P;
const Sl = Zc;
const wl = qc;
const Ml = ht;
const Ol = Te;
const vl = Ds;
const Il = _s;
class SelectQueryBuilder extends Tl.QueryBuilder {
constructor() {
super(...arguments);
this["@instanceof"] = Symbol.for("SelectQueryBuilder");
this.findOptions = {};
this.selects = [];
this.joins = [];
this.conditions = "";
this.orderBys = [];
this.relationMetadatas = [];
}
getQuery() {
let e = this.createComment();
e += this.createCteExpression();
e += this.createSelectExpression();
e += this.createJoinExpression();
e += this.createWhereExpression();
e += this.createGroupByExpression();
e += this.createHavingExpression();
e += this.createOrderByExpression();
e += this.createLimitOffsetExpression();
e += this.createLockExpression();
e = e.trim();
if (this.expressionMap.subQuery) e = "(" + e + ")";
return this.replacePropertyNamesForTheWholeQuery(e);
}
setFindOptions(e) {
this.findOptions = e;
this.applyFindOptions();
return this;
}
subQuery() {
const e = this.createQueryBuilder();
e.expressionMap.subQuery = true;
e.parentQueryBuilder = this;
return e;
}
select(e, t) {
this.expressionMap.queryType = "select";
if (Array.isArray(e)) {
this.expressionMap.selects = e.map(e => ({
selection: e
}));
} else if (typeof e === "function") {
const n = e(this.subQuery());
this.setParameters(n.getParameters());
this.expressionMap.selects.push({
selection: n.getQuery(),
aliasName: t
});
} else if (e) {
this.expressionMap.selects = [ {
selection: e,
aliasName: t
} ];
}
return this;
}
addSelect(e, t) {
if (!e) return this;
if (Array.isArray(e)) {
this.expressionMap.selects = this.expressionMap.selects.concat(e.map(e => ({
selection: e
})));
} else if (typeof e === "function") {
const n = e(this.subQuery());
this.setParameters(n.getParameters());
this.expressionMap.selects.push({
selection: n.getQuery(),
aliasName: t
});
} else if (e) {
this.expressionMap.selects.push({
selection: e,
aliasName: t
});
}
return this;
}
maxExecutionTime(e) {
this.expressionMap.maxExecutionTime = e;
return this;
}
distinct(e = true) {
this.expressionMap.selectDistinct = e;
return this;
}
distinctOn(e) {
this.expressionMap.selectDistinctOn = e;
return this;
}
fromDummy() {
return this.from(this.connection.driver.dummyTableName ?? "(SELECT 1 AS dummy_column)", "dummy_table");
}
from(e, t) {
const n = this.createFromAlias(e, t);
this.expressionMap.setMainAlias(n);
return this;
}
addFrom(e, t) {
const n = this.createFromAlias(e, t);
if (!this.expressionMap.mainAlias) this.expressionMap.setMainAlias(n);
return this;
}
innerJoin(e, t, n, a) {
this.join("INNER", e, t, n, a);
return this;
}
leftJoin(e, t, n, a) {
this.join("LEFT", e, t, n, a);
return this;
}
innerJoinAndSelect(e, t, n, a) {
this.addSelect(t);
this.innerJoin(e, t, n, a);
return this;
}
leftJoinAndSelect(e, t, n, a) {
this.addSelect(t);
this.leftJoin(e, t, n, a);
return this;
}
innerJoinAndMapMany(e, t, n, a, r) {
this.addSelect(n);
this.join("INNER", t, n, a, r, e, true);
return this;
}
innerJoinAndMapOne(e, t, n, a, r, i) {
this.addSelect(n);
this.join("INNER", t, n, a, r, e, false, i);
return this;
}
leftJoinAndMapMany(e, t, n, a, r) {
this.addSelect(n);
this.join("LEFT", t, n, a, r, e, true);
return this;
}
leftJoinAndMapOne(e, t, n, a, r, i) {
this.addSelect(n);
this.join("LEFT", t, n, a, r, e, false, i);
return this;
}
loadRelationIdAndMap(e, t, n, a) {
const r = new hl.RelationIdAttribute(this.expressionMap);
r.mapToProperty = e;
r.relationName = t;
if (typeof n === "string") r.alias = n;
if (typeof n === "object" && n.disableMixedMap) r.disableMixedMap = true;
r.queryBuilderFactory = a;
this.expressionMap.relationIdAttributes.push(r);
if (r.relation.junctionEntityMetadata) {
this.expressionMap.createAlias({
type: "other",
name: r.junctionAlias,
metadata: r.relation.junctionEntityMetadata
});
}
return this;
}
loadRelationCountAndMap(e, t, n, a) {
const r = new dl.RelationCountAttribute(this.expressionMap);
r.mapToProperty = e;
r.relationName = t;
r.alias = n;
r.queryBuilderFactory = a;
this.expressionMap.relationCountAttributes.push(r);
this.expressionMap.createAlias({
type: "other",
name: r.junctionAlias
});
if (r.relation.junctionEntityMetadata) {
this.expressionMap.createAlias({
type: "other",
name: r.junctionAlias,
metadata: r.relation.junctionEntityMetadata
});
}
return this;
}
loadAllRelationIds(e) {
this.expressionMap.mainAlias.metadata.relations.forEach(t => {
if (e !== undefined && e.relations !== undefined && e.relations.indexOf(t.propertyPath) === -1) return;
this.loadRelationIdAndMap(this.expressionMap.mainAlias.name + "." + t.propertyPath, this.expressionMap.mainAlias.name + "." + t.propertyPath, e);
});
return this;
}
where(e, t) {
this.expressionMap.wheres = [];
const n = this.getWhereCondition(e);
if (n) {
this.expressionMap.wheres = [ {
type: "simple",
condition: n
} ];
}
if (t) this.setParameters(t);
return this;
}
andWhere(e, t) {
this.expressionMap.wheres.push({
type: "and",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
orWhere(e, t) {
this.expressionMap.wheres.push({
type: "or",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
whereExists(e) {
return this.where(...this.getExistsCondition(e));
}
andWhereExists(e) {
return this.andWhere(...this.getExistsCondition(e));
}
orWhereExists(e) {
return this.orWhere(...this.getExistsCondition(e));
}
whereInIds(e) {
return this.where(this.getWhereInIdsCondition(e));
}
andWhereInIds(e) {
return this.andWhere(this.getWhereInIdsCondition(e));
}
orWhereInIds(e) {
return this.orWhere(this.getWhereInIdsCondition(e));
}
having(e, t) {
this.expressionMap.havings.push({
type: "simple",
condition: e
});
if (t) this.setParameters(t);
return this;
}
andHaving(e, t) {
this.expressionMap.havings.push({
type: "and",
condition: e
});
if (t) this.setParameters(t);
return this;
}
orHaving(e, t) {
this.expressionMap.havings.push({
type: "or",
condition: e
});
if (t) this.setParameters(t);
return this;
}
groupBy(e) {
if (e) {
this.expressionMap.groupBys = [ e ];
} else {
this.expressionMap.groupBys = [];
}
return this;
}
addGroupBy(e) {
this.expressionMap.groupBys.push(e);
return this;
}
timeTravelQuery(e) {
if (this.connection.driver.options.type === "cockroachdb") {
if (e === undefined) {
this.expressionMap.timeTravel = "follower_read_timestamp()";
} else {
this.expressionMap.timeTravel = e;
}
}
return this;
}
orderBy(e, t = "ASC", n) {
if (t !== undefined && t !== "ASC" && t !== "DESC") throw new Rl.TypeORMError(`SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.`);
if (n !== undefined && n !== "NULLS FIRST" && n !== "NULLS LAST") throw new Rl.TypeORMError(`SelectQueryBuilder.addOrderBy "nulls" can accept only "NULLS FIRST" and "NULLS LAST" values.`);
if (e) {
if (typeof e === "object") {
this.expressionMap.orderBys = e;
} else {
if (n) {
this.expressionMap.orderBys = {
[e]: {
order: t,
nulls: n
}
};
} else {
this.expressionMap.orderBys = {
[e]: t
};
}
}
} else {
this.expressionMap.orderBys = {};
}
return this;
}
addOrderBy(e, t = "ASC", n) {
if (t !== undefined && t !== "ASC" && t !== "DESC") throw new Rl.TypeORMError(`SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.`);
if (n !== undefined && n !== "NULLS FIRST" && n !== "NULLS LAST") throw new Rl.TypeORMError(`SelectQueryBuilder.addOrderBy "nulls" can accept only "NULLS FIRST" and "NULLS LAST" values.`);
if (n) {
this.expressionMap.orderBys[e] = {
order: t,
nulls: n
};
} else {
this.expressionMap.orderBys[e] = t;
}
return this;
}
limit(e) {
this.expressionMap.limit = this.normalizeNumber(e);
if (this.expressionMap.limit !== undefined && isNaN(this.expressionMap.limit)) throw new Rl.TypeORMError(`Provided "limit" value is not a number. Please provide a numeric value.`);
return this;
}
offset(e) {
this.expressionMap.offset = this.normalizeNumber(e);
if (this.expressionMap.offset !== undefined && isNaN(this.expressionMap.offset)) throw new Rl.TypeORMError(`Provided "offset" value is not a number. Please provide a numeric value.`);
return this;
}
take(e) {
this.expressionMap.take = this.normalizeNumber(e);
if (this.expressionMap.take !== undefined && isNaN(this.expressionMap.take)) throw new Rl.TypeORMError(`Provided "take" value is not a number. Please provide a numeric value.`);
return this;
}
skip(e) {
this.expressionMap.skip = this.normalizeNumber(e);
if (this.expressionMap.skip !== undefined && isNaN(this.expressionMap.skip)) throw new Rl.TypeORMError(`Provided "skip" value is not a number. Please provide a numeric value.`);
return this;
}
useIndex(e) {
this.expressionMap.useIndex = e;
return this;
}
setLock(e, t, n) {
this.expressionMap.lockMode = e;
this.expressionMap.lockVersion = t;
this.expressionMap.lockTables = n;
return this;
}
setOnLocked(e) {
this.expressionMap.onLocked = e;
return this;
}
withDeleted() {
this.expressionMap.withDeleted = true;
return this;
}
async getRawOne() {
return (await this.getRawMany())[0];
}
async getRawMany() {
if (this.expressionMap.lockMode === "optimistic") throw new ll.OptimisticLockCanNotBeUsedError;
this.expressionMap.queryEntity = false;
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
const n = await this.loadRawResults(e);
if (t) {
await e.commitTransaction();
}
return n;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) {
await e.release();
}
}
}
async getRawAndEntities() {
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
this.expressionMap.queryEntity = true;
const n = await this.executeEntitiesAndRawResults(e);
if (t) {
await e.commitTransaction();
}
return n;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) await e.release();
}
}
async getOne() {
const e = await this.getRawAndEntities();
const t = e.entities[0];
if (t && this.expressionMap.lockMode === "optimistic" && this.expressionMap.lockVersion) {
const e = this.expressionMap.mainAlias.metadata;
if (this.expressionMap.lockVersion instanceof Date) {
const n = e.updateDateColumn.getEntityValue(t);
if (n.getTime() !== this.expressionMap.lockVersion.getTime()) throw new cl.OptimisticLockVersionMismatchError(e.name, this.expressionMap.lockVersion, n);
} else {
const n = e.versionColumn.getEntityValue(t);
if (n !== this.expressionMap.lockVersion) throw new cl.OptimisticLockVersionMismatchError(e.name, this.expressionMap.lockVersion, n);
}
}
if (t === undefined) {
return null;
}
return t;
}
async getOneOrFail() {
const e = await this.getOne();
if (!e) {
throw new Cl.EntityNotFoundError(this.expressionMap.mainAlias.target, this.expressionMap.parameters);
}
return e;
}
async getMany() {
if (this.expressionMap.lockMode === "optimistic") throw new ll.OptimisticLockCanNotBeUsedError;
const e = await this.getRawAndEntities();
return e.entities;
}
async getCount() {
if (this.expressionMap.lockMode === "optimistic") throw new ll.OptimisticLockCanNotBeUsedError;
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
this.expressionMap.queryEntity = false;
const n = await this.executeCountQuery(e);
if (t) {
await e.commitTransaction();
}
return n;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) await e.release();
}
}
async getExists() {
if (this.expressionMap.lockMode === "optimistic") throw new ll.OptimisticLockCanNotBeUsedError;
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
this.expressionMap.queryEntity = false;
const n = await this.executeExistsQuery(e);
if (t) {
await e.commitTransaction();
}
return n;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) await e.release();
}
}
async getManyAndCount() {
if (this.expressionMap.lockMode === "optimistic") throw new ll.OptimisticLockCanNotBeUsedError;
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
this.expressionMap.queryEntity = true;
const n = await this.executeEntitiesAndRawResults(e);
this.expressionMap.queryEntity = false;
const a = this.expressionMap.cacheId;
this.expressionMap.cacheId = a ? `${a}-count` : a;
const r = await this.executeCountQuery(e);
const i = [ n.entities, r ];
if (t) {
await e.commitTransaction();
}
return i;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) await e.release();
}
}
async stream() {
this.expressionMap.queryEntity = false;
const [e, t] = this.getQueryAndParameters();
const n = this.obtainQueryRunner();
let a = false;
try {
if (this.expressionMap.useTransaction === true && n.isTransactionActive === false) {
await n.startTransaction();
a = true;
}
const r = () => {
if (n !== this.queryRunner) return n.release();
return;
};
const i = n.stream(e, t, r, r);
if (a) {
await n.commitTransaction();
}
return i;
} catch (e) {
if (a) {
try {
await n.rollbackTransaction();
} catch (e) {}
}
throw e;
}
}
cache(e, t) {
if (typeof e === "boolean") {
this.expressionMap.cache = e;
} else if (typeof e === "number") {
this.expressionMap.cache = true;
this.expressionMap.cacheDuration = e;
} else if (typeof e === "string" || typeof e === "number") {
this.expressionMap.cache = true;
this.expressionMap.cacheId = e;
}
if (t) {
this.expressionMap.cacheDuration = t;
}
return this;
}
setOption(e) {
this.expressionMap.options.push(e);
return this;
}
join(e, t, n, a, r, i, s, o) {
if (r) {
this.setParameters(r);
}
const c = new ul.JoinAttribute(this.connection, this.expressionMap);
c.direction = e;
c.mapAsEntity = o;
c.mapToProperty = i;
c.isMappingMany = s;
c.entityOrProperty = t;
c.condition = a;
this.expressionMap.joinAttributes.push(c);
const l = c.metadata;
if (l) {
if (l.deleteDateColumn && !this.expressionMap.withDeleted) {
const e = `${n}.${l.deleteDateColumn.propertyName} IS NULL`;
c.condition = c.condition ? ` ${c.condition} AND ${e}` : `${e}`;
}
c.alias = this.expressionMap.createAlias({
type: "join",
name: n,
metadata: l
});
if (c.relation && c.relation.junctionEntityMetadata) {
this.expressionMap.createAlias({
type: "join",
name: c.junctionAlias,
metadata: c.relation.junctionEntityMetadata
});
}
} else {
let e = "";
if (typeof t === "function") {
const n = t(this.subQuery());
this.setParameters(n.getParameters());
e = n.getQuery();
} else {
e = t;
}
const a = typeof t === "function" || t.substr(0, 1) === "(" && t.substr(-1) === ")";
c.alias = this.expressionMap.createAlias({
type: "join",
name: n,
tablePath: a === false ? t : undefined,
subQuery: a === true ? e : undefined
});
}
}
createSelectExpression() {
if (!this.expressionMap.mainAlias) throw new Rl.TypeORMError("Cannot build query because main alias is not set (call qb#from method)");
const e = [];
const t = [];
if (this.expressionMap.mainAlias.hasMetadata) {
const n = this.expressionMap.mainAlias.metadata;
e.push(...this.buildEscapedEntityColumnSelects(this.expressionMap.mainAlias.name, n));
t.push(...this.findEntityColumnSelects(this.expressionMap.mainAlias.name, n));
}
this.expressionMap.joinAttributes.forEach(n => {
if (n.metadata) {
e.push(...this.buildEscapedEntityColumnSelects(n.alias.name, n.metadata));
t.push(...this.findEntityColumnSelects(n.alias.name, n.metadata));
} else {
const a = this.expressionMap.selects.some(e => e.selection === n.alias.name);
if (a) {
e.push({
selection: this.escape(n.alias.name) + ".*"
});
const a = this.expressionMap.selects.find(e => e.selection === n.alias.name);
t.push(a);
}
}
});
this.expressionMap.selects.filter(e => t.indexOf(e) === -1).forEach(t => e.push({
selection: this.replacePropertyNames(t.selection),
aliasName: t.aliasName
}));
if (e.length === 0) e.push({
selection: "*"
});
let n = "";
if (this.expressionMap.useIndex) {
if (bl.DriverUtils.isMySQLFamily(this.connection.driver)) {
n = ` USE INDEX (${this.expressionMap.useIndex})`;
}
}
const a = this.expressionMap.aliases.filter(e => e.type === "from" && (e.tablePath || e.subQuery)).map(e => {
if (e.subQuery) return e.subQuery + " " + this.escape(e.name);
return this.getTableName(e.tablePath) + " " + this.escape(e.name);
});
const r = this.createSelectDistinctExpression();
const i = e.map(e => e.selection + (e.aliasName ? " AS " + this.escape(e.aliasName) : "")).join(", ");
return r + i + " FROM " + a.join(", ") + this.createTableLockExpression() + n;
}
createSelectDistinctExpression() {
const {selectDistinct: e, selectDistinctOn: t, maxExecutionTime: n} = this.expressionMap;
const {driver: a} = this.connection;
let r = "SELECT ";
if (n > 0) {
if (bl.DriverUtils.isMySQLFamily(a)) {
r += `/*+ MAX_EXECUTION_TIME(${this.expressionMap.maxExecutionTime}) */ `;
}
}
if (bl.DriverUtils.isPostgresFamily(a) && t.length > 0) {
const e = t.map(e => this.replacePropertyNames(e)).join(", ");
r = `SELECT DISTINCT ON (${e}) `;
} else if (e) {
r = "SELECT DISTINCT ";
}
return r;
}
createJoinExpression() {
const e = this.expressionMap.joinAttributes.map(e => {
const t = e.relation;
const n = e.tablePath;
const a = e.alias.name;
let r = e.condition ? " AND (" + e.condition + ")" : "";
const i = e.parentAlias;
if (!i || !t) {
const t = e.alias.subQuery ? e.alias.subQuery : this.getTableName(n);
return " " + e.direction + " JOIN " + t + " " + this.escape(a) + this.createTableLockExpression() + (e.condition ? " ON " + this.replacePropertyNames(e.condition) : "");
}
if (t.isManyToOne || t.isOneToOneOwner) {
const s = t.joinColumns.map(e => a + "." + e.referencedColumn.propertyPath + "=" + i + "." + t.propertyPath + "." + e.referencedColumn.propertyPath).join(" AND ");
return " " + e.direction + " JOIN " + this.getTableName(n) + " " + this.escape(a) + this.createTableLockExpression() + " ON " + this.replacePropertyNames(s + r);
} else if (t.isOneToMany || t.isOneToOneNotOwner) {
const s = t.inverseRelation.joinColumns.map(e => {
if (t.inverseEntityMetadata.tableType === "entity-child" && t.inverseEntityMetadata.discriminatorColumn) {
r += " AND " + a + "." + t.inverseEntityMetadata.discriminatorColumn.databaseName + "='" + t.inverseEntityMetadata.discriminatorValue + "'";
}
return a + "." + t.inverseRelation.propertyPath + "." + e.referencedColumn.propertyPath + "=" + i + "." + e.referencedColumn.propertyPath;
}).join(" AND ");
if (!s) throw new Rl.TypeORMError(`Relation ${t.entityMetadata.name}.${t.propertyName} does not have join columns.`);
return " " + e.direction + " JOIN " + this.getTableName(n) + " " + this.escape(a) + this.createTableLockExpression() + " ON " + this.replacePropertyNames(s + r);
} else {
const s = t.junctionEntityMetadata.tablePath;
const o = e.junctionAlias;
let c = "", l = "";
if (t.isOwning) {
c = t.joinColumns.map(e => o + "." + e.propertyPath + "=" + i + "." + e.referencedColumn.propertyPath).join(" AND ");
l = t.inverseJoinColumns.map(e => a + "." + e.referencedColumn.propertyPath + "=" + o + "." + e.propertyPath).join(" AND ");
} else {
c = t.inverseRelation.inverseJoinColumns.map(e => o + "." + e.propertyPath + "=" + i + "." + e.referencedColumn.propertyPath).join(" AND ");
l = t.inverseRelation.joinColumns.map(e => a + "." + e.referencedColumn.propertyPath + "=" + o + "." + e.propertyPath).join(" AND ");
}
return " " + e.direction + " JOIN " + this.getTableName(s) + " " + this.escape(o) + this.createTableLockExpression() + " ON " + this.replacePropertyNames(c) + " " + e.direction + " JOIN " + this.getTableName(n) + " " + this.escape(a) + this.createTableLockExpression() + " ON " + this.replacePropertyNames(l + r);
}
});
return e.join(" ");
}
createGroupByExpression() {
if (!this.expressionMap.groupBys || !this.expressionMap.groupBys.length) return "";
return " GROUP BY " + this.replacePropertyNames(this.expressionMap.groupBys.join(", "));
}
createOrderByExpression() {
const e = this.expressionMap.allOrderBys;
if (Object.keys(e).length === 0) return "";
return " ORDER BY " + Object.keys(e).map(t => {
const n = typeof e[t] === "string" ? e[t] : e[t].order + " " + e[t].nulls;
const a = this.expressionMap.selects.find(e => e.selection === t);
if (a && !a.aliasName && t.indexOf(".") !== -1) {
const e = t.split(".");
const a = e[0];
const r = e.slice(1).join(".");
const i = this.expressionMap.aliases.find(e => e.name === a);
if (i) {
const e = i.metadata.findColumnWithPropertyPath(r);
if (e) {
const t = bl.DriverUtils.buildAlias(this.connection.driver, undefined, a, e.databaseName);
return this.escape(t) + " " + n;
}
}
}
return this.replacePropertyNames(t) + " " + n;
}).join(", ");
}
createLimitOffsetExpression() {
let e = this.expressionMap.offset, t = this.expressionMap.limit;
if (!e && !t && this.expressionMap.joinAttributes.length === 0) {
e = this.expressionMap.skip;
t = this.expressionMap.take;
}
if (this.connection.driver.options.type === "mssql") {
let n = "";
if ((t || e) && Object.keys(this.expressionMap.allOrderBys).length <= 0) {
n = " ORDER BY (SELECT NULL)";
}
if (t && e) return n + " OFFSET " + e + " ROWS FETCH NEXT " + t + " ROWS ONLY";
if (t) return n + " OFFSET 0 ROWS FETCH NEXT " + t + " ROWS ONLY";
if (e) return n + " OFFSET " + e + " ROWS";
} else if (bl.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql" || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
if (t && e) return " LIMIT " + t + " OFFSET " + e;
if (t) return " LIMIT " + t;
if (e) throw new Nl.OffsetWithoutLimitNotSupportedError;
} else if (bl.DriverUtils.isSQLiteFamily(this.connection.driver)) {
if (t && e) return " LIMIT " + t + " OFFSET " + e;
if (t) return " LIMIT " + t;
if (e) return " LIMIT -1 OFFSET " + e;
} else if (this.connection.driver.options.type === "oracle") {
if (t && e) return " OFFSET " + e + " ROWS FETCH NEXT " + t + " ROWS ONLY";
if (t) return " FETCH NEXT " + t + " ROWS ONLY";
if (e) return " OFFSET " + e + " ROWS";
} else {
if (t && e) return " LIMIT " + t + " OFFSET " + e;
if (t) return " LIMIT " + t;
if (e) return " OFFSET " + e;
}
return "";
}
createTableLockExpression() {
if (this.connection.driver.options.type === "mssql") {
switch (this.expressionMap.lockMode) {
case "pessimistic_read":
return " WITH (HOLDLOCK, ROWLOCK)";
case "pessimistic_write":
return " WITH (UPDLOCK, ROWLOCK)";
case "dirty_read":
return " WITH (NOLOCK)";
}
}
return "";
}
createLockExpression() {
const e = this.connection.driver;
let t = "";
if (this.expressionMap.lockTables) {
if (!(bl.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb")) {
throw new Rl.TypeORMError("Lock tables not supported in selected driver");
}
if (this.expressionMap.lockTables.length < 1) {
throw new Rl.TypeORMError("lockTables cannot be an empty array");
}
t = " OF " + this.expressionMap.lockTables.join(", ");
}
let n = "";
if (this.expressionMap.onLocked === "nowait") {
n = " NOWAIT";
} else if (this.expressionMap.onLocked === "skip_locked") {
n = " SKIP LOCKED";
}
switch (this.expressionMap.lockMode) {
case "pessimistic_read":
if (e.options.type === "mysql" || e.options.type === "aurora-mysql") {
if (bl.DriverUtils.isReleaseVersionOrGreater(e, "8.0.0")) {
return " FOR SHARE" + t + n;
} else {
return " LOCK IN SHARE MODE";
}
} else if (e.options.type === "mariadb") {
return " LOCK IN SHARE MODE";
} else if (bl.DriverUtils.isPostgresFamily(e)) {
return " FOR SHARE" + t + n;
} else if (e.options.type === "oracle") {
return " FOR UPDATE";
} else if (e.options.type === "mssql") {
return "";
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
case "pessimistic_write":
if (bl.DriverUtils.isMySQLFamily(e) || e.options.type === "aurora-mysql" || e.options.type === "oracle") {
return " FOR UPDATE" + n;
} else if (bl.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
return " FOR UPDATE" + t + n;
} else if (e.options.type === "mssql") {
return "";
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
case "pessimistic_partial_write":
if (bl.DriverUtils.isPostgresFamily(e)) {
return " FOR UPDATE" + t + " SKIP LOCKED";
} else if (bl.DriverUtils.isMySQLFamily(e)) {
return " FOR UPDATE SKIP LOCKED";
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
case "pessimistic_write_or_fail":
if (bl.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
return " FOR UPDATE" + t + " NOWAIT";
} else if (bl.DriverUtils.isMySQLFamily(e)) {
return " FOR UPDATE NOWAIT";
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
case "for_no_key_update":
if (bl.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
return " FOR NO KEY UPDATE" + t + n;
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
case "for_key_share":
if (bl.DriverUtils.isPostgresFamily(e)) {
return " FOR KEY SHARE" + t + n;
} else {
throw new gl.LockNotSupportedOnGivenDriverError;
}
default:
return "";
}
}
createHavingExpression() {
if (!this.expressionMap.havings || !this.expressionMap.havings.length) return "";
const e = this.expressionMap.havings.map((e, t) => {
switch (e.type) {
case "and":
return (t > 0 ? "AND " : "") + this.replacePropertyNames(e.condition);
case "or":
return (t > 0 ? "OR " : "") + this.replacePropertyNames(e.condition);
default:
return this.replacePropertyNames(e.condition);
}
}).join(" ");
if (!e.length) return "";
return " HAVING " + e;
}
buildEscapedEntityColumnSelects(e, t) {
const n = this.expressionMap.selects.some(t => t.selection === e);
const a = [];
if (n) {
a.push(...t.columns.filter(e => e.isSelect === true));
}
a.push(...t.columns.filter(t => this.expressionMap.selects.some(n => n.selection === e + "." + t.propertyPath)));
if (a.length === 0) return [];
const r = this.expressionMap.queryEntity ? t.primaryColumns.filter(e => a.indexOf(e) === -1) : [];
const i = [ ...a, ...r ];
const s = [];
const o = this.escape(e);
i.forEach(t => {
let a = o + "." + this.escape(t.databaseName);
if (t.isVirtualProperty && t.query) {
a = `(${t.query(o)})`;
}
if (this.connection.driver.spatialTypes.indexOf(t.type) !== -1) {
if (bl.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") {
const e = this.connection.driver.options.legacySpatialSupport;
const t = e ? "AsText" : "ST_AsText";
a = `${t}(${a})`;
}
if (bl.DriverUtils.isPostgresFamily(this.connection.driver)) if (t.precision) {
a = `ST_AsGeoJSON(${a}, ${t.precision})::json`;
} else {
a = `ST_AsGeoJSON(${a})::json`;
}
if (this.connection.driver.options.type === "mssql") a = `${a}.ToString()`;
}
const r = this.expressionMap.selects.filter(n => n.selection === e + "." + t.propertyPath);
if (r.length) {
r.forEach(n => {
s.push({
selection: a,
aliasName: n.aliasName ? n.aliasName : bl.DriverUtils.buildAlias(this.connection.driver, undefined, e, t.databaseName),
virtual: n.virtual
});
});
} else {
s.push({
selection: a,
aliasName: bl.DriverUtils.buildAlias(this.connection.driver, undefined, e, t.databaseName),
virtual: n
});
}
});
return s;
}
findEntityColumnSelects(e, t) {
const n = this.expressionMap.selects.find(t => t.selection === e);
if (n) return [ n ];
return this.expressionMap.selects.filter(n => t.columns.some(t => n.selection === e + "." + t.propertyPath));
}
computeCountExpression() {
const e = this.expressionMap.mainAlias.name;
const t = this.expressionMap.mainAlias.metadata;
const n = t.primaryColumns;
const a = this.escape(e);
if (this.expressionMap.joinAttributes.length === 0 && this.expressionMap.relationIdAttributes.length === 0 && this.expressionMap.relationCountAttributes.length === 0) {
return "COUNT(1)";
}
if (this.connection.driver.options.type === "cockroachdb" || bl.DriverUtils.isPostgresFamily(this.connection.driver)) {
return "COUNT(DISTINCT(" + n.map(e => `${a}.${this.escape(e.databaseName)}`).join(", ") + "))";
}
if (bl.DriverUtils.isMySQLFamily(this.connection.driver)) {
return "COUNT(DISTINCT " + n.map(e => `${a}.${this.escape(e.databaseName)}`).join(", ") + ")";
}
if (this.connection.driver.options.type === "mssql") {
const e = n.map(e => `${a}.${this.escape(e.databaseName)}`).join(", '|;|', ");
if (n.length === 1) {
return `COUNT(DISTINCT(${e}))`;
}
return `COUNT(DISTINCT(CONCAT(${e})))`;
}
if (this.connection.driver.options.type === "spanner") {
if (n.length === 1) {
return `COUNT(DISTINCT(${a}.${this.escape(n[0].databaseName)}))`;
}
const e = n.map(e => `CAST(${a}.${this.escape(e.databaseName)} AS STRING)`).join(", '|;|', ");
return `COUNT(DISTINCT(CONCAT(${e})))`;
}
return `COUNT(DISTINCT(` + n.map(e => `${a}.${this.escape(e.databaseName)}`).join(" || '|;|' || ") + "))";
}
async executeCountQuery(e) {
const t = this.computeCountExpression();
const n = await this.clone().orderBy().groupBy().offset(undefined).limit(undefined).skip(undefined).take(undefined).select(t, "cnt").setOption("disable-global-order").loadRawResults(e);
if (!n || !n[0] || !n[0]["cnt"]) return 0;
return parseInt(n[0]["cnt"]);
}
async executeExistsQuery(e) {
const t = await this.connection.createQueryBuilder().fromDummy().select("1", "row_exists").whereExists(this).limit(1).loadRawResults(e);
return t.length > 0;
}
applyFindOptions() {
if (this.expressionMap.mainAlias.metadata) {
if (this.findOptions.relationLoadStrategy) {
this.expressionMap.relationLoadStrategy = this.findOptions.relationLoadStrategy;
}
if (this.findOptions.comment) {
this.comment(this.findOptions.comment);
}
if (this.findOptions.withDeleted) {
this.withDeleted();
}
if (this.findOptions.select) {
const e = Array.isArray(this.findOptions.select) ? wl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.select) : this.findOptions.select;
this.buildSelect(e, this.expressionMap.mainAlias.metadata, this.expressionMap.mainAlias.name);
}
if (this.selects.length) {
this.select(this.selects);
}
this.selects = [];
if (this.findOptions.relations) {
const e = Array.isArray(this.findOptions.relations) ? wl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.relations) : this.findOptions.relations;
this.buildRelations(e, typeof this.findOptions.select === "object" ? this.findOptions.select : undefined, this.expressionMap.mainAlias.metadata, this.expressionMap.mainAlias.name);
if (this.findOptions.loadEagerRelations !== false && this.expressionMap.relationLoadStrategy === "join") {
this.buildEagerRelations(e, typeof this.findOptions.select === "object" ? this.findOptions.select : undefined, this.expressionMap.mainAlias.metadata, this.expressionMap.mainAlias.name);
}
}
if (this.selects.length) {
this.addSelect(this.selects);
}
if (this.findOptions.where) {
this.conditions = this.buildWhere(this.findOptions.where, this.expressionMap.mainAlias.metadata, this.expressionMap.mainAlias.name);
if (this.conditions.length) this.andWhere(this.conditions.substr(0, 1) !== "(" ? "(" + this.conditions + ")" : this.conditions);
}
if (this.findOptions.order) {
this.buildOrder(this.findOptions.order, this.expressionMap.mainAlias.metadata, this.expressionMap.mainAlias.name);
}
if (this.joins.length) {
this.joins.forEach(e => {
if (e.select && !e.selection) {
if (e.type === "inner") {
this.innerJoinAndSelect(`${e.parentAlias}.${e.relationMetadata.propertyPath}`, e.alias);
} else {
this.leftJoinAndSelect(`${e.parentAlias}.${e.relationMetadata.propertyPath}`, e.alias);
}
} else {
if (e.type === "inner") {
this.innerJoin(`${e.parentAlias}.${e.relationMetadata.propertyPath}`, e.alias);
} else {
this.leftJoin(`${e.parentAlias}.${e.relationMetadata.propertyPath}`, e.alias);
}
}
});
}
if (this.findOptions.skip !== undefined) {
this.skip(this.findOptions.skip);
}
if (this.findOptions.take !== undefined) {
this.take(this.findOptions.take);
}
if (typeof this.findOptions.cache === "number") {
this.cache(this.findOptions.cache);
} else if (typeof this.findOptions.cache === "boolean") {
this.cache(this.findOptions.cache);
} else if (typeof this.findOptions.cache === "object") {
this.cache(this.findOptions.cache.id, this.findOptions.cache.milliseconds);
}
if (this.findOptions.join) {
if (this.findOptions.join.leftJoin) Object.keys(this.findOptions.join.leftJoin).forEach(e => {
this.leftJoin(this.findOptions.join.leftJoin[e], e);
});
if (this.findOptions.join.innerJoin) Object.keys(this.findOptions.join.innerJoin).forEach(e => {
this.innerJoin(this.findOptions.join.innerJoin[e], e);
});
if (this.findOptions.join.leftJoinAndSelect) Object.keys(this.findOptions.join.leftJoinAndSelect).forEach(e => {
this.leftJoinAndSelect(this.findOptions.join.leftJoinAndSelect[e], e);
});
if (this.findOptions.join.innerJoinAndSelect) Object.keys(this.findOptions.join.innerJoinAndSelect).forEach(e => {
this.innerJoinAndSelect(this.findOptions.join.innerJoinAndSelect[e], e);
});
}
if (this.findOptions.lock) {
if (this.findOptions.lock.mode === "optimistic") {
this.setLock(this.findOptions.lock.mode, this.findOptions.lock.version);
} else if (this.findOptions.lock.mode === "pessimistic_read" || this.findOptions.lock.mode === "pessimistic_write" || this.findOptions.lock.mode === "dirty_read" || this.findOptions.lock.mode === "pessimistic_partial_write" || this.findOptions.lock.mode === "pessimistic_write_or_fail" || this.findOptions.lock.mode === "for_no_key_update" || this.findOptions.lock.mode === "for_key_share") {
const e = this.findOptions.lock.tables ? this.findOptions.lock.tables.map(e => {
const t = this.expressionMap.aliases.find(t => t.metadata.tableNameWithoutPrefix === e);
if (!t) {
throw new Rl.TypeORMError(`"${e}" is not part of this query`);
}
return this.escape(t.name);
}) : undefined;
this.setLock(this.findOptions.lock.mode, undefined, e);
if (this.findOptions.lock.onLocked) {
this.setOnLocked(this.findOptions.lock.onLocked);
}
}
}
if (this.findOptions.loadRelationIds === true) {
this.loadAllRelationIds();
} else if (typeof this.findOptions.loadRelationIds === "object") {
this.loadAllRelationIds(this.findOptions.loadRelationIds);
}
if (this.findOptions.loadEagerRelations !== false) {
Sl.FindOptionsUtils.joinEagerRelations(this, this.expressionMap.mainAlias.name, this.expressionMap.mainAlias.metadata);
}
if (this.findOptions.transaction === true) {
this.expressionMap.useTransaction = true;
}
}
}
concatRelationMetadata(e) {
this.relationMetadatas.push(e);
}
async executeEntitiesAndRawResults(e) {
if (!this.expressionMap.mainAlias) throw new Rl.TypeORMError(`Alias is not set. Use "from" method to set an alias.`);
if ((this.expressionMap.lockMode === "pessimistic_read" || this.expressionMap.lockMode === "pessimistic_write" || this.expressionMap.lockMode === "pessimistic_partial_write" || this.expressionMap.lockMode === "pessimistic_write_or_fail" || this.expressionMap.lockMode === "for_no_key_update" || this.expressionMap.lockMode === "for_key_share") && !e.isTransactionActive) throw new sl.PessimisticLockTransactionRequiredError;
if (this.expressionMap.lockMode === "optimistic") {
const e = this.expressionMap.mainAlias.metadata;
if (!e.versionColumn && !e.updateDateColumn) throw new ol.NoVersionOrUpdateDateColumnError(e.name);
}
const t = new pl.RelationIdLoader(this.connection, e, this.expressionMap.relationIdAttributes);
const n = new yl.RelationCountLoader(this.connection, e, this.expressionMap.relationCountAttributes);
const a = new fl.RelationIdMetadataToAttributeTransformer(this.expressionMap);
a.transform();
const r = new El.RelationCountMetadataToAttributeTransformer(this.expressionMap);
r.transform();
let i = [], s = [];
if ((this.expressionMap.skip || this.expressionMap.take) && this.expressionMap.joinAttributes.length > 0) {
const [t, n] = this.createOrderByCombinedWithSelectExpression("distinctAlias");
const a = this.expressionMap.mainAlias.metadata;
const r = this.expressionMap.mainAlias.name;
const s = a.primaryColumns.map(e => {
const t = this.escape("distinctAlias");
const a = this.escape(bl.DriverUtils.buildAlias(this.connection.driver, undefined, r, e.databaseName));
if (!n[a]) n[a] = "ASC";
const i = bl.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, e.databaseName);
return `${t}.${a} AS ${this.escape(i)}`;
});
const o = this.clone();
const c = o.expressionMap.timeTravel;
i = await new SelectQueryBuilder(this.connection, e).select(`DISTINCT ${s.join(", ")}`).addSelect(t).from(`(${o.orderBy().timeTravelQuery(false).getQuery()})`, "distinctAlias").timeTravelQuery(c).offset(this.expressionMap.skip).limit(this.expressionMap.take).orderBy(n).cache(this.expressionMap.cache && this.expressionMap.cacheId ? `${this.expressionMap.cacheId}-pagination` : this.expressionMap.cache, this.expressionMap.cacheDuration).setParameters(this.getParameters()).setNativeParameters(this.expressionMap.nativeParameters).getRawMany();
if (i.length > 0) {
let t = "";
const n = {};
if (a.hasMultiplePrimaryKeys) {
t = i.map((e, t) => a.primaryColumns.map(a => {
const i = `orm_distinct_ids_${t}_${a.databaseName}`;
const s = bl.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, a.databaseName);
n[i] = e[s];
return `${r}.${a.propertyPath}=:${i}`;
}).join(" AND ")).join(" OR ");
} else {
const e = bl.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, a.primaryColumns[0].databaseName);
const s = i.map(t => t[e]);
const o = s.every(e => typeof e === "number");
if (o) {
t = `${r}.${a.primaryColumns[0].propertyPath} IN (${s.join(", ")})`;
} else {
n["orm_distinct_ids"] = s;
t = r + "." + a.primaryColumns[0].propertyPath + " IN (:...orm_distinct_ids)";
}
}
i = await this.clone().mergeExpressionMap({
extraAppendedAndWhereCondition: t
}).setParameters(n).loadRawResults(e);
}
} else {
i = await this.loadRawResults(e);
}
if (i.length > 0) {
const a = await t.load(i);
const r = await n.load(i);
const o = new il.RawSqlResultsToEntityTransformer(this.expressionMap, this.connection.driver, a, r, this.queryRunner);
s = o.transform(i, this.expressionMap.mainAlias);
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
await e.broadcaster.broadcast("Load", this.expressionMap.mainAlias.metadata, s);
}
}
if (this.expressionMap.relationLoadStrategy === "query") {
const t = new ml.RelationIdLoader(this.connection, e);
await Promise.all(this.relationMetadatas.map(async n => {
const a = n.inverseEntityMetadata.target;
const r = n.inverseEntityMetadata.targetName;
const i = Array.isArray(this.findOptions.select) ? wl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.select) : this.findOptions.select;
const o = Array.isArray(this.findOptions.relations) ? wl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.relations) : this.findOptions.relations;
const c = this.createQueryBuilder(e).select(r).from(a, r).setFindOptions({
select: i ? wl.OrmUtils.deepValue(i, n.propertyPath) : undefined,
order: this.findOptions.order ? wl.OrmUtils.deepValue(this.findOptions.order, n.propertyPath) : undefined,
relations: o ? wl.OrmUtils.deepValue(o, n.propertyPath) : undefined,
withDeleted: this.findOptions.withDeleted,
relationLoadStrategy: this.findOptions.relationLoadStrategy
});
if (s.length > 0) {
const e = await t.loadManyToManyRelationIdsAndGroup(n, s, undefined, c);
s.forEach(t => {
const a = e.find(e => e.entity === t);
if (a) {
const e = a.related === undefined ? null : a.related;
n.setEntityValue(t, e);
}
});
}
}));
}
return {
raw: i,
entities: s
};
}
createOrderByCombinedWithSelectExpression(e) {
const t = this.expressionMap.allOrderBys;
const n = Object.keys(t).map(t => {
if (t.indexOf(".") !== -1) {
const n = t.split(".");
const a = n[0];
const r = n.slice(1).join(".");
const i = this.expressionMap.findAliasByName(a);
const s = i.metadata.findColumnWithPropertyPath(r);
return this.escape(e) + "." + this.escape(bl.DriverUtils.buildAlias(this.connection.driver, undefined, a, s.databaseName));
} else {
if (this.expressionMap.selects.find(e => e.selection === t || e.aliasName === t)) return this.escape(e) + "." + this.escape(t);
return "";
}
}).join(", ");
const a = {};
Object.keys(t).forEach(n => {
if (n.indexOf(".") !== -1) {
const r = n.split(".");
const i = r[0];
const s = r.slice(1).join(".");
const o = this.expressionMap.findAliasByName(i);
const c = o.metadata.findColumnWithPropertyPath(s);
a[this.escape(e) + "." + this.escape(bl.DriverUtils.buildAlias(this.connection.driver, undefined, i, c.databaseName))] = t[n];
} else {
if (this.expressionMap.selects.find(e => e.selection === n || e.aliasName === n)) {
a[this.escape(e) + "." + this.escape(n)] = t[n];
} else {
a[n] = t[n];
}
}
});
return [ n, a ];
}
async loadRawResults(e) {
const [t, n] = this.getQueryAndParameters();
const a = t + " -- PARAMETERS: " + JSON.stringify(n, (e, t) => typeof t === "bigint" ? t.toString() : t);
const r = typeof this.connection.options.cache === "object" ? this.connection.options.cache : {};
let i = undefined;
const s = r.alwaysEnabled && this.expressionMap.cache !== false || this.expressionMap.cache === true;
let o = false;
if (this.connection.queryResultCache && s) {
try {
i = await this.connection.queryResultCache.getFromCache({
identifier: this.expressionMap.cacheId,
query: a,
duration: this.expressionMap.cacheDuration || r.duration || 1e3
}, e);
if (i && !this.connection.queryResultCache.isExpired(i)) {
return JSON.parse(i.result);
}
} catch (e) {
if (!r.ignoreErrors) {
throw e;
}
o = true;
}
}
const c = await e.query(t, n, true);
if (!o && this.connection.queryResultCache && s) {
try {
await this.connection.queryResultCache.storeInCache({
identifier: this.expressionMap.cacheId,
query: a,
time: Date.now(),
duration: this.expressionMap.cacheDuration || r.duration || 1e3,
result: JSON.stringify(c.records)
}, i, e);
} catch (e) {
if (!r.ignoreErrors) {
throw e;
}
}
}
return c.records;
}
mergeExpressionMap(e) {
Al.ObjectUtils.assign(this.expressionMap, e);
return this;
}
normalizeNumber(e) {
if (typeof e === "number" || e === undefined || e === null) return e;
return Number(e);
}
obtainQueryRunner() {
return this.queryRunner || this.connection.createQueryRunner(this.connection.defaultReplicationModeForReads());
}
buildSelect(e, t, n, a) {
for (const r in e) {
if (e[r] === undefined || e[r] === false) continue;
const i = a ? a + "." + r : r;
const s = t.findColumnWithPropertyPathStrict(i);
const o = t.findEmbeddedWithPropertyPath(i);
const c = t.findRelationWithPropertyPath(i);
if (!o && !s && !c) throw new Ml.EntityPropertyNotFoundError(i, t);
if (s) {
this.selects.push(n + "." + i);
} else if (o) {
this.buildSelect(e[r], t, n, i);
}
}
}
buildRelations(e, t, n, a, r) {
if (!e) return;
Object.keys(e).forEach(i => {
const s = e[i];
const o = r ? r + "." + i : i;
const c = n.findEmbeddedWithPropertyPath(o);
const l = n.findRelationWithPropertyPath(o);
if (!c && !l) throw new Ml.EntityPropertyNotFoundError(o, n);
if (c) {
this.buildRelations(s, typeof t === "object" ? wl.OrmUtils.deepValue(t, c.propertyPath) : undefined, n, a, o);
} else if (l) {
let e = a + "_" + o.replace(".", "_");
e = bl.DriverUtils.buildAlias(this.connection.driver, {
joiner: "__"
}, a, e);
if (s === true || typeof s === "object") {
if (this.expressionMap.relationLoadStrategy === "query") {
this.concatRelationMetadata(l);
} else {
this.joins.push({
type: "left",
select: true,
selection: t && typeof t[i] === "object" ? t[i] : undefined,
alias: e,
parentAlias: a,
relationMetadata: l
});
if (t && typeof t[i] === "object") {
this.buildSelect(t[i], l.inverseEntityMetadata, e);
}
}
}
if (typeof s === "object" && this.expressionMap.relationLoadStrategy === "join") {
this.buildRelations(s, typeof t === "object" ? wl.OrmUtils.deepValue(t, l.propertyPath) : undefined, l.inverseEntityMetadata, e, undefined);
}
}
});
}
buildEagerRelations(e, t, n, a, r) {
if (!e) return;
Object.keys(e).forEach(i => {
const s = e[i];
const o = r ? r + "." + i : i;
const c = n.findEmbeddedWithPropertyPath(o);
const l = n.findRelationWithPropertyPath(o);
if (!c && !l) throw new Ml.EntityPropertyNotFoundError(o, n);
if (c) {
this.buildEagerRelations(s, typeof t === "object" ? wl.OrmUtils.deepValue(t, c.propertyPath) : undefined, n, a, o);
} else if (l) {
let e = a + "_" + o.replace(".", "_");
e = bl.DriverUtils.buildAlias(this.connection.driver, {
joiner: "__"
}, a, e);
if (s === true || typeof s === "object") {
l.inverseEntityMetadata.eagerRelations.forEach(n => {
let a = e + "_" + n.propertyPath.replace(".", "_");
a = bl.DriverUtils.buildAlias(this.connection.driver, {
joiner: "__"
}, e, a);
const r = this.joins.find(e => e.alias === a);
if (!r) {
this.joins.push({
type: "left",
select: true,
alias: a,
parentAlias: e,
selection: undefined,
relationMetadata: n
});
}
if (t && typeof t[i] === "object") {
this.buildSelect(t[i], l.inverseEntityMetadata, e);
}
});
}
if (typeof s === "object") {
this.buildEagerRelations(s, typeof t === "object" ? wl.OrmUtils.deepValue(t, l.propertyPath) : undefined, l.inverseEntityMetadata, e, undefined);
}
}
});
}
buildOrder(e, t, n, a) {
for (const r in e) {
if (e[r] === undefined) continue;
const i = a ? a + "." + r : r;
const s = t.findColumnWithPropertyPathStrict(i);
const o = t.findEmbeddedWithPropertyPath(i);
const c = t.findRelationWithPropertyPath(i);
if (!o && !s && !c) throw new Ml.EntityPropertyNotFoundError(i, t);
if (s) {
let t = typeof e[r] === "object" ? e[r].direction : e[r];
t = t === "DESC" || t === "desc" || t === -1 ? "DESC" : "ASC";
let a = typeof e[r] === "object" ? e[r].nulls : undefined;
a = a?.toLowerCase() === "first" ? "NULLS FIRST" : a?.toLowerCase() === "last" ? "NULLS LAST" : undefined;
const s = `${n}.${i}`;
this.addOrderBy(s, t, a);
} else if (o) {
this.buildOrder(e[r], t, n, i);
} else if (c) {
let t = n + "_" + i.replace(".", "_");
t = bl.DriverUtils.buildAlias(this.connection.driver, {
joiner: "__"
}, n, t);
const a = this.joins.find(e => e.alias === t);
if (!a) {
this.joins.push({
type: "left",
select: false,
alias: t,
parentAlias: n,
selection: undefined,
relationMetadata: c
});
}
this.buildOrder(e[r], c.inverseEntityMetadata, t);
}
}
}
buildWhere(e, t, n, a) {
let r = "";
if (Array.isArray(e)) {
if (e.length) {
r = e.map(e => this.buildWhere(e, t, n, a)).filter(e => !!e).map(e => "(" + e + ")").join(" OR ");
}
} else {
const i = [];
for (const r in e) {
if (e[r] === undefined || e[r] === null) continue;
const s = a ? a + "." + r : r;
const o = t.findColumnWithPropertyPathStrict(s);
const c = t.findEmbeddedWithPropertyPath(s);
const l = t.findRelationWithPropertyPath(s);
if (!c && !o && !l) throw new Ml.EntityPropertyNotFoundError(s, t);
if (o) {
let t = `${n}.${s}`;
if (o.isVirtualProperty && o.query) {
t = `(${o.query(this.escape(n))})`;
}
let a = e[r];
if (Ol.InstanceChecker.isEqualOperator(e[r])) {
a = e[r].value;
}
if (o.transformer) {
if (a instanceof vl.FindOperator) {
a.transformValue(o.transformer);
} else {
a = Il.ApplyValueTransformers.transformTo(o.transformer, a);
}
}
if (this.connection.driver.options.type === "mssql") {
a = this.connection.driver.parametrizeValues(o, a);
}
i.push(this.createWhereConditionExpression(this.getWherePredicateCondition(t, a)));
} else if (c) {
const a = this.buildWhere(e[r], t, n, s);
if (a) i.push(a);
} else if (l) {
if (typeof e[r] === "object") {
const t = Object.keys(e[r]).every(t => e[r][t] === undefined);
if (t) {
continue;
}
}
if (Ol.InstanceChecker.isFindOperator(e[r])) {
if (e[r].type === "moreThan" || e[r].type === "lessThan" || e[r].type === "moreThanOrEqual" || e[r].type === "lessThanOrEqual") {
let t = "";
if (e[r].type === "moreThan") {
t = ">";
} else if (e[r].type === "lessThan") {
t = "<";
} else if (e[r].type === "moreThanOrEqual") {
t = ">=";
} else if (e[r].type === "lessThanOrEqual") {
t = "<=";
}
const a = this.subQuery();
if (l.isManyToManyOwner) {
a.select("COUNT(*)").from(l.joinTableName, l.joinTableName).where(l.joinColumns.map(e => `${l.joinTableName}.${e.propertyName} = ${n}.${e.referencedColumn.propertyName}`).join(" AND "));
} else if (l.isManyToManyNotOwner) {
a.select("COUNT(*)").from(l.inverseRelation.joinTableName, l.inverseRelation.joinTableName).where(l.inverseRelation.inverseJoinColumns.map(e => `${l.inverseRelation.joinTableName}.${e.propertyName} = ${n}.${e.referencedColumn.propertyName}`).join(" AND "));
} else if (l.isOneToMany) {
a.select("COUNT(*)").from(l.inverseEntityMetadata.target, l.inverseEntityMetadata.tableName).where(l.inverseRelation.joinColumns.map(e => `${l.inverseEntityMetadata.tableName}.${e.propertyName} = ${n}.${e.referencedColumn.propertyName}`).join(" AND "));
} else {
throw new Error(`This relation isn't supported by given find operator`);
}
this.andWhere(a.getSql() + " " + t + " " + parseInt(e[r].value));
} else {
if (l.isManyToOne || l.isOneToOne && l.isOneToOneOwner) {
const t = `${n}.${s}`;
i.push(this.createWhereConditionExpression(this.getWherePredicateCondition(t, e[r])));
} else {
throw new Error(`This relation isn't supported by given find operator`);
}
}
} else {
let t = n + "_" + l.propertyPath.replace(".", "_");
t = bl.DriverUtils.buildAlias(this.connection.driver, {
joiner: "__"
}, n, t);
const a = this.joins.find(e => e.alias === t);
if (!a) {
this.joins.push({
type: "left",
select: false,
selection: undefined,
alias: t,
parentAlias: n,
relationMetadata: l
});
}
const s = this.buildWhere(e[r], l.inverseEntityMetadata, t);
if (s) {
i.push(s);
}
}
}
}
r = i.length ? "(" + i.join(") AND (") + ")" : i.join(" AND ");
}
return r.length ? "(" + r + ")" : r;
}
}
rl = $c.SelectQueryBuilder = SelectQueryBuilder;
var Pl = {};
var Ll = {};
Object.defineProperty(Ll, "__esModule", {
value: true
});
var Dl = Ll.UpdateResult = void 0;
class UpdateResult {
constructor() {
this.generatedMaps = [];
}
static from(e) {
const t = new this;
t.raw = e.records;
t.affected = e.affected;
return t;
}
}
Dl = Ll.UpdateResult = UpdateResult;
Object.defineProperty(Pl, "__esModule", {
value: true
});
Pl.SoftDeleteQueryBuilder = void 0;
const _l = M;
const $l = Ll;
const xl = et;
const ql = lc;
const Ul = Pe;
const Bl = He();
const Fl = re;
const jl = P;
const kl = jn;
const Ql = Te;
class SoftDeleteQueryBuilder extends _l.QueryBuilder {
constructor(e, t) {
super(e, t);
this["@instanceof"] = Symbol.for("SoftDeleteQueryBuilder");
this.expressionMap.aliasNamePrefixingEnabled = false;
}
getQuery() {
let e = this.createUpdateExpression();
e += this.createCteExpression();
e += this.createOrderByExpression();
e += this.createLimitExpression();
return this.replacePropertyNamesForTheWholeQuery(e.trim());
}
async execute() {
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
if (this.expressionMap.queryType === "soft-delete") await e.broadcaster.broadcast("BeforeSoftRemove", this.expressionMap.mainAlias.metadata); else if (this.expressionMap.queryType === "restore") await e.broadcaster.broadcast("BeforeRecover", this.expressionMap.mainAlias.metadata);
}
const n = new ql.ReturningResultsEntityUpdator(e, this.expressionMap);
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.whereEntities.length > 0) {
this.expressionMap.extraReturningColumns = n.getSoftDeletionReturningColumns();
}
const [a, r] = this.getQueryAndParameters();
const i = await e.query(a, r, true);
const s = $l.UpdateResult.from(i);
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.whereEntities.length > 0) {
await n.update(s, this.expressionMap.whereEntities);
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
if (this.expressionMap.queryType === "soft-delete") await e.broadcaster.broadcast("AfterSoftRemove", this.expressionMap.mainAlias.metadata); else if (this.expressionMap.queryType === "restore") await e.broadcaster.broadcast("AfterRecover", this.expressionMap.mainAlias.metadata);
}
if (t) await e.commitTransaction();
return s;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) {
await e.release();
}
}
}
from(e, t) {
e = Ql.InstanceChecker.isEntitySchema(e) ? e.options.name : e;
const n = this.createFromAlias(e, t);
this.expressionMap.setMainAlias(n);
return this;
}
where(e, t) {
this.expressionMap.wheres = [];
const n = this.getWhereCondition(e);
if (n) this.expressionMap.wheres = [ {
type: "simple",
condition: n
} ];
if (t) this.setParameters(t);
return this;
}
andWhere(e, t) {
this.expressionMap.wheres.push({
type: "and",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
orWhere(e, t) {
this.expressionMap.wheres.push({
type: "or",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
whereInIds(e) {
return this.where(this.getWhereInIdsCondition(e));
}
andWhereInIds(e) {
return this.andWhere(this.getWhereInIdsCondition(e));
}
orWhereInIds(e) {
return this.orWhere(this.getWhereInIdsCondition(e));
}
output(e) {
return this.returning(e);
}
returning(e) {
if (!this.connection.driver.isReturningSqlSupported("update")) {
throw new xl.ReturningStatementNotSupportedError;
}
this.expressionMap.returning = e;
return this;
}
orderBy(e, t = "ASC", n) {
if (e) {
if (typeof e === "object") {
this.expressionMap.orderBys = e;
} else {
if (n) {
this.expressionMap.orderBys = {
[e]: {
order: t,
nulls: n
}
};
} else {
this.expressionMap.orderBys = {
[e]: t
};
}
}
} else {
this.expressionMap.orderBys = {};
}
return this;
}
addOrderBy(e, t = "ASC", n) {
if (n) {
this.expressionMap.orderBys[e] = {
order: t,
nulls: n
};
} else {
this.expressionMap.orderBys[e] = t;
}
return this;
}
limit(e) {
this.expressionMap.limit = e;
return this;
}
whereEntity(e) {
if (!this.expressionMap.mainAlias.hasMetadata) throw new jl.TypeORMError(`.whereEntity method can only be used on queries which update real entity table.`);
this.expressionMap.wheres = [];
const t = Array.isArray(e) ? e : [ e ];
t.forEach(e => {
const t = this.expressionMap.mainAlias.metadata.getEntityIdMap(e);
if (!t) throw new jl.TypeORMError(`Provided entity does not have ids set, cannot perform operation.`);
this.orWhereInIds(t);
});
this.expressionMap.whereEntities = t;
return this;
}
updateEntity(e) {
this.expressionMap.updateEntity = e;
return this;
}
createUpdateExpression() {
const e = this.expressionMap.mainAlias.hasMetadata ? this.expressionMap.mainAlias.metadata : undefined;
if (!e) throw new jl.TypeORMError(`Cannot get entity metadata for the given alias "${this.expressionMap.mainAlias}"`);
if (!e.deleteDateColumn) {
throw new Bl.MissingDeleteDateColumnError(e);
}
const t = [];
switch (this.expressionMap.queryType) {
case "soft-delete":
t.push(this.escape(e.deleteDateColumn.databaseName) + " = CURRENT_TIMESTAMP");
break;
case "restore":
t.push(this.escape(e.deleteDateColumn.databaseName) + " = NULL");
break;
default:
throw new jl.TypeORMError(`The queryType must be "soft-delete" or "restore"`);
}
if (e.versionColumn) t.push(this.escape(e.versionColumn.databaseName) + " = " + this.escape(e.versionColumn.databaseName) + " + 1");
if (e.updateDateColumn) t.push(this.escape(e.updateDateColumn.databaseName) + " = CURRENT_TIMESTAMP");
if (t.length <= 0) {
throw new Fl.UpdateValuesMissingError;
}
const n = this.createWhereExpression();
const a = this.createReturningExpression("update");
if (a === "") {
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")}${n}`;
}
if (this.connection.driver.options.type === "mssql") {
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")} OUTPUT ${a}${n}`;
}
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")}${n} RETURNING ${a}`;
}
createOrderByExpression() {
const e = this.expressionMap.orderBys;
if (Object.keys(e).length > 0) return " ORDER BY " + Object.keys(e).map(t => {
if (typeof e[t] === "string") {
return this.replacePropertyNames(t) + " " + e[t];
} else {
return this.replacePropertyNames(t) + " " + e[t].order + " " + e[t].nulls;
}
}).join(", ");
return "";
}
createLimitExpression() {
const e = this.expressionMap.limit;
if (e) {
if (kl.DriverUtils.isMySQLFamily(this.connection.driver)) {
return " LIMIT " + e;
} else {
throw new Ul.LimitOnUpdateNotSupportedError;
}
}
return "";
}
}
Pl.SoftDeleteQueryBuilder = SoftDeleteQueryBuilder;
var Vl = {};
Object.defineProperty(Vl, "__esModule", {
value: true
});
var Kl = Vl.UpdateQueryBuilder = void 0;
const Wl = M;
const Hl = Ll;
const Gl = et;
const Yl = lc;
const zl = Pe;
const Jl = re;
const Xl = P;
const Zl = ht;
const eu = jn;
class UpdateQueryBuilder extends Wl.QueryBuilder {
constructor(e, t) {
super(e, t);
this["@instanceof"] = Symbol.for("UpdateQueryBuilder");
this.expressionMap.aliasNamePrefixingEnabled = false;
}
getQuery() {
let e = this.createComment();
e += this.createCteExpression();
e += this.createUpdateExpression();
e += this.createOrderByExpression();
e += this.createLimitExpression();
return this.replacePropertyNamesForTheWholeQuery(e.trim());
}
async execute() {
const e = this.obtainQueryRunner();
let t = false;
try {
if (this.expressionMap.useTransaction === true && e.isTransactionActive === false) {
await e.startTransaction();
t = true;
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
await e.broadcaster.broadcast("BeforeUpdate", this.expressionMap.mainAlias.metadata, this.expressionMap.valuesSet);
}
let n = null;
let a = null;
const r = new Yl.ReturningResultsEntityUpdator(e, this.expressionMap);
const i = [];
if (Array.isArray(this.expressionMap.returning) && this.expressionMap.mainAlias.hasMetadata) {
for (const e of this.expressionMap.returning) {
i.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(e));
}
}
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.whereEntities.length > 0) {
this.expressionMap.extraReturningColumns = r.getUpdationReturningColumns();
i.push(...this.expressionMap.extraReturningColumns.filter(e => !i.includes(e)));
}
if (i.length > 0 && this.connection.driver.options.type === "mssql") {
n = this.connection.driver.buildTableVariableDeclaration("@OutputTable", i);
a = `SELECT * FROM @OutputTable`;
}
const [s, o] = this.getQueryAndParameters();
const c = [ n, s, a ];
const l = await e.query(c.filter(e => e != null).join(";\n\n"), o, true);
const u = Hl.UpdateResult.from(l);
if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.whereEntities.length > 0) {
await r.update(u, this.expressionMap.whereEntities);
}
if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
await e.broadcaster.broadcast("AfterUpdate", this.expressionMap.mainAlias.metadata, this.expressionMap.valuesSet);
}
if (t) await e.commitTransaction();
return u;
} catch (n) {
if (t) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw n;
} finally {
if (e !== this.queryRunner) {
await e.release();
}
}
}
set(e) {
this.expressionMap.valuesSet = e;
return this;
}
where(e, t) {
this.expressionMap.wheres = [];
const n = this.getWhereCondition(e);
if (n) this.expressionMap.wheres = [ {
type: "simple",
condition: n
} ];
if (t) this.setParameters(t);
return this;
}
andWhere(e, t) {
this.expressionMap.wheres.push({
type: "and",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
orWhere(e, t) {
this.expressionMap.wheres.push({
type: "or",
condition: this.getWhereCondition(e)
});
if (t) this.setParameters(t);
return this;
}
whereInIds(e) {
return this.where(this.getWhereInIdsCondition(e));
}
andWhereInIds(e) {
return this.andWhere(this.getWhereInIdsCondition(e));
}
orWhereInIds(e) {
return this.orWhere(this.getWhereInIdsCondition(e));
}
output(e) {
return this.returning(e);
}
returning(e) {
if (!this.connection.driver.isReturningSqlSupported("update")) {
throw new Gl.ReturningStatementNotSupportedError;
}
this.expressionMap.returning = e;
return this;
}
orderBy(e, t = "ASC", n) {
if (e) {
if (typeof e === "object") {
this.expressionMap.orderBys = e;
} else {
if (n) {
this.expressionMap.orderBys = {
[e]: {
order: t,
nulls: n
}
};
} else {
this.expressionMap.orderBys = {
[e]: t
};
}
}
} else {
this.expressionMap.orderBys = {};
}
return this;
}
addOrderBy(e, t = "ASC", n) {
if (n) {
this.expressionMap.orderBys[e] = {
order: t,
nulls: n
};
} else {
this.expressionMap.orderBys[e] = t;
}
return this;
}
limit(e) {
this.expressionMap.limit = e;
return this;
}
whereEntity(e) {
if (!this.expressionMap.mainAlias.hasMetadata) throw new Xl.TypeORMError(`.whereEntity method can only be used on queries which update real entity table.`);
this.expressionMap.wheres = [];
const t = Array.isArray(e) ? e : [ e ];
t.forEach(e => {
const t = this.expressionMap.mainAlias.metadata.getEntityIdMap(e);
if (!t) throw new Xl.TypeORMError(`Provided entity does not have ids set, cannot perform operation.`);
this.orWhereInIds(t);
});
this.expressionMap.whereEntities = t;
return this;
}
updateEntity(e) {
this.expressionMap.updateEntity = e;
return this;
}
createUpdateExpression() {
const e = this.getValueSet();
const t = this.expressionMap.mainAlias.hasMetadata ? this.expressionMap.mainAlias.metadata : undefined;
const n = {};
for (const t in e) {
if (e[t] !== undefined) {
n[t] = e[t];
}
}
const a = [];
const r = [];
if (t) {
this.createPropertyPath(t, n).forEach(e => {
const i = t.findColumnsWithPropertyPath(e);
if (i.length <= 0) {
throw new Zl.EntityPropertyNotFoundError(e, t);
}
i.forEach(e => {
if (!e.isUpdate || r.includes(e)) {
return;
}
r.push(e);
let t = e.getEntityValue(n);
if (e.referencedColumn && typeof t === "object" && !(t instanceof Date) && t !== null && !Buffer.isBuffer(t)) {
t = e.referencedColumn.getEntityValue(t);
} else if (!(typeof t === "function")) {
t = this.connection.driver.preparePersistentValue(t, e);
}
if (typeof t === "function") {
a.push(this.escape(e.databaseName) + " = " + t());
} else if ((this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") && t === null) {
a.push(this.escape(e.databaseName) + " = NULL");
} else {
if (this.connection.driver.options.type === "mssql") {
t = this.connection.driver.parametrizeValue(e, t);
}
const n = this.createParameter(t);
let r = null;
if ((eu.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.spatialTypes.indexOf(e.type) !== -1) {
const t = this.connection.driver.options.legacySpatialSupport;
const a = t ? "GeomFromText" : "ST_GeomFromText";
if (e.srid != null) {
r = `${a}(${n}, ${e.srid})`;
} else {
r = `${a}(${n})`;
}
} else if (eu.DriverUtils.isPostgresFamily(this.connection.driver) && this.connection.driver.spatialTypes.indexOf(e.type) !== -1) {
if (e.srid != null) {
r = `ST_SetSRID(ST_GeomFromGeoJSON(${n}), ${e.srid})::${e.type}`;
} else {
r = `ST_GeomFromGeoJSON(${n})::${e.type}`;
}
} else if (this.connection.driver.options.type === "mssql" && this.connection.driver.spatialTypes.indexOf(e.type) !== -1) {
r = e.type + "::STGeomFromText(" + n + ", " + (e.srid || "0") + ")";
} else {
r = n;
}
a.push(this.escape(e.databaseName) + " = " + r);
}
});
});
if (a.length > 0 || Object.keys(n).length === 0) {
if (t.versionColumn && r.indexOf(t.versionColumn) === -1) a.push(this.escape(t.versionColumn.databaseName) + " = " + this.escape(t.versionColumn.databaseName) + " + 1");
if (t.updateDateColumn && r.indexOf(t.updateDateColumn) === -1) a.push(this.escape(t.updateDateColumn.databaseName) + " = CURRENT_TIMESTAMP");
}
} else {
Object.keys(n).map(e => {
const t = n[e];
if (typeof t === "function") {
a.push(this.escape(e) + " = " + t());
} else if ((this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") && t === null) {
a.push(this.escape(e) + " = NULL");
} else {
const n = this.createParameter(t);
a.push(this.escape(e) + " = " + n);
}
});
}
if (a.length <= 0) {
throw new Jl.UpdateValuesMissingError;
}
const i = this.createWhereExpression();
const s = this.createReturningExpression("update");
if (s === "") {
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${i}`;
}
if (this.connection.driver.options.type === "mssql") {
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")} OUTPUT ${s}${i}`;
}
if (this.connection.driver.options.type === "spanner") {
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${i} THEN RETURN ${s}`;
}
return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${i} RETURNING ${s}`;
}
createOrderByExpression() {
const e = this.expressionMap.orderBys;
if (Object.keys(e).length > 0) return " ORDER BY " + Object.keys(e).map(t => {
if (typeof e[t] === "string") {
return this.replacePropertyNames(t) + " " + e[t];
} else {
return this.replacePropertyNames(t) + " " + e[t].order + " " + e[t].nulls;
}
}).join(", ");
return "";
}
createLimitExpression() {
const e = this.expressionMap.limit;
if (e) {
if (eu.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") {
return " LIMIT " + e;
} else {
throw new zl.LimitOnUpdateNotSupportedError;
}
}
return "";
}
getValueSet() {
if (typeof this.expressionMap.valuesSet === "object") return this.expressionMap.valuesSet;
throw new Jl.UpdateValuesMissingError;
}
}
Kl = Vl.UpdateQueryBuilder = UpdateQueryBuilder;
Object.defineProperty(S, "__esModule", {
value: true
});
S.registerQueryBuilders = cu;
const tu = w;
const nu = oo;
const au = M;
const ru = Cc;
const iu = $c;
const su = Pl;
const ou = Vl;
function cu() {
au.QueryBuilder.registerQueryBuilderClass("DeleteQueryBuilder", e => new tu.DeleteQueryBuilder(e));
au.QueryBuilder.registerQueryBuilderClass("InsertQueryBuilder", e => new nu.InsertQueryBuilder(e));
au.QueryBuilder.registerQueryBuilderClass("RelationQueryBuilder", e => new ru.RelationQueryBuilder(e));
au.QueryBuilder.registerQueryBuilderClass("SelectQueryBuilder", e => new iu.SelectQueryBuilder(e));
au.QueryBuilder.registerQueryBuilderClass("SoftDeleteQueryBuilder", e => new su.SoftDeleteQueryBuilder(e));
au.QueryBuilder.registerQueryBuilderClass("UpdateQueryBuilder", e => new ou.UpdateQueryBuilder(e));
}
var lu = {};
var uu = {};
Object.defineProperty(uu, "__esModule", {
value: true
});
uu.RandomGenerator = void 0;
class RandomGenerator {
static sha1(e) {
const t = function(e, t) {
const n = e << t | e >>> 32 - t;
return n;
};
const n = function(e) {
let t = "";
let n;
let a;
for (n = 7; n >= 0; n--) {
a = e >>> n * 4 & 15;
t += a.toString(16);
}
return t;
};
let a;
let r, i;
const s = new Array(80);
let o = 1732584193;
let c = 4023233417;
let l = 2562383102;
let u = 271733878;
let h = 3285377520;
let d, p, m, f, y;
let E;
e = encodeURIComponent(e);
const T = e.length;
const g = [];
for (r = 0; r < T - 3; r += 4) {
i = e.charCodeAt(r) << 24 | e.charCodeAt(r + 1) << 16 | e.charCodeAt(r + 2) << 8 | e.charCodeAt(r + 3);
g.push(i);
}
switch (T % 4) {
case 0:
r = 2147483648;
break;
case 1:
r = e.charCodeAt(T - 1) << 24 | 8388608;
break;
case 2:
r = e.charCodeAt(T - 2) << 24 | e.charCodeAt(T - 1) << 16 | 32768;
break;
case 3:
r = e.charCodeAt(T - 3) << 24 | e.charCodeAt(T - 2) << 16 | e.charCodeAt(T - 1) << 8 | 128;
break;
}
g.push(r);
while (g.length % 16 !== 14) {
g.push(0);
}
g.push(T >>> 29);
g.push(T << 3 & 4294967295);
for (a = 0; a < g.length; a += 16) {
for (r = 0; r < 16; r++) {
s[r] = g[a + r];
}
for (r = 16; r <= 79; r++) {
s[r] = t(s[r - 3] ^ s[r - 8] ^ s[r - 14] ^ s[r - 16], 1);
}
d = o;
p = c;
m = l;
f = u;
y = h;
for (r = 0; r <= 19; r++) {
E = t(d, 5) + (p & m | ~p & f) + y + s[r] + 1518500249 & 4294967295;
y = f;
f = m;
m = t(p, 30);
p = d;
d = E;
}
for (r = 20; r <= 39; r++) {
E = t(d, 5) + (p ^ m ^ f) + y + s[r] + 1859775393 & 4294967295;
y = f;
f = m;
m = t(p, 30);
p = d;
d = E;
}
for (r = 40; r <= 59; r++) {
E = t(d, 5) + (p & m | p & f | m & f) + y + s[r] + 2400959708 & 4294967295;
y = f;
f = m;
m = t(p, 30);
p = d;
d = E;
}
for (r = 60; r <= 79; r++) {
E = t(d, 5) + (p ^ m ^ f) + y + s[r] + 3395469782 & 4294967295;
y = f;
f = m;
m = t(p, 30);
p = d;
d = E;
}
o = o + d & 4294967295;
c = c + p & 4294967295;
l = l + m & 4294967295;
u = u + f & 4294967295;
h = h + y & 4294967295;
}
E = n(o) + n(c) + n(l) + n(u) + n(h);
return E.toLowerCase();
}
}
uu.RandomGenerator = RandomGenerator;
Object.defineProperty(lu, "__esModule", {
value: true
});
var hu = lu.DefaultNamingStrategy = void 0;
const du = uu;
const pu = kn;
class DefaultNamingStrategy {
constructor() {
this.nestedSetColumnNames = {
left: "nsleft",
right: "nsright"
};
this.materializedPathColumnName = "mpath";
}
getTableName(e) {
if (typeof e !== "string") {
e = e.name;
}
return e.split(".").pop();
}
tableName(e, t) {
return t ? t : (0, pu.snakeCase)(e);
}
closureJunctionTableName(e) {
return e + "_closure";
}
columnName(e, t, n) {
const a = t || e;
if (n.length) return (0, pu.camelCase)(n.join("_")) + (0, pu.titleCase)(a);
return a;
}
relationName(e) {
return e;
}
primaryKeyName(e, t) {
const n = [ ...t ];
n.sort();
const a = this.getTableName(e);
const r = a.replace(".", "_");
const i = `${r}_${n.join("_")}`;
return "PK_" + du.RandomGenerator.sha1(i).substr(0, 27);
}
uniqueConstraintName(e, t) {
const n = [ ...t ];
n.sort();
const a = this.getTableName(e);
const r = a.replace(".", "_");
const i = `${r}_${n.join("_")}`;
return "UQ_" + du.RandomGenerator.sha1(i).substr(0, 27);
}
relationConstraintName(e, t, n) {
const a = [ ...t ];
a.sort();
const r = this.getTableName(e);
const i = r.replace(".", "_");
let s = `${i}_${a.join("_")}`;
if (n) s += `_${n}`;
return "REL_" + du.RandomGenerator.sha1(s).substr(0, 26);
}
defaultConstraintName(e, t) {
const n = this.getTableName(e);
const a = n.replace(".", "_");
const r = `${a}_${t}`;
return "DF_" + du.RandomGenerator.sha1(r).substr(0, 27);
}
foreignKeyName(e, t, n, a) {
const r = [ ...t ];
r.sort();
const i = this.getTableName(e);
const s = i.replace(".", "_");
const o = `${s}_${r.join("_")}`;
return "FK_" + du.RandomGenerator.sha1(o).substr(0, 27);
}
indexName(e, t, n) {
const a = [ ...t ];
a.sort();
const r = this.getTableName(e);
const i = r.replace(".", "_");
let s = `${i}_${a.join("_")}`;
if (n) s += `_${n}`;
return "IDX_" + du.RandomGenerator.sha1(s).substr(0, 26);
}
checkConstraintName(e, t, n) {
const a = this.getTableName(e);
const r = a.replace(".", "_");
const i = `${r}_${t}`;
const s = "CHK_" + du.RandomGenerator.sha1(i).substr(0, 26);
return n ? `${s}_ENUM` : s;
}
exclusionConstraintName(e, t) {
const n = this.getTableName(e);
const a = n.replace(".", "_");
const r = `${a}_${t}`;
return "XCL_" + du.RandomGenerator.sha1(r).substr(0, 26);
}
joinColumnName(e, t) {
return (0, pu.camelCase)(e + "_" + t);
}
joinTableName(e, t, n, a) {
return (0, pu.snakeCase)(e + "_" + n.replace(/\./gi, "_") + "_" + t);
}
joinTableColumnDuplicationPrefix(e, t) {
return e + "_" + t;
}
joinTableColumnName(e, t, n) {
return (0, pu.camelCase)(e + "_" + (n ? n : t));
}
joinTableInverseColumnName(e, t, n) {
return this.joinTableColumnName(e, t, n);
}
prefixTableName(e, t) {
return e + t;
}
}
hu = lu.DefaultNamingStrategy = DefaultNamingStrategy;
var mu = {};
var fu = {};
var yu = {};
Object.defineProperty(yu, "__esModule", {
value: true
});
var Eu = yu.TableColumn = void 0;
class TableColumn {
constructor(e) {
this["@instanceof"] = Symbol.for("TableColumn");
this.isNullable = false;
this.isGenerated = false;
this.isPrimary = false;
this.isUnique = false;
this.isArray = false;
this.length = "";
this.zerofill = false;
this.unsigned = false;
if (e) {
this.name = e.name;
this.type = e.type || "";
this.length = e.length || "";
this.width = e.width;
this.charset = e.charset;
this.collation = e.collation;
this.precision = e.precision;
this.scale = e.scale;
this.zerofill = e.zerofill || false;
this.unsigned = this.zerofill ? true : e.unsigned || false;
this.default = e.default;
this.onUpdate = e.onUpdate;
this.isNullable = e.isNullable || false;
this.isGenerated = e.isGenerated || false;
this.generationStrategy = e.generationStrategy;
this.generatedIdentity = e.generatedIdentity;
this.isPrimary = e.isPrimary || false;
this.isUnique = e.isUnique || false;
this.isArray = e.isArray || false;
this.comment = e.comment;
this.enum = e.enum;
this.enumName = e.enumName;
this.primaryKeyConstraintName = e.primaryKeyConstraintName;
this.asExpression = e.asExpression;
this.generatedType = e.generatedType;
this.spatialFeatureType = e.spatialFeatureType;
this.srid = e.srid;
}
}
clone() {
return new TableColumn({
name: this.name,
type: this.type,
length: this.length,
width: this.width,
charset: this.charset,
collation: this.collation,
precision: this.precision,
scale: this.scale,
zerofill: this.zerofill,
unsigned: this.unsigned,
enum: this.enum,
enumName: this.enumName,
primaryKeyConstraintName: this.primaryKeyConstraintName,
asExpression: this.asExpression,
generatedType: this.generatedType,
default: this.default,
onUpdate: this.onUpdate,
isNullable: this.isNullable,
isGenerated: this.isGenerated,
generationStrategy: this.generationStrategy,
generatedIdentity: this.generatedIdentity,
isPrimary: this.isPrimary,
isUnique: this.isUnique,
isArray: this.isArray,
comment: this.comment,
spatialFeatureType: this.spatialFeatureType,
srid: this.srid
});
}
}
Eu = yu.TableColumn = TableColumn;
var Tu = {};
Object.defineProperty(Tu, "__esModule", {
value: true
});
var gu = Tu.TableIndex = void 0;
class TableIndex {
constructor(e) {
this["@instanceof"] = Symbol.for("TableIndex");
this.columnNames = [];
this.name = e.name;
this.columnNames = e.columnNames;
this.isUnique = !!e.isUnique;
this.isSpatial = !!e.isSpatial;
this.isConcurrent = !!e.isConcurrent;
this.isFulltext = !!e.isFulltext;
this.isNullFiltered = !!e.isNullFiltered;
this.parser = e.parser;
this.where = e.where ? e.where : "";
}
clone() {
return new TableIndex({
name: this.name,
columnNames: [ ...this.columnNames ],
isUnique: this.isUnique,
isSpatial: this.isSpatial,
isConcurrent: this.isConcurrent,
isFulltext: this.isFulltext,
isNullFiltered: this.isNullFiltered,
parser: this.parser,
where: this.where
});
}
static create(e) {
return new TableIndex({
name: e.name,
columnNames: e.columns.map(e => e.databaseName),
isUnique: e.isUnique,
isSpatial: e.isSpatial,
isConcurrent: e.isConcurrent,
isFulltext: e.isFulltext,
isNullFiltered: e.isNullFiltered,
parser: e.parser,
where: e.where
});
}
}
gu = Tu.TableIndex = TableIndex;
var Nu = {};
Object.defineProperty(Nu, "__esModule", {
value: true
});
var Au = Nu.TableForeignKey = void 0;
class TableForeignKey {
constructor(e) {
this["@instanceof"] = Symbol.for("TableForeignKey");
this.columnNames = [];
this.referencedColumnNames = [];
this.name = e.name;
this.columnNames = e.columnNames;
this.referencedColumnNames = e.referencedColumnNames;
this.referencedDatabase = e.referencedDatabase;
this.referencedSchema = e.referencedSchema;
this.referencedTableName = e.referencedTableName;
this.onDelete = e.onDelete;
this.onUpdate = e.onUpdate;
this.deferrable = e.deferrable;
}
clone() {
return new TableForeignKey({
name: this.name,
columnNames: [ ...this.columnNames ],
referencedColumnNames: [ ...this.referencedColumnNames ],
referencedDatabase: this.referencedDatabase,
referencedSchema: this.referencedSchema,
referencedTableName: this.referencedTableName,
onDelete: this.onDelete,
onUpdate: this.onUpdate,
deferrable: this.deferrable
});
}
static create(e, t) {
return new TableForeignKey({
name: e.name,
columnNames: e.columnNames,
referencedColumnNames: e.referencedColumnNames,
referencedDatabase: e.referencedEntityMetadata.database,
referencedSchema: e.referencedEntityMetadata.schema,
referencedTableName: e.referencedTablePath,
onDelete: e.onDelete,
onUpdate: e.onUpdate,
deferrable: e.deferrable
});
}
}
Au = Nu.TableForeignKey = TableForeignKey;
var bu = {};
Object.defineProperty(bu, "__esModule", {
value: true
});
bu.TableUtils = void 0;
class TableUtils {
static createTableColumnOptions(e, t) {
return {
name: e.databaseName,
length: t.getColumnLength(e),
width: e.width,
charset: e.charset,
collation: e.collation,
precision: e.precision,
scale: e.scale,
zerofill: e.zerofill,
unsigned: e.unsigned,
asExpression: e.asExpression,
generatedType: e.generatedType,
default: t.normalizeDefault(e),
onUpdate: e.onUpdate,
comment: e.comment,
isGenerated: e.isGenerated,
generationStrategy: e.generationStrategy,
generatedIdentity: e.generatedIdentity,
isNullable: e.isNullable,
type: t.normalizeType(e),
isPrimary: e.isPrimary,
isUnique: t.normalizeIsUnique(e),
isArray: e.isArray || false,
enum: e.enum ? e.enum.map(e => e + "") : e.enum,
enumName: e.enumName,
primaryKeyConstraintName: e.primaryKeyConstraintName,
spatialFeatureType: e.spatialFeatureType,
srid: e.srid
};
}
}
bu.TableUtils = TableUtils;
var Cu = {};
Object.defineProperty(Cu, "__esModule", {
value: true
});
var Ru = Cu.TableUnique = void 0;
class TableUnique {
constructor(e) {
this["@instanceof"] = Symbol.for("TableUnique");
this.columnNames = [];
this.name = e.name;
this.columnNames = e.columnNames;
this.deferrable = e.deferrable;
}
clone() {
return new TableUnique({
name: this.name,
columnNames: [ ...this.columnNames ],
deferrable: this.deferrable
});
}
static create(e) {
return new TableUnique({
name: e.name,
columnNames: e.columns.map(e => e.databaseName),
deferrable: e.deferrable
});
}
}
Ru = Cu.TableUnique = TableUnique;
var Su = {};
Object.defineProperty(Su, "__esModule", {
value: true
});
var wu = Su.TableCheck = void 0;
class TableCheck {
constructor(e) {
this["@instanceof"] = Symbol.for("TableCheck");
this.columnNames = [];
this.name = e.name;
this.columnNames = e.columnNames;
this.expression = e.expression;
}
clone() {
return new TableCheck({
name: this.name,
columnNames: this.columnNames ? [ ...this.columnNames ] : [],
expression: this.expression
});
}
static create(e) {
return new TableCheck({
name: e.name,
expression: e.expression
});
}
}
wu = Su.TableCheck = TableCheck;
var Mu = {};
Object.defineProperty(Mu, "__esModule", {
value: true
});
var Ou = Mu.TableExclusion = void 0;
class TableExclusion {
constructor(e) {
this["@instanceof"] = Symbol.for("TableExclusion");
this.name = e.name;
this.expression = e.expression;
}
clone() {
return new TableExclusion({
name: this.name,
expression: this.expression
});
}
static create(e) {
return new TableExclusion({
name: e.name,
expression: e.expression
});
}
}
Ou = Mu.TableExclusion = TableExclusion;
Object.defineProperty(fu, "__esModule", {
value: true
});
var vu = fu.Table = void 0;
const Iu = yu;
const Pu = Tu;
const Lu = Nu;
const Du = bu;
const _u = Cu;
const $u = Su;
const xu = Mu;
class Table {
constructor(e) {
this["@instanceof"] = Symbol.for("Table");
this.columns = [];
this.indices = [];
this.foreignKeys = [];
this.uniques = [];
this.checks = [];
this.exclusions = [];
this.justCreated = false;
this.withoutRowid = false;
if (e) {
this.database = e.database;
this.schema = e.schema;
this.name = e.name;
if (e.columns) this.columns = e.columns.map(e => new Iu.TableColumn(e));
if (e.indices) this.indices = e.indices.map(e => new Pu.TableIndex(e));
if (e.foreignKeys) this.foreignKeys = e.foreignKeys.map(t => new Lu.TableForeignKey({
...t,
referencedDatabase: t?.referencedDatabase || e.database,
referencedSchema: t?.referencedSchema || e.schema
}));
if (e.uniques) this.uniques = e.uniques.map(e => new _u.TableUnique(e));
if (e.checks) this.checks = e.checks.map(e => new $u.TableCheck(e));
if (e.exclusions) this.exclusions = e.exclusions.map(e => new xu.TableExclusion(e));
if (e.justCreated !== undefined) this.justCreated = e.justCreated;
if (e.withoutRowid) this.withoutRowid = e.withoutRowid;
this.engine = e.engine;
this.comment = e.comment;
}
}
get primaryColumns() {
return this.columns.filter(e => e.isPrimary);
}
clone() {
return new Table({
schema: this.schema,
database: this.database,
name: this.name,
columns: this.columns.map(e => e.clone()),
indices: this.indices.map(e => e.clone()),
foreignKeys: this.foreignKeys.map(e => e.clone()),
uniques: this.uniques.map(e => e.clone()),
checks: this.checks.map(e => e.clone()),
exclusions: this.exclusions.map(e => e.clone()),
justCreated: this.justCreated,
withoutRowid: this.withoutRowid,
engine: this.engine,
comment: this.comment
});
}
addColumn(e) {
this.columns.push(e);
}
removeColumn(e) {
const t = this.columns.find(t => t.name === e.name);
if (t) this.columns.splice(this.columns.indexOf(t), 1);
}
addUniqueConstraint(e) {
this.uniques.push(e);
if (e.columnNames.length === 1) {
const t = this.columns.find(t => t.name === e.columnNames[0]);
if (t) t.isUnique = true;
}
}
removeUniqueConstraint(e) {
const t = this.uniques.find(t => t.name === e.name);
if (t) {
this.uniques.splice(this.uniques.indexOf(t), 1);
if (t.columnNames.length === 1) {
const e = this.columns.find(e => e.name === t.columnNames[0]);
if (e) e.isUnique = false;
}
}
}
addCheckConstraint(e) {
this.checks.push(e);
}
removeCheckConstraint(e) {
const t = this.checks.find(t => t.name === e.name);
if (t) {
this.checks.splice(this.checks.indexOf(t), 1);
}
}
addExclusionConstraint(e) {
this.exclusions.push(e);
}
removeExclusionConstraint(e) {
const t = this.exclusions.find(t => t.name === e.name);
if (t) {
this.exclusions.splice(this.exclusions.indexOf(t), 1);
}
}
addForeignKey(e) {
this.foreignKeys.push(e);
}
removeForeignKey(e) {
const t = this.foreignKeys.find(t => t.name === e.name);
if (t) this.foreignKeys.splice(this.foreignKeys.indexOf(t), 1);
}
addIndex(e, t = false) {
this.indices.push(e);
if (e.columnNames.length === 1 && e.isUnique && t) {
const t = this.columns.find(t => t.name === e.columnNames[0]);
if (t) t.isUnique = true;
}
}
removeIndex(e, t = false) {
const n = this.indices.find(t => t.name === e.name);
if (n) {
this.indices.splice(this.indices.indexOf(n), 1);
if (n.columnNames.length === 1 && n.isUnique && t) {
const e = this.columns.find(e => e.name === n.columnNames[0]);
if (e) e.isUnique = this.indices.some(t => t.columnNames.length === 1 && t.columnNames[0] === e.name && !!n.isUnique);
}
}
}
findColumnByName(e) {
return this.columns.find(t => t.name === e);
}
findColumnIndices(e) {
return this.indices.filter(t => !!t.columnNames.find(t => t === e.name));
}
findColumnForeignKeys(e) {
return this.foreignKeys.filter(t => !!t.columnNames.find(t => t === e.name));
}
findColumnUniques(e) {
return this.uniques.filter(t => !!t.columnNames.find(t => t === e.name));
}
findColumnChecks(e) {
return this.checks.filter(t => !!t.columnNames.find(t => t === e.name));
}
static create(e, t) {
const n = e.database === t.database ? undefined : e.database;
const a = e.schema === t.options.schema ? undefined : e.schema;
const r = {
database: e.database,
schema: e.schema,
name: t.buildTableName(e.tableName, a, n),
withoutRowid: e.withoutRowid,
engine: e.engine,
columns: e.columns.filter(e => e && !e.isVirtualProperty).map(e => Du.TableUtils.createTableColumnOptions(e, t)),
indices: e.indices.filter(e => e.synchronize === true).map(e => Pu.TableIndex.create(e)),
uniques: e.uniques.map(e => _u.TableUnique.create(e)),
checks: e.checks.map(e => $u.TableCheck.create(e)),
exclusions: e.exclusions.map(e => xu.TableExclusion.create(e)),
comment: e.comment
};
return new Table(r);
}
}
vu = fu.Table = Table;
var qu = {};
Object.defineProperty(qu, "__esModule", {
value: true
});
var Uu = qu.Migration = void 0;
class Migration {
constructor(e, t, n, a, r) {
this.id = e;
this.timestamp = t;
this.name = n;
this.instance = a;
this.transaction = r;
}
}
Uu = qu.Migration = Migration;
var Bu = {};
Object.defineProperty(Bu, "__esModule", {
value: true
});
var Fu = Bu.MssqlParameter = void 0;
class MssqlParameter {
constructor(e, t, ...n) {
this.value = e;
this.type = t;
this["@instanceof"] = Symbol.for("MssqlParameter");
this.params = [];
this.params = n || [];
}
}
Fu = Bu.MssqlParameter = MssqlParameter;
Object.defineProperty(mu, "__esModule", {
value: true
});
var ju = mu.MigrationExecutor = void 0;
const ku = fu;
const Qu = qu;
const Vu = Bu;
const Ku = P;
const Wu = Te;
class MigrationExecutor {
constructor(e, t) {
this.connection = e;
this.queryRunner = t;
this.transaction = "all";
const {schema: n} = this.connection.driver.options;
const a = this.connection.driver.database;
this.migrationsDatabase = a;
this.migrationsSchema = n;
this.migrationsTableName = e.options.migrationsTableName || "migrations";
this.migrationsTable = this.connection.driver.buildTableName(this.migrationsTableName, n, a);
}
async executeMigration(e) {
return this.withQueryRunner(async t => {
await this.createMigrationsTableIfNotExist(t);
const n = this.connection.driver.createSchemaBuilder();
if (Wu.InstanceChecker.isRdbmsSchemaBuilder(n)) {
await n.createMetadataTableIfNecessary(t);
}
await t.beforeMigration();
await e.instance.up(t);
await t.afterMigration();
await this.insertExecutedMigration(t, e);
return e;
});
}
async getAllMigrations() {
return Promise.resolve(this.getMigrations());
}
async getExecutedMigrations() {
return this.withQueryRunner(async e => {
await this.createMigrationsTableIfNotExist(e);
return await this.loadExecutedMigrations(e);
});
}
async getPendingMigrations() {
const e = await this.getAllMigrations();
const t = await this.getExecutedMigrations();
return e.filter(e => !t.find(t => t.name === e.name));
}
insertMigration(e) {
return this.withQueryRunner(t => this.insertExecutedMigration(t, e));
}
deleteMigration(e) {
return this.withQueryRunner(t => this.deleteExecutedMigration(t, e));
}
async showMigrations() {
let e = false;
const t = this.queryRunner || this.connection.createQueryRunner();
await this.createMigrationsTableIfNotExist(t);
const n = await this.loadExecutedMigrations(t);
const a = this.getMigrations();
for (const t of a) {
const a = n.find(e => e.name === t.name);
if (a) {
this.connection.logger.logSchemaBuild(`[X] ${a.id} ${t.name}`);
} else {
e = true;
this.connection.logger.logSchemaBuild(`[ ] ${t.name}`);
}
}
if (!this.queryRunner) {
await t.release();
}
return e;
}
async executePendingMigrations() {
const e = this.queryRunner || this.connection.createQueryRunner();
await this.createMigrationsTableIfNotExist(e);
const t = this.connection.driver.createSchemaBuilder();
if (Wu.InstanceChecker.isRdbmsSchemaBuilder(t)) {
await t.createMetadataTableIfNecessary(e);
}
const n = await this.loadExecutedMigrations(e);
const a = this.getLatestTimestampMigration(n);
const r = this.getMigrations();
const i = [];
const s = r.filter(e => {
const t = n.find(t => t.name === e.name);
if (t) return false;
return true;
});
if (!s.length) {
this.connection.logger.logSchemaBuild(`No migrations are pending`);
if (!this.queryRunner) await e.release();
return [];
}
this.connection.logger.logSchemaBuild(`${n.length} migrations are already loaded in the database.`);
this.connection.logger.logSchemaBuild(`${r.length} migrations were found in the source code.`);
if (a) this.connection.logger.logSchemaBuild(`${a.name} is the last executed migration. It was executed on ${new Date(a.timestamp).toString()}.`);
this.connection.logger.logSchemaBuild(`${s.length} migrations are new migrations must be executed.`);
if (this.transaction === "all") {
const e = s.filter(e => !(e.instance?.transaction === undefined));
if (e.length > 0) {
const t = new Ku.ForbiddenTransactionModeOverrideError(e);
this.connection.logger.logMigration(`Migrations failed, error: ${t.message}`);
throw t;
}
}
const o = {
each: true,
none: false,
all: false
}[this.transaction];
for (const e of s) {
if (e.instance) {
const t = e.instance.transaction;
if (t === undefined) {
e.transaction = o;
} else {
e.transaction = t;
}
}
}
let c = false;
if (this.transaction === "all" && !e.isTransactionActive) {
await e.beforeMigration();
await e.startTransaction();
c = true;
}
try {
for (const t of s) {
if (this.fake) {
await this.insertExecutedMigration(e, t);
continue;
}
if (t.transaction && !e.isTransactionActive) {
await e.beforeMigration();
await e.startTransaction();
c = true;
}
await t.instance.up(e).catch(e => {
this.connection.logger.logMigration(`Migration "${t.name}" failed, error: ${e?.message}`);
throw e;
}).then(async () => {
await this.insertExecutedMigration(e, t);
if (t.transaction && c) {
await e.commitTransaction();
await e.afterMigration();
}
}).then(() => {
i.push(t);
this.connection.logger.logSchemaBuild(`Migration ${t.name} has been ${this.fake ? "(fake) " : ""}executed successfully.`);
});
}
if (this.transaction === "all" && c) {
await e.commitTransaction();
await e.afterMigration();
}
} catch (t) {
if (c) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw t;
} finally {
if (!this.queryRunner) await e.release();
}
return i;
}
async undoLastMigration() {
const e = this.queryRunner || this.connection.createQueryRunner();
await this.createMigrationsTableIfNotExist(e);
const t = this.connection.driver.createSchemaBuilder();
if (Wu.InstanceChecker.isRdbmsSchemaBuilder(t)) {
await t.createMetadataTableIfNecessary(e);
}
const n = await this.loadExecutedMigrations(e);
const a = this.getLatestExecutedMigration(n);
if (!a) {
this.connection.logger.logSchemaBuild(`No migrations were found in the database. Nothing to revert!`);
return;
}
const r = this.getMigrations();
const i = r.find(e => e.name === a.name);
if (!i) throw new Ku.TypeORMError(`No migration ${a.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`);
this.connection.logger.logSchemaBuild(`${n.length} migrations are already loaded in the database.`);
this.connection.logger.logSchemaBuild(`${a.name} is the last executed migration. It was executed on ${new Date(a.timestamp).toString()}.`);
this.connection.logger.logSchemaBuild(`Now reverting it...`);
let s = false;
if (this.transaction !== "none" && !e.isTransactionActive) {
await e.startTransaction();
s = true;
}
try {
if (!this.fake) {
await e.beforeMigration();
await i.instance.down(e);
await e.afterMigration();
}
await this.deleteExecutedMigration(e, i);
this.connection.logger.logSchemaBuild(`Migration ${i.name} has been ${this.fake ? "(fake) " : ""}reverted successfully.`);
if (s) await e.commitTransaction();
} catch (t) {
if (s) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw t;
} finally {
if (!this.queryRunner) await e.release();
}
}
async createMigrationsTableIfNotExist(e) {
if (this.connection.driver.options.type === "mongodb") {
return;
}
const t = await e.hasTable(this.migrationsTable);
if (!t) {
await e.createTable(new ku.Table({
database: this.migrationsDatabase,
schema: this.migrationsSchema,
name: this.migrationsTable,
columns: [ {
name: "id",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationId
}),
isGenerated: true,
generationStrategy: "increment",
isPrimary: true,
isNullable: false
}, {
name: "timestamp",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationTimestamp
}),
isPrimary: false,
isNullable: false
}, {
name: "name",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName
}),
isNullable: false
} ]
}));
}
}
async loadExecutedMigrations(e) {
if (this.connection.driver.options.type === "mongodb") {
const t = e;
return t.cursor(this.migrationsTableName, {}).sort({
_id: -1
}).toArray();
} else {
const t = await this.connection.manager.createQueryBuilder(e).select().orderBy(this.connection.driver.escape("id"), "DESC").from(this.migrationsTable, this.migrationsTableName).getRawMany();
return t.map(e => new Qu.Migration(parseInt(e["id"]), parseInt(e["timestamp"]), e["name"]));
}
}
getMigrations() {
const e = this.connection.migrations.map(e => {
const t = e.name || e.constructor.name;
const n = parseInt(t.substr(-13), 10);
if (!n || isNaN(n)) {
throw new Ku.TypeORMError(`${t} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`);
}
return new Qu.Migration(undefined, n, t, e);
});
this.checkForDuplicateMigrations(e);
return e.sort((e, t) => e.timestamp - t.timestamp);
}
checkForDuplicateMigrations(e) {
const t = e.map(e => e.name);
const n = Array.from(new Set(t.filter((e, n) => t.indexOf(e) < n)));
if (n.length > 0) {
throw Error(`Duplicate migrations: ${n.join(", ")}`);
}
}
getLatestTimestampMigration(e) {
const t = e.map(e => e).sort((e, t) => (e.timestamp - t.timestamp) * -1);
return t.length > 0 ? t[0] : undefined;
}
getLatestExecutedMigration(e) {
return e.length > 0 ? e[0] : undefined;
}
async insertExecutedMigration(e, t) {
const n = {};
if (this.connection.driver.options.type === "mssql") {
n["timestamp"] = new Vu.MssqlParameter(t.timestamp, this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationTimestamp
}));
n["name"] = new Vu.MssqlParameter(t.name, this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName
}));
} else {
n["timestamp"] = t.timestamp;
n["name"] = t.name;
}
if (this.connection.driver.options.type === "mongodb") {
const t = e;
await t.databaseConnection.db(this.connection.driver.database).collection(this.migrationsTableName).insertOne(n);
} else {
const t = e.manager.createQueryBuilder();
await t.insert().into(this.migrationsTable).values(n).execute();
}
}
async deleteExecutedMigration(e, t) {
const n = {};
if (this.connection.driver.options.type === "mssql") {
n["timestamp"] = new Vu.MssqlParameter(t.timestamp, this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationTimestamp
}));
n["name"] = new Vu.MssqlParameter(t.name, this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName
}));
} else {
n["timestamp"] = t.timestamp;
n["name"] = t.name;
}
if (this.connection.driver.options.type === "mongodb") {
const t = e;
await t.databaseConnection.db(this.connection.driver.database).collection(this.migrationsTableName).deleteOne(n);
} else {
const t = e.manager.createQueryBuilder();
await t.delete().from(this.migrationsTable).where(`${t.escape("timestamp")} = :timestamp`).andWhere(`${t.escape("name")} = :name`).setParameters(n).execute();
}
}
async withQueryRunner(e) {
const t = this.queryRunner || this.connection.createQueryRunner();
try {
return await e(t);
} finally {
if (!this.queryRunner) {
await t.release();
}
}
}
}
ju = mu.MigrationExecutor = MigrationExecutor;
var Hu = {};
var Gu = {};
Object.defineProperty(Gu, "__esModule", {
value: true
});
Gu.DepGraph = void 0;
const Yu = P;
function zu(e, t, n) {
const a = [];
const r = {};
return function i(s) {
r[s] = true;
a.push(s);
e[s].forEach(function(e) {
if (!r[e]) {
i(e);
} else if (a.indexOf(e) >= 0) {
a.push(e);
throw new Yu.TypeORMError(`Dependency Cycle Found: ${a.join(" -> ")}`);
}
});
a.pop();
if ((!t || e[s].length === 0) && n.indexOf(s) === -1) {
n.push(s);
}
};
}
class DepGraph {
constructor() {
this.nodes = {};
this.outgoingEdges = {};
this.incomingEdges = {};
}
addNode(e, t) {
if (!this.hasNode(e)) {
if (arguments.length === 2) {
this.nodes[e] = t;
} else {
this.nodes[e] = e;
}
this.outgoingEdges[e] = [];
this.incomingEdges[e] = [];
}
}
removeNode(e) {
if (this.hasNode(e)) {
delete this.nodes[e];
delete this.outgoingEdges[e];
delete this.incomingEdges[e];
[ this.incomingEdges, this.outgoingEdges ].forEach(function(t) {
Object.keys(t).forEach(function(n) {
const a = t[n].indexOf(e);
if (a >= 0) {
t[n].splice(a, 1);
}
});
});
}
}
hasNode(e) {
return this.nodes.hasOwnProperty(e);
}
getNodeData(e) {
if (this.hasNode(e)) {
return this.nodes[e];
} else {
throw new Yu.TypeORMError(`Node does not exist: ${e}`);
}
}
setNodeData(e, t) {
if (this.hasNode(e)) {
this.nodes[e] = t;
} else {
throw new Yu.TypeORMError(`Node does not exist: ${e}`);
}
}
addDependency(e, t) {
if (!this.hasNode(e)) {
throw new Yu.TypeORMError(`Node does not exist: ${e}`);
}
if (!this.hasNode(t)) {
throw new Yu.TypeORMError(`Node does not exist: ${t}`);
}
if (this.outgoingEdges[e].indexOf(t) === -1) {
this.outgoingEdges[e].push(t);
}
if (this.incomingEdges[t].indexOf(e) === -1) {
this.incomingEdges[t].push(e);
}
return true;
}
removeDependency(e, t) {
let n;
if (this.hasNode(e)) {
n = this.outgoingEdges[e].indexOf(t);
if (n >= 0) {
this.outgoingEdges[e].splice(n, 1);
}
}
if (this.hasNode(t)) {
n = this.incomingEdges[t].indexOf(e);
if (n >= 0) {
this.incomingEdges[t].splice(n, 1);
}
}
}
dependenciesOf(e, t) {
if (this.hasNode(e)) {
const n = [];
const a = zu(this.outgoingEdges, t, n);
a(e);
const r = n.indexOf(e);
if (r >= 0) {
n.splice(r, 1);
}
return n;
} else {
throw new Yu.TypeORMError(`Node does not exist: ${e}`);
}
}
dependantsOf(e, t) {
if (this.hasNode(e)) {
const n = [];
const a = zu(this.incomingEdges, t, n);
a(e);
const r = n.indexOf(e);
if (r >= 0) {
n.splice(r, 1);
}
return n;
} else {
throw new Yu.TypeORMError(`Node does not exist: ${e}`);
}
}
overallOrder(e) {
const t = this;
const n = [];
const a = Object.keys(this.nodes);
if (a.length === 0) {
return n;
} else {
const r = zu(this.outgoingEdges, false, []);
a.forEach(function(e) {
r(e);
});
const i = zu(this.outgoingEdges, e, n);
a.filter(function(e) {
return t.incomingEdges[e].length === 0;
}).forEach(function(e) {
i(e);
});
return n;
}
}
}
Gu.DepGraph = DepGraph;
Object.defineProperty(Hu, "__esModule", {
value: true
});
Hu.EntityMetadataValidator = void 0;
const Ju = ut();
const Xu = Ze();
const Zu = Gu;
const eh = Ht();
const th = Dn();
const nh = zt();
const ah = P;
const rh = jn;
class EntityMetadataValidator {
validateMany(e, t) {
e.forEach(n => this.validate(n, e, t));
this.validateDependencies(e);
this.validateEagerRelations(e);
}
validate(e, t, n) {
if (!e.primaryColumns.length && !e.isJunction) throw new Ju.MissingPrimaryColumnError(e);
if (e.primaryColumns.length > 1) {
const t = e.primaryColumns.every((e, t, n) => e.primaryKeyConstraintName === n[0].primaryKeyConstraintName);
if (!t) {
throw new ah.TypeORMError(`Entity ${e.name} has multiple primary columns with different constraint names. Constraint names should be the equal.`);
}
}
if (e.inheritancePattern === "STI" || e.tableType === "entity-child") {
if (!e.discriminatorColumn) throw new ah.TypeORMError(`Entity ${e.name} using single-table inheritance, it should also have a discriminator column. Did you forget to put discriminator column options?`);
if (typeof e.discriminatorValue === "undefined") throw new ah.TypeORMError(`Entity ${e.name} has an undefined discriminator value. Discriminator value should be defined.`);
const n = t.find(t => t !== e && (t.inheritancePattern === "STI" || t.tableType === "entity-child") && t.tableName === e.tableName && t.discriminatorValue === e.discriminatorValue && t.inheritanceTree.some(t => e.inheritanceTree.indexOf(t) !== -1));
if (n) throw new ah.TypeORMError(`Entities ${e.name} and ${n.name} have the same discriminator values. Make sure they are different while using the @ChildEntity decorator.`);
}
e.relationCounts.forEach(e => {
if (e.relation.isManyToOne || e.relation.isOneToOne) throw new ah.TypeORMError(`Relation count can not be implemented on ManyToOne or OneToOne relations.`);
});
if (!(n.options.type === "mongodb")) {
e.columns.filter(e => !e.isVirtualProperty).forEach(t => {
const a = n.normalizeType(t);
if (n.supportedDataTypes.indexOf(a) === -1) throw new eh.DataTypeNotSupportedError(t, a, n.options.type);
if (t.length && n.withLengthColumnTypes.indexOf(a) === -1) throw new ah.TypeORMError(`Column ${t.propertyName} of Entity ${e.name} does not support length property.`);
if (t.type === "enum" && !t.enum && !t.enumName) throw new ah.TypeORMError(`Column "${t.propertyName}" of Entity "${e.name}" is defined as enum, but missing "enum" or "enumName" properties.`);
});
}
if (rh.DriverUtils.isMySQLFamily(n) || n.options.type === "aurora-mysql") {
const t = e.columns.filter(e => e.isGenerated && e.generationStrategy !== "uuid");
if (t.length > 1) throw new ah.TypeORMError(`Error in ${e.name} entity. There can be only one auto-increment column in MySql table.`);
}
if (rh.DriverUtils.isMySQLFamily(n)) {
const e = t.filter(e => e.database);
if (e.length === 0 && !n.database) throw new th.NoConnectionOptionError("database");
}
if (n.options.type === "mssql") {
const t = e.columns.filter(e => e.charset);
if (t.length > 1) throw new ah.TypeORMError(`Character set specifying is not supported in Sql Server`);
}
if (n.options.type === "postgres") {
const t = e.columns.find(e => e.asExpression && (!e.generatedType || e.generatedType === "VIRTUAL"));
if (t) throw new ah.TypeORMError(`Column "${t.propertyName}" of Entity "${e.name}" is defined as VIRTUAL, but Postgres supports only STORED generated columns.`);
}
const a = e.create(undefined, {
fromDeserializer: true
});
e.relations.forEach(e => {
if (e.isManyToMany || e.isOneToMany) {
if (e.persistenceEnabled === false) return;
const t = e.getEntityValue(a);
if (Array.isArray(t)) throw new nh.InitializedRelationError(e);
}
});
e.relations.forEach(e => {
if (n.supportedOnDeleteTypes && e.onDelete && !n.supportedOnDeleteTypes.includes(e.onDelete)) {
throw new ah.TypeORMError(`OnDeleteType "${e.onDelete}" is not supported for ${n.options.type}!`);
}
if (n.supportedOnUpdateTypes && e.onUpdate && !n.supportedOnUpdateTypes.includes(e.onUpdate)) {
throw new ah.TypeORMError(`OnUpdateType "${e.onUpdate}" is not valid for ${n.options.type}!`);
}
});
e.relations.forEach(t => {
const n = t.isCascadeRemove && t.inverseRelation && t.inverseRelation.isCascadeRemove;
if (n) throw new ah.TypeORMError(`Relation ${e.name}#${t.propertyName} and ${t.inverseRelation.entityMetadata.name}#${t.inverseRelation.propertyName} both has cascade remove set. ` + `This may lead to unexpected circular removals. Please set cascade remove only from one side of relationship.`);
});
e.eagerRelations.forEach(e => {});
}
validateDependencies(e) {
const t = new Zu.DepGraph;
e.forEach(e => {
t.addNode(e.name);
});
e.forEach(e => {
e.relationsWithJoinColumns.filter(e => !e.isNullable).forEach(n => {
t.addDependency(e.name, n.inverseEntityMetadata.name);
});
});
try {
t.overallOrder();
} catch (e) {
throw new Xu.CircularRelationsError(e.toString().replace("Error: Dependency Cycle Found: ", ""));
}
}
validateEagerRelations(e) {
e.forEach(e => {
e.eagerRelations.forEach(t => {
if (t.inverseRelation && t.inverseRelation.isEager) throw new ah.TypeORMError(`Circular eager relations are disallowed. ` + `${e.targetName}#${t.propertyPath} contains "eager: true", and its inverse side ` + `${t.inverseEntityMetadata.targetName}#${t.inverseRelation.propertyPath} contains "eager: true" as well.` + ` Remove "eager: true" from one side of the relation.`);
});
});
}
}
Hu.EntityMetadataValidator = EntityMetadataValidator;
var ih = {};
var sh = {};
var oh = {};
var ch = {};
var lh = {};
var uh = {
exports: {}
};
uh.exports;
var hh;
function dh() {
if (hh) return uh.exports;
hh = 1;
(function(e, t) {
Object.defineProperty(t, "__esModule", {
value: true
});
t.default = void 0;
const n = a({});
t.default = n;
function a(e) {
t.withOptions = t => a({
...e,
...t
});
return t;
function t(t, ...n) {
const a = typeof t === "string" ? [ t ] : t.raw;
const {alignValues: i = false, escapeSpecialCharacters: s = Array.isArray(t), trimWhitespace: o = true} = e;
let c = "";
for (let e = 0; e < a.length; e++) {
let t = a[e];
if (s) {
t = t.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
}
c += t;
if (e < n.length) {
const t = i ? r(n[e], c) : n[e];
c += t;
}
}
const l = c.split("\n");
let u = null;
for (const e of l) {
const t = e.match(/^(\s+)\S+/);
if (t) {
const e = t[1].length;
if (!u) {
u = e;
} else {
u = Math.min(u, e);
}
}
}
if (u !== null) {
const e = u;
c = l.map(t => t[0] === " " || t[0] === "\t" ? t.slice(e) : t).join("\n");
}
if (o) {
c = c.trim();
}
if (s) {
c = c.replace(/\\n/g, "\n");
}
return c;
}
}
function r(e, t) {
if (typeof e !== "string" || !e.includes("\n")) {
return e;
}
const n = t.slice(t.lastIndexOf("\n") + 1);
const a = n.match(/^(\s+)/);
if (a) {
const t = a[1];
return e.replace(/\n/g, `\n${t}`);
}
return e;
}
e.exports = t.default;
e.exports.default = t.default;
})(uh, uh.exports);
return uh.exports;
}
Object.defineProperty(lh, "__esModule", {
value: true
});
lh.buildSqlTag = fh;
const ph = e;
const mh = ph.__importDefault(dh());
function fh({driver: e, strings: t, expressions: n}) {
let a = "";
const r = [];
let i = 0;
for (const [s, o] of n.entries()) {
a += t[s];
if (o === null) {
a += "NULL";
continue;
}
if (typeof o === "function") {
const t = o();
if (typeof t === "string") {
a += t;
continue;
}
if (Array.isArray(t)) {
if (t.length === 0) {
throw new Error(`Expression ${s} in this sql tagged template is a function which returned an empty array. Empty arrays cannot safely be expanded into parameter lists.`);
}
const n = t.map(() => e.createParameter(`param_${i + 1}`, i++));
a += n.join(", ");
r.push(...t);
continue;
}
throw new Error(`Expression ${s} in this sql tagged template is a function which returned a value of type "${t === null ? "null" : typeof t}". Only array and string types are supported as function return values in sql tagged template expressions.`);
}
a += e.createParameter(`param_${i + 1}`, i++);
r.push(o);
}
a += t[t.length - 1];
a = (0, mh.default)(a);
return {
query: a,
parameters: r
};
}
Object.defineProperty(ch, "__esModule", {
value: true
});
var yh = ch.Repository = void 0;
const Eh = lh;
class Repository {
get metadata() {
return this.manager.connection.getMetadata(this.target);
}
constructor(e, t, n) {
this.target = e;
this.manager = t;
this.queryRunner = n;
}
createQueryBuilder(e, t) {
return this.manager.createQueryBuilder(this.metadata.target, e || this.metadata.targetName, t || this.queryRunner);
}
hasId(e) {
return this.manager.hasId(this.metadata.target, e);
}
getId(e) {
return this.manager.getId(this.metadata.target, e);
}
create(e) {
return this.manager.create(this.metadata.target, e);
}
merge(e, ...t) {
return this.manager.merge(this.metadata.target, e, ...t);
}
preload(e) {
return this.manager.preload(this.metadata.target, e);
}
save(e, t) {
return this.manager.save(this.metadata.target, e, t);
}
remove(e, t) {
return this.manager.remove(this.metadata.target, e, t);
}
softRemove(e, t) {
return this.manager.softRemove(this.metadata.target, e, t);
}
recover(e, t) {
return this.manager.recover(this.metadata.target, e, t);
}
insert(e) {
return this.manager.insert(this.metadata.target, e);
}
update(e, t) {
return this.manager.update(this.metadata.target, e, t);
}
updateAll(e) {
return this.manager.updateAll(this.metadata.target, e);
}
upsert(e, t) {
return this.manager.upsert(this.metadata.target, e, t);
}
delete(e) {
return this.manager.delete(this.metadata.target, e);
}
deleteAll() {
return this.manager.deleteAll(this.metadata.target);
}
softDelete(e) {
return this.manager.softDelete(this.metadata.target, e);
}
restore(e) {
return this.manager.restore(this.metadata.target, e);
}
exist(e) {
return this.manager.exists(this.metadata.target, e);
}
exists(e) {
return this.manager.exists(this.metadata.target, e);
}
existsBy(e) {
return this.manager.existsBy(this.metadata.target, e);
}
count(e) {
return this.manager.count(this.metadata.target, e);
}
countBy(e) {
return this.manager.countBy(this.metadata.target, e);
}
sum(e, t) {
return this.manager.sum(this.metadata.target, e, t);
}
average(e, t) {
return this.manager.average(this.metadata.target, e, t);
}
minimum(e, t) {
return this.manager.minimum(this.metadata.target, e, t);
}
maximum(e, t) {
return this.manager.maximum(this.metadata.target, e, t);
}
async find(e) {
return this.manager.find(this.metadata.target, e);
}
async findBy(e) {
return this.manager.findBy(this.metadata.target, e);
}
findAndCount(e) {
return this.manager.findAndCount(this.metadata.target, e);
}
findAndCountBy(e) {
return this.manager.findAndCountBy(this.metadata.target, e);
}
async findByIds(e) {
return this.manager.findByIds(this.metadata.target, e);
}
async findOne(e) {
return this.manager.findOne(this.metadata.target, e);
}
async findOneBy(e) {
return this.manager.findOneBy(this.metadata.target, e);
}
async findOneById(e) {
return this.manager.findOneById(this.metadata.target, e);
}
async findOneOrFail(e) {
return this.manager.findOneOrFail(this.metadata.target, e);
}
async findOneByOrFail(e) {
return this.manager.findOneByOrFail(this.metadata.target, e);
}
query(e, t) {
return this.manager.query(e, t);
}
async sql(e, ...t) {
const {query: n, parameters: a} = (0, Eh.buildSqlTag)({
driver: this.manager.connection.driver,
strings: e,
expressions: t
});
return await this.query(n, a);
}
clear() {
return this.manager.clear(this.metadata.target);
}
increment(e, t, n) {
return this.manager.increment(this.metadata.target, e, t, n);
}
decrement(e, t, n) {
return this.manager.decrement(this.metadata.target, e, t, n);
}
extend(e) {
const t = this.constructor;
const {target: n, manager: a, queryRunner: r} = this;
const i = class extends t {
constructor(e, t, n) {
super(e, t, n);
}
};
for (const t in e) i.prototype[t] = e[t];
return new i(n, a, r);
}
}
yh = ch.Repository = Repository;
Object.defineProperty(oh, "__esModule", {
value: true
});
var Th = oh.MongoRepository = void 0;
const gh = ch;
const Nh = D;
class MongoRepository extends gh.Repository {
query(e, t) {
throw new Nh.TypeORMError(`Queries aren't supported by MongoDB.`);
}
createQueryBuilder(e, t) {
throw new Nh.TypeORMError(`Query Builder is not supported by MongoDB.`);
}
find(e) {
return this.manager.find(this.metadata.target, e);
}
findBy(e) {
return this.manager.findBy(this.metadata.target, e);
}
findAndCount(e) {
return this.manager.findAndCount(this.metadata.target, e);
}
findAndCountBy(e) {
return this.manager.findAndCountBy(this.metadata.target, e);
}
findByIds(e, t) {
return this.manager.findByIds(this.metadata.target, e, t);
}
async findOne(e) {
return this.manager.findOne(this.metadata.target, e);
}
async findOneBy(e) {
return this.manager.findOneBy(this.metadata.target, e);
}
async findOneById(e) {
return this.manager.findOneById(this.metadata.target, e);
}
async findOneOrFail(e) {
return this.manager.findOneOrFail(this.metadata.target, e);
}
async findOneByOrFail(e) {
return this.manager.findOneByOrFail(this.metadata.target, e);
}
createCursor(e) {
return this.manager.createCursor(this.metadata.target, e);
}
createEntityCursor(e) {
return this.manager.createEntityCursor(this.metadata.target, e);
}
aggregate(e, t) {
return this.manager.aggregate(this.metadata.target, e, t);
}
aggregateEntity(e, t) {
return this.manager.aggregateEntity(this.metadata.target, e, t);
}
bulkWrite(e, t) {
return this.manager.bulkWrite(this.metadata.target, e, t);
}
count(e, t) {
return this.manager.count(this.metadata.target, e || {}, t);
}
countDocuments(e, t) {
return this.manager.countDocuments(this.metadata.target, e || {}, t);
}
countBy(e, t) {
return this.manager.countBy(this.metadata.target, e, t);
}
createCollectionIndex(e, t) {
return this.manager.createCollectionIndex(this.metadata.target, e, t);
}
createCollectionIndexes(e) {
return this.manager.createCollectionIndexes(this.metadata.target, e);
}
deleteMany(e, t) {
return this.manager.deleteMany(this.metadata.tableName, e, t);
}
deleteOne(e, t) {
return this.manager.deleteOne(this.metadata.tableName, e, t);
}
distinct(e, t, n) {
return this.manager.distinct(this.metadata.tableName, e, t, n);
}
dropCollectionIndex(e, t) {
return this.manager.dropCollectionIndex(this.metadata.tableName, e, t);
}
dropCollectionIndexes() {
return this.manager.dropCollectionIndexes(this.metadata.tableName);
}
findOneAndDelete(e, t) {
return this.manager.findOneAndDelete(this.metadata.tableName, e, t);
}
findOneAndReplace(e, t, n) {
return this.manager.findOneAndReplace(this.metadata.tableName, e, t, n);
}
findOneAndUpdate(e, t, n) {
return this.manager.findOneAndUpdate(this.metadata.tableName, e, t, n);
}
collectionIndexes() {
return this.manager.collectionIndexes(this.metadata.tableName);
}
collectionIndexExists(e) {
return this.manager.collectionIndexExists(this.metadata.tableName, e);
}
collectionIndexInformation(e) {
return this.manager.collectionIndexInformation(this.metadata.tableName, e);
}
initializeOrderedBulkOp(e) {
return this.manager.initializeOrderedBulkOp(this.metadata.tableName, e);
}
initializeUnorderedBulkOp(e) {
return this.manager.initializeUnorderedBulkOp(this.metadata.tableName, e);
}
insertMany(e, t) {
return this.manager.insertMany(this.metadata.tableName, e, t);
}
insertOne(e, t) {
return this.manager.insertOne(this.metadata.tableName, e, t);
}
isCapped() {
return this.manager.isCapped(this.metadata.tableName);
}
listCollectionIndexes(e) {
return this.manager.listCollectionIndexes(this.metadata.tableName, e);
}
rename(e, t) {
return this.manager.rename(this.metadata.tableName, e, t);
}
replaceOne(e, t, n) {
return this.manager.replaceOne(this.metadata.tableName, e, t, n);
}
stats(e) {
return this.manager.stats(this.metadata.tableName, e);
}
updateMany(e, t, n) {
return this.manager.updateMany(this.metadata.tableName, e, t, n);
}
updateOne(e, t, n) {
return this.manager.updateOne(this.metadata.tableName, e, t, n);
}
}
Th = oh.MongoRepository = MongoRepository;
var Ah = {};
var bh = {};
Object.defineProperty(bh, "__esModule", {
value: true
});
var Ch = bh.TreeRepositoryUtils = void 0;
class TreeRepositoryUtils {
static createRelationMaps(e, t, n, a) {
return a.map(a => {
const r = t.treeParentRelation.joinColumns[0];
const i = r.referencedColumn ?? t.primaryColumns[0];
const s = r.givenDatabaseName || r.databaseName;
const o = i.givenDatabaseName || i.databaseName;
const c = a[n + "_" + o];
const l = a[n + "_" + s];
return {
id: e.connection.driver.prepareHydratedValue(c, i),
parentId: e.connection.driver.prepareHydratedValue(l, r)
};
});
}
static buildChildrenEntityTree(e, t, n, a, r) {
const i = e.treeChildrenRelation.propertyName;
if (r.depth === 0) {
t[i] = [];
return;
}
const s = e.treeParentRelation.joinColumns[0];
const o = s.referencedColumn ?? e.primaryColumns[0];
const c = o.getEntityValue(t);
const l = a.filter(e => e.parentId === c);
const u = new Set(l.map(e => e.id));
t[i] = n.filter(e => u.has(o.getEntityValue(e)));
t[i].forEach(t => {
TreeRepositoryUtils.buildChildrenEntityTree(e, t, n, a, {
...r,
depth: r.depth - 1
});
});
}
static buildParentEntityTree(e, t, n, a) {
const r = e.treeParentRelation.propertyName;
const i = e.treeParentRelation.joinColumns[0];
const s = i.referencedColumn ?? e.primaryColumns[0];
const o = s.getEntityValue(t);
const c = a.find(e => e.id === o);
const l = n.find(e => {
if (!c) return false;
return s.getEntityValue(e) === c.parentId;
});
if (l) {
t[r] = l;
TreeRepositoryUtils.buildParentEntityTree(e, t[r], n, a);
}
}
}
Ch = bh.TreeRepositoryUtils = TreeRepositoryUtils;
Object.defineProperty(Ah, "__esModule", {
value: true
});
var Rh = Ah.TreeRepository = void 0;
const Sh = jn;
const wh = D;
const Mh = Zc;
const Oh = bh;
const vh = ch;
class TreeRepository extends vh.Repository {
async findTrees(e) {
const t = await this.findRoots(e);
await Promise.all(t.map(t => this.findDescendantsTree(t, e)));
return t;
}
findRoots(e) {
const t = e => this.manager.connection.driver.escape(e);
const n = e => this.manager.connection.driver.escape(e);
const a = this.metadata.treeParentRelation.joinColumns[0];
const r = a.givenDatabaseName || a.databaseName;
const i = this.createQueryBuilder("treeEntity");
Mh.FindOptionsUtils.applyOptionsToTreeQueryBuilder(i, e);
return i.where(`${t("treeEntity")}.${n(r)} IS NULL`).getMany();
}
findDescendants(e, t) {
const n = this.createDescendantsQueryBuilder("treeEntity", "treeClosure", e);
Mh.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
return n.getMany();
}
async findDescendantsTree(e, t) {
const n = this.createDescendantsQueryBuilder("treeEntity", "treeClosure", e);
Mh.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
const a = await n.getRawAndEntities();
const r = Oh.TreeRepositoryUtils.createRelationMaps(this.manager, this.metadata, "treeEntity", a.raw);
Oh.TreeRepositoryUtils.buildChildrenEntityTree(this.metadata, e, a.entities, r, {
depth: -1,
...t
});
return e;
}
countDescendants(e) {
return this.createDescendantsQueryBuilder("treeEntity", "treeClosure", e).getCount();
}
createDescendantsQueryBuilder(e, t, n) {
const a = e => this.manager.connection.driver.escape(e);
if (this.metadata.treeType === "closure-table") {
const r = this.metadata.closureJunctionTable.descendantColumns.map(n => a(t) + "." + a(n.propertyPath) + " = " + a(e) + "." + a(n.referencedColumn.propertyPath)).join(" AND ");
const i = {};
const s = this.metadata.closureJunctionTable.ancestorColumns.map(e => {
i[e.referencedColumn.propertyName] = e.referencedColumn.getEntityValue(n);
return a(t) + "." + a(e.propertyPath) + " = :" + e.referencedColumn.propertyName;
}).join(" AND ");
return this.createQueryBuilder(e).innerJoin(this.metadata.closureJunctionTable.tableName, t, r).where(s).setParameters(i);
} else if (this.metadata.treeType === "nested-set") {
const t = e + "." + this.metadata.nestedSetLeftColumn.propertyPath + " BETWEEN " + "joined." + this.metadata.nestedSetLeftColumn.propertyPath + " AND joined." + this.metadata.nestedSetRightColumn.propertyPath;
const a = {};
const r = this.metadata.treeParentRelation.joinColumns.map(e => {
const t = e.referencedColumn.propertyPath.replace(".", "_");
a[t] = e.referencedColumn.getEntityValue(n);
return "joined." + e.referencedColumn.propertyPath + " = :" + t;
}).join(" AND ");
return this.createQueryBuilder(e).innerJoin(this.metadata.targetName, "joined", t).where(r, a);
} else if (this.metadata.treeType === "materialized-path") {
return this.createQueryBuilder(e).where(t => {
const a = t.subQuery().select(`${this.metadata.targetName}.${this.metadata.materializedPathColumn.propertyPath}`, "path").from(this.metadata.target, this.metadata.targetName).whereInIds(this.metadata.getEntityIdMap(n));
if (Sh.DriverUtils.isSQLiteFamily(this.manager.connection.driver)) {
return `${e}.${this.metadata.materializedPathColumn.propertyPath} LIKE ${a.getQuery()} || '%'`;
} else {
return `${e}.${this.metadata.materializedPathColumn.propertyPath} LIKE NULLIF(CONCAT(${a.getQuery()}, '%'), '%')`;
}
});
}
throw new wh.TypeORMError(`Supported only in tree entities`);
}
findAncestors(e, t) {
const n = this.createAncestorsQueryBuilder("treeEntity", "treeClosure", e);
Mh.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
return n.getMany();
}
async findAncestorsTree(e, t) {
const n = this.createAncestorsQueryBuilder("treeEntity", "treeClosure", e);
Mh.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
const a = await n.getRawAndEntities();
const r = Oh.TreeRepositoryUtils.createRelationMaps(this.manager, this.metadata, "treeEntity", a.raw);
Oh.TreeRepositoryUtils.buildParentEntityTree(this.metadata, e, a.entities, r);
return e;
}
countAncestors(e) {
return this.createAncestorsQueryBuilder("treeEntity", "treeClosure", e).getCount();
}
createAncestorsQueryBuilder(e, t, n) {
if (this.metadata.treeType === "closure-table") {
const a = this.metadata.closureJunctionTable.ancestorColumns.map(n => t + "." + n.propertyPath + " = " + e + "." + n.referencedColumn.propertyPath).join(" AND ");
const r = {};
const i = this.metadata.closureJunctionTable.descendantColumns.map(e => {
r[e.referencedColumn.propertyName] = e.referencedColumn.getEntityValue(n);
return t + "." + e.propertyPath + " = :" + e.referencedColumn.propertyName;
}).join(" AND ");
return this.createQueryBuilder(e).innerJoin(this.metadata.closureJunctionTable.tableName, t, a).where(i).setParameters(r);
} else if (this.metadata.treeType === "nested-set") {
const t = "joined." + this.metadata.nestedSetLeftColumn.propertyPath + " BETWEEN " + e + "." + this.metadata.nestedSetLeftColumn.propertyPath + " AND " + e + "." + this.metadata.nestedSetRightColumn.propertyPath;
const a = {};
const r = this.metadata.treeParentRelation.joinColumns.map(e => {
const t = e.referencedColumn.propertyPath.replace(".", "_");
a[t] = e.referencedColumn.getEntityValue(n);
return "joined." + e.referencedColumn.propertyPath + " = :" + t;
}).join(" AND ");
return this.createQueryBuilder(e).innerJoin(this.metadata.targetName, "joined", t).where(r, a);
} else if (this.metadata.treeType === "materialized-path") {
return this.createQueryBuilder(e).where(t => {
const a = t.subQuery().select(`${this.metadata.targetName}.${this.metadata.materializedPathColumn.propertyPath}`, "path").from(this.metadata.target, this.metadata.targetName).whereInIds(this.metadata.getEntityIdMap(n));
if (Sh.DriverUtils.isSQLiteFamily(this.manager.connection.driver)) {
return `${a.getQuery()} LIKE ${e}.${this.metadata.materializedPathColumn.propertyPath} || '%'`;
} else {
return `${a.getQuery()} LIKE CONCAT(${e}.${this.metadata.materializedPathColumn.propertyPath}, '%')`;
}
});
}
throw new wh.TypeORMError(`Supported only in tree entities`);
}
}
Rh = Ah.TreeRepository = TreeRepository;
var Ih = {};
Object.defineProperty(Ih, "__esModule", {
value: true
});
Ih.PlainObjectToNewEntityTransformer = void 0;
const Ph = I;
class PlainObjectToNewEntityTransformer {
transform(e, t, n, a = false) {
this.groupAndTransform(e, t, n, a);
return e;
}
groupAndTransform(e, t, n, a = false) {
n.nonVirtualColumns.forEach(n => {
const a = n.getEntityValue(t);
if (a !== undefined) n.setEntityValue(e, a);
});
if (n.relations.length) {
n.relations.forEach(n => {
let r = n.getEntityValue(e);
const i = n.getEntityValue(t, a);
if (i === undefined) return;
if (n.isOneToMany || n.isManyToMany) {
if (!Array.isArray(i)) return;
if (!r) {
r = [];
n.setEntityValue(e, r);
}
i.forEach(e => {
let t = r.find(t => n.inverseEntityMetadata.compareEntities(e, t));
const i = n.inverseEntityMetadata.findInheritanceMetadata(e);
if (!t) {
t = i.create(undefined, {
fromDeserializer: true
});
r.push(t);
}
this.groupAndTransform(t, e, i, a);
});
} else {
if (!Ph.ObjectUtils.isObject(i)) {
if (!Ph.ObjectUtils.isObject(r)) n.setEntityValue(e, i);
return;
}
const t = n.inverseEntityMetadata.findInheritanceMetadata(i);
if (!r) {
r = t.create(undefined, {
fromDeserializer: true
});
n.setEntityValue(e, r);
}
this.groupAndTransform(r, i, t, a);
}
});
}
}
}
Ih.PlainObjectToNewEntityTransformer = PlainObjectToNewEntityTransformer;
var Lh = {};
Object.defineProperty(Lh, "__esModule", {
value: true
});
Lh.PlainObjectToDatabaseEntityTransformer = void 0;
class LoadMapItem {
constructor(e, t, n, a) {
this.plainEntity = e;
this.metadata = t;
this.parentLoadMapItem = n;
this.relation = a;
}
get target() {
return this.metadata.target;
}
get id() {
return this.metadata.getEntityIdMixedMap(this.plainEntity);
}
}
class LoadMap {
constructor() {
this.loadMapItems = [];
}
get mainLoadMapItem() {
return this.loadMapItems.find(e => !e.relation && !e.parentLoadMapItem);
}
addLoadMap(e) {
const t = this.loadMapItems.find(t => t.target === e.target && t.id === e.id);
if (!t) this.loadMapItems.push(e);
}
fillEntities(e, t) {
t.forEach(t => {
const n = this.loadMapItems.find(n => n.target === e && n.metadata.compareEntities(t, n.plainEntity));
if (n) n.entity = t;
});
}
groupByTargetIds() {
const e = [];
this.loadMapItems.forEach(t => {
let n = e.find(e => e.target === t.target);
if (!n) {
n = {
target: t.target,
ids: []
};
e.push(n);
}
n.ids.push(t.id);
});
return e;
}
}
class PlainObjectToDatabaseEntityTransformer {
constructor(e) {
this.manager = e;
}
async transform(e, t) {
if (!t.hasAllPrimaryKeys(e)) return Promise.reject("Given object does not have a primary column, cannot transform it to database entity.");
const n = new LoadMap;
const a = (e, r, i, s) => {
const o = new LoadMapItem(e, r, i, s);
n.addLoadMap(o);
r.extractRelationValuesFromEntity(e, t.relations).filter(e => e !== null && e !== undefined).forEach(([e, t, n]) => a(t, n, o, e));
};
a(e, t);
await Promise.all(n.groupByTargetIds().map(e => this.manager.findByIds(e.target, e.ids).then(t => n.fillEntities(e.target, t))));
n.loadMapItems.forEach(e => {
if (!e.relation || !e.entity || !e.parentLoadMapItem || !e.parentLoadMapItem.entity) return;
if (e.relation.isManyToMany || e.relation.isOneToMany) {
if (!e.parentLoadMapItem.entity[e.relation.propertyName]) e.parentLoadMapItem.entity[e.relation.propertyName] = [];
e.parentLoadMapItem.entity[e.relation.propertyName].push(e.entity);
} else {
e.parentLoadMapItem.entity[e.relation.propertyName] = e.entity;
}
});
return n.mainLoadMapItem ? n.mainLoadMapItem.entity : undefined;
}
}
Lh.PlainObjectToDatabaseEntityTransformer = PlainObjectToDatabaseEntityTransformer;
var Dh = {};
var _h = {};
var $h = {};
var xh = {};
Object.defineProperty(xh, "__esModule", {
value: true
});
xh.MetadataUtils = void 0;
class MetadataUtils {
static getInheritanceTree(e) {
const t = [ e ];
const n = e => {
const a = Object.getPrototypeOf(e);
if (a && a.name) {
t.push(a);
n(a);
}
};
n(e);
return t;
}
static isInherited(e, t) {
return e.prototype instanceof t;
}
static filterByTarget(e, t) {
if (!t) return e;
return e.filter(e => e.target && t.indexOf(e.target) !== -1);
}
}
xh.MetadataUtils = MetadataUtils;
Object.defineProperty($h, "__esModule", {
value: true
});
$h.MetadataArgsStorage = void 0;
const qh = xh;
class MetadataArgsStorage {
constructor() {
this.tables = [];
this.trees = [];
this.entityRepositories = [];
this.transactionEntityManagers = [];
this.transactionRepositories = [];
this.namingStrategies = [];
this.entitySubscribers = [];
this.indices = [];
this.foreignKeys = [];
this.uniques = [];
this.checks = [];
this.exclusions = [];
this.columns = [];
this.generations = [];
this.relations = [];
this.joinColumns = [];
this.joinTables = [];
this.entityListeners = [];
this.relationCounts = [];
this.relationIds = [];
this.embeddeds = [];
this.inheritances = [];
this.discriminatorValues = [];
}
filterTables(e) {
return this.filterByTarget(this.tables, e);
}
filterColumns(e) {
return this.filterByTargetAndWithoutDuplicateProperties(this.columns, e);
}
findGenerated(e, t) {
return this.generations.find(n => (Array.isArray(e) ? e.indexOf(n.target) !== -1 : n.target === e) && n.propertyName === t);
}
findTree(e) {
return this.trees.find(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterRelations(e) {
return this.filterByTargetAndWithoutDuplicateRelationProperties(this.relations, e);
}
filterRelationIds(e) {
return this.filterByTargetAndWithoutDuplicateProperties(this.relationIds, e);
}
filterRelationCounts(e) {
return this.filterByTargetAndWithoutDuplicateProperties(this.relationCounts, e);
}
filterIndices(e) {
return this.indices.filter(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterForeignKeys(e) {
return this.foreignKeys.filter(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterUniques(e) {
return this.uniques.filter(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterChecks(e) {
return this.checks.filter(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterExclusions(e) {
return this.exclusions.filter(t => Array.isArray(e) ? e.indexOf(t.target) !== -1 : t.target === e);
}
filterListeners(e) {
return this.filterByTarget(this.entityListeners, e);
}
filterEmbeddeds(e) {
return this.filterByTargetAndWithoutDuplicateEmbeddedProperties(this.embeddeds, e);
}
findJoinTable(e, t) {
return this.joinTables.find(n => n.target === e && n.propertyName === t);
}
filterJoinColumns(e, t) {
return this.joinColumns.filter(n => n.target === e && n.propertyName === t);
}
filterSubscribers(e) {
return this.filterByTarget(this.entitySubscribers, e);
}
filterNamingStrategies(e) {
return this.filterByTarget(this.namingStrategies, e);
}
filterTransactionEntityManagers(e, t) {
return this.transactionEntityManagers.filter(n => (Array.isArray(e) ? e.indexOf(n.target) !== -1 : n.target === e) && n.methodName === t);
}
filterTransactionRepository(e, t) {
return this.transactionRepositories.filter(n => (Array.isArray(e) ? e.indexOf(n.target) !== -1 : n.target === e) && n.methodName === t);
}
filterSingleTableChildren(e) {
return this.tables.filter(t => typeof t.target === "function" && typeof e === "function" && qh.MetadataUtils.isInherited(t.target, e) && t.type === "entity-child");
}
findInheritanceType(e) {
return this.inheritances.find(t => t.target === e);
}
findDiscriminatorValue(e) {
return this.discriminatorValues.find(t => t.target === e);
}
filterByTarget(e, t) {
return e.filter(e => Array.isArray(t) ? t.indexOf(e.target) !== -1 : e.target === t);
}
filterByTargetAndWithoutDuplicateProperties(e, t) {
const n = [];
e.forEach(e => {
const a = Array.isArray(t) ? t.indexOf(e.target) !== -1 : e.target === t;
if (a) {
if (!n.find(t => t.propertyName === e.propertyName)) n.push(e);
}
});
return n;
}
filterByTargetAndWithoutDuplicateRelationProperties(e, t) {
const n = [];
e.forEach(e => {
const a = Array.isArray(t) ? t.indexOf(e.target) !== -1 : e.target === t;
if (a) {
const a = n.findIndex(t => t.propertyName === e.propertyName);
if (Array.isArray(t) && a !== -1 && t.indexOf(e.target) < t.indexOf(n[a].target)) {
const t = Object.create(n[a]);
t.type = e.type;
n[a] = t;
} else if (a === -1) {
n.push(e);
}
}
});
return n;
}
filterByTargetAndWithoutDuplicateEmbeddedProperties(e, t) {
const n = [];
e.forEach(e => {
const a = Array.isArray(t) ? t.indexOf(e.target) !== -1 : e.target === t;
if (a) {
const t = n.find(t => t.prefix === e.prefix && t.propertyName === e.propertyName);
if (!t) n.push(e);
}
});
return n;
}
}
$h.MetadataArgsStorage = MetadataArgsStorage;
var Uh = {};
var Bh = {
exports: {}
};
Bh.exports;
var Fh;
function jh() {
if (Fh) return Bh.exports;
Fh = 1;
let {defineProperty: e, setPrototypeOf: t, create: n, keys: a} = Object, r = "", {round: i, max: s} = Math, o = e => {
let [, t] = /([a-f\d]{3,6})/i.exec(e) || [], n = t ? t.length : 0;
if (3 === n) t = t[0] + t[0] + t[1] + t[1] + t[2] + t[2]; else if (6 ^ n) return [ 0, 0, 0 ];
let a = parseInt(t, 16);
return [ a >> 16 & 255, a >> 8 & 255, 255 & a ];
}, c = (e, t, n) => e === t && t === n ? e < 8 ? 16 : e > 248 ? 231 : i((e - 8) / 247 * 24) + 232 : 16 + 36 * i(e / 51) + 6 * i(t / 51) + i(n / 51), l = e => {
let t, n, a, r, o;
return e < 8 ? 30 + e : e < 16 ? e - 8 + 90 : (e >= 232 ? t = n = a = (10 * (e - 232) + 8) / 255 : (o = (e -= 16) % 36,
t = (e / 36 | 0) / 5, n = (o / 6 | 0) / 5, a = o % 6 / 5), r = 2 * s(t, n, a), r ? 30 + (i(a) << 2 | i(n) << 1 | i(t)) + (2 ^ r ? 0 : 60) : 30);
}, u = (() => {
let e = e => s.some(t => e.test(t)), t = globalThis, n = t.Deno, r = !!n, i = t.process || n || {}, s = i.argv || i.args || [], o = i.env || {}, c = -1;
if (r) try {
o = o.toObject();
} catch (e) {
c = 0;
}
let l = !!o.PM2_HOME && !!o.pm_id || o.NEXT_RUNTIME?.includes("edge") || (r ? n.isatty(1) : !!i.stdout?.isTTY), u = "FORCE_COLOR", h = o[u], d = parseInt(h), p = isNaN(d) ? "false" === h ? 0 : -1 : d, m = u in o && p || e(/^-{1,2}color=?(true|always)?$/);
return m && (c = p), c < 0 && (c = ((e, t, n) => {
let r = e.TERM, i = "," + a(e).join(",");
return {
"24bit": 3,
truecolor: 3,
ansi256: 2,
ansi: 1
}[e.COLORTERM] || (e.TF_BUILD ? 1 : /,TEAMCI/.test(i) ? 2 : e.CI ? /,GIT(HUB|EA)/.test(i) ? 3 : 1 : !t || /-mono|dumb/i.test(r) ? 0 : n || /term-(kit|dir)/.test(r) ? 3 : /-256/.test(r) ? 2 : /scr|xterm|tty|ansi|color|[nm]ux|vt|cyg/.test(r) ? 1 : 3);
})(o, l, "win32" === (r ? n.build.os : i.platform))), !p || o.NO_COLOR || e(/^-{1,2}(no-color|color=(false|never))$/) ? 0 : m && !c || t.window?.chrome ? 3 : c;
})(), h = u > 0, d = {
open: r,
close: r
}, p = h ? (e, t) => ({
open: `[${e}m`,
close: `[${t}m`
}) : () => d, m = 39, f = 49, y = (e, t) => (n, a, r) => p(((e, t, n) => l(c(e, t, n)))(n, a, r) + e, t), E = e => (t, n, a) => e(c(t, n, a)), T = e => t => e(...o(t)), g = (e, t, n) => p(`38;2;${e};${t};${n}`, m), N = (e, t, n) => p(`48;2;${e};${t};${n}`, f), A = e => p(`38;5;${e}`, m), b = e => p(`48;5;${e}`, f);
2 === u ? (g = E(A), N = E(b)) : 1 === u && (g = y(0, m), N = y(10, f), A = e => p(l(e), m),
b = e => p(l(e) + 10, f));
let C, R = {
ansi256: A,
bgAnsi256: b,
fg: A,
bg: b,
rgb: g,
bgRgb: N,
hex: T(g),
bgHex: T(N),
visible: d,
reset: p(0, 0),
bold: p(1, 22),
dim: p(2, 22),
italic: p(3, 23),
underline: p(4, 24),
inverse: p(7, 27),
hidden: p(8, 28)
}, S = "Bright", w = 30;
"black,red,green,yellow,blue,magenta,cyan,white".split(",").map(e => {
C = "bg" + e[0].toUpperCase() + e.slice(1), R[e] = p(w, m), R[e + S] = p(60 + w, m),
R[C] = p(w + 10, f), R[C + S] = p(70 + w++, f);
}), R.grey = R.gray = p(90, m), R.bgGrey = R.bgGray = p(100, f), R.strikethrough = R.strike = p(9, 29);
let M, O = {}, v = ({_p: e}, {open: n, close: a}) => {
let i = (e, ...t) => {
if (!e) {
if (n && n === a) return n;
if (null == e || r === e) return r;
}
let s = e.raw ? String.raw(e, ...t).replace(/\\n/g, "\n") : r + e, o = i._p, {_a: c, _b: l} = o;
if (s.includes("")) for (;o; ) {
let e, t = o.close, n = o.open, a = t.length, i = r, c = 0;
if (a) {
for (;~(e = s.indexOf(t, c)); c = e + a) i += s.slice(c, e) + n;
s = i + s.slice(c);
}
o = o._p;
}
return s.includes("\n") && (s = s.replace(/(\r?\n)/g, l + "$1" + c)), c + s + l;
}, s = n, o = a;
return e && (s = e._a + n, o = a + e._b), t(i, M), i._p = {
open: n,
close: a,
_a: s,
_b: o,
_p: e
}, i.open = s, i.close = o, i;
};
const I = function() {
let a = {
Ansis: I,
isSupported: () => h,
strip: e => e.replace(/[][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, r),
extend(r) {
for (let t in r) {
let n = r[t], a = (typeof n)[0], i = "s" === a ? g(...o(n)) : n;
O[t] = "f" === a ? {
get() {
return (...e) => v(this, n(...e));
}
} : {
get() {
let n = v(this, i);
return e(this, t, {
value: n
}), n;
}
};
}
return M = n({}, O), t(a, M), a;
}
};
return a.extend(R);
}, P = new I;
Bh.exports = P, P.default = P;
return Bh.exports;
}
var kh = {
exports: {}
};
var Qh = "16.6.1";
const Vh = {
version: Qh
};
kh.exports;
var Kh;
function Wh() {
if (Kh) return kh.exports;
Kh = 1;
const e = o;
const t = c;
const n = l;
const a = u;
const r = Vh;
const i = r.version;
const s = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
function h(e) {
const t = {};
let n = e.toString();
n = n.replace(/\r\n?/gm, "\n");
let a;
while ((a = s.exec(n)) != null) {
const e = a[1];
let n = a[2] || "";
n = n.trim();
const r = n[0];
n = n.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
if (r === '"') {
n = n.replace(/\\n/g, "\n");
n = n.replace(/\\r/g, "\r");
}
t[e] = n;
}
return t;
}
function d(e) {
e = e || {};
const t = T(e);
e.path = t;
const n = S.configDotenv(e);
if (!n.parsed) {
const e = new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);
e.code = "MISSING_DATA";
throw e;
}
const a = y(e).split(",");
const r = a.length;
let i;
for (let e = 0; e < r; e++) {
try {
const t = a[e].trim();
const r = E(n, t);
i = S.decrypt(r.ciphertext, r.key);
break;
} catch (t) {
if (e + 1 >= r) {
throw t;
}
}
}
return S.parse(i);
}
function p(e) {
console.log(`[dotenv@${i}][WARN] ${e}`);
}
function m(e) {
console.log(`[dotenv@${i}][DEBUG] ${e}`);
}
function f(e) {
console.log(`[dotenv@${i}] ${e}`);
}
function y(e) {
if (e && e.DOTENV_KEY && e.DOTENV_KEY.length > 0) {
return e.DOTENV_KEY;
}
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY;
}
return "";
}
function E(e, t) {
let n;
try {
n = new URL(t);
} catch (e) {
if (e.code === "ERR_INVALID_URL") {
const e = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
e.code = "INVALID_DOTENV_KEY";
throw e;
}
throw e;
}
const a = n.password;
if (!a) {
const e = new Error("INVALID_DOTENV_KEY: Missing key part");
e.code = "INVALID_DOTENV_KEY";
throw e;
}
const r = n.searchParams.get("environment");
if (!r) {
const e = new Error("INVALID_DOTENV_KEY: Missing environment part");
e.code = "INVALID_DOTENV_KEY";
throw e;
}
const i = `DOTENV_VAULT_${r.toUpperCase()}`;
const s = e.parsed[i];
if (!s) {
const e = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);
e.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
throw e;
}
return {
ciphertext: s,
key: a
};
}
function T(n) {
let a = null;
if (n && n.path && n.path.length > 0) {
if (Array.isArray(n.path)) {
for (const t of n.path) {
if (e.existsSync(t)) {
a = t.endsWith(".vault") ? t : `${t}.vault`;
}
}
} else {
a = n.path.endsWith(".vault") ? n.path : `${n.path}.vault`;
}
} else {
a = t.resolve(process.cwd(), ".env.vault");
}
if (e.existsSync(a)) {
return a;
}
return null;
}
function g(e) {
return e[0] === "~" ? t.join(n.homedir(), e.slice(1)) : e;
}
function N(e) {
const t = Boolean(e && e.debug);
const n = e && "quiet" in e ? e.quiet : true;
if (t || !n) {
f("Loading env from encrypted .env.vault");
}
const a = S._parseVault(e);
let r = process.env;
if (e && e.processEnv != null) {
r = e.processEnv;
}
S.populate(r, a, e);
return {
parsed: a
};
}
function A(n) {
const a = t.resolve(process.cwd(), ".env");
let r = "utf8";
const i = Boolean(n && n.debug);
const s = n && "quiet" in n ? n.quiet : true;
if (n && n.encoding) {
r = n.encoding;
} else {
if (i) {
m("No encoding is specified. UTF-8 is used by default");
}
}
let o = [ a ];
if (n && n.path) {
if (!Array.isArray(n.path)) {
o = [ g(n.path) ];
} else {
o = [];
for (const e of n.path) {
o.push(g(e));
}
}
}
let c;
const l = {};
for (const t of o) {
try {
const a = S.parse(e.readFileSync(t, {
encoding: r
}));
S.populate(l, a, n);
} catch (e) {
if (i) {
m(`Failed to load ${t} ${e.message}`);
}
c = e;
}
}
let u = process.env;
if (n && n.processEnv != null) {
u = n.processEnv;
}
S.populate(u, l, n);
if (i || !s) {
const e = Object.keys(l).length;
const n = [];
for (const e of o) {
try {
const a = t.relative(process.cwd(), e);
n.push(a);
} catch (t) {
if (i) {
m(`Failed to load ${e} ${t.message}`);
}
c = t;
}
}
f(`injecting env (${e}) from ${n.join(",")}`);
}
if (c) {
return {
parsed: l,
error: c
};
} else {
return {
parsed: l
};
}
}
function b(e) {
if (y(e).length === 0) {
return S.configDotenv(e);
}
const t = T(e);
if (!t) {
p(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`);
return S.configDotenv(e);
}
return S._configVault(e);
}
function C(e, t) {
const n = Buffer.from(t.slice(-64), "hex");
let r = Buffer.from(e, "base64");
const i = r.subarray(0, 12);
const s = r.subarray(-16);
r = r.subarray(12, -16);
try {
const e = a.createDecipheriv("aes-256-gcm", n, i);
e.setAuthTag(s);
return `${e.update(r)}${e.final()}`;
} catch (e) {
const t = e instanceof RangeError;
const n = e.message === "Invalid key length";
const a = e.message === "Unsupported state or unable to authenticate data";
if (t || n) {
const e = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
e.code = "INVALID_DOTENV_KEY";
throw e;
} else if (a) {
const e = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
e.code = "DECRYPTION_FAILED";
throw e;
} else {
throw e;
}
}
}
function R(e, t, n = {}) {
const a = Boolean(n && n.debug);
const r = Boolean(n && n.override);
if (typeof t !== "object") {
const e = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
e.code = "OBJECT_REQUIRED";
throw e;
}
for (const n of Object.keys(t)) {
if (Object.prototype.hasOwnProperty.call(e, n)) {
if (r === true) {
e[n] = t[n];
}
if (a) {
if (r === true) {
m(`"${n}" is already defined and WAS overwritten`);
} else {
m(`"${n}" is already defined and was NOT overwritten`);
}
}
} else {
e[n] = t[n];
}
}
}
const S = {
configDotenv: A,
_configVault: N,
_parseVault: d,
config: b,
decrypt: C,
parse: h,
populate: R
};
kh.exports.configDotenv = S.configDotenv;
kh.exports._configVault = S._configVault;
kh.exports._parseVault = S._parseVault;
kh.exports.config = S.config;
kh.exports.decrypt = S.decrypt;
kh.exports.parse = S.parse;
kh.exports.populate = S.populate;
kh.exports = S;
return kh.exports;
}
var Hh;
var Gh;
function Yh() {
if (Gh) return Hh;
Gh = 1;
Hh = [ "ADD CONSTRAINT", "ADD", "ALL", "ALTER COLUMN", "ALTER TABLE", "ALTER", "AND", "ANY", "AS", "ASC", "AUTO_INCREMENT", "BACKUP DATABASE", "BEGIN", "BETWEEN", "BINARY", "BLOB", "BY", "CASCADE", "CASE", "CHAR", "CHECK", "COLUMN", "COMMIT", "CONSTRAINT", "CREATE DATABASE", "CREATE INDEX", "CREATE OR REPLACE VIEW", "CREATE PROCEDURE", "CREATE TABLE", "CREATE UNIQUE INDEX", "CREATE VIEW", "CREATE", "CURRENT_DATE", "CURRENT_TIME", "DATABASE", "DATETIME", "DECIMAL", "DECLARE", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP COLUMN", "DROP CONSTRAINT", "DROP DATABASE", "DROP DEFAULT", "DROP INDEX", "DROP TABLE", "DROP VIEW", "DROP", "EACH", "ELSE", "ELSEIF", "END", "ENGINE", "EXEC", "EXISTS", "FALSE", "FOR", "FOREIGN KEY", "FROM", "FULL OUTER JOIN", "GROUP BY", "GROUP", "HAVING", "IF", "IFNULL", "ILIKE", "IN", "INDEX_LIST", "INDEX", "INNER JOIN", "INSERT INTO SELECT", "INSERT INTO", "INSERT", "INTEGER", "INTERVAL", "INTO", "IS NOT NULL", "IS NULL", "IS", "JOIN", "KEY", "KEYS", "LEADING", "LEFT JOIN", "LEFT", "LIKE", "LIMIT", "LONGTEXT", "MATCH", "NOT NULL", "NOT", "NULL", "ON", "OPTION", "OR", "ORDER BY", "ORDER", "OUT", "OUTER JOIN", "OUTER", "OVERLAPS", "PRAGMA", "PRIMARY KEY", "PRIMARY", "PRINT", "PROCEDURE", "REFERENCES", "REPLACE", "RETURNING", "RIGHT JOIN", "RIGHT", "ROWNUM", "SELECT DISTINCT", "SELECT INTO", "SELECT TOP", "SELECT", "SET", "SHOW", "TABLE", "TEXT", "THEN", "TIMESTAMP", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TOP", "TRAILING", "TRUE", "TRUNCATE TABLE", "UNION ALL", "UNION", "UNIQUE", "UNSIGNED", "UPDATE", "VALUES", "VARBINARY", "VARCHAR", "VIEW", "WHEN", "WHERE", "WITH" ];
return Hh;
}
var zh;
var Jh;
function Xh() {
if (Jh) return zh;
Jh = 1;
const e = {
34: """,
38: "&",
39: "'",
60: "<",
62: ">"
};
function t(t) {
let n = "";
let a = 0;
for (let r = 0; r < t.length; r++) {
const i = e[t.charCodeAt(r)];
if (!i) continue;
if (a !== r) {
n += t.substring(a, r);
}
a = r + 1;
n += i;
}
return n + t.substring(a);
}
zh = t;
return zh;
}
var Zh;
var ed;
function td() {
if (ed) return Zh;
ed = 1;
const e = Yh();
const t = Xh();
const n = {
html: false,
htmlEscaper: t,
classPrefix: "sql-hl-",
colors: {
keyword: "[35m",
function: "[31m",
number: "[32m",
string: "[32m",
identifier: "[0m",
special: "[33m",
bracket: "[33m",
comment: "[2m[90m",
clear: "[0m"
}
};
const a = [ /(?<number>[+-]?(?:\d+\.\d+|\d+|\.\d+)(?:E[+-]?\d+)?)/, /(?<string>'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/, /(?<comment>--[^\n\r]*|#[^\n\r]*|\/\*(?:[^*]|\*(?!\/))*\*\/)/, /\b(?<function>\w+)(?=\s*\()/, /(?<bracket>[()])/, /(?<identifier>\b\w+\b|`(?:[^`\\]|\\.)*`)/, /(?<whitespace>\s+)/, /(?<special>\^-=|\|\*=|\+=|-=|\*=|\/=|%=|&=|>=|<=|<>|!=|!<|!>|>>|<<|.)/ ];
const r = new RegExp([ `\\b(?<keyword>${e.join("|")})\\b`, ...a.map(e => e.source) ].join("|"), "gis");
function i(e) {
const t = Array.from(e.matchAll(r), e => ({
name: Object.keys(e.groups).find(t => e.groups[t]),
content: e[0]
}));
return t;
}
function s(e, t) {
const a = Object.assign({}, n, t);
return i(e).map(({name: e, content: t}) => {
if (a.html) {
const n = a.htmlEscaper(t);
return e === "whitespace" ? n : `<span class="${a.classPrefix}${e}">${n}</span>`;
}
if (a.colors[e]) {
return a.colors[e] + t + a.colors.clear;
}
return t;
}).join("");
}
Zh = {
getSegments: i,
highlight: s,
DEFAULT_OPTIONS: n
};
return Zh;
}
var nd = {};
var ad = {};
var rd = {};
var id = {};
var sd = {};
(function(e) {
e.__esModule = true;
var t = /[\\^$.*+?()[\]{}|]/g;
var n = RegExp(t.source);
function a(e) {
return e && n.test(e) ? e.replace(t, "\\$&") : e || "";
}
e["default"] = a;
})(sd);
var od = {};
(function(e) {
e.__esModule = true;
e.TokenTypes = void 0;
(function(e) {
e["WHITESPACE"] = "whitespace";
e["WORD"] = "word";
e["STRING"] = "string";
e["RESERVED"] = "reserved";
e["RESERVED_TOP_LEVEL"] = "reserved-top-level";
e["RESERVED_TOP_LEVEL_NO_INDENT"] = "reserved-top-level-no-indent";
e["RESERVED_NEWLINE"] = "reserved-newline";
e["OPERATOR"] = "operator";
e["NO_SPACE_OPERATOR"] = "no-space-operator";
e["OPEN_PAREN"] = "open-paren";
e["CLOSE_PAREN"] = "close-paren";
e["LINE_COMMENT"] = "line-comment";
e["BLOCK_COMMENT"] = "block-comment";
e["NUMBER"] = "number";
e["PLACEHOLDER"] = "placeholder";
e["SERVERVARIABLE"] = "servervariable";
})(e.TokenTypes || (e.TokenTypes = {}));
})(od);
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var n = t(sd);
var a = od;
var i = function() {
function e(e) {
this.WHITESPACE_REGEX = /^(\s+)/u;
this.NUMBER_REGEX = /^((-\s*)?[0-9]+(\.[0-9]+)?|0x[0-9a-fA-F]+|0b[01]+|([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}))\b/u;
this.AMBIGUOS_OPERATOR_REGEX = /^(\?\||\?&)/u;
this.OPERATOR_REGEX = /^(!=|<>|>>|<<|==|<=|>=|!<|!>|\|\|\/|\|\/|\|\||~~\*|~~|!~~\*|!~~|~\*|!~\*|!~|:=|=>|&&|@>|<@|#-|@@|@|.)/u;
this.NO_SPACE_OPERATOR_REGEX = /^(::|->>|->|#>>|#>)/u;
this.BLOCK_COMMENT_REGEX = /^(\/\*[^]*?(?:\*\/|$))/u;
this.LINE_COMMENT_REGEX = this.createLineCommentRegex(e.lineCommentTypes);
this.RESERVED_TOP_LEVEL_REGEX = this.createReservedWordRegex(e.reservedTopLevelWords);
this.RESERVED_TOP_LEVEL_NO_INDENT_REGEX = this.createReservedWordRegex(e.reservedTopLevelWordsNoIndent);
this.RESERVED_NEWLINE_REGEX = this.createReservedWordRegex(e.reservedNewlineWords);
this.RESERVED_PLAIN_REGEX = this.createReservedWordRegex(e.reservedWords);
this.WORD_REGEX = this.createWordRegex(e.specialWordChars);
this.STRING_REGEX = this.createStringRegex(e.stringTypes);
this.OPEN_PAREN_REGEX = this.createParenRegex(e.openParens);
this.CLOSE_PAREN_REGEX = this.createParenRegex(e.closeParens);
this.INDEXED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(e.indexedPlaceholderTypes, "[0-9]*");
this.IDENT_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(e.namedPlaceholderTypes, "[a-zA-Z0-9._$]+");
this.STRING_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(e.namedPlaceholderTypes, this.createStringPattern(e.stringTypes));
}
e.prototype.createLineCommentRegex = function(e) {
var t = "((?<!#)>|(?:[^>]))";
return new RegExp("^((?:".concat(e.map(function(e) {
return (0, n["default"])(e);
}).join("|"), ")").concat(t, ".*?(?:\r\n|\r|\n|$))"), "u");
};
e.prototype.createReservedWordRegex = function(e) {
var t = e.join("|").replace(/ /gu, "\\s+");
return new RegExp("^(".concat(t, ")\\b"), "iu");
};
e.prototype.createWordRegex = function(e) {
return new RegExp("^([\\p{Alphabetic}\\p{Mark}\\p{Decimal_Number}\\p{Connector_Punctuation}\\p{Join_Control}".concat(e.join(""), "]+)"), "u");
};
e.prototype.createStringRegex = function(e) {
return new RegExp("^(" + this.createStringPattern(e) + ")", "u");
};
e.prototype.createStringPattern = function(e) {
var t = {
"``": "((`[^`]*($|`))+)",
"[]": "((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)",
'""': '(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)',
"''": "(('[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)",
"N''": "((N'[^N'\\\\]*(?:\\\\.[^N'\\\\]*)*('|$))+)",
"E''": "(((E|e)'[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)"
};
return e.map(function(e) {
return t[e];
}).join("|");
};
e.prototype.createParenRegex = function(e) {
var t = this;
return new RegExp("^(" + e.map(function(e) {
return t.escapeParen(e);
}).join("|") + ")", "iu");
};
e.prototype.escapeParen = function(e) {
if (e.length === 1) {
return (0, n["default"])(e);
} else {
return "\\b" + e + "\\b";
}
};
e.prototype.createPlaceholderRegex = function(e, t) {
if (!e || e.length === 0) {
return null;
}
var a = e.map(n["default"]).join("|");
return new RegExp("^((?:".concat(a, ")(?:").concat(t, "))"), "u");
};
e.prototype.tokenize = function(e) {
if (!e) return [];
var t = [];
var n;
while (e.length) {
n = this.getNextToken(e, n);
e = e.substring(n.value.length);
t.push(n);
}
return t;
};
e.prototype.getNextToken = function(e, t) {
return this.getWhitespaceToken(e) || this.getCommentToken(e) || this.getStringToken(e) || this.getOpenParenToken(e) || this.getCloseParenToken(e) || this.getAmbiguosOperatorToken(e) || this.getNoSpaceOperatorToken(e) || this.getServerVariableToken(e) || this.getPlaceholderToken(e) || this.getNumberToken(e) || this.getReservedWordToken(e, t) || this.getWordToken(e) || this.getOperatorToken(e);
};
e.prototype.getWhitespaceToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.WHITESPACE,
regex: this.WHITESPACE_REGEX
});
};
e.prototype.getCommentToken = function(e) {
return this.getLineCommentToken(e) || this.getBlockCommentToken(e);
};
e.prototype.getLineCommentToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.LINE_COMMENT,
regex: this.LINE_COMMENT_REGEX
});
};
e.prototype.getBlockCommentToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.BLOCK_COMMENT,
regex: this.BLOCK_COMMENT_REGEX
});
};
e.prototype.getStringToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.STRING,
regex: this.STRING_REGEX
});
};
e.prototype.getOpenParenToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.OPEN_PAREN,
regex: this.OPEN_PAREN_REGEX
});
};
e.prototype.getCloseParenToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.CLOSE_PAREN,
regex: this.CLOSE_PAREN_REGEX
});
};
e.prototype.getPlaceholderToken = function(e) {
return this.getIdentNamedPlaceholderToken(e) || this.getStringNamedPlaceholderToken(e) || this.getIndexedPlaceholderToken(e);
};
e.prototype.getServerVariableToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.SERVERVARIABLE,
regex: /(^@@\w+)/iu
});
};
e.prototype.getIdentNamedPlaceholderToken = function(e) {
return this.getPlaceholderTokenWithKey({
input: e,
regex: this.IDENT_NAMED_PLACEHOLDER_REGEX,
parseKey: function(e) {
return e.slice(1);
}
});
};
e.prototype.getStringNamedPlaceholderToken = function(e) {
var t = this;
return this.getPlaceholderTokenWithKey({
input: e,
regex: this.STRING_NAMED_PLACEHOLDER_REGEX,
parseKey: function(e) {
return t.getEscapedPlaceholderKey({
key: e.slice(2, -1),
quoteChar: e.slice(-1)
});
}
});
};
e.prototype.getIndexedPlaceholderToken = function(e) {
return this.getPlaceholderTokenWithKey({
input: e,
regex: this.INDEXED_PLACEHOLDER_REGEX,
parseKey: function(e) {
return e.slice(1);
}
});
};
e.prototype.getPlaceholderTokenWithKey = function(e) {
var t = e.input, n = e.regex, r = e.parseKey;
var i = this.getTokenOnFirstMatch({
input: t,
regex: n,
type: a.TokenTypes.PLACEHOLDER
});
if (i) {
i.key = r(i.value);
}
return i;
};
e.prototype.getEscapedPlaceholderKey = function(e) {
var t = e.key, a = e.quoteChar;
return t.replace(new RegExp((0, n["default"])("\\" + a), "gu"), a);
};
e.prototype.getNumberToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.NUMBER,
regex: this.NUMBER_REGEX
});
};
e.prototype.getOperatorToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.OPERATOR,
regex: this.OPERATOR_REGEX
});
};
e.prototype.getAmbiguosOperatorToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.OPERATOR,
regex: this.AMBIGUOS_OPERATOR_REGEX
});
};
e.prototype.getNoSpaceOperatorToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.NO_SPACE_OPERATOR,
regex: this.NO_SPACE_OPERATOR_REGEX
});
};
e.prototype.getReservedWordToken = function(e, t) {
if (t && t.value && t.value === ".") {
return;
}
return this.getToplevelReservedToken(e) || this.getNewlineReservedToken(e) || this.getTopLevelReservedTokenNoIndent(e) || this.getPlainReservedToken(e);
};
e.prototype.getToplevelReservedToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.RESERVED_TOP_LEVEL,
regex: this.RESERVED_TOP_LEVEL_REGEX
});
};
e.prototype.getNewlineReservedToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.RESERVED_NEWLINE,
regex: this.RESERVED_NEWLINE_REGEX
});
};
e.prototype.getPlainReservedToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.RESERVED,
regex: this.RESERVED_PLAIN_REGEX
});
};
e.prototype.getTopLevelReservedTokenNoIndent = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.RESERVED_TOP_LEVEL_NO_INDENT,
regex: this.RESERVED_TOP_LEVEL_NO_INDENT_REGEX
});
};
e.prototype.getWordToken = function(e) {
return this.getTokenOnFirstMatch({
input: e,
type: a.TokenTypes.WORD,
regex: this.WORD_REGEX
});
};
e.prototype.getTokenOnFirstMatch = function(e) {
var t = e.input, n = e.type, a = e.regex;
var r = t.match(a);
if (r) {
return {
type: n,
value: r[1]
};
}
};
return e;
}();
e["default"] = i;
})(id);
var cd = {};
var ld = {};
var ud = {};
(function(e) {
e.__esModule = true;
var t = function(e) {
if (e === void 0) {
e = [];
}
return e[e.length - 1];
};
e["default"] = t;
})(ud);
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var n = t(ud);
var a = "top-level";
var i = "block-level";
var s = function() {
function e(e) {
this.indent = e;
this.indentTypes = [];
this.indent = e || " ";
}
e.prototype.getIndent = function() {
return new Array(this.indentTypes.length).fill(this.indent).join("");
};
e.prototype.increaseTopLevel = function() {
this.indentTypes.push(a);
};
e.prototype.increaseBlockLevel = function() {
this.indentTypes.push(i);
};
e.prototype.decreaseTopLevel = function() {
if ((0, n["default"])(this.indentTypes) === a) {
this.indentTypes.pop();
}
};
e.prototype.decreaseBlockLevel = function() {
while (this.indentTypes.length > 0) {
var e = this.indentTypes.pop();
if (e !== a) {
break;
}
}
};
e.prototype.resetIndentation = function() {
this.indentTypes = [];
};
return e;
}();
e["default"] = s;
})(ld);
var hd = {};
(function(e) {
e.__esModule = true;
var t = od;
var n = 50;
var a = function() {
function e() {
this.level = 0;
}
e.prototype.beginIfPossible = function(e, t) {
if (this.level === 0 && this.isInlineBlock(e, t)) {
this.level = 1;
} else if (this.level > 0) {
this.level++;
} else {
this.level = 0;
}
};
e.prototype.end = function() {
this.level--;
};
e.prototype.isActive = function() {
return this.level > 0;
};
e.prototype.isInlineBlock = function(e, a) {
var r = 0;
var i = 0;
for (var s = a; s < e.length; s++) {
var o = e[s];
r += o.value.length;
if (r > n) {
return false;
}
if (o.type === t.TokenTypes.OPEN_PAREN) {
i++;
} else if (o.type === t.TokenTypes.CLOSE_PAREN) {
i--;
if (i === 0) {
return true;
}
}
if (this.isForbiddenToken(o)) {
return false;
}
}
return false;
};
e.prototype.isForbiddenToken = function(e) {
var n = e.type, a = e.value;
return n === t.TokenTypes.RESERVED_TOP_LEVEL || n === t.TokenTypes.RESERVED_NEWLINE || n === t.TokenTypes.LINE_COMMENT || n === t.TokenTypes.BLOCK_COMMENT || a === ";";
};
return e;
}();
e["default"] = a;
})(hd);
var dd = {};
(function(e) {
e.__esModule = true;
var t = function() {
function e(e) {
this.params = e;
this.index = 0;
this.params = e;
}
e.prototype.get = function(e) {
var t = e.key, n = e.value;
if (!this.params) {
return n;
}
if (t) {
return this.params[t];
}
return this.params[this.index++];
};
return e;
}();
e["default"] = t;
})(dd);
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var n = od;
var a = t(ld);
var i = t(hd);
var s = t(dd);
var o = [ " ", "\t" ];
var c = function(e) {
var t = e.length - 1;
while (t >= 0 && o.includes(e[t])) {
t--;
}
return e.substring(0, t + 1);
};
var l = function() {
function e(e, t, n) {
this.cfg = e;
this.tokenizer = t;
this.tokenOverride = n;
this.tokens = [];
this.previousReservedWord = {
type: null,
value: null
};
this.previousNonWhiteSpace = {
type: null,
value: null
};
this.index = 0;
this.indentation = new a["default"](this.cfg.indent);
this.inlineBlock = new i["default"];
this.params = new s["default"](this.cfg.params);
}
e.prototype.format = function(e) {
this.tokens = this.tokenizer.tokenize(e);
var t = this.getFormattedQueryFromTokens();
return t.trim();
};
e.prototype.getFormattedQueryFromTokens = function() {
var e = this;
var t = "";
this.tokens.forEach(function(a, r) {
e.index = r;
if (e.tokenOverride) a = e.tokenOverride(a, e.previousReservedWord) || a;
if (a.type === n.TokenTypes.WHITESPACE) {
t = e.formatWhitespace(a, t);
} else if (a.type === n.TokenTypes.LINE_COMMENT) {
t = e.formatLineComment(a, t);
} else if (a.type === n.TokenTypes.BLOCK_COMMENT) {
t = e.formatBlockComment(a, t);
} else if (a.type === n.TokenTypes.RESERVED_TOP_LEVEL || a.type === n.TokenTypes.RESERVED_TOP_LEVEL_NO_INDENT || a.type === n.TokenTypes.RESERVED_NEWLINE || a.type === n.TokenTypes.RESERVED) {
t = e.formatReserved(a, t);
} else if (a.type === n.TokenTypes.OPEN_PAREN) {
t = e.formatOpeningParentheses(a, t);
} else if (a.type === n.TokenTypes.CLOSE_PAREN) {
t = e.formatClosingParentheses(a, t);
} else if (a.type === n.TokenTypes.NO_SPACE_OPERATOR) {
t = e.formatWithoutSpaces(a, t);
} else if (a.type === n.TokenTypes.PLACEHOLDER || a.type === n.TokenTypes.SERVERVARIABLE) {
t = e.formatPlaceholder(a, t);
} else if (a.value === ",") {
t = e.formatComma(a, t);
} else if (a.value === ":") {
t = e.formatWithSpaceAfter(a, t);
} else if (a.value === ".") {
t = e.formatWithoutSpaces(a, t);
} else if (a.value === ";") {
t = e.formatQuerySeparator(a, t);
} else {
t = e.formatWithSpaces(a, t);
}
if (a.type !== n.TokenTypes.WHITESPACE) {
e.previousNonWhiteSpace = a;
}
});
return t;
};
e.prototype.formatWhitespace = function(e, t) {
if (this.cfg.linesBetweenQueries === "preserve" && /((\r\n|\n)(\r\n|\n)+)/u.test(e.value) && this.previousToken().value === ";") {
return t.replace(/(\n|\r\n)$/u, "") + e.value;
}
return t;
};
e.prototype.formatReserved = function(e, t) {
if (e.type === n.TokenTypes.RESERVED_NEWLINE && this.previousReservedWord && this.previousReservedWord.value && e.value.toUpperCase() === "AND" && this.previousReservedWord.value.toUpperCase() === "BETWEEN") {
e.type = n.TokenTypes.RESERVED;
}
if (e.type === n.TokenTypes.RESERVED_TOP_LEVEL) {
t = this.formatTopLevelReservedWord(e, t);
} else if (e.type === n.TokenTypes.RESERVED_TOP_LEVEL_NO_INDENT) {
t = this.formatTopLevelReservedWordNoIndent(e, t);
} else if (e.type === n.TokenTypes.RESERVED_NEWLINE) {
t = this.formatNewlineReservedWord(e, t);
} else {
t = this.formatWithSpaces(e, t);
}
this.previousReservedWord = e;
return t;
};
e.prototype.formatLineComment = function(e, t) {
return this.addNewline(t + e.value);
};
e.prototype.formatBlockComment = function(e, t) {
return this.addNewline(this.addNewline(t) + this.indentComment(e.value));
};
e.prototype.indentComment = function(e) {
return e.replace(/\n[ \t]*/gu, "\n" + this.indentation.getIndent() + " ");
};
e.prototype.formatTopLevelReservedWordNoIndent = function(e, t) {
this.indentation.decreaseTopLevel();
t = this.addNewline(t) + this.equalizeWhitespace(this.formatReservedWord(e.value));
return this.addNewline(t);
};
e.prototype.formatTopLevelReservedWord = function(e, t) {
var n = this.previousNonWhiteSpace.value !== "," && ![ "GRANT" ].includes("".concat(this.previousNonWhiteSpace.value).toUpperCase());
if (n) {
this.indentation.decreaseTopLevel();
t = this.addNewline(t);
}
t = t + this.equalizeWhitespace(this.formatReservedWord(e.value)) + " ";
if (n) this.indentation.increaseTopLevel();
return t;
};
e.prototype.formatNewlineReservedWord = function(e, t) {
return this.addNewline(t) + this.equalizeWhitespace(this.formatReservedWord(e.value)) + " ";
};
e.prototype.equalizeWhitespace = function(e) {
return e.replace(/\s+/gu, " ");
};
e.prototype.formatOpeningParentheses = function(e, t) {
e.value = this.formatCase(e.value);
var a = this.previousToken().type;
if (a !== n.TokenTypes.WHITESPACE && a !== n.TokenTypes.OPEN_PAREN && a !== n.TokenTypes.LINE_COMMENT) {
t = c(t);
}
t += e.value;
this.inlineBlock.beginIfPossible(this.tokens, this.index);
if (!this.inlineBlock.isActive()) {
this.indentation.increaseBlockLevel();
t = this.addNewline(t);
}
return t;
};
e.prototype.formatClosingParentheses = function(e, t) {
e.value = this.formatCase(e.value);
if (this.inlineBlock.isActive()) {
this.inlineBlock.end();
return this.formatWithSpaceAfter(e, t);
} else {
this.indentation.decreaseBlockLevel();
return this.formatWithSpaces(e, this.addNewline(t));
}
};
e.prototype.formatPlaceholder = function(e, t) {
return t + this.params.get(e) + " ";
};
e.prototype.formatComma = function(e, t) {
t = c(t) + e.value + " ";
if (this.inlineBlock.isActive()) {
return t;
} else if (/^LIMIT$/iu.test(this.previousReservedWord.value)) {
return t;
} else {
return this.addNewline(t);
}
};
e.prototype.formatWithSpaceAfter = function(e, t) {
return c(t) + e.value + " ";
};
e.prototype.formatWithoutSpaces = function(e, t) {
return c(t) + e.value;
};
e.prototype.formatWithSpaces = function(e, t) {
var a = e.type === n.TokenTypes.RESERVED ? this.formatReservedWord(e.value) : e.value;
return t + a + " ";
};
e.prototype.formatReservedWord = function(e) {
return this.formatCase(e);
};
e.prototype.formatQuerySeparator = function(e, t) {
this.indentation.resetIndentation();
var n = "\n";
if (this.cfg.linesBetweenQueries !== "preserve") {
n = "\n".repeat(this.cfg.linesBetweenQueries || 1);
}
return c(t) + e.value + n;
};
e.prototype.addNewline = function(e) {
e = c(e);
if (!e.endsWith("\n")) e += "\n";
return e + this.indentation.getIndent();
};
e.prototype.previousToken = function() {
return this.tokens[this.index - 1] || {
type: null,
value: null
};
};
e.prototype.formatCase = function(e) {
if (this.cfg.reservedWordCase === "upper") return e.toUpperCase();
if (this.cfg.reservedWordCase === "lower") return e.toLowerCase();
return e;
};
return e;
}();
e["default"] = l;
})(cd);
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var n = t(id);
var a = t(cd);
var i = function() {
function e(e) {
this.cfg = e;
}
e.prototype.format = function(e) {
return new a["default"](this.cfg, this.tokenizer(), this.tokenOverride).format(e);
};
e.prototype.tokenize = function(e) {
return this.tokenizer().tokenize(e);
};
e.prototype.tokenizer = function() {
return new n["default"](this.getTokenizerConfig());
};
return e;
}();
e["default"] = i;
})(rd);
(function(e) {
var t = r && r.__extends || function() {
var e = function(t, n) {
e = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(e, t) {
e.__proto__ = t;
} || function(e, t) {
for (var n in t) if (Object.prototype.hasOwnProperty.call(t, n)) e[n] = t[n];
};
return e(t, n);
};
return function(t, n) {
if (typeof n !== "function" && n !== null) throw new TypeError("Class extends value " + String(n) + " is not a constructor or null");
e(t, n);
function a() {
this.constructor = t;
}
t.prototype = n === null ? Object.create(n) : (a.prototype = n.prototype, new a);
};
}();
var n = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var a = n(rd);
var i = function(e) {
t(n, e);
function n() {
return e !== null && e.apply(this, arguments) || this;
}
n.prototype.getTokenizerConfig = function() {
return {
reservedWords: s,
reservedTopLevelWords: o,
reservedNewlineWords: l,
reservedTopLevelWordsNoIndent: c,
stringTypes: [ '""', "''", "``", "[]" ],
openParens: [ "(" ],
closeParens: [ ")" ],
indexedPlaceholderTypes: [ "?" ],
namedPlaceholderTypes: [ ":" ],
lineCommentTypes: [ "--" ],
specialWordChars: [ "#", "@" ]
};
};
return n;
}(a["default"]);
e["default"] = i;
var s = [ "ABS", "ACTIVATE", "ALIAS", "ALL", "ALLOCATE", "ALLOW", "ALTER", "ANY", "ARE", "ARRAY", "AS", "ASC", "ASENSITIVE", "ASSOCIATE", "ASUTIME", "ASYMMETRIC", "AT", "ATOMIC", "ATTRIBUTES", "AUDIT", "AUTHORIZATION", "AUX", "AUXILIARY", "AVG", "BEFORE", "BEGIN", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOOLEAN", "BOTH", "BUFFERPOOL", "BY", "CACHE", "CALL", "CALLED", "CAPTURE", "CARDINALITY", "CASCADED", "CASE", "CAST", "CCSID", "CEIL", "CEILING", "CHAR", "CHARACTER", "CHARACTER_LENGTH", "CHAR_LENGTH", "CHECK", "CLOB", "CLONE", "CLOSE", "CLUSTER", "COALESCE", "COLLATE", "COLLECT", "COLLECTION", "COLLID", "COLUMN", "COMMENT", "COMMIT", "CONCAT", "CONDITION", "CONNECT", "CONNECTION", "CONSTRAINT", "CONTAINS", "CONTINUE", "CONVERT", "CORR", "CORRESPONDING", "COUNT", "COUNT_BIG", "COVAR_POP", "COVAR_SAMP", "CREATE", "CROSS", "CUBE", "CUME_DIST", "CURRENT", "CURRENT_DATE", "CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_LC_CTYPE", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_SERVER", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_TIMEZONE", "CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CURRENT_USER", "CURSOR", "CYCLE", "DATA", "DATABASE", "DATAPARTITIONNAME", "DATAPARTITIONNUM", "DATE", "DAY", "DAYS", "DB2GENERAL", "DB2GENRL", "DB2SQL", "DBINFO", "DBPARTITIONNAME", "DBPARTITIONNUM", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFAULTS", "DEFINITION", "DELETE", "DENSERANK", "DENSE_RANK", "DEREF", "DESCRIBE", "DESCRIPTOR", "DETERMINISTIC", "DIAGNOSTICS", "DISABLE", "DISALLOW", "DISCONNECT", "DISTINCT", "DO", "DOCUMENT", "DOUBLE", "DROP", "DSSIZE", "DYNAMIC", "EACH", "EDITPROC", "ELEMENT", "ELSE", "ELSEIF", "ENABLE", "ENCODING", "ENCRYPTION", "END", "END-EXEC", "ENDING", "ERASE", "ESCAPE", "EVERY", "EXCEPTION", "EXCLUDING", "EXCLUSIVE", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXP", "EXPLAIN", "EXTENDED", "EXTERNAL", "EXTRACT", "FALSE", "FENCED", "FETCH", "FIELDPROC", "FILE", "FILTER", "FINAL", "FIRST", "FLOAT", "FLOOR", "FOR", "FOREIGN", "FREE", "FULL", "FUNCTION", "FUSION", "GENERAL", "GENERATED", "GET", "GLOBAL", "GOTO", "GRANT", "GRAPHIC", "GROUP", "GROUPING", "HANDLER", "HASH", "HASHED_VALUE", "HINT", "HOLD", "HOUR", "HOURS", "IDENTITY", "IF", "IMMEDIATE", "IN", "INCLUDING", "INCLUSIVE", "INCREMENT", "INDEX", "INDICATOR", "INDICATORS", "INF", "INFINITY", "INHERIT", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTEGRITY", "INTERSECTION", "INTERVAL", "INTO", "IS", "ISOBID", "ISOLATION", "ITERATE", "JAR", "JAVA", "KEEP", "KEY", "LABEL", "LANGUAGE", "LARGE", "LATERAL", "LC_CTYPE", "LEADING", "LEAVE", "LEFT", "LIKE", "LINKTYPE", "LN", "LOCAL", "LOCALDATE", "LOCALE", "LOCALTIME", "LOCALTIMESTAMP", "LOCATOR", "LOCATORS", "LOCK", "LOCKMAX", "LOCKSIZE", "LONG", "LOOP", "LOWER", "MAINTAINED", "MATCH", "MATERIALIZED", "MAX", "MAXVALUE", "MEMBER", "MERGE", "METHOD", "MICROSECOND", "MICROSECONDS", "MIN", "MINUTE", "MINUTES", "MINVALUE", "MOD", "MODE", "MODIFIES", "MODULE", "MONTH", "MONTHS", "MULTISET", "NAN", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NEW", "NEW_TABLE", "NEXTVAL", "NO", "NOCACHE", "NOCYCLE", "NODENAME", "NODENUMBER", "NOMAXVALUE", "NOMINVALUE", "NONE", "NOORDER", "NORMALIZE", "NORMALIZED", "NOT", "NULL", "NULLIF", "NULLS", "NUMERIC", "NUMPARTS", "OBID", "OCTET_LENGTH", "OF", "OFFSET", "OLD", "OLD_TABLE", "ON", "ONLY", "OPEN", "OPTIMIZATION", "OPTIMIZE", "OPTION", "ORDER", "OUT", "OUTER", "OVER", "OVERLAPS", "OVERLAY", "OVERRIDING", "PACKAGE", "PADDED", "PAGESIZE", "PARAMETER", "PART", "PARTITION", "PARTITIONED", "PARTITIONING", "PARTITIONS", "PASSWORD", "PATH", "PERCENTILE_CONT", "PERCENTILE_DISC", "PERCENT_RANK", "PIECESIZE", "PLAN", "POSITION", "POWER", "PRECISION", "PREPARE", "PREVVAL", "PRIMARY", "PRIQTY", "PRIVILEGES", "PROCEDURE", "PROGRAM", "PSID", "PUBLIC", "QUERY", "QUERYNO", "RANGE", "RANK", "READ", "READS", "REAL", "RECOVERY", "RECURSIVE", "REF", "REFERENCES", "REFERENCING", "REFRESH", "REGR_AVGX", "REGR_AVGY", "REGR_COUNT", "REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX", "REGR_SXY", "REGR_SYY", "RELEASE", "RENAME", "REPEAT", "RESET", "RESIGNAL", "RESTART", "RESTRICT", "RESULT", "RESULT_SET_LOCATOR", "RETURN", "RETURNS", "REVOKE", "RIGHT", "ROLE", "ROLLBACK", "ROLLUP", "ROUND_CEILING", "ROUND_DOWN", "ROUND_FLOOR", "ROUND_HALF_DOWN", "ROUND_HALF_EVEN", "ROUND_HALF_UP", "ROUND_UP", "ROUTINE", "ROW", "ROWNUMBER", "ROWS", "ROWSET", "ROW_NUMBER", "RRN", "RUN", "SAVEPOINT", "SCHEMA", "SCOPE", "SCRATCHPAD", "SCROLL", "SEARCH", "SECOND", "SECONDS", "SECQTY", "SECURITY", "SENSITIVE", "SEQUENCE", "SESSION", "SESSION_USER", "SIGNAL", "SIMILAR", "SIMPLE", "SMALLINT", "SNAN", "SOME", "SOURCE", "SPECIFIC", "SPECIFICTYPE", "SQL", "SQLEXCEPTION", "SQLID", "SQLSTATE", "SQLWARNING", "SQRT", "STACKED", "STANDARD", "START", "STARTING", "STATEMENT", "STATIC", "STATMENT", "STAY", "STDDEV_POP", "STDDEV_SAMP", "STOGROUP", "STORES", "STYLE", "SUBMULTISET", "SUBSTRING", "SUM", "SUMMARY", "SYMMETRIC", "SYNONYM", "SYSFUN", "SYSIBM", "SYSPROC", "SYSTEM", "SYSTEM_USER", "TABLE", "TABLESAMPLE", "TABLESPACE", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TREAT", "TRIGGER", "TRIM", "TRUE", "TRUNCATE", "TYPE", "UESCAPE", "UNDO", "UNIQUE", "UNKNOWN", "UNNEST", "UNTIL", "UPPER", "USAGE", "USER", "USING", "VALIDPROC", "VALUE", "VARCHAR", "VARIABLE", "VARIANT", "VARYING", "VAR_POP", "VAR_SAMP", "VCAT", "VERSION", "VIEW", "VOLATILE", "VOLUMES", "WHEN", "WHENEVER", "WHILE", "WIDTH_BUCKET", "WINDOW", "WITH", "WITHIN", "WITHOUT", "WLM", "WRITE", "XMLELEMENT", "XMLEXISTS", "XMLNAMESPACES", "YEAR", "YEARS" ];
var o = [ "ADD", "AFTER", "ALTER COLUMN", "ALTER TABLE", "DELETE FROM", "EXCEPT", "FETCH FIRST", "FROM", "GROUP BY", "GO", "HAVING", "INSERT INTO", "INTERSECT", "LIMIT", "ORDER BY", "SELECT", "SET CURRENT SCHEMA", "SET SCHEMA", "SET", "UPDATE", "VALUES", "WHERE" ];
var c = [ "INTERSECT", "INTERSECT ALL", "MINUS", "UNION", "UNION ALL" ];
var l = [ "AND", "CROSS JOIN", "INNER JOIN", "JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "OR", "OUTER JOIN", "RIGHT JOIN", "RIGHT OUTER JOIN" ];
})(ad);
var pd = {};
(function(e) {
var t = r && r.__extends || function() {
var e = function(t, n) {
e = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(e, t) {
e.__proto__ = t;
} || function(e, t) {
for (var n in t) if (Object.prototype.hasOwnProperty.call(t, n)) e[n] = t[n];
};
return e(t, n);
};
return function(t, n) {
if (typeof n !== "function" && n !== null) throw new TypeError("Class extends value " + String(n) + " is not a constructor or null");
e(t, n);
function a() {
this.constructor = t;
}
t.prototype = n === null ? Object.create(n) : (a.prototype = n.prototype, new a);
};
}();
var n = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var a = n(rd);
var i = function(e) {
t(n, e);
function n() {
return e !== null && e.apply(this, arguments) || this;
}
n.prototype.getTokenizerConfig = function() {
return {
reservedWords: s,
reservedTopLevelWords: o,
reservedNewlineWords: l,
reservedTopLevelWordsNoIndent: c,
stringTypes: [ '""', "''", "``" ],
openParens: [ "(", "[", "{" ],
closeParens: [ ")", "]", "}" ],
namedPlaceholderTypes: [ "$" ],
lineCommentTypes: [ "#", "--" ],
specialWordChars: []
};
};
return n;
}(a["default"]);
e["default"] = i;
var s = [ "ALL", "ALTER", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "BEGIN", "BETWEEN", "BINARY", "BOOLEAN", "BREAK", "BUCKET", "BUILD", "BY", "CALL", "CASE", "CAST", "CLUSTER", "COLLATE", "COLLECTION", "COMMIT", "CONNECT", "CONTINUE", "CORRELATE", "COVER", "CREATE", "DATABASE", "DATASET", "DATASTORE", "DECLARE", "DECREMENT", "DELETE", "DERIVED", "DESC", "DESCRIBE", "DISTINCT", "DO", "DROP", "EACH", "ELEMENT", "ELSE", "END", "EVERY", "EXCEPT", "EXCLUDE", "EXECUTE", "EXISTS", "EXPLAIN", "FALSE", "FETCH", "FIRST", "FLATTEN", "FOR", "FORCE", "FROM", "FUNCTION", "GRANT", "GROUP", "GSI", "HAVING", "IF", "IGNORE", "ILIKE", "IN", "INCLUDE", "INCREMENT", "INDEX", "INFER", "INLINE", "INNER", "INSERT", "INTERSECT", "INTO", "IS", "JOIN", "KEY", "KEYS", "KEYSPACE", "KNOWN", "LAST", "LEFT", "LET", "LETTING", "LIKE", "LIMIT", "LSM", "MAP", "MAPPING", "MATCHED", "MATERIALIZED", "MERGE", "MISSING", "NAMESPACE", "NEST", "NOT", "NULL", "NUMBER", "OBJECT", "OFFSET", "ON", "OPTION", "OR", "ORDER", "OUTER", "OVER", "PARSE", "PARTITION", "PASSWORD", "PATH", "POOL", "PREPARE", "PRIMARY", "PRIVATE", "PRIVILEGE", "PROCEDURE", "PUBLIC", "RAW", "REALM", "REDUCE", "RENAME", "RETURN", "RETURNING", "REVOKE", "RIGHT", "ROLE", "ROLLBACK", "SATISFIES", "SCHEMA", "SELECT", "SELF", "SEMI", "SET", "SHOW", "SOME", "START", "STATISTICS", "STRING", "SYSTEM", "THEN", "TO", "TRANSACTION", "TRIGGER", "TRUE", "TRUNCATE", "UNDER", "UNION", "UNIQUE", "UNKNOWN", "UNNEST", "UNSET", "UPDATE", "UPSERT", "USE", "USER", "USING", "VALIDATE", "VALUE", "VALUED", "VALUES", "VIA", "VIEW", "WHEN", "WHERE", "WHILE", "WITH", "WITHIN", "WORK", "XOR" ];
var o = [ "DELETE FROM", "EXCEPT ALL", "EXCEPT", "EXPLAIN DELETE FROM", "EXPLAIN UPDATE", "EXPLAIN UPSERT", "FROM", "GROUP BY", "HAVING", "INFER", "INSERT INTO", "LET", "LIMIT", "MERGE", "NEST", "ORDER BY", "PREPARE", "SELECT", "SET CURRENT SCHEMA", "SET SCHEMA", "SET", "UNNEST", "UPDATE", "UPSERT", "USE KEYS", "VALUES", "WHERE" ];
var c = [ "INTERSECT", "INTERSECT ALL", "MINUS", "UNION", "UNION ALL" ];
var l = [ "AND", "INNER JOIN", "JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "OR", "OUTER JOIN", "RIGHT JOIN", "RIGHT OUTER JOIN", "XOR" ];
})(pd);
var md = {};
(function(e) {
var t = r && r.__extends || function() {
var e = function(t, n) {
e = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(e, t) {
e.__proto__ = t;
} || function(e, t) {
for (var n in t) if (Object.prototype.hasOwnProperty.call(t, n)) e[n] = t[n];
};
return e(t, n);
};
return function(t, n) {
if (typeof n !== "function" && n !== null) throw new TypeError("Class extends value " + String(n) + " is not a constructor or null");
e(t, n);
function a() {
this.constructor = t;
}
t.prototype = n === null ? Object.create(n) : (a.prototype = n.prototype, new a);
};
}();
var n = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var a = n(rd);
var i = od;
var s = function(e) {
t(n, e);
function n() {
var t = e !== null && e.apply(this, arguments) || this;
t.tokenOverride = function(e, t) {
if (e.type === i.TokenTypes.RESERVED_TOP_LEVEL && t.value && e.value.toUpperCase() === "SET" && t.value.toUpperCase() === "BY") {
e.type = i.TokenTypes.RESERVED;
return e;
}
};
return t;
}
n.prototype.getTokenizerConfig = function() {
return {
reservedWords: o,
reservedTopLevelWords: c,
reservedNewlineWords: u,
reservedTopLevelWordsNoIndent: l,
stringTypes: [ '""', "N''", "''", "``" ],
openParens: [ "(", "CASE" ],
closeParens: [ ")", "END" ],
indexedPlaceholderTypes: [ "?" ],
namedPlaceholderTypes: [ ":" ],
lineCommentTypes: [ "--" ],
specialWordChars: [ "_", "$", "#", ".", "@" ]
};
};
return n;
}(a["default"]);
e["default"] = s;
var o = [ "A", "ACCESSIBLE", "AGENT", "AGGREGATE", "ALL", "ALTER", "ANY", "ARRAY", "AS", "ASC", "AT", "ATTRIBUTE", "AUTHID", "AVG", "BETWEEN", "BFILE_BASE", "BINARY_INTEGER", "BINARY", "BLOB_BASE", "BLOCK", "BODY", "BOOLEAN", "BOTH", "BOUND", "BREADTH", "BULK", "BY", "BYTE", "C", "CALL", "CALLING", "CASCADE", "CASE", "CHAR_BASE", "CHAR", "CHARACTER", "CHARSET", "CHARSETFORM", "CHARSETID", "CHECK", "CLOB_BASE", "CLONE", "CLOSE", "CLUSTER", "CLUSTERS", "COALESCE", "COLAUTH", "COLLECT", "COLUMNS", "COMMENT", "COMMIT", "COMMITTED", "COMPILED", "COMPRESS", "CONNECT", "CONSTANT", "CONSTRUCTOR", "CONTEXT", "CONTINUE", "CONVERT", "COUNT", "CRASH", "CREATE", "CREDENTIAL", "CURRENT", "CURRVAL", "CURSOR", "CUSTOMDATUM", "DANGLING", "DATA", "DATE_BASE", "DATE", "DAY", "DECIMAL", "DEFAULT", "DEFINE", "DELETE", "DEPTH", "DESC", "DETERMINISTIC", "DIRECTORY", "DISTINCT", "DO", "DOUBLE", "DROP", "DURATION", "ELEMENT", "ELSIF", "EMPTY", "END", "ESCAPE", "EXCEPTIONS", "EXCLUSIVE", "EXECUTE", "EXISTS", "EXIT", "EXTENDS", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FINAL", "FIRST", "FIXED", "FLOAT", "FOR", "FORALL", "FORCE", "FROM", "FUNCTION", "GENERAL", "GOTO", "GRANT", "GROUP", "HASH", "HEAP", "HIDDEN", "HOUR", "IDENTIFIED", "IF", "IMMEDIATE", "IN", "INCLUDING", "INDEX", "INDEXES", "INDICATOR", "INDICES", "INFINITE", "INSTANTIABLE", "INT", "INTEGER", "INTERFACE", "INTERVAL", "INTO", "INVALIDATE", "IS", "ISOLATION", "JAVA", "LANGUAGE", "LARGE", "LEADING", "LENGTH", "LEVEL", "LIBRARY", "LIKE", "LIKE2", "LIKE4", "LIKEC", "LIMITED", "LOCAL", "LOCK", "LONG", "MAP", "MAX", "MAXLEN", "MEMBER", "MERGE", "MIN", "MINUTE", "MLSLABEL", "MOD", "MODE", "MONTH", "MULTISET", "NAME", "NAN", "NATIONAL", "NATIVE", "NATURAL", "NATURALN", "NCHAR", "NEW", "NEXTVAL", "NOCOMPRESS", "NOCOPY", "NOT", "NOWAIT", "NULL", "NULLIF", "NUMBER_BASE", "NUMBER", "OBJECT", "OCICOLL", "OCIDATE", "OCIDATETIME", "OCIDURATION", "OCIINTERVAL", "OCILOBLOCATOR", "OCINUMBER", "OCIRAW", "OCIREF", "OCIREFCURSOR", "OCIROWID", "OCISTRING", "OCITYPE", "OF", "OLD", "ON", "ONLY", "OPAQUE", "OPEN", "OPERATOR", "OPTION", "ORACLE", "ORADATA", "ORDER", "ORGANIZATION", "ORLANY", "ORLVARY", "OTHERS", "OUT", "OVERLAPS", "OVERRIDING", "PACKAGE", "PARALLEL_ENABLE", "PARAMETER", "PARAMETERS", "PARENT", "PARTITION", "PASCAL", "PCTFREE", "PIPE", "PIPELINED", "PLS_INTEGER", "PLUGGABLE", "POSITIVE", "POSITIVEN", "PRAGMA", "PRECISION", "PRIOR", "PRIVATE", "PROCEDURE", "PUBLIC", "RAISE", "RANGE", "RAW", "READ", "REAL", "RECORD", "REF", "REFERENCE", "RELEASE", "RELIES_ON", "REM", "REMAINDER", "RENAME", "RESOURCE", "RESULT_CACHE", "RESULT", "RETURN", "RETURNING", "REVERSE", "REVOKE", "ROLLBACK", "ROW", "ROWID", "ROWNUM", "ROWTYPE", "SAMPLE", "SAVE", "SAVEPOINT", "SB1", "SB2", "SB4", "SEARCH", "SECOND", "SEGMENT", "SELF", "SEPARATE", "SEQUENCE", "SERIALIZABLE", "SHARE", "SHORT", "SIZE_T", "SIZE", "SMALLINT", "SOME", "SPACE", "SPARSE", "SQL", "SQLCODE", "SQLDATA", "SQLERRM", "SQLNAME", "SQLSTATE", "STANDARD", "START", "STATIC", "STDDEV", "STORED", "STRING", "STRUCT", "STYLE", "SUBMULTISET", "SUBPARTITION", "SUBSTITUTABLE", "SUBTYPE", "SUCCESSFUL", "SUM", "SYNONYM", "SYSDATE", "TABAUTH", "TABLE", "TDO", "THE", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_ABBR", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TIMEZONE_REGION", "TO", "TRAILING", "TRANSACTION", "TRANSACTIONAL", "TRIGGER", "TRUE", "TRUSTED", "TYPE", "UB1", "UB2", "UB4", "UID", "UNDER", "UNIQUE", "UNPLUG", "UNSIGNED", "UNTRUSTED", "USE", "USER", "USING", "VALIDATE", "VALIST", "VALUE", "VARCHAR", "VARCHAR2", "VARIABLE", "VARIANCE", "VARRAY", "VARYING", "VIEW", "VIEWS", "VOID", "WHENEVER", "WHILE", "WITH", "WORK", "WRAPPED", "WRITE", "YEAR", "ZONE" ];
var c = [ "ADD", "ALTER COLUMN", "ALTER TABLE", "BEGIN", "CONNECT BY", "DECLARE", "DELETE FROM", "DELETE", "END", "EXCEPT", "EXCEPTION", "FETCH FIRST", "FROM", "GROUP BY", "HAVING", "INSERT INTO", "INSERT", "LIMIT", "LOOP", "MODIFY", "ORDER BY", "SELECT", "SET CURRENT SCHEMA", "SET SCHEMA", "SET", "START WITH", "UPDATE", "VALUES", "WHERE" ];
var l = [ "INTERSECT", "INTERSECT ALL", "MINUS", "UNION", "UNION ALL" ];
var u = [ "AND", "CROSS APPLY", "CROSS JOIN", "ELSE", "END", "INNER JOIN", "JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "OR", "OUTER APPLY", "OUTER JOIN", "RIGHT JOIN", "RIGHT OUTER JOIN", "WHEN", "XOR" ];
})(md);
var fd = {};
(function(e) {
var t = r && r.__extends || function() {
var e = function(t, n) {
e = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(e, t) {
e.__proto__ = t;
} || function(e, t) {
for (var n in t) if (Object.prototype.hasOwnProperty.call(t, n)) e[n] = t[n];
};
return e(t, n);
};
return function(t, n) {
if (typeof n !== "function" && n !== null) throw new TypeError("Class extends value " + String(n) + " is not a constructor or null");
e(t, n);
function a() {
this.constructor = t;
}
t.prototype = n === null ? Object.create(n) : (a.prototype = n.prototype, new a);
};
}();
var n = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
var a = n(rd);
var i = function(e) {
t(n, e);
function n() {
return e !== null && e.apply(this, arguments) || this;
}
n.prototype.getTokenizerConfig = function() {
return {
reservedWords: s,
reservedTopLevelWords: o,
reservedNewlineWords: l,
reservedTopLevelWordsNoIndent: c,
stringTypes: [ '""', "N''", "''", "``", "[]", "E''" ],
openParens: [ "(", "CASE" ],
closeParens: [ ")", "END" ],
indexedPlaceholderTypes: [ "?" ],
namedPlaceholderTypes: [ "@", ":", "%", "$" ],
lineCommentTypes: [ "#", "--" ],
specialWordChars: []
};
};
return n;
}(a["default"]);
e["default"] = i;
var s = [ "ACCESSIBLE", "ACTION", "AGAINST", "AGGREGATE", "ALGORITHM", "ALL", "ALTER", "ANALYSE", "ANALYZE", "AS", "ASC", "AUTOCOMMIT", "AUTO_INCREMENT", "BACKUP", "BEGIN", "BETWEEN", "BINLOG", "BOTH", "CASCADE", "CASE", "CHANGE", "CHANGED", "CHARACTER SET", "CHARSET", "CHECK", "CHECKSUM", "COLLATE", "COLLATION", "COLUMN", "COLUMNS", "COMMENT", "COMMIT", "COMMITTED", "COMPRESSED", "CONCURRENT", "CONSTRAINT", "CONTAINS", "CONVERT", "COUNT", "CREATE", "CROSS", "CURRENT_TIMESTAMP", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MINUTE", "DAY_SECOND", "DAY", "DEFAULT", "DEFINER", "DELAYED", "DELETE", "DESC", "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DO", "DROP", "DUMPFILE", "DUPLICATE", "DYNAMIC", "ELSE", "ENCLOSED", "END", "ENGINE", "ENGINES", "ENGINE_TYPE", "ESCAPE", "ESCAPED", "EVENTS", "EXEC", "EXECUTE", "EXISTS", "EXPLAIN", "EXTENDED", "FAST", "FETCH", "FIELDS", "FILE", "FIRST", "FIXED", "FLUSH", "FOR", "FORCE", "FOREIGN", "FULL", "FULLTEXT", "FUNCTION", "GLOBAL", "GRANTS", "GROUP_CONCAT", "HEAP", "HIGH_PRIORITY", "HOSTS", "HOUR", "HOUR_MINUTE", "HOUR_SECOND", "IDENTIFIED", "IF", "IFNULL", "IGNORE", "IN", "INDEX", "INDEXES", "INFILE", "INSERT", "INSERT_ID", "INSERT_METHOD", "INTERVAL", "INTO", "INVOKER", "IS", "ISOLATION", "KEY", "KEYS", "KILL", "LAST_INSERT_ID", "LEADING", "LEVEL", "LIKE", "LINEAR", "LINES", "LOAD", "LOCAL", "LOCK", "LOCKS", "LOGS", "LOW_PRIORITY", "MARIA", "MASTER", "MASTER_CONNECT_RETRY", "MASTER_HOST", "MASTER_LOG_FILE", "MATCH", "MAX_CONNECTIONS_PER_HOUR", "MAX_QUERIES_PER_HOUR", "MAX_ROWS", "MAX_UPDATES_PER_HOUR", "MAX_USER_CONNECTIONS", "MEDIUM", "MERGE", "MINUTE", "MINUTE_SECOND", "MIN_ROWS", "MODE", "MONTH", "MRG_MYISAM", "MYISAM", "NAMES", "NATURAL", "NOT", "NOW()", "NULL", "OFFSET", "ON DELETE", "ON UPDATE", "ON", "ONLY", "OPEN", "OPTIMIZE", "OPTION", "OPTIONALLY", "OUTFILE", "PACK_KEYS", "PAGE", "PARTIAL", "PARTITION", "PARTITIONS", "PASSWORD", "PRIMARY", "PRIVILEGES", "PROCEDURE", "PROCESS", "PROCESSLIST", "PURGE", "QUICK", "RAID0", "RAID_CHUNKS", "RAID_CHUNKSIZE", "RAID_TYPE", "RANGE", "READ", "READ_ONLY", "READ_WRITE", "REFERENCES", "REGEXP", "RELOAD", "RENAME", "REPAIR", "REPEATABLE", "REPLACE", "REPLICATION", "RESET", "RESTORE", "RESTRICT", "RETURN", "RETURNS", "REVOKE", "RLIKE", "ROLLBACK", "ROW", "ROWS", "ROW_FORMAT", "SECOND", "SECURITY", "SEPARATOR", "SERIALIZABLE", "SESSION", "SHARE", "SHOW", "SHUTDOWN", "SLAVE", "SONAME", "SOUNDS", "SQL", "SQL_AUTO_IS_NULL", "SQL_BIG_RESULT", "SQL_BIG_SELECTS", "SQL_BIG_TABLES", "SQL_BUFFER_RESULT", "SQL_CACHE", "SQL_CALC_FOUND_ROWS", "SQL_LOG_BIN", "SQL_LOG_OFF", "SQL_LOG_UPDATE", "SQL_LOW_PRIORITY_UPDATES", "SQL_MAX_JOIN_SIZE", "SQL_NO_CACHE", "SQL_QUOTE_SHOW_CREATE", "SQL_SAFE_UPDATES", "SQL_SELECT_LIMIT", "SQL_SLAVE_SKIP_COUNTER", "SQL_SMALL_RESULT", "SQL_WARNINGS", "START", "STARTING", "STATUS", "STOP", "STORAGE", "STRAIGHT_JOIN", "STRING", "STRIPED", "SUPER", "TABLE", "TABLES", "TEMPORARY", "TERMINATED", "THEN", "TO", "TRAILING", "TRANSACTIONAL", "TRIGGER", "TRUE", "TRUNCATE", "TYPE", "TYPES", "UNCOMMITTED", "UNIQUE", "UNLOCK", "UNSIGNED", "USAGE", "USE", "USING", "VARIABLES", "VIEW", "WHEN", "WITH", "WORK", "WRITE", "YEAR_MONTH" ];
var o = [ "ADD", "AFTER", "ALTER COLUMN", "ALTER TABLE", "CREATE OR REPLACE", "DECLARE", "DELETE FROM", "EXCEPT", "FETCH FIRST", "FROM", "GO", "GRANT", "GROUP BY", "HAVING", "INSERT INTO", "INSERT", "LIMIT", "MODIFY", "ORDER BY", "RETURNING", "SELECT", "SET CURRENT SCHEMA", "SET SCHEMA", "SET", "UPDATE", "VALUES", "WHERE" ];
var c = [ "INTERSECT ALL", "INTERSECT", "MINUS", "UNION ALL", "UNION" ];
var l = [ "AND", "CROSS APPLY", "CROSS JOIN", "ELSE", "INNER JOIN", "FULL JOIN", "FULL OUTER JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "NATURAL JOIN", "OR", "OUTER APPLY", "OUTER JOIN", "RENAME", "RIGHT JOIN", "RIGHT OUTER JOIN", "JOIN", "WHEN", "XOR" ];
})(fd);
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
e.__esModule = true;
e.tokenize = e.format = void 0;
var n = t(ad);
var a = t(pd);
var i = t(md);
var s = t(fd);
var o = function(e, t) {
if (t === void 0) {
t = {};
}
switch (t.language) {
case "db2":
return new n["default"](t).format(e);
case "n1ql":
return new a["default"](t).format(e);
case "pl/sql":
return new i["default"](t).format(e);
case "sql":
default:
return new s["default"](t).format(e);
}
};
e.format = o;
var c = function(e, t) {
if (t === void 0) {
t = {};
}
return new s["default"](t).tokenize(e);
};
e.tokenize = c;
e["default"] = {
format: e.format,
tokenize: e.tokenize
};
})(nd);
(function(t) {
Object.defineProperty(t, "__esModule", {
value: true
});
t.PlatformTools = t.Writable = t.Readable = t.ReadStream = t.EventEmitter = void 0;
const n = e;
const a = n.__importDefault(jh());
const i = n.__importDefault(Wh());
const l = n.__importDefault(o);
const u = n.__importDefault(c);
const p = td();
const m = nd;
var f = h;
Object.defineProperty(t, "EventEmitter", {
enumerable: true,
get: function() {
return f.EventEmitter;
}
});
var y = o;
Object.defineProperty(t, "ReadStream", {
enumerable: true,
get: function() {
return y.ReadStream;
}
});
var E = d;
Object.defineProperty(t, "Readable", {
enumerable: true,
get: function() {
return E.Readable;
}
});
Object.defineProperty(t, "Writable", {
enumerable: true,
get: function() {
return E.Writable;
}
});
class PlatformTools {
static getGlobalVariable() {
return r;
}
static load(e) {
try {
switch (e) {
case "spanner":
return require("@google-cloud/spanner");
case "mongodb":
return require("mongodb");
case "@sap/hana-client":
return require("@sap/hana-client");
case "@sap/hana-client/extension/Stream":
return require("@sap/hana-client/extension/Stream");
case "hdb-pool":
return require("hdb-pool");
case "mysql":
return require("mysql");
case "mysql2":
return require("mysql2");
case "oracledb":
return require("oracledb");
case "pg":
return require("pg");
case "pg-native":
return require("pg-native");
case "pg-query-stream":
return require("pg-query-stream");
case "typeorm-aurora-data-api-driver":
return require("typeorm-aurora-data-api-driver");
case "redis":
return require("redis");
case "ioredis":
return require("ioredis");
case "better-sqlite3":
return require("better-sqlite3");
case "sqlite3":
return require("sqlite3");
case "sql.js":
return require("sql.js");
case "mssql":
return require("mssql");
case "react-native-sqlite-storage":
return require("react-native-sqlite-storage");
}
} catch (t) {
return s(u.default.resolve(process.cwd() + "/node_modules/" + e));
}
throw new TypeError(`Invalid Package for PlatformTools.load: ${e}`);
}
static pathNormalize(e) {
let t = u.default.normalize(e);
if (process.platform === "win32") t = t.replace(/\\/g, "/");
return t;
}
static pathExtname(e) {
return u.default.extname(e);
}
static pathResolve(e) {
return u.default.resolve(e);
}
static fileExist(e) {
return l.default.existsSync(e);
}
static readFileSync(e) {
return l.default.readFileSync(e);
}
static appendFileSync(e, t) {
l.default.appendFileSync(e, t);
}
static async writeFile(e, t) {
return l.default.promises.writeFile(e, t);
}
static dotenv(e) {
i.default.config({
path: e
});
}
static getEnvVariable(e) {
return process.env[e];
}
static highlightSql(e) {
return (0, p.highlight)(e, {
colors: {
keyword: a.default.blueBright.open,
function: a.default.magentaBright.open,
number: a.default.green.open,
string: a.default.white.open,
identifier: a.default.white.open,
special: a.default.white.open,
bracket: a.default.white.open,
comment: a.default.gray.open,
clear: a.default.reset.open
}
});
}
static formatSql(e, t) {
const n = {
oracle: "pl/sql"
};
const a = t ? n[t] || "sql" : "sql";
return (0, m.format)(e, {
language: a,
indent: " "
});
}
static logInfo(e, t) {
console.log(a.default.gray.underline(e), t);
}
static logError(e, t) {
console.log(a.default.underline.red(e), t);
}
static logWarn(e, t) {
console.log(a.default.underline.yellow(e), t);
}
static log(e) {
console.log(a.default.underline(e));
}
static info(e) {
return a.default.gray(e);
}
static error(e) {
return a.default.red(e);
}
static warn(e) {
return a.default.yellow(e);
}
static logCmdErr(e, t) {
console.log(a.default.black.bgRed(e));
if (t) console.error(t);
}
}
t.PlatformTools = PlatformTools;
PlatformTools.type = "node";
})(Uh);
var yd = {};
var Ed;
var Td;
function gd() {
if (Td) return Ed;
Td = 1;
var e = c;
var t = p.globalPaths;
var n;
if ("win32" === process.platform) {
n = e.dirname(process.execPath);
} else {
n = e.dirname(e.dirname(process.execPath));
}
var a = e.resolve(n, "lib", "node_modules");
var r = e.sep;
var i = "function" === typeof __webpack_require__ || "function" === typeof __non_webpack_require__ ? __non_webpack_require__ : s;
const o = function(e) {
const n = r + ".pnpm";
for (const a of t) {
if (-1 !== a.indexOf(n) && -1 !== e.indexOf(n)) {
return true;
}
}
return false;
};
const l = function(e) {
const t = r + "node_modules";
if (-1 !== e.indexOf(t)) {
const n = e.split(t);
if (n.length) {
return n[0];
}
}
return null;
};
Ed = function n(s) {
if (process.env.APP_ROOT_PATH) {
return e.resolve(process.env.APP_ROOT_PATH);
}
if (process.versions.pnp) {
try {
var c = i("pnpapi");
return c.getPackageInformation(c.topLevel).packageLocation;
} catch (e) {}
}
if ("undefined" !== typeof window && window.process && "renderer" === window.process.type) {
try {
var u = i("electron").remote;
return u.require("app-root-path").path;
} catch (e) {}
}
if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) {
return process.env.LAMBDA_TASK_ROOT;
}
var h = e.resolve(s);
var d = false;
var p = null;
if (o(h)) {
p = l(h);
if (p) {
return p;
}
}
t.forEach(function(e) {
if (!d && 0 === h.indexOf(e)) {
d = true;
}
});
if (!d) {
p = l(h);
}
if (d || null == p) {
if (i.main) {
p = e.dirname(i.main.filename);
} else {
p = e.dirname(process.argv[1]);
}
}
if (d && -1 !== p.indexOf(a) && p.length - 4 === p.indexOf(r + "bin")) {
p = p.slice(0, -4);
}
return p;
};
return Ed;
}
var Nd;
var Ad;
function bd() {
if (Ad) return Nd;
Ad = 1;
Nd = function(e) {
var t = c;
var n = gd();
var a = n(e);
var r = {
resolve: function(e) {
return t.join(a, e);
},
require: function(e) {
return s(r.resolve(e));
},
toString: function() {
return a;
},
setPath: function(e) {
a = t.resolve(e);
r.path = a;
},
path: a
};
return r;
};
return Nd;
}
var Cd;
var Rd;
function Sd() {
if (Rd) return Cd;
Rd = 1;
var e = bd();
Cd = e(__dirname);
return Cd;
}
var wd = {};
var Md;
function Od() {
if (Md) return wd;
Md = 1;
Object.defineProperty(wd, "__esModule", {
value: true
});
wd.importOrRequireFile = i;
const t = e;
const n = t.__importDefault(m);
const a = t.__importDefault(c);
const r = f;
async function i(e) {
const t = async () => [ await Function("return filePath => import(filePath)")()(e.startsWith("file://") ? e : (0,
r.pathToFileURL)(e).toString()), "esm" ];
const n = async () => [ s(e), "commonjs" ];
const a = e.substring(e.lastIndexOf(".") + ".".length);
if (a === "mjs" || a === "mts") return t(); else if (a === "cjs" || a === "cts") return n(); else if (a === "js" || a === "ts") {
const a = await o(e);
if (a != null) {
const e = a?.type === "module";
if (e) return t(); else return n();
} else return n();
}
return n();
}
async function o(e) {
let t = e;
while (t !== a.default.dirname(t)) {
t = a.default.dirname(t);
const e = a.default.join(t, "package.json");
try {
const t = await n.default.stat(e);
if (!t.isFile()) {
continue;
}
try {
return JSON.parse(await n.default.readFile(e, "utf8"));
} catch {
return null;
}
} catch {
continue;
}
}
return null;
}
return wd;
}
var vd = {};
var Id;
function Pd() {
if (Id) return vd;
Id = 1;
Object.defineProperty(vd, "__esModule", {
value: true
});
vd.toPortablePath = a;
vd.filepathToName = r;
vd.isAbsolute = i;
const e = kn;
const t = /^([a-zA-Z]:.*)$/;
const n = /^\\\\(\.\\)?(.*)$/;
function a(e) {
if (process.platform !== `win32`) return e;
if (e.match(t)) e = e.replace(t, `/$1`); else if (e.match(n)) e = e.replace(n, (e, t, n) => `/unc/${t ? `.dot/` : ``}${n}`);
return e.replace(/\\/g, `/`);
}
function r(t) {
const n = a(t).toLowerCase();
return (0, e.hash)(n, {
length: 63
});
}
function i(e) {
return !!e.match(/^(?:[a-z]:|[\\]|[/])/i);
}
return vd;
}
var Ld = {};
var Dd;
function _d() {
if (Dd) return Ld;
Dd = 1;
Object.defineProperty(Ld, "__esModule", {
value: true
});
Ld.ConnectionOptionsEnvReader = void 0;
const e = Uh;
const t = qc;
let n = class ConnectionOptionsEnvReader {
async read() {
return [ {
type: e.PlatformTools.getEnvVariable("TYPEORM_CONNECTION") || (e.PlatformTools.getEnvVariable("TYPEORM_URL") ? e.PlatformTools.getEnvVariable("TYPEORM_URL").split("://")[0] : undefined),
url: e.PlatformTools.getEnvVariable("TYPEORM_URL"),
host: e.PlatformTools.getEnvVariable("TYPEORM_HOST"),
port: this.stringToNumber(e.PlatformTools.getEnvVariable("TYPEORM_PORT")),
username: e.PlatformTools.getEnvVariable("TYPEORM_USERNAME"),
password: e.PlatformTools.getEnvVariable("TYPEORM_PASSWORD"),
database: e.PlatformTools.getEnvVariable("TYPEORM_DATABASE"),
sid: e.PlatformTools.getEnvVariable("TYPEORM_SID"),
schema: e.PlatformTools.getEnvVariable("TYPEORM_SCHEMA"),
extra: e.PlatformTools.getEnvVariable("TYPEORM_DRIVER_EXTRA") ? JSON.parse(e.PlatformTools.getEnvVariable("TYPEORM_DRIVER_EXTRA")) : undefined,
synchronize: t.OrmUtils.toBoolean(e.PlatformTools.getEnvVariable("TYPEORM_SYNCHRONIZE")),
dropSchema: t.OrmUtils.toBoolean(e.PlatformTools.getEnvVariable("TYPEORM_DROP_SCHEMA")),
migrationsRun: t.OrmUtils.toBoolean(e.PlatformTools.getEnvVariable("TYPEORM_MIGRATIONS_RUN")),
entities: this.stringToArray(e.PlatformTools.getEnvVariable("TYPEORM_ENTITIES")),
migrations: this.stringToArray(e.PlatformTools.getEnvVariable("TYPEORM_MIGRATIONS")),
migrationsTableName: e.PlatformTools.getEnvVariable("TYPEORM_MIGRATIONS_TABLE_NAME"),
metadataTableName: e.PlatformTools.getEnvVariable("TYPEORM_METADATA_TABLE_NAME"),
subscribers: this.stringToArray(e.PlatformTools.getEnvVariable("TYPEORM_SUBSCRIBERS")),
logging: this.transformLogging(e.PlatformTools.getEnvVariable("TYPEORM_LOGGING")),
logger: e.PlatformTools.getEnvVariable("TYPEORM_LOGGER"),
entityPrefix: e.PlatformTools.getEnvVariable("TYPEORM_ENTITY_PREFIX"),
maxQueryExecutionTime: e.PlatformTools.getEnvVariable("TYPEORM_MAX_QUERY_EXECUTION_TIME"),
debug: e.PlatformTools.getEnvVariable("TYPEORM_DEBUG"),
cache: this.transformCaching(),
uuidExtension: e.PlatformTools.getEnvVariable("TYPEORM_UUID_EXTENSION")
} ];
}
transformLogging(e) {
if (e === "true" || e === "TRUE" || e === "1") return true;
if (e === "all") return "all";
return this.stringToArray(e);
}
transformCaching() {
const t = e.PlatformTools.getEnvVariable("TYPEORM_CACHE");
if (t === "true" || t === "TRUE" || t === "1") return true;
if (t === "false" || t === "FALSE" || t === "0") return false;
if (t === "redis" || t === "ioredis" || t === "database") return {
type: t,
options: e.PlatformTools.getEnvVariable("TYPEORM_CACHE_OPTIONS") ? JSON.parse(e.PlatformTools.getEnvVariable("TYPEORM_CACHE_OPTIONS")) : undefined,
alwaysEnabled: e.PlatformTools.getEnvVariable("TYPEORM_CACHE_ALWAYS_ENABLED"),
duration: parseInt(e.PlatformTools.getEnvVariable("TYPEORM_CACHE_DURATION"))
};
return undefined;
}
stringToArray(e) {
if (!e) return [];
return e.split(",").map(e => e.trim());
}
stringToNumber(e) {
if (!e) {
return undefined;
}
return parseInt(e);
}
};
Ld.ConnectionOptionsEnvReader = n;
return Ld;
}
Object.defineProperty(yd, "__esModule", {
value: true
});
var $d = yd.ConnectionOptionsReader = void 0;
const xd = e;
const qd = xd.__importDefault(Sd());
const Ud = xd.__importDefault(c);
const Bd = P;
const Fd = Uh;
const jd = Od();
const kd = Pd();
const Qd = _d();
class ConnectionOptionsReader {
constructor(e) {
this.options = e;
}
async all() {
const e = await this.load();
if (!e) throw new Bd.TypeORMError(`No connection options were found in any orm configuration files.`);
return e;
}
async get(e) {
const t = await this.all();
const n = t.find(t => t.name === e || e === "default" && !t.name);
if (!n) throw new Bd.TypeORMError(`Cannot find connection ${e} because its not defined in any orm configuration files.`);
return n;
}
async has(e) {
const t = await this.load();
if (!t) return false;
const n = t.find(t => t.name === e || e === "default" && !t.name);
return !!n;
}
async load() {
let e = undefined;
const t = [ "env", "js", "mjs", "cjs", "ts", "mts", "cts", "json" ];
const n = this.baseFilePath.substr(this.baseFilePath.lastIndexOf("."));
const a = t.find(e => `.${e}` === n);
const r = a || t.find(e => Fd.PlatformTools.fileExist(this.baseFilePath + "." + e));
const i = a ? this.baseFilePath : this.baseFilePath + "." + r;
if (r === "env") {
Fd.PlatformTools.dotenv(i);
} else if (Fd.PlatformTools.fileExist(this.baseDirectory + "/.env")) {
Fd.PlatformTools.dotenv(this.baseDirectory + "/.env");
}
if (Fd.PlatformTools.getEnvVariable("TYPEORM_CONNECTION") || Fd.PlatformTools.getEnvVariable("TYPEORM_URL")) {
e = await (new Qd.ConnectionOptionsEnvReader).read();
} else if (r === "js" || r === "mjs" || r === "cjs" || r === "ts" || r === "mts" || r === "cts") {
const [t, n] = await (0, jd.importOrRequireFile)(i);
const a = await t;
if (n === "esm" || a && "__esModule" in a && "default" in a) {
e = a.default;
} else {
e = a;
}
} else if (r === "json") {
e = s(i);
}
if (e) {
return this.normalizeConnectionOptions(e);
}
return undefined;
}
normalizeConnectionOptions(e) {
if (!Array.isArray(e)) e = [ e ];
e.forEach(t => {
t.baseDirectory = this.baseDirectory;
if (t.entities) {
const n = t.entities.map(e => {
if (typeof e === "string" && e.substr(0, 1) !== "/") return this.baseDirectory + "/" + e;
return e;
});
Object.assign(e, {
entities: n
});
}
if (t.subscribers) {
const n = t.subscribers.map(e => {
if (typeof e === "string" && e.substr(0, 1) !== "/") return this.baseDirectory + "/" + e;
return e;
});
Object.assign(e, {
subscribers: n
});
}
if (t.migrations) {
const n = t.migrations.map(e => {
if (typeof e === "string" && e.substr(0, 1) !== "/") return this.baseDirectory + "/" + e;
return e;
});
Object.assign(e, {
migrations: n
});
}
if (t.type === "sqlite" || t.type === "better-sqlite3") {
if (typeof t.database === "string" && !(0, kd.isAbsolute)(t.database) && t.database.substr(0, 1) !== "/" && t.database.substr(1, 2) !== ":\\" && t.database !== ":memory:") {
Object.assign(t, {
database: this.baseDirectory + "/" + t.database
});
}
}
});
return e;
}
get baseFilePath() {
return Ud.default.resolve(this.baseDirectory, this.baseConfigName);
}
get baseDirectory() {
return this.options?.root ?? qd.default.path;
}
get baseConfigName() {
return this.options?.configName ?? "ormconfig";
}
}
$d = yd.ConnectionOptionsReader = ConnectionOptionsReader;
var Vd = {};
var Kd;
function Wd() {
if (Kd) return Vd;
Kd = 1;
Object.defineProperty(Vd, "__esModule", {
value: true
});
Vd.ConnectionManager = void 0;
const e = jw();
const t = Rt();
const n = U();
let a = class ConnectionManager {
constructor() {
this.connectionMap = new Map;
}
get connections() {
return Array.from(this.connectionMap.values());
}
has(e) {
return this.connectionMap.has(e);
}
get(e = "default") {
const n = this.connectionMap.get(e);
if (!n) throw new t.ConnectionNotFoundError(e);
return n;
}
create(t) {
const a = this.connectionMap.get(t.name || "default");
if (a) {
if (a.isInitialized) throw new n.AlreadyHasActiveConnectionError(t.name || "default");
}
const r = new e.DataSource(t);
this.connectionMap.set(r.name, r);
return r;
}
};
Vd.ConnectionManager = a;
return Vd;
}
var Hd = {};
Object.defineProperty(Hd, "__esModule", {
value: true
});
var Gd = Hd.useContainer = Zd;
var Yd = Hd.getFromContainer = ep;
const zd = new class {
constructor() {
this.instances = [];
}
get(e) {
let t = this.instances.find(t => t.type === e);
if (!t) {
t = {
type: e,
object: new e
};
this.instances.push(t);
}
return t.object;
}
};
let Jd;
let Xd;
function Zd(e, t) {
Jd = e;
Xd = t;
}
function ep(e) {
if (Jd) {
try {
const t = Jd.get(e);
if (t) return t;
if (!Xd || !Xd.fallback) return t;
} catch (e) {
if (!Xd || !Xd.fallbackOnErrors) throw e;
}
}
return zd.get(e);
}
var tp;
function np() {
if (tp) return _h;
tp = 1;
Object.defineProperty(_h, "__esModule", {
value: true
});
_h.getMetadataArgsStorage = s;
_h.getConnectionOptions = o;
_h.getConnectionManager = c;
_h.createConnection = l;
_h.createConnections = u;
_h.getConnection = h;
_h.getManager = d;
_h.getMongoManager = p;
_h.getSqljsManager = m;
_h.getRepository = f;
_h.getTreeRepository = y;
_h.getCustomRepository = E;
_h.getMongoRepository = T;
_h.createQueryBuilder = g;
const e = $h;
const t = Uh;
const n = yd;
const a = Wd();
const r = Hd;
const i = I;
function s() {
const n = t.PlatformTools.getGlobalVariable();
if (!n.typeormMetadataArgsStorage) n.typeormMetadataArgsStorage = new e.MetadataArgsStorage;
return n.typeormMetadataArgsStorage;
}
async function o(e = "default") {
return (new n.ConnectionOptionsReader).get(e);
}
function c() {
return (0, r.getFromContainer)(a.ConnectionManager);
}
async function l(e) {
const t = typeof e === "string" ? e : "default";
const n = i.ObjectUtils.isObject(e) ? e : await o(t);
return c().create(n).connect();
}
async function u(e) {
if (!e) e = await (new n.ConnectionOptionsReader).all();
const t = e.map(e => c().create(e));
for (const e of t) {
await e.connect();
}
return t;
}
function h(e = "default") {
return c().get(e);
}
function d(e = "default") {
return c().get(e).manager;
}
function p(e = "default") {
return c().get(e).manager;
}
function m(e = "default") {
return c().get(e).manager;
}
function f(e, t = "default") {
return c().get(t).getRepository(e);
}
function y(e, t = "default") {
return c().get(t).getTreeRepository(e);
}
function E(e, t = "default") {
return c().get(t).getCustomRepository(e);
}
function T(e, t = "default") {
return c().get(t).getMongoRepository(e);
}
function g(e, t, n = "default") {
if (e) {
return f(e, n).createQueryBuilder(t);
}
return h(n).createQueryBuilder();
}
return _h;
}
var ap;
function rp() {
if (ap) return Dh;
ap = 1;
Object.defineProperty(Dh, "__esModule", {
value: true
});
Dh.AbstractRepository = void 0;
const e = Qe;
const t = np();
const n = le;
let a = class AbstractRepository {
get repository() {
const t = this.getCustomRepositoryTarget(this);
if (!t) throw new e.CustomRepositoryDoesNotHaveEntityError(this.constructor);
return this.manager.getRepository(t);
}
get treeRepository() {
const t = this.getCustomRepositoryTarget(this);
if (!t) throw new e.CustomRepositoryDoesNotHaveEntityError(this.constructor);
return this.manager.getTreeRepository(t);
}
createQueryBuilder(t) {
const n = this.getCustomRepositoryTarget(this.constructor);
if (!n) throw new e.CustomRepositoryDoesNotHaveEntityError(this.constructor);
return this.manager.getRepository(n).createQueryBuilder(t);
}
createQueryBuilderFor(e, t) {
return this.getRepositoryFor(e).createQueryBuilder(t);
}
getRepositoryFor(e) {
return this.manager.getRepository(e);
}
getTreeRepositoryFor(e) {
return this.manager.getTreeRepository(e);
}
getCustomRepositoryTarget(e) {
const a = (0, t.getMetadataArgsStorage)().entityRepositories.find(t => t.target === (typeof e === "function" ? e : e.constructor));
if (!a) throw new n.CustomRepositoryNotFoundError(e);
return a.entity;
}
};
Dh.AbstractRepository = a;
return Dh;
}
var ip = {};
var sp = {};
var op = {};
Object.defineProperty(op, "__esModule", {
value: true
});
op.SubjectTopologicalSorter = void 0;
const cp = P;
class SubjectTopologicalSorter {
constructor(e) {
this.subjects = [ ...e ];
this.metadatas = this.getUniqueMetadatas(this.subjects);
}
sort(e) {
if (!this.metadatas.length) return this.subjects;
const t = [];
if (e === "delete") {
const e = this.subjects.filter(e => !e.entity && !e.databaseEntity);
t.push(...e);
this.removeAlreadySorted(e);
}
const n = this.getNonNullableDependencies();
let a = this.toposort(n);
if (e === "insert") a = a.reverse();
a.forEach(e => {
const n = this.subjects.filter(t => t.metadata.targetName === e || t.metadata.inheritanceTree.some(t => t.name === e));
t.push(...n);
this.removeAlreadySorted(n);
});
const r = this.getDependencies();
let i = this.toposort(r);
if (e === "insert") i = i.reverse();
i.forEach(e => {
const n = this.subjects.filter(t => t.metadata.targetName === e);
t.push(...n);
this.removeAlreadySorted(n);
});
t.push(...this.subjects);
return t;
}
removeAlreadySorted(e) {
e.forEach(e => {
this.subjects.splice(this.subjects.indexOf(e), 1);
});
}
getUniqueMetadatas(e) {
const t = [];
e.forEach(e => {
if (t.indexOf(e.metadata) === -1) t.push(e.metadata);
});
return t;
}
getNonNullableDependencies() {
return this.metadatas.reduce((e, t) => {
t.relationsWithJoinColumns.forEach(n => {
if (n.isNullable) return;
e.push([ t.targetName, n.inverseEntityMetadata.targetName ]);
});
return e;
}, []);
}
getDependencies() {
return this.metadatas.reduce((e, t) => {
t.relationsWithJoinColumns.forEach(n => {
if (n.inverseEntityMetadata === t) return;
e.push([ t.targetName, n.inverseEntityMetadata.targetName ]);
});
return e;
}, []);
}
toposort(e) {
function t(e) {
const t = [];
for (let n = 0, a = e.length; n < a; n++) {
const a = e[n];
if (t.indexOf(a[0]) < 0) t.push(a[0]);
if (t.indexOf(a[1]) < 0) t.push(a[1]);
}
return t;
}
const n = t(e);
let a = n.length, r = new Array(a), i = {}, s = a;
while (s--) {
if (!i[s]) o(n[s], s, []);
}
function o(t, s, c) {
if (c.indexOf(t) >= 0) {
throw new cp.TypeORMError("Cyclic dependency: " + JSON.stringify(t));
}
if (!~n.indexOf(t)) {
throw new cp.TypeORMError("Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(t));
}
if (i[s]) return;
i[s] = true;
const l = e.filter(function(e) {
return e[0] === t;
});
if (s = l.length) {
const e = c.concat(t);
do {
const t = l[--s][1];
o(t, n.indexOf(t), e);
} while (s);
}
r[--a] = t;
}
return r;
}
}
op.SubjectTopologicalSorter = SubjectTopologicalSorter;
var lp = {};
var up = {};
var hp = {
exports: {}
};
hp.exports;
var dp;
function pp() {
if (dp) return hp.exports;
dp = 1;
(function(e, t) {
!function(t, n) {
e.exports = n();
}(r, function() {
var e = 1e3, t = 6e4, n = 36e5, a = "millisecond", r = "second", i = "minute", s = "hour", o = "day", c = "week", l = "month", u = "quarter", h = "year", d = "date", p = "Invalid Date", m = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, f = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, y = {
name: "en",
weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
ordinal: function(e) {
var t = [ "th", "st", "nd", "rd" ], n = e % 100;
return "[" + e + (t[(n - 20) % 10] || t[n] || t[0]) + "]";
}
}, E = function(e, t, n) {
var a = String(e);
return !a || a.length >= t ? e : "" + Array(t + 1 - a.length).join(n) + e;
}, T = {
s: E,
z: function(e) {
var t = -e.utcOffset(), n = Math.abs(t), a = Math.floor(n / 60), r = n % 60;
return (t <= 0 ? "+" : "-") + E(a, 2, "0") + ":" + E(r, 2, "0");
},
m: function e(t, n) {
if (t.date() < n.date()) return -e(n, t);
var a = 12 * (n.year() - t.year()) + (n.month() - t.month()), r = t.clone().add(a, l), i = n - r < 0, s = t.clone().add(a + (i ? -1 : 1), l);
return +(-(a + (n - r) / (i ? r - s : s - r)) || 0);
},
a: function(e) {
return e < 0 ? Math.ceil(e) || 0 : Math.floor(e);
},
p: function(e) {
return {
M: l,
y: h,
w: c,
d: o,
D: d,
h: s,
m: i,
s: r,
ms: a,
Q: u
}[e] || String(e || "").toLowerCase().replace(/s$/, "");
},
u: function(e) {
return void 0 === e;
}
}, g = "en", N = {};
N[g] = y;
var A = "$isDayjsObject", b = function(e) {
return e instanceof w || !(!e || !e[A]);
}, C = function e(t, n, a) {
var r;
if (!t) return g;
if ("string" == typeof t) {
var i = t.toLowerCase();
N[i] && (r = i), n && (N[i] = n, r = i);
var s = t.split("-");
if (!r && s.length > 1) return e(s[0]);
} else {
var o = t.name;
N[o] = t, r = o;
}
return !a && r && (g = r), r || !a && g;
}, R = function(e, t) {
if (b(e)) return e.clone();
var n = "object" == typeof t ? t : {};
return n.date = e, n.args = arguments, new w(n);
}, S = T;
S.l = C, S.i = b, S.w = function(e, t) {
return R(e, {
locale: t.$L,
utc: t.$u,
x: t.$x,
$offset: t.$offset
});
};
var w = function() {
function y(e) {
this.$L = C(e.locale, null, true), this.parse(e), this.$x = this.$x || e.x || {},
this[A] = true;
}
var E = y.prototype;
return E.parse = function(e) {
this.$d = function(e) {
var t = e.date, n = e.utc;
if (null === t) return new Date(NaN);
if (S.u(t)) return new Date;
if (t instanceof Date) return new Date(t);
if ("string" == typeof t && !/Z$/i.test(t)) {
var a = t.match(m);
if (a) {
var r = a[2] - 1 || 0, i = (a[7] || "0").substring(0, 3);
return n ? new Date(Date.UTC(a[1], r, a[3] || 1, a[4] || 0, a[5] || 0, a[6] || 0, i)) : new Date(a[1], r, a[3] || 1, a[4] || 0, a[5] || 0, a[6] || 0, i);
}
}
return new Date(t);
}(e), this.init();
}, E.init = function() {
var e = this.$d;
this.$y = e.getFullYear(), this.$M = e.getMonth(), this.$D = e.getDate(), this.$W = e.getDay(),
this.$H = e.getHours(), this.$m = e.getMinutes(), this.$s = e.getSeconds(), this.$ms = e.getMilliseconds();
}, E.$utils = function() {
return S;
}, E.isValid = function() {
return !(this.$d.toString() === p);
}, E.isSame = function(e, t) {
var n = R(e);
return this.startOf(t) <= n && n <= this.endOf(t);
}, E.isAfter = function(e, t) {
return R(e) < this.startOf(t);
}, E.isBefore = function(e, t) {
return this.endOf(t) < R(e);
}, E.$g = function(e, t, n) {
return S.u(e) ? this[t] : this.set(n, e);
}, E.unix = function() {
return Math.floor(this.valueOf() / 1e3);
}, E.valueOf = function() {
return this.$d.getTime();
}, E.startOf = function(e, t) {
var n = this, a = !!S.u(t) || t, u = S.p(e), p = function(e, t) {
var r = S.w(n.$u ? Date.UTC(n.$y, t, e) : new Date(n.$y, t, e), n);
return a ? r : r.endOf(o);
}, m = function(e, t) {
return S.w(n.toDate()[e].apply(n.toDate("s"), (a ? [ 0, 0, 0, 0 ] : [ 23, 59, 59, 999 ]).slice(t)), n);
}, f = this.$W, y = this.$M, E = this.$D, T = "set" + (this.$u ? "UTC" : "");
switch (u) {
case h:
return a ? p(1, 0) : p(31, 11);
case l:
return a ? p(1, y) : p(0, y + 1);
case c:
var g = this.$locale().weekStart || 0, N = (f < g ? f + 7 : f) - g;
return p(a ? E - N : E + (6 - N), y);
case o:
case d:
return m(T + "Hours", 0);
case s:
return m(T + "Minutes", 1);
case i:
return m(T + "Seconds", 2);
case r:
return m(T + "Milliseconds", 3);
default:
return this.clone();
}
}, E.endOf = function(e) {
return this.startOf(e, false);
}, E.$set = function(e, t) {
var n, c = S.p(e), u = "set" + (this.$u ? "UTC" : ""), p = (n = {}, n[o] = u + "Date",
n[d] = u + "Date", n[l] = u + "Month", n[h] = u + "FullYear", n[s] = u + "Hours",
n[i] = u + "Minutes", n[r] = u + "Seconds", n[a] = u + "Milliseconds", n)[c], m = c === o ? this.$D + (t - this.$W) : t;
if (c === l || c === h) {
var f = this.clone().set(d, 1);
f.$d[p](m), f.init(), this.$d = f.set(d, Math.min(this.$D, f.daysInMonth())).$d;
} else p && this.$d[p](m);
return this.init(), this;
}, E.set = function(e, t) {
return this.clone().$set(e, t);
}, E.get = function(e) {
return this[S.p(e)]();
}, E.add = function(a, u) {
var d, p = this;
a = Number(a);
var m = S.p(u), f = function(e) {
var t = R(p);
return S.w(t.date(t.date() + Math.round(e * a)), p);
};
if (m === l) return this.set(l, this.$M + a);
if (m === h) return this.set(h, this.$y + a);
if (m === o) return f(1);
if (m === c) return f(7);
var y = (d = {}, d[i] = t, d[s] = n, d[r] = e, d)[m] || 1, E = this.$d.getTime() + a * y;
return S.w(E, this);
}, E.subtract = function(e, t) {
return this.add(-1 * e, t);
}, E.format = function(e) {
var t = this, n = this.$locale();
if (!this.isValid()) return n.invalidDate || p;
var a = e || "YYYY-MM-DDTHH:mm:ssZ", r = S.z(this), i = this.$H, s = this.$m, o = this.$M, c = n.weekdays, l = n.months, u = n.meridiem, h = function(e, n, r, i) {
return e && (e[n] || e(t, a)) || r[n].slice(0, i);
}, d = function(e) {
return S.s(i % 12 || 12, e, "0");
}, m = u || function(e, t, n) {
var a = e < 12 ? "AM" : "PM";
return n ? a.toLowerCase() : a;
};
return a.replace(f, function(e, a) {
return a || function(e) {
switch (e) {
case "YY":
return String(t.$y).slice(-2);
case "YYYY":
return S.s(t.$y, 4, "0");
case "M":
return o + 1;
case "MM":
return S.s(o + 1, 2, "0");
case "MMM":
return h(n.monthsShort, o, l, 3);
case "MMMM":
return h(l, o);
case "D":
return t.$D;
case "DD":
return S.s(t.$D, 2, "0");
case "d":
return String(t.$W);
case "dd":
return h(n.weekdaysMin, t.$W, c, 2);
case "ddd":
return h(n.weekdaysShort, t.$W, c, 3);
case "dddd":
return c[t.$W];
case "H":
return String(i);
case "HH":
return S.s(i, 2, "0");
case "h":
return d(1);
case "hh":
return d(2);
case "a":
return m(i, s, true);
case "A":
return m(i, s, false);
case "m":
return String(s);
case "mm":
return S.s(s, 2, "0");
case "s":
return String(t.$s);
case "ss":
return S.s(t.$s, 2, "0");
case "SSS":
return S.s(t.$ms, 3, "0");
case "Z":
return r;
}
return null;
}(e) || r.replace(":", "");
});
}, E.utcOffset = function() {
return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
}, E.diff = function(a, d, p) {
var m, f = this, y = S.p(d), E = R(a), T = (E.utcOffset() - this.utcOffset()) * t, g = this - E, N = function() {
return S.m(f, E);
};
switch (y) {
case h:
m = N() / 12;
break;
case l:
m = N();
break;
case u:
m = N() / 3;
break;
case c:
m = (g - T) / 6048e5;
break;
case o:
m = (g - T) / 864e5;
break;
case s:
m = g / n;
break;
case i:
m = g / t;
break;
case r:
m = g / e;
break;
default:
m = g;
}
return p ? m : S.a(m);
}, E.daysInMonth = function() {
return this.endOf(l).$D;
}, E.$locale = function() {
return N[this.$L];
}, E.locale = function(e, t) {
if (!e) return this.$L;
var n = this.clone(), a = C(e, t, true);
return a && (n.$L = a), n;
}, E.clone = function() {
return S.w(this.$d, this);
}, E.toDate = function() {
return new Date(this.valueOf());
}, E.toJSON = function() {
return this.isValid() ? this.toISOString() : null;
}, E.toISOString = function() {
return this.$d.toISOString();
}, E.toString = function() {
return this.$d.toUTCString();
}, y;
}(), M = w.prototype;
return R.prototype = M, [ [ "$ms", a ], [ "$s", r ], [ "$m", i ], [ "$H", s ], [ "$W", o ], [ "$M", l ], [ "$y", h ], [ "$D", d ] ].forEach(function(e) {
M[e[1]] = function(t) {
return this.$g(t, e[0], e[1]);
};
}), R.extend = function(e, t) {
return e.$i || (e(t, w, R), e.$i = true), R;
}, R.locale = C, R.isDayjs = b, R.unix = function(e) {
return R(1e3 * e);
}, R.en = N[g], R.Ls = N, R.p = {}, R;
});
})(hp, hp.exports);
return hp.exports;
}
Object.defineProperty(up, "__esModule", {
value: true
});
up.DateUtils = void 0;
const mp = e;
const fp = mp.__importDefault(pp());
class DateUtils {
static normalizeHydratedDate(e) {
if (!e) return e;
return typeof e === "string" ? new Date(e) : e;
}
static mixedDateToDateString(e) {
if (e instanceof Date) {
return this.formatZerolessValue(e.getFullYear(), 4) + "-" + this.formatZerolessValue(e.getMonth() + 1) + "-" + this.formatZerolessValue(e.getDate());
}
return e;
}
static mixedDateToDate(e, t = false, n = true) {
let a = typeof e === "string" ? (0, fp.default)(e).toDate() : e;
if (t) a = new Date(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate(), a.getUTCHours(), a.getUTCMinutes(), a.getUTCSeconds(), a.getUTCMilliseconds());
if (!n) a.setUTCMilliseconds(0);
return a;
}
static mixedDateToTimeString(e, t = false) {
if (e instanceof Date) return this.formatZerolessValue(e.getHours()) + ":" + this.formatZerolessValue(e.getMinutes()) + (!t ? ":" + this.formatZerolessValue(e.getSeconds()) : "");
return e;
}
static mixedTimeToDate(e) {
if (typeof e === "string") {
const [t, n, a] = e.split(":");
const r = new Date;
if (t) r.setHours(parseInt(t));
if (n) r.setMinutes(parseInt(n));
if (a) r.setSeconds(parseInt(a));
return r;
}
return e;
}
static mixedTimeToString(e, t = false) {
e = e instanceof Date ? e.getHours() + ":" + e.getMinutes() + (!t ? ":" + e.getSeconds() : "") : e;
if (typeof e === "string") {
return e.split(":").map(e => e.length === 1 ? "0" + e : e).join(":");
}
return e;
}
static mixedDateToDatetimeString(e, t) {
if (typeof e === "string") {
e = new Date(e);
}
if (e instanceof Date) {
let n = this.formatZerolessValue(e.getFullYear(), 4) + "-" + this.formatZerolessValue(e.getMonth() + 1) + "-" + this.formatZerolessValue(e.getDate()) + " " + this.formatZerolessValue(e.getHours()) + ":" + this.formatZerolessValue(e.getMinutes()) + ":" + this.formatZerolessValue(e.getSeconds());
if (t) n += `.${this.formatMilliseconds(e.getMilliseconds())}`;
e = n;
}
return e;
}
static mixedDateToUtcDatetimeString(e) {
if (typeof e === "string") {
e = new Date(e);
}
if (e instanceof Date) {
return this.formatZerolessValue(e.getUTCFullYear(), 4) + "-" + this.formatZerolessValue(e.getUTCMonth() + 1) + "-" + this.formatZerolessValue(e.getUTCDate()) + " " + this.formatZerolessValue(e.getUTCHours()) + ":" + this.formatZerolessValue(e.getUTCMinutes()) + ":" + this.formatZerolessValue(e.getUTCSeconds()) + "." + this.formatMilliseconds(e.getUTCMilliseconds());
}
return e;
}
static simpleArrayToString(e) {
if (Array.isArray(e)) {
return e.map(e => String(e)).join(",");
}
return e;
}
static stringToSimpleArray(e) {
if (typeof e === "string") {
if (e.length > 0) {
return e.split(",");
} else {
return [];
}
}
return e;
}
static simpleJsonToString(e) {
return JSON.stringify(e);
}
static stringToSimpleJson(e) {
return typeof e === "string" ? JSON.parse(e) : e;
}
static simpleEnumToString(e) {
return "" + e;
}
static stringToSimpleEnum(e, t) {
if (t.enum && !isNaN(e) && t.enum.indexOf(parseInt(e)) >= 0) {
e = parseInt(e);
}
return e;
}
static formatZerolessValue(e, t = 2) {
const n = "0".repeat(t);
return String(`${n}${e}`).slice(-t);
}
static formatMilliseconds(e) {
if (e < 10) {
return "00" + e;
} else if (e < 100) {
return "0" + e;
} else {
return String(e);
}
}
}
up.DateUtils = DateUtils;
Object.defineProperty(lp, "__esModule", {
value: true
});
lp.SubjectChangedColumnsComputer = void 0;
const yp = up;
const Ep = qc;
const Tp = _s;
const gp = I;
class SubjectChangedColumnsComputer {
compute(e) {
e.forEach(t => {
this.computeDiffColumns(t);
this.computeDiffRelationalColumns(e, t);
});
}
computeDiffColumns(e) {
if (!e.entity) return;
e.metadata.columns.forEach(t => {
if (t.isVirtual || t.isDiscriminator) return;
const n = e.changeMaps.find(e => e.column === t);
if (n) {
e.changeMaps.splice(e.changeMaps.indexOf(n), 1);
}
const a = t.getEntityValue(e.entity);
if (a === undefined) return;
if (e.databaseEntity) {
const n = t.type !== "json" && t.type !== "jsonb";
let r = t.getEntityValue(e.databaseEntity, n);
if (t.relationMetadata) {
const n = t.relationMetadata.getEntityValue(e.entity);
if (n !== null && n !== undefined) return;
}
let i = a;
if (a !== null) {
switch (t.type) {
case "date":
i = t.isArray ? a.map(e => yp.DateUtils.mixedDateToDateString(e)) : yp.DateUtils.mixedDateToDateString(a);
r = t.isArray ? r.map(e => yp.DateUtils.mixedDateToDateString(e)) : yp.DateUtils.mixedDateToDateString(r);
break;
case "time":
case "time with time zone":
case "time without time zone":
case "timetz":
i = t.isArray ? a.map(e => yp.DateUtils.mixedDateToTimeString(e)) : yp.DateUtils.mixedDateToTimeString(a);
r = t.isArray ? r.map(e => yp.DateUtils.mixedDateToTimeString(e)) : yp.DateUtils.mixedDateToTimeString(r);
break;
case "datetime":
case "datetime2":
case Date:
case "timestamp":
case "timestamp without time zone":
case "timestamp with time zone":
case "timestamp with local time zone":
case "timestamptz":
i = t.isArray ? a.map(e => yp.DateUtils.mixedDateToUtcDatetimeString(e)) : yp.DateUtils.mixedDateToUtcDatetimeString(a);
r = t.isArray ? r.map(e => yp.DateUtils.mixedDateToUtcDatetimeString(e)) : yp.DateUtils.mixedDateToUtcDatetimeString(r);
break;
case "json":
case "jsonb":
if (Ep.OrmUtils.deepCompare(a, r)) return;
break;
case "simple-array":
i = yp.DateUtils.simpleArrayToString(a);
r = yp.DateUtils.simpleArrayToString(r);
break;
case "simple-enum":
i = yp.DateUtils.simpleEnumToString(a);
r = yp.DateUtils.simpleEnumToString(r);
break;
case "simple-json":
i = yp.DateUtils.simpleJsonToString(a);
r = yp.DateUtils.simpleJsonToString(r);
break;
}
if (t.transformer) {
i = Tp.ApplyValueTransformers.transformTo(t.transformer, a);
}
}
if (t.isArray) {
if (Ep.OrmUtils.deepCompare(i, r)) return;
} else if (Buffer.isBuffer(i) && Buffer.isBuffer(r)) {
if (i.equals(r)) {
return;
}
} else {
if (i === r) return;
}
}
if (!e.diffColumns.includes(t)) e.diffColumns.push(t);
e.changeMaps.push({
column: t,
value: a
});
});
}
computeDiffRelationalColumns(e, t) {
if (!t.entity) return;
t.metadata.relationsWithJoinColumns.forEach(n => {
let a = n.getEntityValue(t.entity);
if (a === undefined) return;
if (t.databaseEntity) {
let e = a;
if (e !== null && gp.ObjectUtils.isObject(e)) e = n.getRelationIdMap(e);
const r = n.getEntityValue(t.databaseEntity);
const i = Ep.OrmUtils.compareIds(e, r);
if (i) {
return;
} else {
t.diffRelations.push(n);
}
}
const r = e.find(e => e.mustBeInserted && e.entity === a);
if (r) a = r;
const i = t.changeMaps.find(e => e.relation === n);
if (i) {
i.value = a;
} else {
t.changeMaps.push({
relation: n,
value: a
});
}
});
}
}
lp.SubjectChangedColumnsComputer = SubjectChangedColumnsComputer;
var Np = {};
var Ap = {};
Object.defineProperty(Ap, "__esModule", {
value: true
});
Ap.NestedSetMultipleRootError = void 0;
const bp = D;
class NestedSetMultipleRootError extends bp.TypeORMError {
constructor() {
super(`Nested sets do not support multiple root entities.`);
}
}
Ap.NestedSetMultipleRootError = NestedSetMultipleRootError;
Object.defineProperty(Np, "__esModule", {
value: true
});
Np.NestedSetSubjectExecutor = void 0;
const Cp = qc;
const Rp = Ap;
class NestedSetSubjectExecutor {
constructor(e) {
this.queryRunner = e;
}
async insert(e) {
const t = e => this.queryRunner.connection.driver.escape(e);
const n = this.getTableName(e.metadata.tablePath);
const a = t(e.metadata.nestedSetLeftColumn.databaseName);
const r = t(e.metadata.nestedSetRightColumn.databaseName);
let i = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!i && e.parentSubject && e.parentSubject.entity) i = e.parentSubject.insertedValueSet ? e.parentSubject.insertedValueSet : e.parentSubject.entity;
const s = e.metadata.getEntityIdMap(i);
let o = undefined;
if (s) {
o = await this.queryRunner.manager.createQueryBuilder().select(e.metadata.targetName + "." + e.metadata.nestedSetRightColumn.propertyPath, "right").from(e.metadata.target, e.metadata.targetName).whereInIds(s).getRawOne().then(e => {
const t = e ? e["right"] : undefined;
return typeof t === "string" ? parseInt(t) : t;
});
}
if (o !== undefined) {
await this.queryRunner.query(`UPDATE ${n} SET ` + `${a} = CASE WHEN ${a} > ${o} THEN ${a} + 2 ELSE ${a} END,` + `${r} = ${r} + 2 ` + `WHERE ${r} >= ${o}`);
Cp.OrmUtils.mergeDeep(e.insertedValueSet, e.metadata.nestedSetLeftColumn.createValueMap(o), e.metadata.nestedSetRightColumn.createValueMap(o + 1));
} else {
const t = await this.isUniqueRootEntity(e, i);
if (!t) throw new Rp.NestedSetMultipleRootError;
Cp.OrmUtils.mergeDeep(e.insertedValueSet, e.metadata.nestedSetLeftColumn.createValueMap(1), e.metadata.nestedSetRightColumn.createValueMap(2));
}
}
async update(e) {
let t = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!t && e.parentSubject && e.parentSubject.entity) t = e.parentSubject.entity;
let n = e.databaseEntity;
if (!n && t) n = e.metadata.treeChildrenRelation.getEntityValue(t).find(t => Object.entries(e.identifier).every(([e, n]) => t[e] === n));
if (n === undefined || t === undefined) {
return;
}
const a = e.metadata.treeParentRelation.getEntityValue(n);
const r = e.metadata.getEntityIdMap(a);
const i = e.metadata.getEntityIdMap(t);
if (Cp.OrmUtils.compareIds(r, i)) {
return;
}
if (t) {
const t = e => this.queryRunner.connection.driver.escape(e);
const a = this.getTableName(e.metadata.tablePath);
const r = t(e.metadata.nestedSetLeftColumn.databaseName);
const s = t(e.metadata.nestedSetRightColumn.databaseName);
const o = e.metadata.getEntityIdMap(n);
let c = undefined;
if (o) {
c = (await this.getNestedSetIds(e.metadata, o))[0];
}
let l = undefined;
if (i) {
l = (await this.getNestedSetIds(e.metadata, i))[0];
}
if (c !== undefined && l !== undefined) {
const e = l.left > c.left;
const t = c.right - c.left + 1;
let n;
if (e) {
n = l.left - c.right;
} else {
n = l.right - c.left;
}
const i = `WHEN ${r} >= ${c.left} AND ` + `${r} < ${c.right} ` + `THEN ${r} + ${n} `;
const o = `WHEN ${s} > ${c.left} AND ` + `${s} <= ${c.right} ` + `THEN ${s} + ${n} `;
if (e) {
await this.queryRunner.query(`UPDATE ${a} ` + `SET ${r} = CASE ` + `WHEN ${r} > ${c.right} AND ` + `${r} <= ${l.left} ` + `THEN ${r} - ${t} ` + i + `ELSE ${r} ` + `END, ` + `${s} = CASE ` + `WHEN ${s} > ${c.right} AND ` + `${s} < ${l.left} ` + `THEN ${s} - ${t} ` + o + `ELSE ${s} ` + `END`);
} else {
await this.queryRunner.query(`UPDATE ${a} ` + `SET ${r} = CASE ` + `WHEN ${r} < ${c.left} AND ` + `${r} > ${l.right} ` + `THEN ${r} + ${t} ` + i + `ELSE ${r} ` + `END, ` + `${s} = CASE ` + `WHEN ${s} < ${c.left} AND ` + `${s} >= ${l.right} ` + `THEN ${s} + ${t} ` + o + `ELSE ${s} ` + `END`);
}
}
} else {
const n = await this.isUniqueRootEntity(e, t);
if (!n) throw new Rp.NestedSetMultipleRootError;
}
}
async remove(e) {
if (!Array.isArray(e)) e = [ e ];
const t = e[0].metadata;
const n = e => this.queryRunner.connection.driver.escape(e);
const a = this.getTableName(t.tablePath);
const r = n(t.nestedSetLeftColumn.databaseName);
const i = n(t.nestedSetRightColumn.databaseName);
const s = [];
for (const n of e) {
const e = t.getEntityIdMap(n.entity);
if (e) {
s.push(e);
}
}
const o = await this.getNestedSetIds(t, s);
for (const e of o) {
const t = e.right - e.left + 1;
await this.queryRunner.query(`UPDATE ${a} ` + `SET ${r} = CASE ` + `WHEN ${r} > ${e.left} THEN ${r} - ${t} ` + `ELSE ${r} ` + `END, ` + `${i} = CASE ` + `WHEN ${i} > ${e.right} THEN ${i} - ${t} ` + `ELSE ${i} ` + `END`);
}
}
getNestedSetIds(e, t) {
const n = {
left: `${e.targetName}.${e.nestedSetLeftColumn.propertyPath}`,
right: `${e.targetName}.${e.nestedSetRightColumn.propertyPath}`
};
const a = this.queryRunner.manager.createQueryBuilder();
Object.entries(n).forEach(([e, t]) => {
a.addSelect(t, e);
});
return a.from(e.target, e.targetName).whereInIds(t).orderBy(n.right, "DESC").getRawMany().then(e => {
const t = [];
for (const a of e) {
const e = {};
for (const t of Object.keys(n)) {
const n = a ? a[t] : undefined;
e[t] = typeof n === "string" ? parseInt(n) : n;
}
t.push(e);
}
return t;
});
}
async isUniqueRootEntity(e, t) {
const n = e => this.queryRunner.connection.driver.escape(e);
const a = this.getTableName(e.metadata.tablePath);
const r = [];
const i = e.metadata.treeParentRelation.joinColumns.map(e => {
const a = n(e.databaseName);
const i = e.getEntityValue(t);
if (i == null) {
return `${a} IS NULL`;
}
r.push(i);
const s = this.queryRunner.connection.driver.createParameter("entity_" + e.databaseName, r.length - 1);
return `${a} = ${s}`;
}).join(" AND ");
const s = "count";
const o = await this.queryRunner.query(`SELECT COUNT(1) AS ${n(s)} FROM ${a} WHERE ${i}`, r, true);
return parseInt(o.records[0][s]) === 0;
}
getTableName(e) {
return e.split(".").map(e => e === "" ? e : this.queryRunner.connection.driver.escape(e)).join(".");
}
}
Np.NestedSetSubjectExecutor = NestedSetSubjectExecutor;
var Sp = {};
Object.defineProperty(Sp, "__esModule", {
value: true
});
Sp.ClosureSubjectExecutor = void 0;
const wp = ke();
const Mp = qc;
class ClosureSubjectExecutor {
constructor(e) {
this.queryRunner = e;
}
async insert(e) {
const t = {};
e.metadata.closureJunctionTable.ancestorColumns.forEach(n => {
t[n.databaseName] = e.identifier;
});
e.metadata.closureJunctionTable.descendantColumns.forEach(n => {
t[n.databaseName] = e.identifier;
});
await this.queryRunner.manager.createQueryBuilder().insert().into(e.metadata.closureJunctionTable.tablePath).values(t).updateEntity(false).callListeners(false).execute();
let n = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!n && e.parentSubject && e.parentSubject.entity) n = e.parentSubject.insertedValueSet ? e.parentSubject.insertedValueSet : e.parentSubject.entity;
if (n) {
const t = e => this.queryRunner.connection.driver.escape(e);
const a = this.getTableName(e.metadata.closureJunctionTable.tablePath);
const r = [];
const i = e.metadata.closureJunctionTable.ancestorColumns.map(e => t(e.databaseName));
const s = e.metadata.closureJunctionTable.descendantColumns.map(e => t(e.databaseName));
const o = e.metadata.primaryColumns.map(t => {
r.push(t.getEntityValue(e.insertedValueSet ? e.insertedValueSet : e.entity));
return this.queryRunner.connection.driver.createParameter("child_entity_" + t.databaseName, r.length - 1);
});
const c = e.metadata.closureJunctionTable.descendantColumns.map(a => {
const i = t(a.databaseName);
const s = a.referencedColumn.getEntityValue(n);
if (!s) throw new wp.CannotAttachTreeChildrenEntityError(e.metadata.name);
r.push(s);
const o = this.queryRunner.connection.driver.createParameter("parent_entity_" + a.referencedColumn.databaseName, r.length - 1);
return `${i} = ${o}`;
});
await this.queryRunner.query(`INSERT INTO ${a} (${[ ...i, ...s ].join(", ")}) ` + `SELECT ${i.join(", ")}, ${o.join(", ")} FROM ${a} WHERE ${c.join(" AND ")}`, r);
}
}
async update(e) {
let t = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!t && e.parentSubject && e.parentSubject.entity) t = e.parentSubject.entity;
let n = e.databaseEntity;
if (!n && t) n = e.metadata.treeChildrenRelation.getEntityValue(t).find(t => Object.entries(e.identifier).every(([e, n]) => t[e] === n));
if (n === undefined || t === undefined) {
return;
}
const a = e.metadata.treeParentRelation.getEntityValue(n);
const r = e.metadata.getEntityIdMap(a);
const i = e.metadata.getEntityIdMap(t);
if (Mp.OrmUtils.compareIds(r, i)) {
return;
}
const s = e => this.queryRunner.connection.driver.escape(e);
const o = e.metadata.closureJunctionTable;
const c = o.ancestorColumns.map(e => s(e.databaseName));
const l = o.descendantColumns.map(e => s(e.databaseName));
const u = (e, t) => {
const n = `sub${t}`;
const a = e.createQueryBuilder().select(l.join(", ")).from(o.tablePath, n);
for (const e of o.ancestorColumns) {
a.andWhere(`${s(n)}.${s(e.databaseName)} = :value_${e.referencedColumn.databaseName}`);
}
return e.createQueryBuilder().select(l.join(", ")).from(`(${a.getQuery()})`, t).setParameters(a.getParameters()).getQuery();
};
const h = {};
for (const t of e.metadata.primaryColumns) {
h[`value_${t.databaseName}`] = n[t.databaseName];
}
await this.queryRunner.manager.createQueryBuilder().delete().from(o.tablePath).where(e => `(${l.join(", ")}) IN (${u(e, "descendant")})`).andWhere(e => `(${c.join(", ")}) NOT IN (${u(e, "ancestor")})`).setParameters(h).execute();
if (t) {
const a = [];
const r = this.getTableName(o.tablePath);
const i = s("supertree");
const u = s("subtree");
const h = [ ...c.map(e => `${i}.${e}`), ...l.map(e => `${u}.${e}`) ];
const d = e.metadata.closureJunctionTable.ancestorColumns.map(e => {
const t = s(e.databaseName);
const r = e.referencedColumn.getEntityValue(n);
a.push(r);
const i = this.queryRunner.connection.driver.createParameter("entity_" + e.referencedColumn.databaseName, a.length - 1);
return `${u}.${t} = ${i}`;
});
const p = e.metadata.closureJunctionTable.descendantColumns.map(n => {
const r = s(n.databaseName);
const o = n.referencedColumn.getEntityValue(t);
if (!o) throw new wp.CannotAttachTreeChildrenEntityError(e.metadata.name);
a.push(o);
const c = this.queryRunner.connection.driver.createParameter("parent_entity_" + n.referencedColumn.databaseName, a.length - 1);
return `${i}.${r} = ${c}`;
});
await this.queryRunner.query(`INSERT INTO ${r} (${[ ...c, ...l ].join(", ")}) ` + `SELECT ${h.join(", ")} ` + `FROM ${r} AS ${i}, ${r} AS ${u} ` + `WHERE ${[ ...d, ...p ].join(" AND ")}`, a);
}
}
async remove(e) {
if (!(this.queryRunner.connection.driver.options.type === "mssql")) {
return;
}
if (!Array.isArray(e)) e = [ e ];
const t = e => this.queryRunner.connection.driver.escape(e);
const n = e.map(e => e.identifier);
const a = e[0].metadata.closureJunctionTable;
const r = e => e.map(e => {
const a = n.map(t => t[e.referencedColumn.databaseName]);
return `${t(e.databaseName)} IN (${a.join(", ")})`;
}).join(" AND ");
const i = r(a.ancestorColumns);
const s = r(a.descendantColumns);
await this.queryRunner.manager.createQueryBuilder().delete().from(a.tablePath).where(i).orWhere(s).execute();
}
getTableName(e) {
return e.split(".").map(e => e === "" ? e : this.queryRunner.connection.driver.escape(e)).join(".");
}
}
Sp.ClosureSubjectExecutor = ClosureSubjectExecutor;
var Op = {};
var vp = {};
Object.defineProperty(vp, "__esModule", {
value: true
});
var Ip = vp.EntityMetadata = void 0;
const Pp = z;
const Lp = qc;
const Dp = ht;
const _p = I;
const $p = kn;
class EntityMetadata {
constructor(e) {
this["@instanceof"] = Symbol.for("EntityMetadata");
this.childEntityMetadatas = [];
this.inheritanceTree = [];
this.tableType = "regular";
this.withoutRowid = false;
this.synchronize = true;
this.hasNonNullableRelations = false;
this.isJunction = false;
this.isAlwaysUsingConstructor = true;
this.isClosureJunction = false;
this.hasMultiplePrimaryKeys = false;
this.hasUUIDGeneratedColumns = false;
this.ownColumns = [];
this.columns = [];
this.ancestorColumns = [];
this.descendantColumns = [];
this.nonVirtualColumns = [];
this.ownerColumns = [];
this.inverseColumns = [];
this.generatedColumns = [];
this.primaryColumns = [];
this.ownRelations = [];
this.relations = [];
this.eagerRelations = [];
this.lazyRelations = [];
this.oneToOneRelations = [];
this.ownerOneToOneRelations = [];
this.oneToManyRelations = [];
this.manyToOneRelations = [];
this.manyToManyRelations = [];
this.ownerManyToManyRelations = [];
this.relationsWithJoinColumns = [];
this.relationIds = [];
this.relationCounts = [];
this.foreignKeys = [];
this.embeddeds = [];
this.allEmbeddeds = [];
this.ownIndices = [];
this.indices = [];
this.uniques = [];
this.ownUniques = [];
this.checks = [];
this.exclusions = [];
this.ownListeners = [];
this.listeners = [];
this.afterLoadListeners = [];
this.beforeInsertListeners = [];
this.afterInsertListeners = [];
this.beforeUpdateListeners = [];
this.afterUpdateListeners = [];
this.beforeRemoveListeners = [];
this.beforeSoftRemoveListeners = [];
this.beforeRecoverListeners = [];
this.afterRemoveListeners = [];
this.afterSoftRemoveListeners = [];
this.afterRecoverListeners = [];
this.connection = e.connection;
this.inheritanceTree = e.inheritanceTree || [];
this.inheritancePattern = e.inheritancePattern;
this.treeType = e.tableTree ? e.tableTree.type : undefined;
this.treeOptions = e.tableTree ? e.tableTree.options : undefined;
this.parentClosureEntityMetadata = e.parentClosureEntityMetadata;
this.tableMetadataArgs = e.args;
this.target = this.tableMetadataArgs.target;
this.tableType = this.tableMetadataArgs.type;
this.expression = this.tableMetadataArgs.expression;
this.withoutRowid = this.tableMetadataArgs.withoutRowid;
this.dependsOn = this.tableMetadataArgs.dependsOn;
}
create(e, t) {
const n = t && t.pojo === true ? true : false;
let a;
if (typeof this.target === "function" && !n) {
if (!t?.fromDeserializer || this.isAlwaysUsingConstructor) {
a = new this.target;
} else {
a = Object.create(this.target.prototype);
}
} else {
a = {};
}
if (this.connection.options.typename) {
a[this.connection.options.typename] = this.targetName;
}
this.lazyRelations.forEach(t => this.connection.relationLoader.enableLazyLoad(t, a, e));
return a;
}
hasId(e) {
if (!e) return false;
return this.primaryColumns.every(t => {
const n = t.getEntityValue(e);
return n !== null && n !== undefined && n !== "";
});
}
hasAllPrimaryKeys(e) {
return this.primaryColumns.every(t => {
const n = t.getEntityValue(e);
return n !== null && n !== undefined;
});
}
ensureEntityIdMap(e) {
if (_p.ObjectUtils.isObject(e)) return e;
if (this.hasMultiplePrimaryKeys) throw new Pp.CannotCreateEntityIdMapError(this, e);
return this.primaryColumns[0].createValueMap(e);
}
getEntityIdMap(e) {
if (!e) return undefined;
return EntityMetadata.getValueMap(e, this.primaryColumns, {
skipNulls: true
});
}
getEntityIdMixedMap(e) {
if (!e) return e;
const t = this.getEntityIdMap(e);
if (this.hasMultiplePrimaryKeys) {
return t;
} else if (t) {
return this.primaryColumns[0].getEntityValue(t);
}
return t;
}
compareEntities(e, t) {
const n = this.getEntityIdMap(e);
if (!n) return false;
const a = this.getEntityIdMap(t);
if (!a) return false;
return Lp.OrmUtils.compareIds(n, a);
}
findColumnWithPropertyName(e) {
return this.columns.find(t => t.propertyName === e);
}
findColumnWithDatabaseName(e) {
return this.columns.find(t => t.databaseName === e);
}
hasColumnWithPropertyPath(e) {
const t = this.columns.some(t => t.propertyPath === e);
return t || this.hasRelationWithPropertyPath(e);
}
findColumnWithPropertyPath(e) {
const t = this.columns.find(t => t.propertyPath === e);
if (t) return t;
const n = this.relations.find(t => t.propertyPath === e);
if (n && n.joinColumns.length === 1) return n.joinColumns[0];
return undefined;
}
findColumnWithPropertyPathStrict(e) {
return this.columns.find(t => t.propertyPath === e);
}
findColumnsWithPropertyPath(e) {
const t = this.columns.find(t => t.propertyPath === e);
if (t) return [ t ];
const n = this.findRelationWithPropertyPath(e);
if (n && n.joinColumns) return n.joinColumns;
return [];
}
hasRelationWithPropertyPath(e) {
return this.relations.some(t => t.propertyPath === e);
}
findRelationWithPropertyPath(e) {
return this.relations.find(t => t.propertyPath === e);
}
hasEmbeddedWithPropertyPath(e) {
return this.allEmbeddeds.some(t => t.propertyPath === e);
}
findEmbeddedWithPropertyPath(e) {
return this.allEmbeddeds.find(t => t.propertyPath === e);
}
mapPropertyPathsToColumns(e) {
return e.map(e => {
const t = this.findColumnWithPropertyPath(e);
if (t == null) {
throw new Dp.EntityPropertyNotFoundError(e, this);
}
return t;
});
}
extractRelationValuesFromEntity(e, t) {
const n = [];
t.forEach(t => {
const a = t.getEntityValue(e);
if (Array.isArray(a)) {
a.forEach(e => n.push([ t, e, EntityMetadata.getInverseEntityMetadata(e, t) ]));
} else if (a) {
n.push([ t, a, EntityMetadata.getInverseEntityMetadata(a, t) ]);
}
});
return n;
}
findInheritanceMetadata(e) {
if (this.inheritancePattern === "STI" && this.childEntityMetadatas.length > 0) {
let t;
if (this.discriminatorColumn) {
t = e[this.discriminatorColumn.propertyName];
}
return this.childEntityMetadatas.find(n => t === n.discriminatorValue || e.constructor === n.target) || this;
}
return this;
}
static getInverseEntityMetadata(e, t) {
return t.inverseEntityMetadata.findInheritanceMetadata(e);
}
static createPropertyPath(e, t, n = "") {
const a = [];
Object.keys(t).forEach(r => {
const i = n ? n + "." + r : r;
if (e.hasEmbeddedWithPropertyPath(i)) {
const n = this.createPropertyPath(e, t[r], i);
a.push(...n);
} else {
const e = n ? n + "." + r : r;
a.push(e);
}
});
return a;
}
static difference(e, t) {
return e.filter(e => !t.find(t => Lp.OrmUtils.compareIds(e, t)));
}
static getValueMap(e, t, n) {
return t.reduce((t, a) => {
const r = a.getEntityValueMap(e, n);
if (t === undefined || r === null || r === undefined) return undefined;
return Lp.OrmUtils.mergeDeep(t, r);
}, {});
}
build() {
const e = this.connection.namingStrategy;
const t = this.connection.options.entityPrefix;
const n = this.connection.options.entitySkipConstructor;
this.engine = this.tableMetadataArgs.engine;
this.database = this.tableMetadataArgs.type === "entity-child" && this.parentEntityMetadata ? this.parentEntityMetadata.database : this.tableMetadataArgs.database;
if (this.tableMetadataArgs.schema) {
this.schema = this.tableMetadataArgs.schema;
} else if (this.tableMetadataArgs.type === "entity-child" && this.parentEntityMetadata) {
this.schema = this.parentEntityMetadata.schema;
} else if (this.connection.options?.hasOwnProperty("schema")) {
this.schema = this.connection.options.schema;
}
this.givenTableName = this.tableMetadataArgs.type === "entity-child" && this.parentEntityMetadata ? this.parentEntityMetadata.givenTableName : this.tableMetadataArgs.name;
this.synchronize = this.tableMetadataArgs.synchronize === false ? false : true;
this.targetName = typeof this.tableMetadataArgs.target === "function" ? this.tableMetadataArgs.target.name : this.tableMetadataArgs.target;
if (this.tableMetadataArgs.type === "closure-junction") {
this.tableNameWithoutPrefix = e.closureJunctionTableName(this.givenTableName);
} else if (this.tableMetadataArgs.type === "entity-child" && this.parentEntityMetadata) {
this.tableNameWithoutPrefix = e.tableName(this.parentEntityMetadata.targetName, this.parentEntityMetadata.givenTableName);
} else {
this.tableNameWithoutPrefix = e.tableName(this.targetName, this.givenTableName);
if (this.tableMetadataArgs.type === "junction" && this.connection.driver.maxAliasLength && this.connection.driver.maxAliasLength > 0 && this.tableNameWithoutPrefix.length > this.connection.driver.maxAliasLength) {
this.tableNameWithoutPrefix = (0, $p.shorten)(this.tableNameWithoutPrefix, {
separator: "_",
segmentLength: 3
});
}
}
this.tableName = t ? e.prefixTableName(t, this.tableNameWithoutPrefix) : this.tableNameWithoutPrefix;
this.target = this.target ? this.target : this.tableName;
this.name = this.targetName ? this.targetName : this.tableName;
this.expression = this.tableMetadataArgs.expression;
this.withoutRowid = this.tableMetadataArgs.withoutRowid === true ? true : false;
this.tablePath = this.connection.driver.buildTableName(this.tableName, this.schema, this.database);
this.orderBy = typeof this.tableMetadataArgs.orderBy === "function" ? this.tableMetadataArgs.orderBy(this.propertiesMap) : this.tableMetadataArgs.orderBy;
if (n !== undefined) {
this.isAlwaysUsingConstructor = !n;
}
this.isJunction = this.tableMetadataArgs.type === "closure-junction" || this.tableMetadataArgs.type === "junction";
this.isClosureJunction = this.tableMetadataArgs.type === "closure-junction";
this.comment = this.tableMetadataArgs.comment;
}
registerColumn(e) {
if (this.ownColumns.indexOf(e) !== -1) return;
this.ownColumns.push(e);
this.columns = this.embeddeds.reduce((e, t) => e.concat(t.columnsFromTree), this.ownColumns);
this.primaryColumns = this.columns.filter(e => e.isPrimary);
this.hasMultiplePrimaryKeys = this.primaryColumns.length > 1;
this.hasUUIDGeneratedColumns = this.columns.filter(e => e.isGenerated || e.generationStrategy === "uuid").length > 0;
this.propertiesMap = this.createPropertiesMap();
if (this.childEntityMetadatas) this.childEntityMetadatas.forEach(t => t.registerColumn(e));
}
createPropertiesMap() {
const e = {};
this.columns.forEach(t => Lp.OrmUtils.mergeDeep(e, t.createValueMap(t.propertyPath)));
this.relations.forEach(t => Lp.OrmUtils.mergeDeep(e, t.createValueMap(t.propertyPath)));
return e;
}
getInsertionReturningColumns() {
return this.columns.filter(e => e.default !== undefined || e.asExpression !== undefined || e.isGenerated || e.isCreateDate || e.isUpdateDate || e.isDeleteDate || e.isVersion);
}
}
Ip = vp.EntityMetadata = EntityMetadata;
Object.defineProperty(Op, "__esModule", {
value: true
});
Op.MaterializedPathSubjectExecutor = void 0;
const xp = qc;
const qp = vp;
const Up = Ps;
class MaterializedPathSubjectExecutor {
constructor(e) {
this.queryRunner = e;
}
async insert(e) {
let t = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!t && e.parentSubject && e.parentSubject.entity) t = e.parentSubject.insertedValueSet ? e.parentSubject.insertedValueSet : e.parentSubject.entity;
const n = e.metadata.getEntityIdMap(t);
let a = "";
if (n) {
a = await this.getEntityPath(e, n);
}
const r = e.metadata.treeParentRelation.joinColumns.map(t => t.referencedColumn.getEntityValue(e.insertedValueSet)).join("_");
await this.queryRunner.manager.createQueryBuilder().update(e.metadata.target).set({
[e.metadata.materializedPathColumn.propertyPath]: a + r + "."
}).where(e.identifier).execute();
}
async update(e) {
let t = e.metadata.treeParentRelation.getEntityValue(e.entity);
if (!t && e.parentSubject && e.parentSubject.entity) t = e.parentSubject.entity;
let n = e.databaseEntity;
if (!n && t) n = e.metadata.treeChildrenRelation.getEntityValue(t).find(t => Object.entries(e.identifier).every(([e, n]) => t[e] === n));
const a = e.metadata.treeParentRelation.getEntityValue(n);
const r = this.getEntityParentReferencedColumnMap(e, a);
const i = this.getEntityParentReferencedColumnMap(e, t);
if (xp.OrmUtils.compareIds(r, i)) {
return;
}
let s = "";
if (i) {
s = await this.getEntityPath(e, i);
}
let o = "";
if (r) {
o = await this.getEntityPath(e, r) || "";
}
const c = e.metadata.treeParentRelation.joinColumns.map(e => e.referencedColumn.getEntityValue(n)).join("_");
const l = e.metadata.materializedPathColumn.propertyPath;
await this.queryRunner.manager.createQueryBuilder().update(e.metadata.target).set({
[l]: () => `REPLACE(${this.queryRunner.connection.driver.escape(l)}, '${o}${c}.', '${s}${c}.')`
}).where(`${l} LIKE :path`, {
path: `${o}${c}.%`
}).execute();
}
getEntityParentReferencedColumnMap(e, t) {
if (!t) return undefined;
return qp.EntityMetadata.getValueMap(t, e.metadata.treeParentRelation.joinColumns.map(e => e.referencedColumn).filter(e => e != null), {
skipNulls: true
});
}
getEntityPath(e, t) {
const n = e.metadata;
const a = (Array.isArray(t) ? t : [ t ]).map(e => n.ensureEntityIdMap(e));
return this.queryRunner.manager.createQueryBuilder().select(e.metadata.targetName + "." + e.metadata.materializedPathColumn.propertyPath, "path").from(e.metadata.target, e.metadata.targetName).where(new Up.Brackets(e => {
for (const t of a) {
e.orWhere(new Up.Brackets(e => e.where(t)));
}
})).getRawOne().then(e => e ? e["path"] : "");
}
}
Op.MaterializedPathSubjectExecutor = MaterializedPathSubjectExecutor;
Object.defineProperty(sp, "__esModule", {
value: true
});
sp.SubjectExecutor = void 0;
const Bp = op;
const Fp = lp;
const jp = j();
const kp = mn();
const Qp = sc;
const Vp = Np;
const Kp = Sp;
const Wp = Op;
const Hp = qc;
const Gp = I;
const Yp = Te;
class SubjectExecutor {
constructor(e, t, n) {
this.hasExecutableOperations = false;
this.insertSubjects = [];
this.updateSubjects = [];
this.removeSubjects = [];
this.softRemoveSubjects = [];
this.recoverSubjects = [];
this.queryRunner = e;
this.allSubjects = t;
this.options = n;
this.validate();
this.recompute();
}
async execute() {
let e = undefined;
if (!this.options || this.options.listeners !== false) {
e = this.broadcastBeforeEventsForAll();
if (e.promises.length > 0) await Promise.all(e.promises);
}
if (e && e.count > 0) {
this.insertSubjects.forEach(e => e.recompute());
this.updateSubjects.forEach(e => e.recompute());
this.removeSubjects.forEach(e => e.recompute());
this.softRemoveSubjects.forEach(e => e.recompute());
this.recoverSubjects.forEach(e => e.recompute());
this.recompute();
}
this.insertSubjects = new Bp.SubjectTopologicalSorter(this.insertSubjects).sort("insert");
await this.executeInsertOperations();
this.updateSubjects = this.allSubjects.filter(e => e.mustBeUpdated);
await this.executeUpdateOperations();
this.removeSubjects = new Bp.SubjectTopologicalSorter(this.removeSubjects).sort("delete");
await this.executeRemoveOperations();
this.softRemoveSubjects = this.allSubjects.filter(e => e.mustBeSoftRemoved);
await this.executeSoftRemoveOperations();
this.recoverSubjects = this.allSubjects.filter(e => e.mustBeRecovered);
await this.executeRecoverOperations();
this.updateSpecialColumnsInPersistedEntities();
if (!this.options || this.options.listeners !== false) {
e = this.broadcastAfterEventsForAll();
if (e.promises.length > 0) await Promise.all(e.promises);
}
}
validate() {
this.allSubjects.forEach(e => {
if (e.mustBeUpdated && e.mustBeRemoved) throw new kp.SubjectRemovedAndUpdatedError(e);
});
}
recompute() {
(new Fp.SubjectChangedColumnsComputer).compute(this.allSubjects);
this.insertSubjects = this.allSubjects.filter(e => e.mustBeInserted);
this.updateSubjects = this.allSubjects.filter(e => e.mustBeUpdated);
this.removeSubjects = this.allSubjects.filter(e => e.mustBeRemoved);
this.softRemoveSubjects = this.allSubjects.filter(e => e.mustBeSoftRemoved);
this.recoverSubjects = this.allSubjects.filter(e => e.mustBeRecovered);
this.hasExecutableOperations = this.insertSubjects.length > 0 || this.updateSubjects.length > 0 || this.removeSubjects.length > 0 || this.softRemoveSubjects.length > 0 || this.recoverSubjects.length > 0;
}
broadcastBeforeEventsForAll() {
const e = new Qp.BroadcasterResult;
if (this.insertSubjects.length) this.insertSubjects.forEach(t => this.queryRunner.broadcaster.broadcastBeforeInsertEvent(e, t.metadata, t.entity));
if (this.updateSubjects.length) this.updateSubjects.forEach(t => this.queryRunner.broadcaster.broadcastBeforeUpdateEvent(e, t.metadata, t.entity, t.databaseEntity, t.diffColumns, t.diffRelations));
if (this.removeSubjects.length) this.removeSubjects.forEach(t => this.queryRunner.broadcaster.broadcastBeforeRemoveEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
if (this.softRemoveSubjects.length) this.softRemoveSubjects.forEach(t => this.queryRunner.broadcaster.broadcastBeforeSoftRemoveEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
if (this.recoverSubjects.length) this.recoverSubjects.forEach(t => this.queryRunner.broadcaster.broadcastBeforeRecoverEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
return e;
}
broadcastAfterEventsForAll() {
const e = new Qp.BroadcasterResult;
if (this.insertSubjects.length) this.insertSubjects.forEach(t => this.queryRunner.broadcaster.broadcastAfterInsertEvent(e, t.metadata, t.entity, t.identifier));
if (this.updateSubjects.length) this.updateSubjects.forEach(t => this.queryRunner.broadcaster.broadcastAfterUpdateEvent(e, t.metadata, t.entity, t.databaseEntity, t.diffColumns, t.diffRelations));
if (this.removeSubjects.length) this.removeSubjects.forEach(t => this.queryRunner.broadcaster.broadcastAfterRemoveEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
if (this.softRemoveSubjects.length) this.softRemoveSubjects.forEach(t => this.queryRunner.broadcaster.broadcastAfterSoftRemoveEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
if (this.recoverSubjects.length) this.recoverSubjects.forEach(t => this.queryRunner.broadcaster.broadcastAfterRecoverEvent(e, t.metadata, t.entity, t.databaseEntity, t.identifier));
return e;
}
async executeInsertOperations() {
const [e, t] = this.groupBulkSubjects(this.insertSubjects, "insert");
for (const n of t) {
const t = e[n];
const a = [];
const r = [];
const i = [];
if (this.queryRunner.connection.driver.options.type === "mongodb") {
t.forEach(e => {
if (e.metadata.createDateColumn && e.entity) {
e.entity[e.metadata.createDateColumn.databaseName] = new Date;
}
if (e.metadata.updateDateColumn && e.entity) {
e.entity[e.metadata.updateDateColumn.databaseName] = new Date;
}
e.createValueSetAndPopChangeMap();
r.push(e);
a.push(e.entity);
});
} else if (this.queryRunner.connection.driver.options.type === "oracle") {
t.forEach(e => {
i.push(e);
});
} else {
t.forEach(e => {
if (e.changeMaps.length === 0 || e.metadata.treeType || this.queryRunner.connection.driver.options.type === "oracle" || this.queryRunner.connection.driver.options.type === "sap") {
i.push(e);
} else {
r.push(e);
a.push(e.createValueSetAndPopChangeMap());
}
});
}
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
const e = await this.queryRunner.manager.insert(t[0].metadata.target, a);
t.forEach((t, n) => {
t.identifier = e.identifiers[n];
t.generatedMap = e.generatedMaps[n];
t.insertedValueSet = a[n];
});
} else {
if (a.length > 0) {
const e = await this.queryRunner.manager.createQueryBuilder().insert().into(t[0].metadata.target).values(a).updateEntity(this.options && this.options.reload === false ? false : true).callListeners(false).execute();
r.forEach((t, n) => {
t.identifier = e.identifiers[n];
t.generatedMap = e.generatedMaps[n];
t.insertedValueSet = a[n];
});
}
if (i.length > 0) {
for (const e of i) {
e.insertedValueSet = e.createValueSetAndPopChangeMap();
if (e.metadata.treeType === "nested-set") await new Vp.NestedSetSubjectExecutor(this.queryRunner).insert(e);
await this.queryRunner.manager.createQueryBuilder().insert().into(e.metadata.target).values(e.insertedValueSet).updateEntity(this.options && this.options.reload === false ? false : true).callListeners(false).execute().then(t => {
e.identifier = t.identifiers[0];
e.generatedMap = t.generatedMaps[0];
});
if (e.metadata.treeType === "closure-table") {
await new Kp.ClosureSubjectExecutor(this.queryRunner).insert(e);
} else if (e.metadata.treeType === "materialized-path") {
await new Wp.MaterializedPathSubjectExecutor(this.queryRunner).insert(e);
}
}
}
}
t.forEach(e => {
if (e.generatedMap) {
e.metadata.columns.forEach(t => {
const n = t.getEntityValue(e.generatedMap);
if (n !== undefined && n !== null) {
const a = this.queryRunner.connection.driver.prepareHydratedValue(n, t);
t.setEntityValue(e.generatedMap, a);
}
});
}
});
}
}
async executeUpdateOperations() {
const e = async e => {
if (!e.identifier) throw new jp.SubjectWithoutIdentifierError(e);
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
const t = this.cloneMongoSubjectEntity(e);
if (e.metadata.objectIdColumn && e.metadata.objectIdColumn.propertyName) {
delete t[e.metadata.objectIdColumn.propertyName];
}
if (e.metadata.createDateColumn && e.metadata.createDateColumn.propertyName) {
delete t[e.metadata.createDateColumn.propertyName];
}
if (e.metadata.updateDateColumn && e.metadata.updateDateColumn.propertyName) {
t[e.metadata.updateDateColumn.propertyName] = new Date;
}
const n = this.queryRunner.manager;
await n.update(e.metadata.target, e.identifier, t);
} else {
const t = e.createValueSetAndPopChangeMap();
switch (e.metadata.treeType) {
case "nested-set":
await new Vp.NestedSetSubjectExecutor(this.queryRunner).update(e);
break;
case "closure-table":
await new Kp.ClosureSubjectExecutor(this.queryRunner).update(e);
break;
case "materialized-path":
await new Wp.MaterializedPathSubjectExecutor(this.queryRunner).update(e);
break;
}
const n = this.queryRunner.manager.createQueryBuilder().update(e.metadata.target).set(t).updateEntity(this.options && this.options.reload === false ? false : true).callListeners(false);
if (e.entity) {
n.whereEntity(e.identifier);
} else {
n.where(e.identifier);
}
const a = await n.execute();
const r = a.generatedMaps[0];
if (r) {
e.metadata.columns.forEach(e => {
const t = e.getEntityValue(r);
if (t !== undefined && t !== null) {
const n = this.queryRunner.connection.driver.prepareHydratedValue(t, e);
e.setEntityValue(r, n);
}
});
if (!e.generatedMap) {
e.generatedMap = {};
}
Object.assign(e.generatedMap, r);
}
}
};
const t = [];
const n = [];
for (const e of this.updateSubjects) {
if (e.metadata.treeType === "nested-set") {
t.push(e);
} else {
n.push(e);
}
}
const a = new Promise(async (n, a) => {
for (const n of t) {
try {
await e(n);
} catch (e) {
a(e);
}
}
n();
});
await Promise.all([ ...n.map(e), a ]);
}
async executeRemoveOperations() {
const [e, t] = this.groupBulkSubjects(this.removeSubjects, "delete");
for (const n of t) {
const t = e[n];
const a = t.map(e => {
if (!e.identifier) throw new jp.SubjectWithoutIdentifierError(e);
return e.identifier;
});
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
const e = this.queryRunner.manager;
await e.delete(t[0].metadata.target, a);
} else {
switch (t[0].metadata.treeType) {
case "nested-set":
await new Vp.NestedSetSubjectExecutor(this.queryRunner).remove(t);
break;
case "closure-table":
await new Kp.ClosureSubjectExecutor(this.queryRunner).remove(t);
break;
}
await this.queryRunner.manager.createQueryBuilder().delete().from(t[0].metadata.target).where(a).callListeners(false).execute();
}
}
}
cloneMongoSubjectEntity(e) {
const t = {};
if (e.entity) {
for (const n of e.metadata.columns) {
Hp.OrmUtils.mergeDeep(t, n.getEntityValueMap(e.entity));
}
}
return t;
}
async executeSoftRemoveOperations() {
await Promise.all(this.softRemoveSubjects.map(async e => {
if (!e.identifier) throw new jp.SubjectWithoutIdentifierError(e);
let t;
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
const n = this.cloneMongoSubjectEntity(e);
if (e.metadata.objectIdColumn && e.metadata.objectIdColumn.propertyName) {
delete n[e.metadata.objectIdColumn.propertyName];
}
if (e.metadata.createDateColumn && e.metadata.createDateColumn.propertyName) {
delete n[e.metadata.createDateColumn.propertyName];
}
if (e.metadata.updateDateColumn && e.metadata.updateDateColumn.propertyName) {
n[e.metadata.updateDateColumn.propertyName] = new Date;
}
if (e.metadata.deleteDateColumn && e.metadata.deleteDateColumn.propertyName) {
n[e.metadata.deleteDateColumn.propertyName] = new Date;
}
const a = this.queryRunner.manager;
t = await a.update(e.metadata.target, e.identifier, n);
} else {
const n = this.queryRunner.manager.createQueryBuilder().softDelete().from(e.metadata.target).updateEntity(this.options && this.options.reload === false ? false : true).callListeners(false);
if (e.entity) {
n.whereEntity(e.identifier);
} else {
n.where(e.identifier);
}
t = await n.execute();
}
e.generatedMap = t.generatedMaps[0];
if (e.generatedMap) {
e.metadata.columns.forEach(t => {
const n = t.getEntityValue(e.generatedMap);
if (n !== undefined && n !== null) {
const a = this.queryRunner.connection.driver.prepareHydratedValue(n, t);
t.setEntityValue(e.generatedMap, a);
}
});
}
}));
}
async executeRecoverOperations() {
await Promise.all(this.recoverSubjects.map(async e => {
if (!e.identifier) throw new jp.SubjectWithoutIdentifierError(e);
let t;
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
const n = this.cloneMongoSubjectEntity(e);
if (e.metadata.objectIdColumn && e.metadata.objectIdColumn.propertyName) {
delete n[e.metadata.objectIdColumn.propertyName];
}
if (e.metadata.createDateColumn && e.metadata.createDateColumn.propertyName) {
delete n[e.metadata.createDateColumn.propertyName];
}
if (e.metadata.updateDateColumn && e.metadata.updateDateColumn.propertyName) {
n[e.metadata.updateDateColumn.propertyName] = new Date;
}
if (e.metadata.deleteDateColumn && e.metadata.deleteDateColumn.propertyName) {
n[e.metadata.deleteDateColumn.propertyName] = null;
}
const a = this.queryRunner.manager;
t = await a.update(e.metadata.target, e.identifier, n);
} else {
const n = this.queryRunner.manager.createQueryBuilder().restore().from(e.metadata.target).updateEntity(this.options && this.options.reload === false ? false : true).callListeners(false);
if (e.entity) {
n.whereEntity(e.identifier);
} else {
n.where(e.identifier);
}
t = await n.execute();
}
e.generatedMap = t.generatedMaps[0];
if (e.generatedMap) {
e.metadata.columns.forEach(t => {
const n = t.getEntityValue(e.generatedMap);
if (n !== undefined && n !== null) {
const a = this.queryRunner.connection.driver.prepareHydratedValue(n, t);
t.setEntityValue(e.generatedMap, a);
}
});
}
}));
}
updateSpecialColumnsInPersistedEntities() {
if (this.insertSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities(this.insertSubjects);
if (this.updateSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities(this.updateSubjects);
if (this.softRemoveSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities(this.softRemoveSubjects);
if (this.recoverSubjects.length) this.updateSpecialColumnsInInsertedAndUpdatedEntities(this.recoverSubjects);
if (this.removeSubjects.length) {
this.removeSubjects.forEach(e => {
if (!e.entity) return;
e.metadata.primaryColumns.forEach(t => {
t.setEntityValue(e.entity, undefined);
});
});
}
this.allSubjects.forEach(e => {
if (!e.entity) return;
e.metadata.relationIds.forEach(t => {
t.setValue(e.entity);
});
if (Yp.InstanceChecker.isMongoEntityManager(this.queryRunner.manager)) {
if (e.metadata.objectIdColumn && e.metadata.objectIdColumn.databaseName && e.metadata.objectIdColumn.databaseName !== e.metadata.objectIdColumn.propertyName) {
delete e.entity[e.metadata.objectIdColumn.databaseName];
}
}
});
}
updateSpecialColumnsInInsertedAndUpdatedEntities(e) {
e.forEach(e => {
if (!e.entity) return;
e.metadata.columns.forEach(t => {
if (e.metadata.childEntityMetadatas.length > 0 && e.metadata.childEntityMetadatas.map(e => e.target).indexOf(t.target) !== -1) return;
if (t.isVirtual) return;
if (t.isDeleteDate) return;
if (t.isNullable) {
const n = t.getEntityValue(e.entity);
if (n === undefined) t.setEntityValue(e.entity, null);
}
if (e.updatedRelationMaps.length > 0) {
e.updatedRelationMaps.forEach(t => {
t.relation.joinColumns.forEach(n => {
if (n.isVirtual === true) return;
n.setEntityValue(e.entity, Gp.ObjectUtils.isObject(t.value) ? n.referencedColumn.getEntityValue(t.value) : t.value);
});
});
}
});
if (e.generatedMap) this.queryRunner.manager.merge(e.metadata.target, e.entity, e.generatedMap);
});
}
groupBulkSubjects(e, t) {
const n = {};
const a = [];
const r = e.some(e => e.metadata.getInsertionReturningColumns().length > 0);
const i = t === "delete" || this.queryRunner.connection.driver.isReturningSqlSupported("insert") || r === false;
e.forEach((e, t) => {
const r = i || e.metadata.isJunction ? e.metadata.name : e.metadata.name + "_" + t;
if (!n[r]) {
n[r] = [ e ];
a.push(r);
} else {
n[r].push(e);
}
});
return [ n, a ];
}
}
sp.SubjectExecutor = SubjectExecutor;
var zp = {};
Object.defineProperty(zp, "__esModule", {
value: true
});
zp.Subject = void 0;
const Jp = qc;
const Xp = I;
const Zp = Te;
class Subject {
constructor(e) {
this["@instanceof"] = Symbol.for("Subject");
this.identifier = undefined;
this.entityWithFulfilledIds = undefined;
this.databaseEntityLoaded = false;
this.changeMaps = [];
this.canBeInserted = false;
this.canBeUpdated = false;
this.mustBeRemoved = false;
this.canBeSoftRemoved = false;
this.canBeRecovered = false;
this.updatedRelationMaps = [];
this.diffColumns = [];
this.diffRelations = [];
this.metadata = e.metadata;
this.entity = e.entity;
this.parentSubject = e.parentSubject;
if (e.canBeInserted !== undefined) this.canBeInserted = e.canBeInserted;
if (e.canBeUpdated !== undefined) this.canBeUpdated = e.canBeUpdated;
if (e.mustBeRemoved !== undefined) this.mustBeRemoved = e.mustBeRemoved;
if (e.canBeSoftRemoved !== undefined) this.canBeSoftRemoved = e.canBeSoftRemoved;
if (e.canBeRecovered !== undefined) this.canBeRecovered = e.canBeRecovered;
if (e.identifier !== undefined) this.identifier = e.identifier;
if (e.changeMaps !== undefined) this.changeMaps.push(...e.changeMaps);
this.recompute();
}
get mustBeInserted() {
return this.canBeInserted && !this.databaseEntity;
}
get mustBeUpdated() {
return this.canBeUpdated && this.identifier && (this.databaseEntityLoaded === false || this.databaseEntityLoaded && this.databaseEntity) && this.changeMaps.some(e => !e.column || e.column.isUpdate);
}
get mustBeSoftRemoved() {
return this.canBeSoftRemoved && this.identifier && (this.databaseEntityLoaded === false || this.databaseEntityLoaded && this.databaseEntity);
}
get mustBeRecovered() {
return this.canBeRecovered && this.identifier && (this.databaseEntityLoaded === false || this.databaseEntityLoaded && this.databaseEntity);
}
createValueSetAndPopChangeMap() {
const e = [];
const t = this.changeMaps.reduce((t, n) => {
let a = n.value;
if (Zp.InstanceChecker.isSubject(a)) {
a = a.insertedValueSet ? a.insertedValueSet : a.entity;
}
let r;
if (this.metadata.isJunction && n.column) {
r = n.column.createValueMap(n.column.referencedColumn.getEntityValue(a));
} else if (n.column) {
r = n.column.createValueMap(a);
} else if (n.relation) {
if (Xp.ObjectUtils.isObject(a) && !Buffer.isBuffer(a)) {
const i = n.relation.getRelationIdMap(a);
if (i === undefined) {
e.push(n);
this.canBeUpdated = true;
return t;
}
r = n.relation.createValueMap(i);
this.updatedRelationMaps.push({
relation: n.relation,
value: i
});
} else {
r = n.relation.createValueMap(a);
this.updatedRelationMaps.push({
relation: n.relation,
value: a
});
}
}
Jp.OrmUtils.mergeDeep(t, r);
return t;
}, {});
this.changeMaps = e;
return t;
}
recompute() {
if (this.entity) {
this.entityWithFulfilledIds = Object.assign({}, this.entity);
if (this.parentSubject) {
this.metadata.primaryColumns.forEach(e => {
if (e.relationMetadata && e.relationMetadata.inverseEntityMetadata === this.parentSubject.metadata) {
const t = e.referencedColumn.getEntityValue(this.parentSubject.entity);
e.setEntityValue(this.entityWithFulfilledIds, t);
}
});
}
this.identifier = this.metadata.getEntityIdMap(this.entityWithFulfilledIds);
} else if (this.databaseEntity) {
this.identifier = this.metadata.getEntityIdMap(this.databaseEntity);
}
}
}
zp.Subject = Subject;
var em = {};
Object.defineProperty(em, "__esModule", {
value: true
});
em.OneToManySubjectBuilder = void 0;
const tm = zp;
const nm = qc;
const am = vp;
class OneToManySubjectBuilder {
constructor(e) {
this.subjects = e;
}
build() {
this.subjects.forEach(e => {
e.metadata.oneToManyRelations.forEach(t => {
if (t.persistenceEnabled === false) return;
this.buildForSubjectRelation(e, t);
});
});
}
buildForSubjectRelation(e, t) {
let n = [];
if (e.databaseEntity) {
const a = t.getEntityValue(e.databaseEntity);
if (a) {
n = a.map(e => t.inverseEntityMetadata.getEntityIdMap(e));
}
}
let a = t.getEntityValue(e.entity);
if (a === null) a = [];
if (a === undefined) return;
const r = [];
a.forEach(a => {
let i = t.inverseEntityMetadata.getEntityIdMap(a);
let s = this.subjects.find(e => e.entity === a);
if (s) i = s.identifier;
if (!i) {
if (!s) return;
s.changeMaps.push({
relation: t.inverseRelation,
value: e
});
return;
}
const o = n.find(e => nm.OrmUtils.compareIds(i, e));
if (!o) {
if (!s) {
s = new tm.Subject({
metadata: t.inverseEntityMetadata,
parentSubject: e,
canBeUpdated: true,
identifier: i
});
this.subjects.push(s);
}
s.changeMaps.push({
relation: t.inverseRelation,
value: e
});
}
r.push(i);
});
if (t.inverseRelation?.orphanedRowAction !== "disable") {
am.EntityMetadata.difference(n, r).forEach(n => {
const a = new tm.Subject({
metadata: t.inverseEntityMetadata,
parentSubject: e,
identifier: n
});
if (!t.inverseRelation || t.inverseRelation.orphanedRowAction === "nullify") {
a.canBeUpdated = true;
a.changeMaps = [ {
relation: t.inverseRelation,
value: null
} ];
} else if (t.inverseRelation.orphanedRowAction === "delete") {
a.mustBeRemoved = true;
} else if (t.inverseRelation.orphanedRowAction === "soft-delete") {
a.canBeSoftRemoved = true;
}
this.subjects.push(a);
});
}
}
}
em.OneToManySubjectBuilder = OneToManySubjectBuilder;
var rm = {};
Object.defineProperty(rm, "__esModule", {
value: true
});
rm.OneToOneInverseSideSubjectBuilder = void 0;
const im = zp;
const sm = qc;
class OneToOneInverseSideSubjectBuilder {
constructor(e) {
this.subjects = e;
}
build() {
this.subjects.forEach(e => {
e.metadata.oneToOneRelations.forEach(t => {
if (t.isOwning || t.persistenceEnabled === false) return;
this.buildForSubjectRelation(e, t);
});
});
}
buildForSubjectRelation(e, t) {
let n = undefined;
if (e.databaseEntity) n = t.getEntityValue(e.databaseEntity);
const a = t.getEntityValue(e.entity);
if (a === undefined) return;
if (a === null) {
if (n) {
const a = new im.Subject({
metadata: t.inverseEntityMetadata,
parentSubject: e,
canBeUpdated: true,
identifier: n,
changeMaps: [ {
relation: t.inverseRelation,
value: null
} ]
});
this.subjects.push(a);
}
return;
}
let r = t.inverseEntityMetadata.getEntityIdMap(a);
let i = this.subjects.find(e => !!e.entity && e.entity === a);
if (i) r = i.identifier;
if (!r) {
if (!i) return;
i.changeMaps.push({
relation: t.inverseRelation,
value: e
});
}
const s = n && sm.OrmUtils.compareIds(r, n);
if (!s) {
if (!i) {
i = new im.Subject({
metadata: t.inverseEntityMetadata,
canBeUpdated: true,
identifier: r
});
this.subjects.push(i);
}
i.changeMaps.push({
relation: t.inverseRelation,
value: e
});
}
}
}
rm.OneToOneInverseSideSubjectBuilder = OneToOneInverseSideSubjectBuilder;
var om = {};
Object.defineProperty(om, "__esModule", {
value: true
});
om.ManyToManySubjectBuilder = void 0;
const cm = zp;
const lm = qc;
class ManyToManySubjectBuilder {
constructor(e) {
this.subjects = e;
}
build() {
this.subjects.forEach(e => {
if (!e.entity) return;
e.metadata.manyToManyRelations.forEach(t => {
if (t.persistenceEnabled === false) return;
this.buildForSubjectRelation(e, t);
});
});
}
buildForAllRemoval(e) {
if (!e.databaseEntity) return;
e.metadata.manyToManyRelations.forEach(t => {
if (t.persistenceEnabled === false) return;
const n = t.getEntityValue(e.databaseEntity);
n.forEach(n => {
const a = new cm.Subject({
metadata: t.junctionEntityMetadata,
parentSubject: e,
mustBeRemoved: true,
identifier: this.buildJunctionIdentifier(e, t, n)
});
this.subjects.push(a);
});
});
}
buildForSubjectRelation(e, t) {
let n = [];
if (e.databaseEntity) {
const a = t.getEntityValue(e.databaseEntity);
if (a) {
n = a.map(e => t.inverseEntityMetadata.getEntityIdMap(e));
}
}
let a = t.getEntityValue(e.entity);
if (a === null) a = [];
if (!Array.isArray(a)) return;
a.forEach(a => {
let r = t.inverseEntityMetadata.getEntityIdMap(a);
const i = this.subjects.find(e => e.entity === a);
if (i) r = i.identifier;
if (!r) {
if (!i) return;
}
const s = n.find(e => lm.OrmUtils.compareIds(e, r));
if (s) return;
const o = t.isOwning ? e : i || a;
const c = t.isOwning ? i || a : e;
const l = new cm.Subject({
metadata: t.junctionEntityMetadata,
parentSubject: e,
canBeInserted: true
});
this.subjects.push(l);
t.junctionEntityMetadata.ownerColumns.forEach(e => {
l.changeMaps.push({
column: e,
value: o
});
});
t.junctionEntityMetadata.inverseColumns.forEach(e => {
l.changeMaps.push({
column: e,
value: c
});
});
});
const r = [];
a.forEach(e => {
let n = t.inverseEntityMetadata.getEntityIdMap(e);
const a = this.subjects.find(t => t.entity === e);
if (a) n = a.identifier;
if (n !== undefined && n !== null) r.push(n);
});
const i = n.filter(e => !r.find(t => lm.OrmUtils.compareIds(t, e)));
i.forEach(n => {
const a = new cm.Subject({
metadata: t.junctionEntityMetadata,
parentSubject: e,
mustBeRemoved: true,
identifier: this.buildJunctionIdentifier(e, t, n)
});
this.subjects.push(a);
});
}
buildJunctionIdentifier(e, t, n) {
const a = t.isOwning ? e.entity : n;
const r = t.isOwning ? n : e.entity;
const i = {};
t.junctionEntityMetadata.ownerColumns.forEach(e => {
lm.OrmUtils.mergeDeep(i, e.createValueMap(e.referencedColumn.getEntityValue(a)));
});
t.junctionEntityMetadata.inverseColumns.forEach(e => {
lm.OrmUtils.mergeDeep(i, e.createValueMap(e.referencedColumn.getEntityValue(r)));
});
return i;
}
}
om.ManyToManySubjectBuilder = ManyToManySubjectBuilder;
var um = {};
Object.defineProperty(um, "__esModule", {
value: true
});
um.SubjectDatabaseEntityLoader = void 0;
const hm = qc;
class SubjectDatabaseEntityLoader {
constructor(e, t) {
this.queryRunner = e;
this.subjects = t;
}
async load(e) {
const t = this.groupByEntityTargets().map(async t => {
const n = [];
const a = [];
t.subjects.forEach(e => {
if (e.databaseEntity || !e.identifier) return;
n.push(e.identifier);
a.push(e);
});
if (!n.length) return;
const r = [];
if (e === "save" || e === "soft-remove" || e === "recover") {
t.subjects.forEach(e => {
e.metadata.relations.forEach(t => {
const n = t.getEntityValue(e.entityWithFulfilledIds);
if (n === undefined) return;
if (r.indexOf(t.propertyPath) === -1) r.push(t.propertyPath);
});
});
} else {
r.push(...t.subjects[0].metadata.manyToManyRelations.map(e => e.propertyPath));
}
const i = {
loadEagerRelations: false,
loadRelationIds: {
relations: r,
disableMixedMap: true
},
withDeleted: true
};
let s = [];
if (this.queryRunner.connection.driver.options.type === "mongodb") {
const e = this.queryRunner.manager.getRepository(t.target);
s = await e.findByIds(n, i);
} else {
s = await this.queryRunner.manager.getRepository(t.target).createQueryBuilder().setFindOptions(i).whereInIds(n).getMany();
}
s.forEach(e => {
const t = a[0].metadata.getEntityIdMap(e);
a.forEach(n => {
if (n.databaseEntity) return;
if (hm.OrmUtils.compareIds(n.identifier, t)) n.databaseEntity = e;
});
});
for (const e of a) {
e.databaseEntityLoaded = true;
}
});
await Promise.all(t);
}
groupByEntityTargets() {
return this.subjects.reduce((e, t) => {
let n = e.find(e => e.target === t.metadata.target);
if (!n) {
n = {
target: t.metadata.target,
subjects: []
};
e.push(n);
}
n.subjects.push(t);
return e;
}, []);
}
}
um.SubjectDatabaseEntityLoader = SubjectDatabaseEntityLoader;
var dm = {};
Object.defineProperty(dm, "__esModule", {
value: true
});
dm.CascadesSubjectBuilder = void 0;
const pm = zp;
const mm = I;
class CascadesSubjectBuilder {
constructor(e) {
this.allSubjects = e;
}
build(e, t) {
e.metadata.extractRelationValuesFromEntity(e.entity, e.metadata.relations).forEach(([n, a, r]) => {
if (a === undefined || a === null || !n.isCascadeInsert && !n.isCascadeUpdate && !n.isCascadeSoftRemove && !n.isCascadeRecover) return;
if (!mm.ObjectUtils.isObject(a)) return;
const i = this.findByPersistEntityLike(r.target, a);
if (i) {
if (i.canBeInserted === false) i.canBeInserted = n.isCascadeInsert === true && t === "save";
if (i.canBeUpdated === false) i.canBeUpdated = n.isCascadeUpdate === true && t === "save";
if (i.canBeSoftRemoved === false) i.canBeSoftRemoved = n.isCascadeSoftRemove === true && t === "soft-remove";
if (i.canBeRecovered === false) i.canBeRecovered = n.isCascadeRecover === true && t === "recover";
return;
}
const s = new pm.Subject({
metadata: r,
parentSubject: e,
entity: a,
canBeInserted: n.isCascadeInsert === true && t === "save",
canBeUpdated: n.isCascadeUpdate === true && t === "save",
canBeSoftRemoved: n.isCascadeSoftRemove === true && t === "soft-remove",
canBeRecovered: n.isCascadeRecover === true && t === "recover"
});
this.allSubjects.push(s);
this.build(s, t);
});
}
findByPersistEntityLike(e, t) {
return this.allSubjects.find(n => {
if (!n.entity) return false;
if (n.entity === t) return true;
return n.metadata.target === e && n.metadata.compareEntities(n.entityWithFulfilledIds, t);
});
}
}
dm.CascadesSubjectBuilder = CascadesSubjectBuilder;
Object.defineProperty(ip, "__esModule", {
value: true
});
ip.EntityPersistExecutor = void 0;
const fm = Oe();
const ym = sp;
const Em = ae();
const Tm = zp;
const gm = em;
const Nm = rm;
const Am = om;
const bm = um;
const Cm = dm;
const Rm = qc;
class EntityPersistExecutor {
constructor(e, t, n, a, r, i) {
this.connection = e;
this.queryRunner = t;
this.mode = n;
this.target = a;
this.entity = r;
this.options = i;
}
async execute() {
if (!this.entity || typeof this.entity !== "object") return Promise.reject(new fm.MustBeEntityError(this.mode, this.entity));
await Promise.resolve();
const e = this.queryRunner || this.connection.createQueryRunner();
const t = e.data;
if (this.options && this.options.data) {
e.data = this.options.data;
}
try {
const t = Array.isArray(this.entity) ? this.entity : [ this.entity ];
const n = this.options && this.options.chunk && this.options.chunk > 0 ? Rm.OrmUtils.chunk(t, this.options.chunk) : [ t ];
const a = await Promise.all(n.map(async t => {
const n = [];
t.forEach(e => {
const t = this.target ? this.target : e.constructor;
if (t === Object) throw new Em.CannotDetermineEntityError(this.mode);
const a = this.connection.getMetadata(t).findInheritanceMetadata(e);
n.push(new Tm.Subject({
metadata: a,
entity: e,
canBeInserted: this.mode === "save",
canBeUpdated: this.mode === "save",
mustBeRemoved: this.mode === "remove",
canBeSoftRemoved: this.mode === "soft-remove",
canBeRecovered: this.mode === "recover"
}));
});
const a = new Cm.CascadesSubjectBuilder(n);
n.forEach(e => {
a.build(e, this.mode);
});
await new bm.SubjectDatabaseEntityLoader(e, n).load(this.mode);
if (this.mode === "save" || this.mode === "soft-remove" || this.mode === "recover") {
new gm.OneToManySubjectBuilder(n).build();
new Nm.OneToOneInverseSideSubjectBuilder(n).build();
new Am.ManyToManySubjectBuilder(n).build();
} else {
n.forEach(e => {
if (e.mustBeRemoved) {
new Am.ManyToManySubjectBuilder(n).buildForAllRemoval(e);
}
});
}
return new ym.SubjectExecutor(e, n, this.options);
}));
const r = a.filter(e => e.hasExecutableOperations);
if (r.length === 0) return;
let i = false;
try {
if (!e.isTransactionActive) {
if (this.connection.driver.transactionSupport !== "none" && (!this.options || this.options.transaction !== false)) {
i = true;
await e.startTransaction();
}
}
for (const e of r) {
await e.execute();
}
if (i === true) await e.commitTransaction();
} catch (t) {
if (i) {
try {
await e.rollbackTransaction();
} catch (e) {}
}
throw t;
}
} finally {
e.data = t;
if (!this.queryRunner) await e.release();
}
}
}
ip.EntityPersistExecutor = EntityPersistExecutor;
var Sm;
function wm() {
if (Sm) return sh;
Sm = 1;
Object.defineProperty(sh, "__esModule", {
value: true
});
sh.EntityManager = void 0;
const e = Ee;
const t = Ue;
const n = an;
const a = oh;
const r = Ah;
const i = ch;
const s = Zc;
const o = Ih;
const c = Lh;
const l = P;
const u = rp();
const h = ip;
const d = I;
const p = np();
const m = Te;
const f = lh;
const y = qc;
let E = class EntityManager {
constructor(e, t) {
this["@instanceof"] = Symbol.for("EntityManager");
this.repositories = new Map;
this.treeRepositories = [];
this.plainObjectToEntityTransformer = new o.PlainObjectToNewEntityTransformer;
this.connection = e;
if (t) {
this.queryRunner = t;
d.ObjectUtils.assign(this.queryRunner, {
manager: this
});
}
}
async transaction(e, n) {
const a = typeof e === "string" ? e : undefined;
const r = typeof e === "function" ? e : n;
if (!r) {
throw new l.TypeORMError(`Transaction method requires callback in second parameter if isolation level is supplied.`);
}
if (this.queryRunner && this.queryRunner.isReleased) throw new t.QueryRunnerProviderAlreadyReleasedError;
const i = this.queryRunner || this.connection.createQueryRunner();
try {
await i.startTransaction(a);
const e = await r(i.manager);
await i.commitTransaction();
return e;
} catch (e) {
try {
await i.rollbackTransaction();
} catch (e) {}
throw e;
} finally {
if (!this.queryRunner) await i.release();
}
}
async query(e, t) {
return this.connection.query(e, t, this.queryRunner);
}
async sql(e, ...t) {
const {query: n, parameters: a} = (0, f.buildSqlTag)({
driver: this.connection.driver,
strings: e,
expressions: t
});
return await this.query(n, a);
}
createQueryBuilder(e, t, n) {
if (t) {
return this.connection.createQueryBuilder(e, t, n || this.queryRunner);
} else {
return this.connection.createQueryBuilder(e || n || this.queryRunner);
}
}
hasId(e, t) {
const n = arguments.length === 2 ? e : e.constructor;
const a = arguments.length === 2 ? t : e;
const r = this.connection.getMetadata(n);
return r.hasId(a);
}
getId(e, t) {
const n = arguments.length === 2 ? e : e.constructor;
const a = arguments.length === 2 ? t : e;
const r = this.connection.getMetadata(n);
return r.getEntityIdMixedMap(a);
}
create(e, t) {
const n = this.connection.getMetadata(e);
if (!t) return n.create(this.queryRunner);
if (Array.isArray(t)) return t.map(t => this.create(e, t));
const a = n.create(this.queryRunner);
this.plainObjectToEntityTransformer.transform(a, t, n, true);
return a;
}
merge(e, t, ...n) {
const a = this.connection.getMetadata(e);
n.forEach(e => this.plainObjectToEntityTransformer.transform(t, e, a));
return t;
}
async preload(e, t) {
const n = this.connection.getMetadata(e);
const a = new c.PlainObjectToDatabaseEntityTransformer(this.connection.manager);
const r = await a.transform(t, n);
if (r) return this.merge(e, r, t);
return undefined;
}
save(e, t, n) {
let a = arguments.length > 1 && (typeof e === "function" || m.InstanceChecker.isEntitySchema(e) || typeof e === "string") ? e : undefined;
const r = a ? t : e;
const i = a ? n : t;
if (m.InstanceChecker.isEntitySchema(a)) a = a.options.name;
if (Array.isArray(r) && r.length === 0) return Promise.resolve(r);
return new h.EntityPersistExecutor(this.connection, this.queryRunner, "save", a, r, i).execute().then(() => r);
}
remove(e, t, n) {
const a = arguments.length > 1 && (typeof e === "function" || m.InstanceChecker.isEntitySchema(e) || typeof e === "string") ? e : undefined;
const r = a ? t : e;
const i = a ? n : t;
if (Array.isArray(r) && r.length === 0) return Promise.resolve(r);
return new h.EntityPersistExecutor(this.connection, this.queryRunner, "remove", a, r, i).execute().then(() => r);
}
softRemove(e, t, n) {
let a = arguments.length > 1 && (typeof e === "function" || m.InstanceChecker.isEntitySchema(e) || typeof e === "string") ? e : undefined;
const r = a ? t : e;
const i = a ? n : t;
if (m.InstanceChecker.isEntitySchema(a)) a = a.options.name;
if (Array.isArray(r) && r.length === 0) return Promise.resolve(r);
return new h.EntityPersistExecutor(this.connection, this.queryRunner, "soft-remove", a, r, i).execute().then(() => r);
}
recover(e, t, n) {
let a = arguments.length > 1 && (typeof e === "function" || m.InstanceChecker.isEntitySchema(e) || typeof e === "string") ? e : undefined;
const r = a ? t : e;
const i = a ? n : t;
if (m.InstanceChecker.isEntitySchema(a)) a = a.options.name;
if (Array.isArray(r) && r.length === 0) return Promise.resolve(r);
return new h.EntityPersistExecutor(this.connection, this.queryRunner, "recover", a, r, i).execute().then(() => r);
}
async insert(e, t) {
return this.createQueryBuilder().insert().into(e).values(t).execute();
}
async upsert(e, t, n) {
const a = this.connection.getMetadata(e);
let r;
if (Array.isArray(n)) {
r = {
conflictPaths: n
};
} else {
r = n;
}
let i;
if (!Array.isArray(t)) {
i = [ t ];
} else {
i = t;
}
const s = a.mapPropertyPathsToColumns(Array.isArray(r.conflictPaths) ? r.conflictPaths : Object.keys(r.conflictPaths));
const o = a.columns.filter(e => !s.includes(e) && i.some(t => typeof e.getEntityValue(t) !== "undefined"));
return this.createQueryBuilder().insert().into(e).values(i).orUpdate([ ...s, ...o ].map(e => e.databaseName), s.map(e => e.databaseName), {
skipUpdateIfNoValuesChanged: r.skipUpdateIfNoValuesChanged,
indexPredicate: r.indexPredicate,
upsertType: r.upsertType || this.connection.driver.supportedUpsertTypes[0]
}).execute();
}
update(e, t, n) {
if (y.OrmUtils.isCriteriaNullOrEmpty(t)) {
return Promise.reject(new l.TypeORMError(`Empty criteria(s) are not allowed for the update method.`));
}
if (y.OrmUtils.isPrimitiveCriteria(t)) {
return this.createQueryBuilder().update(e).set(n).whereInIds(t).execute();
} else {
return this.createQueryBuilder().update(e).set(n).where(t).execute();
}
}
updateAll(e, t) {
return this.createQueryBuilder().update(e).set(t).execute();
}
delete(e, t) {
if (y.OrmUtils.isCriteriaNullOrEmpty(t)) {
return Promise.reject(new l.TypeORMError(`Empty criteria(s) are not allowed for the delete method.`));
}
if (y.OrmUtils.isPrimitiveCriteria(t)) {
return this.createQueryBuilder().delete().from(e).whereInIds(t).execute();
} else {
return this.createQueryBuilder().delete().from(e).where(t).execute();
}
}
deleteAll(e) {
return this.createQueryBuilder().delete().from(e).execute();
}
softDelete(e, t) {
if (y.OrmUtils.isCriteriaNullOrEmpty(t)) {
return Promise.reject(new l.TypeORMError(`Empty criteria(s) are not allowed for the softDelete method.`));
}
if (y.OrmUtils.isPrimitiveCriteria(t)) {
return this.createQueryBuilder().softDelete().from(e).whereInIds(t).execute();
} else {
return this.createQueryBuilder().softDelete().from(e).where(t).execute();
}
}
restore(e, t) {
if (y.OrmUtils.isCriteriaNullOrEmpty(t)) {
return Promise.reject(new l.TypeORMError(`Empty criteria(s) are not allowed for the restore method.`));
}
if (y.OrmUtils.isPrimitiveCriteria(t)) {
return this.createQueryBuilder().restore().from(e).whereInIds(t).execute();
} else {
return this.createQueryBuilder().restore().from(e).where(t).execute();
}
}
exists(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, s.FindOptionsUtils.extractFindManyOptionsAlias(t) || n.name).setFindOptions(t || {}).getExists();
}
async existsBy(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
where: t
}).getExists();
}
count(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, s.FindOptionsUtils.extractFindManyOptionsAlias(t) || n.name).setFindOptions(t || {}).getCount();
}
countBy(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
where: t
}).getCount();
}
sum(e, t, n) {
return this.callAggregateFun(e, "SUM", t, n);
}
average(e, t, n) {
return this.callAggregateFun(e, "AVG", t, n);
}
minimum(e, t, n) {
return this.callAggregateFun(e, "MIN", t, n);
}
maximum(e, t, n) {
return this.callAggregateFun(e, "MAX", t, n);
}
async callAggregateFun(e, t, n, a = {}) {
const r = this.connection.getMetadata(e);
const i = r.columns.find(e => e.propertyPath === n);
if (!i) {
throw new l.TypeORMError(`Column "${n}" was not found in table "${r.name}"`);
}
const s = await this.createQueryBuilder(e, r.name).setFindOptions({
where: a
}).select(`${t}(${this.connection.driver.escape(i.databaseName)})`, t).getRawOne();
return s[t] === null ? null : parseFloat(s[t]);
}
async find(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, s.FindOptionsUtils.extractFindManyOptionsAlias(t) || n.name).setFindOptions(t || {}).getMany();
}
async findBy(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
where: t
}).getMany();
}
findAndCount(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, s.FindOptionsUtils.extractFindManyOptionsAlias(t) || n.name).setFindOptions(t || {}).getManyAndCount();
}
findAndCountBy(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
where: t
}).getManyAndCount();
}
async findByIds(e, t) {
if (!t.length) return Promise.resolve([]);
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).andWhereInIds(t).getMany();
}
async findOne(e, t) {
const n = this.connection.getMetadata(e);
let a = n.name;
if (t && t.join) {
a = t.join.alias;
}
if (!t.where) {
throw new Error(`You must provide selection conditions in order to find a single row.`);
}
return this.createQueryBuilder(e, a).setFindOptions({
...t,
take: 1
}).getOne();
}
async findOneBy(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
where: t,
take: 1
}).getOne();
}
async findOneById(e, t) {
const n = this.connection.getMetadata(e);
return this.createQueryBuilder(e, n.name).setFindOptions({
take: 1
}).whereInIds(n.ensureEntityIdMap(t)).getOne();
}
async findOneOrFail(t, n) {
return this.findOne(t, n).then(a => {
if (a === null) {
return Promise.reject(new e.EntityNotFoundError(t, n));
}
return Promise.resolve(a);
});
}
async findOneByOrFail(t, n) {
return this.findOneBy(t, n).then(a => {
if (a === null) {
return Promise.reject(new e.EntityNotFoundError(t, n));
}
return Promise.resolve(a);
});
}
async clear(e) {
const t = this.connection.getMetadata(e);
const n = this.queryRunner || this.connection.createQueryRunner();
try {
return await n.clearTable(t.tablePath);
} finally {
if (!this.queryRunner) await n.release();
}
}
async increment(e, t, n, a) {
const r = this.connection.getMetadata(e);
const i = r.findColumnWithPropertyPath(n);
if (!i) throw new l.TypeORMError(`Column ${n} was not found in ${r.targetName} entity.`);
if (isNaN(Number(a))) throw new l.TypeORMError(`Value "${a}" is not a number.`);
const s = n.split(".").reduceRight((e, t) => ({
[t]: e
}), () => this.connection.driver.escape(i.databaseName) + " + " + a);
return this.createQueryBuilder(e, "entity").update(e).set(s).where(t).execute();
}
async decrement(e, t, n, a) {
const r = this.connection.getMetadata(e);
const i = r.findColumnWithPropertyPath(n);
if (!i) throw new l.TypeORMError(`Column ${n} was not found in ${r.targetName} entity.`);
if (isNaN(Number(a))) throw new l.TypeORMError(`Value "${a}" is not a number.`);
const s = n.split(".").reduceRight((e, t) => ({
[t]: e
}), () => this.connection.driver.escape(i.databaseName) + " - " + a);
return this.createQueryBuilder(e, "entity").update(e).set(s).where(t).execute();
}
getRepository(e) {
const t = this.repositories.get(e);
if (t) return t;
if (this.connection.driver.options.type === "mongodb") {
const t = new a.MongoRepository(e, this, this.queryRunner);
this.repositories.set(e, t);
return t;
} else {
const t = new i.Repository(e, this, this.queryRunner);
this.repositories.set(e, t);
return t;
}
}
getTreeRepository(e) {
if (this.connection.driver.treeSupport === false) throw new l.TreeRepositoryNotSupportedError(this.connection.driver);
const t = this.treeRepositories.find(t => t.target === e);
if (t) return t;
const n = new r.TreeRepository(e, this, this.queryRunner);
this.treeRepositories.push(n);
return n;
}
getMongoRepository(e) {
return this.connection.getMongoRepository(e);
}
withRepository(e) {
const t = e.constructor;
const {target: n, manager: a, queryRunner: r, ...i} = e;
return Object.assign(new t(e.target, this), {
...i
});
}
getCustomRepository(e) {
const t = (0, p.getMetadataArgsStorage)().entityRepositories.find(t => t.target === (typeof e === "function" ? e : e.constructor));
if (!t) throw new l.CustomRepositoryNotFoundError(e);
const n = t.entity ? this.connection.getMetadata(t.entity) : undefined;
const a = new t.target(this, n);
if (a instanceof u.AbstractRepository) {
if (!a["manager"]) a["manager"] = this;
} else {
if (!n) throw new l.CustomRepositoryCannotInheritRepositoryError(e);
a["manager"] = this;
a["metadata"] = n;
}
return a;
}
async release() {
if (!this.queryRunner) throw new n.NoNeedToReleaseEntityManagerError;
return this.queryRunner.release();
}
};
sh.EntityManager = E;
return sh;
}
var Mm = {};
var Om = {};
Object.defineProperty(Om, "__esModule", {
value: true
});
Om.DocumentToEntityTransformer = void 0;
class DocumentToEntityTransformer {
constructor(e = false) {
this.enableRelationIdValues = e;
}
transformAll(e, t) {
return e.map(e => this.transform(e, t));
}
transform(e, t) {
const n = t.create(undefined, {
fromDeserializer: true
});
let a = false;
if (t.objectIdColumn) {
const {databaseNameWithoutPrefixes: r, propertyName: i} = t.objectIdColumn;
const s = e[r];
const o = e[i];
if (s) {
n[i] = s;
a = true;
} else if (o) {
n[i] = o;
a = true;
}
}
if (this.enableRelationIdValues) {
t.columns.filter(e => !!e.relationMetadata).forEach(t => {
const r = e[t.databaseNameWithoutPrefixes];
if (r !== undefined && r !== null && t.propertyName) {
n[t.propertyName] = r;
a = true;
}
});
}
t.ownColumns.forEach(t => {
const r = e[t.databaseNameWithoutPrefixes];
if (r !== undefined && t.propertyName && !t.isVirtual) {
n[t.propertyName] = r;
a = true;
}
});
const r = (e, t, n) => {
n.forEach(n => {
if (!t[n.prefix]) return;
if (n.isArray) {
e[n.propertyName] = t[n.prefix].map((e, a) => {
const i = n.create({
fromDeserializer: true
});
n.columns.forEach(t => {
i[t.propertyName] = e[t.databaseNameWithoutPrefixes];
});
r(i, t[n.prefix][a], n.embeddeds);
return i;
});
} else {
if (n.embeddeds.length && !e[n.propertyName]) e[n.propertyName] = n.create({
fromDeserializer: true
});
n.columns.forEach(a => {
const r = t[n.prefix][a.databaseNameWithoutPrefixes];
if (r === undefined) return;
if (!e[n.propertyName]) e[n.propertyName] = n.create({
fromDeserializer: true
});
e[n.propertyName][a.propertyName] = r;
});
r(e[n.propertyName], t[n.prefix], n.embeddeds);
}
});
};
r(n, e, t.embeddeds);
return a ? n : null;
}
}
Om.DocumentToEntityTransformer = DocumentToEntityTransformer;
var vm;
function Im() {
if (vm) return Mm;
vm = 1;
Object.defineProperty(Mm, "__esModule", {
value: true
});
Mm.MongoEntityManager = void 0;
const e = wm();
const t = Om;
const n = Zc;
const a = Uh;
const r = oc;
const i = Ll;
const s = eo;
const o = I;
let c = class MongoEntityManager extends e.EntityManager {
get mongoQueryRunner() {
return this.connection.driver.queryRunner;
}
constructor(e) {
super(e);
this["@instanceof"] = Symbol.for("MongoEntityManager");
}
async find(e, t) {
const a = this.convertFindManyOptionsOrConditionsToMongodbQuery(t);
const r = this.createEntityCursor(e, a);
const i = this.connection.getMetadata(e).deleteDateColumn;
if (n.FindOptionsUtils.isFindManyOptions(t)) {
if (t.select) r.project(this.convertFindOptionsSelectToProjectCriteria(t.select));
if (t.skip) r.skip(t.skip);
if (t.take) r.limit(t.take);
if (t.order) r.sort(this.convertFindOptionsOrderToOrderCriteria(t.order));
if (i && !t.withDeleted) {
this.filterSoftDeleted(r, i, a);
}
} else if (i) {
this.filterSoftDeleted(r, i, a);
}
return r.toArray();
}
async findAndCount(e, t) {
return this.executeFindAndCount(e, t);
}
async findAndCountBy(e, t) {
return this.executeFindAndCount(e, t);
}
async findByIds(e, t, r) {
const i = this.connection.getMetadata(e);
const s = this.convertFindManyOptionsOrConditionsToMongodbQuery(r) || {};
const o = a.PlatformTools.load("mongodb").ObjectId;
s["_id"] = {
$in: t.map(e => {
if (typeof e === "string") {
return new o(e);
}
if (typeof e === "object") {
if (e instanceof o) {
return e;
}
const t = i.objectIdColumn.propertyName;
if (e[t] instanceof o) {
return e[t];
}
}
})
};
const c = this.createEntityCursor(e, s);
if (n.FindOptionsUtils.isFindManyOptions(r)) {
if (r.select) c.project(this.convertFindOptionsSelectToProjectCriteria(r.select));
if (r.skip) c.skip(r.skip);
if (r.take) c.limit(r.take);
if (r.order) c.sort(this.convertFindOptionsOrderToOrderCriteria(r.order));
}
return c.toArray();
}
async findOne(e, t) {
return this.executeFindOne(e, t);
}
async findOneBy(e, t) {
return this.executeFindOne(e, t);
}
async findOneById(e, t) {
return this.executeFindOne(e, t);
}
async insert(e, t) {
const n = new r.InsertResult;
if (Array.isArray(t)) {
n.raw = await this.insertMany(e, t);
Object.keys(n.raw.insertedIds).forEach(t => {
const a = n.raw.insertedIds[t];
n.generatedMaps.push(this.connection.driver.createGeneratedMap(this.connection.getMetadata(e), a));
n.identifiers.push(this.connection.driver.createGeneratedMap(this.connection.getMetadata(e), a));
});
} else {
n.raw = await this.insertOne(e, t);
n.generatedMaps.push(this.connection.driver.createGeneratedMap(this.connection.getMetadata(e), n.raw.insertedId));
n.identifiers.push(this.connection.driver.createGeneratedMap(this.connection.getMetadata(e), n.raw.insertedId));
}
return n;
}
async update(e, t, n) {
const a = new i.UpdateResult;
if (Array.isArray(t)) {
const r = await Promise.all(t.map(t => this.update(e, t, n)));
a.raw = r.map(e => e.raw);
a.affected = r.map(e => e.affected || 0).reduce((e, t) => e + t, 0);
a.generatedMaps = r.reduce((e, t) => e.concat(t.generatedMaps), []);
} else {
const r = this.connection.getMetadata(e);
const i = await this.updateMany(e, this.convertMixedCriteria(r, t), {
$set: n
});
a.raw = i;
a.affected = i.modifiedCount;
}
return a;
}
async delete(e, t) {
const n = new s.DeleteResult;
if (Array.isArray(t)) {
const a = await Promise.all(t.map(t => this.delete(e, t)));
n.raw = a.map(e => e.raw);
n.affected = a.map(e => e.affected || 0).reduce((e, t) => e + t, 0);
} else {
const a = await this.deleteMany(e, this.convertMixedCriteria(this.connection.getMetadata(e), t));
n.raw = a;
n.affected = a.deletedCount;
}
return n;
}
createCursor(e, t = {}) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.cursor(n.tableName, t);
}
createEntityCursor(e, t = {}) {
const n = this.connection.getMetadata(e);
const a = this.createCursor(e, t);
this.applyEntityTransformationToCursor(n, a);
return a;
}
aggregate(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.aggregate(a.tableName, t, n);
}
aggregateEntity(e, t, n) {
const a = this.connection.getMetadata(e);
const r = this.mongoQueryRunner.aggregate(a.tableName, t, n);
this.applyEntityTransformationToCursor(a, r);
return r;
}
bulkWrite(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.bulkWrite(a.tableName, t, n);
}
count(e, t = {}, n = {}) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.count(a.tableName, t, n);
}
countDocuments(e, t = {}, n = {}) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.countDocuments(a.tableName, t, n);
}
countBy(e, t, n) {
return this.count(e, t, n);
}
createCollectionIndex(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.createCollectionIndex(a.tableName, t, n);
}
createCollectionIndexes(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.createCollectionIndexes(n.tableName, t);
}
deleteMany(e, t, n = {}) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.deleteMany(a.tableName, t, n);
}
deleteOne(e, t, n = {}) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.deleteOne(a.tableName, t, n);
}
distinct(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.distinct(r.tableName, t, n, a);
}
dropCollectionIndex(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.dropCollectionIndex(a.tableName, t, n);
}
dropCollectionIndexes(e) {
const t = this.connection.getMetadata(e);
return this.mongoQueryRunner.dropCollectionIndexes(t.tableName);
}
findOneAndDelete(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.findOneAndDelete(a.tableName, t, n);
}
findOneAndReplace(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.findOneAndReplace(r.tableName, t, n, a);
}
findOneAndUpdate(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.findOneAndUpdate(r.tableName, t, n, a);
}
collectionIndexes(e) {
const t = this.connection.getMetadata(e);
return this.mongoQueryRunner.collectionIndexes(t.tableName);
}
collectionIndexExists(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.collectionIndexExists(n.tableName, t);
}
collectionIndexInformation(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.collectionIndexInformation(n.tableName, t);
}
initializeOrderedBulkOp(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.initializeOrderedBulkOp(n.tableName, t);
}
initializeUnorderedBulkOp(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.initializeUnorderedBulkOp(n.tableName, t);
}
insertMany(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.insertMany(a.tableName, t, n);
}
insertOne(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.insertOne(a.tableName, t, n);
}
isCapped(e) {
const t = this.connection.getMetadata(e);
return this.mongoQueryRunner.isCapped(t.tableName);
}
listCollectionIndexes(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.listCollectionIndexes(n.tableName, t);
}
rename(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.rename(a.tableName, t, n);
}
replaceOne(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.replaceOne(r.tableName, t, n, a);
}
stats(e, t) {
const n = this.connection.getMetadata(e);
return this.mongoQueryRunner.stats(n.tableName, t);
}
watch(e, t, n) {
const a = this.connection.getMetadata(e);
return this.mongoQueryRunner.watch(a.tableName, t, n);
}
updateMany(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.updateMany(r.tableName, t, n, a);
}
updateOne(e, t, n, a) {
const r = this.connection.getMetadata(e);
return this.mongoQueryRunner.updateOne(r.tableName, t, n, a);
}
convertFindManyOptionsOrConditionsToMongodbQuery(e) {
if (!e) return undefined;
if (n.FindOptionsUtils.isFindManyOptions(e)) return typeof e.where === "string" ? {} : e.where;
return e;
}
convertFindOneOptionsOrConditionsToMongodbQuery(e) {
if (!e) return undefined;
if (n.FindOptionsUtils.isFindOneOptions(e)) return typeof e.where === "string" ? {} : e.where;
return e;
}
convertFindOptionsOrderToOrderCriteria(e) {
return Object.keys(e).reduce((t, n) => {
switch (e[n]) {
case "DESC":
t[n] = -1;
break;
case "ASC":
t[n] = 1;
break;
default:
t[n] = e[n];
}
return t;
}, {});
}
convertFindOptionsSelectToProjectCriteria(e) {
if (Array.isArray(e)) {
return e.reduce((e, t) => {
e[t] = 1;
return e;
}, {});
} else {
return {};
}
}
convertMixedCriteria(e, t) {
const n = a.PlatformTools.load("mongodb").ObjectId;
if (n.isValid(t)) {
return {
_id: new n(t)
};
}
if (o.ObjectUtils.isObject(t)) {
return e.columns.reduce((e, n) => {
const a = n.getEntityValue(t);
if (a !== undefined) e[n.databasePath] = a;
return e;
}, {});
}
return {
_id: new n(t)
};
}
applyEntityTransformationToCursor(e, n) {
const a = this.mongoQueryRunner;
n["__to_array_func"] = n.toArray;
n.toArray = async () => n["__to_array_func"]().then(async n => {
const r = new t.DocumentToEntityTransformer;
const i = r.transformAll(n, e);
await a.broadcaster.broadcast("Load", e, i);
return i;
});
n["__next_func"] = n.next;
n.next = async () => n["__next_func"]().then(async n => {
if (!n) {
return n;
}
const r = new t.DocumentToEntityTransformer;
const i = r.transform(n, e);
await a.broadcaster.broadcast("Load", e, [ i ]);
return i;
});
}
filterSoftDeleted(e, t, n) {
const {$or: a, ...r} = n ?? {};
e.filter({
$or: [ {
[t.propertyName]: {
$eq: null
}
}, ...Array.isArray(a) ? a : [] ],
...r
});
}
async executeFindOne(e, t, r) {
const i = a.PlatformTools.load("mongodb").ObjectId;
const s = t instanceof i || typeof t === "string" ? t : undefined;
const o = s ? r : t;
const c = this.convertFindOneOptionsOrConditionsToMongodbQuery(o) || {};
if (s) {
c["_id"] = s instanceof i ? s : new i(s);
}
const l = this.createEntityCursor(e, c);
const u = this.connection.getMetadata(e).deleteDateColumn;
if (n.FindOptionsUtils.isFindOneOptions(o)) {
if (o.select) l.project(this.convertFindOptionsSelectToProjectCriteria(o.select));
if (o.order) l.sort(this.convertFindOptionsOrderToOrderCriteria(o.order));
if (u && !o.withDeleted) {
this.filterSoftDeleted(l, u, c);
}
} else if (u) {
this.filterSoftDeleted(l, u, c);
}
const h = await l.limit(1).toArray();
return h.length > 0 ? h[0] : null;
}
async executeFind(e, t) {
const a = this.convertFindManyOptionsOrConditionsToMongodbQuery(t);
const r = this.createEntityCursor(e, a);
const i = this.connection.getMetadata(e).deleteDateColumn;
if (n.FindOptionsUtils.isFindManyOptions(t)) {
if (t.select) r.project(this.convertFindOptionsSelectToProjectCriteria(t.select));
if (t.skip) r.skip(t.skip);
if (t.take) r.limit(t.take);
if (t.order) r.sort(this.convertFindOptionsOrderToOrderCriteria(t.order));
if (i && !t.withDeleted) {
this.filterSoftDeleted(r, i, a);
}
} else if (i) {
this.filterSoftDeleted(r, i, a);
}
return r.toArray();
}
async executeFindAndCount(e, t) {
const a = this.convertFindManyOptionsOrConditionsToMongodbQuery(t);
const r = await this.createEntityCursor(e, a);
const i = this.connection.getMetadata(e).deleteDateColumn;
if (n.FindOptionsUtils.isFindManyOptions(t)) {
if (t.select) r.project(this.convertFindOptionsSelectToProjectCriteria(t.select));
if (t.skip) r.skip(t.skip);
if (t.take) r.limit(t.take);
if (t.order) r.sort(this.convertFindOptionsOrderToOrderCriteria(t.order));
if (i && !t.withDeleted) {
this.filterSoftDeleted(r, i, a);
}
} else if (i) {
this.filterSoftDeleted(r, i, a);
}
const [s, o] = await Promise.all([ r.toArray(), this.count(e, a) ]);
return [ s, parseInt(o) ];
}
};
Mm.MongoEntityManager = c;
return Mm;
}
var Pm = {};
var Lm;
function Dm() {
if (Lm) return Pm;
Lm = 1;
Object.defineProperty(Pm, "__esModule", {
value: true
});
Pm.SqljsEntityManager = void 0;
const e = wm();
let t = class SqljsEntityManager extends e.EntityManager {
constructor(e, t) {
super(e, t);
this["@instanceof"] = Symbol.for("SqljsEntityManager");
this.driver = e.driver;
}
async loadDatabase(e) {
await this.driver.load(e);
}
async saveDatabase(e) {
await this.driver.save(e);
}
exportDatabase() {
return this.driver.export();
}
};
Pm.SqljsEntityManager = t;
return Pm;
}
var _m;
function $m() {
if (_m) return ih;
_m = 1;
Object.defineProperty(ih, "__esModule", {
value: true
});
ih.EntityManagerFactory = void 0;
const e = wm();
const t = Im();
const n = Dm();
let a = class EntityManagerFactory {
create(a, r) {
if (a.driver.options.type === "mongodb") return new t.MongoEntityManager(a);
if (a.driver.options.type === "sqljs") return new n.SqljsEntityManager(a, r);
return new e.EntityManager(a, r);
}
};
ih.EntityManagerFactory = a;
return ih;
}
var xm = {};
var qm = {};
var Um = {};
var Bm = {};
Object.defineProperty(Bm, "__esModule", {
value: true
});
Bm.View = void 0;
class View {
constructor(e) {
this["@instanceof"] = Symbol.for("View");
this.indices = [];
if (e) {
this.database = e.database;
this.schema = e.schema;
this.name = e.name;
this.expression = e.expression;
this.materialized = !!e.materialized;
}
}
clone() {
return new View({
database: this.database,
schema: this.schema,
name: this.name,
expression: this.expression,
materialized: this.materialized
});
}
addIndex(e) {
this.indices.push(e);
}
removeIndex(e) {
const t = this.indices.find(t => t.name === e.name);
if (t) {
this.indices.splice(this.indices.indexOf(t), 1);
}
}
static create(e, t) {
const n = {
database: e.database,
schema: e.schema,
name: t.buildTableName(e.tableName, e.schema, e.database),
expression: e.expression,
materialized: e.tableMetadataArgs.materialized
};
return new View(n);
}
}
Bm.View = View;
var Fm = {};
Object.defineProperty(Fm, "__esModule", {
value: true
});
Fm.ViewUtils = void 0;
class ViewUtils {
static viewMetadataCmp(e, t) {
if (!e || !t) {
return 0;
}
if (e.dependsOn && (e.dependsOn.has(t.target) || e.dependsOn.has(t.name))) {
return 1;
}
if (t.dependsOn && (t.dependsOn.has(e.target) || t.dependsOn.has(e.name))) {
return -1;
}
return 0;
}
}
Fm.ViewUtils = ViewUtils;
Object.defineProperty(Um, "__esModule", {
value: true
});
Um.RdbmsSchemaBuilder = void 0;
const jm = fu;
const km = yu;
const Qm = Nu;
const Vm = Tu;
const Km = bu;
const Wm = Cu;
const Hm = Su;
const Gm = Mu;
const Ym = Bm;
const zm = Fm;
const Jm = jn;
class RdbmsSchemaBuilder {
constructor(e) {
this.connection = e;
this["@instanceof"] = Symbol.for("RdbmsSchemaBuilder");
}
async build() {
this.queryRunner = this.connection.createQueryRunner();
this.currentDatabase = this.connection.driver.database;
this.currentSchema = this.connection.driver.schema;
const e = !(this.connection.driver.options.type === "cockroachdb") && !(this.connection.driver.options.type === "spanner") && this.connection.options.migrationsTransactionMode !== "none";
await this.queryRunner.beforeMigration();
if (e) {
await this.queryRunner.startTransaction();
}
try {
await this.createMetadataTableIfNecessary(this.queryRunner);
const t = this.entityToSyncMetadatas.map(e => this.getTablePath(e));
const n = this.viewEntityToSyncMetadatas.map(e => this.getTablePath(e));
await this.queryRunner.getTables(t);
await this.queryRunner.getViews(n);
await this.executeSchemaSyncOperationsInProperOrder();
if (this.connection.queryResultCache) await this.connection.queryResultCache.synchronize(this.queryRunner);
if (e) {
await this.queryRunner.commitTransaction();
}
} catch (t) {
try {
if (e) {
await this.queryRunner.rollbackTransaction();
}
} catch (e) {}
throw t;
} finally {
await this.queryRunner.afterMigration();
await this.queryRunner.release();
}
}
async createMetadataTableIfNecessary(e) {
if (this.viewEntityToSyncMetadatas.length > 0 || this.hasGeneratedColumns()) {
await this.createTypeormMetadataTable(e);
}
}
async log() {
this.queryRunner = this.connection.createQueryRunner();
try {
const e = this.entityToSyncMetadatas.map(e => this.getTablePath(e));
const t = this.viewEntityToSyncMetadatas.map(e => this.getTablePath(e));
await this.queryRunner.getTables(e);
await this.queryRunner.getViews(t);
this.queryRunner.enableSqlMemory();
await this.executeSchemaSyncOperationsInProperOrder();
if (this.connection.queryResultCache) await this.connection.queryResultCache.synchronize(this.queryRunner);
return this.queryRunner.getMemorySql();
} finally {
this.queryRunner.disableSqlMemory();
await this.queryRunner.release();
}
}
get entityToSyncMetadatas() {
return this.connection.entityMetadatas.filter(e => e.synchronize && e.tableType !== "entity-child" && e.tableType !== "view");
}
get viewEntityToSyncMetadatas() {
return this.connection.entityMetadatas.filter(e => e.tableType === "view" && e.synchronize).sort(zm.ViewUtils.viewMetadataCmp);
}
hasGeneratedColumns() {
return this.connection.entityMetadatas.some(e => e.columns.some(e => e.generatedType));
}
async executeSchemaSyncOperationsInProperOrder() {
await this.dropOldViews();
await this.dropOldForeignKeys();
await this.dropOldIndices();
await this.dropOldChecks();
await this.dropOldExclusions();
await this.dropCompositeUniqueConstraints();
await this.renameColumns();
await this.changeTableComment();
await this.createNewTables();
await this.dropRemovedColumns();
await this.addNewColumns();
await this.updatePrimaryKeys();
await this.updateExistColumns();
await this.createNewIndices();
await this.createNewChecks();
await this.createNewExclusions();
await this.createCompositeUniqueConstraints();
await this.createForeignKeys();
await this.createViews();
await this.createNewViewIndices();
}
getTablePath(e) {
const t = this.connection.driver.parseTableName(e);
return this.connection.driver.buildTableName(t.tableName, t.schema || this.currentSchema, t.database || this.currentDatabase);
}
async dropOldForeignKeys() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.foreignKeys.filter(t => {
const n = e.foreignKeys.find(e => t.name === e.name && this.getTablePath(t) === this.getTablePath(e.referencedEntityMetadata));
return !n || n.onDelete && n.onDelete !== t.onDelete || n.onUpdate && n.onUpdate !== t.onUpdate;
});
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`dropping old foreign keys of ${t.name}: ${n.map(e => e.name).join(", ")}`);
await this.queryRunner.dropForeignKeys(t, n);
}
}
async renameTables() {}
async renameColumns() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
if (e.columns.length !== t.columns.length) continue;
const n = e.columns.filter(e => !e.isVirtualProperty).filter(e => !t.columns.find(t => t.name === e.databaseName && t.type === this.connection.driver.normalizeType(e) && t.isNullable === e.isNullable && t.isUnique === this.connection.driver.normalizeIsUnique(e)));
if (n.length === 0 || n.length > 1) continue;
const a = t.columns.filter(t => !e.columns.find(e => !e.isVirtualProperty && e.databaseName === t.name && this.connection.driver.normalizeType(e) === t.type && e.isNullable === t.isNullable && this.connection.driver.normalizeIsUnique(e) === t.isUnique));
if (a.length === 0 || a.length > 1) continue;
const r = a[0].clone();
r.name = n[0].databaseName;
this.connection.logger.logSchemaBuild(`renaming column "${a[0].name}" in "${t.name}" to "${r.name}"`);
await this.queryRunner.renameColumn(t, a[0], r);
}
}
async dropOldIndices() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.indices.filter(t => {
const n = e.indices.find(e => e.name === t.name);
if (n) {
if (n.synchronize === false) return false;
if (n.isUnique !== t.isUnique) return true;
if (n.isSpatial !== t.isSpatial) return true;
if (this.connection.driver.isFullTextColumnTypeSupported() && n.isFulltext !== t.isFulltext) return true;
if (n.columns.length !== t.columnNames.length) return true;
return !n.columns.every(e => t.columnNames.indexOf(e.databaseName) !== -1);
}
return true;
}).map(async e => {
this.connection.logger.logSchemaBuild(`dropping an index: "${e.name}" from table ${t.name}`);
await this.queryRunner.dropIndex(t, e);
});
await Promise.all(n);
}
if (this.connection.options.type === "postgres") {
const e = this.queryRunner;
for (const t of this.viewEntityToSyncMetadatas) {
const n = this.queryRunner.loadedViews.find(e => this.getTablePath(e) === this.getTablePath(t));
if (!n) continue;
const a = n.indices.filter(e => {
const n = t.indices.find(t => t.name === e.name);
if (n) {
if (n.synchronize === false) return false;
if (n.isUnique !== e.isUnique) return true;
if (n.isSpatial !== e.isSpatial) return true;
if (this.connection.driver.isFullTextColumnTypeSupported() && n.isFulltext !== e.isFulltext) return true;
if (n.columns.length !== e.columnNames.length) return true;
return !n.columns.every(t => e.columnNames.indexOf(t.databaseName) !== -1);
}
return true;
}).map(async t => {
this.connection.logger.logSchemaBuild(`dropping an index: "${t.name}" from view ${n.name}`);
await e.dropViewIndex(n, t);
});
await Promise.all(a);
}
}
}
async dropOldChecks() {
if (Jm.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") return;
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.checks.filter(t => !e.checks.find(e => e.name === t.name));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`dropping old check constraint: ${n.map(e => `"${e.name}"`).join(", ")} from table "${t.name}"`);
await this.queryRunner.dropCheckConstraints(t, n);
}
}
async dropCompositeUniqueConstraints() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.uniques.filter(t => t.columnNames.length > 1 && !e.uniques.find(e => e.name === t.name));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`dropping old unique constraint: ${n.map(e => `"${e.name}"`).join(", ")} from table "${t.name}"`);
await this.queryRunner.dropUniqueConstraints(t, n);
}
}
async dropOldExclusions() {
if (!(this.connection.driver.options.type === "postgres")) return;
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.exclusions.filter(t => !e.exclusions.find(e => e.name === t.name));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`dropping old exclusion constraint: ${n.map(e => `"${e.name}"`).join(", ")} from table "${t.name}"`);
await this.queryRunner.dropExclusionConstraints(t, n);
}
}
async changeTableComment() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
if (Jm.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "postgres") {
const n = e.comment;
await this.queryRunner.changeTableComment(t, n);
}
}
}
async createNewTables() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (t) continue;
this.connection.logger.logSchemaBuild(`creating a new table: ${this.getTablePath(e)}`);
const n = jm.Table.create(e, this.connection.driver);
await this.queryRunner.createTable(n, false, false);
this.queryRunner.loadedTables.push(n);
}
}
async createViews() {
for (const e of this.viewEntityToSyncMetadatas) {
const t = this.queryRunner.loadedViews.find(t => {
const n = typeof t.expression === "string" ? t.expression.trim() : t.expression(this.connection).getQuery();
const a = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.getTablePath(t) === this.getTablePath(e) && n === a;
});
if (t) continue;
this.connection.logger.logSchemaBuild(`creating a new view: ${this.getTablePath(e)}`);
const n = Ym.View.create(e, this.connection.driver);
await this.queryRunner.createView(n, true);
this.queryRunner.loadedViews.push(n);
}
}
async dropOldViews() {
const e = [];
const t = this.viewEntityToSyncMetadatas;
const n = new Map;
for (const e of this.queryRunner.loadedViews) {
const a = t.find(t => this.getTablePath(e) === this.getTablePath(t));
if (a) {
n.set(e, a);
}
}
for (const t of this.queryRunner.loadedViews) {
const a = n.get(t);
if (!a) {
continue;
}
const r = typeof t.expression === "string" ? t.expression.trim() : t.expression(this.connection).getQuery();
const i = typeof a.expression === "string" ? a.expression.trim() : a.expression(this.connection).getQuery();
if (r === i) continue;
this.connection.logger.logSchemaBuild(`dropping an old view: ${t.name}`);
e.push(t);
}
const a = e => {
const t = n.get(e);
let r = [ e ];
if (!t) {
return r;
}
for (const [i, s] of n.entries()) {
if (i === e) {
continue;
}
if (s.dependsOn && (s.dependsOn.has(t.target) || s.dependsOn.has(t.name))) {
r = r.concat(a(i));
}
}
return r;
};
const r = new Set(e.map(e => a(e)).reduce((e, t) => e.concat(t), []).sort((e, t) => zm.ViewUtils.viewMetadataCmp(n.get(e), n.get(t))).reverse());
for (const e of r) {
await this.queryRunner.dropView(e);
}
this.queryRunner.loadedViews = this.queryRunner.loadedViews.filter(e => !r.has(e));
}
async dropRemovedColumns() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = t.columns.filter(t => !e.columns.find(e => e.isVirtualProperty || e.databaseName === t.name));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`columns dropped in ${t.name}: ` + n.map(e => e.name).join(", "));
await this.queryRunner.dropColumns(t, n);
}
}
async addNewColumns() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.columns.filter(e => !e.isVirtualProperty && !t.columns.find(t => t.name === e.databaseName));
if (n.length === 0) continue;
const a = this.metadataColumnsToTableColumnOptions(n);
const r = a.map(e => new km.TableColumn(e));
if (r.length === 0) continue;
this.connection.logger.logSchemaBuild(`new columns added: ` + n.map(e => e.databaseName).join(", "));
await this.queryRunner.addColumns(t, r);
}
}
async updatePrimaryKeys() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.columns.filter(e => e.isPrimary);
const a = t.columns.filter(e => e.isPrimary);
if (a.length !== n.length && n.length > 1) {
const e = n.map(e => new km.TableColumn(Km.TableUtils.createTableColumnOptions(e, this.connection.driver)));
await this.queryRunner.updatePrimaryKeys(t, e);
}
}
}
async updateExistColumns() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = this.connection.driver.findChangedColumns(t.columns, e.columns);
if (n.length === 0) continue;
for (const t of n) {
await this.dropColumnReferencedForeignKeys(this.getTablePath(e), t.databaseName);
}
for (const t of n) {
await this.dropColumnCompositeIndices(this.getTablePath(e), t.databaseName);
}
if (!(Jm.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql" || this.connection.driver.options.type === "spanner")) {
for (const t of n) {
await this.dropColumnCompositeUniques(this.getTablePath(e), t.databaseName);
}
}
const a = n.map(e => {
const n = t.columns.find(t => t.name === e.databaseName);
const a = Km.TableUtils.createTableColumnOptions(e, this.connection.driver);
const r = new km.TableColumn(a);
return {
oldColumn: n,
newColumn: r
};
});
if (a.length === 0) continue;
this.connection.logger.logSchemaBuild(`columns changed in "${t.name}". updating: ` + n.map(e => e.databaseName).join(", "));
await this.queryRunner.changeColumns(t, a);
}
}
async createNewIndices() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.indices.filter(e => !t.indices.find(t => t.name === e.name) && e.synchronize === true).map(e => Vm.TableIndex.create(e));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`adding new indices ${n.map(e => `"${e.name}"`).join(", ")} in table "${t.name}"`);
await this.queryRunner.createIndices(t, n);
}
}
async createNewViewIndices() {
if (this.connection.options.type !== "postgres" || !Jm.DriverUtils.isPostgresFamily(this.connection.driver)) {
return;
}
const e = this.queryRunner;
for (const t of this.viewEntityToSyncMetadatas) {
const n = this.queryRunner.loadedViews.find(e => {
const n = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
const a = typeof t.expression === "string" ? t.expression.trim() : t.expression(this.connection).getQuery();
return this.getTablePath(e) === this.getTablePath(t) && n === a;
});
if (!n || !n.materialized) continue;
const a = t.indices.filter(e => !n.indices.find(t => t.name === e.name) && e.synchronize === true).map(e => Vm.TableIndex.create(e));
if (a.length === 0) continue;
this.connection.logger.logSchemaBuild(`adding new indices ${a.map(e => `"${e.name}"`).join(", ")} in view "${n.name}"`);
await e.createViewIndices(n, a);
}
}
async createNewChecks() {
if (Jm.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") return;
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.checks.filter(e => !t.checks.find(t => t.name === e.name)).map(e => Hm.TableCheck.create(e));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`adding new check constraints: ${n.map(e => `"${e.name}"`).join(", ")} in table "${t.name}"`);
await this.queryRunner.createCheckConstraints(t, n);
}
}
async createCompositeUniqueConstraints() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.uniques.filter(e => e.columns.length > 1 && !t.uniques.find(t => t.name === e.name)).map(e => Wm.TableUnique.create(e));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`adding new unique constraints: ${n.map(e => `"${e.name}"`).join(", ")} in table "${t.name}"`);
await this.queryRunner.createUniqueConstraints(t, n);
}
}
async createNewExclusions() {
if (!(this.connection.driver.options.type === "postgres")) return;
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.exclusions.filter(e => !t.exclusions.find(t => t.name === e.name)).map(e => Gm.TableExclusion.create(e));
if (n.length === 0) continue;
this.connection.logger.logSchemaBuild(`adding new exclusion constraints: ${n.map(e => `"${e.name}"`).join(", ")} in table "${t.name}"`);
await this.queryRunner.createExclusionConstraints(t, n);
}
}
async createForeignKeys() {
for (const e of this.entityToSyncMetadatas) {
const t = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === this.getTablePath(e));
if (!t) continue;
const n = e.foreignKeys.filter(e => !t.foreignKeys.find(t => t.name === e.name && this.getTablePath(t) === this.getTablePath(e.referencedEntityMetadata)));
if (n.length === 0) continue;
const a = n.map(e => Qm.TableForeignKey.create(e, this.connection.driver));
this.connection.logger.logSchemaBuild(`creating a foreign keys: ${n.map(e => e.name).join(", ")} on table "${t.name}"`);
await this.queryRunner.createForeignKeys(t, a);
}
}
async dropColumnReferencedForeignKeys(e, t) {
const n = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === e);
if (!n) return;
const a = [];
const r = n.foreignKeys.find(e => e.columnNames.indexOf(t) !== -1);
if (r) {
const e = n.clone();
e.foreignKeys = [ r ];
a.push(e);
n.removeForeignKey(r);
}
for (const n of this.queryRunner.loadedTables) {
const r = n.foreignKeys.filter(n => this.getTablePath(n) === e && n.referencedColumnNames.indexOf(t) !== -1);
if (r.length > 0) {
const e = n.clone();
e.foreignKeys = r;
a.push(e);
r.forEach(e => n.removeForeignKey(e));
}
}
if (a.length > 0) {
for (const e of a) {
this.connection.logger.logSchemaBuild(`dropping related foreign keys of ${e.name}: ${e.foreignKeys.map(e => e.name).join(", ")}`);
await this.queryRunner.dropForeignKeys(e, e.foreignKeys);
}
}
}
async dropColumnCompositeIndices(e, t) {
const n = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === e);
if (!n) return;
const a = n.indices.filter(e => e.columnNames.length > 1 && e.columnNames.indexOf(t) !== -1);
if (a.length === 0) return;
this.connection.logger.logSchemaBuild(`dropping related indices of "${e}"."${t}": ${a.map(e => e.name).join(", ")}`);
await this.queryRunner.dropIndices(n, a);
}
async dropColumnCompositeUniques(e, t) {
const n = this.queryRunner.loadedTables.find(t => this.getTablePath(t) === e);
if (!n) return;
const a = n.uniques.filter(e => e.columnNames.length > 1 && e.columnNames.indexOf(t) !== -1);
if (a.length === 0) return;
this.connection.logger.logSchemaBuild(`dropping related unique constraints of "${e}"."${t}": ${a.map(e => e.name).join(", ")}`);
await this.queryRunner.dropUniqueConstraints(n, a);
}
metadataColumnsToTableColumnOptions(e) {
return e.map(e => Km.TableUtils.createTableColumnOptions(e, this.connection.driver));
}
async createTypeormMetadataTable(e) {
const t = this.currentSchema;
const n = this.currentDatabase;
const a = this.connection.driver.buildTableName(this.connection.metadataTableName, t, n);
const r = this.connection.driver.options.type === "spanner";
await e.createTable(new jm.Table({
database: n,
schema: t,
name: a,
columns: [ {
name: "type",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataType
}),
isNullable: false,
isPrimary: r
}, {
name: "database",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataDatabase
}),
isNullable: true,
isPrimary: r
}, {
name: "schema",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataSchema
}),
isNullable: true,
isPrimary: r
}, {
name: "table",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataTable
}),
isNullable: true,
isPrimary: r
}, {
name: "name",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataName
}),
isNullable: true,
isPrimary: r
}, {
name: "value",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.metadataValue
}),
isNullable: true,
isPrimary: r
} ]
}), true);
}
}
Um.RdbmsSchemaBuilder = RdbmsSchemaBuilder;
var Xm = {};
var Zm = {};
var ef = {};
Object.defineProperty(ef, "__esModule", {
value: true
});
ef.Query = void 0;
class Query {
constructor(e, t) {
this.query = e;
this.parameters = t;
this["@instanceof"] = Symbol.for("Query");
}
}
ef.Query = Query;
var tf = {};
Object.defineProperty(tf, "__esModule", {
value: true
});
tf.SqlInMemory = void 0;
class SqlInMemory {
constructor() {
this.upQueries = [];
this.downQueries = [];
}
}
tf.SqlInMemory = SqlInMemory;
Object.defineProperty(Zm, "__esModule", {
value: true
});
Zm.BaseQueryRunner = void 0;
const nf = ef;
const af = tf;
const rf = D;
const sf = qc;
const of = Te;
const cf = lh;
class BaseQueryRunner {
constructor() {
this.isReleased = false;
this.isTransactionActive = false;
this.data = {};
this.loadedTables = [];
this.loadedViews = [];
this.sqlMemoryMode = false;
this.sqlInMemory = new af.SqlInMemory;
this.transactionDepth = 0;
this.cachedTablePaths = {};
}
async sql(e, ...t) {
const {query: n, parameters: a} = (0, cf.buildSqlTag)({
driver: this.connection.driver,
strings: e,
expressions: t
});
return await this.query(n, a);
}
async beforeMigration() {}
async afterMigration() {}
async getTable(e) {
this.loadedTables = await this.loadTables([ e ]);
return this.loadedTables.length > 0 ? this.loadedTables[0] : undefined;
}
async getTables(e) {
if (!e) {
return await this.loadTables(e);
}
this.loadedTables = await this.loadTables(e);
return this.loadedTables;
}
async getView(e) {
this.loadedViews = await this.loadViews([ e ]);
return this.loadedViews.length > 0 ? this.loadedViews[0] : undefined;
}
async getViews(e) {
this.loadedViews = await this.loadViews(e);
return this.loadedViews;
}
enableSqlMemory() {
this.sqlInMemory = new af.SqlInMemory;
this.sqlMemoryMode = true;
}
disableSqlMemory() {
this.sqlInMemory = new af.SqlInMemory;
this.sqlMemoryMode = false;
}
clearSqlMemory() {
this.sqlInMemory = new af.SqlInMemory;
}
getMemorySql() {
return this.sqlInMemory;
}
async executeMemoryUpSql() {
for (const {query: e, parameters: t} of this.sqlInMemory.upQueries) {
await this.query(e, t);
}
}
async executeMemoryDownSql() {
for (const {query: e, parameters: t} of this.sqlInMemory.downQueries.reverse()) {
await this.query(e, t);
}
}
getReplicationMode() {
return this.mode;
}
async getCachedView(e) {
const t = this.loadedViews.find(t => t.name === e);
if (t) return t;
const n = await this.loadViews([ e ]);
if (n.length > 0) {
this.loadedViews.push(n[0]);
return n[0];
} else {
throw new rf.TypeORMError(`View "${e}" does not exist.`);
}
}
async getCachedTable(e) {
if (e in this.cachedTablePaths) {
const t = this.cachedTablePaths[e];
const n = this.loadedTables.find(e => this.getTablePath(e) === t);
if (n) {
return n;
}
}
const t = await this.loadTables([ e ]);
if (t.length > 0) {
const n = this.getTablePath(t[0]);
const a = this.loadedTables.find(e => this.getTablePath(e) === n);
if (!a) {
this.cachedTablePaths[e] = this.getTablePath(t[0]);
this.loadedTables.push(t[0]);
return t[0];
} else {
return a;
}
} else {
throw new rf.TypeORMError(`Table "${e}" does not exist.`);
}
}
replaceCachedTable(e, t) {
const n = this.getTablePath(e);
const a = this.loadedTables.find(e => this.getTablePath(e) === n);
for (const [e, a] of Object.entries(this.cachedTablePaths)) {
if (a === n) {
this.cachedTablePaths[e] = this.getTablePath(t);
}
}
if (a) {
a.database = t.database;
a.schema = t.schema;
a.name = t.name;
a.columns = t.columns;
a.indices = t.indices;
a.foreignKeys = t.foreignKeys;
a.uniques = t.uniques;
a.checks = t.checks;
a.justCreated = t.justCreated;
a.engine = t.engine;
a.comment = t.comment;
}
}
getTablePath(e) {
const t = this.connection.driver.parseTableName(e);
return this.connection.driver.buildTableName(t.tableName, t.schema, t.database);
}
getTypeormMetadataTableName() {
const e = this.connection.driver.options;
return this.connection.driver.buildTableName(this.connection.metadataTableName, e.schema, e.database);
}
selectTypeormMetadataSql({database: e, schema: t, table: n, type: a, name: r}) {
const i = this.connection.createQueryBuilder();
const s = i.select().from(this.getTypeormMetadataTableName(), "t").where(`${i.escape("type")} = :type`, {
type: a
}).andWhere(`${i.escape("name")} = :name`, {
name: r
});
if (e) {
s.andWhere(`${i.escape("database")} = :database`, {
database: e
});
}
if (t) {
s.andWhere(`${i.escape("schema")} = :schema`, {
schema: t
});
}
if (n) {
s.andWhere(`${i.escape("table")} = :table`, {
table: n
});
}
const [o, c] = s.getQueryAndParameters();
return new nf.Query(o, c);
}
insertTypeormMetadataSql({database: e, schema: t, table: n, type: a, name: r, value: i}) {
const [s, o] = this.connection.createQueryBuilder().insert().into(this.getTypeormMetadataTableName()).values({
database: e,
schema: t,
table: n,
type: a,
name: r,
value: i
}).getQueryAndParameters();
return new nf.Query(s, o);
}
deleteTypeormMetadataSql({database: e, schema: t, table: n, type: a, name: r}) {
const i = this.connection.createQueryBuilder();
const s = i.delete().from(this.getTypeormMetadataTableName()).where(`${i.escape("type")} = :type`, {
type: a
}).andWhere(`${i.escape("name")} = :name`, {
name: r
});
if (e) {
s.andWhere(`${i.escape("database")} = :database`, {
database: e
});
}
if (t) {
s.andWhere(`${i.escape("schema")} = :schema`, {
schema: t
});
}
if (n) {
s.andWhere(`${i.escape("table")} = :table`, {
table: n
});
}
const [o, c] = s.getQueryAndParameters();
return new nf.Query(o, c);
}
isColumnChanged(e, t, n, a, r = true) {
return e.charset !== t.charset || e.collation !== t.collation || e.precision !== t.precision || e.scale !== t.scale || e.width !== t.width || e.zerofill !== t.zerofill || e.unsigned !== t.unsigned || e.asExpression !== t.asExpression || n && e.default !== t.default || e.onUpdate !== t.onUpdate || e.isNullable !== t.isNullable || a && e.comment !== t.comment || r && this.isEnumChanged(e, t);
}
isEnumChanged(e, t) {
return !sf.OrmUtils.isArraysEqual(e.enum || [], t.enum || []);
}
isDefaultColumnLength(e, t, n) {
if (this.connection.hasMetadata(e.name)) {
const n = this.connection.getMetadata(e.name);
const a = n.findColumnWithDatabaseName(t.name);
if (a) {
const e = this.connection.driver.getColumnLength(a);
if (e) return false;
}
}
if (this.connection.driver.dataTypeDefaults && this.connection.driver.dataTypeDefaults[t.type] && this.connection.driver.dataTypeDefaults[t.type].length) {
return this.connection.driver.dataTypeDefaults[t.type].length.toString() === n.toString();
}
return false;
}
isDefaultColumnPrecision(e, t, n) {
if (this.connection.hasMetadata(e.name)) {
const n = this.connection.getMetadata(e.name);
const a = n.findColumnWithDatabaseName(t.name);
if (a && a.precision !== null && a.precision !== undefined) return false;
}
if (this.connection.driver.dataTypeDefaults && this.connection.driver.dataTypeDefaults[t.type] && this.connection.driver.dataTypeDefaults[t.type].precision !== null && this.connection.driver.dataTypeDefaults[t.type].precision !== undefined) return this.connection.driver.dataTypeDefaults[t.type].precision === n;
return false;
}
isDefaultColumnScale(e, t, n) {
if (this.connection.hasMetadata(e.name)) {
const n = this.connection.getMetadata(e.name);
const a = n.findColumnWithDatabaseName(t.name);
if (a && a.scale !== null && a.scale !== undefined) return false;
}
if (this.connection.driver.dataTypeDefaults && this.connection.driver.dataTypeDefaults[t.type] && this.connection.driver.dataTypeDefaults[t.type].scale !== null && this.connection.driver.dataTypeDefaults[t.type].scale !== undefined) return this.connection.driver.dataTypeDefaults[t.type].scale === n;
return false;
}
async executeQueries(e, t) {
if (of.InstanceChecker.isQuery(e)) e = [ e ];
if (of.InstanceChecker.isQuery(t)) t = [ t ];
this.sqlInMemory.upQueries.push(...e);
this.sqlInMemory.downQueries.push(...t);
if (this.sqlMemoryMode === true) return Promise.resolve();
for (const {query: t, parameters: n} of e) {
await this.query(t, n);
}
}
generateIndexName(e, t) {
return this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
}
}
Zm.BaseQueryRunner = BaseQueryRunner;
var lf = {};
Object.defineProperty(lf, "__esModule", {
value: true
});
var uf = lf.QueryResult = void 0;
class QueryResult {
constructor() {
this.records = [];
}
}
uf = lf.QueryResult = QueryResult;
var hf = {};
Object.defineProperty(hf, "__esModule", {
value: true
});
hf.Broadcaster = void 0;
const df = I;
const pf = sc;
class Broadcaster {
constructor(e) {
this.queryRunner = e;
}
async broadcast(e, ...t) {
const n = new pf.BroadcasterResult;
const a = this[`broadcast${e}Event`];
if (typeof a === "function") {
a.call(this, n, ...t);
}
await n.wait();
}
broadcastBeforeInsertEvent(e, t, n) {
if (n && t.beforeInsertListeners.length) {
t.beforeInsertListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(a => {
if (this.isAllowedSubscriber(a, t.target) && a.beforeInsert) {
const r = a.beforeInsert({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t
});
if (r instanceof Promise) e.promises.push(r);
e.count++;
}
});
}
}
broadcastBeforeUpdateEvent(e, t, n, a, r, i) {
if (n && t.beforeUpdateListeners.length) {
t.beforeUpdateListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(s => {
if (this.isAllowedSubscriber(s, t.target) && s.beforeUpdate) {
const o = s.beforeUpdate({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
updatedColumns: r || [],
updatedRelations: i || []
});
if (o instanceof Promise) e.promises.push(o);
e.count++;
}
});
}
}
broadcastBeforeRemoveEvent(e, t, n, a, r) {
if (n && t.beforeRemoveListeners.length) {
t.beforeRemoveListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.beforeRemove) {
const s = i.beforeRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastBeforeSoftRemoveEvent(e, t, n, a, r) {
if (n && t.beforeSoftRemoveListeners.length) {
t.beforeSoftRemoveListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.beforeSoftRemove) {
const s = i.beforeSoftRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastBeforeRecoverEvent(e, t, n, a, r) {
if (n && t.beforeRecoverListeners.length) {
t.beforeRecoverListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.beforeRecover) {
const s = i.beforeRecover({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastAfterInsertEvent(e, t, n, a) {
if (n && t.afterInsertListeners.length) {
t.afterInsertListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(r => {
if (this.isAllowedSubscriber(r, t.target) && r.afterInsert) {
const i = r.afterInsert({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
entityId: t.getEntityIdMixedMap(a)
});
if (i instanceof Promise) e.promises.push(i);
e.count++;
}
});
}
}
broadcastBeforeQueryEvent(e, t, n) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(a => {
if (a.beforeQuery) {
const r = a.beforeQuery({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
query: t,
parameters: n
});
if (r instanceof Promise) e.promises.push(r);
e.count++;
}
});
}
}
broadcastAfterQueryEvent(e, t, n, a, r, i, s) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(o => {
if (o.afterQuery) {
const c = o.afterQuery({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
query: t,
parameters: n,
success: a,
executionTime: r,
rawResults: i,
error: s
});
if (c instanceof Promise) e.promises.push(c);
e.count++;
}
});
}
}
broadcastBeforeTransactionStartEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.beforeTransactionStart) {
const n = t.beforeTransactionStart({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastAfterTransactionStartEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.afterTransactionStart) {
const n = t.afterTransactionStart({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastBeforeTransactionCommitEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.beforeTransactionCommit) {
const n = t.beforeTransactionCommit({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastAfterTransactionCommitEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.afterTransactionCommit) {
const n = t.afterTransactionCommit({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastBeforeTransactionRollbackEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.beforeTransactionRollback) {
const n = t.beforeTransactionRollback({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastAfterTransactionRollbackEvent(e) {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(t => {
if (t.afterTransactionRollback) {
const n = t.afterTransactionRollback({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (n instanceof Promise) e.promises.push(n);
e.count++;
}
});
}
}
broadcastAfterUpdateEvent(e, t, n, a, r, i) {
if (n && t.afterUpdateListeners.length) {
t.afterUpdateListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(s => {
if (this.isAllowedSubscriber(s, t.target) && s.afterUpdate) {
const o = s.afterUpdate({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
updatedColumns: r || [],
updatedRelations: i || []
});
if (o instanceof Promise) e.promises.push(o);
e.count++;
}
});
}
}
broadcastAfterRemoveEvent(e, t, n, a, r) {
if (n && t.afterRemoveListeners.length) {
t.afterRemoveListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.afterRemove) {
const s = i.afterRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastAfterSoftRemoveEvent(e, t, n, a, r) {
if (n && t.afterSoftRemoveListeners.length) {
t.afterSoftRemoveListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.afterSoftRemove) {
const s = i.afterSoftRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastAfterRecoverEvent(e, t, n, a, r) {
if (n && t.afterRecoverListeners.length) {
t.afterRecoverListeners.forEach(t => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(i => {
if (this.isAllowedSubscriber(i, t.target) && i.afterRecover) {
const s = i.afterRecover({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: n,
metadata: t,
databaseEntity: a,
entityId: t.getEntityIdMixedMap(a ?? r)
});
if (s instanceof Promise) e.promises.push(s);
e.count++;
}
});
}
}
broadcastLoadEventsForAll(e, t, n) {
return this.broadcastLoadEvent(e, t, n);
}
broadcastLoadEvent(e, t, n) {
const a = this.queryRunner.connection.subscribers.filter(e => this.isAllowedSubscriber(e, t.target) && e.afterLoad);
if (t.relations.length || t.afterLoadListeners.length || a.length) {
const r = n.filter(e => !(e instanceof Promise));
if (t.relations.length) {
t.relations.forEach(t => {
r.forEach(n => {
if (t.isLazy && !n.hasOwnProperty(t.propertyName)) return;
const a = t.getEntityValue(n);
if (df.ObjectUtils.isObject(a)) this.broadcastLoadEvent(e, t.inverseEntityMetadata, Array.isArray(a) ? a : [ a ]);
});
});
}
if (t.afterLoadListeners.length) {
t.afterLoadListeners.forEach(t => {
r.forEach(n => {
if (t.isAllowed(n)) {
const a = t.execute(n);
if (a instanceof Promise) e.promises.push(a);
e.count++;
}
});
});
}
a.forEach(n => {
r.forEach(a => {
const r = n.afterLoad(a, {
entity: a,
metadata: t,
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager
});
if (r instanceof Promise) e.promises.push(r);
e.count++;
});
});
}
}
isAllowedSubscriber(e, t) {
return !e.listenTo || !e.listenTo() || e.listenTo() === Object || e.listenTo() === t || e.listenTo().isPrototypeOf(t);
}
}
hf.Broadcaster = Broadcaster;
var mf = {};
Object.defineProperty(mf, "__esModule", {
value: true
});
mf.MetadataTableType = void 0;
var ff;
(function(e) {
e["VIEW"] = "VIEW";
e["MATERIALIZED_VIEW"] = "MATERIALIZED_VIEW";
e["GENERATED_COLUMN"] = "GENERATED_COLUMN";
})(ff || (mf.MetadataTableType = ff = {}));
Object.defineProperty(Xm, "__esModule", {
value: true
});
Xm.CockroachQueryRunner = void 0;
const yf = P;
const Ef = nn();
const Tf = Sn();
const gf = pe();
const Nf = Zm;
const Af = lf;
const bf = fu;
const Cf = Su;
const Rf = yu;
const Sf = Mu;
const wf = Nu;
const Mf = Tu;
const Of = Cu;
const vf = Bm;
const If = hf;
const Pf = sc;
const Lf = Te;
const Df = qc;
const _f = us;
const $f = ef;
const xf = mf;
class CockroachQueryRunner extends Nf.BaseQueryRunner {
constructor(e, t) {
super();
this.queries = [];
this.storeQueries = false;
this.transactionRetries = 0;
this.driver = e;
this.connection = e.connection;
this.mode = t;
this.broadcaster = new If.Broadcaster(this);
}
connect() {
if (this.databaseConnection) return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise) return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
const n = e => this.releaseConnection(e);
this.releaseCallback = e => {
this.databaseConnection.removeListener("error", n);
t(e);
};
this.databaseConnection.on("error", n);
return this.databaseConnection;
});
} else {
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
const n = e => this.releaseConnection(e);
this.releaseCallback = e => {
this.databaseConnection.removeListener("error", n);
t(e);
};
this.databaseConnection.on("error", n);
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
async releaseConnection(e) {
if (this.isReleased) {
return;
}
this.isReleased = true;
if (this.releaseCallback) {
this.releaseCallback(e);
this.releaseCallback = undefined;
}
const t = this.driver.connectedQueryRunners.indexOf(this);
if (t !== -1) {
this.driver.connectedQueryRunners.splice(t, 1);
}
}
release() {
return this.releaseConnection();
}
async startTransaction(e) {
this.isTransactionActive = true;
this.transactionRetries = 0;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
await this.query("START TRANSACTION");
await this.query("SAVEPOINT cockroach_restart");
if (e) {
await this.query("SET TRANSACTION ISOLATION LEVEL " + e);
}
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
this.storeQueries = true;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new gf.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
this.transactionDepth -= 1;
} else {
this.storeQueries = false;
await this.query("RELEASE SAVEPOINT cockroach_restart");
await this.query("COMMIT");
this.queries = [];
this.isTransactionActive = false;
this.transactionRetries = 0;
this.transactionDepth -= 1;
}
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new gf.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
this.storeQueries = false;
await this.query("ROLLBACK");
this.queries = [];
this.isTransactionActive = false;
this.transactionRetries = 0;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new Tf.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new Pf.BroadcasterResult;
const i = Date.now();
if (this.isTransactionActive && this.storeQueries) {
this.queries.push({
query: e,
parameters: t
});
}
try {
const s = await new Promise((n, r) => {
a.query(e, t, (e, t) => e ? r(e) : n(t));
});
const o = this.driver.options.maxQueryExecutionTime;
const c = Date.now();
const l = c - i;
if (o && l > o) {
this.driver.connection.logger.logQuerySlow(l, e, t, this);
}
const u = new Af.QueryResult;
if (s.hasOwnProperty("rowCount")) {
u.affected = s.rowCount;
}
if (s.hasOwnProperty("rows")) {
u.records = s.rows;
}
switch (s.command) {
case "DELETE":
u.raw = [ s.rows, s.rowCount ];
break;
default:
u.raw = s.rows;
}
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, s, undefined);
if (n) {
return u;
} else {
return u.raw;
}
} catch (n) {
if (n.code === "40001" && this.isTransactionActive && this.transactionRetries < (this.driver.options.maxTransactionRetries || 5)) {
this.transactionRetries += 1;
this.storeQueries = false;
await this.query("ROLLBACK TO SAVEPOINT cockroach_restart");
const e = 2 ** this.transactionRetries * .1 * (Math.random() + .5) * 1e3;
await new Promise(t => setTimeout(t, e));
let t = undefined;
for (const e of this.queries) {
this.driver.connection.logger.logQuery(`Retrying transaction for query "${e.query}"`, e.parameters, this);
t = await this.query(e.query, e.parameters);
}
this.transactionRetries = 0;
this.storeQueries = true;
return t;
} else {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
throw new Ef.QueryFailedError(e, t, n);
}
} finally {
await r.wait();
}
}
async stream(e, t, n, a) {
const r = this.driver.loadStreamDependency();
if (this.isReleased) {
throw new Tf.QueryRunnerAlreadyReleasedError;
}
const i = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
const s = i.query(new r(e, t));
if (n) {
s.on("end", n);
}
if (a) {
s.on("error", a);
}
return s;
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
return Promise.resolve([]);
}
async hasDatabase(e) {
const t = await this.query(`SELECT * FROM "pg_database" WHERE "datname" = '${e}'`);
return t.length ? true : false;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT * FROM current_database()`);
return e[0]["current_database"];
}
async hasSchema(e) {
const t = await this.query(`SELECT * FROM "information_schema"."schemata" WHERE "schema_name" = '${e}'`);
return t.length ? true : false;
}
async getCurrentSchema() {
const e = await this.query(`SELECT * FROM current_schema()`);
return e[0]["current_schema"];
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = `SELECT * FROM "information_schema"."tables" WHERE "table_schema" = '${t.schema}' AND "table_name" = '${t.tableName}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = `SELECT * FROM "information_schema"."columns" WHERE "table_schema" = '${n.schema}' AND "table_name" = '${n.tableName}' AND "column_name" = '${t}'`;
const r = await this.query(a);
return r.length ? true : false;
}
async createDatabase(e, t) {
const n = `CREATE DATABASE ${t ? "IF NOT EXISTS " : ""} "${e}"`;
const a = `DROP DATABASE "${e}"`;
await this.executeQueries(new $f.Query(n), new $f.Query(a));
}
async dropDatabase(e, t) {
const n = `DROP DATABASE ${t ? "IF EXISTS " : ""} "${e}"`;
const a = `CREATE DATABASE "${e}"`;
await this.executeQueries(new $f.Query(n), new $f.Query(a));
}
async createSchema(e, t) {
const n = e.indexOf(".") === -1 ? e : e.split(".")[1];
const a = t ? `CREATE SCHEMA IF NOT EXISTS "${n}"` : `CREATE SCHEMA "${n}"`;
const r = `DROP SCHEMA "${n}" CASCADE`;
await this.executeQueries(new $f.Query(a), new $f.Query(r));
}
async dropSchema(e, t, n) {
const a = e.indexOf(".") === -1 ? e : e.split(".")[1];
const r = t ? `DROP SCHEMA IF EXISTS "${a}" ${n ? "CASCADE" : ""}` : `DROP SCHEMA "${a}" ${n ? "CASCADE" : ""}`;
const i = `CREATE SCHEMA "${a}"`;
await this.executeQueries(new $f.Query(r), new $f.Query(i));
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
const s = e.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
const o = [];
for (const t of s) {
const n = await this.hasEnumType(e, t);
const a = this.buildEnumName(e, t);
if (!n && o.indexOf(a) === -1) {
o.push(a);
r.push(this.createEnumTypeSql(e, t, a));
i.push(this.dropEnumTypeSql(e, t, a));
}
}
e.columns.filter(e => e.isGenerated && e.generationStrategy === "increment").forEach(t => {
r.push(new $f.Query(`CREATE SEQUENCE ${this.escapePath(this.buildSequencePath(e, t))}`));
i.push(new $f.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(e, t))}`));
});
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.filter(e => !e.isUnique).forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(e, t));
});
}
const c = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of c) {
const n = await this.getCurrentSchema();
let {schema: a} = this.driver.parseTableName(e);
if (!a) {
a = n;
}
const s = this.insertTypeormMetadataSql({
schema: a,
table: e.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const o = this.deleteTypeormMetadataSql({
schema: a,
table: e.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(s);
i.push(o);
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = this.getTablePath(e);
const s = await this.getCachedTable(i);
const o = [];
const c = [];
if (n) s.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(s, e)));
if (a) {
s.indices.forEach(e => {
o.push(this.dropIndexSql(s, e));
c.push(this.createIndexSql(s, e));
});
}
o.push(this.dropTableSql(s));
c.push(this.createTableSql(s, r));
s.columns.filter(e => e.isGenerated && e.generationStrategy === "increment").forEach(e => {
o.push(new $f.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(s, e))}`));
c.push(new $f.Query(`CREATE SEQUENCE ${this.escapePath(this.buildSequencePath(s, e))}`));
});
const l = s.columns.filter(e => e.generatedType && e.asExpression);
for (const e of l) {
const t = await this.getCurrentSchema();
let {schema: n} = this.driver.parseTableName(s);
if (!n) {
n = t;
}
const a = this.deleteTypeormMetadataSql({
schema: n,
table: s.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const r = this.insertTypeormMetadataSql({
schema: n,
table: s.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
o.push(a);
c.push(r);
}
await this.executeQueries(o, c);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = Lf.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {schema: s, tableName: o} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new $f.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
a.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME TO "${o}"`));
if (i.primaryColumns.length > 0 && !i.primaryColumns[0].primaryKeyConstraintName) {
const e = i.primaryColumns.map(e => e.name);
const t = this.connection.namingStrategy.primaryKeyName(r, e);
const s = this.connection.namingStrategy.primaryKeyName(i, e);
n.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${t}" TO "${s}"`));
a.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${t}"`));
}
i.uniques.forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.uniqueConstraintName(i, e.columnNames);
n.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
const {schema: s} = this.driver.parseTableName(i);
const o = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
const c = s ? `ALTER INDEX "${s}"."${e.name}" RENAME TO "${o}"` : `ALTER INDEX "${e.name}" RENAME TO "${o}"`;
const l = s ? `ALTER INDEX "${s}"."${o}" RENAME TO "${e.name}"` : `ALTER INDEX "${o}" RENAME TO "${e.name}"`;
n.push(new $f.Query(c));
a.push(new $f.Query(l));
e.name = o;
});
i.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
n.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new $f.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
const c = i.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
for (const e of c) {
if (e.enumName) continue;
const t = await this.getUserDefinedTypeName(r, e);
n.push(new $f.Query(`ALTER TYPE "${t.schema}"."${t.name}" RENAME TO ${this.buildEnumName(i, e, false)}`));
a.push(new $f.Query(`ALTER TYPE ${this.buildEnumName(i, e)} RENAME TO "${t.name}"`));
}
await this.executeQueries(n, a);
}
async addColumn(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
if (t.generationStrategy === "increment") {
throw new yf.TypeORMError(`Adding sequential generated columns into existing table is not supported`);
}
if (t.type === "enum" || t.type === "simple-enum") {
const e = await this.hasEnumType(n, t);
if (!e) {
r.push(this.createEnumTypeSql(n, t));
i.push(this.dropEnumTypeSql(n, t));
}
}
r.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t)}`));
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${t.name}"`));
if (t.isPrimary) {
const e = a.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const s = e.map(e => `"${e.name}"`).join(", ");
r.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${s})`));
}
e.push(t);
const s = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const o = e.map(e => `"${e.name}"`).join(", ");
r.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${s}" PRIMARY KEY (${o})`));
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${s}"`));
}
if (t.generatedType && t.asExpression) {
const e = await this.getCurrentSchema();
let {schema: a} = this.driver.parseTableName(n);
if (!a) {
a = e;
}
const s = this.insertTypeormMetadataSql({
schema: a,
table: n.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const o = this.deleteTypeormMetadataSql({
schema: a,
table: n.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(s);
i.push(o);
}
const s = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (s) {
if (s.isUnique) {
const e = new Of.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(n, s.columnNames),
columnNames: s.columnNames
});
r.push(this.createUniqueConstraintSql(n, e));
i.push(this.dropIndexSql(n, e));
a.uniques.push(e);
} else {
r.push(this.createIndexSql(n, s));
i.push(this.dropIndexSql(n, s));
}
}
if (t.isUnique) {
const e = new Of.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
columnNames: [ t.name ]
});
a.uniques.push(e);
r.push(this.createUniqueConstraintSql(n, e));
i.push(this.dropIndexSql(n, e.name));
}
if (t.comment) {
r.push(new $f.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
i.push(new $f.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = Lf.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new yf.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i;
if (Lf.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
return this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
let o = false;
const c = Lf.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!c) throw new yf.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (c.type !== n.type || c.length !== n.length || n.isArray !== c.isArray || c.generatedType !== n.generatedType || c.asExpression !== n.asExpression) {
await this.dropColumn(a, c);
await this.addColumn(a, n);
r = a.clone();
} else {
if (c.name !== n.name) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "${n.name}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${n.name}" TO "${c.name}"`));
if (c.type === "enum" || c.type === "simple-enum") {
const e = await this.getUserDefinedTypeName(a, c);
i.push(new $f.Query(`ALTER TYPE "${e.schema}"."${e.name}" RENAME TO ${this.buildEnumName(a, n, false)}`));
s.push(new $f.Query(`ALTER TYPE ${this.buildEnumName(a, n)} RENAME TO "${e.name}"`));
}
if (c.isPrimary === true && !c.primaryKeyConstraintName) {
const e = r.primaryColumns;
const t = e.map(e => e.name);
const o = this.connection.namingStrategy.primaryKeyName(r, t);
t.splice(t.indexOf(c.name), 1);
t.push(n.name);
const l = this.connection.namingStrategy.primaryKeyName(r, t);
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${l}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${l}" TO "${o}"`));
}
r.findColumnUniques(c).forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const o = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${e.name}"`));
e.name = o;
});
r.findColumnIndices(c).forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const {schema: o} = this.driver.parseTableName(a);
const l = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
const u = o ? `ALTER INDEX "${o}"."${e.name}" RENAME TO "${l}"` : `ALTER INDEX "${e.name}" RENAME TO "${l}"`;
const h = o ? `ALTER INDEX "${o}"."${l}" RENAME TO "${e.name}"` : `ALTER INDEX "${l}" RENAME TO "${e.name}"`;
i.push(new $f.Query(u));
s.push(new $f.Query(h));
e.name = l;
});
r.findColumnForeignKeys(c).forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const o = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${e.name}"`));
e.name = o;
});
const e = r.columns.find(e => e.name === c.name);
r.columns[r.columns.indexOf(e)].name = n.name;
c.name = n.name;
}
if (n.precision !== c.precision || n.scale !== c.scale) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
}
if (c.isNullable !== n.isNullable) {
if (n.isNullable) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
} else {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
}
}
if (c.comment !== n.comment) {
i.push(new $f.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${c.name}" IS ${this.escapeComment(n.comment)}`));
s.push(new $f.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${n.name}" IS ${this.escapeComment(c.comment)}`));
}
if (n.isPrimary !== c.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
}
if (n.isPrimary === true) {
e.push(n);
const t = r.columns.find(e => e.name === n.name);
t.isPrimary = true;
const o = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${o}"`));
} else {
const t = e.find(e => e.name === n.name);
e.splice(e.indexOf(t), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
}
}
if (n.isUnique !== c.isUnique) {
if (n.isUnique) {
const e = new Of.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
columnNames: [ n.name ]
});
r.uniques.push(e);
i.push(this.createUniqueConstraintSql(a, e));
s.push(this.dropIndexSql(a, e));
} else {
const e = r.uniques.find(e => e.columnNames.length === 1 && !!e.columnNames.find(e => e === n.name));
r.uniques.splice(r.uniques.indexOf(e), 1);
i.push(this.dropIndexSql(a, e));
s.push(this.createUniqueConstraintSql(a, e));
}
}
if ((n.type === "enum" || n.type === "simple-enum") && (c.type === "enum" || c.type === "simple-enum") && (!Df.OrmUtils.isArraysEqual(n.enum, c.enum) || n.enumName !== c.enumName)) {
const e = n.isArray ? "[]" : "";
const t = this.buildEnumName(a, n);
const r = this.buildEnumName(a, c);
const l = this.buildEnumName(a, c, false);
const u = this.buildEnumName(a, c, true, false, true);
const h = this.buildEnumName(a, c, false, false, true);
i.push(new $f.Query(`ALTER TYPE ${r} RENAME TO ${h}`));
s.push(new $f.Query(`ALTER TYPE ${u} RENAME TO ${l}`));
i.push(this.createEnumTypeSql(a, n, t));
s.push(this.dropEnumTypeSql(a, n, t));
if (c.default !== null && c.default !== undefined) {
o = true;
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET DEFAULT ${c.default}`));
}
const d = `${t}${e} USING "${n.name}"::"text"::${t}${e}`;
const p = `${u}${e} USING "${n.name}"::"text"::${u}${e}`;
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${d}`));
i.push(new $f.Query(`SELECT pg_sleep(0.1)`));
s.push(new $f.Query(`SELECT pg_sleep(0.1)`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${p}`));
if (n.default !== null && n.default !== undefined) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
}
i.push(this.dropEnumTypeSql(a, c, u));
s.push(this.createEnumTypeSql(a, c, u));
}
if (c.isGenerated !== n.isGenerated && n.generationStrategy !== "uuid") {
if (n.isGenerated) {
if (n.generationStrategy === "increment") {
throw new yf.TypeORMError(`Adding sequential generated columns into existing table is not supported`);
} else if (n.generationStrategy === "rowid") {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT unique_rowid()`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
}
} else {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT unique_rowid()`));
}
}
if (n.default !== c.default && !o) {
if (n.default !== null && n.default !== undefined) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
if (c.default !== null && c.default !== undefined) {
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
} else {
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
}
} else if (c.default !== null && c.default !== undefined) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
}
}
}
if ((n.spatialFeatureType || "").toLowerCase() !== (c.spatialFeatureType || "").toLowerCase() || n.srid !== c.srid) {
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Lf.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new yf.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = a.primaryKeyConstraintName ? a.primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
const n = r.findColumnByName(a.name);
n.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns[0].primaryKeyConstraintName ? r.primaryColumns[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
}
const c = r.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (c) {
r.checks.splice(r.checks.indexOf(c), 1);
i.push(this.dropCheckConstraintSql(n, c));
s.push(this.createCheckConstraintSql(n, c));
}
const l = r.uniques.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (l) {
r.uniques.splice(r.uniques.indexOf(l), 1);
i.push(this.dropIndexSql(n, l.name));
s.push(this.createUniqueConstraintSql(n, l));
}
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, a)}`));
if (a.generationStrategy === "increment") {
i.push(new $f.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(n, a))}`));
s.push(new $f.Query(`CREATE SEQUENCE ${this.escapePath(this.buildSequencePath(n, a))}`));
}
if (a.generatedType && a.asExpression) {
const e = await this.getCurrentSchema();
let {schema: t} = this.driver.parseTableName(n);
if (!t) {
t = e;
}
const r = this.deleteTypeormMetadataSql({
schema: t,
table: n.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const o = this.insertTypeormMetadataSql({
schema: t,
table: n.name,
type: xf.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(r);
s.push(o);
}
if (a.type === "enum" || a.type === "simple-enum") {
const e = await this.hasEnumType(n, a);
if (e) {
const e = await this.getUserDefinedTypeName(n, a);
const t = `"${e.schema}"."${e.name}"`;
i.push(this.dropEnumTypeSql(n, a, t));
s.push(this.createEnumTypeSql(n, a, t));
}
}
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t, n) {
const a = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = a.clone();
const i = this.createPrimaryKeySql(a, t, n);
r.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
const s = this.dropPrimaryKeySql(r);
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async updatePrimaryKeys(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = t.map(e => e.name);
const i = [];
const s = [];
const o = a.primaryColumns;
if (o.length > 0) {
const e = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, o.map(e => e.name));
const t = o.map(e => `"${e.name}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
}
a.columns.filter(e => r.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const c = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, r);
const l = r.map(e => `"${e}"`).join(", ");
i.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
s.push(new $f.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
await this.executeQueries(i, s);
this.replaceCachedTable(n, a);
}
async dropPrimaryKey(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.dropPrimaryKeySql(n);
const r = this.createPrimaryKeySql(n, n.primaryColumns.map(e => e.name), t);
await this.executeQueries(a, r);
n.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.uniqueConstraintName(n, t.columnNames);
const a = this.createUniqueConstraintSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addUniqueConstraint(t);
}
async createUniqueConstraints(e, t) {
for (const n of t) {
await this.createUniqueConstraint(e, n);
}
}
async dropUniqueConstraint(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Lf.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
if (!a) throw new yf.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
const r = this.dropIndexSql(n, a);
const i = this.createUniqueConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeUniqueConstraint(a);
}
async dropUniqueConstraints(e, t) {
for (const n of t) {
await this.dropUniqueConstraint(e, n);
}
}
async createCheckConstraint(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Lf.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new yf.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
throw new yf.TypeORMError(`CockroachDB does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new yf.TypeORMError(`CockroachDB does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new yf.TypeORMError(`CockroachDB does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new yf.TypeORMError(`CockroachDB does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
for (const n of t) {
await this.createForeignKey(e, n);
}
}
async dropForeignKey(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Lf.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new yf.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
for (const n of t) {
await this.dropForeignKey(e, n);
}
}
async createIndex(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
if (t.isUnique) {
const e = new Of.TableUnique({
name: t.name,
columnNames: t.columnNames
});
const a = this.createUniqueConstraintSql(n, e);
const r = this.dropIndexSql(n, e);
await this.executeQueries(a, r);
n.addUniqueConstraint(e);
} else {
const e = this.createIndexSql(n, t);
const a = this.dropIndexSql(n, t);
await this.executeQueries(e, a);
n.addIndex(t);
}
}
async createIndices(e, t) {
for (const n of t) {
await this.createIndex(e, n);
}
}
async dropIndex(e, t) {
const n = Lf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Lf.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new yf.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
for (const n of t) {
await this.dropIndex(e, n);
}
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase() {
const e = [];
this.connection.entityMetadatas.filter(e => e.schema).forEach(t => {
const n = !!e.find(e => e === t.schema);
if (!n) e.push(t.schema);
});
e.push(this.driver.options.schema || "current_schema()");
const t = e.map(e => e === "current_schema()" ? e : "'" + e + "'").join(", ");
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = await this.getVersion();
const a = `SELECT 'DROP VIEW IF EXISTS "' || schemaname || '"."' || viewname || '" CASCADE;' as "query" ` + `FROM "pg_views" WHERE "schemaname" IN (${t})`;
const r = await this.query(a);
await Promise.all(r.map(e => this.query(e["query"])));
const i = `SELECT 'DROP TABLE IF EXISTS "' || table_schema || '"."' || table_name || '" CASCADE;' as "query" FROM "information_schema"."tables" WHERE "table_schema" IN (${t})`;
const s = await this.query(i);
await Promise.all(s.map(e => this.query(e["query"])));
const o = `SELECT 'DROP SEQUENCE "' || sequence_schema || '"."' || sequence_name || '";' as "query" FROM "information_schema"."sequences" WHERE "sequence_schema" IN (${t})`;
const c = await this.query(o);
await Promise.all(c.map(e => this.query(e["query"])));
if (_f.VersionUtils.isGreaterOrEqual(e, "20.2.19")) {
await this.dropEnumTypes(t);
}
if (!n) await this.commitTransaction();
} catch (e) {
try {
if (!n) await this.rollbackTransaction();
} catch {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = await this.getCurrentSchema();
const r = e.map(e => {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
return `("t"."schema" = '${t || a}' AND "t"."name" = '${n}')`;
}).join(" OR ");
const i = `SELECT "t".*, "v"."check_option" FROM ${this.escapePath(this.getTypeormMetadataTableName())} "t" ` + `INNER JOIN "information_schema"."views" "v" ON "v"."table_schema" = "t"."schema" AND "v"."table_name" = "t"."name" WHERE "t"."type" = '${xf.MetadataTableType.VIEW}' ${r ? `AND (${r})` : ""}`;
const s = await this.query(i);
return s.map(e => {
const t = new vf.View;
const r = e["schema"] === a && !this.driver.options.schema ? undefined : e["schema"];
t.database = n;
t.schema = e["schema"];
t.name = this.driver.buildTableName(e["name"], r);
t.expression = e["value"];
return t;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = await this.getCurrentSchema();
const n = await this.getCurrentDatabase();
const a = [];
if (!e) {
const e = `SELECT "table_schema", "table_name" FROM "information_schema"."tables"`;
a.push(...await this.query(e));
} else {
const n = e.map(e => this.driver.parseTableName(e)).map(({schema: e, tableName: n}) => `("table_schema" = '${e || t}' AND "table_name" = '${n}')`).join(" OR ");
const r = `SELECT "table_schema", "table_name" FROM "information_schema"."tables" WHERE ` + n;
a.push(...await this.query(r));
}
if (a.length === 0) {
return [];
}
const r = a.map(({table_name: e, table_schema: t}) => `("table_schema" = '${t}' AND "table_name" = '${e}')`).join(" OR ");
const i = `SELECT "columns".*, "attr"."attgenerated" as "generated_type", ` + `pg_catalog.col_description(('"' || table_catalog || '"."' || table_schema || '"."' || table_name || '"')::regclass::oid, ordinal_position) as description ` + `FROM "information_schema"."columns" ` + `LEFT JOIN "pg_class" AS "cls" ON "cls"."relname" = "table_name" ` + `LEFT JOIN "pg_namespace" AS "ns" ON "ns"."oid" = "cls"."relnamespace" AND "ns"."nspname" = "table_schema" ` + `LEFT JOIN "pg_attribute" AS "attr" ON "attr"."attrelid" = "cls"."oid" AND "attr"."attname" = "column_name" AND "attr"."attnum" = "ordinal_position" ` + `WHERE "is_hidden" = 'NO' AND ` + r;
const s = a.map(({table_name: e, table_schema: t}) => `("ns"."nspname" = '${t}' AND "t"."relname" = '${e}')`).join(" OR ");
const o = `SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "cnst"."conname" AS "constraint_name", ` + `pg_get_constraintdef("cnst"."oid") AS "expression", ` + `CASE "cnst"."contype" WHEN 'p' THEN 'PRIMARY' WHEN 'u' THEN 'UNIQUE' WHEN 'c' THEN 'CHECK' WHEN 'x' THEN 'EXCLUDE' END AS "constraint_type", "a"."attname" AS "column_name" ` + `FROM "pg_constraint" "cnst" ` + `INNER JOIN "pg_class" "t" ON "t"."oid" = "cnst"."conrelid" ` + `INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "cnst"."connamespace" ` + `LEFT JOIN "pg_attribute" "a" ON "a"."attrelid" = "cnst"."conrelid" AND "a"."attnum" = ANY ("cnst"."conkey") ` + `WHERE "t"."relkind" = 'r' AND (${s})`;
const c = `SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "i"."relname" AS "constraint_name", "a"."attname" AS "column_name", ` + `CASE "ix"."indisunique" WHEN 't' THEN 'TRUE' ELSE'FALSE' END AS "is_unique", pg_get_expr("ix"."indpred", "ix"."indrelid") AS "condition", ` + `"types"."typname" AS "type_name" ` + `FROM "pg_class" "t" ` + `INNER JOIN "pg_index" "ix" ON "ix"."indrelid" = "t"."oid" ` + `INNER JOIN "pg_attribute" "a" ON "a"."attrelid" = "t"."oid" AND "a"."attnum" = ANY ("ix"."indkey") ` + `INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "t"."relnamespace" ` + `INNER JOIN "pg_class" "i" ON "i"."oid" = "ix"."indexrelid" ` + `INNER JOIN "pg_type" "types" ON "types"."oid" = "a"."atttypid" ` + `LEFT JOIN "pg_constraint" "cnst" ON "cnst"."conname" = "i"."relname" ` + `WHERE "t"."relkind" = 'r' AND "cnst"."contype" IS NULL AND (${s})`;
const l = a.map(({table_name: e, table_schema: t}) => `("ns"."nspname" = '${t}' AND "cl"."relname" = '${e}')`).join(" OR ");
const u = `SELECT "con"."conname" AS "constraint_name", "con"."nspname" AS "table_schema", "con"."relname" AS "table_name", "att2"."attname" AS "column_name", ` + `"ns"."nspname" AS "referenced_table_schema", "cl"."relname" AS "referenced_table_name", "att"."attname" AS "referenced_column_name", "con"."confdeltype" AS "on_delete", "con"."confupdtype" AS "on_update" ` + `FROM ( ` + `SELECT UNNEST ("con1"."conkey") AS "parent", UNNEST ("con1"."confkey") AS "child", "con1"."confrelid", "con1"."conrelid", "con1"."conname", "con1"."contype", "ns"."nspname", "cl"."relname", ` + `CASE "con1"."confdeltype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confdeltype", ` + `CASE "con1"."confupdtype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confupdtype" ` + `FROM "pg_class" "cl" ` + `INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" ` + `INNER JOIN "pg_constraint" "con1" ON "con1"."conrelid" = "cl"."oid" ` + `WHERE "con1"."contype" = 'f' AND (${l}) ` + `) "con" ` + `INNER JOIN "pg_attribute" "att" ON "att"."attrelid" = "con"."confrelid" AND "att"."attnum" = "con"."child" ` + `INNER JOIN "pg_class" "cl" ON "cl"."oid" = "con"."confrelid" ` + `INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" ` + `INNER JOIN "pg_attribute" "att2" ON "att2"."attrelid" = "con"."conrelid" AND "att2"."attnum" = "con"."parent"`;
const h = a.map(e => `'${e.table_schema}'`).join(", ");
const d = `SELECT "t"."typname" AS "name", string_agg("e"."enumlabel", '|') AS "value" ` + `FROM "pg_enum" "e" ` + `INNER JOIN "pg_type" "t" ON "t"."oid" = "e"."enumtypid" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" IN (${h}) ` + `GROUP BY "t"."typname"`;
const [p, m, f, y, E] = await Promise.all([ this.query(i), this.query(o), this.query(c), this.query(u), this.query(d) ]);
return Promise.all(a.map(async e => {
const a = new bf.Table;
const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
const i = r(e, "table_schema");
a.database = n;
a.schema = e["table_schema"];
a.name = this.driver.buildTableName(e["table_name"], i);
a.columns = await Promise.all(p.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]).map(async t => {
const n = m.filter(e => e["table_name"] === t["table_name"] && e["table_schema"] === t["table_schema"] && e["column_name"] === t["column_name"]);
const r = new Rf.TableColumn;
r.name = t["column_name"];
r.type = t["crdb_sql_type"].toLowerCase();
if (t["crdb_sql_type"].indexOf("COLLATE") !== -1) {
r.collation = t["crdb_sql_type"].substr(t["crdb_sql_type"].indexOf("COLLATE") + "COLLATE".length + 1, t["crdb_sql_type"].length);
r.type = r.type.substr(0, t["crdb_sql_type"].indexOf("COLLATE") - 1);
}
if (r.type.indexOf("(") !== -1) r.type = r.type.substr(0, r.type.indexOf("("));
if (r.type === "numeric" || r.type === "decimal") {
if (t["numeric_precision"] !== null && !this.isDefaultColumnPrecision(a, r, t["numeric_precision"])) {
r.precision = parseInt(t["numeric_precision"]);
} else if (t["numeric_scale"] !== null && !this.isDefaultColumnScale(a, r, t["numeric_scale"])) {
r.precision = undefined;
}
if (t["numeric_scale"] !== null && !this.isDefaultColumnScale(a, r, t["numeric_scale"])) {
r.scale = parseInt(t["numeric_scale"]);
} else if (t["numeric_precision"] !== null && !this.isDefaultColumnPrecision(a, r, t["numeric_precision"])) {
r.scale = undefined;
}
}
let i = t["udt_name"];
if (i.indexOf("_") === 0) {
i = i.substr(1, i.length);
}
const s = E.find(e => e["name"] === i);
if (s) {
const e = this.buildEnumName(a, r, false, true);
const t = e !== s["name"] ? s["name"] : undefined;
r.type = "enum";
r.enum = s["value"].split("|");
r.enumName = t;
}
if (t["data_type"].toLowerCase() === "array") {
r.isArray = true;
if (!s) {
const e = t["crdb_sql_type"].replace("[]", "").toLowerCase();
r.type = this.connection.driver.normalizeType({
type: e
});
}
}
if (this.driver.withLengthColumnTypes.indexOf(r.type) !== -1 && t["character_maximum_length"]) {
const e = t["character_maximum_length"].toString();
r.length = !this.isDefaultColumnLength(a, r, e) ? e : "";
}
r.isNullable = t["is_nullable"] === "YES";
const o = n.find(e => e["constraint_type"] === "PRIMARY");
if (o) {
r.isPrimary = true;
const e = m.filter(e => e["table_name"] === t["table_name"] && e["table_schema"] === t["table_schema"] && e["column_name"] !== t["column_name"] && e["constraint_type"] === "PRIMARY");
const n = e.map(e => e["column_name"]);
n.push(t["column_name"]);
const i = this.connection.namingStrategy.primaryKeyName(a, n);
if (o["constraint_name"] !== i) {
r.primaryKeyConstraintName = o["constraint_name"];
}
}
const c = n.filter(e => e["constraint_type"] === "UNIQUE");
const l = c.every(e => m.some(n => n["constraint_type"] === "UNIQUE" && n["constraint_name"] === e["constraint_name"] && n["column_name"] !== t["column_name"]));
r.isUnique = c.length > 0 && !l;
if (t["column_default"] !== null && t["column_default"] !== undefined) {
if (t["column_default"] === "unique_rowid()") {
r.isGenerated = true;
r.generationStrategy = "rowid";
} else if (t["column_default"].indexOf("nextval") !== -1) {
r.isGenerated = true;
r.generationStrategy = "increment";
} else if (t["column_default"] === "gen_random_uuid()") {
r.isGenerated = true;
r.generationStrategy = "uuid";
} else {
r.default = t["column_default"].replace(/:::[\w\s[\]"]+/g, "");
r.default = r.default.replace(/^(-?[\d.]+)$/, "($1)");
if (s) {
r.default = r.default.replace(`.${s["name"]}`, "");
}
}
}
if ((t["is_generated"] === "YES" || t["is_generated"] === "ALWAYS") && t["generation_expression"]) {
r.generatedType = t["generated_type"] === "s" ? "STORED" : "VIRTUAL";
const n = this.selectTypeormMetadataSql({
schema: e["table_schema"],
table: e["table_name"],
type: xf.MetadataTableType.GENERATED_COLUMN,
name: r.name
});
const a = await this.query(n.query, n.parameters);
if (a[0] && a[0].value) {
r.asExpression = a[0].value;
} else {
r.asExpression = "";
}
}
r.comment = t["description"] == null ? undefined : t["description"];
if (t["character_set_name"]) r.charset = t["character_set_name"];
if (r.type === "geometry" || r.type === "geography") {
const e = `SELECT * FROM (` + `SELECT "f_table_schema" "table_schema", "f_table_name" "table_name", ` + `"f_${r.type}_column" "column_name", "srid", "type" ` + `FROM "${r.type}_columns"` + `) AS _ ` + `WHERE "column_name" = '${t["column_name"]}' AND ` + `"table_schema" = '${t["table_schema"]}' AND ` + `"table_name" = '${t["table_name"]}'`;
const n = await this.query(e);
if (n.length > 0) {
r.spatialFeatureType = n[0].type;
r.srid = n[0].srid ? parseInt(n[0].srid) : undefined;
}
}
return r;
}));
const s = Df.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "UNIQUE"), e => e["constraint_name"]);
a.uniques = s.map(e => {
const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
return new Of.TableUnique({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"])
});
});
const o = Df.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "CHECK"), e => e["constraint_name"]);
a.checks = o.map(e => {
const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
return new Cf.TableCheck({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
expression: e["expression"].replace(/^\s*CHECK\s*\((.*)\)\s*$/i, "$1")
});
});
const c = Df.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "EXCLUDE"), e => e["constraint_name"]);
a.exclusions = c.map(e => new Sf.TableExclusion({
name: e["constraint_name"],
expression: e["expression"].substring(8)
}));
const l = Df.OrmUtils.uniq(y.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]), e => e["constraint_name"]);
a.foreignKeys = l.map(e => {
const t = y.filter(t => t["constraint_name"] === e["constraint_name"]);
const n = r(e, "referenced_table_schema");
const a = this.driver.buildTableName(e["referenced_table_name"], n);
return new wf.TableForeignKey({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
referencedSchema: e["referenced_table_schema"],
referencedTableName: a,
referencedColumnNames: t.map(e => e["referenced_column_name"]),
onDelete: e["on_delete"],
onUpdate: e["on_update"]
});
});
const u = Df.OrmUtils.uniq(f.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]), e => e["constraint_name"]);
a.indices = u.map(e => {
const t = f.filter(t => t["constraint_name"] === e["constraint_name"]);
return new Mf.TableIndex({
table: a,
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
isUnique: e["is_unique"] === "TRUE",
where: e["condition"],
isSpatial: t.every(e => this.driver.spatialTypes.indexOf(e["type_name"]) >= 0),
isFulltext: false
});
});
return a;
}));
}
createTableSql(e, t) {
const n = e.columns.map(t => this.buildCreateColumnSql(e, t)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (!n) e.uniques.push(new Of.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ]
}));
});
e.indices.filter(e => e.isUnique).forEach(t => {
e.uniques.push(new Of.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, t.columnNames),
columnNames: t.columnNames
}));
});
if (e.uniques.length > 0) {
const t = e.uniques.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.uniqueConstraintName(e, t.columnNames);
const a = t.columnNames.map(e => `"${e}"`).join(", ");
return `CONSTRAINT "${n}" UNIQUE (${a})`;
}).join(", ");
a += `, ${t}`;
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT "${n}" CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${t.name}" FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return r;
}).join(", ");
a += `, ${t}`;
}
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const t = r[0].primaryKeyConstraintName ? r[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(e, r.map(e => e.name));
const n = r.map(e => `"${e.name}"`).join(", ");
a += `, CONSTRAINT "${t}" PRIMARY KEY (${n})`;
}
a += `)`;
e.columns.filter(e => e.comment).forEach(t => a += `; COMMENT ON COLUMN ${this.escapePath(e)}."${t.name}" IS ${this.escapeComment(t.comment)}`);
return new $f.Query(a);
}
async getVersion() {
const e = await this.query(`SELECT version() AS "version"`);
const t = e[0].version;
return t.replace(/^CockroachDB CCL v([\d.]+) .*$/, "$1");
}
dropTableSql(e) {
return new $f.Query(`DROP TABLE ${this.escapePath(e)}`);
}
createViewSql(e) {
if (typeof e.expression === "string") {
return new $f.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
} else {
return new $f.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
const t = await this.getCurrentSchema();
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = t;
}
const r = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: xf.MetadataTableType.VIEW,
schema: n,
name: a,
value: r
});
}
dropViewSql(e) {
return new $f.Query(`DROP VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const t = await this.getCurrentSchema();
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = t;
}
return this.deleteTypeormMetadataSql({
type: xf.MetadataTableType.VIEW,
schema: n,
name: a
});
}
async dropEnumTypes(e) {
const t = `SELECT 'DROP TYPE IF EXISTS "' || n.nspname || '"."' || t.typname || '";' as "query" FROM "pg_type" "t" ` + `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" IN (${e}) GROUP BY "n"."nspname", "t"."typname"`;
const n = await this.query(t);
await Promise.all(n.map(e => this.query(e["query"])));
}
async hasEnumType(e, t) {
let {schema: n} = this.driver.parseTableName(e);
if (!n) {
n = await this.getCurrentSchema();
}
const a = this.buildEnumName(e, t, false, true);
const r = `SELECT "n"."nspname", "t"."typname" FROM "pg_type" "t" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" = '${n}' AND "t"."typname" = '${a}'`;
const i = await this.query(r);
return i.length ? true : false;
}
createEnumTypeSql(e, t, n) {
if (!n) n = this.buildEnumName(e, t);
const a = t.enum.map(e => `'${e.replaceAll("'", "''")}'`).join(", ");
return new $f.Query(`CREATE TYPE ${n} AS ENUM(${a})`);
}
dropEnumTypeSql(e, t, n) {
if (!n) n = this.buildEnumName(e, t);
return new $f.Query(`DROP TYPE ${n}`);
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
return new $f.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} ${t.isSpatial ? "USING GiST " : ""}(${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
dropIndexSql(e, t) {
const n = Lf.InstanceChecker.isTableIndex(t) || Lf.InstanceChecker.isTableUnique(t) ? t.name : t;
return new $f.Query(`DROP INDEX ${this.escapePath(e)}@"${n}" CASCADE`);
}
createPrimaryKeySql(e, t, n) {
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
const r = t.map(e => `"${e}"`).join(", ");
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
}
dropPrimaryKeySql(e) {
if (!e.primaryColumns.length) throw new yf.TypeORMError(`Table ${e} has no primary keys.`);
const t = e.primaryColumns.map(e => e.name);
const n = e.primaryColumns[0].primaryKeyConstraintName;
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
}
createUniqueConstraintSql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
}
dropUniqueConstraintSql(e, t) {
const n = Lf.InstanceChecker.isTableUnique(t) ? t.name : t;
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createCheckConstraintSql(e, t) {
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = Lf.InstanceChecker.isTableCheck(t) ? t.name : t;
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
const a = t.referencedColumnNames.map(e => `"` + e + `"`).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return new $f.Query(r);
}
dropForeignKeySql(e, t) {
const n = Lf.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new $f.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
buildSequenceName(e, t) {
const {tableName: n} = this.driver.parseTableName(e);
const a = Lf.InstanceChecker.isTableColumn(t) ? t.name : t;
return `${n}_${a}_seq`;
}
buildSequencePath(e, t) {
const {schema: n} = this.driver.parseTableName(e);
return n ? `${n}.${this.buildSequenceName(e, t)}` : this.buildSequenceName(e, t);
}
buildEnumName(e, t, n = true, a, r) {
const {schema: i, tableName: s} = this.driver.parseTableName(e);
let o = t.enumName ? t.enumName : `${s}_${t.name.toLowerCase()}_enum`;
if (i && n) o = `${i}.${o}`;
if (r) o = o + "_old";
return o.split(".").map(e => a ? e : `"${e}"`).join(".");
}
async getUserDefinedTypeName(e, t) {
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = await this.getCurrentSchema();
}
const r = await this.query(`SELECT "udt_schema", "udt_name" ` + `FROM "information_schema"."columns" WHERE "table_schema" = '${n}' AND "table_name" = '${a}' AND "column_name"='${t.name}'`);
let i = r[0]["udt_name"];
if (i.indexOf("_") === 0) {
i = i.substr(1, i.length);
}
return {
schema: r[0]["udt_schema"],
name: i
};
}
escapeComment(e) {
if (e === undefined || e.length === 0) {
return "NULL";
}
e = e.replace(/'/g, "''").replace(/\u0000/g, "");
return `'${e}'`;
}
escapePath(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
if (t && t !== this.driver.searchSchema) {
return `"${t}"."${n}"`;
}
return `"${n}"`;
}
buildCreateColumnSql(e, t) {
let n = '"' + t.name + '"';
if (t.isGenerated) {
if (t.generationStrategy === "increment") {
n += ` INT DEFAULT nextval('${this.escapePath(this.buildSequencePath(e, t))}')`;
} else if (t.generationStrategy === "rowid") {
n += " INT DEFAULT unique_rowid()";
} else if (t.generationStrategy === "uuid") {
n += " UUID DEFAULT gen_random_uuid()";
}
}
if (t.type === "enum" || t.type === "simple-enum") {
n += " " + this.buildEnumName(e, t);
if (t.isArray) n += " array";
} else if (!t.isGenerated) {
n += " " + this.connection.driver.createFullType(t);
}
if (t.asExpression) {
n += ` AS (${t.asExpression}) ${t.generatedType ? t.generatedType : "VIRTUAL"}`;
} else {
if (t.charset) n += ' CHARACTER SET "' + t.charset + '"';
if (t.collation) n += ' COLLATE "' + t.collation + '"';
}
if (!t.isNullable) n += " NOT NULL";
if (!t.isGenerated && t.default !== undefined && t.default !== null) n += " DEFAULT " + t.default;
return n;
}
changeTableComment(e, t) {
throw new yf.TypeORMError(`cockroachdb driver does not support change table comment.`);
}
}
Xm.CockroachQueryRunner = CockroachQueryRunner;
Object.defineProperty(qm, "__esModule", {
value: true
});
qm.CockroachDriver = void 0;
const qf = P;
const Uf = Y();
const Bf = Tt();
const Ff = Uh;
const jf = Um;
const kf = _s;
const Qf = up;
const Vf = Te;
const Kf = I;
const Wf = qc;
const Hf = jn;
const Gf = Xm;
class CockroachDriver {
constructor(e) {
this.slaves = [];
this.connectedQueryRunners = [];
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "array", "bool", "boolean", "bytes", "bytea", "blob", "date", "enum", "geometry", "geography", "numeric", "decimal", "dec", "float", "float4", "float8", "double precision", "real", "inet", "int", "int4", "integer", "int2", "int8", "int64", "smallint", "bigint", "interval", "string", "character varying", "character", "char", "char varying", "varchar", "text", "time", "time without time zone", "timestamp", "timestamptz", "timestamp without time zone", "timestamp with time zone", "json", "jsonb", "uuid" ];
this.supportedUpsertTypes = [ "on-conflict-do-update", "primary-key" ];
this.spatialTypes = [ "geometry", "geography" ];
this.withLengthColumnTypes = [ "character varying", "char varying", "varchar", "character", "char", "string" ];
this.withPrecisionColumnTypes = [ "numeric", "decimal", "dec" ];
this.withScaleColumnTypes = [ "numeric", "decimal", "dec" ];
this.mappedDataTypes = {
createDate: "timestamptz",
createDateDefault: "now()",
updateDate: "timestamptz",
updateDateDefault: "now()",
deleteDate: "timestamptz",
deleteDateNullable: true,
version: Number,
treeLevel: Number,
migrationId: Number,
migrationName: "varchar",
migrationTimestamp: "int8",
cacheId: Number,
cacheIdentifier: "varchar",
cacheTime: "int8",
cacheDuration: Number,
cacheQuery: "string",
cacheResult: "string",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "string"
};
this.parametersPrefix = "$";
this.dataTypeDefaults = {
char: {
length: 1
}
};
this.cteCapabilities = {
enabled: true,
writable: true,
materializedHint: true,
requiresRecursiveHint: true
};
this.connection = e;
this.options = e.options;
this.isReplicated = this.options.replication ? true : false;
this.loadDependencies();
this.database = Hf.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
this.schema = Hf.DriverUtils.buildDriverOptions(this.options).schema;
}
async connect() {
if (this.options.replication) {
this.slaves = await Promise.all(this.options.replication.slaves.map(e => this.createPool(this.options, e)));
this.master = await this.createPool(this.options, this.options.replication.master);
} else {
this.master = await this.createPool(this.options, this.options);
}
if (!this.database || !this.searchSchema) {
const e = this.createQueryRunner("master");
if (!this.database) {
this.database = await e.getCurrentDatabase();
}
if (!this.searchSchema) {
this.searchSchema = await e.getCurrentSchema();
}
await e.release();
}
if (!this.schema) {
this.schema = this.searchSchema;
}
}
async afterConnect() {
if (this.options.timeTravelQueries) {
await this.connection.query(`SET default_transaction_use_follower_reads = 'on';`);
}
await this.connection.query("SET enable_experimental_alter_column_type_general = true");
return Promise.resolve();
}
async disconnect() {
if (!this.master) return Promise.reject(new Uf.ConnectionIsNotSetError("cockroachdb"));
await this.closePool(this.master);
await Promise.all(this.slaves.map(e => this.closePool(e)));
this.master = undefined;
this.slaves = [];
}
createSchemaBuilder() {
return new jf.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new Gf.CockroachQueryRunner(this, e);
}
preparePersistentValue(e, t) {
if (t.transformer) e = kf.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return Qf.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return Qf.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "datetime" || t.type === Date || t.type === "timestamp" || t.type === "timestamptz" || t.type === "timestamp with time zone" || t.type === "timestamp without time zone") {
return Qf.DateUtils.mixedDateToDate(e);
} else if ([ "json", "jsonb", ...this.spatialTypes ].indexOf(t.type) >= 0) {
return JSON.stringify(e);
} else if (t.type === "simple-array") {
return Qf.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return Qf.DateUtils.simpleJsonToString(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? kf.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if ([ Number, "int4", "smallint", "int2" ].some(e => e === t.type) && !t.isArray || t.generationStrategy === "increment") {
e = parseInt(e);
} else if (t.type === Boolean) {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date || t.type === "timestamp" || t.type === "timestamptz" || t.type === "timestamp with time zone" || t.type === "timestamp without time zone") {
e = Qf.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = Qf.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = Qf.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array") {
e = Qf.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = Qf.DateUtils.stringToSimpleJson(e);
} else if (t.type === "enum" || t.type === "simple-enum") {
if (t.isArray) {
if (e === "{}") return [];
if (Array.isArray(e)) return e;
e = e.slice(1, -1).split(",").map(e => {
if (e.startsWith(`"`) && e.endsWith(`"`)) e = e.slice(1, -1);
return e.replace(/\\(\\|")/g, "$1");
});
e = e.map(e => !isNaN(+e) && t.enum.indexOf(parseInt(e)) >= 0 ? parseInt(e) : e);
} else {
e = !isNaN(+e) && t.enum.indexOf(parseInt(e)) >= 0 ? parseInt(e) : e;
}
}
if (t.transformer) e = kf.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
const r = new Map;
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
if (r.has(i)) {
return this.parametersPrefix + r.get(i);
}
const s = t[i];
if (n) {
return s.map(e => {
a.push(e);
return this.createParameter(i, a.length - 1);
}).join(", ");
}
if (typeof s === "function") {
return s();
}
a.push(s);
r.set(i, a.length);
return this.createParameter(i, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return '"' + e + '"';
}
buildTableName(e, t) {
const n = [ e ];
if (t) {
n.unshift(t);
}
return n.join(".");
}
parseTableName(e) {
const t = this.database;
const n = this.schema;
if (Vf.InstanceChecker.isTable(e) || Vf.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (Vf.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (Vf.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: t,
schema: (a.length > 1 ? a[0] : undefined) || n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
normalizeType(e) {
if (e.type === Number || e.type === "integer" || e.type === "int" || e.type === "bigint" || e.type === "int64") {
return "int8";
} else if (e.type === String || e.type === "character varying" || e.type === "char varying") {
return "varchar";
} else if (e.type === Date || e.type === "timestamp without time zone") {
return "timestamp";
} else if (e.type === "timestamp with time zone") {
return "timestamptz";
} else if (e.type === "time without time zone") {
return "time";
} else if (e.type === Boolean || e.type === "boolean") {
return "bool";
} else if (e.type === "simple-array" || e.type === "simple-json" || e.type === "text") {
return "string";
} else if (e.type === "bytea" || e.type === "blob") {
return "bytes";
} else if (e.type === "smallint") {
return "int2";
} else if (e.type === "numeric" || e.type === "dec") {
return "decimal";
} else if (e.type === "double precision" || e.type === "float") {
return "float8";
} else if (e.type === "real") {
return "float4";
} else if (e.type === "character") {
return "char";
} else if (e.type === "simple-enum") {
return "enum";
} else if (e.type === "json") {
return "jsonb";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (t === undefined || t === null) {
return undefined;
}
if ((e.type === "enum" || e.type === "simple-enum") && t !== undefined) {
if (e.isArray) {
const n = this.buildEnumName(e);
let a = t;
if (typeof t === "string") {
if (t === "{}") return `ARRAY[]::${n}[]`;
a = t.replace("{", "").replace("}", "").split(",");
}
if (Array.isArray(a)) {
const e = `ARRAY[${a.map(e => `'${e}'`).join(",")}]`;
return `${e}::${n}[]`;
}
} else {
return `'${t}'`;
}
} else if (typeof t === "number") {
return `(${t})`;
}
if (typeof t === "boolean") {
return t ? "true" : "false";
}
if (typeof t === "function") {
const e = t();
if (e.toUpperCase() === "CURRENT_TIMESTAMP") {
return "current_timestamp()";
} else if (e.toUpperCase() === "CURRENT_DATE") {
return "current_date()";
}
return e;
}
if (typeof t === "string") {
const n = e.isArray ? `::${e.type}[]` : "";
return `'${t}'${n}`;
}
if (Kf.ObjectUtils.isObject(t) && t !== null) {
return `'${JSON.stringify(t)}'`;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
return e.length ? e.length.toString() : "";
}
createFullType(e) {
let t = e.type;
if (e.length) {
t += "(" + e.length + ")";
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += "(" + e.precision + "," + e.scale + ")";
} else if (e.precision !== null && e.precision !== undefined) {
t += "(" + e.precision + ")";
} else if (this.spatialTypes.indexOf(e.type) >= 0) {
if (e.spatialFeatureType != null && e.srid != null) {
t = `${e.type}(${e.spatialFeatureType},${e.srid})`;
} else if (e.spatialFeatureType != null) {
t = `${e.type}(${e.spatialFeatureType})`;
} else {
t = e.type;
}
}
if (e.isArray) t += " array";
return t;
}
async obtainMasterConnection() {
if (!this.master) {
throw new qf.TypeORMError("Driver not Connected");
}
return new Promise((e, t) => {
this.master.connect((n, a, r) => {
n ? t(n) : e([ a, r ]);
});
});
}
async obtainSlaveConnection() {
if (!this.slaves.length) return this.obtainMasterConnection();
const e = Math.floor(Math.random() * this.slaves.length);
return new Promise((t, n) => {
this.slaves[e].connect((e, a, r) => {
e ? n(e) : t([ a, r ]);
});
});
}
createGeneratedMap(e, t) {
if (!t) return undefined;
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
Wf.OrmUtils.mergeDeep(n, r.createValueMap(this.prepareHydratedValue(t[a], r)));
}
return n;
}, {});
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
return n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== t.length || n.isArray !== t.isArray || n.precision !== t.precision || t.scale !== undefined && n.scale !== t.scale || n.comment !== this.escapeComment(t.comment) || !n.isGenerated && this.lowerDefaultValueIfNecessary(this.normalizeDefault(t)) !== n.default || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.isUnique !== this.normalizeIsUnique(t) || n.enumName !== t.enumName || n.enum && t.enum && !Wf.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || n.isGenerated !== t.isGenerated || n.generatedType !== t.generatedType || (n.asExpression || "").trim() !== (t.asExpression || "").trim() || (n.spatialFeatureType || "").toLowerCase() !== (t.spatialFeatureType || "").toLowerCase() || n.srid !== t.srid;
});
}
lowerDefaultValueIfNecessary(e) {
if (!e) {
return e;
}
return e.split(`'`).map((e, t) => t % 2 === 1 ? e : e.toLowerCase()).join(`'`);
}
isReturningSqlSupported() {
return true;
}
isUUIDGenerationSupported() {
return true;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return this.parametersPrefix + (t + 1);
}
loadStreamDependency() {
try {
return Ff.PlatformTools.load("pg-query-stream");
} catch (e) {
throw new qf.TypeORMError(`To use streams you should install pg-query-stream package. Please run npm i pg-query-stream --save command.`);
}
}
loadDependencies() {
try {
const e = this.options.driver || Ff.PlatformTools.load("pg");
this.postgres = e;
try {
const e = this.options.nativeDriver || Ff.PlatformTools.load("pg-native");
if (e && this.postgres.native) this.postgres = this.postgres.native;
} catch (e) {}
} catch (e) {
throw new Bf.DriverPackageNotInstalledError("Postgres", "pg");
}
}
async createPool(e, t) {
t = Object.assign({}, t, Hf.DriverUtils.buildDriverOptions(t));
const n = Object.assign({}, {
host: t.host,
user: t.username,
password: t.password,
database: t.database,
port: t.port,
ssl: t.ssl,
application_name: e.applicationName,
max: e.poolSize
}, e.extra || {});
const a = new this.postgres.Pool(n);
const {logger: r} = this.connection;
const i = e.poolErrorHandler || (e => r.log("warn", `Postgres pool raised an error. ${e}`));
a.on("error", i);
return new Promise((e, t) => {
a.connect((n, r, i) => {
if (n) return t(n);
i();
e(a);
});
});
}
async closePool(e) {
await Promise.all(this.connectedQueryRunners.map(e => e.release()));
return new Promise((t, n) => {
e.end(e => e ? n(e) : t());
});
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/'/g, "''").replace(/\u0000/g, "");
return e;
}
buildEnumName(e) {
const {schema: t, tableName: n} = this.parseTableName(e.entityMetadata);
let a = e.enumName ? e.enumName : `${n}_${e.databaseName.toLowerCase()}_enum`;
if (t) a = `${t}.${a}`;
return a.split(".").map(e => `"${e}"`).join(".");
}
}
qm.CockroachDriver = CockroachDriver;
var Yf = {};
var zf = {};
Object.defineProperty(zf, "__esModule", {
value: true
});
zf.MongoQueryRunner = void 0;
const Jf = hf;
const Xf = P;
class MongoQueryRunner {
constructor(e, t) {
this.isReleased = false;
this.isTransactionActive = false;
this.data = {};
this.connection = e;
this.databaseConnection = t;
this.broadcaster = new Jf.Broadcaster(this);
}
async beforeMigration() {}
async afterMigration() {}
cursor(e, t) {
return this.getCollection(e).find(t || {});
}
aggregate(e, t, n) {
return this.getCollection(e).aggregate(t, n || {});
}
async bulkWrite(e, t, n) {
return await this.getCollection(e).bulkWrite(t, n || {});
}
async count(e, t, n) {
return this.getCollection(e).count(t || {}, n || {});
}
async countDocuments(e, t, n) {
return this.getCollection(e).countDocuments(t || {}, n || {});
}
async createCollectionIndex(e, t, n) {
return this.getCollection(e).createIndex(t, n || {});
}
async createCollectionIndexes(e, t) {
return this.getCollection(e).createIndexes(t);
}
async deleteMany(e, t, n) {
return this.getCollection(e).deleteMany(t, n || {});
}
async deleteOne(e, t, n) {
return this.getCollection(e).deleteOne(t, n || {});
}
async distinct(e, t, n, a) {
return this.getCollection(e).distinct(t, n, a || {});
}
async dropCollectionIndex(e, t, n) {
return this.getCollection(e).dropIndex(t, n || {});
}
async dropCollectionIndexes(e) {
return this.getCollection(e).dropIndexes();
}
async findOneAndDelete(e, t, n) {
return this.getCollection(e).findOneAndDelete(t, n || {});
}
async findOneAndReplace(e, t, n, a) {
return this.getCollection(e).findOneAndReplace(t, n, a || {});
}
async findOneAndUpdate(e, t, n, a) {
return this.getCollection(e).findOneAndUpdate(t, n, a || {});
}
async collectionIndexes(e) {
return this.getCollection(e).indexes();
}
async collectionIndexExists(e, t) {
return this.getCollection(e).indexExists(t);
}
async collectionIndexInformation(e, t) {
return this.getCollection(e).indexInformation(t || {});
}
initializeOrderedBulkOp(e, t) {
return this.getCollection(e).initializeOrderedBulkOp(t);
}
initializeUnorderedBulkOp(e, t) {
return this.getCollection(e).initializeUnorderedBulkOp(t);
}
async insertMany(e, t, n) {
return this.getCollection(e).insertMany(t, n || {});
}
async insertOne(e, t, n) {
return this.getCollection(e).insertOne(t, n || {});
}
async isCapped(e) {
return this.getCollection(e).isCapped();
}
listCollectionIndexes(e, t) {
return this.getCollection(e).listIndexes(t);
}
async rename(e, t, n) {
return this.getCollection(e).rename(t, n || {});
}
async replaceOne(e, t, n, a) {
return this.getCollection(e).replaceOne(t, n, a || {});
}
async stats(e, t) {
return this.getCollection(e).stats(t || {});
}
watch(e, t, n) {
return this.getCollection(e).watch(t, n);
}
async updateMany(e, t, n, a) {
return this.getCollection(e).updateMany(t, n, a || {});
}
async updateOne(e, t, n, a) {
return await this.getCollection(e).updateOne(t, n, a || {});
}
async clearDatabase() {
await this.databaseConnection.db(this.connection.driver.database).dropDatabase();
}
async connect() {}
async release() {}
async startTransaction() {}
async commitTransaction() {}
async rollbackTransaction() {}
query(e, t) {
throw new Xf.TypeORMError(`Executing SQL query is not supported by MongoDB driver.`);
}
async sql(e, ...t) {
throw new Xf.TypeORMError(`Executing SQL query is not supported by MongoDB driver.`);
}
stream(e, t, n, a) {
throw new Xf.TypeORMError(`Stream is not supported by MongoDB driver. Use watch instead.`);
}
async getDatabases() {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async getSchemas(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async getTable(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async getTables(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async getView(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async getViews(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
getReplicationMode() {
return "master";
}
async hasDatabase(e) {
throw new Xf.TypeORMError(`Check database queries are not supported by MongoDB driver.`);
}
async getCurrentDatabase() {
throw new Xf.TypeORMError(`Check database queries are not supported by MongoDB driver.`);
}
async hasSchema(e) {
throw new Xf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
}
async getCurrentSchema() {
throw new Xf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
}
async hasTable(e) {
throw new Xf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
}
async hasColumn(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createDatabase(e) {
throw new Xf.TypeORMError(`Database create queries are not supported by MongoDB driver.`);
}
async dropDatabase(e, t) {
throw new Xf.TypeORMError(`Database drop queries are not supported by MongoDB driver.`);
}
async createSchema(e, t) {
throw new Xf.TypeORMError(`Schema create queries are not supported by MongoDB driver.`);
}
async dropSchema(e, t) {
throw new Xf.TypeORMError(`Schema drop queries are not supported by MongoDB driver.`);
}
async createTable(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropTable(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createView(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropView(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async renameTable(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async addColumn(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async addColumns(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async renameColumn(e, t, n) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async changeColumn(e, t, n) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async changeColumns(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropColumn(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropColumns(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createPrimaryKey(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async updatePrimaryKeys(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropPrimaryKey(e) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createUniqueConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createUniqueConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropUniqueConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropUniqueConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createCheckConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createCheckConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropCheckConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropCheckConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createExclusionConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createExclusionConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropExclusionConstraint(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropExclusionConstraints(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createForeignKey(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createForeignKeys(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropForeignKey(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropForeignKeys(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createIndex(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async createIndices(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropIndex(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async dropIndices(e, t) {
throw new Xf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
}
async clearTable(e) {
await this.databaseConnection.db(this.connection.driver.database).dropCollection(e);
}
enableSqlMemory() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
disableSqlMemory() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
clearSqlMemory() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
getMemorySql() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
async executeMemoryUpSql() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
async executeMemoryDownSql() {
throw new Xf.TypeORMError(`This operation is not supported by MongoDB driver.`);
}
getCollection(e) {
return this.databaseConnection.db(this.connection.driver.database).collection(e);
}
changeTableComment(e, t) {
throw new Xf.TypeORMError(`mongodb driver does not support change table comment.`);
}
}
zf.MongoQueryRunner = MongoQueryRunner;
var Zf = {};
Object.defineProperty(Zf, "__esModule", {
value: true
});
Zf.MongoSchemaBuilder = void 0;
const ey = tf;
class MongoSchemaBuilder {
constructor(e) {
this.connection = e;
}
async build() {
const e = this.connection.createQueryRunner();
const t = [];
this.connection.entityMetadatas.forEach(n => {
n.indices.forEach(a => {
const r = Object.assign({}, {
name: a.name,
unique: a.isUnique,
sparse: a.isSparse,
background: a.isBackground
}, a.expireAfterSeconds === undefined ? {} : {
expireAfterSeconds: a.expireAfterSeconds
});
t.push(e.createCollectionIndex(n.tableName, a.columnNamesWithOrderingMap, r));
});
n.uniques.forEach(a => {
const r = {
name: a.name,
unique: true
};
t.push(e.createCollectionIndex(n.tableName, a.columnNamesWithOrderingMap, r));
});
});
await Promise.all(t);
}
log() {
return Promise.resolve(new ey.SqlInMemory);
}
}
Zf.MongoSchemaBuilder = MongoSchemaBuilder;
Object.defineProperty(Yf, "__esModule", {
value: true
});
Yf.MongoDriver = void 0;
const ty = Y();
const ny = Tt();
const ay = zf;
const ry = Uh;
const iy = Zf;
const sy = I;
const oy = _s;
const cy = jn;
const ly = P;
const uy = Te;
class MongoDriver {
constructor(e) {
this.connection = e;
this.isReplicated = false;
this.treeSupport = false;
this.transactionSupport = "none";
this.supportedDataTypes = [];
this.spatialTypes = [];
this.withLengthColumnTypes = [];
this.withPrecisionColumnTypes = [];
this.withScaleColumnTypes = [];
this.mappedDataTypes = {
createDate: "int",
createDateDefault: "",
updateDate: "int",
updateDateDefault: "",
deleteDate: "int",
deleteDateNullable: true,
version: "int",
treeLevel: "int",
migrationId: "int",
migrationName: "int",
migrationTimestamp: "int",
cacheId: "int",
cacheIdentifier: "int",
cacheTime: "int",
cacheDuration: "int",
cacheQuery: "int",
cacheResult: "int",
metadataType: "int",
metadataDatabase: "int",
metadataSchema: "int",
metadataTable: "int",
metadataName: "int",
metadataValue: "int"
};
this.cteCapabilities = {
enabled: false
};
this.validOptionNames = [ "appName", "authMechanism", "authSource", "autoEncryption", "checkServerIdentity", "compressors", "connectTimeoutMS", "directConnection", "family", "forceServerObjectId", "ignoreUndefined", "keepAlive", "keepAliveInitialDelay", "localThresholdMS", "maxStalenessSeconds", "minPoolSize", "monitorCommands", "noDelay", "pkFactory", "promoteBuffers", "promoteLongs", "promoteValues", "raw", "readConcern", "readPreference", "readPreferenceTags", "replicaSet", "retryWrites", "serializeFunctions", "socketTimeoutMS", "ssl", "sslCA", "sslCRL", "sslCert", "sslKey", "sslPass", "sslValidate", "tls", "tlsAllowInvalidCertificates", "tlsCAFile", "tlsCertificateKeyFile", "tlsCertificateKeyFilePassword", "w", "writeConcern", "wtimeoutMS", "appname", "fsync", "j", "useNewUrlParser", "useUnifiedTopology", "wtimeout" ];
this.options = e.options;
this.validateOptions(e.options);
this.loadDependencies();
this.database = cy.DriverUtils.buildMongoDBDriverOptions(this.options).database;
}
async connect() {
const e = cy.DriverUtils.buildMongoDBDriverOptions(this.options);
const t = await this.mongodb.MongoClient.connect(this.buildConnectionUrl(e), this.buildConnectionOptions(e));
this.queryRunner = new ay.MongoQueryRunner(this.connection, t);
sy.ObjectUtils.assign(this.queryRunner, {
manager: this.connection.manager
});
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
if (!this.queryRunner) throw new ty.ConnectionIsNotSetError("mongodb");
this.queryRunner.databaseConnection.close();
this.queryRunner = undefined;
}
createSchemaBuilder() {
return new iy.MongoSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return this.queryRunner;
}
escapeQueryWithParameters(e, t, n) {
throw new ly.TypeORMError(`This operation is not supported by Mongodb driver.`);
}
escape(e) {
return e;
}
buildTableName(e, t, n) {
return e;
}
parseTableName(e) {
if (uy.InstanceChecker.isEntityMetadata(e)) {
return {
tableName: e.tableName
};
}
if (uy.InstanceChecker.isTable(e) || uy.InstanceChecker.isView(e)) {
return {
tableName: e.name
};
}
if (uy.InstanceChecker.isTableForeignKey(e)) {
return {
tableName: e.referencedTableName
};
}
return {
tableName: e
};
}
preparePersistentValue(e, t) {
if (t.transformer) e = oy.ApplyValueTransformers.transformTo(t.transformer, e);
return e;
}
prepareHydratedValue(e, t) {
if (t.transformer) e = oy.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
normalizeDefault(e) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
normalizeIsUnique(e) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
getColumnLength(e) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
createFullType(e) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
obtainMasterConnection() {
return Promise.resolve();
}
obtainSlaveConnection() {
return Promise.resolve();
}
createGeneratedMap(e, t) {
return e.objectIdColumn.createValueMap(t);
}
findChangedColumns(e, t) {
throw new ly.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
}
isReturningSqlSupported() {
return false;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return "";
}
validateOptions(e) {}
loadDependencies() {
try {
const e = this.options.driver || ry.PlatformTools.load("mongodb");
this.mongodb = e;
} catch (e) {
throw new ny.DriverPackageNotInstalledError("MongoDB", "mongodb");
}
}
buildConnectionUrl(e) {
const t = e.type.toLowerCase();
const n = e.username && e.password ? `${encodeURIComponent(e.username)}:${encodeURIComponent(e.password)}@` : "";
const a = t === "mongodb+srv" ? "" : `:${e.port || "27017"}`;
let r;
if (e.replicaSet) {
r = `${t}://${n}${e.hostReplicaSet || e.host + a || "127.0.0.1" + a}/${e.database || ""}`;
} else {
r = `${t}://${n}${e.host || "127.0.0.1"}${a}/${e.database || ""}`;
}
return r;
}
buildConnectionOptions(e) {
const t = {};
for (const n of this.validOptionNames) {
if (n in e) {
t[n] = e[n];
}
}
t.driverInfo = {
name: "TypeORM"
};
if ("poolSize" in e) {
t["maxPoolSize"] = e["poolSize"];
}
Object.assign(t, e.extra);
return t;
}
}
Yf.MongoDriver = MongoDriver;
var hy = {};
var dy = {};
var py = {};
Object.defineProperty(py, "__esModule", {
value: true
});
py.QueryLock = void 0;
class QueryLock {
constructor() {
this.queue = [];
}
async acquire() {
let e;
const t = new Promise(t => e = t);
const n = [ ...this.queue ];
this.queue.push(t);
if (n.length > 0) {
await Promise.all(n);
}
return () => {
e();
if (this.queue.includes(t)) {
this.queue.splice(this.queue.indexOf(t), 1);
}
};
}
}
py.QueryLock = QueryLock;
Object.defineProperty(dy, "__esModule", {
value: true
});
dy.SqlServerQueryRunner = void 0;
const my = P;
const fy = nn();
const yy = Sn();
const Ey = pe();
const Ty = Zm;
const gy = py;
const Ny = lf;
const Ay = fu;
const by = Su;
const Cy = yu;
const Ry = Nu;
const Sy = Tu;
const wy = Cu;
const My = Bm;
const Oy = hf;
const vy = sc;
const Iy = Te;
const Py = qc;
const Ly = ef;
const Dy = mf;
class SqlServerQueryRunner extends Ty.BaseQueryRunner {
constructor(e, t) {
super();
this.lock = new gy.QueryLock;
this.driver = e;
this.connection = e.connection;
this.broadcaster = new Oy.Broadcaster(this);
this.mode = t;
}
connect() {
return Promise.resolve();
}
release() {
this.isReleased = true;
return Promise.resolve();
}
async startTransaction(e) {
if (this.isReleased) throw new yy.QueryRunnerAlreadyReleasedError;
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
await new Promise(async (t, n) => {
const a = e => {
if (e) {
this.isTransactionActive = false;
return n(e);
}
t();
};
if (this.transactionDepth === 0) {
const t = await (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection());
this.databaseConnection = t.transaction();
this.connection.logger.logQuery("BEGIN TRANSACTION");
if (e) {
this.databaseConnection.begin(this.convertIsolationLevel(e), a);
this.connection.logger.logQuery("SET TRANSACTION ISOLATION LEVEL " + e);
} else {
this.databaseConnection.begin(a);
}
} else {
await this.query(`SAVE TRANSACTION typeorm_${this.transactionDepth}`);
t();
}
this.transactionDepth += 1;
});
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (this.isReleased) throw new yy.QueryRunnerAlreadyReleasedError;
if (!this.isTransactionActive) throw new Ey.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth === 1) {
return new Promise((e, t) => {
this.databaseConnection.commit(async n => {
if (n) return t(n);
this.isTransactionActive = false;
this.databaseConnection = null;
await this.broadcaster.broadcast("AfterTransactionCommit");
e();
this.connection.logger.logQuery("COMMIT");
this.transactionDepth -= 1;
});
});
}
this.transactionDepth -= 1;
}
async rollbackTransaction() {
if (this.isReleased) throw new yy.QueryRunnerAlreadyReleasedError;
if (!this.isTransactionActive) throw new Ey.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TRANSACTION typeorm_${this.transactionDepth - 1}`);
this.transactionDepth -= 1;
} else {
return new Promise((e, t) => {
this.databaseConnection.rollback(async n => {
if (n) return t(n);
this.isTransactionActive = false;
this.databaseConnection = null;
await this.broadcaster.broadcast("AfterTransactionRollback");
e();
this.connection.logger.logQuery("ROLLBACK");
this.transactionDepth -= 1;
});
});
}
}
async query(e, t, n = false) {
if (this.isReleased) throw new yy.QueryRunnerAlreadyReleasedError;
const a = await this.lock.acquire();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new vy.BroadcasterResult;
try {
const a = await (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection());
const i = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : a);
if (t && t.length) {
t.forEach((e, t) => {
const n = t.toString();
if (Iy.InstanceChecker.isMssqlParameter(e)) {
const t = this.mssqlParameterToNativeParameter(e);
if (t) {
i.input(n, t, e.value);
} else {
i.input(n, e.value);
}
} else {
i.input(n, e);
}
});
}
const s = Date.now();
const o = await new Promise((n, a) => {
i.query(e, (i, o) => {
const c = this.driver.options.maxQueryExecutionTime;
const l = Date.now();
const u = l - s;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, u, o, undefined);
if (c && u > c) {
this.driver.connection.logger.logQuerySlow(u, e, t, this);
}
if (i) {
a(new fy.QueryFailedError(e, t, i));
}
n(o);
});
});
const c = new Ny.QueryResult;
if (o?.hasOwnProperty("recordset")) {
c.records = o.recordset;
}
if (o?.hasOwnProperty("rowsAffected")) {
c.affected = o.rowsAffected[0];
}
const l = e.slice(0, e.indexOf(" "));
switch (l) {
case "DELETE":
c.raw = [ o.recordset, o.rowsAffected[0] ];
break;
default:
c.raw = o.recordset;
}
if (n) {
return c;
} else {
return c.raw;
}
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
throw n;
} finally {
await r.wait();
a();
}
}
async stream(e, t, n, a) {
if (this.isReleased) throw new yy.QueryRunnerAlreadyReleasedError;
const r = await this.lock.acquire();
this.driver.connection.logger.logQuery(e, t, this);
const i = await (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection());
const s = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : i);
if (t && t.length) {
t.forEach((e, t) => {
const n = t.toString();
if (Iy.InstanceChecker.isMssqlParameter(e)) {
s.input(n, this.mssqlParameterToNativeParameter(e), e.value);
} else {
s.input(n, e);
}
});
}
s.query(e);
const o = s.toReadableStream();
o.on("error", n => {
r();
this.driver.connection.logger.logQueryError(n, e, t, this);
});
o.on("end", () => {
r();
});
if (n) {
o.on("end", n);
}
if (a) {
o.on("error", a);
}
return o;
}
async getDatabases() {
const e = await this.query(`EXEC sp_databases`);
return e.map(e => e["DATABASE_NAME"]);
}
async getSchemas(e) {
const t = e ? `SELECT * FROM "${e}"."sys"."schema"` : `SELECT * FROM "sys"."schemas"`;
const n = await this.query(t);
return n.map(e => e["name"]);
}
async hasDatabase(e) {
const t = await this.query(`SELECT DB_ID('${e}') as "db_id"`);
const n = t[0]["db_id"];
return !!n;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT DB_NAME() AS "db_name"`);
return e[0]["db_name"];
}
async hasSchema(e) {
const t = await this.query(`SELECT SCHEMA_ID('${e}') as "schema_id"`);
const n = t[0]["schema_id"];
return !!n;
}
async getCurrentSchema() {
const e = await this.query(`SELECT SCHEMA_NAME() AS "schema_name"`);
return e[0]["schema_name"];
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
if (!t.database) {
t.database = await this.getCurrentDatabase();
}
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = `SELECT * FROM "${t.database}"."INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_NAME" = '${t.tableName}' AND "TABLE_SCHEMA" = '${t.schema}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
if (!n.database) {
n.database = await this.getCurrentDatabase();
}
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = `SELECT * FROM "${n.database}"."INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = '${n.tableName}' AND "TABLE_SCHEMA" = '${n.schema}' AND "COLUMN_NAME" = '${t}'`;
const r = await this.query(a);
return r.length ? true : false;
}
async createDatabase(e, t) {
const n = t ? `IF DB_ID('${e}') IS NULL CREATE DATABASE "${e}"` : `CREATE DATABASE "${e}"`;
const a = `DROP DATABASE "${e}"`;
await this.executeQueries(new Ly.Query(n), new Ly.Query(a));
}
async dropDatabase(e, t) {
const n = t ? `IF DB_ID('${e}') IS NOT NULL DROP DATABASE "${e}"` : `DROP DATABASE "${e}"`;
const a = `CREATE DATABASE "${e}"`;
await this.executeQueries(new Ly.Query(n), new Ly.Query(a));
}
async createSchema(e, t) {
const n = [];
const a = [];
if (e.indexOf(".") === -1) {
const r = t ? `IF SCHEMA_ID('${e}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${e}"') END` : `CREATE SCHEMA "${e}"`;
n.push(new Ly.Query(r));
a.push(new Ly.Query(`DROP SCHEMA "${e}"`));
} else {
const r = e.split(".")[0];
const i = e.split(".")[1];
const s = await this.getCurrentDatabase();
n.push(new Ly.Query(`USE "${r}"`));
a.push(new Ly.Query(`USE "${s}"`));
const o = t ? `IF SCHEMA_ID('${i}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${i}"') END` : `CREATE SCHEMA "${i}"`;
n.push(new Ly.Query(o));
a.push(new Ly.Query(`DROP SCHEMA "${i}"`));
n.push(new Ly.Query(`USE "${s}"`));
a.push(new Ly.Query(`USE "${r}"`));
}
await this.executeQueries(n, a);
}
async dropSchema(e, t) {
const n = [];
const a = [];
if (e.indexOf(".") === -1) {
const r = t ? `IF SCHEMA_ID('${e}') IS NULL BEGIN EXEC ('DROP SCHEMA "${e}"') END` : `DROP SCHEMA "${e}"`;
n.push(new Ly.Query(r));
a.push(new Ly.Query(`CREATE SCHEMA "${e}"`));
} else {
const r = e.split(".")[0];
const i = e.split(".")[1];
const s = await this.getCurrentDatabase();
n.push(new Ly.Query(`USE "${r}"`));
a.push(new Ly.Query(`USE "${s}"`));
const o = t ? `IF SCHEMA_ID('${i}') IS NULL BEGIN EXEC ('DROP SCHEMA "${i}"') END` : `DROP SCHEMA "${i}"`;
n.push(new Ly.Query(o));
a.push(new Ly.Query(`CREATE SCHEMA "${i}"`));
n.push(new Ly.Query(`USE "${s}"`));
a.push(new Ly.Query(`USE "${r}"`));
}
await this.executeQueries(n, a);
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(e, t));
});
}
const s = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of s) {
const n = this.driver.parseTableName(e);
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = this.insertTypeormMetadataSql({
database: n.database,
schema: n.schema,
table: n.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const s = this.deleteTypeormMetadataSql({
database: n.database,
schema: n.schema,
table: n.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(a);
i.push(s);
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const s = [];
const o = [];
if (a) {
i.indices.forEach(e => {
s.push(this.dropIndexSql(i, e));
o.push(this.createIndexSql(i, e));
});
}
if (n) i.foreignKeys.forEach(e => s.push(this.dropForeignKeySql(i, e)));
s.push(this.dropTableSql(i));
o.push(this.createTableSql(i, r));
const c = i.columns.filter(e => e.generatedType && e.asExpression);
for (const e of c) {
const t = this.driver.parseTableName(i);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = this.deleteTypeormMetadataSql({
database: t.database,
schema: t.schema,
table: t.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const a = this.insertTypeormMetadataSql({
database: t.database,
schema: t.schema,
table: t.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
s.push(n);
o.push(a);
}
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = Iy.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
let s = undefined;
let o = undefined;
let c = r.name;
const l = r.name.split(".");
if (l.length === 3) {
s = l[0];
c = l[2];
if (l[1] !== "") o = l[1];
} else if (l.length === 2) {
o = l[0];
c = l[1];
}
i.name = this.driver.buildTableName(t, o, s);
const u = await this.getCurrentDatabase();
if (s && s !== u) {
n.push(new Ly.Query(`USE "${s}"`));
a.push(new Ly.Query(`USE "${u}"`));
}
n.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}", "${t}"`));
a.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}", "${c}"`));
if (i.primaryColumns.length > 0 && !i.primaryColumns[0].primaryKeyConstraintName) {
const e = i.primaryColumns.map(e => e.name);
const t = this.connection.namingStrategy.primaryKeyName(r, e);
const s = this.connection.namingStrategy.primaryKeyName(i, e);
n.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${t}", "${s}"`));
a.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${s}", "${t}"`));
}
i.uniques.forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.uniqueConstraintName(i, e.columnNames);
n.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${e.name}", "${s}"`));
a.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${s}", "${e.name}"`));
e.name = s;
});
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
const s = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
n.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${e.name}", "${s}", "INDEX"`));
a.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(i)}.${s}", "${e.name}", "INDEX"`));
e.name = s;
});
i.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
const c = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
n.push(new Ly.Query(`EXEC sp_rename "${this.buildForeignKeyName(e.name, o, s)}", "${c}"`));
a.push(new Ly.Query(`EXEC sp_rename "${this.buildForeignKeyName(c, o, s)}", "${e.name}"`));
e.name = c;
});
if (s && s !== u) {
n.push(new Ly.Query(`USE "${u}"`));
a.push(new Ly.Query(`USE "${s}"`));
}
await this.executeQueries(n, a);
r.name = i.name;
this.replaceCachedTable(r, i);
}
async addColumn(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
r.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t, false, true)}`));
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${t.name}"`));
if (t.isPrimary) {
const e = a.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const s = e.map(e => `"${e.name}"`).join(", ");
r.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${s})`));
}
e.push(t);
const s = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const o = e.map(e => `"${e.name}"`).join(", ");
r.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${s}" PRIMARY KEY (${o})`));
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${s}"`));
}
const s = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (s) {
r.push(this.createIndexSql(n, s));
i.push(this.dropIndexSql(n, s));
}
if (t.isUnique) {
const e = new wy.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
columnNames: [ t.name ]
});
a.uniques.push(e);
r.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e.name}"`));
}
if (t.default !== null && t.default !== undefined) {
const e = this.connection.namingStrategy.defaultConstraintName(n, t.name);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
}
if (t.generatedType && t.asExpression) {
const e = this.driver.parseTableName(n);
if (!e.schema) {
e.schema = await this.getCurrentSchema();
}
const a = this.insertTypeormMetadataSql({
database: e.database,
schema: e.schema,
table: e.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const s = this.deleteTypeormMetadataSql({
database: e.database,
schema: e.schema,
table: e.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(a);
i.push(s);
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = Iy.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new my.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i = undefined;
if (Iy.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
await this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = Iy.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!o) throw new my.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (n.isGenerated !== o.isGenerated && n.generationStrategy !== "uuid" || n.type !== o.type || n.length !== o.length || n.asExpression !== o.asExpression || n.generatedType !== o.generatedType) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.name !== o.name) {
let e = undefined;
let t = undefined;
const c = a.name.split(".");
if (c.length === 3) {
e = c[0];
if (c[1] !== "") t = c[1];
} else if (c.length === 2) {
t = c[0];
}
const l = await this.getCurrentDatabase();
if (e && e !== l) {
i.push(new Ly.Query(`USE "${e}"`));
s.push(new Ly.Query(`USE "${l}"`));
}
i.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(a)}.${o.name}", "${n.name}"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(a)}.${n.name}", "${o.name}"`));
if (o.isPrimary === true && !o.primaryKeyConstraintName) {
const e = r.primaryColumns;
const t = e.map(e => e.name);
const a = this.connection.namingStrategy.primaryKeyName(r, t);
t.splice(t.indexOf(o.name), 1);
t.push(n.name);
const c = this.connection.namingStrategy.primaryKeyName(r, t);
i.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${a}", "${c}"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${c}", "${a}"`));
}
r.findColumnIndices(o).forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const a = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
i.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${a}", "INDEX"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${a}", "${e.name}", "INDEX"`));
e.name = a;
});
r.findColumnForeignKeys(o).forEach(a => {
const c = this.connection.namingStrategy.foreignKeyName(r, a.columnNames, this.getTablePath(a), a.referencedColumnNames);
if (a.name !== c) return;
a.columnNames.splice(a.columnNames.indexOf(o.name), 1);
a.columnNames.push(n.name);
const l = this.connection.namingStrategy.foreignKeyName(r, a.columnNames, this.getTablePath(a), a.referencedColumnNames);
i.push(new Ly.Query(`EXEC sp_rename "${this.buildForeignKeyName(a.name, t, e)}", "${l}"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.buildForeignKeyName(l, t, e)}", "${a.name}"`));
a.name = l;
});
r.findColumnChecks(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = this.connection.namingStrategy.checkConstraintName(r, e.expression);
i.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${t}"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${t}", "${e.name}"`));
e.name = t;
});
r.findColumnUniques(o).forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const a = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
i.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${a}"`));
s.push(new Ly.Query(`EXEC sp_rename "${this.getTablePath(r)}.${a}", "${e.name}"`));
e.name = a;
});
if (o.default !== null && o.default !== undefined) {
const e = this.connection.namingStrategy.defaultConstraintName(a, o.name);
const t = this.connection.namingStrategy.defaultConstraintName(a, n.name);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e}" DEFAULT ${o.default} FOR "${n.name}"`));
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" DEFAULT ${o.default} FOR "${n.name}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
if (e && e !== l) {
i.push(new Ly.Query(`USE "${l}"`));
s.push(new Ly.Query(`USE "${e}"`));
}
const u = r.columns.find(e => e.name === o.name);
r.columns[r.columns.indexOf(u)].name = n.name;
o.name = n.name;
}
if (this.isColumnChanged(o, n, false, false, false)) {
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN ${this.buildCreateColumnSql(a, n, true, false, true)}`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN ${this.buildCreateColumnSql(a, o, true, false, true)}`));
}
if (this.isEnumChanged(o, n)) {
const e = this.getEnumExpression(o);
const t = new by.TableCheck({
name: this.connection.namingStrategy.checkConstraintName(a, e, true),
expression: e
});
const r = this.getEnumExpression(n);
const c = new by.TableCheck({
name: this.connection.namingStrategy.checkConstraintName(a, r, true),
expression: r
});
i.push(this.dropCheckConstraintSql(a, t));
i.push(this.createCheckConstraintSql(a, c));
s.push(this.dropCheckConstraintSql(a, c));
s.push(this.createCheckConstraintSql(a, t));
}
if (n.isPrimary !== o.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
}
if (n.isPrimary === true) {
e.push(n);
const t = r.columns.find(e => e.name === n.name);
t.isPrimary = true;
const o = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${o}"`));
} else {
const t = e.find(e => e.name === n.name);
e.splice(e.indexOf(t), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new wy.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
columnNames: [ n.name ]
});
r.uniques.push(e);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
} else {
const e = r.uniques.find(e => e.columnNames.length === 1 && !!e.columnNames.find(e => e === n.name));
r.uniques.splice(r.uniques.indexOf(e), 1);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
}
}
if (n.default !== o.default) {
if (o.default !== null && o.default !== undefined) {
const e = this.connection.namingStrategy.defaultConstraintName(a, o.name);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e}" DEFAULT ${o.default} FOR "${o.name}"`));
}
if (n.default !== null && n.default !== undefined) {
const e = this.connection.namingStrategy.defaultConstraintName(a, n.name);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e}" DEFAULT ${n.default} FOR "${n.name}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Iy.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new my.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = a.primaryKeyConstraintName ? a.primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
const n = r.findColumnByName(a.name);
n.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns[0].primaryKeyConstraintName ? r.primaryColumns[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
}
const c = r.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (c) {
r.checks.splice(r.checks.indexOf(c), 1);
i.push(this.dropCheckConstraintSql(n, c));
s.push(this.createCheckConstraintSql(n, c));
}
const l = r.uniques.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (l) {
r.uniques.splice(r.uniques.indexOf(l), 1);
i.push(this.dropUniqueConstraintSql(n, l));
s.push(this.createUniqueConstraintSql(n, l));
}
if (a.default !== null && a.default !== undefined) {
const e = this.connection.namingStrategy.defaultConstraintName(n, a.name);
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" DEFAULT ${a.default} FOR "${a.name}"`));
}
if (a.generatedType && a.asExpression) {
const e = this.driver.parseTableName(n);
if (!e.schema) {
e.schema = await this.getCurrentSchema();
}
const t = this.deleteTypeormMetadataSql({
database: e.database,
schema: e.schema,
table: e.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const r = this.insertTypeormMetadataSql({
database: e.database,
schema: e.schema,
table: e.tableName,
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(t);
s.push(r);
}
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, a, false, false)}`));
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t, n) {
const a = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = a.clone();
const i = this.createPrimaryKeySql(a, t, n);
r.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
const s = this.dropPrimaryKeySql(r);
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async updatePrimaryKeys(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = t.map(e => e.name);
const i = [];
const s = [];
const o = a.primaryColumns;
if (o.length > 0) {
const e = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, o.map(e => e.name));
const t = o.map(e => `"${e.name}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
}
a.columns.filter(e => r.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const c = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, r);
const l = r.map(e => `"${e}"`).join(", ");
i.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
s.push(new Ly.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
await this.executeQueries(i, s);
this.replaceCachedTable(n, a);
}
async dropPrimaryKey(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.dropPrimaryKeySql(n);
const r = this.createPrimaryKeySql(n, n.primaryColumns.map(e => e.name), t);
await this.executeQueries(a, r);
n.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.uniqueConstraintName(n, t.columnNames);
const a = this.createUniqueConstraintSql(n, t);
const r = this.dropUniqueConstraintSql(n, t);
await this.executeQueries(a, r);
n.addUniqueConstraint(t);
}
async createUniqueConstraints(e, t) {
const n = t.map(t => this.createUniqueConstraint(e, t));
await Promise.all(n);
}
async dropUniqueConstraint(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Iy.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
if (!a) throw new my.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
const r = this.dropUniqueConstraintSql(n, a);
const i = this.createUniqueConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeUniqueConstraint(a);
}
async dropUniqueConstraints(e, t) {
const n = t.map(t => this.dropUniqueConstraint(e, t));
await Promise.all(n);
}
async createCheckConstraint(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Iy.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new my.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
throw new my.TypeORMError(`SqlServer does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new my.TypeORMError(`SqlServer does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new my.TypeORMError(`SqlServer does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new my.TypeORMError(`SqlServer does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.connection.hasMetadata(n.name) ? this.connection.getMetadata(n.name) : undefined;
if (a && a.treeParentRelation && a.treeParentRelation.isTreeParent && a.foreignKeys.find(e => e.onDelete !== "NO ACTION")) throw new my.TypeORMError("SqlServer does not support options in TreeParent.");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const r = this.createForeignKeySql(n, t);
const i = this.dropForeignKeySql(n, t);
await this.executeQueries(r, i);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
const n = t.map(t => this.createForeignKey(e, t));
await Promise.all(n);
}
async dropForeignKey(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Iy.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new my.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
const n = t.map(t => this.dropForeignKey(e, t));
await Promise.all(n);
}
async createIndex(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = Iy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Iy.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new my.TypeORMError(`Supplied index was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase(e) {
if (e) {
const t = await this.hasDatabase(e);
if (!t) return Promise.resolve();
}
const t = this.isTransactionActive;
if (!t) await this.startTransaction();
try {
const n = e ? `SELECT * FROM "${e}"."INFORMATION_SCHEMA"."VIEWS"` : `SELECT * FROM "INFORMATION_SCHEMA"."VIEWS"`;
const a = await this.query(n);
await Promise.all(a.map(e => {
const t = `DROP VIEW "${e["TABLE_SCHEMA"]}"."${e["TABLE_NAME"]}"`;
return this.query(t);
}));
const r = e ? `SELECT * FROM "${e}"."INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" = 'BASE TABLE'` : `SELECT * FROM "INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" = 'BASE TABLE'`;
const i = await this.query(r);
if (i.length > 0) {
const e = i.reduce((e, {TABLE_CATALOG: t, TABLE_SCHEMA: n, TABLE_NAME: a}) => {
e[t] = e[t] || [];
e[t].push({
TABLE_SCHEMA: n,
TABLE_NAME: a
});
return e;
}, {});
const t = Object.entries(e).map(([e, t]) => {
const n = t.map(({TABLE_SCHEMA: t, TABLE_NAME: n}) => `("fk"."referenced_object_id" = OBJECT_ID('"${e}"."${t}"."${n}"'))`).join(" OR ");
return `\n SELECT DISTINCT '${e}' AS "TABLE_CATALOG",\n OBJECT_SCHEMA_NAME("fk"."parent_object_id",\n DB_ID('${e}')) AS "TABLE_SCHEMA",\n OBJECT_NAME("fk"."parent_object_id", DB_ID('${e}')) AS "TABLE_NAME",\n "fk"."name" AS "CONSTRAINT_NAME"\n FROM "${e}"."sys"."foreign_keys" AS "fk"\n WHERE (${n})\n `;
}).join(" UNION ALL ");
const n = await this.query(t);
await Promise.all(n.map(async ({TABLE_CATALOG: e, TABLE_SCHEMA: t, TABLE_NAME: n, CONSTRAINT_NAME: a}) => {
await this.query(`ALTER TABLE "${e}"."${t}"."${n}" ` + `NOCHECK CONSTRAINT "${a}"`);
await this.query(`ALTER TABLE "${e}"."${t}"."${n}" ` + `DROP CONSTRAINT "${a}" -- FROM CLEAR`);
}));
await Promise.all(i.map(e => {
if (e["TABLE_NAME"].startsWith("#")) {
return;
}
const t = `DROP TABLE "${e["TABLE_CATALOG"]}"."${e["TABLE_SCHEMA"]}"."${e["TABLE_NAME"]}"`;
return this.query(t);
}));
}
if (!t) await this.commitTransaction();
} catch (e) {
try {
if (!t) await this.rollbackTransaction();
} catch (e) {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentSchema();
const a = await this.getCurrentDatabase();
const r = e.map(e => this.driver.parseTableName(e).database).filter(e => e);
if (this.driver.database && !r.find(e => e === this.driver.database)) r.push(this.driver.database);
const i = e.map(e => {
let {schema: t, tableName: a} = this.driver.parseTableName(e);
if (!t) {
t = n;
}
return `("T"."SCHEMA" = '${t}' AND "T"."NAME" = '${a}')`;
}).join(" OR ");
const s = r.map(e => `SELECT "T".*, "V"."CHECK_OPTION" FROM ${this.escapePath(this.getTypeormMetadataTableName())} "t" ` + `INNER JOIN "${e}"."INFORMATION_SCHEMA"."VIEWS" "V" ON "V"."TABLE_SCHEMA" = "T"."SCHEMA" AND "v"."TABLE_NAME" = "T"."NAME" WHERE "T"."TYPE" = '${Dy.MetadataTableType.VIEW}' ${i ? `AND (${i})` : ""}`).join(" UNION ALL ");
const o = await this.query(s);
return o.map(e => {
const t = new My.View;
const r = e["TABLE_CATALOG"] === a ? undefined : e["TABLE_CATALOG"];
const i = e["schema"] === n && !this.driver.options.schema ? undefined : e["schema"];
t.database = e["TABLE_CATALOG"];
t.schema = e["schema"];
t.name = this.driver.buildTableName(e["name"], i, r);
t.expression = e["value"];
return t;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = await this.getCurrentSchema();
const n = await this.getCurrentDatabase();
const a = [];
if (!e) {
const e = `SELECT DISTINCT "name" ` + `FROM "master"."dbo"."sysdatabases" ` + `WHERE "name" NOT IN ('master', 'model', 'msdb')`;
const t = await this.query(e);
const n = t.map(({name: e}) => `\n SELECT DISTINCT\n "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME"\n FROM "${e}"."INFORMATION_SCHEMA"."TABLES"\n WHERE\n "TABLE_TYPE" = 'BASE TABLE'\n AND\n "TABLE_CATALOG" = '${e}'\n AND\n ISNULL(Objectproperty(Object_id("TABLE_CATALOG" + '.' + "TABLE_SCHEMA" + '.' + "TABLE_NAME"), 'IsMSShipped'), 0) = 0\n `).join(" UNION ALL ");
a.push(...await this.query(n));
} else {
const r = e.map(e => this.driver.parseTableName(e)).reduce((e, {database: a, ...r}) => {
a = a || n;
e[a] = e[a] || [];
e[a].push({
schema: r.schema || t,
tableName: r.tableName
});
return e;
}, {});
const i = Object.entries(r).map(([e, t]) => {
const n = t.map(({schema: e, tableName: t}) => `("TABLE_SCHEMA" = '${e}' AND "TABLE_NAME" = '${t}')`).join(" OR ");
return `\n SELECT DISTINCT\n "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME"\n FROM "${e}"."INFORMATION_SCHEMA"."TABLES"\n WHERE\n "TABLE_TYPE" = 'BASE TABLE' AND\n "TABLE_CATALOG" = '${e}' AND\n ${n}\n `;
}).join(" UNION ALL ");
a.push(...await this.query(i));
}
if (a.length === 0) {
return [];
}
const r = a.reduce((e, {TABLE_CATALOG: t, ...n}) => {
e[t] = e[t] || [];
e[t].push(n);
return e;
}, {});
const i = Object.entries(r).map(([e, t]) => {
const n = t.map(({TABLE_SCHEMA: e, TABLE_NAME: t}) => `("TABLE_SCHEMA" = '${e}' AND "TABLE_NAME" = '${t}')`).join("OR");
return `SELECT "COLUMNS".*, "cc"."is_persisted", "cc"."definition" ` + `FROM "${e}"."INFORMATION_SCHEMA"."COLUMNS" ` + `LEFT JOIN "sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` + `WHERE (${n})`;
}).join(" UNION ALL ");
const s = Object.entries(r).map(([e, t]) => {
const n = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `("columnUsages"."TABLE_SCHEMA" = '${t}' AND "columnUsages"."TABLE_NAME" = '${e}')`).join(" OR ");
return `SELECT "columnUsages".*, "tableConstraints"."CONSTRAINT_TYPE", "chk"."definition" ` + `FROM "${e}"."INFORMATION_SCHEMA"."CONSTRAINT_COLUMN_USAGE" "columnUsages" ` + `INNER JOIN "${e}"."INFORMATION_SCHEMA"."TABLE_CONSTRAINTS" "tableConstraints" ` + `ON ` + `"tableConstraints"."CONSTRAINT_NAME" = "columnUsages"."CONSTRAINT_NAME" AND ` + `"tableConstraints"."TABLE_SCHEMA" = "columnUsages"."TABLE_SCHEMA" AND ` + `"tableConstraints"."TABLE_NAME" = "columnUsages"."TABLE_NAME" ` + `LEFT JOIN "${e}"."sys"."check_constraints" "chk" ` + `ON ` + `"chk"."object_id" = OBJECT_ID("columnUsages"."TABLE_CATALOG" + '.' + "columnUsages"."TABLE_SCHEMA" + '.' + "columnUsages"."CONSTRAINT_NAME") ` + `WHERE ` + `(${n}) AND ` + `"tableConstraints"."CONSTRAINT_TYPE" IN ('PRIMARY KEY', 'UNIQUE', 'CHECK')`;
}).join(" UNION ALL ");
const o = Object.entries(r).map(([e, t]) => {
const n = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `("s1"."name" = '${t}' AND "t1"."name" = '${e}')`).join(" OR ");
return `SELECT "fk"."name" AS "FK_NAME", '${e}' AS "TABLE_CATALOG", "s1"."name" AS "TABLE_SCHEMA", "t1"."name" AS "TABLE_NAME", ` + `"col1"."name" AS "COLUMN_NAME", "s2"."name" AS "REF_SCHEMA", "t2"."name" AS "REF_TABLE", "col2"."name" AS "REF_COLUMN", ` + `"fk"."delete_referential_action_desc" AS "ON_DELETE", "fk"."update_referential_action_desc" AS "ON_UPDATE" ` + `FROM "${e}"."sys"."foreign_keys" "fk" ` + `INNER JOIN "${e}"."sys"."foreign_key_columns" "fkc" ON "fkc"."constraint_object_id" = "fk"."object_id" ` + `INNER JOIN "${e}"."sys"."tables" "t1" ON "t1"."object_id" = "fk"."parent_object_id" ` + `INNER JOIN "${e}"."sys"."schemas" "s1" ON "s1"."schema_id" = "t1"."schema_id" ` + `INNER JOIN "${e}"."sys"."tables" "t2" ON "t2"."object_id" = "fk"."referenced_object_id" ` + `INNER JOIN "${e}"."sys"."schemas" "s2" ON "s2"."schema_id" = "t2"."schema_id" ` + `INNER JOIN "${e}"."sys"."columns" "col1" ON "col1"."column_id" = "fkc"."parent_column_id" AND "col1"."object_id" = "fk"."parent_object_id" ` + `INNER JOIN "${e}"."sys"."columns" "col2" ON "col2"."column_id" = "fkc"."referenced_column_id" AND "col2"."object_id" = "fk"."referenced_object_id" ` + `WHERE (${n})`;
}).join(" UNION ALL ");
const c = Object.entries(r).map(([e, t]) => {
const n = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `("TABLE_SCHEMA" = '${t}' AND "TABLE_NAME" = '${e}')`).join(" OR ");
return `SELECT "TABLE_CATALOG", "TABLE_SCHEMA", "COLUMN_NAME", "TABLE_NAME" ` + `FROM "${e}"."INFORMATION_SCHEMA"."COLUMNS" ` + `WHERE ` + `EXISTS(SELECT 1 FROM "${e}"."sys"."columns" "S" WHERE OBJECT_ID("TABLE_CATALOG" + '.' + "TABLE_SCHEMA" + '.' + "TABLE_NAME") = "S"."OBJECT_ID" AND "COLUMN_NAME" = "S"."NAME" AND "S"."is_identity" = 1) AND ` + `(${n})`;
}).join(" UNION ALL ");
const l = `SELECT "NAME", "COLLATION_NAME" FROM "sys"."databases"`;
const u = Object.entries(r).map(([e, t]) => {
const n = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `("s"."name" = '${t}' AND "t"."name" = '${e}')`).join(" OR ");
return `SELECT '${e}' AS "TABLE_CATALOG", "s"."name" AS "TABLE_SCHEMA", "t"."name" AS "TABLE_NAME", ` + `"ind"."name" AS "INDEX_NAME", "col"."name" AS "COLUMN_NAME", "ind"."is_unique" AS "IS_UNIQUE", "ind"."filter_definition" as "CONDITION" ` + `FROM "${e}"."sys"."indexes" "ind" ` + `INNER JOIN "${e}"."sys"."index_columns" "ic" ON "ic"."object_id" = "ind"."object_id" AND "ic"."index_id" = "ind"."index_id" ` + `INNER JOIN "${e}"."sys"."columns" "col" ON "col"."object_id" = "ic"."object_id" AND "col"."column_id" = "ic"."column_id" ` + `INNER JOIN "${e}"."sys"."tables" "t" ON "t"."object_id" = "ind"."object_id" ` + `INNER JOIN "${e}"."sys"."schemas" "s" ON "s"."schema_id" = "t"."schema_id" ` + `WHERE ` + `"ind"."is_primary_key" = 0 AND "ind"."is_unique_constraint" = 0 AND "t"."is_ms_shipped" = 0 AND ` + `(${n})`;
}).join(" UNION ALL ");
const [h, d, p, m, f, y] = await Promise.all([ this.query(i), this.query(s), this.query(o), this.query(c), this.query(l), this.query(u) ]);
return await Promise.all(a.map(async e => {
const a = new Ay.Table;
const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
const i = e["TABLE_CATALOG"] === n ? undefined : e["TABLE_CATALOG"];
const s = r(e, "TABLE_SCHEMA");
a.database = e["TABLE_CATALOG"];
a.schema = e["TABLE_SCHEMA"];
a.name = this.driver.buildTableName(e["TABLE_NAME"], s, i);
const o = f.find(t => t["NAME"] === e["TABLE_CATALOG"]);
a.columns = await Promise.all(h.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_CATALOG"] === e["TABLE_CATALOG"]).map(async t => {
const n = d.filter(e => e["TABLE_NAME"] === t["TABLE_NAME"] && e["TABLE_SCHEMA"] === t["TABLE_SCHEMA"] && e["TABLE_CATALOG"] === t["TABLE_CATALOG"] && e["COLUMN_NAME"] === t["COLUMN_NAME"]);
const r = n.filter(e => e["CONSTRAINT_TYPE"] === "UNIQUE");
const i = r.every(e => d.some(n => n["CONSTRAINT_TYPE"] === "UNIQUE" && n["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"] && n["TABLE_SCHEMA"] === t["TABLE_SCHEMA"] && n["TABLE_CATALOG"] === t["TABLE_CATALOG"] && n["COLUMN_NAME"] !== t["COLUMN_NAME"]));
const s = !!m.find(e => e["TABLE_NAME"] === t["TABLE_NAME"] && e["TABLE_SCHEMA"] === t["TABLE_SCHEMA"] && e["TABLE_CATALOG"] === t["TABLE_CATALOG"] && e["COLUMN_NAME"] === t["COLUMN_NAME"]);
const c = new Cy.TableColumn;
c.name = t["COLUMN_NAME"];
c.type = t["DATA_TYPE"].toLowerCase();
if (this.driver.withLengthColumnTypes.indexOf(c.type) !== -1 && t["CHARACTER_MAXIMUM_LENGTH"]) {
const e = t["CHARACTER_MAXIMUM_LENGTH"].toString();
if (e === "-1") {
c.length = "MAX";
} else {
c.length = !this.isDefaultColumnLength(a, c, e) ? e : "";
}
}
if (c.type === "decimal" || c.type === "numeric") {
if (t["NUMERIC_PRECISION"] !== null && !this.isDefaultColumnPrecision(a, c, t["NUMERIC_PRECISION"])) c.precision = t["NUMERIC_PRECISION"];
if (t["NUMERIC_SCALE"] !== null && !this.isDefaultColumnScale(a, c, t["NUMERIC_SCALE"])) c.scale = t["NUMERIC_SCALE"];
}
if (c.type === "nvarchar") {
const e = n.filter(e => e["CONSTRAINT_TYPE"] === "CHECK");
if (e.length) {
for (const t of e) {
if (this.isEnumCheckConstraint(t["CONSTRAINT_NAME"])) {
c.enum = [];
const e = new RegExp("\\[" + c.name + "\\]='([^']+)'", "g");
let n;
while ((n = e.exec(t["definition"])) !== null) {
c.enum.unshift(n[1]);
}
break;
}
}
}
}
const l = n.find(e => e["CONSTRAINT_TYPE"] === "PRIMARY KEY");
if (l) {
c.isPrimary = true;
const e = d.filter(e => e["TABLE_NAME"] === t["TABLE_NAME"] && e["TABLE_SCHEMA"] === t["TABLE_SCHEMA"] && e["TABLE_CATALOG"] === t["TABLE_CATALOG"] && e["COLUMN_NAME"] !== t["COLUMN_NAME"] && e["CONSTRAINT_TYPE"] === "PRIMARY KEY");
const n = e.map(e => e["COLUMN_NAME"]);
n.push(t["COLUMN_NAME"]);
const r = this.connection.namingStrategy.primaryKeyName(a, n);
if (l["CONSTRAINT_NAME"] !== r) {
c.primaryKeyConstraintName = l["CONSTRAINT_NAME"];
}
}
c.default = t["COLUMN_DEFAULT"] !== null && t["COLUMN_DEFAULT"] !== undefined ? this.removeParenthesisFromDefault(t["COLUMN_DEFAULT"]) : undefined;
c.isNullable = t["IS_NULLABLE"] === "YES";
c.isUnique = r.length > 0 && !i;
c.isGenerated = s;
if (s) c.generationStrategy = "increment";
if (c.default === "newsequentialid()") {
c.isGenerated = true;
c.generationStrategy = "uuid";
c.default = undefined;
}
if (t["COLLATION_NAME"]) c.collation = t["COLLATION_NAME"] === o["COLLATION_NAME"] ? undefined : t["COLLATION_NAME"];
if (c.type === "datetime2" || c.type === "time" || c.type === "datetimeoffset") {
c.precision = !this.isDefaultColumnPrecision(a, c, t["DATETIME_PRECISION"]) ? t["DATETIME_PRECISION"] : undefined;
}
if (t["is_persisted"] !== null && t["is_persisted"] !== undefined && t["definition"]) {
c.generatedType = t["is_persisted"] === true ? "STORED" : "VIRTUAL";
const n = this.selectTypeormMetadataSql({
database: e["TABLE_CATALOG"],
schema: e["TABLE_SCHEMA"],
table: e["TABLE_NAME"],
type: Dy.MetadataTableType.GENERATED_COLUMN,
name: c.name
});
const a = await this.query(n.query, n.parameters);
if (a[0] && a[0].value) {
c.asExpression = a[0].value;
} else {
c.asExpression = "";
}
}
return c;
}));
const c = Py.OrmUtils.uniq(d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_CATALOG"] === e["TABLE_CATALOG"] && t["CONSTRAINT_TYPE"] === "UNIQUE"), e => e["CONSTRAINT_NAME"]);
a.uniques = c.map(e => {
const t = d.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new wy.TableUnique({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"])
});
});
const l = Py.OrmUtils.uniq(d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_CATALOG"] === e["TABLE_CATALOG"] && t["CONSTRAINT_TYPE"] === "CHECK"), e => e["CONSTRAINT_NAME"]);
a.checks = l.filter(e => !this.isEnumCheckConstraint(e["CONSTRAINT_NAME"])).map(e => {
const t = d.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new by.TableCheck({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
expression: e["definition"]
});
});
const u = Py.OrmUtils.uniq(p.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_CATALOG"] === e["TABLE_CATALOG"]), e => e["FK_NAME"]);
a.foreignKeys = u.map(e => {
const t = p.filter(t => t["FK_NAME"] === e["FK_NAME"]);
const a = e["TABLE_CATALOG"] === n ? undefined : e["TABLE_CATALOG"];
const i = r(e, "REF_SCHEMA");
const s = this.driver.buildTableName(e["REF_TABLE"], i, a);
return new Ry.TableForeignKey({
name: e["FK_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: e["TABLE_CATALOG"],
referencedSchema: e["REF_SCHEMA"],
referencedTableName: s,
referencedColumnNames: t.map(e => e["REF_COLUMN"]),
onDelete: e["ON_DELETE"].replace("_", " "),
onUpdate: e["ON_UPDATE"].replace("_", " ")
});
});
const E = Py.OrmUtils.uniq(y.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_CATALOG"] === e["TABLE_CATALOG"]), e => e["INDEX_NAME"]);
a.indices = E.map(e => {
const t = y.filter(t => t["TABLE_CATALOG"] === e["TABLE_CATALOG"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_NAME"] === e["TABLE_NAME"] && t["INDEX_NAME"] === e["INDEX_NAME"]);
return new Sy.TableIndex({
table: a,
name: e["INDEX_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
isUnique: e["IS_UNIQUE"],
where: e["CONDITION"]
});
});
return a;
}));
}
createTableSql(e, t) {
const n = e.columns.map(t => this.buildCreateColumnSql(e, t, false, true)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (!n) e.uniques.push(new wy.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ]
}));
});
if (e.uniques.length > 0) {
const t = e.uniques.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.uniqueConstraintName(e, t.columnNames);
const a = t.columnNames.map(e => `"${e}"`).join(", ");
return `CONSTRAINT "${n}" UNIQUE (${a})`;
}).join(", ");
a += `, ${t}`;
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT "${n}" CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${t.name}" FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return r;
}).join(", ");
a += `, ${t}`;
}
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const t = r[0].primaryKeyConstraintName ? r[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(e, r.map(e => e.name));
const n = r.map(e => `"${e.name}"`).join(", ");
a += `, CONSTRAINT "${t}" PRIMARY KEY (${n})`;
}
a += `)`;
return new Ly.Query(a);
}
dropTableSql(e, t) {
const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
return new Ly.Query(n);
}
createViewSql(e) {
const t = this.driver.parseTableName(e);
const n = t.schema ? `"${t.schema}"."${t.tableName}"` : `"${t.tableName}"`;
if (typeof e.expression === "string") {
return new Ly.Query(`CREATE VIEW ${n} AS ${e.expression}`);
} else {
return new Ly.Query(`CREATE VIEW ${n} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
const t = this.driver.parseTableName(e);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: Dy.MetadataTableType.VIEW,
database: t.database,
schema: t.schema,
name: t.tableName,
value: n
});
}
dropViewSql(e) {
return new Ly.Query(`DROP VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const t = this.driver.parseTableName(e);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
return this.deleteTypeormMetadataSql({
type: Dy.MetadataTableType.VIEW,
database: t.database,
schema: t.schema,
name: t.tableName
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
return new Ly.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
dropIndexSql(e, t) {
const n = Iy.InstanceChecker.isTableIndex(t) ? t.name : t;
return new Ly.Query(`DROP INDEX "${n}" ON ${this.escapePath(e)}`);
}
createPrimaryKeySql(e, t, n) {
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
const r = t.map(e => `"${e}"`).join(", ");
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
}
dropPrimaryKeySql(e) {
const t = e.primaryColumns.map(e => e.name);
const n = e.primaryColumns[0].primaryKeyConstraintName;
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
}
createUniqueConstraintSql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
}
dropUniqueConstraintSql(e, t) {
const n = Iy.InstanceChecker.isTableUnique(t) ? t.name : t;
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createCheckConstraintSql(e, t) {
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = Iy.InstanceChecker.isTableCheck(t) ? t.name : t;
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
const a = t.referencedColumnNames.map(e => `"` + e + `"`).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return new Ly.Query(r);
}
dropForeignKeySql(e, t) {
const n = Iy.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new Ly.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
escapePath(e) {
const {database: t, schema: n, tableName: a} = this.driver.parseTableName(e);
if (t && t !== this.driver.database) {
if (n && n !== this.driver.searchSchema) {
return `"${t}"."${n}"."${a}"`;
}
return `"${t}".."${a}"`;
}
if (n && n !== this.driver.searchSchema) {
return `"${n}"."${a}"`;
}
return `"${a}"`;
}
buildForeignKeyName(e, t, n) {
let a = e;
if (t && t !== this.driver.searchSchema) a = t + "." + a;
if (n && n !== this.driver.database) a = n + "." + a;
return a;
}
removeParenthesisFromDefault(e) {
if (e.substr(0, 1) !== "(") return e;
const t = e.substr(1, e.lastIndexOf(")") - 1);
return this.removeParenthesisFromDefault(t);
}
buildCreateColumnSql(e, t, n, a, r) {
let i = `"${t.name}" ${this.connection.driver.createFullType(t)}`;
if (!r && t.enum) {
const n = this.getEnumExpression(t);
const a = this.connection.namingStrategy.checkConstraintName(e, n, true);
i += ` CONSTRAINT ${a} CHECK(${n})`;
}
if (t.collation) i += " COLLATE " + t.collation;
if (t.asExpression) {
i += ` AS (${t.asExpression})`;
if (t.generatedType === "STORED") {
i += ` PERSISTED`;
if (t.isNullable !== true) i += " NOT NULL";
}
} else {
if (t.isNullable !== true) i += " NOT NULL";
}
if (t.isGenerated === true && t.generationStrategy === "increment" && !n) i += " IDENTITY(1,1)";
if (t.default !== undefined && t.default !== null && a) {
const n = this.connection.namingStrategy.defaultConstraintName(e, t.name);
i += ` CONSTRAINT "${n}" DEFAULT ${t.default}`;
}
if (t.isGenerated && t.generationStrategy === "uuid" && !t.default) {
const n = this.connection.namingStrategy.defaultConstraintName(e, t.name);
i += ` CONSTRAINT "${n}" DEFAULT NEWSEQUENTIALID()`;
}
return i;
}
getEnumExpression(e) {
if (!e.enum) {
throw new Error(`Enum is not defined in column ${e.name}`);
}
return e.name + " IN (" + e.enum.map(e => "'" + e + "'").join(",") + ")";
}
isEnumCheckConstraint(e) {
return e.indexOf("CHK_") !== -1 && e.indexOf("_ENUM") !== -1;
}
mssqlParameterToNativeParameter(e) {
switch (this.driver.normalizeType({
type: e.type
})) {
case "bit":
return this.driver.mssql.Bit;
case "bigint":
return this.driver.mssql.BigInt;
case "decimal":
return this.driver.mssql.Decimal(...e.params);
case "float":
return this.driver.mssql.Float;
case "int":
return this.driver.mssql.Int;
case "money":
return this.driver.mssql.Money;
case "numeric":
return this.driver.mssql.Numeric(...e.params);
case "smallint":
return this.driver.mssql.SmallInt;
case "smallmoney":
return this.driver.mssql.SmallMoney;
case "real":
return this.driver.mssql.Real;
case "tinyint":
return this.driver.mssql.TinyInt;
case "char":
if (this.driver.options.options?.disableAsciiToUnicodeParamConversion) {
return this.driver.mssql.Char(...e.params);
}
return this.driver.mssql.NChar(...e.params);
case "nchar":
return this.driver.mssql.NChar(...e.params);
case "text":
if (this.driver.options.options?.disableAsciiToUnicodeParamConversion) {
return this.driver.mssql.Text;
}
return this.driver.mssql.Ntext;
case "ntext":
return this.driver.mssql.Ntext;
case "varchar":
if (this.driver.options.options?.disableAsciiToUnicodeParamConversion) {
return this.driver.mssql.VarChar(...e.params);
}
return this.driver.mssql.NVarChar(...e.params);
case "nvarchar":
return this.driver.mssql.NVarChar(...e.params);
case "xml":
return this.driver.mssql.Xml;
case "time":
return this.driver.mssql.Time(...e.params);
case "date":
return this.driver.mssql.Date;
case "datetime":
return this.driver.mssql.DateTime;
case "datetime2":
return this.driver.mssql.DateTime2(...e.params);
case "datetimeoffset":
return this.driver.mssql.DateTimeOffset(...e.params);
case "smalldatetime":
return this.driver.mssql.SmallDateTime;
case "uniqueidentifier":
return this.driver.mssql.UniqueIdentifier;
case "variant":
return this.driver.mssql.Variant;
case "binary":
return this.driver.mssql.Binary;
case "varbinary":
return this.driver.mssql.VarBinary(...e.params);
case "image":
return this.driver.mssql.Image;
case "udt":
return this.driver.mssql.UDT;
case "rowversion":
return this.driver.mssql.RowVersion;
}
}
convertIsolationLevel(e) {
const t = this.driver.mssql.ISOLATION_LEVEL;
switch (e) {
case "READ UNCOMMITTED":
return t.READ_UNCOMMITTED;
case "REPEATABLE READ":
return t.REPEATABLE_READ;
case "SERIALIZABLE":
return t.SERIALIZABLE;
case "READ COMMITTED":
default:
return t.READ_COMMITTED;
}
}
changeTableComment(e, t) {
throw new my.TypeORMError(`sqlserver driver does not support change table comment.`);
}
}
dy.SqlServerQueryRunner = SqlServerQueryRunner;
Object.defineProperty(hy, "__esModule", {
value: true
});
hy.SqlServerDriver = void 0;
const _y = Y();
const $y = Tt();
const xy = jn;
const qy = dy;
const Uy = up;
const By = Uh;
const Fy = Um;
const jy = Bu;
const ky = yu;
const Qy = qc;
const Vy = _s;
const Ky = P;
const Wy = Te;
const Hy = Ds;
class SqlServerDriver {
constructor(e) {
this.slaves = [];
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "simple";
this.supportedDataTypes = [ "int", "bigint", "bit", "decimal", "money", "numeric", "smallint", "smallmoney", "tinyint", "float", "real", "date", "datetime2", "datetime", "datetimeoffset", "smalldatetime", "time", "char", "varchar", "text", "nchar", "nvarchar", "ntext", "binary", "image", "varbinary", "hierarchyid", "sql_variant", "timestamp", "uniqueidentifier", "xml", "geometry", "geography", "rowversion" ];
this.supportedUpsertTypes = [];
this.spatialTypes = [ "geometry", "geography" ];
this.withLengthColumnTypes = [ "char", "varchar", "nchar", "nvarchar", "binary", "varbinary" ];
this.withPrecisionColumnTypes = [ "decimal", "numeric", "time", "datetime2", "datetimeoffset" ];
this.withScaleColumnTypes = [ "decimal", "numeric" ];
this.mappedDataTypes = {
createDate: "datetime2",
createDateDefault: "getdate()",
updateDate: "datetime2",
updateDateDefault: "getdate()",
deleteDate: "datetime2",
deleteDateNullable: true,
version: "int",
treeLevel: "int",
migrationId: "int",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "nvarchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "nvarchar(MAX)",
cacheResult: "nvarchar(MAX)",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "nvarchar(MAX)"
};
this.parametersPrefix = "@";
this.dataTypeDefaults = {
char: {
length: 1
},
nchar: {
length: 1
},
varchar: {
length: 255
},
nvarchar: {
length: 255
},
binary: {
length: 1
},
varbinary: {
length: 1
},
decimal: {
precision: 18,
scale: 0
},
numeric: {
precision: 18,
scale: 0
},
time: {
precision: 7
},
datetime2: {
precision: 7
},
datetimeoffset: {
precision: 7
}
};
this.cteCapabilities = {
enabled: true,
writable: false
};
this.maxAliasLength = 128;
this.connection = e;
this.options = e.options;
this.isReplicated = this.options.replication ? true : false;
this.loadDependencies();
this.database = xy.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
this.schema = xy.DriverUtils.buildDriverOptions(this.options).schema;
}
async connect() {
if (this.options.replication) {
this.slaves = await Promise.all(this.options.replication.slaves.map(e => this.createPool(this.options, e)));
this.master = await this.createPool(this.options, this.options.replication.master);
} else {
this.master = await this.createPool(this.options, this.options);
}
if (!this.database || !this.searchSchema) {
const e = this.createQueryRunner("master");
if (!this.database) {
this.database = await e.getCurrentDatabase();
}
if (!this.searchSchema) {
this.searchSchema = await e.getCurrentSchema();
}
await e.release();
}
if (!this.schema) {
this.schema = this.searchSchema;
}
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
if (!this.master) return Promise.reject(new _y.ConnectionIsNotSetError("mssql"));
await this.closePool(this.master);
await Promise.all(this.slaves.map(e => this.closePool(e)));
this.master = undefined;
this.slaves = [];
}
async closePool(e) {
return new Promise((t, n) => {
e.close(e => e ? n(e) : t());
});
}
createSchemaBuilder() {
return new Fy.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new qy.SqlServerQueryRunner(this, e);
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
const r = new Map;
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
if (r.has(i)) {
return this.parametersPrefix + r.get(i);
}
const s = t[i];
if (n) {
return s.map(e => {
a.push(e);
return this.createParameter(i, a.length - 1);
}).join(", ");
}
if (typeof s === "function") {
return s();
}
a.push(s);
r.set(i, a.length - 1);
return this.createParameter(i, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return `"${e}"`;
}
buildTableName(e, t, n) {
const a = [ e ];
if (t) {
a.unshift(t);
}
if (n) {
if (!t) {
a.unshift("");
}
a.unshift(n);
}
return a.join(".");
}
parseTableName(e) {
const t = this.database;
const n = this.schema;
if (Wy.InstanceChecker.isTable(e) || Wy.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (Wy.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (Wy.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
if (a.length === 3) {
return {
database: a[0] || t,
schema: a[1] || n,
tableName: a[2]
};
} else if (a.length === 2) {
return {
database: t,
schema: a[0],
tableName: a[1]
};
} else {
return {
database: t,
schema: n,
tableName: e
};
}
}
preparePersistentValue(e, t) {
if (t.transformer) e = Vy.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return Uy.DateUtils.mixedDateToDate(e);
} else if (t.type === "time") {
return Uy.DateUtils.mixedTimeToDate(e);
} else if (t.type === "datetime" || t.type === "smalldatetime" || t.type === Date) {
return Uy.DateUtils.mixedDateToDate(e, false, false);
} else if (t.type === "datetime2" || t.type === "datetimeoffset") {
return Uy.DateUtils.mixedDateToDate(e, false, true);
} else if (t.type === "simple-array") {
return Uy.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return Uy.DateUtils.simpleJsonToString(e);
} else if (t.type === "simple-enum") {
return Uy.DateUtils.simpleEnumToString(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? Vy.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean) {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date || t.type === "datetime2" || t.type === "smalldatetime" || t.type === "datetimeoffset") {
e = Uy.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = Uy.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = Uy.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array") {
e = Uy.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = Uy.DateUtils.stringToSimpleJson(e);
} else if (t.type === "simple-enum") {
e = Uy.DateUtils.stringToSimpleEnum(e, t);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = Vy.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number || e.type === "integer") {
return "int";
} else if (e.type === String) {
return "nvarchar";
} else if (e.type === Date) {
return "datetime";
} else if (e.type === Boolean) {
return "bit";
} else if (e.type === Buffer) {
return "binary";
} else if (e.type === "uuid") {
return "uniqueidentifier";
} else if (e.type === "simple-array" || e.type === "simple-json") {
return "ntext";
} else if (e.type === "simple-enum") {
return "nvarchar";
} else if (e.type === "dec") {
return "decimal";
} else if (e.type === "double precision") {
return "float";
} else if (e.type === "rowversion") {
return "timestamp";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (typeof t === "number") {
return `${t}`;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
const e = t();
if (e.toUpperCase() === "CURRENT_TIMESTAMP") {
return "getdate()";
}
return e;
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === undefined || t === null) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
if (e.type === "varchar" || e.type === "nvarchar" || e.type === String) return "255";
return "";
}
createFullType(e) {
if (e.asExpression) return "";
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += `(${e.precision},${e.scale})`;
} else if (e.precision !== null && e.precision !== undefined) {
t += `(${e.precision})`;
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
if (!this.master) {
return Promise.reject(new Ky.TypeORMError("Driver not Connected"));
}
return Promise.resolve(this.master);
}
obtainSlaveConnection() {
if (!this.slaves.length) return this.obtainMasterConnection();
const e = Math.floor(Math.random() * this.slaves.length);
return Promise.resolve(this.slaves[e]);
}
createGeneratedMap(e, t) {
if (!t) return undefined;
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
Qy.OrmUtils.mergeDeep(n, r.createValueMap(this.prepareHydratedValue(t[a], r)));
}
return n;
}, {});
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || this.compareColumnType(n, t) || this.compareColumnLength(n, t) || n.precision !== t.precision || n.scale !== t.scale || n.isGenerated !== t.isGenerated || !n.isGenerated && this.lowerDefaultValueIfNecessary(this.normalizeDefault(t)) !== this.lowerDefaultValueIfNecessary(n.default) || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.asExpression !== t.asExpression || n.generatedType !== t.generatedType || n.isUnique !== this.normalizeIsUnique(t) || n.enum && t.enum && !Qy.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + ""));
return a;
});
}
isReturningSqlSupported() {
if (this.options.options && this.options.options.disableOutputReturning) {
return false;
}
return true;
}
isUUIDGenerationSupported() {
return true;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return this.parametersPrefix + t;
}
parametrizeValue(e, t) {
if (Wy.InstanceChecker.isMssqlParameter(t)) return t;
const n = this.normalizeType({
type: e.type
});
if (e.length) {
return new jy.MssqlParameter(t, n, e.length);
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
return new jy.MssqlParameter(t, n, e.precision, e.scale);
} else if (e.precision !== null && e.precision !== undefined) {
return new jy.MssqlParameter(t, n, e.precision);
} else if (e.scale !== null && e.scale !== undefined) {
return new jy.MssqlParameter(t, n, e.scale);
}
return new jy.MssqlParameter(t, n);
}
parametrizeValues(e, t) {
if (t instanceof Hy.FindOperator) {
if (t.type !== "raw") {
t.transformValue({
to: t => this.parametrizeValues(e, t),
from: e => e
});
}
return t;
}
return this.parametrizeValue(e, t);
}
parametrizeMap(e, t) {
if (!this.connection.hasMetadata(e)) return t;
const n = this.connection.getMetadata(e);
return Object.keys(t).reduce((e, a) => {
const r = t[a];
const i = n.findColumnWithDatabaseName(a);
if (!i) return r;
e[a] = this.parametrizeValue(i, r);
return e;
}, {});
}
buildTableVariableDeclaration(e, t) {
const n = t.map(e => `${this.escape(e.databaseName)} ${this.createFullType(new ky.TableColumn({
name: e.databaseName,
type: this.normalizeType(e),
length: e.length,
isNullable: e.isNullable,
isArray: e.isArray
}))}`);
return `DECLARE ${e} TABLE (${n.join(", ")})`;
}
loadDependencies() {
try {
const e = this.options.driver || By.PlatformTools.load("mssql");
this.mssql = e;
} catch (e) {
throw new $y.DriverPackageNotInstalledError("SQL Server", "mssql");
}
}
compareColumnType(e, t) {
if (t.asExpression) return false;
return e.type !== this.normalizeType(t);
}
compareColumnLength(e, t) {
if (t.asExpression) return false;
return e.length.toUpperCase() !== this.getColumnLength(t).toUpperCase();
}
lowerDefaultValueIfNecessary(e) {
if (!e) {
return e;
}
return e.split(`'`).map((e, t) => t % 2 === 1 ? e : e.toLowerCase()).join(`'`);
}
createPool(e, t) {
t = Object.assign({}, t, xy.DriverUtils.buildDriverOptions(t));
const n = !t.domain ? t.authentication : {
type: "ntlm",
options: {
domain: t.domain,
userName: t.username,
password: t.password
}
};
const a = Object.assign({}, {
connectionTimeout: this.options.connectionTimeout,
requestTimeout: this.options.requestTimeout,
stream: this.options.stream,
pool: this.options.pool,
options: this.options.options
}, {
server: t.host,
database: t.database,
port: t.port,
user: t.username,
password: t.password,
authentication: n
}, e.extra || {});
if (!a.options) {
a.options = {
useUTC: false
};
} else if (!a.options.useUTC) {
Object.assign(a.options, {
useUTC: false
});
}
Object.assign(a.options, {
enableArithAbort: true
});
return new Promise((t, n) => {
const r = new this.mssql.ConnectionPool(a);
const {logger: i} = this.connection;
const s = e.pool && e.pool.errorHandler || (e => i.log("warn", `MSSQL pool raised an error. ${e}`));
r.on("error", s);
const o = r.connect(e => {
if (e) return n(e);
t(o);
});
});
}
}
hy.SqlServerDriver = SqlServerDriver;
var Gy = {};
var Yy = {};
Object.defineProperty(Yy, "__esModule", {
value: true
});
Yy.OracleQueryRunner = void 0;
const zy = P;
const Jy = nn();
const Xy = Sn();
const Zy = pe();
const eE = Zm;
const tE = lf;
const nE = fu;
const aE = Su;
const rE = yu;
const iE = Nu;
const sE = Tu;
const oE = Cu;
const cE = Bm;
const lE = hf;
const uE = sc;
const hE = Te;
const dE = qc;
const pE = ef;
const mE = mf;
class OracleQueryRunner extends eE.BaseQueryRunner {
constructor(e, t) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new lE.Broadcaster(this);
this.mode = t;
}
connect() {
if (this.databaseConnection) return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise) return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(e => {
this.databaseConnection = e;
return this.databaseConnection;
});
} else {
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(e => {
this.databaseConnection = e;
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
async release() {
this.isReleased = true;
if (!this.databaseConnection) {
return;
}
await this.databaseConnection.close();
}
async startTransaction(e = "READ COMMITTED") {
if (this.isReleased) throw new Xy.QueryRunnerAlreadyReleasedError;
if (e !== "SERIALIZABLE" && e !== "READ COMMITTED") {
throw new zy.TypeORMError(`Oracle only supports SERIALIZABLE and READ COMMITTED isolation`);
}
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
await this.query("SET TRANSACTION ISOLATION LEVEL " + e);
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new Zy.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth === 1) {
await this.query("COMMIT");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new Zy.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("ROLLBACK");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new Xy.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new uE.BroadcasterResult;
const i = Date.now();
try {
const s = {
autoCommit: !this.isTransactionActive,
outFormat: this.driver.oracle.OUT_FORMAT_OBJECT
};
const o = await a.execute(e, t || {}, s);
const c = this.driver.options.maxQueryExecutionTime;
const l = Date.now();
const u = l - i;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, u, o, undefined);
if (c && u > c) this.driver.connection.logger.logQuerySlow(u, e, t, this);
const h = new tE.QueryResult;
h.raw = o.rows || o.outBinds || o.rowsAffected || o.implicitResults;
if (o?.hasOwnProperty("rows") && Array.isArray(o.rows)) {
h.records = o.rows;
}
if (o?.hasOwnProperty("outBinds") && Array.isArray(o.outBinds)) {
h.records = o.outBinds;
}
if (o?.hasOwnProperty("implicitResults") && Array.isArray(o.implicitResults)) {
h.records = o.implicitResults;
}
if (o?.hasOwnProperty("rowsAffected")) {
h.affected = o.rowsAffected;
}
if (n) {
return h;
} else {
return h.raw;
}
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
throw new Jy.QueryFailedError(e, t, n);
} finally {
await r.wait();
}
}
async stream(e, t, n, a) {
if (this.isReleased) {
throw new Xy.QueryRunnerAlreadyReleasedError;
}
const r = {
autoCommit: !this.isTransactionActive,
outFormat: this.driver.oracle.OUT_FORMAT_OBJECT
};
const i = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
try {
const s = i.queryStream(e, t, r);
if (n) {
s.on("end", n);
}
if (a) {
s.on("error", a);
}
return s;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
throw new Jy.QueryFailedError(e, t, n);
}
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
return Promise.resolve([]);
}
async hasDatabase(e) {
try {
const t = await this.query(`SELECT 1 AS "exists" FROM global_name@"${e}"`);
return t.length > 0;
} catch (e) {
return false;
}
}
async getCurrentDatabase() {
const e = await this.query(`SELECT SYS_CONTEXT('USERENV','DB_NAME') AS "db_name" FROM dual`);
return e[0]["db_name"];
}
async hasSchema(e) {
return Promise.resolve(false);
}
async getCurrentSchema() {
const e = await this.query(`SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') AS "schema_name" FROM dual`);
return e[0]["schema_name"];
}
async hasTable(e) {
const {tableName: t} = this.driver.parseTableName(e);
const n = `SELECT "TABLE_NAME" FROM "USER_TABLES" WHERE "TABLE_NAME" = '${t}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const {tableName: n} = this.driver.parseTableName(e);
const a = `SELECT "COLUMN_NAME" FROM "USER_TAB_COLS" WHERE "TABLE_NAME" = '${n}' AND "COLUMN_NAME" = '${t}'`;
const r = await this.query(a);
return r.length ? true : false;
}
async createDatabase(e, t) {
if (t) {
try {
await this.query(`CREATE DATABASE IF NOT EXISTS "${e}";`);
} catch (e) {
if (e.message.includes("ORA-01100: database already mounted")) {
return;
}
throw e;
}
} else {
await this.query(`CREATE DATABASE "${e}"`);
}
}
async dropDatabase(e, t) {
return Promise.resolve();
}
async createSchema(e, t) {
throw new zy.TypeORMError(`Schema create queries are not supported by Oracle driver.`);
}
async dropSchema(e, t) {
throw new zy.TypeORMError(`Schema drop queries are not supported by Oracle driver.`);
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(t));
});
}
const s = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of s) {
const n = this.insertTypeormMetadataSql({
table: e.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const a = this.deleteTypeormMetadataSql({
table: e.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(n);
i.push(a);
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const s = [];
const o = [];
if (a) {
i.indices.forEach(e => {
s.push(this.dropIndexSql(e));
o.push(this.createIndexSql(i, e));
});
}
if (n) i.foreignKeys.forEach(e => s.push(this.dropForeignKeySql(i, e)));
s.push(this.dropTableSql(i));
o.push(this.createTableSql(i, r));
const c = i.columns.filter(e => e.generatedType && e.asExpression);
for (const e of c) {
const t = this.deleteTypeormMetadataSql({
table: i.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const n = this.insertTypeormMetadataSql({
table: i.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
s.push(t);
o.push(n);
}
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = hE.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {database: s, tableName: o} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new pE.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
a.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME TO "${o}"`));
if (i.primaryColumns.length > 0 && !i.primaryColumns[0].primaryKeyConstraintName) {
const e = i.primaryColumns.map(e => e.name);
const t = this.connection.namingStrategy.primaryKeyName(r, e);
const s = this.connection.namingStrategy.primaryKeyName(i, e);
n.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${t}" TO "${s}"`));
a.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${t}"`));
}
i.uniques.forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.uniqueConstraintName(i, e.columnNames);
n.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
const s = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
n.push(new pE.Query(`ALTER INDEX "${e.name}" RENAME TO "${s}"`));
a.push(new pE.Query(`ALTER INDEX "${s}" RENAME TO "${e.name}"`));
e.name = s;
});
i.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
n.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new pE.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
await this.executeQueries(n, a);
r.name = i.name;
this.replaceCachedTable(r, i);
}
async addColumn(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
r.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t)}`));
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${t.name}"`));
if (t.isPrimary) {
const e = a.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const s = e.map(e => `"${e.name}"`).join(", ");
r.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${s})`));
}
e.push(t);
const s = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const o = e.map(e => `"${e.name}"`).join(", ");
r.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${s}" PRIMARY KEY (${o})`));
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${s}"`));
}
const s = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (s) {
a.indices.splice(a.indices.indexOf(s), 1);
r.push(this.createIndexSql(n, s));
i.push(this.dropIndexSql(s));
}
if (t.isUnique) {
const e = new oE.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
columnNames: [ t.name ]
});
a.uniques.push(e);
r.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e.name}"`));
}
if (t.generatedType && t.asExpression) {
const e = this.insertTypeormMetadataSql({
table: n.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const a = this.deleteTypeormMetadataSql({
table: n.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(e);
i.push(a);
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = hE.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new zy.TypeORMError(`Column "${t}" was not found in the ${this.escapePath(a)} table.`);
let i = undefined;
if (hE.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
await this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = hE.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!o) throw new zy.TypeORMError(`Column "${t}" was not found in the ${this.escapePath(a)} table.`);
if (n.isGenerated !== o.isGenerated && n.generationStrategy !== "uuid" || o.type !== n.type || o.length !== n.length || o.generatedType !== n.generatedType || o.asExpression !== n.asExpression) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.name !== o.name) {
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${o.name}" TO "${n.name}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${n.name}" TO "${o.name}"`));
if (o.isPrimary === true && !o.primaryKeyConstraintName) {
const e = r.primaryColumns;
const t = e.map(e => e.name);
const c = this.connection.namingStrategy.primaryKeyName(r, t);
t.splice(t.indexOf(o.name), 1);
t.push(n.name);
const l = this.connection.namingStrategy.primaryKeyName(r, t);
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${c}" TO "${l}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${l}" TO "${c}"`));
}
r.findColumnUniques(o).forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const c = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${c}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${c}" TO "${e.name}"`));
e.name = c;
});
r.findColumnIndices(o).forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const a = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
i.push(new pE.Query(`ALTER INDEX "${e.name}" RENAME TO "${a}"`));
s.push(new pE.Query(`ALTER INDEX "${a}" RENAME TO "${e.name}"`));
e.name = a;
});
r.findColumnForeignKeys(o).forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const c = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${c}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${c}" TO "${e.name}"`));
e.name = c;
});
const e = r.columns.find(e => e.name === o.name);
r.columns[r.columns.indexOf(e)].name = n.name;
o.name = n.name;
}
if (this.isColumnChanged(o, n, true)) {
let e = "";
let t = "";
let r = "";
let c = "";
if (n.default !== null && n.default !== undefined) {
e = `DEFAULT ${n.default}`;
if (o.default !== null && o.default !== undefined) {
t = `DEFAULT ${o.default}`;
} else {
t = "DEFAULT NULL";
}
} else if (o.default !== null && o.default !== undefined) {
e = "DEFAULT NULL";
t = `DEFAULT ${o.default}`;
}
if (n.isNullable !== o.isNullable) {
if (n.isNullable === true) {
r = "NULL";
c = "NOT NULL";
} else {
r = "NOT NULL";
c = "NULL";
}
}
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} MODIFY "${o.name}" ${this.connection.driver.createFullType(n)} ${e} ${r}`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} MODIFY "${o.name}" ${this.connection.driver.createFullType(o)} ${t} ${c}`));
}
if (n.isPrimary !== o.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
}
if (n.isPrimary === true) {
e.push(n);
const t = r.columns.find(e => e.name === n.name);
t.isPrimary = true;
const o = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${o}"`));
} else {
const t = e.find(e => e.name === n.name);
e.splice(e.indexOf(t), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new oE.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
columnNames: [ n.name ]
});
r.uniques.push(e);
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
} else {
const e = r.uniques.find(e => e.columnNames.length === 1 && !!e.columnNames.find(e => e === n.name));
r.uniques.splice(r.uniques.indexOf(e), 1);
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = hE.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new zy.TypeORMError(`Column "${t}" was not found in table ${this.escapePath(n)}`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = a.primaryKeyConstraintName ? a.primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
const n = r.findColumnByName(a.name);
n.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns[0].primaryKeyConstraintName ? r.primaryColumns[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
i.push(this.dropIndexSql(o));
s.push(this.createIndexSql(n, o));
}
const c = r.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (c) {
r.checks.splice(r.checks.indexOf(c), 1);
i.push(this.dropCheckConstraintSql(n, c));
s.push(this.createCheckConstraintSql(n, c));
}
const l = r.uniques.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (l) {
r.uniques.splice(r.uniques.indexOf(l), 1);
i.push(this.dropUniqueConstraintSql(n, l));
s.push(this.createUniqueConstraintSql(n, l));
}
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a)}`));
if (a.generatedType && a.asExpression) {
const e = this.deleteTypeormMetadataSql({
table: n.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const t = this.insertTypeormMetadataSql({
table: n.name,
type: mE.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(e);
s.push(t);
}
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t, n) {
const a = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = a.clone();
const i = this.createPrimaryKeySql(a, t, n);
r.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
const s = this.dropPrimaryKeySql(r);
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async updatePrimaryKeys(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = t.map(e => e.name);
const r = n.clone();
const i = [];
const s = [];
const o = r.primaryColumns;
if (o.length > 0) {
const e = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, o.map(e => e.name));
const t = o.map(e => `"${e.name}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
}
r.columns.filter(e => a.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const c = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, a);
const l = a.map(e => `"${e}"`).join(", ");
i.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
s.push(new pE.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
await this.executeQueries(i, s);
this.replaceCachedTable(n, r);
}
async dropPrimaryKey(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.dropPrimaryKeySql(n);
const r = this.createPrimaryKeySql(n, n.primaryColumns.map(e => e.name), t);
await this.executeQueries(a, r);
n.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.uniqueConstraintName(n, t.columnNames);
const a = this.createUniqueConstraintSql(n, t);
const r = this.dropUniqueConstraintSql(n, t);
await this.executeQueries(a, r);
n.addUniqueConstraint(t);
}
async createUniqueConstraints(e, t) {
const n = t.map(t => this.createUniqueConstraint(e, t));
await Promise.all(n);
}
async dropUniqueConstraint(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = hE.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
if (!a) throw new zy.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
const r = this.dropUniqueConstraintSql(n, a);
const i = this.createUniqueConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeUniqueConstraint(a);
}
async dropUniqueConstraints(e, t) {
const n = t.map(t => this.dropUniqueConstraint(e, t));
await Promise.all(n);
}
async createCheckConstraint(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = hE.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new zy.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
throw new zy.TypeORMError(`Oracle does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new zy.TypeORMError(`Oracle does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new zy.TypeORMError(`Oracle does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new zy.TypeORMError(`Oracle does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
const n = t.map(t => this.createForeignKey(e, t));
await Promise.all(n);
}
async dropForeignKey(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = hE.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new zy.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
const n = t.map(t => this.dropForeignKey(e, t));
await Promise.all(n);
}
async createIndex(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = hE.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new zy.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase() {
const e = this.isTransactionActive;
if (!e) await this.startTransaction();
try {
const t = `SELECT 'DROP VIEW "' || VIEW_NAME || '"' AS "query" FROM "USER_VIEWS"`;
const n = await this.query(t);
await Promise.all(n.map(e => this.query(e["query"])));
const a = `SELECT 'DROP MATERIALIZED VIEW "' || MVIEW_NAME || '"' AS "query" FROM "USER_MVIEWS"`;
const r = await this.query(a);
await Promise.all(r.map(e => this.query(e["query"])));
const i = `SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS' AS "query" FROM "USER_TABLES"`;
const s = await this.query(i);
await Promise.all(s.map(e => this.query(e["query"])));
if (!e) await this.commitTransaction();
} catch (t) {
try {
if (!e) await this.rollbackTransaction();
} catch (e) {}
throw t;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = await this.getCurrentSchema();
const r = e.map(e => this.driver.parseTableName(e)).map(({schema: e, tableName: t}) => {
if (!e) {
e = this.driver.options.schema || a;
}
return `("T"."schema" = '${e}' AND "T"."name" = '${t}')`;
}).join(" OR ");
let i = `SELECT "T".* FROM ${this.escapePath(this.getTypeormMetadataTableName())} "T" ` + `INNER JOIN "USER_OBJECTS" "O" ON "O"."OBJECT_NAME" = "T"."name" AND "O"."OBJECT_TYPE" IN ( 'MATERIALIZED VIEW', 'VIEW' ) ` + `WHERE "T"."type" IN ('${mE.MetadataTableType.MATERIALIZED_VIEW}', '${mE.MetadataTableType.VIEW}')`;
if (r.length > 0) i += ` AND ${r}`;
const s = await this.query(i);
return s.map(e => {
const t = this.driver.parseTableName(e["name"]);
const r = new cE.View;
r.database = t.database || e["database"] || n;
r.schema = t.schema || e["schema"] || a;
r.name = t.tableName;
r.expression = e["value"];
r.materialized = e["type"] === mE.MetadataTableType.MATERIALIZED_VIEW;
return r;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = [];
const n = await this.getCurrentSchema();
const a = await this.getCurrentDatabase();
if (!e) {
const e = `SELECT "TABLE_NAME", "OWNER" FROM "ALL_TABLES"`;
t.push(...await this.query(e));
} else {
const n = e.map(e => {
const t = e.split(".");
if (t.length >= 3) {
const [, e, n] = t;
return `("OWNER" = '${e}' AND "TABLE_NAME" = '${n}')`;
} else if (t.length === 2) {
const [e, n] = t;
return `("OWNER" = '${e}' AND "TABLE_NAME" = '${n}')`;
} else if (t.length === 1) {
const [e] = t;
return `("TABLE_NAME" = '${e}')`;
} else {
return `(1=0)`;
}
}).join(" OR ");
const a = `SELECT "TABLE_NAME", "OWNER" FROM "ALL_TABLES" WHERE ${n}`;
t.push(...await this.query(a));
}
if (t.length === 0) {
return [];
}
const r = t.map(({TABLE_NAME: e, OWNER: t}) => `("C"."OWNER" = '${t}' AND "C"."TABLE_NAME" = '${e}')`).join(" OR ");
const i = `SELECT * FROM "ALL_TAB_COLS" "C" WHERE (${r})`;
const s = `SELECT "C"."INDEX_NAME", "C"."OWNER", "C"."TABLE_NAME", "C"."UNIQUENESS", ` + `LISTAGG ("COL"."COLUMN_NAME", ',') WITHIN GROUP (ORDER BY "COL"."COLUMN_NAME") AS "COLUMN_NAMES" ` + `FROM "ALL_INDEXES" "C" ` + `INNER JOIN "ALL_IND_COLUMNS" "COL" ON "COL"."INDEX_OWNER" = "C"."OWNER" AND "COL"."INDEX_NAME" = "C"."INDEX_NAME" ` + `LEFT JOIN "ALL_CONSTRAINTS" "CON" ON "CON"."OWNER" = "C"."OWNER" AND "CON"."CONSTRAINT_NAME" = "C"."INDEX_NAME" ` + `WHERE (${r}) AND "CON"."CONSTRAINT_NAME" IS NULL ` + `GROUP BY "C"."INDEX_NAME", "C"."OWNER", "C"."TABLE_NAME", "C"."UNIQUENESS"`;
const o = `SELECT "C"."CONSTRAINT_NAME", "C"."OWNER", "C"."TABLE_NAME", "COL"."COLUMN_NAME", "REF_COL"."TABLE_NAME" AS "REFERENCED_TABLE_NAME", ` + `"REF_COL"."COLUMN_NAME" AS "REFERENCED_COLUMN_NAME", "C"."DELETE_RULE" AS "ON_DELETE" ` + `FROM "ALL_CONSTRAINTS" "C" ` + `INNER JOIN "ALL_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER" AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME" ` + `INNER JOIN "ALL_CONS_COLUMNS" "REF_COL" ON "REF_COL"."OWNER" = "C"."R_OWNER" AND "REF_COL"."CONSTRAINT_NAME" = "C"."R_CONSTRAINT_NAME" AND "REF_COL"."POSITION" = "COL"."POSITION" ` + `WHERE (${r}) AND "C"."CONSTRAINT_TYPE" = 'R'`;
const c = `SELECT "C"."CONSTRAINT_NAME", "C"."CONSTRAINT_TYPE", "C"."OWNER", "C"."TABLE_NAME", "COL"."COLUMN_NAME", "C"."SEARCH_CONDITION" ` + `FROM "ALL_CONSTRAINTS" "C" ` + `INNER JOIN "ALL_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER" AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME" ` + `WHERE (${r}) AND "C"."CONSTRAINT_TYPE" IN ('C', 'U', 'P') AND "C"."GENERATED" = 'USER NAME'`;
const [l, u, h, d] = await Promise.all([ this.query(i), this.query(s), this.query(o), this.query(c) ]);
return await Promise.all(t.map(async e => {
const t = new nE.Table;
const r = e["OWNER"] === n && (!this.driver.options.schema || this.driver.options.schema === n) ? undefined : e["OWNER"];
t.database = a;
t.schema = e["OWNER"];
t.name = this.driver.buildTableName(e["TABLE_NAME"], r);
t.columns = await Promise.all(l.filter(t => t["OWNER"] === e["OWNER"] && t["TABLE_NAME"] === e["TABLE_NAME"] && !(t["VIRTUAL_COLUMN"] === "YES" && t["USER_GENERATED"] === "NO")).map(async n => {
const a = d.filter(e => e["OWNER"] === n["OWNER"] && e["TABLE_NAME"] === n["TABLE_NAME"] && e["COLUMN_NAME"] === n["COLUMN_NAME"]);
const r = a.filter(e => e["CONSTRAINT_TYPE"] === "U");
const i = r.every(e => d.some(t => t["OWNER"] === n["OWNER"] && t["TABLE_NAME"] === n["TABLE_NAME"] && t["COLUMN_NAME"] !== n["COLUMN_NAME"] && t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"] && t["CONSTRAINT_TYPE"] === "U"));
const s = new rE.TableColumn;
s.name = n["COLUMN_NAME"];
s.type = n["DATA_TYPE"].toLowerCase();
if (s.type.indexOf("(") !== -1) s.type = s.type.replace(/\([0-9]*\)/, "");
if (this.driver.withLengthColumnTypes.indexOf(s.type) !== -1) {
const e = s.type === "raw" ? n["DATA_LENGTH"] : n["CHAR_COL_DECL_LENGTH"];
s.length = e && !this.isDefaultColumnLength(t, s, e) ? e.toString() : "";
}
if (s.type === "number" || s.type === "float") {
if (n["DATA_PRECISION"] !== null && !this.isDefaultColumnPrecision(t, s, n["DATA_PRECISION"])) s.precision = n["DATA_PRECISION"];
if (n["DATA_SCALE"] !== null && !this.isDefaultColumnScale(t, s, n["DATA_SCALE"])) s.scale = n["DATA_SCALE"];
} else if ((s.type === "timestamp" || s.type === "timestamp with time zone" || s.type === "timestamp with local time zone") && n["DATA_SCALE"] !== null) {
s.precision = !this.isDefaultColumnPrecision(t, s, n["DATA_SCALE"]) ? n["DATA_SCALE"] : undefined;
}
s.default = n["DATA_DEFAULT"] !== null && n["DATA_DEFAULT"] !== undefined && n["VIRTUAL_COLUMN"] === "NO" && n["DATA_DEFAULT"].trim() !== "NULL" ? s.default = n["DATA_DEFAULT"].trim() : undefined;
const o = a.find(e => e["CONSTRAINT_TYPE"] === "P");
if (o) {
s.isPrimary = true;
const e = d.filter(e => e["OWNER"] === n["OWNER"] && e["TABLE_NAME"] === n["TABLE_NAME"] && e["COLUMN_NAME"] !== n["COLUMN_NAME"] && e["CONSTRAINT_TYPE"] === "P");
const a = e.map(e => e["COLUMN_NAME"]);
a.push(n["COLUMN_NAME"]);
const r = this.connection.namingStrategy.primaryKeyName(t, a);
if (o["CONSTRAINT_NAME"] !== r) {
s.primaryKeyConstraintName = o["CONSTRAINT_NAME"];
}
}
s.isNullable = n["NULLABLE"] === "Y";
s.isUnique = r.length > 0 && !i;
s.isGenerated = n["IDENTITY_COLUMN"] === "YES";
if (s.isGenerated) {
s.generationStrategy = "increment";
s.default = undefined;
}
s.comment = "";
if (n["VIRTUAL_COLUMN"] === "YES") {
s.generatedType = "VIRTUAL";
const t = this.selectTypeormMetadataSql({
table: e["TABLE_NAME"],
type: mE.MetadataTableType.GENERATED_COLUMN,
name: s.name
});
const n = await this.query(t.query, t.parameters);
if (n[0] && n[0].value) {
s.asExpression = n[0].value;
} else {
s.asExpression = "";
}
}
return s;
}));
const i = dE.OrmUtils.uniq(d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["OWNER"] === e["OWNER"] && t["CONSTRAINT_TYPE"] === "U"), e => e["CONSTRAINT_NAME"]);
t.uniques = i.map(e => {
const t = d.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new oE.TableUnique({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"])
});
});
const s = dE.OrmUtils.uniq(d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["OWNER"] === e["OWNER"] && t["CONSTRAINT_TYPE"] === "C"), e => e["CONSTRAINT_NAME"]);
t.checks = s.map(e => {
const t = d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["OWNER"] === e["OWNER"] && t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new aE.TableCheck({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
expression: e["SEARCH_CONDITION"]
});
});
const o = dE.OrmUtils.uniq(h.filter(t => t["OWNER"] === e["OWNER"] && t["TABLE_NAME"] === e["TABLE_NAME"]), e => e["CONSTRAINT_NAME"]);
t.foreignKeys = o.map(e => {
const n = h.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["OWNER"] === e["OWNER"] && t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new iE.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: n.map(e => e["COLUMN_NAME"]),
referencedDatabase: t.database,
referencedSchema: e["OWNER"],
referencedTableName: e["REFERENCED_TABLE_NAME"],
referencedColumnNames: n.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["ON_DELETE"],
onUpdate: "NO ACTION"
});
});
const c = l.filter(t => t["OWNER"] === e["OWNER"] && t["TABLE_NAME"] === e["TABLE_NAME"] && t["VIRTUAL_COLUMN"] === "YES" && t["USER_GENERATED"] === "NO").reduce((e, t) => {
const n = l.find(e => t["DATA_DEFAULT"].includes(e["COLUMN_NAME"]));
if (!n) return e;
return {
...e,
[t["COLUMN_NAME"]]: n["COLUMN_NAME"]
};
}, {});
t.indices = u.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["OWNER"] === e["OWNER"]).map(e => {
const t = e["COLUMN_NAMES"].split(",").map(e => c[e] ?? e);
return new sE.TableIndex({
name: e["INDEX_NAME"],
columnNames: t,
isUnique: e["UNIQUENESS"] === "UNIQUE"
});
});
return t;
}));
}
createTableSql(e, t) {
const n = e.columns.map(e => this.buildCreateColumnSql(e)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (!n) e.uniques.push(new oE.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ]
}));
});
if (e.uniques.length > 0) {
const t = e.uniques.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.uniqueConstraintName(e, t.columnNames);
const a = t.columnNames.map(e => `"${e}"`).join(", ");
return `CONSTRAINT "${n}" UNIQUE (${a})`;
}).join(", ");
a += `, ${t}`;
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT "${n}" CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${t.name}" FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete && t.onDelete !== "NO ACTION") {
r += ` ON DELETE ${t.onDelete}`;
}
return r;
}).join(", ");
a += `, ${t}`;
}
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const t = r[0].primaryKeyConstraintName ? r[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(e, r.map(e => e.name));
const n = r.map(e => `"${e.name}"`).join(", ");
a += `, CONSTRAINT "${t}" PRIMARY KEY (${n})`;
}
a += `)`;
return new pE.Query(a);
}
dropTableSql(e, t) {
const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
return new pE.Query(n);
}
createViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
if (typeof e.expression === "string") {
return new pE.Query(`CREATE ${t}VIEW ${this.escapePath(e)} AS ${e.expression}`);
} else {
return new pE.Query(`CREATE ${t}VIEW ${this.escapePath(e)} AS ${e.expression(this.connection).getQuery()}`);
}
}
insertViewDefinitionSql(e) {
const t = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
const n = e.materialized ? mE.MetadataTableType.MATERIALIZED_VIEW : mE.MetadataTableType.VIEW;
const {schema: a, tableName: r} = this.driver.parseTableName(e);
return this.insertTypeormMetadataSql({
type: n,
name: r,
schema: a,
value: t
});
}
dropViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
return new pE.Query(`DROP ${t}VIEW ${this.escapePath(e)}`);
}
deleteViewDefinitionSql(e) {
const t = e.materialized ? mE.MetadataTableType.MATERIALIZED_VIEW : mE.MetadataTableType.VIEW;
return this.deleteTypeormMetadataSql({
type: t,
name: e.name
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
return new pE.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n})`);
}
dropIndexSql(e) {
const t = hE.InstanceChecker.isTableIndex(e) ? e.name : e;
return new pE.Query(`DROP INDEX "${t}"`);
}
createPrimaryKeySql(e, t, n) {
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
const r = t.map(e => `"${e}"`).join(", ");
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
}
dropPrimaryKeySql(e) {
if (!e.primaryColumns.length) throw new zy.TypeORMError(`Table ${e} has no primary keys.`);
const t = e.primaryColumns.map(e => e.name);
const n = e.primaryColumns[0].primaryKeyConstraintName;
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
}
createUniqueConstraintSql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
}
dropUniqueConstraintSql(e, t) {
const n = hE.InstanceChecker.isTableUnique(t) ? t.name : t;
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createCheckConstraintSql(e, t) {
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = hE.InstanceChecker.isTableCheck(t) ? t.name : t;
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
const a = t.referencedColumnNames.map(e => `"` + e + `"`).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete && t.onDelete !== "NO ACTION") {
r += ` ON DELETE ${t.onDelete}`;
}
return new pE.Query(r);
}
dropForeignKeySql(e, t) {
const n = hE.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new pE.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
buildCreateColumnSql(e) {
let t = `"${e.name}" ` + this.connection.driver.createFullType(e);
if (e.charset) t += " CHARACTER SET " + e.charset;
if (e.collation) t += " COLLATE " + e.collation;
if (e.asExpression) t += ` AS (${e.asExpression}) VIRTUAL`;
if (e.default !== undefined && e.default !== null) t += " DEFAULT " + e.default;
if (e.isNullable !== true && !e.isGenerated) t += " NOT NULL";
if (e.isGenerated === true && e.generationStrategy === "increment") t += " GENERATED BY DEFAULT AS IDENTITY";
return t;
}
escapePath(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
if (t && t !== this.driver.schema) {
return `"${t}"."${n}"`;
}
return `"${n}"`;
}
changeTableComment(e, t) {
throw new zy.TypeORMError(`oracle driver does not support change table comment.`);
}
}
Yy.OracleQueryRunner = OracleQueryRunner;
Object.defineProperty(Gy, "__esModule", {
value: true
});
Gy.OracleDriver = void 0;
const fE = Y();
const yE = Tt();
const EE = Yy;
const TE = up;
const gE = Uh;
const NE = Um;
const AE = jn;
const bE = qc;
const CE = _s;
const RE = P;
const SE = Te;
class OracleDriver {
constructor(e) {
this.slaves = [];
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "char", "nchar", "nvarchar2", "varchar2", "long", "raw", "long raw", "number", "numeric", "float", "dec", "decimal", "integer", "int", "smallint", "real", "double precision", "date", "timestamp", "timestamp with time zone", "timestamp with local time zone", "interval year to month", "interval day to second", "bfile", "blob", "clob", "nclob", "rowid", "urowid", "simple-json", "json" ];
this.supportedUpsertTypes = [];
this.supportedOnDeleteTypes = [ "CASCADE", "SET NULL", "NO ACTION" ];
this.supportedOnUpdateTypes = [ "NO ACTION" ];
this.spatialTypes = [];
this.withLengthColumnTypes = [ "char", "nchar", "nvarchar2", "varchar2", "varchar", "raw" ];
this.withPrecisionColumnTypes = [ "number", "float", "timestamp", "timestamp with time zone", "timestamp with local time zone" ];
this.withScaleColumnTypes = [ "number" ];
this.mappedDataTypes = {
createDate: "timestamp",
createDateDefault: "CURRENT_TIMESTAMP",
updateDate: "timestamp",
updateDateDefault: "CURRENT_TIMESTAMP",
deleteDate: "timestamp",
deleteDateNullable: true,
version: "number",
treeLevel: "number",
migrationId: "number",
migrationName: "varchar2",
migrationTimestamp: "number",
cacheId: "number",
cacheIdentifier: "varchar2",
cacheTime: "number",
cacheDuration: "number",
cacheQuery: "clob",
cacheResult: "clob",
metadataType: "varchar2",
metadataDatabase: "varchar2",
metadataSchema: "varchar2",
metadataTable: "varchar2",
metadataName: "varchar2",
metadataValue: "clob"
};
this.parametersPrefix = ":";
this.dataTypeDefaults = {
char: {
length: 1
},
nchar: {
length: 1
},
varchar: {
length: 255
},
varchar2: {
length: 255
},
nvarchar2: {
length: 255
},
raw: {
length: 2e3
},
float: {
precision: 126
},
timestamp: {
precision: 6
},
"timestamp with time zone": {
precision: 6
},
"timestamp with local time zone": {
precision: 6
}
};
this.maxAliasLength = 29;
this.cteCapabilities = {
enabled: true
};
this.dummyTableName = "DUAL";
this.connection = e;
this.options = e.options;
if (this.options.useUTC === true) {
process.env.ORA_SDTZ = "UTC";
}
this.loadDependencies();
this.database = AE.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
this.schema = AE.DriverUtils.buildDriverOptions(this.options).schema;
}
async connect() {
this.oracle.fetchAsString = [ this.oracle.DB_TYPE_CLOB ];
this.oracle.fetchAsBuffer = [ this.oracle.DB_TYPE_BLOB ];
if (this.options.replication) {
this.slaves = await Promise.all(this.options.replication.slaves.map(e => this.createPool(this.options, e)));
this.master = await this.createPool(this.options, this.options.replication.master);
} else {
this.master = await this.createPool(this.options, this.options);
}
if (!this.database || !this.schema) {
const e = this.createQueryRunner("master");
if (!this.database) {
this.database = await e.getCurrentDatabase();
}
if (!this.schema) {
this.schema = await e.getCurrentSchema();
}
await e.release();
}
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
if (!this.master) return Promise.reject(new fE.ConnectionIsNotSetError("oracle"));
await this.closePool(this.master);
await Promise.all(this.slaves.map(e => this.closePool(e)));
this.master = undefined;
this.slaves = [];
}
createSchemaBuilder() {
return new NE.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new EE.OracleQueryRunner(this, e);
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => {
if (typeof n[e] === "boolean") return n[e] ? 1 : 0;
return n[e];
});
if (!t || !Object.keys(t).length) return [ e, a ];
const r = new Map;
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
if (r.has(i)) {
return this.parametersPrefix + r.get(i);
}
const s = t[i];
if (n) {
return s.map(e => {
a.push(e);
return this.createParameter(i, a.length - 1);
}).join(", ");
}
if (typeof s === "function") {
return s();
}
if (typeof s === "boolean") {
return s ? "1" : "0";
}
a.push(s);
r.set(i, a.length);
return this.createParameter(i, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return `"${e}"`;
}
buildTableName(e, t, n) {
const a = [ e ];
if (t) {
a.unshift(t);
}
return a.join(".");
}
parseTableName(e) {
const t = this.database;
const n = this.schema;
if (SE.InstanceChecker.isTable(e) || SE.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (SE.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (SE.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
if (a.length === 3) {
return {
database: a[0] || t,
schema: a[1] || n,
tableName: a[2]
};
} else if (a.length === 2) {
return {
database: t,
schema: a[0] || n,
tableName: a[1]
};
} else {
return {
database: t,
schema: n,
tableName: e
};
}
}
preparePersistentValue(e, t) {
if (t.transformer) e = CE.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e ? 1 : 0;
} else if (t.type === "date") {
if (typeof e === "string") e = e.replace(/[^0-9-]/g, "");
return () => `TO_DATE('${TE.DateUtils.mixedDateToDateString(e)}', 'YYYY-MM-DD')`;
} else if (t.type === Date || t.type === "timestamp" || t.type === "timestamp with time zone" || t.type === "timestamp with local time zone") {
return TE.DateUtils.mixedDateToDate(e);
} else if (t.type === "simple-array") {
return TE.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return TE.DateUtils.simpleJsonToString(e);
} else if (t.type === "json") {
return TE.DateUtils.simpleJsonToString(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? CE.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean) {
e = !!e;
} else if (t.type === "date") {
e = TE.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = TE.DateUtils.mixedTimeToString(e);
} else if (t.type === Date || t.type === "timestamp" || t.type === "timestamp with time zone" || t.type === "timestamp with local time zone") {
e = TE.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "simple-array") {
e = TE.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = TE.DateUtils.stringToSimpleJson(e);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = CE.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number || e.type === Boolean || e.type === "numeric" || e.type === "dec" || e.type === "decimal" || e.type === "int" || e.type === "integer" || e.type === "smallint") {
return "number";
} else if (e.type === "real" || e.type === "double precision") {
return "float";
} else if (e.type === String || e.type === "varchar") {
return "varchar2";
} else if (e.type === Date) {
return "timestamp";
} else if (e.type === Buffer) {
return "blob";
} else if (e.type === "uuid") {
return "varchar2";
} else if (e.type === "simple-array") {
return "clob";
} else if (e.type === "simple-json") {
return "clob";
} else if (e.type === "json") {
return "json";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (typeof t === "number") {
return "" + t;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
return t();
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === null || t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
switch (e.type) {
case String:
case "varchar":
case "varchar2":
case "nvarchar2":
return "255";
case "raw":
return "2000";
case "uuid":
return "36";
default:
return "";
}
}
createFullType(e) {
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += "(" + e.precision + "," + e.scale + ")";
} else if (e.precision !== null && e.precision !== undefined) {
t += "(" + e.precision + ")";
}
if (e.type === "timestamp with time zone") {
t = "TIMESTAMP" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "") + " WITH TIME ZONE";
} else if (e.type === "timestamp with local time zone") {
t = "TIMESTAMP" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "") + " WITH LOCAL TIME ZONE";
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
return new Promise((e, t) => {
if (!this.master) {
return t(new RE.TypeORMError("Driver not Connected"));
}
this.master.getConnection((n, a, r) => {
if (n) return t(n);
e(a);
});
});
}
obtainSlaveConnection() {
if (!this.slaves.length) return this.obtainMasterConnection();
return new Promise((e, t) => {
const n = Math.floor(Math.random() * this.slaves.length);
this.slaves[n].getConnection((n, a) => {
if (n) return t(n);
e(a);
});
});
}
createGeneratedMap(e, t) {
if (!t) return undefined;
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
bE.OrmUtils.mergeDeep(n, r.createValueMap(this.prepareHydratedValue(t[a], r)));
}
return n;
}, {});
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== this.getColumnLength(t) || n.precision !== t.precision || n.scale !== t.scale || n.default !== this.normalizeDefault(t) || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.asExpression !== t.asExpression || n.generatedType !== t.generatedType || n.isUnique !== this.normalizeIsUnique(t) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
return a;
});
}
isReturningSqlSupported() {
return true;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return this.parametersPrefix + (t + 1);
}
columnTypeToNativeParameter(e) {
switch (this.normalizeType({
type: e
})) {
case "number":
case "numeric":
case "int":
case "integer":
case "smallint":
case "dec":
case "decimal":
return this.oracle.DB_TYPE_NUMBER;
case "char":
case "nchar":
case "nvarchar2":
case "varchar2":
return this.oracle.DB_TYPE_VARCHAR;
case "blob":
return this.oracle.DB_TYPE_BLOB;
case "simple-json":
case "clob":
return this.oracle.DB_TYPE_CLOB;
case "date":
case "timestamp":
case "timestamp with time zone":
case "timestamp with local time zone":
return this.oracle.DB_TYPE_TIMESTAMP;
case "json":
return this.oracle.DB_TYPE_JSON;
}
}
loadDependencies() {
try {
const e = this.options.driver || gE.PlatformTools.load("oracledb");
this.oracle = e;
} catch (e) {
throw new yE.DriverPackageNotInstalledError("Oracle", "oracledb");
}
const e = this.options.thickMode;
if (e) {
typeof e === "object" ? this.oracle.initOracleClient(e) : this.oracle.initOracleClient();
}
}
async createPool(e, t) {
t = Object.assign({}, t, AE.DriverUtils.buildDriverOptions(t));
if (!t.connectString) {
let e = `(PROTOCOL=TCP)`;
if (t.host) {
e += `(HOST=${t.host})`;
}
if (t.port) {
e += `(PORT=${t.port})`;
}
let n = `(SERVER=DEDICATED)`;
if (t.sid) {
n += `(SID=${t.sid})`;
}
if (t.serviceName) {
n += `(SERVICE_NAME=${t.serviceName})`;
}
const a = `(DESCRIPTION=(ADDRESS=${e})(CONNECT_DATA=${n}))`;
Object.assign(t, {
connectString: a
});
}
const n = Object.assign({}, {
user: t.username,
password: t.password,
connectString: t.connectString
}, {
poolMax: e.poolSize
}, e.extra || {});
return new Promise((e, t) => {
this.oracle.createPool(n, (n, a) => {
if (n) return t(n);
e(a);
});
});
}
async closePool(e) {
return new Promise((t, n) => {
e.close(e => e ? n(e) : t());
e = undefined;
});
}
}
Gy.OracleDriver = OracleDriver;
var wE = {};
var ME = {};
var OE = {};
Object.defineProperty(OE, "__esModule", {
value: true
});
OE.AbstractSqliteQueryRunner = void 0;
const vE = pe();
const IE = yu;
const PE = fu;
const LE = Tu;
const DE = Nu;
const _E = Bm;
const $E = ef;
const xE = Cu;
const qE = Zm;
const UE = qc;
const BE = Su;
const FE = P;
const jE = mf;
const kE = Te;
class AbstractSqliteQueryRunner extends qE.BaseQueryRunner {
constructor() {
super();
this.transactionPromise = null;
}
connect() {
return Promise.resolve(this.driver.databaseConnection);
}
release() {
this.loadedTables = [];
this.clearSqlMemory();
return Promise.resolve();
}
async startTransaction(e) {
if (this.driver.transactionSupport === "none") throw new FE.TypeORMError(`Transactions aren't supported by ${this.connection.driver.options.type}.`);
if (this.isTransactionActive && this.driver.transactionSupport === "simple") throw new FE.TransactionAlreadyStartedError;
if (e && e !== "READ UNCOMMITTED" && e !== "SERIALIZABLE") throw new FE.TypeORMError(`SQLite only supports SERIALIZABLE and READ UNCOMMITTED isolation`);
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
if (e) {
if (e === "READ UNCOMMITTED") {
await this.query("PRAGMA read_uncommitted = true");
} else {
await this.query("PRAGMA read_uncommitted = false");
}
}
await this.query("BEGIN TRANSACTION");
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new vE.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("COMMIT");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new vE.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("ROLLBACK");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
stream(e, t, n, a) {
throw new FE.TypeORMError(`Stream is not supported by sqlite driver.`);
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
return Promise.resolve([]);
}
async hasDatabase(e) {
return Promise.resolve(false);
}
async getCurrentDatabase() {
return Promise.resolve(undefined);
}
async hasSchema(e) {
throw new FE.TypeORMError(`This driver does not support table schemas`);
}
async getCurrentSchema() {
return Promise.resolve(undefined);
}
async hasTable(e) {
const t = kE.InstanceChecker.isTable(e) ? e.name : e;
const n = `SELECT * FROM "sqlite_master" WHERE "type" = 'table' AND "name" = '${t}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e.name : e;
const a = `PRAGMA table_xinfo(${this.escapePath(n)})`;
const r = await this.query(a);
return !!r.find(e => e["name"] === t);
}
async createDatabase(e, t) {
return Promise.resolve();
}
async dropDatabase(e, t) {
return Promise.resolve();
}
async createSchema(e, t) {
return Promise.resolve();
}
async dropSchema(e, t) {
return Promise.resolve();
}
async createTable(e, t = false, n = true, a = true) {
const r = [];
const i = [];
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(t));
});
}
const s = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of s) {
const n = this.insertTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const a = this.deleteTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(n);
i.push(a);
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const s = [];
const o = [];
if (a) {
i.indices.forEach(e => {
s.push(this.dropIndexSql(e));
o.push(this.createIndexSql(i, e));
});
}
s.push(this.dropTableSql(i, t));
o.push(this.createTableSql(i, r));
const c = i.columns.filter(e => e.generatedType && e.asExpression);
for (const e of c) {
const t = this.deleteTypeormMetadataSql({
table: i.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const n = this.insertTypeormMetadataSql({
table: i.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
s.push(t);
o.push(n);
}
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = kE.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
a.name = t;
const r = new $E.Query(`ALTER TABLE ${this.escapePath(n.name)} RENAME TO ${this.escapePath(t)}`);
const i = new $E.Query(`ALTER TABLE ${this.escapePath(t)} RENAME TO ${this.escapePath(n.name)}`);
await this.executeQueries(r, i);
a.uniques.forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(n, e.columnNames);
if (e.name !== t) return;
e.name = this.connection.namingStrategy.uniqueConstraintName(a, e.columnNames);
});
a.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(n, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
e.name = this.connection.namingStrategy.foreignKeyName(a, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
});
a.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(n, e.columnNames, e.where);
if (e.name !== t) return;
e.name = this.connection.namingStrategy.indexName(a, e.columnNames, e.where);
});
n.name = a.name;
await this.recreateTable(a, n);
}
async addColumn(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
return this.addColumns(n, [ t ]);
}
async addColumns(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.addColumn(e));
await this.recreateTable(a, n);
}
async renameColumn(e, t, n) {
const a = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = kE.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new FE.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i = undefined;
if (kE.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
return this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = kE.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new FE.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
await this.changeColumns(a, [ {
oldColumn: r,
newColumn: n
} ]);
}
async changeColumns(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => {
if (e.newColumn.name !== e.oldColumn.name) {
a.findColumnUniques(e.oldColumn).forEach(t => {
const r = this.connection.namingStrategy.uniqueConstraintName(n, t.columnNames);
t.columnNames.splice(t.columnNames.indexOf(e.oldColumn.name), 1);
t.columnNames.push(e.newColumn.name);
if (t.name === r) {
t.name = this.connection.namingStrategy.uniqueConstraintName(a, t.columnNames);
}
});
a.findColumnForeignKeys(e.oldColumn).forEach(t => {
const r = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
t.columnNames.splice(t.columnNames.indexOf(e.oldColumn.name), 1);
t.columnNames.push(e.newColumn.name);
if (t.name === r) {
t.name = this.connection.namingStrategy.foreignKeyName(a, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
}
});
a.findColumnIndices(e.oldColumn).forEach(t => {
const r = this.connection.namingStrategy.indexName(n, t.columnNames, t.where);
t.columnNames.splice(t.columnNames.indexOf(e.oldColumn.name), 1);
t.columnNames.push(e.newColumn.name);
if (t.name === r) {
t.name = this.connection.namingStrategy.indexName(a, t.columnNames, t.where);
}
});
}
const t = a.columns.find(t => t.name === e.oldColumn.name);
if (t) a.columns[a.columns.indexOf(t)] = e.newColumn;
});
await this.recreateTable(a, n);
}
async dropColumn(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = kE.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new FE.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
await this.dropColumns(n, [ a ]);
}
async dropColumns(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => {
const t = kE.InstanceChecker.isTableColumn(e) ? e : n.findColumnByName(e);
if (!t) throw new Error(`Column "${e}" was not found in table "${n.name}"`);
a.removeColumn(t);
a.findColumnUniques(t).forEach(e => a.removeUniqueConstraint(e));
a.findColumnIndices(t).forEach(e => a.removeIndex(e));
a.findColumnForeignKeys(t).forEach(e => a.removeForeignKey(e));
});
await this.recreateTable(a, n);
}
async createPrimaryKey(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
a.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
await this.recreateTable(a, n);
n.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
}
async updatePrimaryKeys(e, t) {
await Promise.resolve();
}
async dropPrimaryKey(e) {
const t = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const n = t.clone();
n.primaryColumns.forEach(e => {
e.isPrimary = false;
});
await this.recreateTable(n, t);
t.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
await this.createUniqueConstraints(e, [ t ]);
}
async createUniqueConstraints(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.addUniqueConstraint(e));
await this.recreateTable(a, n);
}
async dropUniqueConstraint(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = kE.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
if (!a) throw new FE.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
await this.dropUniqueConstraints(n, [ a ]);
}
async dropUniqueConstraints(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.removeUniqueConstraint(e));
await this.recreateTable(a, n);
}
async createCheckConstraint(e, t) {
await this.createCheckConstraints(e, [ t ]);
}
async createCheckConstraints(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.addCheckConstraint(e));
await this.recreateTable(a, n);
}
async dropCheckConstraint(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = kE.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new FE.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
await this.dropCheckConstraints(n, [ a ]);
}
async dropCheckConstraints(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.removeCheckConstraint(e));
await this.recreateTable(a, n);
}
async createExclusionConstraint(e, t) {
throw new FE.TypeORMError(`Sqlite does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new FE.TypeORMError(`Sqlite does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new FE.TypeORMError(`Sqlite does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new FE.TypeORMError(`Sqlite does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
await this.createForeignKeys(e, [ t ]);
}
async createForeignKeys(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.addForeignKey(e));
await this.recreateTable(a, n);
}
async dropForeignKey(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = kE.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new FE.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
await this.dropForeignKeys(e, [ a ]);
}
async dropForeignKeys(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
t.forEach(e => a.removeForeignKey(e));
await this.recreateTable(a, n);
}
async createIndex(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = kE.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new FE.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`DELETE FROM ${this.escapePath(e)}`);
}
async clearDatabase(e) {
let t = undefined;
if (e && this.driver.getAttachedDatabaseHandleByRelativePath(e)) {
t = this.driver.getAttachedDatabaseHandleByRelativePath(e);
}
await this.query(`PRAGMA foreign_keys = OFF`);
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = t ? `SELECT 'DROP VIEW "${t}"."' || name || '";' as query FROM "${t}"."sqlite_master" WHERE "type" = 'view'` : `SELECT 'DROP VIEW "' || name || '";' as query FROM "sqlite_master" WHERE "type" = 'view'`;
const a = await this.query(e);
await Promise.all(a.map(e => this.query(e["query"])));
const r = t ? `SELECT 'DROP TABLE "${t}"."' || name || '";' as query FROM "${t}"."sqlite_master" WHERE "type" = 'table' AND "name" != 'sqlite_sequence'` : `SELECT 'DROP TABLE "' || name || '";' as query FROM "sqlite_master" WHERE "type" = 'table' AND "name" != 'sqlite_sequence'`;
const i = await this.query(r);
await Promise.all(i.map(e => this.query(e["query"])));
if (!n) await this.commitTransaction();
} catch (e) {
try {
if (!n) await this.rollbackTransaction();
} catch (e) {}
throw e;
} finally {
await this.query(`PRAGMA foreign_keys = ON`);
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = e.map(e => "'" + e + "'").join(", ");
let a = `SELECT "t".* FROM "${this.getTypeormMetadataTableName()}" "t" INNER JOIN "sqlite_master" s ON "s"."name" = "t"."name" AND "s"."type" = 'view' WHERE "t"."type" = '${jE.MetadataTableType.VIEW}'`;
if (n.length > 0) a += ` AND "t"."name" IN (${n})`;
const r = await this.query(a);
return r.map(e => {
const t = new _E.View;
t.name = e["name"];
t.expression = e["value"];
return t;
});
}
async loadTableRecords(e, t) {
let n = undefined;
const [a, r] = this.splitTablePath(e);
if (a && this.driver.getAttachedDatabasePathRelativeByHandle(a)) {
n = this.driver.getAttachedDatabasePathRelativeByHandle(a);
}
return this.query(`SELECT ${n ? `'${n}'` : null} as database, ${a ? `'${a}'` : null} as schema, * FROM ${a ? `"${a}".` : ""}${this.escapePath(`sqlite_master`)} WHERE "type" = '${t}' AND "${t === "table" ? "name" : "tbl_name"}" IN ('${r}')`);
}
async loadPragmaRecords(e, t) {
const [, n] = this.splitTablePath(e);
return this.query(`PRAGMA ${t}("${n}")`);
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
let t = [];
let n;
if (!e) {
const e = `SELECT * FROM "sqlite_master" WHERE "type" = 'table'`;
t.push(...await this.query(e));
const a = t.map(({name: e}) => `'${e}'`).join(", ");
n = await this.query(`SELECT * FROM "sqlite_master" WHERE "type" = 'index' AND "tbl_name" IN (${a})`);
} else {
const a = e.filter(e => e.split(".").length === 1).map(e => `'${e}'`);
const r = e.filter(e => e.split(".").length > 1);
const i = e => {
const t = [ ...r.map(t => this.loadTableRecords(t, e)) ];
if (a.length) {
t.push(this.query(`SELECT * FROM "sqlite_master" WHERE "type" = '${e}' AND "${e === "table" ? "name" : "tbl_name"}" IN (${a})`));
}
return t;
};
t = (await Promise.all(i("table"))).reduce((e, t) => [ ...e, ...t ], []).filter(Boolean);
n = (await Promise.all(i("index"))).reduce((e, t) => [ ...e, ...t ], []).filter(Boolean);
}
if (t.length === 0) {
return [];
}
return Promise.all(t.map(async e => {
const t = e["database"] && this.driver.getAttachedDatabaseHandleByRelativePath(e["database"]) ? `${this.driver.getAttachedDatabaseHandleByRelativePath(e["database"])}.${e["name"]}` : e["name"];
const a = e["sql"];
const r = a.includes("WITHOUT ROWID");
const i = new PE.Table({
name: t,
withoutRowid: r
});
const [s, o, c] = await Promise.all([ this.loadPragmaRecords(t, `table_xinfo`), this.loadPragmaRecords(t, `index_list`), this.loadPragmaRecords(t, `foreign_key_list`) ]);
let l = undefined;
const u = e["sql"];
const h = u.toUpperCase().indexOf("AUTOINCREMENT");
if (h !== -1) {
l = u.substr(0, h);
const e = l.lastIndexOf(",");
const t = l.lastIndexOf("(");
if (e !== -1) {
l = l.substr(e);
l = l.substr(0, l.lastIndexOf('"'));
l = l.substr(l.indexOf('"') + 1);
} else if (t !== -1) {
l = l.substr(t);
l = l.substr(0, l.lastIndexOf('"'));
l = l.substr(l.indexOf('"') + 1);
}
}
i.columns = await Promise.all(s.map(async e => {
const t = new IE.TableColumn;
t.name = e["name"];
t.type = e["type"].toLowerCase();
t.default = e["dflt_value"] !== null && e["dflt_value"] !== undefined ? e["dflt_value"] : undefined;
t.isNullable = e["notnull"] === 0;
t.isPrimary = e["pk"] > 0;
t.comment = "";
t.isGenerated = l === e["name"];
if (t.isGenerated) {
t.generationStrategy = "increment";
}
if (e["hidden"] === 2 || e["hidden"] === 3) {
t.generatedType = e["hidden"] === 2 ? "VIRTUAL" : "STORED";
const n = this.selectTypeormMetadataSql({
table: i.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
const a = await this.query(n.query, n.parameters);
if (a[0] && a[0].value) {
t.asExpression = a[0].value;
} else {
t.asExpression = "";
}
}
if (t.type === "varchar") {
t.enum = UE.OrmUtils.parseSqlCheckExpression(a, t.name);
}
const n = t.type.indexOf("(");
if (n !== -1) {
const e = t.type;
const a = e.substr(0, n);
if (this.driver.withLengthColumnTypes.find(e => e === a)) {
const r = parseInt(e.substring(n + 1, e.length - 1));
if (r) {
t.length = r.toString();
t.type = a;
}
}
if (this.driver.withPrecisionColumnTypes.find(e => e === a)) {
const n = new RegExp(`^${a}\\((\\d+),?\\s?(\\d+)?\\)`);
const r = e.match(n);
if (r && r[1]) {
t.precision = +r[1];
}
if (this.driver.withScaleColumnTypes.find(e => e === a)) {
if (r && r[2]) {
t.scale = +r[2];
}
}
t.type = a;
}
}
return t;
}));
let d;
const p = [];
const m = /CONSTRAINT "([^"]*)" FOREIGN KEY ?\((.*?)\) REFERENCES "([^"]*)"/g;
while ((d = m.exec(a)) !== null) {
p.push({
name: d[1],
columns: d[2].substr(1, d[2].length - 2).split(`", "`),
referencedTableName: d[3]
});
}
const f = UE.OrmUtils.uniq(c, e => e["id"]);
i.foreignKeys = f.map(e => {
const t = c.filter(t => t["id"] === e["id"] && t["table"] === e["table"]);
const n = t.map(e => e["from"]);
const a = t.map(e => e["to"]);
const r = p.find(t => t.referencedTableName === e["table"] && t.columns.every(e => n.indexOf(e) !== -1));
return new DE.TableForeignKey({
name: r?.name,
columnNames: n,
referencedTableName: e["table"],
referencedColumnNames: a,
onDelete: e["on_delete"],
onUpdate: e["on_update"]
});
});
let y;
const E = [];
const T = /CONSTRAINT "([^"]*)" UNIQUE ?\((.*?)\)/g;
while ((y = T.exec(a)) !== null) {
E.push({
name: y[1],
columns: y[2].substr(1, y[2].length - 2).split(`", "`)
});
}
const g = o.filter(e => e["origin"] === "u").map(e => e["name"]).filter((e, t, n) => n.indexOf(e) === t).map(async e => {
const t = o.find(t => t["name"] === e);
const n = await this.query(`PRAGMA index_info("${t["name"]}")`);
const a = n.sort((e, t) => parseInt(e["seqno"]) - parseInt(t["seqno"])).map(e => e["name"]);
if (a.length === 1) {
const e = i.columns.find(e => !!a.find(t => t === e.name));
if (e) e.isUnique = true;
}
const r = E.find(e => e.columns.every(e => a.indexOf(e) !== -1));
return new xE.TableUnique({
name: r ? r.name : this.connection.namingStrategy.uniqueConstraintName(i, a),
columnNames: a
});
});
i.uniques = await Promise.all(g);
let N;
const A = /CONSTRAINT "([^"]*)" CHECK ?(\(.*?\))([,]|[)]$)/g;
while ((N = A.exec(a)) !== null) {
i.checks.push(new BE.TableCheck({
name: N[1],
expression: N[2]
}));
}
const b = o.filter(e => e["origin"] === "c").map(e => e["name"]).filter((e, t, n) => n.indexOf(e) === t).map(async t => {
const a = n.find(e => e["name"] === t);
const r = /WHERE (.*)/.exec(a["sql"]);
const s = o.find(e => e["name"] === t);
const c = await this.query(`PRAGMA index_info("${s["name"]}")`);
const l = c.sort((e, t) => parseInt(e["seqno"]) - parseInt(t["seqno"])).map(e => e["name"]);
const u = `${e["database"] ? `${e["database"]}.` : ""}${s["name"]}`;
const h = s["unique"] === "1" || s["unique"] === 1;
return new LE.TableIndex({
table: i,
name: u,
columnNames: l,
isUnique: h,
where: r ? r[1] : undefined
});
});
const C = await Promise.all(b);
i.indices = C.filter(e => !!e);
return i;
}));
}
createTableSql(e, t, n) {
const a = e.columns.filter(e => e.isPrimary);
const r = a.find(e => e.isGenerated && e.generationStrategy === "increment");
const i = a.length > 1;
if (i && r) throw new FE.TypeORMError(`Sqlite does not support AUTOINCREMENT on composite primary key`);
const s = e.columns.map(e => this.buildCreateColumnSql(e, i)).join(", ");
const [o] = this.splitTablePath(e.name);
let c = `CREATE TABLE ${this.escapePath(e.name)} (${s}`;
const [l, u] = this.splitTablePath(e.name);
const h = n ? `${l ? `${l}.` : ""}${u.replace(/^temporary_/, "")}` : e.name;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (!n) e.uniques.push(new xE.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ]
}));
});
if (e.uniques.length > 0) {
const t = e.uniques.map(e => {
const t = e.name ? e.name : this.connection.namingStrategy.uniqueConstraintName(h, e.columnNames);
const n = e.columnNames.map(e => `"${e}"`).join(", ");
return `CONSTRAINT "${t}" UNIQUE (${n})`;
}).join(", ");
c += `, ${t}`;
}
if (e.checks.length > 0) {
const t = e.checks.map(e => {
const t = e.name ? e.name : this.connection.namingStrategy.checkConstraintName(h, e.expression);
return `CONSTRAINT "${t}" CHECK (${e.expression})`;
}).join(", ");
c += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.filter(e => {
const [t] = this.splitTablePath(e.referencedTableName);
if (t !== o) {
return false;
}
return true;
}).map(e => {
const [, t] = this.splitTablePath(e.referencedTableName);
const n = e.columnNames.map(e => `"${e}"`).join(", ");
if (!e.name) e.name = this.connection.namingStrategy.foreignKeyName(h, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
const a = e.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${e.name}" FOREIGN KEY (${n}) REFERENCES "${t}" (${a})`;
if (e.onDelete) r += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) r += ` ON UPDATE ${e.onUpdate}`;
if (e.deferrable) r += ` DEFERRABLE ${e.deferrable}`;
return r;
}).join(", ");
c += `, ${t}`;
}
if (a.length > 1) {
const e = a.map(e => `"${e.name}"`).join(", ");
c += `, PRIMARY KEY (${e})`;
}
c += `)`;
if (e.withoutRowid) {
c += " WITHOUT ROWID";
}
return new $E.Query(c);
}
dropTableSql(e, t) {
const n = kE.InstanceChecker.isTable(e) ? e.name : e;
const a = t ? `DROP TABLE IF EXISTS ${this.escapePath(n)}` : `DROP TABLE ${this.escapePath(n)}`;
return new $E.Query(a);
}
createViewSql(e) {
if (typeof e.expression === "string") {
return new $E.Query(`CREATE VIEW "${e.name}" AS ${e.expression}`);
} else {
return new $E.Query(`CREATE VIEW "${e.name}" AS ${e.expression(this.connection).getQuery()}`);
}
}
insertViewDefinitionSql(e) {
const t = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: jE.MetadataTableType.VIEW,
name: e.name,
value: t
});
}
dropViewSql(e) {
const t = kE.InstanceChecker.isView(e) ? e.name : e;
return new $E.Query(`DROP VIEW "${t}"`);
}
deleteViewDefinitionSql(e) {
const t = kE.InstanceChecker.isView(e) ? e.name : e;
return this.deleteTypeormMetadataSql({
type: jE.MetadataTableType.VIEW,
name: t
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
const [a, r] = this.splitTablePath(e.name);
return new $E.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX ${a ? `"${a}".` : ""}${this.escapePath(t.name)} ON "${r}" (${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
dropIndexSql(e) {
const t = kE.InstanceChecker.isTableIndex(e) ? e.name : e;
return new $E.Query(`DROP INDEX ${this.escapePath(t)}`);
}
buildCreateColumnSql(e, t) {
let n = '"' + e.name + '"';
if (kE.InstanceChecker.isColumnMetadata(e)) {
n += " " + this.driver.normalizeType(e);
} else {
n += " " + this.connection.driver.createFullType(e);
}
if (e.enum) n += ' CHECK( "' + e.name + '" IN (' + e.enum.map(e => "'" + e + "'").join(",") + ") )";
if (e.isPrimary && !t) n += " PRIMARY KEY";
if (e.isGenerated === true && e.generationStrategy === "increment") n += " AUTOINCREMENT";
if (e.collation) n += " COLLATE " + e.collation;
if (e.isNullable !== true) n += " NOT NULL";
if (e.asExpression) {
n += ` AS (${e.asExpression}) ${e.generatedType ? e.generatedType : "VIRTUAL"}`;
} else {
if (e.default !== undefined && e.default !== null) n += " DEFAULT (" + e.default + ")";
}
return n;
}
async recreateTable(e, t, n = true) {
const a = [];
const r = [];
t.indices.forEach(e => {
a.push(this.dropIndexSql(e));
r.push(this.createIndexSql(t, e));
});
let [i, s] = this.splitTablePath(e.name);
const [, o] = this.splitTablePath(t.name);
e.name = s = `${i ? `${i}.` : ""}temporary_${s}`;
a.push(this.createTableSql(e, true, true));
r.push(this.dropTableSql(e));
if (n) {
let n = e.columns.filter(e => !e.generatedType).map(e => `"${e.name}"`);
let i = t.columns.filter(e => !e.generatedType).map(e => `"${e.name}"`);
if (i.length < n.length) {
n = e.columns.filter(e => {
const n = t.columns.find(t => t.name === e.name);
if (n && n.generatedType) return false;
return !e.generatedType && n;
}).map(e => `"${e.name}"`);
} else if (i.length > n.length) {
i = t.columns.filter(t => !t.generatedType && e.columns.find(e => e.name === t.name)).map(e => `"${e.name}"`);
}
a.push(new $E.Query(`INSERT INTO ${this.escapePath(e.name)}(${n.join(", ")}) SELECT ${i.join(", ")} FROM ${this.escapePath(t.name)}`));
r.push(new $E.Query(`INSERT INTO ${this.escapePath(t.name)}(${i.join(", ")}) SELECT ${n.join(", ")} FROM ${this.escapePath(e.name)}`));
}
a.push(this.dropTableSql(t));
r.push(this.createTableSql(t, true));
a.push(new $E.Query(`ALTER TABLE ${this.escapePath(e.name)} RENAME TO ${this.escapePath(o)}`));
r.push(new $E.Query(`ALTER TABLE ${this.escapePath(t.name)} RENAME TO ${this.escapePath(s)}`));
e.name = t.name;
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
a.push(this.createIndexSql(e, t));
r.push(this.dropIndexSql(t));
});
t.columns.filter(t => {
const n = e.columns.find(e => e.name === t.name);
return t.generatedType && t.asExpression && (!n || !n.generatedType && !n.asExpression);
}).forEach(e => {
const n = this.deleteTypeormMetadataSql({
table: t.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const i = this.insertTypeormMetadataSql({
table: t.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
a.push(n);
r.push(i);
});
e.columns.filter(e => e.generatedType && e.asExpression && !t.columns.some(t => t.name === e.name)).forEach(t => {
const n = this.insertTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const i = this.deleteTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
a.push(n);
r.push(i);
});
e.columns.filter(e => e.generatedType && e.asExpression).forEach(n => {
const i = t.columns.find(e => e.name === n.name && e.generatedType && n.generatedType && e.asExpression !== n.asExpression);
if (!i) return;
const s = this.deleteTypeormMetadataSql({
table: t.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: i.name
});
const o = this.insertTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: n.name,
value: n.asExpression
});
a.push(s);
a.push(o);
const c = this.insertTypeormMetadataSql({
table: e.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: i.name,
value: i.asExpression
});
const l = this.deleteTypeormMetadataSql({
table: t.name,
type: jE.MetadataTableType.GENERATED_COLUMN,
name: n.name
});
r.push(c);
r.push(l);
});
await this.executeQueries(a, r);
this.replaceCachedTable(t, e);
}
splitTablePath(e) {
return e.indexOf(".") !== -1 ? e.split(".") : [ undefined, e ];
}
escapePath(e, t) {
const n = kE.InstanceChecker.isTable(e) || kE.InstanceChecker.isView(e) ? e.name : e;
return n.replace(/^\.+|\.+$/g, "").split(".").map(e => t ? e : `"${e}"`).join(".");
}
changeTableComment(e, t) {
throw new FE.TypeORMError(`sqlit driver does not support change comment.`);
}
}
OE.AbstractSqliteQueryRunner = AbstractSqliteQueryRunner;
var QE;
function VE() {
if (QE) return ME;
QE = 1;
Object.defineProperty(ME, "__esModule", {
value: true
});
ME.SqliteQueryRunner = void 0;
const e = Y();
const t = nn();
const n = Sn();
const a = lf;
const r = hf;
const i = sc;
const s = OE;
let o = class SqliteQueryRunner extends s.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new r.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async query(r, s, o = false) {
if (this.isReleased) throw new n.QueryRunnerAlreadyReleasedError;
const c = this.driver.connection;
const l = c.options;
const u = this.driver.options.maxQueryExecutionTime;
const h = this.broadcaster;
if (!c.isInitialized) {
throw new e.ConnectionIsNotSetError("sqlite");
}
const d = await this.connect();
this.driver.connection.logger.logQuery(r, s, this);
await h.broadcast("BeforeQuery", r, s);
const p = new i.BroadcasterResult;
return new Promise(async (e, n) => {
try {
const i = Date.now();
const m = r.startsWith("INSERT ");
const f = r.startsWith("DELETE ");
const y = r.startsWith("UPDATE ");
const E = async () => {
if (m || f || y) {
await d.run(r, s, g);
} else {
await d.all(r, s, g);
}
};
const T = this;
const g = function(d, f) {
if (d && d.toString().indexOf("SQLITE_BUSY:") !== -1) {
if (typeof l.busyErrorRetry === "number" && l.busyErrorRetry > 0) {
setTimeout(E, l.busyErrorRetry);
return;
}
}
const y = Date.now();
const g = y - i;
if (u && g > u) c.logger.logQuerySlow(g, r, s, T);
if (d) {
c.logger.logQueryError(d, r, s, T);
h.broadcastAfterQueryEvent(p, r, s, false, undefined, undefined, d);
return n(new t.QueryFailedError(r, s, d));
} else {
const t = new a.QueryResult;
if (m) {
t.raw = this["lastID"];
} else {
t.raw = f;
}
h.broadcastAfterQueryEvent(p, r, s, true, g, t.raw, undefined);
if (Array.isArray(f)) {
t.records = f;
}
t.affected = this["changes"];
if (o) {
e(t);
} else {
e(t.raw);
}
}
};
await E();
} catch (e) {
n(e);
} finally {
await p.wait();
}
});
}
};
ME.SqliteQueryRunner = o;
return ME;
}
var KE = {};
Object.defineProperty(KE, "__esModule", {
value: true
});
KE.AbstractSqliteDriver = void 0;
const WE = up;
const HE = Um;
const GE = qc;
const YE = _s;
const zE = jn;
const JE = P;
const XE = Te;
class AbstractSqliteDriver {
constructor(e) {
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "int", "integer", "tinyint", "smallint", "mediumint", "bigint", "unsigned big int", "int2", "int8", "integer", "character", "varchar", "varying character", "nchar", "native character", "nvarchar", "text", "clob", "text", "blob", "real", "double", "double precision", "float", "real", "numeric", "decimal", "boolean", "date", "time", "datetime", "json" ];
this.supportedUpsertTypes = [ "on-conflict-do-update" ];
this.withLengthColumnTypes = [ "character", "varchar", "varying character", "nchar", "native character", "nvarchar", "text", "blob", "clob" ];
this.spatialTypes = [];
this.withPrecisionColumnTypes = [ "real", "double", "double precision", "float", "real", "numeric", "decimal", "date", "time", "datetime" ];
this.withScaleColumnTypes = [ "real", "double", "double precision", "float", "real", "numeric", "decimal" ];
this.mappedDataTypes = {
createDate: "datetime",
createDateDefault: "datetime('now')",
updateDate: "datetime",
updateDateDefault: "datetime('now')",
deleteDate: "datetime",
deleteDateNullable: true,
version: "integer",
treeLevel: "integer",
migrationId: "integer",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "varchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text"
};
this.cteCapabilities = {
enabled: true,
requiresRecursiveHint: true
};
this.attachedDatabases = {};
this.connection = e;
this.options = e.options;
this.database = zE.DriverUtils.buildDriverOptions(this.options).database;
}
async connect() {
this.databaseConnection = await this.createDatabaseConnection();
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
return new Promise((e, t) => {
this.queryRunner = undefined;
this.databaseConnection.close(n => n ? t(n) : e());
});
}
hasAttachedDatabases() {
return !!Object.keys(this.attachedDatabases).length;
}
getAttachedDatabaseHandleByRelativePath(e) {
return this.attachedDatabases?.[e]?.attachHandle;
}
getAttachedDatabasePathRelativeByHandle(e) {
return Object.values(this.attachedDatabases).find(({attachHandle: t}) => e === t)?.attachFilepathRelative;
}
createSchemaBuilder() {
return new HE.RdbmsSchemaBuilder(this.connection);
}
preparePersistentValue(e, t) {
if (t.transformer) e = YE.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean || t.type === "boolean") {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return WE.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return WE.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "datetime" || t.type === Date) {
return WE.DateUtils.mixedDateToUtcDatetimeString(e);
} else if (t.type === "json" || t.type === "simple-json") {
return WE.DateUtils.simpleJsonToString(e);
} else if (t.type === "simple-array") {
return WE.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-enum") {
return WE.DateUtils.simpleEnumToString(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? YE.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean || t.type === "boolean") {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date) {
if (e && typeof e === "string") {
if (/^\d\d\d\d-\d\d-\d\d \d\d:\d\d/.test(e)) {
e = e.replace(" ", "T");
}
if (/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d\d\d)?)?$/.test(e)) {
e += "Z";
}
}
e = WE.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = WE.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = WE.DateUtils.mixedTimeToString(e);
} else if (t.type === "json" || t.type === "simple-json") {
e = WE.DateUtils.stringToSimpleJson(e);
} else if (t.type === "simple-array") {
e = WE.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-enum") {
e = WE.DateUtils.stringToSimpleEnum(e, t);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = YE.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => {
if (typeof n[e] === "boolean") {
return n[e] === true ? 1 : 0;
}
if (n[e] instanceof Date) {
return WE.DateUtils.mixedDateToUtcDatetimeString(n[e]);
}
return n[e];
});
if (!t || !Object.keys(t).length) return [ e, a ];
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, r) => {
if (!t.hasOwnProperty(r)) {
return e;
}
const i = t[r];
if (n) {
return i.map(e => {
a.push(e);
return this.createParameter(r, a.length - 1);
}).join(", ");
}
if (typeof i === "function") {
return i();
} else if (typeof i === "number") {
return String(i);
}
if (typeof i === "boolean") {
a.push(+i);
return this.createParameter(r, a.length - 1);
}
if (i instanceof Date) {
a.push(WE.DateUtils.mixedDateToUtcDatetimeString(i));
return this.createParameter(r, a.length - 1);
}
a.push(i);
return this.createParameter(r, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return '"' + e + '"';
}
buildTableName(e, t, n) {
return e;
}
parseTableName(e) {
const t = this.database;
const n = undefined;
if (XE.InstanceChecker.isTable(e) || XE.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.schema ? `"${e.schema}"."${e.name}"` : e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (XE.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (XE.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
if (a.length === 3) {
return {
database: a[0] || t,
schema: a[1] || n,
tableName: a[2]
};
} else if (a.length === 2) {
const e = this.getAttachedDatabasePathRelativeByHandle(a[0]) ?? t;
return {
database: e,
schema: a[0],
tableName: a[1]
};
} else {
return {
database: t,
schema: n,
tableName: e
};
}
}
normalizeType(e) {
if (e.type === Number || e.type === "int") {
return "integer";
} else if (e.type === String) {
return "varchar";
} else if (e.type === Date) {
return "datetime";
} else if (e.type === Boolean) {
return "boolean";
} else if (e.type === "uuid") {
return "varchar";
} else if (e.type === "simple-array") {
return "text";
} else if (e.type === "simple-json") {
return "text";
} else if (e.type === "simple-enum") {
return "varchar";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (typeof t === "number") {
return "" + t;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
return t();
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === null || t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
return e.length ? e.length.toString() : "";
}
createFullType(e) {
let t = e.type;
if (e.enum) {
return "varchar";
}
if (e.length) {
t += "(" + e.length + ")";
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += "(" + e.precision + "," + e.scale + ")";
} else if (e.precision !== null && e.precision !== undefined) {
t += "(" + e.precision + ")";
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
return Promise.resolve();
}
obtainSlaveConnection() {
return Promise.resolve();
}
createGeneratedMap(e, t, n, a) {
const r = e.generatedColumns.reduce((e, r) => {
let i;
if (r.generationStrategy === "increment" && t) {
i = t - a + n + 1;
}
if (!i) return e;
return GE.OrmUtils.mergeDeep(e, r.createValueMap(i));
}, {});
return Object.keys(r).length > 0 ? r : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== t.length || n.precision !== t.precision || n.scale !== t.scale || this.normalizeDefault(t) !== n.default || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.generatedType !== t.generatedType || n.asExpression !== t.asExpression || n.isUnique !== this.normalizeIsUnique(t) || n.enum && t.enum && !GE.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
return a;
});
}
isReturningSqlSupported() {
return false;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return "?";
}
createDatabaseConnection() {
throw new JE.TypeORMError("Do not use AbstractSqlite directly, it has to be used with one of the sqlite drivers");
}
loadDependencies() {}
}
KE.AbstractSqliteDriver = AbstractSqliteDriver;
Object.defineProperty(wE, "__esModule", {
value: true
});
wE.SqliteDriver = void 0;
const ZE = e;
const eT = ZE.__importDefault(m);
const tT = ZE.__importDefault(c);
const nT = Tt();
const aT = VE();
const rT = Uh;
const iT = KE;
const sT = Pd();
class SqliteDriver extends iT.AbstractSqliteDriver {
constructor(e) {
super(e);
this.connection = e;
this.options = e.options;
this.database = this.options.database;
this.loadDependencies();
}
async disconnect() {
return new Promise((e, t) => {
this.queryRunner = undefined;
this.databaseConnection.close(n => n ? t(n) : e());
});
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new aT.SqliteQueryRunner(this);
return this.queryRunner;
}
normalizeType(e) {
if (e.type === Buffer) {
return "blob";
}
return super.normalizeType(e);
}
async afterConnect() {
return this.attachDatabases();
}
buildTableName(e, t, n) {
if (!n) return e;
if (this.getAttachedDatabaseHandleByRelativePath(n)) return `${this.getAttachedDatabaseHandleByRelativePath(n)}.${e}`;
if (n === this.options.database) return e;
const a = (0, sT.filepathToName)(n);
const r = (0, sT.isAbsolute)(n) ? n : tT.default.join(this.getMainDatabasePath(), n);
this.attachedDatabases[n] = {
attachFilepathAbsolute: r,
attachFilepathRelative: n,
attachHandle: a
};
return `${a}.${e}`;
}
async createDatabaseConnection() {
if (this.options.flags === undefined || !(this.options.flags & this.sqlite.OPEN_URI)) {
await this.createDatabaseDirectory(this.options.database);
}
const e = await new Promise((e, t) => {
if (this.options.flags === undefined) {
const n = new this.sqlite.Database(this.options.database, a => {
if (a) return t(a);
e(n);
});
} else {
const n = new this.sqlite.Database(this.options.database, this.options.flags, a => {
if (a) return t(a);
e(n);
});
}
});
function t(t) {
return new Promise((n, a) => {
e.run(t, e => {
if (e) return a(e);
n();
});
});
}
if (this.options.key) {
await t(`PRAGMA key = ${JSON.stringify(this.options.key)}`);
}
if (this.options.enableWAL) {
await t(`PRAGMA journal_mode = WAL`);
}
if (this.options.busyTimeout && typeof this.options.busyTimeout === "number" && this.options.busyTimeout > 0) {
await t(`PRAGMA busy_timeout = ${this.options.busyTimeout}`);
}
await t(`PRAGMA foreign_keys = ON`);
return e;
}
loadDependencies() {
try {
const e = this.options.driver || rT.PlatformTools.load("sqlite3");
this.sqlite = e.verbose();
} catch (e) {
throw new nT.DriverPackageNotInstalledError("SQLite", "sqlite3");
}
}
async createDatabaseDirectory(e) {
await eT.default.mkdir(tT.default.dirname(e), {
recursive: true
});
}
async attachDatabases() {
for await (const {attachHandle: e, attachFilepathAbsolute: t} of Object.values(this.attachedDatabases)) {
await this.createDatabaseDirectory(t);
await this.connection.query(`ATTACH "${t}" AS "${e}"`);
}
}
getMainDatabasePath() {
const e = this.options.database;
return tT.default.dirname((0, sT.isAbsolute)(e) ? e : tT.default.join(process.cwd(), e));
}
}
wE.SqliteDriver = SqliteDriver;
var oT = {};
var cT = {};
Object.defineProperty(cT, "__esModule", {
value: true
});
cT.CordovaQueryRunner = void 0;
const lT = P;
const uT = nn();
const hT = Sn();
const dT = lf;
const pT = hf;
const mT = sc;
const fT = OE;
class CordovaQueryRunner extends fT.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new pT.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async query(e, t, n = false) {
if (this.isReleased) throw new hT.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new mT.BroadcasterResult;
const i = Date.now();
try {
const s = await new Promise(async (n, r) => {
a.executeSql(e, t, e => n(e), e => r(e));
});
const o = this.driver.options.maxQueryExecutionTime;
const c = Date.now();
const l = c - i;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, s, undefined);
if (o && l > o) {
this.driver.connection.logger.logQuerySlow(l, e, t, this);
}
const u = new dT.QueryResult;
if (e.substr(0, 11) === "INSERT INTO") {
u.raw = s.insertId;
} else {
const e = [];
for (let t = 0; t < s.rows.length; t++) {
e.push(s.rows.item(t));
}
u.records = e;
u.raw = e;
}
if (n) {
return u;
} else {
return u.raw;
}
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
throw new uT.QueryFailedError(e, t, n);
} finally {
await r.wait();
}
}
async startTransaction() {
throw new lT.TypeORMError("Transactions are not supported by the Cordova driver");
}
async commitTransaction() {
throw new lT.TypeORMError("Transactions are not supported by the Cordova driver");
}
async rollbackTransaction() {
throw new lT.TypeORMError("Transactions are not supported by the Cordova driver");
}
async clearDatabase() {
await this.query(`PRAGMA foreign_keys = OFF`);
try {
const e = `SELECT 'DROP VIEW "' || name || '";' as query FROM "sqlite_master" WHERE "type" = 'view'`;
const t = await this.query(e);
const n = `SELECT 'DROP TABLE "' || name || '";' as query FROM "sqlite_master" WHERE "type" = 'table' AND "name" != 'sqlite_sequence'`;
const a = await this.query(n);
await Promise.all(t.map(e => this.query(e["query"])));
await Promise.all(a.map(e => this.query(e["query"])));
} finally {
await this.query(`PRAGMA foreign_keys = ON`);
}
}
parametrize(e, t = 0) {
return Object.keys(e).map((e, t) => `"${e}"` + "=?");
}
}
cT.CordovaQueryRunner = CordovaQueryRunner;
Object.defineProperty(oT, "__esModule", {
value: true
});
oT.CordovaDriver = void 0;
const yT = KE;
const ET = cT;
const TT = Tt();
class CordovaDriver extends yT.AbstractSqliteDriver {
constructor(e) {
super(e);
this.transactionSupport = "none";
this.database = this.options.database;
this.loadDependencies();
}
async disconnect() {
this.queryRunner = undefined;
return new Promise((e, t) => {
this.databaseConnection.close(e, t);
});
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new ET.CordovaQueryRunner(this);
return this.queryRunner;
}
async createDatabaseConnection() {
const e = Object.assign({}, {
name: this.options.database,
location: this.options.location
}, this.options.extra || {});
const t = await new Promise((t, n) => {
this.sqlite.openDatabase(e, e => t(e), e => n(e));
});
await new Promise((e, n) => {
t.executeSql(`PRAGMA foreign_keys = ON`, [], () => e(), e => n(e));
});
return t;
}
loadDependencies() {
try {
const e = this.options.driver || window.sqlitePlugin;
this.sqlite = e;
} catch (e) {
throw new TT.DriverPackageNotInstalledError("Cordova-SQLite", "cordova-sqlite-storage");
}
}
}
oT.CordovaDriver = CordovaDriver;
var gT = {};
var NT = {};
Object.defineProperty(NT, "__esModule", {
value: true
});
NT.ReactNativeQueryRunner = void 0;
const AT = nn();
const bT = Sn();
const CT = lf;
const RT = hf;
const ST = sc;
const wT = OE;
class ReactNativeQueryRunner extends wT.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new RT.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async query(e, t, n = false) {
if (this.isReleased) throw new bT.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new ST.BroadcasterResult;
const i = Date.now();
return new Promise(async (s, o) => {
try {
a.executeSql(e, t, async a => {
const o = this.driver.options.maxQueryExecutionTime;
const c = Date.now();
const l = c - i;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, a, undefined);
if (o && l > o) this.driver.connection.logger.logQuerySlow(l, e, t, this);
if (r.promises.length > 0) await Promise.all(r.promises);
const u = new CT.QueryResult;
if (a?.hasOwnProperty("rowsAffected")) {
u.affected = a.rowsAffected;
}
if (a?.hasOwnProperty("rows")) {
const e = [];
for (let t = 0; t < a.rows.length; t++) {
e.push(a.rows.item(t));
}
u.raw = e;
u.records = e;
}
if (e.substr(0, 11) === "INSERT INTO") {
u.raw = a.insertId;
}
if (n) {
s(u);
} else {
s(u.raw);
}
}, async n => {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
o(new AT.QueryFailedError(e, t, n));
});
} catch (e) {
o(e);
} finally {
await r.wait();
}
});
}
parametrize(e, t = 0) {
return Object.keys(e).map((e, t) => `"${e}"` + "=?");
}
}
NT.ReactNativeQueryRunner = ReactNativeQueryRunner;
Object.defineProperty(gT, "__esModule", {
value: true
});
gT.ReactNativeDriver = void 0;
const MT = up;
const OT = Um;
const vT = qc;
const IT = _s;
const PT = P;
const LT = Te;
const DT = NT;
class ReactNativeDriver {
constructor(e) {
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "int", "integer", "tinyint", "smallint", "mediumint", "bigint", "unsigned big int", "int2", "int8", "integer", "character", "varchar", "varying character", "nchar", "native character", "nvarchar", "text", "clob", "text", "blob", "real", "double", "double precision", "float", "real", "numeric", "decimal", "boolean", "date", "time", "datetime" ];
this.supportedUpsertTypes = [ "on-conflict-do-update" ];
this.withLengthColumnTypes = [ "character", "varchar", "varying character", "nchar", "native character", "nvarchar", "text", "blob", "clob" ];
this.spatialTypes = [];
this.withPrecisionColumnTypes = [ "real", "double", "double precision", "float", "real", "numeric", "decimal", "date", "time", "datetime" ];
this.withScaleColumnTypes = [ "real", "double", "double precision", "float", "real", "numeric", "decimal" ];
this.mappedDataTypes = {
createDate: "datetime",
createDateDefault: "datetime('now')",
updateDate: "datetime",
updateDateDefault: "datetime('now')",
deleteDate: "datetime",
deleteDateNullable: true,
version: "integer",
treeLevel: "integer",
migrationId: "integer",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "varchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text"
};
this.cteCapabilities = {
enabled: true,
requiresRecursiveHint: true
};
this.attachedDatabases = {};
this.connection = e;
this.options = e.options;
this.database = this.options.database;
this.loadDependencies();
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new DT.ReactNativeQueryRunner(this);
return this.queryRunner;
}
async connect() {
this.databaseConnection = await this.createDatabaseConnection();
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
return new Promise((e, t) => {
this.queryRunner = undefined;
this.databaseConnection.close(e, t);
});
}
hasAttachedDatabases() {
return !!Object.keys(this.attachedDatabases).length;
}
getAttachedDatabaseHandleByRelativePath(e) {
return this.attachedDatabases?.[e]?.attachHandle;
}
getAttachedDatabasePathRelativeByHandle(e) {
return Object.values(this.attachedDatabases).find(({attachHandle: t}) => e === t)?.attachFilepathRelative;
}
createSchemaBuilder() {
return new OT.RdbmsSchemaBuilder(this.connection);
}
preparePersistentValue(e, t) {
if (t.transformer) e = IT.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean || t.type === "boolean") {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return MT.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return MT.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "datetime" || t.type === Date) {
return MT.DateUtils.mixedDateToUtcDatetimeString(e);
} else if (t.type === "simple-array") {
return MT.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return MT.DateUtils.simpleJsonToString(e);
} else if (t.type === "simple-enum") {
return MT.DateUtils.simpleEnumToString(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? IT.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean || t.type === "boolean") {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date) {
if (e && typeof e === "string") {
if (/^\d\d\d\d-\d\d-\d\d \d\d:\d\d/.test(e)) {
e = e.replace(" ", "T");
}
if (/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d\d\d)?)?$/.test(e)) {
e += "Z";
}
}
e = MT.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = MT.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = MT.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array") {
e = MT.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = MT.DateUtils.stringToSimpleJson(e);
} else if (t.type === "simple-enum") {
e = MT.DateUtils.stringToSimpleEnum(e, t);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = IT.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => {
if (typeof n[e] === "boolean") {
return n[e] === true ? 1 : 0;
}
if (n[e] instanceof Date) {
return MT.DateUtils.mixedDateToUtcDatetimeString(n[e]);
}
return n[e];
});
if (!t || !Object.keys(t).length) return [ e, a ];
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, r) => {
if (!t.hasOwnProperty(r)) {
return e;
}
const i = t[r];
if (n) {
return i.map(e => {
a.push(e);
return this.createParameter(r, a.length - 1);
}).join(", ");
}
if (typeof i === "function") {
return i();
} else if (typeof i === "number") {
return String(i);
}
if (typeof i === "boolean") {
a.push(+i);
return this.createParameter(r, a.length - 1);
}
if (i instanceof Date) {
a.push(MT.DateUtils.mixedDateToUtcDatetimeString(i));
return this.createParameter(r, a.length - 1);
}
a.push(i);
return this.createParameter(r, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return '"' + e + '"';
}
buildTableName(e, t, n) {
return e;
}
parseTableName(e) {
const t = this.database;
const n = undefined;
if (LT.InstanceChecker.isTable(e) || LT.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.schema ? `"${e.schema}"."${e.name}"` : e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (LT.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (LT.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
if (a.length === 3) {
return {
database: a[0] || t,
schema: a[1] || n,
tableName: a[2]
};
} else if (a.length === 2) {
const e = this.getAttachedDatabasePathRelativeByHandle(a[0]) ?? t;
return {
database: e,
schema: a[0],
tableName: a[1]
};
} else {
return {
database: t,
schema: n,
tableName: e
};
}
}
normalizeType(e) {
if (e.type === Number || e.type === "int") {
return "integer";
} else if (e.type === String) {
return "varchar";
} else if (e.type === Date) {
return "datetime";
} else if (e.type === Boolean) {
return "boolean";
} else if (e.type === "uuid") {
return "varchar";
} else if (e.type === "simple-array") {
return "text";
} else if (e.type === "simple-json") {
return "text";
} else if (e.type === "simple-enum") {
return "varchar";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (typeof t === "number") {
return "" + t;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
return t();
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === null || t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
return e.length ? e.length.toString() : "";
}
createFullType(e) {
let t = e.type;
if (e.enum) {
return "varchar";
}
if (e.length) {
t += "(" + e.length + ")";
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += "(" + e.precision + "," + e.scale + ")";
} else if (e.precision !== null && e.precision !== undefined) {
t += "(" + e.precision + ")";
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
return Promise.resolve();
}
obtainSlaveConnection() {
return Promise.resolve();
}
createGeneratedMap(e, t, n, a) {
const r = e.generatedColumns.reduce((e, r) => {
let i;
if (r.generationStrategy === "increment" && t) {
i = t - a + n + 1;
}
if (!i) return e;
return vT.OrmUtils.mergeDeep(e, r.createValueMap(i));
}, {});
return Object.keys(r).length > 0 ? r : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== t.length || n.precision !== t.precision || n.scale !== t.scale || this.normalizeDefault(t) !== n.default || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.generatedType !== t.generatedType || n.asExpression !== t.asExpression || n.isUnique !== this.normalizeIsUnique(t) || n.enum && t.enum && !vT.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
return a;
});
}
isReturningSqlSupported() {
return false;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return "?";
}
createDatabaseConnection() {
return new Promise((e, t) => {
const n = Object.assign({}, {
name: this.options.database,
location: this.options.location
}, this.options.extra || {});
this.sqlite.openDatabase(n, n => {
const a = n;
a.executeSql(`PRAGMA foreign_keys = ON`, [], t => {
e(a);
}, e => {
t(e);
});
}, e => {
t(e);
});
});
}
loadDependencies() {
try {
const e = this.options.driver || require("react-native-sqlite-storage");
this.sqlite = e;
} catch (e) {
throw new PT.DriverPackageNotInstalledError("React-Native", "react-native-sqlite-storage");
}
}
}
gT.ReactNativeDriver = ReactNativeDriver;
var _T = {};
var $T = {};
Object.defineProperty($T, "__esModule", {
value: true
});
$T.NativescriptQueryRunner = void 0;
const xT = nn();
const qT = Sn();
const UT = lf;
const BT = hf;
const FT = OE;
class NativescriptQueryRunner extends FT.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new BT.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async query(e, t, n = false) {
if (this.isReleased) {
throw new qT.QueryRunnerAlreadyReleasedError;
}
const a = this.driver.connection;
const r = await this.connect();
return new Promise(async (i, s) => {
const o = e.substr(0, 11) === "INSERT INTO";
a.logger.logQuery(e, t, this);
const c = (r, c) => {
const u = this.driver.options.maxQueryExecutionTime;
const h = Date.now();
const d = h - l;
if (u && d > u) {
a.logger.logQuerySlow(d, e, t, this);
}
if (r) {
a.logger.logQueryError(r, e, t, this);
s(new xT.QueryFailedError(e, t, r));
}
const p = new UT.QueryResult;
p.raw = c;
if (!o && Array.isArray(c)) {
p.records = c;
}
if (n) {
i(p);
} else {
i(p.raw);
}
};
const l = Date.now();
if (o) {
r.execSQL(e, t, c);
} else {
r.all(e, t, c);
}
});
}
parametrize(e, t = 0) {
return Object.keys(e).map((e, t) => `"${e}"` + "=?");
}
}
$T.NativescriptQueryRunner = NativescriptQueryRunner;
Object.defineProperty(_T, "__esModule", {
value: true
});
_T.NativescriptDriver = void 0;
const jT = KE;
const kT = $T;
const QT = Tt();
class NativescriptDriver extends jT.AbstractSqliteDriver {
constructor(e) {
super(e);
this.connection = e;
this.options = e.options;
this.database = this.options.database;
this.driver = this.options.driver;
this.loadDependencies();
}
async disconnect() {
return new Promise((e, t) => {
this.queryRunner = undefined;
this.databaseConnection.close().then(e).catch(t);
});
}
createQueryRunner(e) {
if (!this.queryRunner) {
this.queryRunner = new kT.NativescriptQueryRunner(this);
}
return this.queryRunner;
}
normalizeType(e) {
if (e.type === Buffer) {
return "blob";
}
return super.normalizeType(e);
}
createDatabaseConnection() {
return new Promise((e, t) => {
const n = Object.assign({}, {
readOnly: this.options.readOnly,
key: this.options.key,
multithreading: this.options.multithreading,
migrate: this.options.migrate,
iosFlags: this.options.iosFlags,
androidFlags: this.options.androidFlags
}, this.options.extra || {});
new this.sqlite(this.options.database, n, (n, a) => {
if (n) return t(n);
a.resultType(this.sqlite.RESULTSASOBJECT);
a.execSQL(`PRAGMA foreign_keys = ON`, [], (n, r) => {
if (n) return t(n);
e(a);
});
});
});
}
loadDependencies() {
this.sqlite = this.driver;
if (!this.driver) {
throw new QT.DriverPackageNotInstalledError("Nativescript", "nativescript-sqlite");
}
}
}
_T.NativescriptDriver = NativescriptDriver;
var VT = {};
var KT = {};
Object.defineProperty(KT, "__esModule", {
value: true
});
KT.SqljsQueryRunner = void 0;
const WT = nn();
const HT = Sn();
const GT = lf;
const YT = hf;
const zT = sc;
const JT = OE;
class SqljsQueryRunner extends JT.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.isDirty = false;
this.driver = e;
this.connection = e.connection;
this.broadcaster = new YT.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async flush() {
if (this.isDirty) {
await this.driver.autoSave();
this.isDirty = false;
}
}
async release() {
await this.flush();
return super.release();
}
async commitTransaction() {
await super.commitTransaction();
if (!this.isTransactionActive) {
await this.flush();
}
}
async query(e, t = [], n = false) {
if (this.isReleased) throw new HT.QueryRunnerAlreadyReleasedError;
const a = e.trim().split(" ", 1)[0];
const r = this.driver.databaseConnection;
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const i = new zT.BroadcasterResult;
const s = Date.now();
let o;
try {
o = r.prepare(e);
if (t) {
t = t.map(e => typeof e !== "undefined" ? e : null);
o.bind(t);
}
const c = this.driver.options.maxQueryExecutionTime;
const l = Date.now();
const u = l - s;
if (c && u > c) this.driver.connection.logger.logQuerySlow(u, e, t, this);
const h = [];
while (o.step()) {
h.push(o.getAsObject());
}
this.broadcaster.broadcastAfterQueryEvent(i, e, t, true, u, h, undefined);
const d = new GT.QueryResult;
d.affected = r.getRowsModified();
d.records = h;
d.raw = h;
o.free();
if (a !== "SELECT") {
this.isDirty = true;
}
if (n) {
return d;
} else {
return d.raw;
}
} catch (n) {
if (o) {
o.free();
}
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(i, e, t, false, undefined, undefined, n);
throw new WT.QueryFailedError(e, t, n);
} finally {
await i.wait();
}
}
}
KT.SqljsQueryRunner = SqljsQueryRunner;
Object.defineProperty(VT, "__esModule", {
value: true
});
VT.SqljsDriver = void 0;
const XT = KE;
const ZT = KT;
const eg = Tt();
const tg = xt();
const ng = Uh;
const ag = qc;
const rg = P;
class SqljsDriver extends XT.AbstractSqliteDriver {
constructor(e) {
super(e);
if (this.options.autoSave && !this.options.location && !this.options.autoSaveCallback) {
throw new tg.DriverOptionNotSetError(`location or autoSaveCallback`);
}
this.loadDependencies();
}
async connect() {
this.databaseConnection = await this.createDatabaseConnection();
}
async disconnect() {
this.queryRunner = undefined;
this.databaseConnection.close();
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new ZT.SqljsQueryRunner(this);
return this.queryRunner;
}
async load(e, t = true) {
if (typeof e === "string") {
if (ng.PlatformTools.type === "node") {
if (ng.PlatformTools.fileExist(e)) {
const t = ng.PlatformTools.readFileSync(e);
return this.createDatabaseConnectionWithImport(t);
} else if (t) {
throw new rg.TypeORMError(`File ${e} does not exist`);
} else {
return this.createDatabaseConnectionWithImport();
}
} else {
let n = null;
if (this.options.useLocalForage) {
if (window.localforage) {
n = await window.localforage.getItem(e);
} else {
throw new rg.TypeORMError(`localforage is not defined - please import localforage.js into your site`);
}
} else {
n = ng.PlatformTools.getGlobalVariable().localStorage.getItem(e);
}
if (n != null) {
return this.createDatabaseConnectionWithImport(JSON.parse(n));
} else if (t) {
throw new rg.TypeORMError(`File ${e} does not exist`);
} else {
return this.createDatabaseConnectionWithImport();
}
}
} else {
return this.createDatabaseConnectionWithImport(e);
}
}
async save(e) {
if (!e && !this.options.location) {
throw new rg.TypeORMError(`No location is set, specify a location parameter or add the location option to your configuration`);
}
let t = "";
if (e) {
t = e;
} else if (this.options.location) {
t = this.options.location;
}
if (ng.PlatformTools.type === "node") {
try {
const e = Buffer.from(this.databaseConnection.export());
await ng.PlatformTools.writeFile(t, e);
} catch (e) {
throw new rg.TypeORMError(`Could not save database, error: ${e}`);
}
} else {
const e = this.databaseConnection.export();
const n = [].slice.call(e);
if (this.options.useLocalForage) {
if (window.localforage) {
await window.localforage.setItem(t, JSON.stringify(n));
} else {
throw new rg.TypeORMError(`localforage is not defined - please import localforage.js into your site`);
}
} else {
ng.PlatformTools.getGlobalVariable().localStorage.setItem(t, JSON.stringify(n));
}
}
}
async autoSave() {
if (this.options.autoSave && !this.queryRunner?.isTransactionActive) {
if (this.options.autoSaveCallback) {
await this.options.autoSaveCallback(this.export());
} else {
await this.save();
}
}
}
export() {
return this.databaseConnection.export();
}
createGeneratedMap(e, t) {
const n = e.generatedColumns.reduce((e, t) => {
if (t.isPrimary && t.generationStrategy === "increment") {
const n = "SELECT last_insert_rowid()";
try {
const a = this.databaseConnection.exec(n);
this.connection.logger.logQuery(n);
return ag.OrmUtils.mergeDeep(e, t.createValueMap(a[0].values[0][0]));
} catch (e) {
this.connection.logger.logQueryError(e, n, []);
}
}
return e;
}, {});
return Object.keys(n).length > 0 ? n : undefined;
}
createDatabaseConnection() {
if (this.options.location) {
return this.load(this.options.location, false);
}
return this.createDatabaseConnectionWithImport(this.options.database);
}
async createDatabaseConnectionWithImport(e) {
const t = typeof this.sqlite.Database === "function";
const n = t ? this.sqlite : await this.sqlite(this.options.sqlJsConfig);
if (e && e.length > 0) {
this.databaseConnection = new n.Database(e);
} else {
this.databaseConnection = new n.Database;
}
this.databaseConnection.exec(`PRAGMA foreign_keys = ON`);
return this.databaseConnection;
}
loadDependencies() {
if (ng.PlatformTools.type === "browser") {
const e = this.options.driver || window.SQL;
this.sqlite = e;
} else {
try {
const e = this.options.driver || ng.PlatformTools.load("sql.js");
this.sqlite = e;
} catch (e) {
throw new eg.DriverPackageNotInstalledError("sql.js", "sql.js");
}
}
}
}
VT.SqljsDriver = SqljsDriver;
var ig = {};
var sg = {};
Object.defineProperty(sg, "__esModule", {
value: true
});
sg.MysqlQueryRunner = void 0;
const og = P;
const cg = nn();
const lg = Sn();
const ug = pe();
const hg = Zm;
const dg = lf;
const pg = fu;
const mg = yu;
const fg = Nu;
const yg = Tu;
const Eg = Cu;
const Tg = Bm;
const gg = hf;
const Ng = sc;
const Ag = Te;
const bg = qc;
const Cg = us;
const Rg = ef;
const Sg = mf;
class MysqlQueryRunner extends hg.BaseQueryRunner {
constructor(e, t) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new gg.Broadcaster(this);
this.mode = t;
}
connect() {
if (this.databaseConnection) return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise) return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(e => {
this.databaseConnection = e;
return this.databaseConnection;
});
} else {
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(e => {
this.databaseConnection = e;
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
release() {
this.isReleased = true;
if (this.databaseConnection) this.databaseConnection.release();
return Promise.resolve();
}
async startTransaction(e) {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
if (e) {
await this.query("SET TRANSACTION ISOLATION LEVEL " + e);
}
await this.query("START TRANSACTION");
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new ug.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("COMMIT");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new ug.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("ROLLBACK");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new lg.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new Ng.BroadcasterResult;
const i = Date.now();
return new Promise(async (s, o) => {
try {
const c = this.driver.options.enableQueryTimeout;
const l = this.driver.options.maxQueryExecutionTime;
const u = c && l ? {
sql: e,
timeout: l
} : e;
a.query(u, t, async (a, c) => {
const l = this.driver.options.maxQueryExecutionTime;
const u = Date.now();
const h = u - i;
if (l && h > l) this.driver.connection.logger.logQuerySlow(h, e, t, this);
if (a) {
this.driver.connection.logger.logQueryError(a, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, a);
return o(new cg.QueryFailedError(e, t, a));
}
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, h, c, undefined);
const d = new dg.QueryResult;
d.raw = c;
try {
d.records = Array.from(c);
} catch {}
if (c?.hasOwnProperty("affectedRows")) {
d.affected = c.affectedRows;
}
if (n) {
s(d);
} else {
s(d.raw);
}
});
} catch (e) {
o(e);
} finally {
await r.wait();
}
});
}
stream(e, t, n, a) {
if (this.isReleased) throw new lg.QueryRunnerAlreadyReleasedError;
return new Promise(async (r, i) => {
try {
const i = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
const s = i.query(e, t);
if (n) s.on("end", n);
if (a) s.on("error", a);
r(s.stream());
} catch (e) {
i(e);
}
});
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
throw new og.TypeORMError(`MySql driver does not support table schemas`);
}
async hasDatabase(e) {
const t = await this.query(`SELECT * FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\` = '${e}'`);
return t.length ? true : false;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT DATABASE() AS \`db_name\``);
return e[0]["db_name"];
}
async hasSchema(e) {
throw new og.TypeORMError(`MySql driver does not support table schemas`);
}
async getCurrentSchema() {
const e = await this.query(`SELECT SCHEMA() AS \`schema_name\``);
return e[0]["schema_name"];
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
const n = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${t.database}' AND \`TABLE_NAME\` = '${t.tableName}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
const a = Ag.InstanceChecker.isTableColumn(t) ? t.name : t;
const r = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${n.database}' AND \`TABLE_NAME\` = '${n.tableName}' AND \`COLUMN_NAME\` = '${a}'`;
const i = await this.query(r);
return i.length ? true : false;
}
async createDatabase(e, t) {
const n = t ? `CREATE DATABASE IF NOT EXISTS \`${e}\`` : `CREATE DATABASE \`${e}\``;
const a = `DROP DATABASE \`${e}\``;
await this.executeQueries(new Rg.Query(n), new Rg.Query(a));
}
async dropDatabase(e, t) {
const n = t ? `DROP DATABASE IF EXISTS \`${e}\`` : `DROP DATABASE \`${e}\``;
const a = `CREATE DATABASE \`${e}\``;
await this.executeQueries(new Rg.Query(n), new Rg.Query(a));
}
async createSchema(e, t) {
throw new og.TypeORMError(`Schema create queries are not supported by MySql driver.`);
}
async dropSchema(e, t) {
throw new og.TypeORMError(`Schema drop queries are not supported by MySql driver.`);
}
async createTable(e, t = false, n = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const a = [];
const r = [];
a.push(this.createTableSql(e, n));
r.push(this.dropTableSql(e));
e.indices.forEach(t => r.push(this.dropIndexSql(e, t)));
if (n) e.foreignKeys.forEach(t => r.push(this.dropForeignKeySql(e, t)));
const i = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of i) {
const n = await this.getCurrentDatabase();
const i = this.insertTypeormMetadataSql({
schema: n,
table: e.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const s = this.deleteTypeormMetadataSql({
schema: n,
table: e.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
a.push(i);
r.push(s);
}
return this.executeQueries(a, r);
}
async dropTable(e, t, n = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const a = n;
const r = this.getTablePath(e);
const i = await this.getCachedTable(r);
const s = [];
const o = [];
if (n) i.foreignKeys.forEach(e => s.push(this.dropForeignKeySql(i, e)));
i.indices.forEach(e => s.push(this.dropIndexSql(i, e)));
s.push(this.dropTableSql(i));
o.push(this.createTableSql(i, a));
const c = i.columns.filter(e => e.generatedType && e.asExpression);
for (const e of c) {
const t = await this.getCurrentDatabase();
const n = this.deleteTypeormMetadataSql({
schema: t,
table: i.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const a = this.insertTypeormMetadataSql({
schema: t,
table: i.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
s.push(n);
o.push(a);
}
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = Ag.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {database: s} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new Rg.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(i)}`));
a.push(new Rg.Query(`RENAME TABLE ${this.escapePath(i)} TO ${this.escapePath(r)}`));
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames);
if (e.name !== t) return;
const s = e.columnNames.map(e => `\`${e}\``).join(", ");
const o = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
let c = "";
if (e.isUnique) c += "UNIQUE ";
if (e.isSpatial) c += "SPATIAL ";
if (e.isFulltext) c += "FULLTEXT ";
const l = e.isFulltext && e.parser ? ` WITH PARSER ${e.parser}` : "";
n.push(new Rg.Query(`ALTER TABLE ${this.escapePath(i)} DROP INDEX \`${e.name}\`, ADD ${c}INDEX \`${o}\` (${s})${l}`));
a.push(new Rg.Query(`ALTER TABLE ${this.escapePath(i)} DROP INDEX \`${o}\`, ADD ${c}INDEX \`${e.name}\` (${s})${l}`));
e.name = o;
});
i.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
const s = e.columnNames.map(e => `\`${e}\``).join(", ");
const o = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
const c = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
let l = `ALTER TABLE ${this.escapePath(i)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${c}\` FOREIGN KEY (${s}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${o})`;
if (e.onDelete) l += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) l += ` ON UPDATE ${e.onUpdate}`;
let u = `ALTER TABLE ${this.escapePath(i)} DROP FOREIGN KEY \`${c}\`, ADD CONSTRAINT \`${e.name}\` FOREIGN KEY (${s}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${o})`;
if (e.onDelete) u += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) u += ` ON UPDATE ${e.onUpdate}`;
n.push(new Rg.Query(l));
a.push(new Rg.Query(u));
e.name = c;
});
await this.executeQueries(n, a);
r.name = i.name;
this.replaceCachedTable(r, i);
}
async changeTableComment(e, t) {
const n = [];
const a = [];
const r = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
t = this.escapeComment(t);
const i = this.escapeComment(r.comment);
if (t === i) {
return;
}
const s = r.clone();
n.push(new Rg.Query(`ALTER TABLE ${this.escapePath(s)} COMMENT ${t}`));
a.push(new Rg.Query(`ALTER TABLE ${this.escapePath(r)} COMMENT ${i}`));
await this.executeQueries(n, a);
r.comment = s.comment;
this.replaceCachedTable(r, s);
}
async addColumn(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
const s = a.primaryColumns.length > 0;
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t, s, false)}`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${t.name}\``));
if (t.isPrimary && s) {
const e = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const a = e.clone();
a.isGenerated = false;
a.generationStrategy = undefined;
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
const s = a.primaryColumns;
let o = s.map(e => `\`${e.name}\``).join(", ");
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
s.push(t);
o = s.map(e => `\`${e.name}\``).join(", ");
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
if (e) {
const a = e.clone();
a.isGenerated = false;
a.generationStrategy = undefined;
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
}
}
if (t.generatedType && t.asExpression) {
const e = await this.getCurrentDatabase();
const a = this.insertTypeormMetadataSql({
schema: e,
table: n.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const s = this.deleteTypeormMetadataSql({
schema: e,
table: n.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(a);
i.push(s);
}
const o = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (o) {
r.push(this.createIndexSql(n, o));
i.push(this.dropIndexSql(n, o));
} else if (t.isUnique) {
const e = new yg.TableIndex({
name: this.connection.namingStrategy.indexName(n, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
});
a.indices.push(e);
a.uniques.push(new Eg.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
r.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${e.name}\` (\`${t.name}\`)`));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${e.name}\``));
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = Ag.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new og.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i = undefined;
if (Ag.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
await this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = Ag.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!o) throw new og.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (n.isGenerated !== o.isGenerated && n.generationStrategy !== "uuid" || o.type !== n.type || o.length !== n.length || o.generatedType && n.generatedType && o.generatedType !== n.generatedType || !o.generatedType && n.generatedType === "VIRTUAL" || o.generatedType === "VIRTUAL" && !n.generatedType) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.name !== o.name) {
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` \`${n.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${n.name}\` \`${o.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
r.findColumnIndices(o).forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const c = e.columnNames.map(e => `\`${e}\``).join(", ");
const l = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
let u = "";
if (e.isUnique) u += "UNIQUE ";
if (e.isSpatial) u += "SPATIAL ";
if (e.isFulltext) u += "FULLTEXT ";
const h = e.isFulltext && e.parser ? ` WITH PARSER ${e.parser}` : "";
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\`, ADD ${u}INDEX \`${l}\` (${c})${h}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${l}\`, ADD ${u}INDEX \`${e.name}\` (${c})${h}`));
e.name = l;
});
r.findColumnForeignKeys(o).forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const c = e.columnNames.map(e => `\`${e}\``).join(", ");
const l = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
const u = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
let h = `ALTER TABLE ${this.escapePath(a)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${u}\` FOREIGN KEY (${c}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${l})`;
if (e.onDelete) h += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) h += ` ON UPDATE ${e.onUpdate}`;
let d = `ALTER TABLE ${this.escapePath(a)} DROP FOREIGN KEY \`${u}\`, ADD CONSTRAINT \`${e.name}\` FOREIGN KEY (${c}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${l})`;
if (e.onDelete) d += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) d += ` ON UPDATE ${e.onUpdate}`;
i.push(new Rg.Query(h));
s.push(new Rg.Query(d));
e.name = u;
});
const e = r.columns.find(e => e.name === o.name);
r.columns[r.columns.indexOf(e)].name = n.name;
o.name = n.name;
}
if (this.isColumnChanged(o, n, true, true)) {
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(n, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${n.name}\` ${this.buildCreateColumnSql(o, true)}`));
if (o.generatedType && !n.generatedType) {
const e = await this.getCurrentDatabase();
const t = this.deleteTypeormMetadataSql({
schema: e,
table: a.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: o.name
});
const n = this.insertTypeormMetadataSql({
schema: e,
table: a.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: o.name,
value: o.asExpression
});
i.push(t);
s.push(n);
} else if (!o.generatedType && n.generatedType) {
const e = await this.getCurrentDatabase();
const t = this.insertTypeormMetadataSql({
schema: e,
table: a.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: n.name,
value: n.asExpression
});
const r = this.deleteTypeormMetadataSql({
schema: e,
table: a.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: n.name
});
i.push(t);
s.push(r);
} else if (o.asExpression !== n.asExpression) {
const e = await this.getCurrentDatabase();
const t = this.connection.createQueryBuilder().update(this.getTypeormMetadataTableName()).set({
value: n.asExpression
}).where("`type` = :type", {
type: Sg.MetadataTableType.GENERATED_COLUMN
}).andWhere("`name` = :name", {
name: o.name
}).andWhere("`schema` = :schema", {
schema: e
}).andWhere("`table` = :table", {
table: a.name
}).getQueryAndParameters();
const r = this.connection.createQueryBuilder().update(this.getTypeormMetadataTableName()).set({
value: o.asExpression
}).where("`type` = :type", {
type: Sg.MetadataTableType.GENERATED_COLUMN
}).andWhere("`name` = :name", {
name: n.name
}).andWhere("`schema` = :schema", {
schema: e
}).andWhere("`table` = :table", {
table: a.name
}).getQueryAndParameters();
i.push(new Rg.Query(t[0], t[1]));
s.push(new Rg.Query(r[0], r[1]));
}
}
if (n.isPrimary !== o.isPrimary) {
const e = r.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
}
const t = r.primaryColumns;
if (t.length > 0) {
const e = t.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
}
if (n.isPrimary === true) {
t.push(n);
const e = r.columns.find(e => e.name === n.name);
e.isPrimary = true;
const o = t.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${o})`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
} else {
const e = t.find(e => e.name === n.name);
t.splice(t.indexOf(e), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (t.length > 0) {
const e = t.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
}
}
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new yg.TableIndex({
name: this.connection.namingStrategy.indexName(a, [ n.name ]),
columnNames: [ n.name ],
isUnique: true
});
r.indices.push(e);
r.uniques.push(new Eg.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
} else {
const e = r.indices.find(e => e.columnNames.length === 1 && e.isUnique === true && !!e.columnNames.find(e => e === n.name));
r.indices.splice(r.indices.indexOf(e), 1);
const t = r.uniques.find(t => t.name === e.name);
r.uniques.splice(r.uniques.indexOf(t), 1);
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
}
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Ag.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new og.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = r.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
}
const t = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${t})`));
const o = r.findColumnByName(a.name);
o.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${e})`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
}
if (e && e.name !== a.name) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
} else if (a.isUnique) {
const e = this.connection.namingStrategy.uniqueConstraintName(n, [ a.name ]);
const t = r.uniques.find(t => t.name === e);
if (t) r.uniques.splice(r.uniques.indexOf(t), 1);
const o = this.connection.namingStrategy.indexName(n, [ a.name ]);
const c = r.indices.find(e => e.name === o);
if (c) r.indices.splice(r.indices.indexOf(c), 1);
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${o}\``));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${o}\` (\`${a.name}\`)`));
}
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${a.name}\``));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a, true)}`));
if (a.generatedType && a.asExpression) {
const e = await this.getCurrentDatabase();
const t = this.deleteTypeormMetadataSql({
schema: e,
table: n.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const r = this.insertTypeormMetadataSql({
schema: e,
table: n.name,
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(t);
s.push(r);
}
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = this.createPrimaryKeySql(n, t);
const i = this.dropPrimaryKeySql(n);
await this.executeQueries(r, i);
a.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
this.replaceCachedTable(n, a);
}
async updatePrimaryKeys(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = t.map(e => e.name);
const i = [];
const s = [];
const o = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (o) {
const e = o.clone();
e.isGenerated = false;
e.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(o, true)}`));
}
const c = a.primaryColumns;
if (c.length > 0) {
const e = c.map(e => `\`${e.name}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${e})`));
}
a.columns.filter(e => r.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const l = r.map(e => `\`${e}\``).join(", ");
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${l})`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
const u = o ? o : t.find(e => e.isGenerated && e.generationStrategy === "increment");
if (u) {
const e = u.clone();
e.isGenerated = false;
e.generationStrategy = undefined;
i.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(u, true)}`));
s.push(new Rg.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${u.name}\` ${this.buildCreateColumnSql(e, true)}`));
const t = a.columns.find(e => e.name === u.name);
t.isGenerated = true;
t.generationStrategy = "increment";
}
await this.executeQueries(i, s);
this.replaceCachedTable(n, a);
}
async dropPrimaryKey(e) {
const t = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const n = this.dropPrimaryKeySql(t);
const a = this.createPrimaryKeySql(t, t.primaryColumns.map(e => e.name));
await this.executeQueries(n, a);
t.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async createUniqueConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async createCheckConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support check constraints.`);
}
async createCheckConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support check constraints.`);
}
async dropCheckConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support check constraints.`);
}
async dropCheckConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support check constraints.`);
}
async createExclusionConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new og.TypeORMError(`MySql does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new og.TypeORMError(`MySql does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
const n = t.map(t => this.createForeignKey(e, t));
await Promise.all(n);
}
async dropForeignKey(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Ag.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new og.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
const n = t.map(t => this.dropForeignKey(e, t));
await Promise.all(n);
}
async createIndex(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t, true);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = Ag.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = Ag.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new og.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a, true);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase(e) {
const t = e ? e : this.driver.database;
if (t) {
const e = await this.hasDatabase(t);
if (!e) return Promise.resolve();
} else {
throw new og.TypeORMError(`Can not clear database. No database is specified`);
}
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = `SELECT concat('DROP VIEW IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`VIEWS\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
const a = await this.query(e);
await Promise.all(a.map(e => this.query(e["query"])));
const r = `SET FOREIGN_KEY_CHECKS = 0;`;
const i = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
const s = `SET FOREIGN_KEY_CHECKS = 1;`;
await this.query(r);
const o = await this.query(i);
await Promise.all(o.map(e => this.query(e["query"])));
await this.query(s);
if (!n) await this.commitTransaction();
} catch (e) {
try {
if (!n) await this.rollbackTransaction();
} catch (e) {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = e.map(e => {
let {database: t, tableName: a} = this.driver.parseTableName(e);
if (!t) {
t = n;
}
return `(\`t\`.\`schema\` = '${t}' AND \`t\`.\`name\` = '${a}')`;
}).join(" OR ");
const r = `SELECT \`t\`.*, \`v\`.\`check_option\` FROM ${this.escapePath(this.getTypeormMetadataTableName())} \`t\` ` + `INNER JOIN \`information_schema\`.\`views\` \`v\` ON \`v\`.\`table_schema\` = \`t\`.\`schema\` AND \`v\`.\`table_name\` = \`t\`.\`name\` WHERE \`t\`.\`type\` = '${Sg.MetadataTableType.VIEW}' ${a ? `AND (${a})` : ""}`;
const i = await this.query(r);
return i.map(e => {
const t = new Tg.View;
const a = e["schema"] === n ? undefined : e["schema"];
t.database = e["schema"];
t.name = this.driver.buildTableName(e["name"], undefined, a);
t.expression = e["value"];
return t;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = await this.getCurrentDatabase();
const n = [];
if (!e) {
const e = `SELECT \`TABLE_SCHEMA\`, \`TABLE_NAME\`, \`TABLE_COMMENT\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\``;
n.push(...await this.query(e));
} else {
const a = e.filter(e => e).map(e => {
let {database: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = t;
}
return `SELECT \`TABLE_SCHEMA\`, \`TABLE_NAME\`, \`TABLE_COMMENT\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${n}' AND \`TABLE_NAME\` = '${a}'`;
}).join(" UNION ");
n.push(...await this.query(a));
}
if (!n.length) return [];
const a = n.map(({TABLE_SCHEMA: e, TABLE_NAME: t}) => `\n SELECT\n *\n FROM \`INFORMATION_SCHEMA\`.\`STATISTICS\`\n WHERE\n \`TABLE_SCHEMA\` = '${e}'\n AND\n \`TABLE_NAME\` = '${t}'\n `).join(" UNION ");
const r = n.map(({TABLE_SCHEMA: e, TABLE_NAME: t}) => `\n SELECT\n *\n FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`kcu\`\n WHERE\n \`kcu\`.\`TABLE_SCHEMA\` = '${e}'\n AND\n \`kcu\`.\`TABLE_NAME\` = '${t}'\n `).join(" UNION ");
const i = n.map(({TABLE_SCHEMA: e, TABLE_NAME: t}) => `\n SELECT\n *\n FROM \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\`\n WHERE\n \`CONSTRAINT_SCHEMA\` = '${e}'\n AND\n \`TABLE_NAME\` = '${t}'\n `).join(" UNION ");
const s = n.map(({TABLE_SCHEMA: e, TABLE_NAME: t}) => `\n SELECT\n *\n FROM\n \`INFORMATION_SCHEMA\`.\`COLUMNS\`\n WHERE\n \`TABLE_SCHEMA\` = '${e}'\n AND\n \`TABLE_NAME\` = '${t}'\n `).join(" UNION ");
const o = `\n SELECT\n \`SCHEMA_NAME\`,\n \`DEFAULT_CHARACTER_SET_NAME\` as \`CHARSET\`,\n \`DEFAULT_COLLATION_NAME\` AS \`COLLATION\`\n FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\`\n `;
const c = `SELECT * FROM (${r}) \`kcu\` WHERE \`CONSTRAINT_NAME\` = 'PRIMARY'`;
const l = `\n SELECT\n \`s\`.*\n FROM (${a}) \`s\`\n LEFT JOIN (${i}) \`rc\`\n ON\n \`s\`.\`INDEX_NAME\` = \`rc\`.\`CONSTRAINT_NAME\`\n AND\n \`s\`.\`TABLE_SCHEMA\` = \`rc\`.\`CONSTRAINT_SCHEMA\`\n WHERE\n \`s\`.\`INDEX_NAME\` != 'PRIMARY'\n AND\n \`rc\`.\`CONSTRAINT_NAME\` IS NULL\n `;
const u = `\n SELECT\n \`kcu\`.\`TABLE_SCHEMA\`,\n \`kcu\`.\`TABLE_NAME\`,\n \`kcu\`.\`CONSTRAINT_NAME\`,\n \`kcu\`.\`COLUMN_NAME\`,\n \`kcu\`.\`REFERENCED_TABLE_SCHEMA\`,\n \`kcu\`.\`REFERENCED_TABLE_NAME\`,\n \`kcu\`.\`REFERENCED_COLUMN_NAME\`,\n \`rc\`.\`DELETE_RULE\` \`ON_DELETE\`,\n \`rc\`.\`UPDATE_RULE\` \`ON_UPDATE\`\n FROM (${r}) \`kcu\`\n INNER JOIN (${i}) \`rc\`\n ON\n \`rc\`.\`CONSTRAINT_SCHEMA\` = \`kcu\`.\`CONSTRAINT_SCHEMA\`\n AND\n \`rc\`.\`TABLE_NAME\` = \`kcu\`.\`TABLE_NAME\`\n AND\n \`rc\`.\`CONSTRAINT_NAME\` = \`kcu\`.\`CONSTRAINT_NAME\`\n `;
const [h, d, p, m, f] = await Promise.all([ this.query(s), this.query(c), this.query(o), this.query(l), this.query(u) ]);
const y = this.driver.options.type === "mariadb";
const E = this.driver.version;
return Promise.all(n.map(async e => {
const n = new pg.Table;
const a = p.find(t => t["SCHEMA_NAME"] === e["TABLE_SCHEMA"]);
const r = a["COLLATION"];
const i = a["CHARSET"];
const s = e["TABLE_SCHEMA"] === t ? undefined : e["TABLE_SCHEMA"];
n.database = e["TABLE_SCHEMA"];
n.name = this.driver.buildTableName(e["TABLE_NAME"], undefined, s);
n.columns = await Promise.all(h.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]).map(async t => {
const a = m.filter(n => n["TABLE_NAME"] === e["TABLE_NAME"] && n["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && n["COLUMN_NAME"] === t["COLUMN_NAME"] && parseInt(n["NON_UNIQUE"], 10) === 0);
const s = this.connection.entityMetadatas.find(e => this.getTablePath(n) === this.getTablePath(e));
const o = a.length > 0 && s && s.indices.some(e => a.some(t => e.name === t["INDEX_NAME"] && e.synchronize === false));
const c = a.every(e => m.some(n => n["INDEX_NAME"] === e["INDEX_NAME"] && n["COLUMN_NAME"] !== t["COLUMN_NAME"]));
const l = new mg.TableColumn;
l.name = t["COLUMN_NAME"];
l.type = t["DATA_TYPE"].toLowerCase();
if (l.type === "geomcollection") {
l.type = "geometrycollection";
}
l.zerofill = t["COLUMN_TYPE"].indexOf("zerofill") !== -1;
l.unsigned = l.zerofill ? true : t["COLUMN_TYPE"].indexOf("unsigned") !== -1;
if (this.driver.withWidthColumnTypes.indexOf(l.type) !== -1) {
const e = t["COLUMN_TYPE"].substring(t["COLUMN_TYPE"].indexOf("(") + 1, t["COLUMN_TYPE"].indexOf(")"));
l.width = e && !this.isDefaultColumnWidth(n, l, parseInt(e)) ? parseInt(e) : undefined;
}
if (t["COLUMN_DEFAULT"] === null || t["COLUMN_DEFAULT"] === undefined || y && t["COLUMN_DEFAULT"] === "NULL") {
l.default = undefined;
} else if (/^CURRENT_TIMESTAMP(\([0-9]*\))?$/i.test(t["COLUMN_DEFAULT"])) {
l.default = t["COLUMN_DEFAULT"].toUpperCase();
} else if (y && Cg.VersionUtils.isGreaterOrEqual(E, "10.2.7")) {
l.default = t["COLUMN_DEFAULT"];
} else {
l.default = `'${t["COLUMN_DEFAULT"]}'`;
}
if (t["EXTRA"].indexOf("on update") !== -1) {
l.onUpdate = t["EXTRA"].substring(t["EXTRA"].indexOf("on update") + 10).toUpperCase();
}
if (t["GENERATION_EXPRESSION"]) {
l.generatedType = t["EXTRA"].indexOf("VIRTUAL") !== -1 ? "VIRTUAL" : "STORED";
const n = this.selectTypeormMetadataSql({
schema: e["TABLE_SCHEMA"],
table: e["TABLE_NAME"],
type: Sg.MetadataTableType.GENERATED_COLUMN,
name: l.name
});
const a = await this.query(n.query, n.parameters);
if (a[0] && a[0].value) {
l.asExpression = a[0].value;
} else {
l.asExpression = "";
}
}
l.isUnique = a.length > 0 && !o && !c;
if (y && l.generatedType) ; else {
l.isNullable = t["IS_NULLABLE"] === "YES";
}
l.isPrimary = d.some(e => e["TABLE_NAME"] === t["TABLE_NAME"] && e["TABLE_SCHEMA"] === t["TABLE_SCHEMA"] && e["COLUMN_NAME"] === t["COLUMN_NAME"]);
l.isGenerated = t["EXTRA"].indexOf("auto_increment") !== -1;
if (l.isGenerated) l.generationStrategy = "increment";
l.comment = typeof t["COLUMN_COMMENT"] === "string" && t["COLUMN_COMMENT"].length === 0 ? undefined : t["COLUMN_COMMENT"];
if (t["CHARACTER_SET_NAME"]) l.charset = t["CHARACTER_SET_NAME"] === i ? undefined : t["CHARACTER_SET_NAME"];
if (t["COLLATION_NAME"]) l.collation = t["COLLATION_NAME"] === r ? undefined : t["COLLATION_NAME"];
if (this.driver.withLengthColumnTypes.indexOf(l.type) !== -1 && t["CHARACTER_MAXIMUM_LENGTH"]) {
const e = t["CHARACTER_MAXIMUM_LENGTH"].toString();
l.length = !this.isDefaultColumnLength(n, l, e) ? e : "";
}
if (l.type === "decimal" || l.type === "double" || l.type === "float") {
if (t["NUMERIC_PRECISION"] !== null && !this.isDefaultColumnPrecision(n, l, t["NUMERIC_PRECISION"])) l.precision = parseInt(t["NUMERIC_PRECISION"]);
if (t["NUMERIC_SCALE"] !== null && !this.isDefaultColumnScale(n, l, t["NUMERIC_SCALE"])) l.scale = parseInt(t["NUMERIC_SCALE"]);
}
if (l.type === "enum" || l.type === "simple-enum" || l.type === "set") {
const e = t["COLUMN_TYPE"];
const n = e.substring(e.indexOf("(") + 1, e.lastIndexOf(")")).split(",");
l.enum = n.map(e => e.substring(1, e.length - 1));
l.length = "";
}
if ((l.type === "datetime" || l.type === "time" || l.type === "timestamp") && t["DATETIME_PRECISION"] !== null && t["DATETIME_PRECISION"] !== undefined && !this.isDefaultColumnPrecision(n, l, parseInt(t["DATETIME_PRECISION"]))) {
l.precision = parseInt(t["DATETIME_PRECISION"]);
}
return l;
}));
const o = bg.OrmUtils.uniq(f.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]), e => e["CONSTRAINT_NAME"]);
n.foreignKeys = o.map(e => {
const n = f.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
const a = e["REFERENCED_TABLE_SCHEMA"] === t ? undefined : e["REFERENCED_TABLE_SCHEMA"];
const r = this.driver.buildTableName(e["REFERENCED_TABLE_NAME"], undefined, a);
return new fg.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: n.map(e => e["COLUMN_NAME"]),
referencedDatabase: e["REFERENCED_TABLE_SCHEMA"],
referencedTableName: r,
referencedColumnNames: n.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["ON_DELETE"],
onUpdate: e["ON_UPDATE"]
});
});
const c = bg.OrmUtils.uniq(m.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]), e => e["INDEX_NAME"]);
n.indices = c.map(e => {
const t = m.filter(t => t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_NAME"] === e["TABLE_NAME"] && t["INDEX_NAME"] === e["INDEX_NAME"]);
const a = parseInt(e["NON_UNIQUE"], 10);
return new yg.TableIndex({
table: n,
name: e["INDEX_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
isUnique: a === 0,
isSpatial: e["INDEX_TYPE"] === "SPATIAL",
isFulltext: e["INDEX_TYPE"] === "FULLTEXT"
});
});
n.comment = e["TABLE_COMMENT"];
return n;
}));
}
createTableSql(e, t) {
const n = e.columns.map(e => this.buildCreateColumnSql(e, true)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.indices.some(e => e.columnNames.length === 1 && !!e.isUnique && e.columnNames.indexOf(t.name) !== -1);
const a = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames.indexOf(t.name) !== -1);
if (!n && !a) e.indices.push(new yg.TableIndex({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
}));
});
if (e.uniques.length > 0) {
e.uniques.forEach(t => {
const n = e.indices.some(e => e.name === t.name);
if (!n) {
e.indices.push(new yg.TableIndex({
name: t.name,
columnNames: t.columnNames,
isUnique: true
}));
}
});
}
if (e.indices.length > 0) {
const t = e.indices.map(t => {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
let a = "";
if (t.isUnique) a += "UNIQUE ";
if (t.isSpatial) a += "SPATIAL ";
if (t.isFulltext) a += "FULLTEXT ";
const r = t.isFulltext && t.parser ? ` WITH PARSER ${t.parser}` : "";
return `${a}INDEX \`${t.name}\` (${n})${r}`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `\`${e}\``).join(", ");
let r = `CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return r;
}).join(", ");
a += `, ${t}`;
}
if (e.primaryColumns.length > 0) {
const t = e.primaryColumns.map(e => `\`${e.name}\``).join(", ");
a += `, PRIMARY KEY (${t})`;
}
a += `) ENGINE=${e.engine || "InnoDB"}`;
if (e.comment) {
a += ` COMMENT="${e.comment}"`;
}
return new Rg.Query(a);
}
dropTableSql(e) {
return new Rg.Query(`DROP TABLE ${this.escapePath(e)}`);
}
createViewSql(e) {
if (typeof e.expression === "string") {
return new Rg.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
} else {
return new Rg.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
const t = await this.getCurrentDatabase();
const n = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: Sg.MetadataTableType.VIEW,
schema: t,
name: e.name,
value: n
});
}
dropViewSql(e) {
return new Rg.Query(`DROP VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const t = await this.getCurrentDatabase();
const n = Ag.InstanceChecker.isView(e) ? e.name : e;
return this.deleteTypeormMetadataSql({
type: Sg.MetadataTableType.VIEW,
schema: t,
name: n
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
let a = "";
if (t.isUnique) a += "UNIQUE ";
if (t.isSpatial) a += "SPATIAL ";
if (t.isFulltext) a += "FULLTEXT ";
const r = t.isFulltext && t.parser ? ` WITH PARSER ${t.parser}` : "";
return new Rg.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})${r}`);
}
dropIndexSql(e, t) {
const n = Ag.InstanceChecker.isTableIndex(t) ? t.name : t;
return new Rg.Query(`DROP INDEX \`${n}\` ON ${this.escapePath(e)}`);
}
createPrimaryKeySql(e, t) {
const n = t.map(e => `\`${e}\``).join(", ");
return new Rg.Query(`ALTER TABLE ${this.escapePath(e)} ADD PRIMARY KEY (${n})`);
}
dropPrimaryKeySql(e) {
return new Rg.Query(`ALTER TABLE ${this.escapePath(e)} DROP PRIMARY KEY`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
const a = t.referencedColumnNames.map(e => `\`${e}\``).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return new Rg.Query(r);
}
dropForeignKeySql(e, t) {
const n = Ag.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new Rg.Query(`ALTER TABLE ${this.escapePath(e)} DROP FOREIGN KEY \`${n}\``);
}
escapeComment(e) {
if (!e || e.length === 0) {
return `''`;
}
e = e.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\u0000/g, "");
return `'${e}'`;
}
escapePath(e) {
const {database: t, tableName: n} = this.driver.parseTableName(e);
if (t && t !== this.driver.database) {
return `\`${t}\`.\`${n}\``;
}
return `\`${n}\``;
}
buildCreateColumnSql(e, t, n = false) {
let a = "";
if (n) {
a = this.connection.driver.createFullType(e);
} else {
a = `\`${e.name}\` ${this.connection.driver.createFullType(e)}`;
}
if (e.charset) a += ` CHARACTER SET "${e.charset}"`;
if (e.collation) a += ` COLLATE "${e.collation}"`;
if (e.asExpression) a += ` AS (${e.asExpression}) ${e.generatedType ? e.generatedType : "VIRTUAL"}`;
if (e.zerofill) {
a += " ZEROFILL";
} else if (e.unsigned) {
a += " UNSIGNED";
}
if (e.enum) a += ` (${e.enum.map(e => "'" + e.replace(/'/g, "''") + "'").join(", ")})`;
const r = this.driver.options.type === "mariadb";
if (r && e.asExpression && [ "VIRTUAL", "STORED" ].includes(e.generatedType || "VIRTUAL")) ; else {
if (!e.isNullable) a += " NOT NULL";
if (e.isNullable) a += " NULL";
}
if (e.isPrimary && !t) a += " PRIMARY KEY";
if (e.isGenerated && e.generationStrategy === "increment") a += " AUTO_INCREMENT";
if (e.comment && e.comment.length > 0) a += ` COMMENT ${this.escapeComment(e.comment)}`;
if (e.default !== undefined && e.default !== null) a += ` DEFAULT ${e.default}`;
if (e.onUpdate) a += ` ON UPDATE ${e.onUpdate}`;
return a;
}
async getVersion() {
const e = await this.query(`SELECT VERSION() AS \`version\``);
const t = e[0].version;
return t.replace(/^([\d.]+).*$/, "$1");
}
isDefaultColumnWidth(e, t, n) {
if (this.connection.hasMetadata(e.name)) {
const n = this.connection.getMetadata(e.name);
const a = n.findColumnWithDatabaseName(t.name);
if (a && a.width) return false;
}
const a = this.connection.driver.dataTypeDefaults && this.connection.driver.dataTypeDefaults[t.type] && this.connection.driver.dataTypeDefaults[t.type].width;
if (a) {
const e = [ "int", "tinyint", "smallint", "mediumint" ];
const r = e.indexOf(t.type) !== -1;
if (t.unsigned && r) {
return a - 1 === n;
} else {
return a === n;
}
}
return false;
}
}
sg.MysqlQueryRunner = MysqlQueryRunner;
Object.defineProperty(ig, "__esModule", {
value: true
});
ig.MysqlDriver = void 0;
const wg = Y();
const Mg = Tt();
const Og = jn;
const vg = sg;
const Ig = up;
const Pg = Uh;
const Lg = Um;
const Dg = qc;
const _g = _s;
const $g = P;
const xg = us;
const qg = Te;
class MysqlDriver {
constructor(e) {
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "bit", "int", "integer", "tinyint", "smallint", "mediumint", "bigint", "float", "double", "double precision", "real", "decimal", "dec", "numeric", "fixed", "bool", "boolean", "date", "datetime", "timestamp", "time", "year", "char", "nchar", "national char", "varchar", "nvarchar", "national varchar", "blob", "text", "tinyblob", "tinytext", "mediumblob", "mediumtext", "longblob", "longtext", "enum", "set", "binary", "varbinary", "json", "geometry", "point", "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", "geometrycollection", "uuid", "inet4", "inet6" ];
this.supportedUpsertTypes = [ "on-duplicate-key-update" ];
this.spatialTypes = [ "geometry", "point", "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", "geometrycollection" ];
this.withLengthColumnTypes = [ "char", "varchar", "nvarchar", "binary", "varbinary" ];
this.withWidthColumnTypes = [ "bit", "tinyint", "smallint", "mediumint", "int", "integer", "bigint" ];
this.withPrecisionColumnTypes = [ "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real", "time", "datetime", "timestamp" ];
this.withScaleColumnTypes = [ "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real" ];
this.unsignedAndZerofillTypes = [ "int", "integer", "smallint", "tinyint", "mediumint", "bigint", "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real" ];
this.mappedDataTypes = {
createDate: "datetime",
createDatePrecision: 6,
createDateDefault: "CURRENT_TIMESTAMP(6)",
updateDate: "datetime",
updateDatePrecision: 6,
updateDateDefault: "CURRENT_TIMESTAMP(6)",
deleteDate: "datetime",
deleteDatePrecision: 6,
deleteDateNullable: true,
version: "int",
treeLevel: "int",
migrationId: "int",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "varchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text"
};
this.dataTypeDefaults = {
varchar: {
length: 255
},
nvarchar: {
length: 255
},
"national varchar": {
length: 255
},
char: {
length: 1
},
binary: {
length: 1
},
varbinary: {
length: 255
},
decimal: {
precision: 10,
scale: 0
},
dec: {
precision: 10,
scale: 0
},
numeric: {
precision: 10,
scale: 0
},
fixed: {
precision: 10,
scale: 0
},
float: {
precision: 12
},
double: {
precision: 22
},
time: {
precision: 0
},
datetime: {
precision: 0
},
timestamp: {
precision: 0
},
bit: {
width: 1
},
int: {
width: 11
},
integer: {
width: 11
},
tinyint: {
width: 4
},
smallint: {
width: 6
},
mediumint: {
width: 9
},
bigint: {
width: 20
}
};
this.maxAliasLength = 63;
this.cteCapabilities = {
enabled: false,
requiresRecursiveHint: true
};
this._isReturningSqlSupported = {
delete: false,
insert: false,
update: false
};
this.uuidColumnTypeSuported = false;
this.connection = e;
this.options = {
legacySpatialSupport: true,
...e.options
};
this.isReplicated = this.options.replication ? true : false;
this.loadDependencies();
this.database = Og.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
}
async connect() {
if (this.options.replication) {
this.poolCluster = this.mysql.createPoolCluster(this.options.replication);
this.options.replication.slaves.forEach((e, t) => {
this.poolCluster.add("SLAVE" + t, this.createConnectionOptions(this.options, e));
});
this.poolCluster.add("MASTER", this.createConnectionOptions(this.options, this.options.replication.master));
} else {
this.pool = await this.createPool(this.createConnectionOptions(this.options, this.options));
}
if (!this.database) {
const e = this.createQueryRunner("master");
this.database = await e.getCurrentDatabase();
await e.release();
}
const e = this.createQueryRunner("master");
this.version = await e.getVersion();
await e.release();
if (this.options.type === "mariadb") {
if (xg.VersionUtils.isGreaterOrEqual(this.version, "10.0.5")) {
this._isReturningSqlSupported.delete = true;
}
if (xg.VersionUtils.isGreaterOrEqual(this.version, "10.5.0")) {
this._isReturningSqlSupported.insert = true;
}
if (xg.VersionUtils.isGreaterOrEqual(this.version, "10.2.0")) {
this.cteCapabilities.enabled = true;
}
if (xg.VersionUtils.isGreaterOrEqual(this.version, "10.7.0")) {
this.uuidColumnTypeSuported = true;
}
} else if (this.options.type === "mysql") {
if (xg.VersionUtils.isGreaterOrEqual(this.version, "8.0.0")) {
this.cteCapabilities.enabled = true;
}
}
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
if (!this.poolCluster && !this.pool) return Promise.reject(new wg.ConnectionIsNotSetError("mysql"));
if (this.poolCluster) {
return new Promise((e, t) => {
this.poolCluster.end(n => n ? t(n) : e());
this.poolCluster = undefined;
});
}
if (this.pool) {
return new Promise((e, t) => {
this.pool.end(n => {
if (n) return t(n);
this.pool = undefined;
e();
});
});
}
}
createSchemaBuilder() {
return new Lg.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new vg.MysqlQueryRunner(this, e);
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, r) => {
if (!t.hasOwnProperty(r)) {
return e;
}
const i = t[r];
if (n) {
return i.map(e => {
a.push(e);
return this.createParameter(r, a.length - 1);
}).join(", ");
}
if (typeof i === "function") {
return i();
}
a.push(i);
return this.createParameter(r, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return "`" + e + "`";
}
buildTableName(e, t, n) {
const a = [ e ];
if (n) {
a.unshift(n);
}
return a.join(".");
}
parseTableName(e) {
const t = this.database;
const n = undefined;
if (qg.InstanceChecker.isTable(e) || qg.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (qg.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (qg.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: (a.length > 1 ? a[0] : undefined) || t,
schema: n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
preparePersistentValue(e, t) {
if (t.transformer) e = _g.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return Ig.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return Ig.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "json") {
return JSON.stringify(e);
} else if (t.type === "timestamp" || t.type === "datetime" || t.type === Date) {
return Ig.DateUtils.mixedDateToDate(e);
} else if (t.type === "simple-array") {
return Ig.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return Ig.DateUtils.simpleJsonToString(e);
} else if (t.type === "enum" || t.type === "simple-enum") {
return "" + e;
} else if (t.type === "set") {
return Ig.DateUtils.simpleArrayToString(e);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? _g.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean || t.type === "bool" || t.type === "boolean") {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date) {
e = Ig.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = Ig.DateUtils.mixedDateToDateString(e);
} else if (t.type === "json") {
e = typeof e === "string" ? JSON.parse(e) : e;
} else if (t.type === "time") {
e = Ig.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array") {
e = Ig.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = Ig.DateUtils.stringToSimpleJson(e);
} else if ((t.type === "enum" || t.type === "simple-enum") && t.enum && !isNaN(e) && t.enum.indexOf(parseInt(e)) >= 0) {
e = parseInt(e);
} else if (t.type === "set") {
e = Ig.DateUtils.stringToSimpleArray(e);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = _g.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number || e.type === "integer") {
return "int";
} else if (e.type === String) {
return "varchar";
} else if (e.type === Date) {
return "datetime";
} else if (e.type === Buffer) {
return "blob";
} else if (e.type === Boolean) {
return "tinyint";
} else if (e.type === "uuid" && !this.uuidColumnTypeSuported) {
return "varchar";
} else if (e.type === "json" && this.options.type === "mariadb" && !xg.VersionUtils.isGreaterOrEqual(this.version, "10.4.3")) {
return "longtext";
} else if (e.type === "simple-array" || e.type === "simple-json") {
return "text";
} else if (e.type === "simple-enum") {
return "enum";
} else if (e.type === "double precision" || e.type === "real") {
return "double";
} else if (e.type === "dec" || e.type === "numeric" || e.type === "fixed") {
return "decimal";
} else if (e.type === "bool" || e.type === "boolean") {
return "tinyint";
} else if (e.type === "nvarchar" || e.type === "national varchar") {
return "varchar";
} else if (e.type === "nchar" || e.type === "national char") {
return "char";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (t === null) {
return undefined;
}
if ((e.type === "enum" || e.type === "simple-enum" || typeof t === "string") && t !== undefined) {
return `'${t}'`;
}
if (e.type === "set" && t !== undefined) {
return `'${Ig.DateUtils.simpleArrayToString(t)}'`;
}
if (typeof t === "number") {
return `'${t.toFixed(e.scale)}'`;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
const e = t();
return this.normalizeDatetimeFunction(e);
}
if (t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.indices.some(t => t.isUnique && t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
if (e.generationStrategy === "uuid" && !this.uuidColumnTypeSuported) return "36";
switch (e.type) {
case String:
case "varchar":
case "nvarchar":
case "national varchar":
return "255";
case "varbinary":
return "255";
default:
return "";
}
}
createFullType(e) {
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.width) {
t += `(${e.width})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += `(${e.precision},${e.scale})`;
} else if (e.precision !== null && e.precision !== undefined) {
t += `(${e.precision})`;
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
return new Promise((e, t) => {
if (this.poolCluster) {
this.poolCluster.getConnection("MASTER", (n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
} else if (this.pool) {
this.pool.getConnection((n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
} else {
t(new $g.TypeORMError(`Connection is not established with mysql database`));
}
});
}
obtainSlaveConnection() {
if (!this.poolCluster) return this.obtainMasterConnection();
return new Promise((e, t) => {
this.poolCluster.getConnection("SLAVE*", (n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
});
}
createGeneratedMap(e, t, n) {
if (!t) {
return undefined;
}
if (t.insertId === undefined) {
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
Dg.OrmUtils.mergeDeep(n, r.createValueMap(t[a]));
}
return n;
}, {});
}
const a = e.generatedColumns.reduce((e, a) => {
let r;
if (a.generationStrategy === "increment" && t.insertId) {
r = t.insertId + n;
}
return Dg.OrmUtils.mergeDeep(e, a.createValueMap(r));
}, {});
return Object.keys(a).length > 0 ? a : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || this.isColumnDataTypeChanged(n, t) || n.length !== this.getColumnLength(t) || n.width !== t.width || t.precision !== undefined && n.precision !== t.precision || t.scale !== undefined && n.scale !== t.scale || n.zerofill !== t.zerofill || n.unsigned !== t.unsigned || n.asExpression !== t.asExpression || n.generatedType !== t.generatedType || n.comment !== this.escapeComment(t.comment) || !this.compareDefaultValues(this.normalizeDefault(t), n.default) || n.enum && t.enum && !Dg.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || n.onUpdate !== this.normalizeDatetimeFunction(t.onUpdate) || n.isPrimary !== t.isPrimary || !this.compareNullableValues(t, n) || n.isUnique !== this.normalizeIsUnique(t) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
return a;
});
}
isReturningSqlSupported(e) {
return this._isReturningSqlSupported[e];
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return true;
}
createParameter(e, t) {
return "?";
}
loadDependencies() {
const e = this.options.connectorPackage ?? "mysql";
const t = e === "mysql" ? "mysql2" : "mysql";
try {
const n = this.options.driver || Pg.PlatformTools.load(e);
this.mysql = n;
if (Object.keys(this.mysql).length === 0) {
throw new $g.TypeORMError(`'${e}' was found but it is empty. Falling back to '${t}'.`);
}
} catch (n) {
try {
this.mysql = Pg.PlatformTools.load(t);
} catch (t) {
throw new Mg.DriverPackageNotInstalledError("Mysql", e);
}
}
}
createConnectionOptions(e, t) {
t = Object.assign({}, t, Og.DriverUtils.buildDriverOptions(t));
return Object.assign({}, {
charset: e.charset,
timezone: e.timezone,
connectTimeout: e.connectTimeout,
insecureAuth: e.insecureAuth,
supportBigNumbers: e.supportBigNumbers !== undefined ? e.supportBigNumbers : true,
bigNumberStrings: e.bigNumberStrings !== undefined ? e.bigNumberStrings : true,
dateStrings: e.dateStrings,
debug: e.debug,
trace: e.trace,
multipleStatements: e.multipleStatements,
flags: e.flags
}, {
host: t.host,
user: t.username,
password: t.password,
database: t.database,
port: t.port,
ssl: e.ssl,
socketPath: t.socketPath
}, e.acquireTimeout === undefined ? {} : {
acquireTimeout: e.acquireTimeout
}, {
connectionLimit: e.poolSize
}, e.extra || {});
}
createPool(e) {
const t = this.mysql.createPool(e);
return new Promise((e, n) => {
t.getConnection((a, r) => {
if (a) return t.end(() => n(a));
r.release();
e(t);
});
});
}
prepareDbConnection(e) {
const {logger: t} = this.connection;
if (e.listeners("error").length === 0) {
e.on("error", e => t.log("warn", `MySQL connection raised an error. ${e}`));
}
return e;
}
compareDefaultValues(e, t) {
if (typeof e === "string" && typeof t === "string") {
e = e.replace(/^'+|'+$/g, "");
t = t.replace(/^'+|'+$/g, "");
}
return e === t;
}
compareNullableValues(e, t) {
const n = this.options.type === "mariadb";
if (n && e.generatedType) {
return true;
}
return e.isNullable === t.isNullable;
}
normalizeDatetimeFunction(e) {
if (!e) return e;
const t = e.toUpperCase().indexOf("CURRENT_TIMESTAMP") !== -1 || e.toUpperCase().indexOf("NOW") !== -1;
if (t) {
const t = e.match(/\(\d+\)/);
if (this.options.type === "mariadb") {
return t ? `CURRENT_TIMESTAMP${t[0]}` : "CURRENT_TIMESTAMP()";
} else {
return t ? `CURRENT_TIMESTAMP${t[0]}` : "CURRENT_TIMESTAMP";
}
} else {
return e;
}
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/\u0000/g, "");
return e;
}
isColumnDataTypeChanged(e, t) {
if (this.normalizeType(t) === "json" && e.type.toLowerCase() === "longtext") return false;
return e.type !== this.normalizeType(t);
}
}
ig.MysqlDriver = MysqlDriver;
var Ug = {};
var Bg = {};
Object.defineProperty(Bg, "__esModule", {
value: true
});
Bg.PostgresQueryRunner = void 0;
const Fg = P;
const jg = nn();
const kg = Sn();
const Qg = pe();
const Vg = Zm;
const Kg = lf;
const Wg = fu;
const Hg = Su;
const Gg = yu;
const Yg = Mu;
const zg = Nu;
const Jg = Tu;
const Xg = Cu;
const Zg = Bm;
const eN = hf;
const tN = sc;
const nN = Te;
const aN = qc;
const rN = jn;
const iN = ef;
const sN = mf;
class PostgresQueryRunner extends Vg.BaseQueryRunner {
constructor(e, t) {
super();
this.driver = e;
this.connection = e.connection;
this.mode = t;
this.broadcaster = new eN.Broadcaster(this);
}
connect() {
if (this.databaseConnection) return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise) return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
const n = e => this.releasePostgresConnection(e);
this.releaseCallback = e => {
this.databaseConnection.removeListener("error", n);
t(e);
};
this.databaseConnection.on("error", n);
return this.databaseConnection;
});
} else {
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
const n = e => this.releasePostgresConnection(e);
this.releaseCallback = e => {
this.databaseConnection.removeListener("error", n);
t(e);
};
this.databaseConnection.on("error", n);
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
async releasePostgresConnection(e) {
if (this.isReleased) {
return;
}
this.isReleased = true;
if (this.releaseCallback) {
this.releaseCallback(e);
this.releaseCallback = undefined;
}
const t = this.driver.connectedQueryRunners.indexOf(this);
if (t !== -1) {
this.driver.connectedQueryRunners.splice(t, 1);
}
}
release() {
return this.releasePostgresConnection();
}
async startTransaction(e) {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
await this.query("START TRANSACTION");
if (e) {
await this.query("SET TRANSACTION ISOLATION LEVEL " + e);
}
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new Qg.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("COMMIT");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new Qg.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.query("ROLLBACK");
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new kg.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const r = new tN.BroadcasterResult;
try {
const i = Date.now();
const s = await a.query(e, t);
const o = this.driver.options.maxQueryExecutionTime;
const c = Date.now();
const l = c - i;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, s, undefined);
if (o && l > o) this.driver.connection.logger.logQuerySlow(l, e, t, this);
const u = new Kg.QueryResult;
if (s) {
if (s.hasOwnProperty("rows")) {
u.records = s.rows;
}
if (s.hasOwnProperty("rowCount")) {
u.affected = s.rowCount;
}
switch (s.command) {
case "DELETE":
case "UPDATE":
u.raw = [ s.rows, s.rowCount ];
break;
default:
u.raw = s.rows;
}
if (!n) {
return u.raw;
}
}
return u;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, undefined, undefined, n);
throw new jg.QueryFailedError(e, t, n);
} finally {
await r.wait();
}
}
async stream(e, t, n, a) {
const r = this.driver.loadStreamDependency();
if (this.isReleased) throw new kg.QueryRunnerAlreadyReleasedError;
const i = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
const s = i.query(new r(e, t));
if (n) s.on("end", n);
if (a) s.on("error", a);
return s;
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
return Promise.resolve([]);
}
async hasDatabase(e) {
const t = await this.query(`SELECT * FROM pg_database WHERE datname='${e}';`);
return t.length ? true : false;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT * FROM current_database()`);
return e[0]["current_database"];
}
async hasSchema(e) {
const t = await this.query(`SELECT * FROM "information_schema"."schemata" WHERE "schema_name" = '${e}'`);
return t.length ? true : false;
}
async getCurrentSchema() {
const e = await this.query(`SELECT * FROM current_schema()`);
return e[0]["current_schema"];
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = `SELECT * FROM "information_schema"."tables" WHERE "table_schema" = '${t.schema}' AND "table_name" = '${t.tableName}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = `SELECT * FROM "information_schema"."columns" WHERE "table_schema" = '${n.schema}' AND "table_name" = '${n.tableName}' AND "column_name" = '${t}'`;
const r = await this.query(a);
return r.length ? true : false;
}
async createDatabase(e, t) {
if (t) {
const t = await this.hasDatabase(e);
if (t) return Promise.resolve();
}
const n = `CREATE DATABASE "${e}"`;
const a = `DROP DATABASE "${e}"`;
await this.executeQueries(new iN.Query(n), new iN.Query(a));
}
async dropDatabase(e, t) {
const n = t ? `DROP DATABASE IF EXISTS "${e}"` : `DROP DATABASE "${e}"`;
const a = `CREATE DATABASE "${e}"`;
await this.executeQueries(new iN.Query(n), new iN.Query(a));
}
async createSchema(e, t) {
const n = e.indexOf(".") === -1 ? e : e.split(".")[1];
const a = t ? `CREATE SCHEMA IF NOT EXISTS "${n}"` : `CREATE SCHEMA "${n}"`;
const r = `DROP SCHEMA "${n}" CASCADE`;
await this.executeQueries(new iN.Query(a), new iN.Query(r));
}
async dropSchema(e, t, n) {
const a = e.indexOf(".") === -1 ? e : e.split(".")[1];
const r = t ? `DROP SCHEMA IF EXISTS "${a}" ${n ? "CASCADE" : ""}` : `DROP SCHEMA "${a}" ${n ? "CASCADE" : ""}`;
const i = `CREATE SCHEMA "${a}"`;
await this.executeQueries(new iN.Query(r), new iN.Query(i));
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
const s = e.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
const o = [];
for (const t of s) {
const n = await this.hasEnumType(e, t);
const a = this.buildEnumName(e, t);
if (!n && o.indexOf(a) === -1) {
o.push(a);
r.push(this.createEnumTypeSql(e, t, a));
i.push(this.dropEnumTypeSql(e, t, a));
}
}
const c = e.columns.filter(e => e.generatedType === "STORED" && e.asExpression);
for (const t of c) {
const n = (await this.getTableNameWithSchema(e.name)).split(".");
const a = n[1];
const s = n[0];
const o = this.insertTypeormMetadataSql({
database: this.driver.database,
schema: s,
table: a,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const c = this.deleteTypeormMetadataSql({
database: this.driver.database,
schema: s,
table: a,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(o);
i.push(c);
}
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(e, t));
});
}
if (e.comment) {
r.push(new iN.Query("COMMENT ON TABLE " + this.escapePath(e) + " IS '" + e.comment + "'"));
i.push(new iN.Query("COMMENT ON TABLE " + this.escapePath(e) + " IS NULL"));
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = this.getTablePath(e);
const s = await this.getCachedTable(i);
const o = [];
const c = [];
if (a) {
s.indices.forEach(e => {
o.push(this.dropIndexSql(s, e));
c.push(this.createIndexSql(s, e));
});
}
if (n) s.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(s, e)));
o.push(this.dropTableSql(s));
c.push(this.createTableSql(s, r));
const l = s.columns.filter(e => e.generatedType && e.asExpression);
for (const e of l) {
const t = (await this.getTableNameWithSchema(s.name)).split(".");
const n = t[1];
const a = t[0];
const r = this.deleteTypeormMetadataSql({
database: this.driver.database,
schema: a,
table: n,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const i = this.insertTypeormMetadataSql({
database: this.driver.database,
schema: a,
table: n,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
o.push(r);
c.push(i);
}
await this.executeQueries(o, c);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = nN.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {schema: s, tableName: o} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new iN.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
a.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME TO "${o}"`));
if (i.primaryColumns.length > 0 && !i.primaryColumns[0].primaryKeyConstraintName) {
const e = i.primaryColumns.map(e => e.name);
const t = this.connection.namingStrategy.primaryKeyName(r, e);
const s = this.connection.namingStrategy.primaryKeyName(i, e);
n.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${t}" TO "${s}"`));
a.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${t}"`));
}
i.columns.map(e => {
if (e.isGenerated && e.generationStrategy === "increment") {
const t = this.buildSequencePath(r, e.name);
const s = this.buildSequenceName(r, e.name);
const o = this.buildSequencePath(i, e.name);
const c = this.buildSequenceName(i, e.name);
const l = `ALTER SEQUENCE ${this.escapePath(t)} RENAME TO "${c}"`;
const u = `ALTER SEQUENCE ${this.escapePath(o)} RENAME TO "${s}"`;
n.push(new iN.Query(l));
a.push(new iN.Query(u));
}
});
i.uniques.forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.uniqueConstraintName(i, e.columnNames);
n.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
const {schema: s} = this.driver.parseTableName(i);
const o = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
const c = s ? `ALTER INDEX "${s}"."${e.name}" RENAME TO "${o}"` : `ALTER INDEX "${e.name}" RENAME TO "${o}"`;
const l = s ? `ALTER INDEX "${s}"."${o}" RENAME TO "${e.name}"` : `ALTER INDEX "${o}" RENAME TO "${e.name}"`;
n.push(new iN.Query(c));
a.push(new iN.Query(l));
e.name = o;
});
i.foreignKeys.forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
const s = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
n.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${e.name}" TO "${s}"`));
a.push(new iN.Query(`ALTER TABLE ${this.escapePath(i)} RENAME CONSTRAINT "${s}" TO "${e.name}"`));
e.name = s;
});
const c = i.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
for (const e of c) {
if (e.enumName) continue;
const t = await this.getUserDefinedTypeName(r, e);
n.push(new iN.Query(`ALTER TYPE "${t.schema}"."${t.name}" RENAME TO ${this.buildEnumName(i, e, false)}`));
a.push(new iN.Query(`ALTER TYPE ${this.buildEnumName(i, e)} RENAME TO "${t.name}"`));
}
await this.executeQueries(n, a);
}
async addColumn(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
if (t.type === "enum" || t.type === "simple-enum") {
const e = await this.hasEnumType(n, t);
if (!e) {
r.push(this.createEnumTypeSql(n, t));
i.push(this.dropEnumTypeSql(n, t));
}
}
r.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t)}`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${t.name}"`));
if (t.isPrimary) {
const e = a.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const s = e.map(e => `"${e.name}"`).join(", ");
r.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${s})`));
}
e.push(t);
const s = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, e.map(e => e.name));
const o = e.map(e => `"${e.name}"`).join(", ");
r.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${s}" PRIMARY KEY (${o})`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${s}"`));
}
const s = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (s) {
r.push(this.createIndexSql(n, s));
i.push(this.dropIndexSql(n, s));
}
if (t.isUnique) {
const e = new Xg.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
columnNames: [ t.name ]
});
a.uniques.push(e);
r.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e.name}"`));
}
if (t.generatedType === "STORED" && t.asExpression) {
const e = (await this.getTableNameWithSchema(n.name)).split(".");
const a = e[1];
const s = e[0];
const o = this.insertTypeormMetadataSql({
database: this.driver.database,
schema: s,
table: a,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const c = this.deleteTypeormMetadataSql({
database: this.driver.database,
schema: s,
table: a,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(o);
i.push(c);
}
if (t.comment) {
r.push(new iN.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
i.push(new iN.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = nN.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new Fg.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i;
if (nN.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
return this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
let o = false;
const c = nN.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!c) throw new Fg.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (c.type !== n.type || c.length !== n.length || n.isArray !== c.isArray || !c.generatedType && n.generatedType === "STORED" || c.asExpression !== n.asExpression && n.generatedType === "STORED") {
await this.dropColumn(a, c);
await this.addColumn(a, n);
r = a.clone();
} else {
if (c.name !== n.name) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "${n.name}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${n.name}" TO "${c.name}"`));
if (c.type === "enum" || c.type === "simple-enum") {
const e = await this.getUserDefinedTypeName(a, c);
i.push(new iN.Query(`ALTER TYPE "${e.schema}"."${e.name}" RENAME TO ${this.buildEnumName(a, n, false)}`));
s.push(new iN.Query(`ALTER TYPE ${this.buildEnumName(a, n)} RENAME TO "${e.name}"`));
}
if (c.isPrimary === true && !c.primaryKeyConstraintName) {
const e = r.primaryColumns;
const t = e.map(e => e.name);
const o = this.connection.namingStrategy.primaryKeyName(r, t);
t.splice(t.indexOf(c.name), 1);
t.push(n.name);
const l = this.connection.namingStrategy.primaryKeyName(r, t);
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${l}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${l}" TO "${o}"`));
}
if (c.isGenerated === true && n.generationStrategy === "increment") {
const e = this.buildSequencePath(a, c.name);
const t = this.buildSequenceName(a, c.name);
const r = this.buildSequencePath(a, n.name);
const o = this.buildSequenceName(a, n.name);
const l = `ALTER SEQUENCE ${this.escapePath(e)} RENAME TO "${o}"`;
const u = `ALTER SEQUENCE ${this.escapePath(r)} RENAME TO "${t}"`;
i.push(new iN.Query(l));
s.push(new iN.Query(u));
}
r.findColumnUniques(c).forEach(e => {
const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const o = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${e.name}"`));
e.name = o;
});
r.findColumnIndices(c).forEach(e => {
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const {schema: o} = this.driver.parseTableName(a);
const l = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
const u = o ? `ALTER INDEX "${o}"."${e.name}" RENAME TO "${l}"` : `ALTER INDEX "${e.name}" RENAME TO "${l}"`;
const h = o ? `ALTER INDEX "${o}"."${l}" RENAME TO "${e.name}"` : `ALTER INDEX "${l}" RENAME TO "${e.name}"`;
i.push(new iN.Query(u));
s.push(new iN.Query(h));
e.name = l;
});
r.findColumnForeignKeys(c).forEach(e => {
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
if (e.name !== t) return;
e.columnNames.splice(e.columnNames.indexOf(c.name), 1);
e.columnNames.push(n.name);
const o = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${e.name}"`));
e.name = o;
});
const e = r.columns.find(e => e.name === c.name);
r.columns[r.columns.indexOf(e)].name = n.name;
c.name = n.name;
}
if (n.precision !== c.precision || n.scale !== c.scale) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
}
if ((n.type === "enum" || n.type === "simple-enum") && (c.type === "enum" || c.type === "simple-enum") && (!aN.OrmUtils.isArraysEqual(n.enum, c.enum) || n.enumName !== c.enumName)) {
const e = n.isArray ? "[]" : "";
const t = this.buildEnumName(a, n);
const r = this.buildEnumName(a, c);
const l = this.buildEnumName(a, c, false);
const u = this.buildEnumName(a, c, true, false, true);
const h = this.buildEnumName(a, c, false, false, true);
i.push(new iN.Query(`ALTER TYPE ${r} RENAME TO ${h}`));
s.push(new iN.Query(`ALTER TYPE ${u} RENAME TO ${l}`));
i.push(this.createEnumTypeSql(a, n, t));
s.push(this.dropEnumTypeSql(a, n, t));
if (c.default !== null && c.default !== undefined) {
o = true;
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET DEFAULT ${c.default}`));
}
const d = `${t}${e} USING "${n.name}"::"text"::${t}${e}`;
const p = `${u}${e} USING "${n.name}"::"text"::${u}${e}`;
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${d}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${p}`));
if (n.default !== null && n.default !== undefined) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
}
i.push(this.dropEnumTypeSql(a, c, u));
s.push(this.createEnumTypeSql(a, c, u));
}
if (c.isNullable !== n.isNullable) {
if (n.isNullable) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
} else {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
}
}
if (c.comment !== n.comment) {
i.push(new iN.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${c.name}" IS ${this.escapeComment(n.comment)}`));
s.push(new iN.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${n.name}" IS ${this.escapeComment(c.comment)}`));
}
if (n.isPrimary !== c.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
}
if (n.isPrimary === true) {
e.push(n);
const t = r.columns.find(e => e.name === n.name);
t.isPrimary = true;
const o = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${o}"`));
} else {
const t = e.find(e => e.name === n.name);
e.splice(e.indexOf(t), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (e.length > 0) {
const t = e[0].primaryKeyConstraintName ? e[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
}
}
if (n.isUnique !== c.isUnique) {
if (n.isUnique === true) {
const e = new Xg.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
columnNames: [ n.name ]
});
r.uniques.push(e);
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
} else {
const e = r.uniques.find(e => e.columnNames.length === 1 && !!e.columnNames.find(e => e === n.name));
r.uniques.splice(r.uniques.indexOf(e), 1);
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
}
}
if (c.isGenerated !== n.isGenerated) {
if (c.isGenerated) {
if (c.generationStrategy === "uuid") {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
} else if (c.generationStrategy === "increment") {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
i.push(new iN.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
s.push(new iN.Query(`CREATE SEQUENCE IF NOT EXISTS ${this.escapePath(this.buildSequencePath(a, n))} OWNED BY ${this.escapePath(a)}."${n.name}"`));
}
}
if (n.generationStrategy === "uuid") {
if (n.isGenerated === true) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
} else {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
}
} else if (n.generationStrategy === "increment") {
if (n.isGenerated === true) {
i.push(new iN.Query(`CREATE SEQUENCE IF NOT EXISTS ${this.escapePath(this.buildSequencePath(a, n))} OWNED BY ${this.escapePath(a)}."${n.name}"`));
s.push(new iN.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
} else {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
i.push(new iN.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
s.push(new iN.Query(`CREATE SEQUENCE IF NOT EXISTS ${this.escapePath(this.buildSequencePath(a, n))} OWNED BY ${this.escapePath(a)}."${n.name}"`));
}
}
}
if (n.default !== c.default && !o) {
if (n.default !== null && n.default !== undefined) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
if (c.default !== null && c.default !== undefined) {
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
} else {
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
}
} else if (c.default !== null && c.default !== undefined) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
}
}
if ((n.spatialFeatureType || "").toLowerCase() !== (c.spatialFeatureType || "").toLowerCase() || n.srid !== c.srid) {
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
}
if (n.generatedType !== c.generatedType) {
if (!n.generatedType || n.generatedType === "VIRTUAL") {
const e = (await this.getTableNameWithSchema(a.name)).split(".");
const t = e[1];
const r = e[0];
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "TEMP_OLD_${c.name}"`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD ${this.buildCreateColumnSql(a, n)}`));
i.push(new iN.Query(`UPDATE ${this.escapePath(a)} SET "${n.name}" = "TEMP_OLD_${c.name}"`));
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP COLUMN "TEMP_OLD_${c.name}"`));
i.push(this.deleteTypeormMetadataSql({
database: this.driver.database,
schema: r,
table: t,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: c.name
}));
s.push(this.insertTypeormMetadataSql({
database: this.driver.database,
schema: r,
table: t,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: c.name,
value: c.asExpression
}));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} ADD ${this.buildCreateColumnSql(a, c)}`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(a)} DROP COLUMN "${n.name}"`));
}
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new Fg.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = a.primaryKeyConstraintName ? a.primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
const n = r.findColumnByName(a.name);
n.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns[0].primaryKeyConstraintName ? r.primaryColumns[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(r, r.primaryColumns.map(e => e.name));
const t = r.primaryColumns.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
}
const c = r.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (c) {
r.checks.splice(r.checks.indexOf(c), 1);
i.push(this.dropCheckConstraintSql(n, c));
s.push(this.createCheckConstraintSql(n, c));
}
const l = r.uniques.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (l) {
r.uniques.splice(r.uniques.indexOf(l), 1);
i.push(this.dropUniqueConstraintSql(n, l));
s.push(this.createUniqueConstraintSql(n, l));
}
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, a)}`));
if (a.type === "enum" || a.type === "simple-enum") {
const e = await this.hasEnumType(n, a);
if (e) {
const e = await this.getUserDefinedTypeName(n, a);
const t = `"${e.schema}"."${e.name}"`;
i.push(this.dropEnumTypeSql(n, a, t));
s.push(this.createEnumTypeSql(n, a, t));
}
}
if (a.generatedType === "STORED") {
const e = (await this.getTableNameWithSchema(n.name)).split(".");
const t = e[1];
const r = e[0];
const o = this.deleteTypeormMetadataSql({
database: this.driver.database,
schema: r,
table: t,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const c = this.insertTypeormMetadataSql({
database: this.driver.database,
schema: r,
table: t,
type: sN.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(o);
s.push(c);
}
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t, n) {
const a = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = a.clone();
const i = this.createPrimaryKeySql(a, t, n);
r.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
const s = this.dropPrimaryKeySql(r);
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async updatePrimaryKeys(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = t.map(e => e.name);
const i = [];
const s = [];
const o = a.primaryColumns;
if (o.length > 0) {
const e = o[0].primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, o.map(e => e.name));
const t = o.map(e => `"${e.name}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
}
a.columns.filter(e => r.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const c = o[0]?.primaryKeyConstraintName ? o[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(a, r);
const l = r.map(e => `"${e}"`).join(", ");
i.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
s.push(new iN.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
await this.executeQueries(i, s);
this.replaceCachedTable(n, a);
}
async dropPrimaryKey(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.dropPrimaryKeySql(n);
const r = this.createPrimaryKeySql(n, n.primaryColumns.map(e => e.name), t);
await this.executeQueries(a, r);
n.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.uniqueConstraintName(n, t.columnNames);
const a = this.createUniqueConstraintSql(n, t);
const r = this.dropUniqueConstraintSql(n, t);
await this.executeQueries(a, r);
n.addUniqueConstraint(t);
}
async createUniqueConstraints(e, t) {
for (const n of t) {
await this.createUniqueConstraint(e, n);
}
}
async dropUniqueConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
const r = this.dropUniqueConstraintSql(n, a);
const i = this.createUniqueConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeUniqueConstraint(a);
}
async dropUniqueConstraints(e, t) {
for (const n of t) {
await this.dropUniqueConstraint(e, n);
}
}
async createCheckConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.exclusionConstraintName(n, t.expression);
const a = this.createExclusionConstraintSql(n, t);
const r = this.dropExclusionConstraintSql(n, t);
await this.executeQueries(a, r);
n.addExclusionConstraint(t);
}
async createExclusionConstraints(e, t) {
const n = t.map(t => this.createExclusionConstraint(e, t));
await Promise.all(n);
}
async dropExclusionConstraint(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableExclusion(t) ? t : n.exclusions.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied exclusion constraint was not found in table ${n.name}`);
const r = this.dropExclusionConstraintSql(n, a);
const i = this.createExclusionConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeExclusionConstraint(a);
}
async dropExclusionConstraints(e, t) {
const n = t.map(t => this.dropExclusionConstraint(e, t));
await Promise.all(n);
}
async createForeignKey(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
for (const n of t) {
await this.createForeignKey(e, n);
}
}
async dropForeignKey(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
if (!a.name) {
a.name = this.connection.namingStrategy.foreignKeyName(n, a.columnNames, this.getTablePath(a), a.referencedColumnNames);
}
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
for (const n of t) {
await this.dropForeignKey(e, n);
}
}
async createIndex(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createViewIndex(e, t) {
const n = nN.InstanceChecker.isView(e) ? e : await this.getCachedView(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createViewIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
for (const n of t) {
await this.createIndex(e, n);
}
}
async createViewIndices(e, t) {
for (const n of t) {
await this.createViewIndex(e, n);
}
}
async dropIndex(e, t) {
const n = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = nN.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropViewIndex(e, t) {
const n = nN.InstanceChecker.isView(e) ? e : await this.getCachedView(e);
const a = nN.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new Fg.TypeORMError(`Supplied index ${t} was not found in view ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createViewIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
for (const n of t) {
await this.dropIndex(e, n);
}
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase() {
const e = [];
this.connection.entityMetadatas.filter(e => e.schema).forEach(t => {
const n = !!e.find(e => e === t.schema);
if (!n) e.push(t.schema);
});
e.push(this.driver.options.schema || "current_schema()");
const t = e.map(e => e === "current_schema()" ? e : "'" + e + "'").join(", ");
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = `SELECT 'DROP VIEW IF EXISTS "' || schemaname || '"."' || viewname || '" CASCADE;' as "query" ` + `FROM "pg_views" WHERE "schemaname" IN (${t}) AND "viewname" NOT IN ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews')`;
const a = await this.query(e);
await Promise.all(a.map(e => this.query(e["query"])));
if (rN.DriverUtils.isReleaseVersionOrGreater(this.driver, "9.3")) {
const e = `SELECT 'DROP MATERIALIZED VIEW IF EXISTS "' || schemaname || '"."' || matviewname || '" CASCADE;' as "query" ` + `FROM "pg_matviews" WHERE "schemaname" IN (${t})`;
const n = await this.query(e);
await Promise.all(n.map(e => this.query(e["query"])));
}
const r = `SELECT 'DROP TABLE IF EXISTS "' || schemaname || '"."' || tablename || '" CASCADE;' as "query" FROM "pg_tables" WHERE "schemaname" IN (${t}) AND "tablename" NOT IN ('spatial_ref_sys')`;
const i = await this.query(r);
await Promise.all(i.map(e => this.query(e["query"])));
await this.dropEnumTypes(t);
if (!n) {
await this.commitTransaction();
}
} catch (e) {
try {
if (!n) {
await this.rollbackTransaction();
}
} catch {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) return [];
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = await this.getCurrentSchema();
const r = e.length === 0 ? "1=1" : e.map(e => this.driver.parseTableName(e)).map(({schema: e, tableName: t}) => {
if (!e) {
e = this.driver.options.schema || a;
}
return `("t"."schema" = '${e}' AND "t"."name" = '${t}')`;
}).join(" OR ");
const i = e.length === 0 ? "1=1" : e.map(e => this.driver.parseTableName(e)).map(({schema: e, tableName: t}) => {
if (!e) {
e = this.driver.options.schema || a;
}
return `("ns"."nspname" = '${e}' AND "t"."relname" = '${t}')`;
}).join(" OR ");
const s = `SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "i"."relname" AS "constraint_name", "a"."attname" AS "column_name", ` + `CASE "ix"."indisunique" WHEN 't' THEN 'TRUE' ELSE'FALSE' END AS "is_unique", pg_get_expr("ix"."indpred", "ix"."indrelid") AS "condition", ` + `"types"."typname" AS "type_name" ` + `FROM "pg_class" "t" ` + `INNER JOIN "pg_index" "ix" ON "ix"."indrelid" = "t"."oid" ` + `INNER JOIN "pg_attribute" "a" ON "a"."attrelid" = "t"."oid" AND "a"."attnum" = ANY ("ix"."indkey") ` + `INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "t"."relnamespace" ` + `INNER JOIN "pg_class" "i" ON "i"."oid" = "ix"."indexrelid" ` + `INNER JOIN "pg_type" "types" ON "types"."oid" = "a"."atttypid" ` + `LEFT JOIN "pg_constraint" "cnst" ON "cnst"."conname" = "i"."relname" ` + `WHERE "t"."relkind" IN ('m') AND "cnst"."contype" IS NULL AND (${i})`;
const o = `SELECT "t".* FROM ${this.escapePath(this.getTypeormMetadataTableName())} "t" ` + `INNER JOIN "pg_catalog"."pg_class" "c" ON "c"."relname" = "t"."name" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "c"."relnamespace" AND "n"."nspname" = "t"."schema" ` + `WHERE "t"."type" IN ('${sN.MetadataTableType.VIEW}', '${sN.MetadataTableType.MATERIALIZED_VIEW}') ${r ? `AND (${r})` : ""}`;
const c = await this.query(o);
const l = await this.query(s);
return c.map(e => {
const t = aN.OrmUtils.uniq(l.filter(t => t["table_name"] === e["name"] && t["table_schema"] === e["schema"]), e => e["constraint_name"]);
const r = new Zg.View;
const i = e["schema"] === a && !this.driver.options.schema ? undefined : e["schema"];
r.database = n;
r.schema = e["schema"];
r.name = this.driver.buildTableName(e["name"], i);
r.expression = e["value"];
r.materialized = e["type"] === sN.MetadataTableType.MATERIALIZED_VIEW;
r.indices = t.map(e => {
const t = l.filter(t => t["table_schema"] === e["table_schema"] && t["table_name"] === e["table_name"] && t["constraint_name"] === e["constraint_name"]);
return new Jg.TableIndex({
view: r,
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
isUnique: e["is_unique"] === "TRUE",
where: e["condition"],
isFulltext: false
});
});
return r;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = await this.getCurrentSchema();
const n = await this.getCurrentDatabase();
const a = [];
if (!e) {
const e = `SELECT "table_schema", "table_name", obj_description(('"' || "table_schema" || '"."' || "table_name" || '"')::regclass, 'pg_class') AS table_comment FROM "information_schema"."tables"`;
a.push(...await this.query(e));
} else {
const n = e.map(e => this.driver.parseTableName(e)).map(({schema: e, tableName: n}) => `("table_schema" = '${e || t}' AND "table_name" = '${n}')`).join(" OR ");
const r = `SELECT "table_schema", "table_name", obj_description(('"' || "table_schema" || '"."' || "table_name" || '"')::regclass, 'pg_class') AS table_comment FROM "information_schema"."tables" WHERE ` + n;
a.push(...await this.query(r));
}
if (a.length === 0) {
return [];
}
const r = a.map(({table_schema: e, table_name: t}) => `("table_schema" = '${e}' AND "table_name" = '${t}')`).join(" OR ");
const i = `SELECT columns.*, pg_catalog.col_description(('"' || table_catalog || '"."' || table_schema || '"."' || table_name || '"')::regclass::oid, ordinal_position) AS description, ` + `('"' || "udt_schema" || '"."' || "udt_name" || '"')::"regtype" AS "regtype", pg_catalog.format_type("col_attr"."atttypid", "col_attr"."atttypmod") AS "format_type" ` + `FROM "information_schema"."columns" ` + `LEFT JOIN "pg_catalog"."pg_attribute" AS "col_attr" ON "col_attr"."attname" = "columns"."column_name" ` + `AND "col_attr"."attrelid" = ( ` + `SELECT "cls"."oid" FROM "pg_catalog"."pg_class" AS "cls" ` + `LEFT JOIN "pg_catalog"."pg_namespace" AS "ns" ON "ns"."oid" = "cls"."relnamespace" ` + `WHERE "cls"."relname" = "columns"."table_name" ` + `AND "ns"."nspname" = "columns"."table_schema" ` + `) ` + `WHERE ` + r;
const s = a.map(({table_schema: e, table_name: t}) => `("ns"."nspname" = '${e}' AND "t"."relname" = '${t}')`).join(" OR ");
const o = `SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "cnst"."conname" AS "constraint_name", ` + `pg_get_constraintdef("cnst"."oid") AS "expression", ` + `CASE "cnst"."contype" WHEN 'p' THEN 'PRIMARY' WHEN 'u' THEN 'UNIQUE' WHEN 'c' THEN 'CHECK' WHEN 'x' THEN 'EXCLUDE' END AS "constraint_type", "a"."attname" AS "column_name" ` + `FROM "pg_constraint" "cnst" ` + `INNER JOIN "pg_class" "t" ON "t"."oid" = "cnst"."conrelid" ` + `INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "cnst"."connamespace" ` + `LEFT JOIN "pg_attribute" "a" ON "a"."attrelid" = "cnst"."conrelid" AND "a"."attnum" = ANY ("cnst"."conkey") ` + `WHERE "t"."relkind" IN ('r', 'p') AND (${s})`;
const c = `SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "i"."relname" AS "constraint_name", "a"."attname" AS "column_name", ` + `CASE "ix"."indisunique" WHEN 't' THEN 'TRUE' ELSE'FALSE' END AS "is_unique", pg_get_expr("ix"."indpred", "ix"."indrelid") AS "condition", ` + `"types"."typname" AS "type_name", "am"."amname" AS "index_type" ` + `FROM "pg_class" "t" ` + `INNER JOIN "pg_index" "ix" ON "ix"."indrelid" = "t"."oid" ` + `INNER JOIN "pg_attribute" "a" ON "a"."attrelid" = "t"."oid" AND "a"."attnum" = ANY ("ix"."indkey") ` + `INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "t"."relnamespace" ` + `INNER JOIN "pg_class" "i" ON "i"."oid" = "ix"."indexrelid" ` + `INNER JOIN "pg_type" "types" ON "types"."oid" = "a"."atttypid" ` + `INNER JOIN "pg_am" "am" ON "i"."relam" = "am"."oid" ` + `LEFT JOIN "pg_constraint" "cnst" ON "cnst"."conname" = "i"."relname" ` + `WHERE "t"."relkind" IN ('r', 'p') AND "cnst"."contype" IS NULL AND (${s})`;
const l = a.map(({table_schema: e, table_name: t}) => `("ns"."nspname" = '${e}' AND "cl"."relname" = '${t}')`).join(" OR ");
const u = await this.hasSupportForPartitionedTables();
const h = u ? ` AND "cl"."relispartition" = 'f'` : "";
const d = `SELECT "con"."conname" AS "constraint_name", "con"."nspname" AS "table_schema", "con"."relname" AS "table_name", "att2"."attname" AS "column_name", ` + `"ns"."nspname" AS "referenced_table_schema", "cl"."relname" AS "referenced_table_name", "att"."attname" AS "referenced_column_name", "con"."confdeltype" AS "on_delete", ` + `"con"."confupdtype" AS "on_update", "con"."condeferrable" AS "deferrable", "con"."condeferred" AS "deferred" ` + `FROM ( ` + `SELECT UNNEST ("con1"."conkey") AS "parent", UNNEST ("con1"."confkey") AS "child", "con1"."confrelid", "con1"."conrelid", "con1"."conname", "con1"."contype", "ns"."nspname", ` + `"cl"."relname", "con1"."condeferrable", ` + `CASE WHEN "con1"."condeferred" THEN 'INITIALLY DEFERRED' ELSE 'INITIALLY IMMEDIATE' END as condeferred, ` + `CASE "con1"."confdeltype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confdeltype", ` + `CASE "con1"."confupdtype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confupdtype" ` + `FROM "pg_class" "cl" ` + `INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" ` + `INNER JOIN "pg_constraint" "con1" ON "con1"."conrelid" = "cl"."oid" ` + `WHERE "con1"."contype" = 'f' AND (${l}) ` + `) "con" ` + `INNER JOIN "pg_attribute" "att" ON "att"."attrelid" = "con"."confrelid" AND "att"."attnum" = "con"."child" ` + `INNER JOIN "pg_class" "cl" ON "cl"."oid" = "con"."confrelid" ${h}` + `INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" ` + `INNER JOIN "pg_attribute" "att2" ON "att2"."attrelid" = "con"."conrelid" AND "att2"."attnum" = "con"."parent"`;
const [p, m, f, y] = await Promise.all([ this.query(i), this.query(o), this.query(c), this.query(d) ]);
return Promise.all(a.map(async e => {
const a = new Wg.Table;
const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
const i = r(e, "table_schema");
a.database = n;
a.schema = e["table_schema"];
a.comment = e["table_comment"];
a.name = this.driver.buildTableName(e["table_name"], i);
a.columns = await Promise.all(p.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]).map(async t => {
const r = m.filter(e => e["table_name"] === t["table_name"] && e["table_schema"] === t["table_schema"] && e["column_name"] === t["column_name"]);
const i = new Gg.TableColumn;
i.name = t["column_name"];
i.type = t["regtype"].toLowerCase();
if (i.type === "numeric" || i.type === "numeric[]" || i.type === "decimal" || i.type === "float") {
let e = t["numeric_precision"];
let n = t["numeric_scale"];
if (t["data_type"] === "ARRAY") {
const a = t["format_type"].match(/^numeric\(([0-9]+),([0-9]+)\)\[\]$/);
if (a) {
e = +a[1];
n = +a[2];
}
}
if (e !== null && !this.isDefaultColumnPrecision(a, i, e)) {
i.precision = e;
} else if (n !== null && !this.isDefaultColumnScale(a, i, n)) {
i.precision = undefined;
}
if (n !== null && !this.isDefaultColumnScale(a, i, n)) {
i.scale = n;
} else if (e !== null && !this.isDefaultColumnPrecision(a, i, e)) {
i.scale = undefined;
}
}
if (i.type === "interval" || i.type === "time without time zone" || i.type === "time with time zone" || i.type === "timestamp without time zone" || i.type === "timestamp with time zone") {
i.precision = !this.isDefaultColumnPrecision(a, i, t["datetime_precision"]) ? t["datetime_precision"] : undefined;
}
if (t["data_type"] === "USER-DEFINED" || t["data_type"] === "ARRAY") {
const {name: n} = await this.getUserDefinedTypeName(a, i);
const r = this.buildEnumName(a, i, false, true);
const s = r !== n ? n : undefined;
const o = `SELECT "e"."enumlabel" AS "value" FROM "pg_enum" "e" ` + `INNER JOIN "pg_type" "t" ON "t"."oid" = "e"."enumtypid" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" = '${e["table_schema"]}' AND "t"."typname" = '${s || n}'`;
const c = await this.query(o);
if (c.length) {
i.type = "enum";
i.enum = c.map(e => e["value"]);
i.enumName = s;
}
if (t["data_type"] === "ARRAY") {
i.isArray = true;
const e = i.type.replace("[]", "");
i.type = this.connection.driver.normalizeType({
type: e
});
}
}
if (i.type === "geometry" || i.type === "geography") {
const e = `SELECT * FROM (` + `SELECT "f_table_schema" "table_schema", "f_table_name" "table_name", ` + `"f_${i.type}_column" "column_name", "srid", "type" ` + `FROM "${i.type}_columns"` + `) AS _ ` + `WHERE "column_name" = '${t["column_name"]}' AND ` + `"table_schema" = '${t["table_schema"]}' AND ` + `"table_name" = '${t["table_name"]}'`;
const n = await this.query(e);
if (n.length > 0) {
i.spatialFeatureType = n[0].type;
i.srid = n[0].srid;
}
}
if (this.driver.withLengthColumnTypes.indexOf(i.type) !== -1) {
let e;
if (i.isArray) {
const n = /\((\d+)\)/.exec(t["format_type"]);
e = n ? n[1] : undefined;
} else if (t["character_maximum_length"]) {
e = t["character_maximum_length"].toString();
}
if (e) {
i.length = !this.isDefaultColumnLength(a, i, e) ? e : "";
}
}
i.isNullable = t["is_nullable"] === "YES";
const s = r.find(e => e["constraint_type"] === "PRIMARY");
if (s) {
i.isPrimary = true;
const e = m.filter(e => e["table_name"] === t["table_name"] && e["table_schema"] === t["table_schema"] && e["column_name"] !== t["column_name"] && e["constraint_type"] === "PRIMARY");
const n = e.map(e => e["column_name"]);
n.push(t["column_name"]);
const r = this.connection.namingStrategy.primaryKeyName(a, n);
if (s["constraint_name"] !== r) {
i.primaryKeyConstraintName = s["constraint_name"];
}
}
const o = r.filter(e => e["constraint_type"] === "UNIQUE");
const c = o.every(e => m.some(n => n["constraint_type"] === "UNIQUE" && n["constraint_name"] === e["constraint_name"] && n["column_name"] !== t["column_name"]));
i.isUnique = o.length > 0 && !c;
if (t.is_identity === "YES") {
i.isGenerated = true;
i.generationStrategy = "identity";
i.generatedIdentity = t.identity_generation;
} else if (t["column_default"] !== null && t["column_default"] !== undefined) {
const e = `nextval('${this.buildSequenceName(a, t["column_name"])}'::regclass)`;
const n = `nextval('${this.buildSequencePath(a, t["column_name"])}'::regclass)`;
const r = t["column_default"].replace(/"/g, "");
if (r === e || r === n) {
i.isGenerated = true;
i.generationStrategy = "increment";
} else if (t["column_default"] === "gen_random_uuid()" || /^uuid_generate_v\d\(\)/.test(t["column_default"])) {
if (i.type === "uuid") {
i.isGenerated = true;
i.generationStrategy = "uuid";
} else {
i.default = t["column_default"];
}
} else if (t["column_default"] === "now()" || t["column_default"].indexOf("'now'::text") !== -1) {
i.default = t["column_default"];
} else {
i.default = t["column_default"].replace(/::[\w\s.[\]\-"]+/g, "");
i.default = i.default.replace(/^(-?\d+)$/, "'$1'");
}
}
if (t["is_generated"] === "ALWAYS" && t["generation_expression"]) {
i.generatedType = "STORED";
const t = this.selectTypeormMetadataSql({
database: n,
schema: e["table_schema"],
table: e["table_name"],
type: sN.MetadataTableType.GENERATED_COLUMN,
name: i.name
});
const a = await this.query(t.query, t.parameters);
if (a[0] && a[0].value) {
i.asExpression = a[0].value;
} else {
i.asExpression = "";
}
}
i.comment = t["description"] ? t["description"] : undefined;
if (t["character_set_name"]) i.charset = t["character_set_name"];
if (t["collation_name"]) i.collation = t["collation_name"];
return i;
}));
const s = aN.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "UNIQUE"), e => e["constraint_name"]);
a.uniques = s.map(e => {
const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
return new Xg.TableUnique({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
deferrable: e["deferrable"] ? e["deferred"] : undefined
});
});
const o = aN.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "CHECK"), e => e["constraint_name"]);
a.checks = o.map(e => {
const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
return new Hg.TableCheck({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
expression: e["expression"].replace(/^\s*CHECK\s*\((.*)\)\s*$/i, "$1")
});
});
const c = aN.OrmUtils.uniq(m.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"] && t["constraint_type"] === "EXCLUDE"), e => e["constraint_name"]);
a.exclusions = c.map(e => new Yg.TableExclusion({
name: e["constraint_name"],
expression: e["expression"].substring(8)
}));
const l = aN.OrmUtils.uniq(y.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]), e => e["constraint_name"]);
a.foreignKeys = l.map(e => {
const t = y.filter(t => t["constraint_name"] === e["constraint_name"]);
const n = r(e, "referenced_table_schema");
const a = this.driver.buildTableName(e["referenced_table_name"], n);
return new zg.TableForeignKey({
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
referencedSchema: e["referenced_table_schema"],
referencedTableName: a,
referencedColumnNames: t.map(e => e["referenced_column_name"]),
onDelete: e["on_delete"],
onUpdate: e["on_update"],
deferrable: e["deferrable"] ? e["deferred"] : undefined
});
});
const u = aN.OrmUtils.uniq(f.filter(t => t["table_name"] === e["table_name"] && t["table_schema"] === e["table_schema"]), e => e["constraint_name"]);
a.indices = u.map(e => {
const t = f.filter(t => t["table_schema"] === e["table_schema"] && t["table_name"] === e["table_name"] && t["constraint_name"] === e["constraint_name"]);
return new Jg.TableIndex({
table: a,
name: e["constraint_name"],
columnNames: t.map(e => e["column_name"]),
isUnique: e["is_unique"] === "TRUE",
where: e["condition"],
isSpatial: e["index_type"] === "gist",
isFulltext: false
});
});
return a;
}));
}
createTableSql(e, t) {
const n = e.columns.map(t => this.buildCreateColumnSql(e, t)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (!n) e.uniques.push(new Xg.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ]
}));
});
if (e.uniques.length > 0) {
const t = e.uniques.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.uniqueConstraintName(e, t.columnNames);
const a = t.columnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${n}" UNIQUE (${a})`;
if (t.deferrable) r += ` DEFERRABLE ${t.deferrable}`;
return r;
}).join(", ");
a += `, ${t}`;
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT "${n}" CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.exclusions.length > 0) {
const t = e.exclusions.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.exclusionConstraintName(e, t.expression);
return `CONSTRAINT "${n}" EXCLUDE ${t.expression}`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${t.name}" FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
if (t.deferrable) r += ` DEFERRABLE ${t.deferrable}`;
return r;
}).join(", ");
a += `, ${t}`;
}
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const t = r[0].primaryKeyConstraintName ? r[0].primaryKeyConstraintName : this.connection.namingStrategy.primaryKeyName(e, r.map(e => e.name));
const n = r.map(e => `"${e.name}"`).join(", ");
a += `, CONSTRAINT "${t}" PRIMARY KEY (${n})`;
}
a += `)`;
e.columns.filter(e => e.comment).forEach(t => a += `; COMMENT ON COLUMN ${this.escapePath(e)}."${t.name}" IS ${this.escapeComment(t.comment)}`);
return new iN.Query(a);
}
async getVersion() {
const e = await this.query(`SELECT version()`);
return e[0].version.replace(/^PostgreSQL ([\d.]+).*$/, "$1");
}
dropTableSql(e) {
return new iN.Query(`DROP TABLE ${this.escapePath(e)}`);
}
createViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
const n = this.escapePath(e);
if (typeof e.expression === "string") {
return new iN.Query(`CREATE ${t}VIEW ${n} AS ${e.expression}`);
} else {
return new iN.Query(`CREATE ${t}VIEW ${n} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
const t = await this.getCurrentSchema();
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = t;
}
const r = e.materialized ? sN.MetadataTableType.MATERIALIZED_VIEW : sN.MetadataTableType.VIEW;
const i = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: r,
schema: n,
name: a,
value: i
});
}
dropViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
return new iN.Query(`DROP ${t}VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const t = await this.getCurrentSchema();
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = t;
}
const r = e.materialized ? sN.MetadataTableType.MATERIALIZED_VIEW : sN.MetadataTableType.VIEW;
return this.deleteTypeormMetadataSql({
type: r,
schema: n,
name: a
});
}
async dropEnumTypes(e) {
const t = `SELECT 'DROP TYPE IF EXISTS "' || n.nspname || '"."' || t.typname || '" CASCADE;' as "query" FROM "pg_type" "t" ` + `INNER JOIN "pg_enum" "e" ON "e"."enumtypid" = "t"."oid" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" IN (${e}) GROUP BY "n"."nspname", "t"."typname"`;
const n = await this.query(t);
await Promise.all(n.map(e => this.query(e["query"])));
}
async hasEnumType(e, t) {
let {schema: n} = this.driver.parseTableName(e);
if (!n) {
n = await this.getCurrentSchema();
}
const a = this.buildEnumName(e, t, false, true);
const r = `SELECT "n"."nspname", "t"."typname" FROM "pg_type" "t" ` + `INNER JOIN "pg_namespace" "n" ON "n"."oid" = "t"."typnamespace" ` + `WHERE "n"."nspname" = '${n}' AND "t"."typname" = '${a}'`;
const i = await this.query(r);
return i.length ? true : false;
}
createEnumTypeSql(e, t, n) {
if (!n) n = this.buildEnumName(e, t);
const a = t.enum.map(e => `'${e.replaceAll("'", "''")}'`).join(", ");
return new iN.Query(`CREATE TYPE ${n} AS ENUM(${a})`);
}
dropEnumTypeSql(e, t, n) {
if (!n) n = this.buildEnumName(e, t);
return new iN.Query(`DROP TYPE ${n}`);
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
return new iN.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX${t.isConcurrent ? " CONCURRENTLY" : ""} "${t.name}" ON ${this.escapePath(e)} ${t.isSpatial ? "USING GiST " : ""}(${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
createViewIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
return new iN.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
dropIndexSql(e, t) {
const n = nN.InstanceChecker.isTableIndex(t) ? t.name : t;
const a = nN.InstanceChecker.isTableIndex(t) ? t.isConcurrent : false;
const {schema: r} = this.driver.parseTableName(e);
return r ? new iN.Query(`DROP INDEX ${a ? "CONCURRENTLY " : ""}"${r}"."${n}"`) : new iN.Query(`DROP INDEX ${a ? "CONCURRENTLY " : ""}"${n}"`);
}
createPrimaryKeySql(e, t, n) {
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
const r = t.map(e => `"${e}"`).join(", ");
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
}
dropPrimaryKeySql(e) {
if (!e.primaryColumns.length) throw new Fg.TypeORMError(`Table ${e} has no primary keys.`);
const t = e.primaryColumns.map(e => e.name);
const n = e.primaryColumns[0].primaryKeyConstraintName;
const a = n ? n : this.connection.namingStrategy.primaryKeyName(e, t);
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
}
createUniqueConstraintSql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
let a = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`;
if (t.deferrable) a += ` DEFERRABLE ${t.deferrable}`;
return new iN.Query(a);
}
dropUniqueConstraintSql(e, t) {
const n = nN.InstanceChecker.isTableUnique(t) ? t.name : t;
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createCheckConstraintSql(e, t) {
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = nN.InstanceChecker.isTableCheck(t) ? t.name : t;
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createExclusionConstraintSql(e, t) {
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" EXCLUDE ${t.expression}`);
}
dropExclusionConstraintSql(e, t) {
const n = nN.InstanceChecker.isTableExclusion(t) ? t.name : t;
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
const a = t.referencedColumnNames.map(e => `"` + e + `"`).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
if (t.deferrable) r += ` DEFERRABLE ${t.deferrable}`;
return new iN.Query(r);
}
dropForeignKeySql(e, t) {
const n = nN.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new iN.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
buildSequenceName(e, t) {
const {tableName: n} = this.driver.parseTableName(e);
const a = nN.InstanceChecker.isTableColumn(t) ? t.name : t;
let r = `${n}_${a}_seq`;
if (r.length > this.connection.driver.maxAliasLength) {
r = `${n.substring(0, 29)}_${a.substring(0, Math.max(29, 63 - e.name.length - 5))}_seq`;
}
return r;
}
buildSequencePath(e, t) {
const {schema: n} = this.driver.parseTableName(e);
return n ? `${n}.${this.buildSequenceName(e, t)}` : this.buildSequenceName(e, t);
}
buildEnumName(e, t, n = true, a, r) {
const {schema: i, tableName: s} = this.driver.parseTableName(e);
let o = t.enumName ? t.enumName : `${s}_${t.name.toLowerCase()}_enum`;
if (i && n) o = `${i}.${o}`;
if (r) o = o + "_old";
return o.split(".").map(e => a ? e : `"${e}"`).join(".");
}
async getUserDefinedTypeName(e, t) {
let {schema: n, tableName: a} = this.driver.parseTableName(e);
if (!n) {
n = await this.getCurrentSchema();
}
const r = await this.query(`SELECT "udt_schema", "udt_name" ` + `FROM "information_schema"."columns" WHERE "table_schema" = '${n}' AND "table_name" = '${a}' AND "column_name"='${t.name}'`);
let i = r[0]["udt_name"];
if (i.indexOf("_") === 0) {
i = i.substr(1, i.length);
}
return {
schema: r[0]["udt_schema"],
name: i
};
}
escapeComment(e) {
if (!e || e.length === 0) {
return "NULL";
}
e = e.replace(/'/g, "''").replace(/\u0000/g, "");
return `'${e}'`;
}
escapePath(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
if (t && t !== this.driver.searchSchema) {
return `"${t}"."${n}"`;
}
return `"${n}"`;
}
async getTableNameWithSchema(e) {
const t = nN.InstanceChecker.isTable(e) ? e.name : e;
if (t.indexOf(".") === -1) {
const e = await this.query(`SELECT current_schema()`);
const n = e[0]["current_schema"];
return `${n}.${t}`;
} else {
return `${t.split(".")[0]}.${t.split(".")[1]}`;
}
}
buildCreateColumnSql(e, t) {
let n = '"' + t.name + '"';
if (t.isGenerated === true && t.generationStrategy !== "uuid") {
if (t.generationStrategy === "identity") {
const e = t.generatedIdentity || "BY DEFAULT";
n += ` ${t.type} GENERATED ${e} AS IDENTITY`;
} else {
if (t.type === "integer" || t.type === "int" || t.type === "int4") n += " SERIAL";
if (t.type === "smallint" || t.type === "int2") n += " SMALLSERIAL";
if (t.type === "bigint" || t.type === "int8") n += " BIGSERIAL";
}
}
if (t.type === "enum" || t.type === "simple-enum") {
n += " " + this.buildEnumName(e, t);
if (t.isArray) n += " array";
} else if (!t.isGenerated || t.type === "uuid") {
n += " " + this.connection.driver.createFullType(t);
}
if (t.generatedType === "STORED" && t.asExpression) {
n += ` GENERATED ALWAYS AS (${t.asExpression}) STORED`;
}
if (t.charset) n += ' CHARACTER SET "' + t.charset + '"';
if (t.collation) n += ' COLLATE "' + t.collation + '"';
if (t.isNullable !== true) n += " NOT NULL";
if (t.default !== undefined && t.default !== null) n += " DEFAULT " + t.default;
if (t.isGenerated && t.generationStrategy === "uuid" && !t.default) n += ` DEFAULT ${this.driver.uuidGenerator}`;
return n;
}
async hasSupportForPartitionedTables() {
const e = await this.query(`SELECT TRUE FROM information_schema.columns WHERE table_name = 'pg_class' and column_name = 'relispartition'`);
return e.length ? true : false;
}
async changeTableComment(e, t) {
const n = [];
const a = [];
const r = nN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
t = this.escapeComment(t);
const i = this.escapeComment(r.comment);
if (t === i) {
return;
}
const s = r.clone();
n.push(new iN.Query(`COMMENT ON TABLE ${this.escapePath(s)} IS ${t}`));
a.push(new iN.Query(`COMMENT ON TABLE ${this.escapePath(r)} IS ${i}`));
await this.executeQueries(n, a);
r.comment = s.comment;
this.replaceCachedTable(r, s);
}
}
Bg.PostgresQueryRunner = PostgresQueryRunner;
Object.defineProperty(Ug, "__esModule", {
value: true
});
Ug.PostgresDriver = void 0;
const oN = Y();
const cN = Tt();
const lN = Uh;
const uN = Um;
const hN = _s;
const dN = up;
const pN = qc;
const mN = us;
const fN = Bg;
const yN = jn;
const EN = P;
const TN = Te;
class PostgresDriver {
constructor(e) {
this.slaves = [];
this.connectedQueryRunners = [];
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "int", "int2", "int4", "int8", "smallint", "integer", "bigint", "decimal", "numeric", "real", "float", "float4", "float8", "double precision", "money", "character varying", "varchar", "character", "char", "text", "citext", "hstore", "bytea", "bit", "varbit", "bit varying", "timetz", "timestamptz", "timestamp", "timestamp without time zone", "timestamp with time zone", "date", "time", "time without time zone", "time with time zone", "interval", "bool", "boolean", "enum", "point", "line", "lseg", "box", "path", "polygon", "circle", "cidr", "inet", "macaddr", "macaddr8", "tsvector", "tsquery", "uuid", "xml", "json", "jsonb", "int4range", "int8range", "numrange", "tsrange", "tstzrange", "daterange", "int4multirange", "int8multirange", "nummultirange", "tsmultirange", "tstzmultirange", "datemultirange", "geometry", "geography", "cube", "ltree" ];
this.supportedUpsertTypes = [ "on-conflict-do-update" ];
this.spatialTypes = [ "geometry", "geography" ];
this.withLengthColumnTypes = [ "character varying", "varchar", "character", "char", "bit", "varbit", "bit varying" ];
this.withPrecisionColumnTypes = [ "numeric", "decimal", "interval", "time without time zone", "time with time zone", "timestamp without time zone", "timestamp with time zone" ];
this.withScaleColumnTypes = [ "numeric", "decimal" ];
this.mappedDataTypes = {
createDate: "timestamp",
createDateDefault: "now()",
updateDate: "timestamp",
updateDateDefault: "now()",
deleteDate: "timestamp",
deleteDateNullable: true,
version: "int4",
treeLevel: "int4",
migrationId: "int4",
migrationName: "varchar",
migrationTimestamp: "int8",
cacheId: "int4",
cacheIdentifier: "varchar",
cacheTime: "int8",
cacheDuration: "int4",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text"
};
this.parametersPrefix = "$";
this.dataTypeDefaults = {
character: {
length: 1
},
bit: {
length: 1
},
interval: {
precision: 6
},
"time without time zone": {
precision: 6
},
"time with time zone": {
precision: 6
},
"timestamp without time zone": {
precision: 6
},
"timestamp with time zone": {
precision: 6
}
};
this.maxAliasLength = 63;
this.isGeneratedColumnsSupported = false;
this.cteCapabilities = {
enabled: true,
writable: true,
requiresRecursiveHint: true,
materializedHint: true
};
if (!e) {
return;
}
this.connection = e;
this.options = e.options;
this.isReplicated = this.options.replication ? true : false;
if (this.options.useUTC) {
process.env.PGTZ = "UTC";
}
this.loadDependencies();
this.database = yN.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
this.schema = yN.DriverUtils.buildDriverOptions(this.options).schema;
}
async connect() {
if (this.options.replication) {
this.slaves = await Promise.all(this.options.replication.slaves.map(e => this.createPool(this.options, e)));
this.master = await this.createPool(this.options, this.options.replication.master);
} else {
this.master = await this.createPool(this.options, this.options);
}
const e = this.createQueryRunner("master");
this.version = await e.getVersion();
if (!this.database) {
this.database = await e.getCurrentDatabase();
}
if (!this.searchSchema) {
this.searchSchema = await e.getCurrentSchema();
}
await e.release();
if (!this.schema) {
this.schema = this.searchSchema;
}
}
async afterConnect() {
const e = await this.checkMetadataForExtensions();
const [t, n] = await this.obtainMasterConnection();
const a = this.options.installExtensions === undefined || this.options.installExtensions;
if (a && e.hasExtensions) {
await this.enableExtensions(e, t);
}
this.isGeneratedColumnsSupported = mN.VersionUtils.isGreaterOrEqual(this.version, "12.0");
await n();
}
async enableExtensions(e, t) {
const {logger: n} = this.connection;
const {hasUuidColumns: a, hasCitextColumns: r, hasHstoreColumns: i, hasCubeColumns: s, hasGeometryColumns: o, hasLtreeColumns: c, hasExclusionConstraints: l} = e;
if (a) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "${this.options.uuidExtension || "uuid-ossp"}"`);
} catch (e) {
n.log("warn", `At least one of the entities has uuid column, but the '${this.options.uuidExtension || "uuid-ossp"}' extension cannot be installed automatically. Please install it manually using superuser rights, or select another uuid extension.`);
}
if (r) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "citext"`);
} catch (e) {
n.log("warn", "At least one of the entities has citext column, but the 'citext' extension cannot be installed automatically. Please install it manually using superuser rights");
}
if (i) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "hstore"`);
} catch (e) {
n.log("warn", "At least one of the entities has hstore column, but the 'hstore' extension cannot be installed automatically. Please install it manually using superuser rights");
}
if (o) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "postgis"`);
} catch (e) {
n.log("warn", "At least one of the entities has a geometry column, but the 'postgis' extension cannot be installed automatically. Please install it manually using superuser rights");
}
if (s) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "cube"`);
} catch (e) {
n.log("warn", "At least one of the entities has a cube column, but the 'cube' extension cannot be installed automatically. Please install it manually using superuser rights");
}
if (c) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "ltree"`);
} catch (e) {
n.log("warn", "At least one of the entities has a ltree column, but the 'ltree' extension cannot be installed automatically. Please install it manually using superuser rights");
}
if (l) try {
await this.executeQuery(t, `CREATE EXTENSION IF NOT EXISTS "btree_gist"`);
} catch (e) {
n.log("warn", "At least one of the entities has an exclusion constraint, but the 'btree_gist' extension cannot be installed automatically. Please install it manually using superuser rights");
}
}
async checkMetadataForExtensions() {
const e = this.connection.entityMetadatas.some(e => e.generatedColumns.filter(e => e.generationStrategy === "uuid").length > 0);
const t = this.connection.entityMetadatas.some(e => e.columns.filter(e => e.type === "citext").length > 0);
const n = this.connection.entityMetadatas.some(e => e.columns.filter(e => e.type === "hstore").length > 0);
const a = this.connection.entityMetadatas.some(e => e.columns.filter(e => e.type === "cube").length > 0);
const r = this.connection.entityMetadatas.some(e => e.columns.filter(e => this.spatialTypes.indexOf(e.type) >= 0).length > 0);
const i = this.connection.entityMetadatas.some(e => e.columns.filter(e => e.type === "ltree").length > 0);
const s = this.connection.entityMetadatas.some(e => e.exclusions.length > 0);
return {
hasUuidColumns: e,
hasCitextColumns: t,
hasHstoreColumns: n,
hasCubeColumns: a,
hasGeometryColumns: r,
hasLtreeColumns: i,
hasExclusionConstraints: s,
hasExtensions: e || t || n || r || a || i || s
};
}
async disconnect() {
if (!this.master) return Promise.reject(new oN.ConnectionIsNotSetError("postgres"));
await this.closePool(this.master);
await Promise.all(this.slaves.map(e => this.closePool(e)));
this.master = undefined;
this.slaves = [];
}
createSchemaBuilder() {
return new uN.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new fN.PostgresQueryRunner(this, e);
}
preparePersistentValue(e, t) {
if (t.transformer) e = hN.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return dN.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return dN.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "datetime" || t.type === Date || t.type === "timestamp" || t.type === "timestamp with time zone" || t.type === "timestamp without time zone") {
return dN.DateUtils.mixedDateToDate(e);
} else if ([ "json", "jsonb", ...this.spatialTypes ].indexOf(t.type) >= 0) {
return JSON.stringify(e);
} else if (t.type === "hstore") {
if (typeof e === "string") {
return e;
} else {
const t = e => {
if (e === null || typeof e === "undefined") {
return "NULL";
}
return `"${`${e}`.replace(/(?=["\\])/g, "\\")}"`;
};
return Object.keys(e).map(n => t(n) + "=>" + t(e[n])).join(",");
}
} else if (t.type === "simple-array") {
return dN.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return dN.DateUtils.simpleJsonToString(e);
} else if (t.type === "cube") {
if (t.isArray) {
return `{${e.map(e => `"(${e.join(",")})"`).join(",")}}`;
}
return `(${e.join(",")})`;
} else if (t.type === "ltree") {
return e.split(".").filter(Boolean).join(".").replace(/[\s]+/g, "_");
} else if ((t.type === "enum" || t.type === "simple-enum") && !t.isArray) {
return "" + e;
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? hN.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean) {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date || t.type === "timestamp" || t.type === "timestamp with time zone" || t.type === "timestamp without time zone") {
e = dN.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = dN.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = dN.DateUtils.mixedTimeToString(e);
} else if (t.type === "hstore") {
if (t.hstoreType === "object") {
const t = e => e.replace(/\\./g, e => e[1]);
const n = /"([^"\\]*(?:\\.[^"\\]*)*)"=>(?:(NULL)|"([^"\\]*(?:\\.[^"\\]*)*)")(?:,|$)/g;
const a = {};
`${e}`.replace(n, (e, n, r, i) => {
a[t(n)] = r ? null : t(i);
return "";
});
e = a;
}
} else if (t.type === "simple-array") {
e = dN.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = dN.DateUtils.stringToSimpleJson(e);
} else if (t.type === "cube") {
e = e.replace(/[()\s]+/g, "");
if (t.isArray) {
const t = /(?:"((?:[\d\s.,])*)")|(?:(NULL))/g;
const n = e;
e = [];
let a = null;
while ((a = t.exec(n)) !== null) {
if (a[1] !== undefined) {
e.push(a[1].split(",").filter(Boolean).map(Number));
} else {
e.push(undefined);
}
}
} else {
e = e.split(",").filter(Boolean).map(Number);
}
} else if (t.type === "enum" || t.type === "simple-enum") {
if (t.isArray) {
if (e === "{}") return [];
e = e.slice(1, -1).split(",").map(e => {
if (e.startsWith(`"`) && e.endsWith(`"`)) e = e.slice(1, -1);
return e.replace(/\\(\\|")/g, "$1");
});
e = e.map(e => !isNaN(+e) && t.enum.indexOf(parseInt(e)) >= 0 ? parseInt(e) : e);
} else {
e = !isNaN(+e) && t.enum.indexOf(parseInt(e)) >= 0 ? parseInt(e) : e;
}
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = hN.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
const r = new Map;
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
if (r.has(i)) {
return this.parametersPrefix + r.get(i);
}
const s = t[i];
if (n) {
return s.map(e => {
a.push(e);
return this.createParameter(i, a.length - 1);
}).join(", ");
}
if (typeof s === "function") {
return s();
}
a.push(s);
r.set(i, a.length);
return this.createParameter(i, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return '"' + e + '"';
}
buildTableName(e, t) {
const n = [ e ];
if (t) {
n.unshift(t);
}
return n.join(".");
}
parseTableName(e) {
const t = this.database;
const n = this.schema;
if (TN.InstanceChecker.isTable(e) || TN.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (TN.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (TN.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: t,
schema: (a.length > 1 ? a[0] : undefined) || n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
normalizeType(e) {
if (e.type === Number || e.type === "int" || e.type === "int4") {
return "integer";
} else if (e.type === String || e.type === "varchar") {
return "character varying";
} else if (e.type === Date || e.type === "timestamp") {
return "timestamp without time zone";
} else if (e.type === "timestamptz") {
return "timestamp with time zone";
} else if (e.type === "time") {
return "time without time zone";
} else if (e.type === "timetz") {
return "time with time zone";
} else if (e.type === Boolean || e.type === "bool") {
return "boolean";
} else if (e.type === "simple-array") {
return "text";
} else if (e.type === "simple-json") {
return "text";
} else if (e.type === "simple-enum") {
return "enum";
} else if (e.type === "int2") {
return "smallint";
} else if (e.type === "int8") {
return "bigint";
} else if (e.type === "decimal") {
return "numeric";
} else if (e.type === "float8" || e.type === "float") {
return "double precision";
} else if (e.type === "float4") {
return "real";
} else if (e.type === "char") {
return "character";
} else if (e.type === "varbit") {
return "bit varying";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (t === null || t === undefined) {
return undefined;
}
if (e.isArray && Array.isArray(t)) {
return `'{${t.map(e => `${e}`).join(",")}}'`;
}
if ((e.type === "enum" || e.type === "simple-enum" || typeof t === "number" || typeof t === "string") && t !== undefined) {
return `'${t}'`;
}
if (typeof t === "boolean") {
return t ? "true" : "false";
}
if (typeof t === "function") {
const e = t();
return this.normalizeDatetimeFunction(e);
}
if (typeof t === "object") {
return `'${JSON.stringify(t)}'`;
}
return `${t}`;
}
defaultEqual(e, t) {
if ([ "json", "jsonb" ].includes(e.type) && ![ "function", "undefined" ].includes(typeof e.default)) {
const n = typeof t.default === "string" ? JSON.parse(t.default.substring(1, t.default.length - 1)) : t.default;
return pN.OrmUtils.deepCompare(e.default, n);
}
const n = this.lowerDefaultValueIfNecessary(this.normalizeDefault(e));
return n === t.default;
}
normalizeIsUnique(e) {
return e.entityMetadata.uniques.some(t => t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
return e.length ? e.length.toString() : "";
}
createFullType(e) {
let t = e.type;
if (e.length) {
t += "(" + e.length + ")";
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += "(" + e.precision + "," + e.scale + ")";
} else if (e.precision !== null && e.precision !== undefined) {
t += "(" + e.precision + ")";
}
if (e.type === "time without time zone") {
t = "TIME" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "");
} else if (e.type === "time with time zone") {
t = "TIME" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "") + " WITH TIME ZONE";
} else if (e.type === "timestamp without time zone") {
t = "TIMESTAMP" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "");
} else if (e.type === "timestamp with time zone") {
t = "TIMESTAMP" + (e.precision !== null && e.precision !== undefined ? "(" + e.precision + ")" : "") + " WITH TIME ZONE";
} else if (this.spatialTypes.indexOf(e.type) >= 0) {
if (e.spatialFeatureType != null && e.srid != null) {
t = `${e.type}(${e.spatialFeatureType},${e.srid})`;
} else if (e.spatialFeatureType != null) {
t = `${e.type}(${e.spatialFeatureType})`;
} else {
t = e.type;
}
}
if (e.isArray) t += " array";
return t;
}
async obtainMasterConnection() {
if (!this.master) {
throw new EN.TypeORMError("Driver not Connected");
}
return new Promise((e, t) => {
this.master.connect((n, a, r) => {
n ? t(n) : e([ a, r ]);
});
});
}
async obtainSlaveConnection() {
if (!this.slaves.length) {
return this.obtainMasterConnection();
}
const e = Math.floor(Math.random() * this.slaves.length);
return new Promise((t, n) => {
this.slaves[e].connect((e, a, r) => {
e ? n(e) : t([ a, r ]);
});
});
}
createGeneratedMap(e, t) {
if (!t) return undefined;
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
pN.OrmUtils.mergeDeep(n, r.createValueMap(t[a]));
}
return n;
}, {});
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== t.length || n.isArray !== t.isArray || n.precision !== t.precision || t.scale !== undefined && n.scale !== t.scale || n.comment !== this.escapeComment(t.comment) || !n.isGenerated && !this.defaultEqual(t, n) || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.isUnique !== this.normalizeIsUnique(t) || n.enumName !== t.enumName || n.enum && t.enum && !pN.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || n.isGenerated !== t.isGenerated || (n.spatialFeatureType || "").toLowerCase() !== (t.spatialFeatureType || "").toLowerCase() || n.srid !== t.srid || n.generatedType !== t.generatedType || (n.asExpression || "").trim() !== (t.asExpression || "").trim();
return a;
});
}
lowerDefaultValueIfNecessary(e) {
if (!e) {
return e;
}
return e.split(`'`).map((e, t) => t % 2 === 1 ? e : e.toLowerCase()).join(`'`);
}
isReturningSqlSupported() {
return true;
}
isUUIDGenerationSupported() {
return true;
}
isFullTextColumnTypeSupported() {
return false;
}
get uuidGenerator() {
return this.options.uuidExtension === "pgcrypto" ? "gen_random_uuid()" : "uuid_generate_v4()";
}
createParameter(e, t) {
return this.parametersPrefix + (t + 1);
}
loadStreamDependency() {
try {
return lN.PlatformTools.load("pg-query-stream");
} catch (e) {
throw new EN.TypeORMError(`To use streams you should install pg-query-stream package. Please run npm i pg-query-stream --save command.`);
}
}
loadDependencies() {
try {
const e = this.options.driver || lN.PlatformTools.load("pg");
this.postgres = e;
try {
const e = this.options.nativeDriver || lN.PlatformTools.load("pg-native");
if (e && this.postgres.native) this.postgres = this.postgres.native;
} catch (e) {}
} catch (e) {
throw new cN.DriverPackageNotInstalledError("Postgres", "pg");
}
}
async createPool(e, t) {
const {logger: n} = this.connection;
t = Object.assign({}, t);
const a = Object.assign({}, {
connectionString: t.url,
host: t.host,
user: t.username,
password: t.password,
database: t.database,
port: t.port,
ssl: t.ssl,
connectionTimeoutMillis: e.connectTimeoutMS,
application_name: e.applicationName ?? t.applicationName,
max: e.poolSize
}, e.extra || {});
if (e.parseInt8 !== undefined) {
if (this.postgres.defaults && Object.getOwnPropertyDescriptor(this.postgres.defaults, "parseInt8")?.set) {
this.postgres.defaults.parseInt8 = e.parseInt8;
} else {
n.log("warn", "Attempted to set parseInt8 option, but the postgres driver does not support setting defaults.parseInt8. This option will be ignored.");
}
}
const r = new this.postgres.Pool(a);
const i = e.poolErrorHandler || (e => n.log("warn", `Postgres pool raised an error. ${e}`));
r.on("error", i);
return new Promise((t, n) => {
r.connect((a, i, s) => {
if (a) return n(a);
if (e.logNotifications) {
i.on("notice", e => {
e && this.connection.logger.log("info", e.message);
});
i.on("notification", e => {
e && this.connection.logger.log("info", `Received NOTIFY on channel ${e.channel}: ${e.payload}.`);
});
}
s();
t(r);
});
});
}
async closePool(e) {
while (this.connectedQueryRunners.length) {
await this.connectedQueryRunners[0].release();
}
return new Promise((t, n) => {
e.end(e => e ? n(e) : t());
});
}
executeQuery(e, t) {
this.connection.logger.logQuery(t);
return new Promise((n, a) => {
e.query(t, (e, t) => e ? a(e) : n(t));
});
}
normalizeDatetimeFunction(e) {
const t = e.toUpperCase();
const n = t.indexOf("CURRENT_TIMESTAMP") !== -1 || t.indexOf("CURRENT_DATE") !== -1 || t.indexOf("CURRENT_TIME") !== -1 || t.indexOf("LOCALTIMESTAMP") !== -1 || t.indexOf("LOCALTIME") !== -1;
if (n) {
const n = e.match(/\(\d+\)/);
if (t.indexOf("CURRENT_TIMESTAMP") !== -1) {
return n ? `('now'::text)::timestamp${n[0]} with time zone` : "now()";
} else if (t === "CURRENT_DATE") {
return "('now'::text)::date";
} else if (t.indexOf("CURRENT_TIME") !== -1) {
return n ? `('now'::text)::time${n[0]} with time zone` : "('now'::text)::time with time zone";
} else if (t.indexOf("LOCALTIMESTAMP") !== -1) {
return n ? `('now'::text)::timestamp${n[0]} without time zone` : "('now'::text)::timestamp without time zone";
} else if (t.indexOf("LOCALTIME") !== -1) {
return n ? `('now'::text)::time${n[0]} without time zone` : "('now'::text)::time without time zone";
}
}
return e;
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/\u0000/g, "");
return e;
}
}
Ug.PostgresDriver = PostgresDriver;
var gN = {};
var NN = {};
var AN = {};
Object.defineProperty(AN, "__esModule", {
value: true
});
AN.ExpoQueryRunner = void 0;
const bN = nn();
const CN = Sn();
const RN = lf;
const SN = hf;
const wN = sc;
const MN = OE;
class ExpoQueryRunner extends MN.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new SN.Broadcaster(this);
}
async beforeMigration() {
await this.query("PRAGMA foreign_keys = OFF");
}
async afterMigration() {
await this.query("PRAGMA foreign_keys = ON");
}
async query(e, t, n = false) {
if (this.isReleased) throw new CN.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
const r = new wN.BroadcasterResult;
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const i = Date.now();
const s = await a.prepareAsync(e);
try {
const a = await s.executeAsync(t);
const o = this.driver.options.maxQueryExecutionTime;
const c = Date.now();
const l = c - i;
this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, a, undefined);
await r.wait();
if (o && l > o) {
this.driver.connection.logger.logQuerySlow(l, e, t, this);
}
const u = new RN.QueryResult;
u.affected = a.changes;
u.records = await a.getAllAsync();
u.raw = e.startsWith("INSERT INTO") ? a.lastInsertRowId : u.records;
return n ? u : u.raw;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(r, e, t, false, 0, undefined, n);
await r.wait();
throw new bN.QueryFailedError(e, t, n);
} finally {
await r.wait();
await s.finalizeAsync();
}
}
}
AN.ExpoQueryRunner = ExpoQueryRunner;
Object.defineProperty(NN, "__esModule", {
value: true
});
NN.ExpoDriver = void 0;
const ON = KE;
const vN = AN;
class ExpoDriver extends ON.AbstractSqliteDriver {
constructor(e) {
super(e);
this.sqlite = this.options.driver;
}
async disconnect() {
this.queryRunner = undefined;
await this.databaseConnection.closeAsync();
this.databaseConnection = undefined;
}
createQueryRunner() {
if (!this.queryRunner) this.queryRunner = new vN.ExpoQueryRunner(this);
return this.queryRunner;
}
async createDatabaseConnection() {
this.databaseConnection = await this.sqlite.openDatabaseAsync(this.options.database);
await this.databaseConnection.runAsync("PRAGMA foreign_keys = ON");
return this.databaseConnection;
}
}
NN.ExpoDriver = ExpoDriver;
var IN = {};
var PN = {};
Object.defineProperty(PN, "__esModule", {
value: true
});
PN.ExpoLegacyQueryRunner = void 0;
const LN = Sn();
const DN = nn();
const _N = OE;
const $N = pe();
const xN = hf;
const qN = lf;
const UN = sc;
class ExpoLegacyQueryRunner extends _N.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new xN.Broadcaster(this);
}
async startTransaction() {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive && typeof this.transaction === "undefined") throw new $N.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
this.transaction = undefined;
this.isTransactionActive = false;
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive && typeof this.transaction === "undefined") throw new $N.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
this.transaction = undefined;
this.isTransactionActive = false;
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async beforeMigration() {
const e = await this.connect();
return new Promise((t, n) => {
e.exec([ {
sql: "PRAGMA foreign_keys = OFF",
args: []
} ], false, e => e ? n(e) : t());
});
}
async afterMigration() {
const e = await this.connect();
return new Promise((t, n) => {
e.exec([ {
sql: "PRAGMA foreign_keys = ON",
args: []
} ], false, e => e ? n(e) : t());
});
}
async query(e, t, n = false) {
if (this.isReleased) throw new LN.QueryRunnerAlreadyReleasedError;
return new Promise(async (a, r) => {
const i = await this.connect();
const s = new UN.BroadcasterResult;
this.driver.connection.logger.logQuery(e, t, this);
this.broadcaster.broadcastBeforeQueryEvent(s, e, t);
const o = Date.now();
i.transaction(async i => {
if (typeof this.transaction === "undefined") {
await this.startTransaction();
this.transaction = i;
}
this.transaction.executeSql(e, t, async (r, i) => {
const c = this.driver.options.maxQueryExecutionTime;
const l = Date.now();
const u = l - o;
this.broadcaster.broadcastAfterQueryEvent(s, e, t, true, u, i, undefined);
await s.wait();
if (c && u > c) {
this.driver.connection.logger.logQuerySlow(u, e, t, this);
}
const h = new qN.QueryResult;
if (i?.hasOwnProperty("rowsAffected")) {
h.affected = i.rowsAffected;
}
if (i?.hasOwnProperty("rows")) {
let e = [];
for (let t = 0; t < i.rows.length; t++) {
e.push(i.rows.item(t));
}
h.raw = e;
h.records = e;
}
if (e.startsWith("INSERT INTO")) {
h.raw = i.insertId;
}
if (n) {
a(h);
} else {
a(h.raw);
}
}, async (n, a) => {
this.driver.connection.logger.logQueryError(a, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(s, e, t, false, undefined, undefined, a);
await s.wait();
r(new DN.QueryFailedError(e, t, a));
});
}, async e => {
await this.rollbackTransaction();
r(e);
}, () => {
this.isTransactionActive = false;
this.transaction = undefined;
});
});
}
}
PN.ExpoLegacyQueryRunner = ExpoLegacyQueryRunner;
Object.defineProperty(IN, "__esModule", {
value: true
});
IN.ExpoLegacyDriver = void 0;
const BN = KE;
const FN = PN;
class ExpoLegacyDriver extends BN.AbstractSqliteDriver {
constructor(e) {
super(e);
this.database = this.options.database;
this.sqlite = this.options.driver;
}
async disconnect() {
return new Promise((e, t) => {
try {
this.queryRunner = undefined;
this.databaseConnection._db.close();
this.databaseConnection = undefined;
e();
} catch (e) {
t(e);
}
});
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new FN.ExpoLegacyQueryRunner(this);
return this.queryRunner;
}
createDatabaseConnection() {
return new Promise((e, t) => {
try {
const n = this.sqlite.openDatabase(this.options.database);
n.transaction(a => {
a.executeSql(`PRAGMA foreign_keys = ON`, [], (t, a) => {
e(n);
}, (e, n) => {
t({
transaction: e,
error: n
});
});
}, e => {
t(e);
});
} catch (e) {
t(e);
}
});
}
}
IN.ExpoLegacyDriver = ExpoLegacyDriver;
Object.defineProperty(gN, "__esModule", {
value: true
});
gN.ExpoDriverFactory = void 0;
const jN = NN;
const kN = IN;
class ExpoDriverFactory {
constructor(e) {
this.connection = e;
}
create() {
if (this.isLegacyDriver) {
return new kN.ExpoLegacyDriver(this.connection);
}
return new jN.ExpoDriver(this.connection);
}
get isLegacyDriver() {
return !("openDatabaseAsync" in this.connection.options.driver);
}
}
gN.ExpoDriverFactory = ExpoDriverFactory;
var QN = {};
var VN = {};
Object.defineProperty(VN, "__esModule", {
value: true
});
VN.AuroraMysqlQueryRunner = void 0;
const KN = lf;
const WN = pe();
const HN = yu;
const GN = fu;
const YN = Nu;
const zN = Tu;
const JN = Sn();
const XN = Bm;
const ZN = ef;
const eA = qc;
const tA = Cu;
const nA = Zm;
const aA = hf;
const rA = P;
const iA = mf;
const sA = Te;
class AuroraMysqlQueryRunner extends nA.BaseQueryRunner {
constructor(e, t) {
super();
this.driver = e;
this.connection = e.connection;
this.client = t;
this.broadcaster = new aA.Broadcaster(this);
}
async connect() {
return {};
}
release() {
this.isReleased = true;
if (this.databaseConnection) this.databaseConnection.release();
return Promise.resolve();
}
async startTransaction(e) {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
await this.client.startTransaction();
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new WN.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.client.commitTransaction();
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new WN.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.client.rollbackTransaction();
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new JN.QueryRunnerAlreadyReleasedError;
const a = await this.client.query(e, t);
const r = new KN.QueryResult;
r.raw = a;
if (a?.hasOwnProperty("records") && Array.isArray(a.records)) {
r.records = a.records;
}
if (a?.hasOwnProperty("numberOfRecordsUpdated")) {
r.affected = a.numberOfRecordsUpdated;
}
if (!n) {
return r.raw;
}
return r;
}
stream(e, t, n, a) {
if (this.isReleased) throw new JN.QueryRunnerAlreadyReleasedError;
return new Promise(async (r, i) => {
try {
const i = await this.connect();
const s = i.query(e, t);
if (n) s.on("end", n);
if (a) s.on("error", a);
r(s);
} catch (e) {
i(e);
}
});
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
throw new rA.TypeORMError(`MySql driver does not support table schemas`);
}
async hasDatabase(e) {
const t = await this.query(`SELECT * FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\` = '${e}'`);
return t.length ? true : false;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT DATABASE() AS \`db_name\``);
return e[0]["db_name"];
}
async hasSchema(e) {
throw new rA.TypeORMError(`MySql driver does not support table schemas`);
}
async getCurrentSchema() {
const e = await this.query(`SELECT SCHEMA() AS \`schema_name\``);
return e[0]["schema_name"];
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
const n = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${t.database}' AND \`TABLE_NAME\` = '${t.tableName}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
const a = sA.InstanceChecker.isTableColumn(t) ? t.name : t;
const r = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${n.database}' AND \`TABLE_NAME\` = '${n.tableName}' AND \`COLUMN_NAME\` = '${a}'`;
const i = await this.query(r);
return i.length ? true : false;
}
async createDatabase(e, t) {
const n = t ? `CREATE DATABASE IF NOT EXISTS \`${e}\`` : `CREATE DATABASE \`${e}\``;
const a = `DROP DATABASE \`${e}\``;
await this.executeQueries(new ZN.Query(n), new ZN.Query(a));
}
async dropDatabase(e, t) {
const n = t ? `DROP DATABASE IF EXISTS \`${e}\`` : `DROP DATABASE \`${e}\``;
const a = `CREATE DATABASE \`${e}\``;
await this.executeQueries(new ZN.Query(n), new ZN.Query(a));
}
async createSchema(e, t) {
throw new rA.TypeORMError(`Schema create queries are not supported by MySql driver.`);
}
async dropSchema(e, t) {
throw new rA.TypeORMError(`Schema drop queries are not supported by MySql driver.`);
}
async createTable(e, t = false, n = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const a = [];
const r = [];
a.push(this.createTableSql(e, n));
r.push(this.dropTableSql(e));
e.indices.forEach(t => r.push(this.dropIndexSql(e, t)));
if (n) e.foreignKeys.forEach(t => r.push(this.dropForeignKeySql(e, t)));
return this.executeQueries(a, r);
}
async dropTable(e, t, n = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const a = n;
const r = this.getTablePath(e);
const i = await this.getCachedTable(r);
const s = [];
const o = [];
if (n) i.foreignKeys.forEach(e => s.push(this.dropForeignKeySql(i, e)));
i.indices.forEach(e => s.push(this.dropIndexSql(i, e)));
s.push(this.dropTableSql(i));
o.push(this.createTableSql(i, a));
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = sA.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {database: s} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new ZN.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(i)}`));
a.push(new ZN.Query(`RENAME TABLE ${this.escapePath(i)} TO ${this.escapePath(r)}`));
i.indices.forEach(e => {
const t = e.columnNames.map(e => `\`${e}\``).join(", ");
const r = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
let s = "";
if (e.isUnique) s += "UNIQUE ";
if (e.isSpatial) s += "SPATIAL ";
if (e.isFulltext) s += "FULLTEXT ";
n.push(new ZN.Query(`ALTER TABLE ${this.escapePath(i)} DROP INDEX \`${e.name}\`, ADD ${s}INDEX \`${r}\` (${t})`));
a.push(new ZN.Query(`ALTER TABLE ${this.escapePath(i)} DROP INDEX \`${r}\`, ADD ${s}INDEX \`${e.name}\` (${t})`));
e.name = r;
});
i.foreignKeys.forEach(e => {
const t = e.columnNames.map(e => `\`${e}\``).join(", ");
const r = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
const s = this.connection.namingStrategy.foreignKeyName(i, e.columnNames);
let o = `ALTER TABLE ${this.escapePath(i)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${s}\` FOREIGN KEY (${t}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${r})`;
if (e.onDelete) o += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) o += ` ON UPDATE ${e.onUpdate}`;
let c = `ALTER TABLE ${this.escapePath(i)} DROP FOREIGN KEY \`${s}\`, ADD CONSTRAINT \`${e.name}\` FOREIGN KEY (${t}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${r})`;
if (e.onDelete) c += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) c += ` ON UPDATE ${e.onUpdate}`;
n.push(new ZN.Query(o));
a.push(new ZN.Query(c));
e.name = s;
});
await this.executeQueries(n, a);
r.name = i.name;
this.replaceCachedTable(r, i);
}
async addColumn(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
const s = a.primaryColumns.length > 0;
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t, s, false)}`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${t.name}\``));
if (t.isPrimary && s) {
const e = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const a = e.clone();
a.isGenerated = false;
a.generationStrategy = undefined;
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
const s = a.primaryColumns;
let o = s.map(e => `\`${e.name}\``).join(", ");
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
s.push(t);
o = s.map(e => `\`${e.name}\``).join(", ");
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
if (e) {
const a = e.clone();
a.isGenerated = false;
a.generationStrategy = undefined;
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
}
}
const o = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (o) {
r.push(this.createIndexSql(n, o));
i.push(this.dropIndexSql(n, o));
} else if (t.isUnique) {
const e = new zN.TableIndex({
name: this.connection.namingStrategy.indexName(n, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
});
a.indices.push(e);
a.uniques.push(new tA.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
r.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${e.name}\` (\`${t.name}\`)`));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${e.name}\``));
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = sA.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new rA.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i = undefined;
if (sA.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
await this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = sA.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!o) throw new rA.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (n.isGenerated !== o.isGenerated && n.generationStrategy !== "uuid" || o.type !== n.type || o.length !== n.length || o.generatedType !== n.generatedType) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.name !== o.name) {
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` \`${n.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${n.name}\` \`${o.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
r.findColumnIndices(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = e.columnNames.map(e => `\`${e}\``).join(", ");
const c = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
let l = "";
if (e.isUnique) l += "UNIQUE ";
if (e.isSpatial) l += "SPATIAL ";
if (e.isFulltext) l += "FULLTEXT ";
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\`, ADD ${l}INDEX \`${c}\` (${t})`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${c}\`, ADD ${l}INDEX \`${e.name}\` (${t})`));
e.name = c;
});
r.findColumnForeignKeys(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = e.columnNames.map(e => `\`${e}\``).join(", ");
const c = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
const l = this.connection.namingStrategy.foreignKeyName(r, e.columnNames);
let u = `ALTER TABLE ${this.escapePath(a)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${l}\` FOREIGN KEY (${t}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${c})`;
if (e.onDelete) u += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) u += ` ON UPDATE ${e.onUpdate}`;
let h = `ALTER TABLE ${this.escapePath(a)} DROP FOREIGN KEY \`${l}\`, ADD CONSTRAINT \`${e.name}\` FOREIGN KEY (${t}) ` + `REFERENCES ${this.escapePath(this.getTablePath(e))}(${c})`;
if (e.onDelete) h += ` ON DELETE ${e.onDelete}`;
if (e.onUpdate) h += ` ON UPDATE ${e.onUpdate}`;
i.push(new ZN.Query(u));
s.push(new ZN.Query(h));
e.name = l;
});
const e = r.columns.find(e => e.name === o.name);
r.columns[r.columns.indexOf(e)].name = n.name;
o.name = n.name;
}
if (this.isColumnChanged(o, n, true)) {
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(n, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${n.name}\` ${this.buildCreateColumnSql(o, true)}`));
}
if (n.isPrimary !== o.isPrimary) {
const e = r.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
}
const t = r.primaryColumns;
if (t.length > 0) {
const e = t.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
}
if (n.isPrimary === true) {
t.push(n);
const e = r.columns.find(e => e.name === n.name);
e.isPrimary = true;
const o = t.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${o})`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
} else {
const e = t.find(e => e.name === n.name);
t.splice(t.indexOf(e), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (t.length > 0) {
const e = t.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
}
}
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new zN.TableIndex({
name: this.connection.namingStrategy.indexName(a, [ n.name ]),
columnNames: [ n.name ],
isUnique: true
});
r.indices.push(e);
r.uniques.push(new tA.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
} else {
const e = r.indices.find(e => e.columnNames.length === 1 && e.isUnique === true && !!e.columnNames.find(e => e === n.name));
r.indices.splice(r.indices.indexOf(e), 1);
const t = r.uniques.find(t => t.name === e.name);
r.uniques.splice(r.uniques.indexOf(t), 1);
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
}
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = sA.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!a) throw new rA.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
if (a.isPrimary) {
const e = r.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (e) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
}
const t = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${t})`));
const o = r.findColumnByName(a.name);
o.isPrimary = false;
if (r.primaryColumns.length > 0) {
const e = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${e})`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
}
if (e && e.name !== a.name) {
const t = e.clone();
t.isGenerated = false;
t.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
}
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
} else if (a.isUnique) {
const e = this.connection.namingStrategy.uniqueConstraintName(n, [ a.name ]);
const t = r.uniques.find(t => t.name === e);
if (t) r.uniques.splice(r.uniques.indexOf(t), 1);
const o = this.connection.namingStrategy.indexName(n, [ a.name ]);
const c = r.indices.find(e => e.name === o);
if (c) r.indices.splice(r.indices.indexOf(c), 1);
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${o}\``));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${o}\` (\`${a.name}\`)`));
}
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${a.name}\``));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a, true)}`));
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = this.createPrimaryKeySql(n, t);
const i = this.dropPrimaryKeySql(n);
await this.executeQueries(r, i);
a.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
this.replaceCachedTable(n, a);
}
async updatePrimaryKeys(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = t.map(e => e.name);
const i = [];
const s = [];
const o = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
if (o) {
const e = o.clone();
e.isGenerated = false;
e.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(e, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(o, true)}`));
}
const c = a.primaryColumns;
if (c.length > 0) {
const e = c.map(e => `\`${e.name}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${e})`));
}
a.columns.filter(e => r.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const l = r.map(e => `\`${e}\``).join(", ");
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${l})`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
const u = o ? o : t.find(e => e.isGenerated && e.generationStrategy === "increment");
if (u) {
const e = u.clone();
e.isGenerated = false;
e.generationStrategy = undefined;
i.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(u, true)}`));
s.push(new ZN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${u.name}\` ${this.buildCreateColumnSql(e, true)}`));
const t = a.columns.find(e => e.name === u.name);
t.isGenerated = true;
t.generationStrategy = "increment";
}
await this.executeQueries(i, s);
this.replaceCachedTable(n, a);
}
async dropPrimaryKey(e) {
const t = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const n = this.dropPrimaryKeySql(t);
const a = this.createPrimaryKeySql(t, t.primaryColumns.map(e => e.name));
await this.executeQueries(n, a);
t.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async createUniqueConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
}
async createCheckConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support check constraints.`);
}
async createCheckConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support check constraints.`);
}
async dropCheckConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support check constraints.`);
}
async dropCheckConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support check constraints.`);
}
async createExclusionConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new rA.TypeORMError(`MySql does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new rA.TypeORMError(`MySql does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
const n = t.map(t => this.createForeignKey(e, t));
await Promise.all(n);
}
async dropForeignKey(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = sA.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new rA.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
const n = t.map(t => this.dropForeignKey(e, t));
await Promise.all(n);
}
async createIndex(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t, true);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = sA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = sA.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new rA.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a, true);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase(e) {
const t = e ? e : this.driver.database;
if (t) {
const e = await this.hasDatabase(t);
if (!e) return Promise.resolve();
} else {
throw new rA.TypeORMError(`Can not clear database. No database is specified`);
}
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = `SELECT concat('DROP VIEW IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`VIEWS\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
const a = await this.query(e);
await Promise.all(a.map(e => this.query(e["query"])));
const r = `SET FOREIGN_KEY_CHECKS = 0;`;
const i = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
const s = `SET FOREIGN_KEY_CHECKS = 1;`;
await this.query(r);
const o = await this.query(i);
await Promise.all(o.map(e => this.query(e["query"])));
await this.query(s);
if (!n) {
await this.commitTransaction();
}
} catch (e) {
try {
if (!n) {
await this.rollbackTransaction();
}
} catch (e) {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = e.map(e => {
let {database: t, tableName: a} = this.driver.parseTableName(e);
if (!t) {
t = n;
}
return `(\`t\`.\`schema\` = '${t}' AND \`t\`.\`name\` = '${a}')`;
}).join(" OR ");
const r = `SELECT \`t\`.*, \`v\`.\`check_option\` FROM ${this.escapePath(this.getTypeormMetadataTableName())} \`t\` ` + `INNER JOIN \`information_schema\`.\`views\` \`v\` ON \`v\`.\`table_schema\` = \`t\`.\`schema\` AND \`v\`.\`table_name\` = \`t\`.\`name\` WHERE \`t\`.\`type\` = '${iA.MetadataTableType.VIEW}' ${a ? `AND (${a})` : ""}`;
const i = await this.query(r);
return i.map(e => {
const t = new XN.View;
const a = e["schema"] === n ? undefined : e["schema"];
t.database = e["schema"];
t.name = this.driver.buildTableName(e["name"], undefined, a);
t.expression = e["value"];
return t;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = [];
const n = await this.getCurrentDatabase();
if (!e) {
const e = `SELECT TABLE_NAME, TABLE_SCHEMA FROM \`INFORMATION_SCHEMA\`.\`TABLES\``;
t.push(...await this.query(e));
} else {
const a = e.map(e => {
let [t, a] = e.split(".");
if (!a) {
a = t;
t = this.driver.database || n;
}
return `(\`TABLE_SCHEMA\` = '${t}' AND \`TABLE_NAME\` = '${a}')`;
}).join(" OR ");
const r = `SELECT TABLE_NAME, TABLE_SCHEMA FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE ` + a;
t.push(...await this.query(r));
}
if (t.length === 0) {
return [];
}
const a = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `(\`TABLE_SCHEMA\` = '${t}' AND \`TABLE_NAME\` = '${e}')`).join(" OR ");
const r = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE ` + a;
const i = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` WHERE \`CONSTRAINT_NAME\` = 'PRIMARY' AND (${a})`;
const s = `SELECT \`SCHEMA_NAME\`, \`DEFAULT_CHARACTER_SET_NAME\` as \`CHARSET\`, \`DEFAULT_COLLATION_NAME\` AS \`COLLATION\` FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\``;
const o = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `(\`s\`.\`TABLE_SCHEMA\` = '${t}' AND \`s\`.\`TABLE_NAME\` = '${e}')`).join(" OR ");
const c = `SELECT \`s\`.* FROM \`INFORMATION_SCHEMA\`.\`STATISTICS\` \`s\` ` + `LEFT JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`rc\` ON \`s\`.\`INDEX_NAME\` = \`rc\`.\`CONSTRAINT_NAME\` ` + `WHERE (${o}) AND \`s\`.\`INDEX_NAME\` != 'PRIMARY' AND \`rc\`.\`CONSTRAINT_NAME\` IS NULL`;
const l = t.map(({TABLE_NAME: e, TABLE_SCHEMA: t}) => `(\`kcu\`.\`TABLE_SCHEMA\` = '${t}' AND \`kcu\`.\`TABLE_NAME\` = '${e}')`).join(" OR ");
const u = `SELECT \`kcu\`.\`TABLE_SCHEMA\`, \`kcu\`.\`TABLE_NAME\`, \`kcu\`.\`CONSTRAINT_NAME\`, \`kcu\`.\`COLUMN_NAME\`, \`kcu\`.\`REFERENCED_TABLE_SCHEMA\`, ` + `\`kcu\`.\`REFERENCED_TABLE_NAME\`, \`kcu\`.\`REFERENCED_COLUMN_NAME\`, \`rc\`.\`DELETE_RULE\` \`ON_DELETE\`, \`rc\`.\`UPDATE_RULE\` \`ON_UPDATE\` ` + `FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`kcu\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`rc\` ON \`rc\`.\`constraint_name\` = \`kcu\`.\`constraint_name\` ` + `WHERE ` + l;
const [h, d, p, m, f] = await Promise.all([ this.query(r), this.query(i), this.query(s), this.query(c), this.query(u) ]);
return Promise.all(t.map(async e => {
const t = new GN.Table;
const a = p.find(t => t["SCHEMA_NAME"] === e["TABLE_SCHEMA"]);
const r = a["COLLATION"];
const i = a["CHARSET"];
const s = e["TABLE_SCHEMA"] === n ? undefined : e["TABLE_SCHEMA"];
t.database = e["TABLE_SCHEMA"];
t.name = this.driver.buildTableName(e["TABLE_NAME"], undefined, s);
t.columns = h.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]).map(n => {
const a = m.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["COLUMN_NAME"] === n["COLUMN_NAME"] && parseInt(t["NON_UNIQUE"], 10) === 0);
const s = this.connection.entityMetadatas.find(e => this.getTablePath(t) === this.getTablePath(e));
const o = a.length > 0 && s && s.indices.some(e => a.some(t => e.name === t["INDEX_NAME"] && e.synchronize === false));
const c = a.every(e => m.some(t => t["INDEX_NAME"] === e["INDEX_NAME"] && t["COLUMN_NAME"] !== n["COLUMN_NAME"]));
const l = new HN.TableColumn;
l.name = n["COLUMN_NAME"];
l.type = n["DATA_TYPE"].toLowerCase();
l.unsigned = l.zerofill ? true : n["COLUMN_TYPE"].indexOf("unsigned") !== -1;
if (this.driver.withWidthColumnTypes.indexOf(l.type) !== -1) {
const e = n["COLUMN_TYPE"].substring(n["COLUMN_TYPE"].indexOf("(") + 1, n["COLUMN_TYPE"].indexOf(")"));
l.width = e && !this.isDefaultColumnWidth(t, l, parseInt(e)) ? parseInt(e) : undefined;
}
if (n["COLUMN_DEFAULT"] === null || n["COLUMN_DEFAULT"] === undefined) {
l.default = undefined;
} else {
l.default = n["COLUMN_DEFAULT"] === "CURRENT_TIMESTAMP" ? n["COLUMN_DEFAULT"] : `'${n["COLUMN_DEFAULT"]}'`;
}
if (n["EXTRA"].indexOf("on update") !== -1) {
l.onUpdate = n["EXTRA"].substring(n["EXTRA"].indexOf("on update") + 10);
}
if (n["GENERATION_EXPRESSION"]) {
l.asExpression = n["GENERATION_EXPRESSION"];
l.generatedType = n["EXTRA"].indexOf("VIRTUAL") !== -1 ? "VIRTUAL" : "STORED";
}
l.isUnique = a.length > 0 && !o && !c;
l.isNullable = n["IS_NULLABLE"] === "YES";
l.isPrimary = d.some(e => e["TABLE_NAME"] === n["TABLE_NAME"] && e["TABLE_SCHEMA"] === n["TABLE_SCHEMA"] && e["COLUMN_NAME"] === n["COLUMN_NAME"]);
l.zerofill = n["COLUMN_TYPE"].indexOf("zerofill") !== -1;
l.isGenerated = n["EXTRA"].indexOf("auto_increment") !== -1;
if (l.isGenerated) l.generationStrategy = "increment";
l.comment = typeof n["COLUMN_COMMENT"] === "string" && n["COLUMN_COMMENT"].length === 0 ? undefined : n["COLUMN_COMMENT"];
if (n["CHARACTER_SET_NAME"]) l.charset = n["CHARACTER_SET_NAME"] === i ? undefined : n["CHARACTER_SET_NAME"];
if (n["COLLATION_NAME"]) l.collation = n["COLLATION_NAME"] === r ? undefined : n["COLLATION_NAME"];
if (this.driver.withLengthColumnTypes.indexOf(l.type) !== -1 && n["CHARACTER_MAXIMUM_LENGTH"]) {
const e = n["CHARACTER_MAXIMUM_LENGTH"].toString();
l.length = !this.isDefaultColumnLength(t, l, e) ? e : "";
}
if (l.type === "decimal" || l.type === "double" || l.type === "float") {
if (n["NUMERIC_PRECISION"] !== null && !this.isDefaultColumnPrecision(t, l, n["NUMERIC_PRECISION"])) l.precision = parseInt(n["NUMERIC_PRECISION"]);
if (n["NUMERIC_SCALE"] !== null && !this.isDefaultColumnScale(t, l, n["NUMERIC_SCALE"])) l.scale = parseInt(n["NUMERIC_SCALE"]);
}
if (l.type === "enum" || l.type === "simple-enum" || l.type === "set") {
const e = n["COLUMN_TYPE"];
const t = e.substring(e.indexOf("(") + 1, e.lastIndexOf(")")).split(",");
l.enum = t.map(e => e.substring(1, e.length - 1));
l.length = "";
}
if ((l.type === "datetime" || l.type === "time" || l.type === "timestamp") && n["DATETIME_PRECISION"] !== null && n["DATETIME_PRECISION"] !== undefined && !this.isDefaultColumnPrecision(t, l, parseInt(n["DATETIME_PRECISION"]))) {
l.precision = parseInt(n["DATETIME_PRECISION"]);
}
return l;
});
const o = eA.OrmUtils.uniq(f.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]), e => e["CONSTRAINT_NAME"]);
t.foreignKeys = o.map(e => {
const t = f.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
const a = e["REFERENCED_TABLE_SCHEMA"] === n ? undefined : e["REFERENCED_TABLE_SCHEMA"];
const r = this.driver.buildTableName(e["REFERENCED_TABLE_NAME"], undefined, a);
return new YN.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: e["REFERENCED_TABLE_SCHEMA"],
referencedTableName: r,
referencedColumnNames: t.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["ON_DELETE"],
onUpdate: e["ON_UPDATE"]
});
});
const c = eA.OrmUtils.uniq(m.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"]), e => e["INDEX_NAME"]);
t.indices = c.map(e => {
const n = m.filter(t => t["TABLE_SCHEMA"] === e["TABLE_SCHEMA"] && t["TABLE_NAME"] === e["TABLE_NAME"] && t["INDEX_NAME"] === e["INDEX_NAME"]);
const a = parseInt(e["NON_UNIQUE"], 10);
return new zN.TableIndex({
table: t,
name: e["INDEX_NAME"],
columnNames: n.map(e => e["COLUMN_NAME"]),
isUnique: a === 0,
isSpatial: e["INDEX_TYPE"] === "SPATIAL",
isFulltext: e["INDEX_TYPE"] === "FULLTEXT"
});
});
return t;
}));
}
createTableSql(e, t) {
const n = e.columns.map(e => this.buildCreateColumnSql(e, true)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.indices.some(e => e.columnNames.length === 1 && !!e.isUnique && e.columnNames.indexOf(t.name) !== -1);
const a = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames.indexOf(t.name) !== -1);
if (!n && !a) e.indices.push(new zN.TableIndex({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
}));
});
if (e.uniques.length > 0) {
e.uniques.forEach(t => {
const n = e.indices.some(e => e.name === t.name);
if (!n) {
e.indices.push(new zN.TableIndex({
name: t.name,
columnNames: t.columnNames,
isUnique: true
}));
}
});
}
if (e.indices.length > 0) {
const t = e.indices.map(t => {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
let a = "";
if (t.isUnique) a += "UNIQUE ";
if (t.isSpatial) a += "SPATIAL ";
if (t.isFulltext) a += "FULLTEXT ";
return `${a}INDEX \`${t.name}\` (${n})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames);
const a = t.referencedColumnNames.map(e => `\`${e}\``).join(", ");
let r = `CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return r;
}).join(", ");
a += `, ${t}`;
}
if (e.primaryColumns.length > 0) {
const t = e.primaryColumns.map(e => `\`${e.name}\``).join(", ");
a += `, PRIMARY KEY (${t})`;
}
a += `) ENGINE=${e.engine || "InnoDB"}`;
return new ZN.Query(a);
}
dropTableSql(e) {
return new ZN.Query(`DROP TABLE ${this.escapePath(e)}`);
}
createViewSql(e) {
if (typeof e.expression === "string") {
return new ZN.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
} else {
return new ZN.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
const t = await this.getCurrentDatabase();
const n = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: iA.MetadataTableType.VIEW,
schema: t,
name: e.name,
value: n
});
}
dropViewSql(e) {
return new ZN.Query(`DROP VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const t = await this.getCurrentDatabase();
const n = sA.InstanceChecker.isView(e) ? e.name : e;
return this.deleteTypeormMetadataSql({
type: iA.MetadataTableType.VIEW,
schema: t,
name: n
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
let a = "";
if (t.isUnique) a += "UNIQUE ";
if (t.isSpatial) a += "SPATIAL ";
if (t.isFulltext) a += "FULLTEXT ";
return new ZN.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})`);
}
dropIndexSql(e, t) {
const n = sA.InstanceChecker.isTableIndex(t) ? t.name : t;
return new ZN.Query(`DROP INDEX \`${n}\` ON ${this.escapePath(e)}`);
}
createPrimaryKeySql(e, t) {
const n = t.map(e => `\`${e}\``).join(", ");
return new ZN.Query(`ALTER TABLE ${this.escapePath(e)} ADD PRIMARY KEY (${n})`);
}
dropPrimaryKeySql(e) {
return new ZN.Query(`ALTER TABLE ${this.escapePath(e)} DROP PRIMARY KEY`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
const a = t.referencedColumnNames.map(e => `\`${e}\``).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) r += ` ON DELETE ${t.onDelete}`;
if (t.onUpdate) r += ` ON UPDATE ${t.onUpdate}`;
return new ZN.Query(r);
}
dropForeignKeySql(e, t) {
const n = sA.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new ZN.Query(`ALTER TABLE ${this.escapePath(e)} DROP FOREIGN KEY \`${n}\``);
}
escapeComment(e) {
if (!e || e.length === 0) {
return `''`;
}
e = e.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\u0000/g, "");
return `'${e}'`;
}
escapePath(e) {
const {database: t, tableName: n} = this.driver.parseTableName(e);
if (t && t !== this.driver.database) {
return `\`${t}\`.\`${n}\``;
}
return `\`${n}\``;
}
buildCreateColumnSql(e, t, n = false) {
let a = "";
if (n) {
a = this.connection.driver.createFullType(e);
} else {
a = `\`${e.name}\` ${this.connection.driver.createFullType(e)}`;
}
if (e.asExpression) a += ` AS (${e.asExpression}) ${e.generatedType ? e.generatedType : "VIRTUAL"}`;
if (e.zerofill) {
a += " ZEROFILL";
} else if (e.unsigned) {
a += " UNSIGNED";
}
if (e.enum) a += ` (${e.enum.map(e => "'" + e + "'").join(", ")})`;
if (e.charset) a += ` CHARACTER SET "${e.charset}"`;
if (e.collation) a += ` COLLATE "${e.collation}"`;
if (!e.isNullable) a += " NOT NULL";
if (e.isNullable) a += " NULL";
if (e.isPrimary && !t) a += " PRIMARY KEY";
if (e.isGenerated && e.generationStrategy === "increment") a += " AUTO_INCREMENT";
if (e.comment) a += ` COMMENT ${this.escapeComment(e.comment)}`;
if (e.default !== undefined && e.default !== null) a += ` DEFAULT ${e.default}`;
if (e.onUpdate) a += ` ON UPDATE ${e.onUpdate}`;
return a;
}
isDefaultColumnWidth(e, t, n) {
if (this.connection.hasMetadata(e.name)) {
const n = this.connection.getMetadata(e.name);
const a = n.findColumnWithDatabaseName(t.name);
if (a && a.width) return false;
}
const a = this.connection.driver.dataTypeDefaults && this.connection.driver.dataTypeDefaults[t.type] && this.connection.driver.dataTypeDefaults[t.type].width;
if (a) {
const e = [ "int", "tinyint", "smallint", "mediumint" ];
const r = e.indexOf(t.type) !== -1;
if (t.unsigned && r) {
return a - 1 === n;
} else {
return a === n;
}
}
return false;
}
changeTableComment(e, t) {
throw new rA.TypeORMError(`aurora-mysql driver does not support change table comment.`);
}
}
VN.AuroraMysqlQueryRunner = AuroraMysqlQueryRunner;
Object.defineProperty(QN, "__esModule", {
value: true
});
QN.AuroraMysqlDriver = void 0;
const oA = jn;
const cA = VN;
const lA = up;
const uA = Uh;
const hA = Um;
const dA = qc;
const pA = _s;
const mA = P;
const fA = Te;
class AuroraMysqlDriver {
constructor(e) {
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "nested";
this.supportedDataTypes = [ "bit", "int", "integer", "tinyint", "smallint", "mediumint", "bigint", "float", "double", "double precision", "real", "decimal", "dec", "numeric", "fixed", "bool", "boolean", "date", "datetime", "timestamp", "time", "year", "char", "nchar", "national char", "varchar", "nvarchar", "national varchar", "blob", "text", "tinyblob", "tinytext", "mediumblob", "mediumtext", "longblob", "longtext", "enum", "set", "binary", "varbinary", "json", "geometry", "point", "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", "geometrycollection" ];
this.supportedUpsertTypes = [ "on-duplicate-key-update" ];
this.spatialTypes = [ "geometry", "point", "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", "geometrycollection" ];
this.withLengthColumnTypes = [ "char", "varchar", "nvarchar", "binary", "varbinary" ];
this.withWidthColumnTypes = [ "bit", "tinyint", "smallint", "mediumint", "int", "integer", "bigint" ];
this.withPrecisionColumnTypes = [ "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real", "time", "datetime", "timestamp" ];
this.withScaleColumnTypes = [ "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real" ];
this.unsignedAndZerofillTypes = [ "int", "integer", "smallint", "tinyint", "mediumint", "bigint", "decimal", "dec", "numeric", "fixed", "float", "double", "double precision", "real" ];
this.mappedDataTypes = {
createDate: "datetime",
createDatePrecision: 6,
createDateDefault: "CURRENT_TIMESTAMP(6)",
updateDate: "datetime",
updateDatePrecision: 6,
updateDateDefault: "CURRENT_TIMESTAMP(6)",
deleteDate: "datetime",
deleteDatePrecision: 6,
deleteDateNullable: true,
version: "int",
treeLevel: "int",
migrationId: "int",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "varchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text"
};
this.dataTypeDefaults = {
varchar: {
length: 255
},
nvarchar: {
length: 255
},
"national varchar": {
length: 255
},
char: {
length: 1
},
binary: {
length: 1
},
varbinary: {
length: 255
},
decimal: {
precision: 10,
scale: 0
},
dec: {
precision: 10,
scale: 0
},
numeric: {
precision: 10,
scale: 0
},
fixed: {
precision: 10,
scale: 0
},
float: {
precision: 12
},
double: {
precision: 22
},
time: {
precision: 0
},
datetime: {
precision: 0
},
timestamp: {
precision: 0
},
bit: {
width: 1
},
int: {
width: 11
},
integer: {
width: 11
},
tinyint: {
width: 4
},
smallint: {
width: 6
},
mediumint: {
width: 9
},
bigint: {
width: 20
}
};
this.maxAliasLength = 63;
this.cteCapabilities = {
enabled: false
};
this.connection = e;
this.options = e.options;
this.loadDependencies();
this.client = new this.DataApiDriver(this.options.region, this.options.secretArn, this.options.resourceArn, this.options.database, (e, t) => this.connection.logger.logQuery(e, t), this.options.serviceConfigOptions, this.options.formatOptions);
this.database = oA.DriverUtils.buildDriverOptions(this.options).database;
}
async connect() {
if (!this.database) {
const e = this.createQueryRunner("master");
this.database = await e.getCurrentDatabase();
await e.release();
}
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {}
createSchemaBuilder() {
return new hA.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new cA.AuroraMysqlQueryRunner(this, new this.DataApiDriver(this.options.region, this.options.secretArn, this.options.resourceArn, this.options.database, (e, t) => this.connection.logger.logQuery(e, t), this.options.serviceConfigOptions, this.options.formatOptions));
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, r) => {
if (!t.hasOwnProperty(r)) {
return e;
}
const i = t[r];
if (n) {
return i.map(e => {
a.push(e);
return this.createParameter(r, a.length - 1);
}).join(", ");
}
if (typeof i === "function") {
return i();
}
a.push(i);
return this.createParameter(r, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return "`" + e + "`";
}
buildTableName(e, t, n) {
const a = [ e ];
if (n) {
a.unshift(n);
}
return a.join(".");
}
parseTableName(e) {
const t = this.database;
const n = undefined;
if (fA.InstanceChecker.isTable(e) || fA.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (fA.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (fA.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: (a.length > 1 ? a[0] : undefined) || t,
schema: n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
preparePersistentValue(e, t) {
if (t.transformer) e = pA.ApplyValueTransformers.transformTo(t.transformer, e);
if (!this.options.formatOptions || this.options.formatOptions.castParameters !== false) {
return this.client.preparePersistentValue(e, t);
}
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return lA.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return lA.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "json") {
return JSON.stringify(e);
} else if (t.type === "timestamp" || t.type === "datetime" || t.type === Date) {
return lA.DateUtils.mixedDateToDate(e);
} else if (t.type === "simple-array" || t.type === "set") {
return lA.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return lA.DateUtils.simpleJsonToString(e);
} else if (t.type === "enum" || t.type === "simple-enum") {
return "" + e;
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? pA.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (!this.options.formatOptions || this.options.formatOptions.castParameters !== false) {
return this.client.prepareHydratedValue(e, t);
}
if (t.type === Boolean || t.type === "bool" || t.type === "boolean") {
e = e ? true : false;
} else if (t.type === "datetime" || t.type === Date) {
e = lA.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = lA.DateUtils.mixedDateToDateString(e);
} else if (t.type === "json") {
e = typeof e === "string" ? JSON.parse(e) : e;
} else if (t.type === "time") {
e = lA.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array" || t.type === "set") {
e = lA.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = lA.DateUtils.stringToSimpleJson(e);
} else if ((t.type === "enum" || t.type === "simple-enum") && t.enum && !isNaN(e) && t.enum.indexOf(parseInt(e)) >= 0) {
e = parseInt(e);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = pA.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number || e.type === "integer") {
return "int";
} else if (e.type === String) {
return "varchar";
} else if (e.type === Date) {
return "datetime";
} else if (e.type === Buffer) {
return "blob";
} else if (e.type === Boolean) {
return "tinyint";
} else if (e.type === "uuid") {
return "varchar";
} else if (e.type === "simple-array" || e.type === "simple-json") {
return "text";
} else if (e.type === "simple-enum") {
return "enum";
} else if (e.type === "double precision" || e.type === "real") {
return "double";
} else if (e.type === "dec" || e.type === "numeric" || e.type === "fixed") {
return "decimal";
} else if (e.type === "bool" || e.type === "boolean") {
return "tinyint";
} else if (e.type === "nvarchar" || e.type === "national varchar") {
return "varchar";
} else if (e.type === "nchar" || e.type === "national char") {
return "char";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
const t = e.default;
if (t === null) {
return undefined;
}
if ((e.type === "enum" || e.type === "simple-enum") && t !== undefined) {
return `'${t}'`;
}
if (e.type === "set" && t !== undefined) {
return `'${lA.DateUtils.simpleArrayToString(t)}'`;
}
if (typeof t === "number") {
return `${t}`;
}
if (typeof t === "boolean") {
return t ? "1" : "0";
}
if (typeof t === "function") {
return t();
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.indices.some(t => t.isUnique && t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
if (e.generationStrategy === "uuid") return "36";
switch (e.type) {
case String:
case "varchar":
case "nvarchar":
case "national varchar":
return "255";
case "varbinary":
return "255";
default:
return "";
}
}
createFullType(e) {
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.width) {
t += `(${e.width})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += `(${e.precision},${e.scale})`;
} else if (e.precision !== null && e.precision !== undefined) {
t += `(${e.precision})`;
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
return new Promise((e, t) => {
if (this.poolCluster) {
this.poolCluster.getConnection("MASTER", (n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
} else if (this.pool) {
this.pool.getConnection((n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
} else {
t(new mA.TypeORMError(`Connection is not established with mysql database`));
}
});
}
obtainSlaveConnection() {
if (!this.poolCluster) return this.obtainMasterConnection();
return new Promise((e, t) => {
this.poolCluster.getConnection("SLAVE*", (n, a) => {
n ? t(n) : e(this.prepareDbConnection(a));
});
});
}
createGeneratedMap(e, t, n) {
const a = e.generatedColumns.reduce((e, a) => {
let r;
if (a.generationStrategy === "increment" && t.insertId) {
r = t.insertId + n;
}
return dA.OrmUtils.mergeDeep(e, a.createValueMap(r));
}, {});
return Object.keys(a).length > 0 ? a : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
let a = t.length;
if (!a && t.generationStrategy === "uuid") {
a = this.getColumnLength(t);
}
return n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== a || n.width !== t.width || n.precision !== t.precision || n.scale !== t.scale || n.zerofill !== t.zerofill || n.unsigned !== t.unsigned || n.asExpression !== t.asExpression || n.generatedType !== t.generatedType || n.comment !== this.escapeComment(t.comment) || !this.compareDefaultValues(this.normalizeDefault(t), n.default) || n.enum && t.enum && !dA.OrmUtils.isArraysEqual(n.enum, t.enum.map(e => e + "")) || n.onUpdate !== t.onUpdate || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.isUnique !== this.normalizeIsUnique(t) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
});
}
isReturningSqlSupported() {
return false;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return true;
}
createParameter(e, t) {
return "?";
}
loadDependencies() {
const e = this.options.driver || uA.PlatformTools.load("typeorm-aurora-data-api-driver");
this.DataApiDriver = e;
this.DataApiDriver = this.DataApiDriver.default || this.DataApiDriver;
}
createConnectionOptions(e, t) {
t = Object.assign({}, t, oA.DriverUtils.buildDriverOptions(t));
return Object.assign({}, {
resourceArn: e.resourceArn,
secretArn: e.secretArn,
database: e.database,
region: e.region,
type: e.type
}, {
host: t.host,
user: t.username,
password: t.password,
database: t.database,
port: t.port,
ssl: e.ssl
}, e.extra || {});
}
async createPool(e) {
return {};
}
prepareDbConnection(e) {
const {logger: t} = this.connection;
if (e.listeners("error").length === 0) {
e.on("error", e => t.log("warn", `MySQL connection raised an error. ${e}`));
}
return e;
}
compareDefaultValues(e, t) {
if (typeof e === "string" && typeof t === "string") {
e = e.replace(/^'+|'+$/g, "");
t = t.replace(/^'+|'+$/g, "");
}
return e === t;
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/\u0000/g, "");
return e;
}
}
QN.AuroraMysqlDriver = AuroraMysqlDriver;
var yA = {};
var EA = {};
Object.defineProperty(EA, "__esModule", {
value: true
});
EA.AuroraPostgresQueryRunner = void 0;
const TA = Sn();
const gA = pe();
const NA = Bg;
const AA = lf;
const bA = P;
class PostgresQueryRunnerWrapper extends NA.PostgresQueryRunner {
constructor(e, t) {
super(e, t);
}
}
class AuroraPostgresQueryRunner extends PostgresQueryRunnerWrapper {
constructor(e, t, n) {
super(e, n);
this.client = t;
}
connect() {
if (this.databaseConnection) return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise) return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
this.releaseCallback = t;
return this.databaseConnection;
});
} else {
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(([e, t]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = e;
this.releaseCallback = t;
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
async startTransaction(e) {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
if (this.transactionDepth === 0) {
await this.client.startTransaction();
} else {
await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
}
this.transactionDepth += 1;
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive) throw new gA.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth > 1) {
await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.client.commitTransaction();
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive) throw new gA.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
} else {
await this.client.rollbackTransaction();
this.isTransactionActive = false;
}
this.transactionDepth -= 1;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new TA.QueryRunnerAlreadyReleasedError;
const a = await this.client.query(e, t);
const r = new AA.QueryResult;
r.raw = a;
if (a?.hasOwnProperty("records") && Array.isArray(a.records)) {
r.records = a.records;
}
if (a?.hasOwnProperty("numberOfRecordsUpdated")) {
r.affected = a.numberOfRecordsUpdated;
}
if (!n) {
return r.raw;
}
return r;
}
changeTableComment(e, t) {
throw new bA.TypeORMError(`aurora-postgres driver does not support change comment.`);
}
}
EA.AuroraPostgresQueryRunner = AuroraPostgresQueryRunner;
Object.defineProperty(yA, "__esModule", {
value: true
});
yA.AuroraPostgresDriver = void 0;
const CA = Ug;
const RA = Uh;
const SA = EA;
const wA = _s;
const MA = jn;
class PostgresWrapper extends CA.PostgresDriver {}
class AuroraPostgresDriver extends PostgresWrapper {
constructor(e) {
super();
this.transactionSupport = "nested";
this.connection = e;
this.options = e.options;
this.isReplicated = false;
this.loadDependencies();
this.client = new this.DataApiDriver(this.options.region, this.options.secretArn, this.options.resourceArn, this.options.database, (e, t) => this.connection.logger.logQuery(e, t), this.options.serviceConfigOptions, this.options.formatOptions);
this.database = MA.DriverUtils.buildDriverOptions(this.options).database;
}
async connect() {}
async disconnect() {}
createQueryRunner(e) {
return new SA.AuroraPostgresQueryRunner(this, new this.DataApiDriver(this.options.region, this.options.secretArn, this.options.resourceArn, this.options.database, (e, t) => this.connection.logger.logQuery(e, t), this.options.serviceConfigOptions, this.options.formatOptions), e);
}
preparePersistentValue(e, t) {
if (this.options.formatOptions && this.options.formatOptions.castParameters === false) {
return super.preparePersistentValue(e, t);
}
if (t.transformer) e = wA.ApplyValueTransformers.transformTo(t.transformer, e);
return this.client.preparePersistentValue(e, t);
}
prepareHydratedValue(e, t) {
if (this.options.formatOptions && this.options.formatOptions.castParameters === false) {
return super.prepareHydratedValue(e, t);
}
if (t.transformer) e = wA.ApplyValueTransformers.transformFrom(t.transformer, e);
return this.client.prepareHydratedValue(e, t);
}
loadDependencies() {
const e = this.options.driver || RA.PlatformTools.load("typeorm-aurora-data-api-driver");
const {pg: t} = e;
this.DataApiDriver = t;
}
executeQuery(e, t) {
return this.connection.query(t);
}
async afterConnect() {
const e = await this.checkMetadataForExtensions();
if (e.hasExtensions) {
await this.enableExtensions(e, this.connection);
}
return Promise.resolve();
}
}
yA.AuroraPostgresDriver = AuroraPostgresDriver;
var OA = {};
var vA = {};
Object.defineProperty(vA, "__esModule", {
value: true
});
vA.SapQueryRunner = void 0;
const IA = y;
const PA = P;
const LA = Sn();
const DA = ye();
const _A = pe();
const $A = Zm;
const xA = py;
const qA = lf;
const UA = fu;
const BA = Su;
const FA = yu;
const jA = Nu;
const kA = Tu;
const QA = Cu;
const VA = Bm;
const KA = hf;
const WA = sc;
const HA = Te;
const GA = qc;
const YA = ef;
const zA = mf;
class SapQueryRunner extends $A.BaseQueryRunner {
constructor(e, t) {
super();
this.lock = new xA.QueryLock;
this.driver = e;
this.connection = e.connection;
this.broadcaster = new KA.Broadcaster(this);
this.mode = t;
}
async connect() {
if (this.databaseConnection) return this.databaseConnection;
this.databaseConnection = await this.driver.obtainMasterConnection();
return this.databaseConnection;
}
release() {
this.isReleased = true;
if (this.databaseConnection) {
return this.driver.master.release(this.databaseConnection);
}
return Promise.resolve();
}
async startTransaction(e) {
if (this.isReleased) throw new LA.QueryRunnerAlreadyReleasedError;
if (this.isTransactionActive && this.driver.transactionSupport === "simple") throw new DA.TransactionAlreadyStartedError;
await this.broadcaster.broadcast("BeforeTransactionStart");
this.isTransactionActive = true;
await this.setAutoCommit({
status: "off"
});
if (e) {
await this.query(`SET TRANSACTION ISOLATION LEVEL ${e || ""}`);
}
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (this.isReleased) throw new LA.QueryRunnerAlreadyReleasedError;
if (!this.isTransactionActive) throw new _A.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
await this.query("COMMIT");
this.isTransactionActive = false;
await this.setAutoCommit({
status: "on"
});
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (this.isReleased) throw new LA.QueryRunnerAlreadyReleasedError;
if (!this.isTransactionActive) throw new _A.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
await this.query("ROLLBACK");
this.isTransactionActive = false;
await this.setAutoCommit({
status: "on"
});
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async setAutoCommit(e) {
const t = await this.connect();
const n = (0, IA.promisify)(t.exec.bind(t));
t.setAutoCommit(e.status === "on");
const a = `SET TRANSACTION AUTOCOMMIT DDL ${e.status.toUpperCase()};`;
try {
await n(a);
} catch (e) {
throw new PA.QueryFailedError(a, [], e);
}
}
async query(e, t, n = false) {
if (this.isReleased) throw new LA.QueryRunnerAlreadyReleasedError;
const a = await this.lock.acquire();
const r = await this.connect();
let i;
const s = new qA.QueryResult;
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const o = new WA.BroadcasterResult;
try {
const n = Date.now();
const a = e.substr(0, 11) === "INSERT INTO";
if (t?.some(Array.isArray)) {
i = await (0, IA.promisify)(r.prepare).call(r, e);
}
let c;
try {
c = i ? await (0, IA.promisify)(i.exec).call(i, t) : await (0, IA.promisify)(r.exec).call(r, e, t, {});
} catch (n) {
throw new PA.QueryFailedError(e, t, n);
}
const l = this.driver.connection.options.maxQueryExecutionTime;
const u = Date.now();
const h = u - n;
this.broadcaster.broadcastAfterQueryEvent(o, e, t, true, h, c, undefined);
if (l && h > l) {
this.driver.connection.logger.logQuerySlow(h, e, t, this);
}
if (typeof c === "number") {
s.affected = c;
} else if (Array.isArray(c)) {
s.records = c;
}
s.raw = c;
if (a) {
const e = `SELECT CURRENT_IDENTITY_VALUE() FROM "SYS"."DUMMY"`;
this.driver.connection.logger.logQuery(e, [], this);
const t = await new Promise((t, n) => {
r.exec(e, (a, r) => a ? n(new PA.QueryFailedError(e, [], a)) : t(r));
});
s.raw = t[0]["CURRENT_IDENTITY_VALUE()"];
s.records = t;
}
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(o, e, t, false, undefined, undefined, n);
throw n;
} finally {
if (i?.drop) {
await new Promise(e => i.drop(() => e()));
}
await o.wait();
a();
}
if (n) {
return s;
} else {
return s.raw;
}
}
async stream(e, t, n, a) {
if (this.isReleased) throw new LA.QueryRunnerAlreadyReleasedError;
const r = await this.lock.acquire();
let i;
let s;
const o = async () => {
if (s) {
await (0, IA.promisify)(s.close).call(s);
}
if (i) {
await (0, IA.promisify)(i.drop).call(i);
}
r();
};
try {
const r = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
i = await (0, IA.promisify)(r.prepare).call(r, e);
s = await (0, IA.promisify)(i.executeQuery).call(i, t);
const c = this.driver.streamClient.createObjectStream(s);
c.on("end", async () => {
await o();
n?.();
});
c.on("error", async n => {
this.driver.connection.logger.logQueryError(n, e, t, this);
await o();
a?.(n);
});
return c;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
await o();
throw new PA.QueryFailedError(e, t, n);
}
}
async getDatabases() {
const e = await this.query(`SELECT DATABASE_NAME FROM "SYS"."M_DATABASES"`);
return e.map(e => e["DATABASE_NAME"]);
}
async getSchemas(e) {
const t = e ? `SELECT * FROM "${e}"."SYS"."SCHEMAS"` : `SELECT * FROM "SYS"."SCHEMAS"`;
const n = await this.query(t);
return n.map(e => e["SCHEMA_NAME"]);
}
async hasDatabase(e) {
const t = await this.getDatabases();
return t.indexOf(e) !== -1;
}
async getCurrentDatabase() {
const e = await this.query(`SELECT "DATABASE_NAME" AS "dbName" FROM "SYS"."M_DATABASE"`);
return e[0].dbName;
}
async getDatabaseAndVersion() {
const e = await this.query(`SELECT "DATABASE_NAME" AS "database", "VERSION" AS "version" FROM "SYS"."M_DATABASE"`);
return e[0];
}
async hasSchema(e) {
const t = await this.getSchemas();
return t.indexOf(e) !== -1;
}
async getCurrentSchema() {
const e = await this.query(`SELECT CURRENT_SCHEMA AS "schemaName" FROM "SYS"."DUMMY"`);
return e[0].schemaName;
}
async hasTable(e) {
const t = this.driver.parseTableName(e);
if (!t.schema) {
t.schema = await this.getCurrentSchema();
}
const n = `SELECT COUNT(*) as "hasTable" FROM "SYS"."TABLES" WHERE "SCHEMA_NAME" = '${t.schema}' AND "TABLE_NAME" = '${t.tableName}'`;
const a = await this.query(n);
return a[0].hasTable > 0;
}
async hasColumn(e, t) {
const n = this.driver.parseTableName(e);
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = `SELECT COUNT(*) as "hasColumn" FROM "SYS"."TABLE_COLUMNS" WHERE "SCHEMA_NAME" = '${n.schema}' AND "TABLE_NAME" = '${n.tableName}' AND "COLUMN_NAME" = '${t}'`;
const r = await this.query(a);
return r[0].hasColumn > 0;
}
async createDatabase(e, t) {
return Promise.resolve();
}
async dropDatabase(e, t) {
return Promise.resolve();
}
async createSchema(e, t) {
const n = e.indexOf(".") === -1 ? e : e.split(".")[1];
let a = false;
if (t) {
const e = await this.query(`SELECT * FROM "SYS"."SCHEMAS" WHERE "SCHEMA_NAME" = '${n}'`);
a = !!e.length;
}
if (!t || t && !a) {
const e = `CREATE SCHEMA "${n}"`;
const t = `DROP SCHEMA "${n}" CASCADE`;
await this.executeQueries(new YA.Query(e), new YA.Query(t));
}
}
async dropSchema(e, t, n) {
const a = e.indexOf(".") === -1 ? e : e.split(".")[0];
let r = false;
if (t) {
const e = await this.query(`SELECT * FROM "SYS"."SCHEMAS" WHERE "SCHEMA_NAME" = '${a}'`);
r = !!e.length;
}
if (!t || t && r) {
const e = `DROP SCHEMA "${a}" ${n ? "CASCADE" : ""}`;
const t = `CREATE SCHEMA "${a}"`;
await this.executeQueries(new YA.Query(e), new YA.Query(t));
}
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(e, t));
});
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const s = [];
const o = [];
if (a) {
i.indices.forEach(e => {
s.push(this.dropIndexSql(i, e));
o.push(this.createIndexSql(i, e));
});
}
if (n) i.foreignKeys.forEach(e => s.push(this.dropForeignKeySql(i, e)));
s.push(this.dropTableSql(i));
o.push(this.createTableSql(i, r));
await this.executeQueries(s, o);
}
async createView(e, t = false) {
const n = [];
const a = [];
n.push(this.createViewSql(e));
if (t) n.push(await this.insertViewDefinitionSql(e));
a.push(this.dropViewSql(e));
if (t) a.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(n, a);
}
async dropView(e) {
const t = HA.InstanceChecker.isView(e) ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
const n = [];
const a = [];
const r = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const i = r.clone();
const {schema: s, tableName: o} = this.driver.parseTableName(r);
i.name = s ? `${s}.${t}` : t;
n.push(new YA.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(i)}`));
a.push(new YA.Query(`RENAME TABLE ${this.escapePath(i)} TO ${this.escapePath(r)}`));
i.foreignKeys.forEach(e => {
n.push(this.dropForeignKeySql(i, e));
a.push(this.createForeignKeySql(i, e));
});
const c = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${s}' AND "REFERENCED_TABLE_NAME" = '${o}'`;
const l = await this.query(c);
let u = [];
const h = [];
if (l.length > 0) {
u = l.map(e => {
const t = l.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
h.push({
tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
fkName: e["CONSTRAINT_NAME"]
});
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: i.database,
referencedSchema: i.schema,
referencedTableName: i.name,
referencedColumnNames: t.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
u.forEach(e => {
const t = h.find(t => t.fkName === e.name);
n.push(this.dropForeignKeySql(t.tableName, e));
a.push(this.createForeignKeySql(t.tableName, e));
});
}
if (i.primaryColumns.length > 0) {
const e = i.primaryColumns.map(e => e.name);
const t = e.map(e => `"${e}"`).join(", ");
const s = this.connection.namingStrategy.primaryKeyName(r, e);
const o = this.connection.namingStrategy.primaryKeyName(i, e);
n.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} DROP CONSTRAINT "${s}"`));
a.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} ADD CONSTRAINT "${s}" PRIMARY KEY (${t})`));
n.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} ADD CONSTRAINT "${o}" PRIMARY KEY (${t})`));
a.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} DROP CONSTRAINT "${o}"`));
}
i.foreignKeys.forEach(e => {
e.name = this.connection.namingStrategy.foreignKeyName(i, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
n.push(this.createForeignKeySql(i, e));
a.push(this.dropForeignKeySql(i, e));
});
u.forEach(e => {
const t = h.find(t => t.fkName === e.name);
n.push(this.createForeignKeySql(t.tableName, e));
a.push(this.dropForeignKeySql(t.tableName, e));
});
i.indices.forEach(e => {
const t = this.connection.namingStrategy.indexName(i, e.columnNames, e.where);
n.push(this.dropIndexSql(i, e));
a.push(this.createIndexSql(i, e));
e.name = t;
n.push(this.createIndexSql(i, e));
a.push(this.dropIndexSql(i, e));
});
await this.executeQueries(n, a);
r.name = i.name;
this.replaceCachedTable(r, i);
}
async addColumn(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.driver.parseTableName(n);
if (!a.schema) {
a.schema = await this.getCurrentSchema();
}
const r = n.clone();
const i = [];
const s = [];
i.push(new YA.Query(this.addColumnSql(n, t)));
s.push(new YA.Query(this.dropColumnSql(n, t)));
if (t.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${a.schema}' AND "REFERENCED_TABLE_NAME" = '${a.tableName}'`;
const o = await this.query(t);
let c = [];
const l = [];
if (o.length > 0) {
c = o.map(e => {
const t = o.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
l.push({
tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
fkName: e["CONSTRAINT_NAME"]
});
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: n.database,
referencedSchema: n.schema,
referencedTableName: n.name,
referencedColumnNames: t.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
c.forEach(e => {
const t = l.find(t => t.fkName === e.name);
i.push(this.dropForeignKeySql(t.tableName, e));
s.push(this.createForeignKeySql(t.tableName, e));
});
}
const u = this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const h = e.map(e => `"${e.name}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${u}"`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${u}" PRIMARY KEY (${h})`));
c.forEach(e => {
const t = l.find(t => t.fkName === e.name);
i.push(this.createForeignKeySql(t.tableName, e));
s.push(this.dropForeignKeySql(t.tableName, e));
});
}
e.push(t);
const o = this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${o}"`));
}
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (o) {
i.push(this.createIndexSql(n, o));
s.push(this.dropIndexSql(n, o));
} else if (t.isUnique) {
const e = new kA.TableIndex({
name: this.connection.namingStrategy.indexName(n, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
});
r.indices.push(e);
r.uniques.push(new QA.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
i.push(this.createIndexSql(n, e));
s.push(this.dropIndexSql(n, e));
}
await this.executeQueries(i, s);
r.addColumn(t);
this.replaceCachedTable(n, r);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const r = HA.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!r) throw new PA.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i = undefined;
if (HA.InstanceChecker.isTableColumn(n)) {
i = n;
} else {
i = r.clone();
i.name = n;
}
await this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = HA.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
if (!o) throw new PA.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (n.isGenerated !== o.isGenerated && n.generationStrategy !== "uuid" || n.type !== o.type || n.length !== o.length) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.name !== o.name) {
i.push(new YA.Query(`RENAME COLUMN ${this.escapePath(a)}."${o.name}" TO "${n.name}"`));
s.push(new YA.Query(`RENAME COLUMN ${this.escapePath(a)}."${n.name}" TO "${o.name}"`));
if (o.isPrimary === true) {
const e = r.primaryColumns;
const t = e.map(e => e.name);
const a = this.connection.namingStrategy.primaryKeyName(r, t);
t.splice(t.indexOf(o.name), 1);
t.push(n.name);
const c = t.map(e => `"${e}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${a}"`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${a}" PRIMARY KEY (${c})`));
const l = this.connection.namingStrategy.primaryKeyName(r, t);
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${l}" PRIMARY KEY (${c})`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${l}"`));
}
r.findColumnIndices(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
i.push(this.dropIndexSql(r, e));
s.push(this.createIndexSql(r, e));
e.name = t;
i.push(this.createIndexSql(r, e));
s.push(this.dropIndexSql(r, e));
});
r.findColumnForeignKeys(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
i.push(this.dropForeignKeySql(r, e));
s.push(this.createForeignKeySql(r, e));
e.name = t;
i.push(this.createForeignKeySql(r, e));
s.push(this.dropForeignKeySql(r, e));
});
r.findColumnChecks(o).forEach(e => {
e.columnNames.splice(e.columnNames.indexOf(o.name), 1);
e.columnNames.push(n.name);
const t = this.connection.namingStrategy.checkConstraintName(r, e.expression);
i.push(this.dropCheckConstraintSql(r, e));
s.push(this.createCheckConstraintSql(r, e));
e.name = t;
i.push(this.createCheckConstraintSql(r, e));
s.push(this.dropCheckConstraintSql(r, e));
});
const e = r.columns.find(e => e.name === o.name);
r.columns[r.columns.indexOf(e)].name = n.name;
o.name = n.name;
}
if (this.isColumnChanged(o, n, true)) {
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER (${this.buildCreateColumnSql(n, !(o.default === null || o.default === undefined), !o.isNullable)})`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER (${this.buildCreateColumnSql(o, !(n.default === null || n.default === undefined), !n.isNullable)})`));
} else if (o.comment !== n.comment) {
i.push(new YA.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${o.name}" IS ${this.escapeComment(n.comment)}`));
s.push(new YA.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${n.name}" IS ${this.escapeComment(o.comment)}`));
}
if (n.isPrimary !== o.isPrimary) {
const e = r.primaryColumns;
if (e.length > 0) {
const t = this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
}
if (n.isPrimary === true) {
e.push(n);
const t = r.columns.find(e => e.name === n.name);
t.isPrimary = true;
const o = this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const c = e.map(e => `"${e.name}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${o}"`));
} else {
const t = e.find(e => e.name === n.name);
e.splice(e.indexOf(t), 1);
const o = r.columns.find(e => e.name === n.name);
o.isPrimary = false;
if (e.length > 0) {
const t = this.connection.namingStrategy.primaryKeyName(r, e.map(e => e.name));
const n = e.map(e => `"${e.name}"`).join(", ");
i.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
}
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new kA.TableIndex({
name: this.connection.namingStrategy.indexName(a, [ n.name ]),
columnNames: [ n.name ],
isUnique: true
});
r.indices.push(e);
r.uniques.push(new QA.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
i.push(this.createIndexSql(a, e));
s.push(this.dropIndexSql(a, e));
} else {
const e = r.indices.find(e => e.columnNames.length === 1 && e.isUnique === true && !!e.columnNames.find(e => e === n.name));
r.indices.splice(r.indices.indexOf(e), 1);
const t = r.uniques.find(t => t.name === e.name);
r.uniques.splice(r.uniques.indexOf(t), 1);
i.push(this.dropIndexSql(a, e));
s.push(this.createIndexSql(a, e));
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.driver.parseTableName(n);
if (!a.schema) {
a.schema = await this.getCurrentSchema();
}
const r = HA.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
if (!r) throw new PA.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const i = n.clone();
const s = [];
const o = [];
if (r.isPrimary) {
const e = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${a.schema}' AND "REFERENCED_TABLE_NAME" = '${a.tableName}'`;
const t = await this.query(e);
let c = [];
const l = [];
if (t.length > 0) {
c = t.map(e => {
const a = t.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
l.push({
tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
fkName: e["CONSTRAINT_NAME"]
});
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: a.map(e => e["COLUMN_NAME"]),
referencedDatabase: n.database,
referencedSchema: n.schema,
referencedTableName: n.name,
referencedColumnNames: a.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
c.forEach(e => {
const t = l.find(t => t.fkName === e.name);
s.push(this.dropForeignKeySql(t.tableName, e));
o.push(this.createForeignKeySql(t.tableName, e));
});
}
const u = this.connection.namingStrategy.primaryKeyName(i, i.primaryColumns.map(e => e.name));
const h = i.primaryColumns.map(e => `"${e.name}"`).join(", ");
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} DROP CONSTRAINT "${u}"`));
o.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} ADD CONSTRAINT "${u}" PRIMARY KEY (${h})`));
const d = i.findColumnByName(r.name);
d.isPrimary = false;
if (i.primaryColumns.length > 0) {
const e = this.connection.namingStrategy.primaryKeyName(i, i.primaryColumns.map(e => e.name));
const t = i.primaryColumns.map(e => `"${e.name}"`).join(", ");
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
o.push(new YA.Query(`ALTER TABLE ${this.escapePath(i)} DROP CONSTRAINT "${e}"`));
}
c.forEach(e => {
const t = l.find(t => t.fkName === e.name);
s.push(this.createForeignKeySql(t.tableName, e));
o.push(this.dropForeignKeySql(t.tableName, e));
});
}
const c = i.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === r.name);
if (c) {
i.indices.splice(i.indices.indexOf(c), 1);
s.push(this.dropIndexSql(n, c));
o.push(this.createIndexSql(n, c));
} else if (r.isUnique) {
const e = this.connection.namingStrategy.uniqueConstraintName(n, [ r.name ]);
const t = i.uniques.find(t => t.name === e);
if (t) {
i.uniques.splice(i.uniques.indexOf(t), 1);
s.push(this.dropIndexSql(n, e));
o.push(new YA.Query(`CREATE UNIQUE INDEX "${e}" ON ${this.escapePath(n)} ("${r.name}")`));
}
const a = this.connection.namingStrategy.indexName(n, [ r.name ]);
const c = i.indices.find(e => e.name === a);
if (c) {
i.indices.splice(i.indices.indexOf(c), 1);
s.push(this.dropIndexSql(n, a));
o.push(new YA.Query(`CREATE UNIQUE INDEX "${a}" ON ${this.escapePath(n)} ("${r.name}")`));
}
}
const l = i.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === r.name);
if (l) {
i.checks.splice(i.checks.indexOf(l), 1);
s.push(this.dropCheckConstraintSql(n, l));
o.push(this.createCheckConstraintSql(n, l));
}
s.push(new YA.Query(this.dropColumnSql(n, r)));
o.push(new YA.Query(this.addColumnSql(n, r)));
await this.executeQueries(s, o);
i.removeColumn(r);
this.replaceCachedTable(n, i);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = n.clone();
const r = this.createPrimaryKeySql(n, t);
a.columns.forEach(e => {
if (t.find(t => t === e.name)) e.isPrimary = true;
});
const i = this.dropPrimaryKeySql(a);
await this.executeQueries(r, i);
this.replaceCachedTable(n, a);
}
async updatePrimaryKeys(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = this.driver.parseTableName(n);
if (!a.schema) {
a.schema = await this.getCurrentSchema();
}
const r = n.clone();
const i = t.map(e => e.name);
const s = [];
const o = [];
const c = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${a.schema}' AND "REFERENCED_TABLE_NAME" = '${a.tableName}'`;
const l = await this.query(c);
let u = [];
const h = [];
if (l.length > 0) {
u = l.map(e => {
const t = l.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
h.push({
tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
fkName: e["CONSTRAINT_NAME"]
});
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: n.database,
referencedSchema: n.schema,
referencedTableName: n.name,
referencedColumnNames: t.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
u.forEach(e => {
const t = h.find(t => t.fkName === e.name);
s.push(this.dropForeignKeySql(t.tableName, e));
o.push(this.createForeignKeySql(t.tableName, e));
});
}
const d = r.primaryColumns;
if (d.length > 0) {
const e = this.connection.namingStrategy.primaryKeyName(r, d.map(e => e.name));
const t = d.map(e => `"${e.name}"`).join(", ");
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
o.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
}
r.columns.filter(e => i.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
const p = this.connection.namingStrategy.primaryKeyName(r, i);
const m = i.map(e => `"${e}"`).join(", ");
s.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${p}" PRIMARY KEY (${m})`));
o.push(new YA.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${p}"`));
u.forEach(e => {
const t = h.find(t => t.fkName === e.name);
s.push(this.createForeignKeySql(t.tableName, e));
o.push(this.dropForeignKeySql(t.tableName, e));
});
await this.executeQueries(s, o);
this.replaceCachedTable(n, r);
}
async dropPrimaryKey(e) {
const t = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const n = this.driver.parseTableName(t);
if (!n.schema) {
n.schema = await this.getCurrentSchema();
}
const a = [];
const r = [];
const i = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${n.schema}' AND "REFERENCED_TABLE_NAME" = '${n.tableName}'`;
const s = await this.query(i);
let o = [];
const c = [];
if (s.length > 0) {
o = s.map(e => {
const n = s.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
c.push({
tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
fkName: e["CONSTRAINT_NAME"]
});
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: n.map(e => e["COLUMN_NAME"]),
referencedDatabase: t.database,
referencedSchema: t.schema,
referencedTableName: t.name,
referencedColumnNames: n.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
o.forEach(e => {
const t = c.find(t => t.fkName === e.name);
a.push(this.dropForeignKeySql(t.tableName, e));
r.push(this.createForeignKeySql(t.tableName, e));
});
}
a.push(this.dropPrimaryKeySql(t));
r.push(this.createPrimaryKeySql(t, t.primaryColumns.map(e => e.name)));
o.forEach(e => {
const t = c.find(t => t.fkName === e.name);
a.push(this.createForeignKeySql(t.tableName, e));
r.push(this.dropForeignKeySql(t.tableName, e));
});
await this.executeQueries(a, r);
t.primaryColumns.forEach(e => {
e.isPrimary = false;
});
}
async createUniqueConstraint(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
}
async createUniqueConstraints(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraint(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraints(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
}
async createCheckConstraint(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = HA.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
if (!a) throw new PA.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new PA.TypeORMError(`SAP HANA does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
const n = t.map(t => this.createForeignKey(e, t));
await Promise.all(n);
}
async dropForeignKey(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = HA.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new PA.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
const n = t.map(t => this.dropForeignKey(e, t));
await Promise.all(n);
}
async createIndex(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
const n = t.map(t => this.createIndex(e, t));
await Promise.all(n);
}
async dropIndex(e, t) {
const n = HA.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
const a = HA.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
if (!a) throw new PA.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
const n = t.map(t => this.dropIndex(e, t));
await Promise.all(n);
}
async clearTable(e) {
await this.query(`TRUNCATE TABLE ${this.escapePath(e)}`);
}
async clearDatabase() {
const e = [];
this.connection.entityMetadatas.filter(e => e.schema).forEach(t => {
const n = !!e.find(e => e === t.schema);
if (!n) e.push(t.schema);
});
e.push(this.driver.options.schema || "current_schema");
const t = e.map(e => e === "current_schema" ? e : "'" + e + "'").join(", ");
const n = this.isTransactionActive;
if (!n) await this.startTransaction();
try {
const e = `SELECT 'DROP TABLE "' || schema_name || '"."' || table_name || '" CASCADE;' as "query" FROM "SYS"."TABLES" WHERE "SCHEMA_NAME" IN (${t}) AND "TABLE_NAME" NOT IN ('SYS_AFL_GENERATOR_PARAMETERS') AND "IS_COLUMN_TABLE" = 'TRUE'`;
const a = await this.query(e);
await Promise.all(a.map(e => this.query(e["query"])));
if (!n) await this.commitTransaction();
} catch (e) {
try {
if (!n) await this.rollbackTransaction();
} catch (e) {}
throw e;
}
}
async loadViews(e) {
const t = await this.hasTable(this.getTypeormMetadataTableName());
if (!t) {
return [];
}
if (!e) {
e = [];
}
const n = await this.getCurrentDatabase();
const a = await this.getCurrentSchema();
const r = e.map(e => {
let {schema: t, tableName: n} = this.driver.parseTableName(e);
if (!t) {
t = a;
}
return `("t"."schema" = '${t}' AND "t"."name" = '${n}')`;
}).join(" OR ");
const i = `SELECT "t".* FROM ${this.escapePath(this.getTypeormMetadataTableName())} "t" WHERE "t"."type" = '${zA.MetadataTableType.VIEW}' ${r ? `AND (${r})` : ""}`;
const s = await this.query(i);
return s.map(e => {
const t = new VA.View;
const r = e["schema"] === a && !this.driver.options.schema ? undefined : e["schema"];
t.database = n;
t.schema = e["schema"];
t.name = this.driver.buildTableName(e["name"], r);
t.expression = e["value"];
return t;
});
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = await this.getCurrentSchema();
const n = await this.getCurrentDatabase();
const a = [];
if (!e) {
const e = `SELECT "SCHEMA_NAME", "TABLE_NAME" FROM "SYS"."TABLES"`;
a.push(...await this.query(e));
} else {
const n = e.map(e => {
let [n, a] = e.split(".");
if (!a) {
a = n;
n = this.driver.options.schema || t;
}
return `("SCHEMA_NAME" = '${n}' AND "TABLE_NAME" = '${a}')`;
}).join(" OR ");
const r = `SELECT "SCHEMA_NAME", "TABLE_NAME" FROM "SYS"."TABLES" WHERE ` + n;
a.push(...await this.query(r));
}
if (a.length === 0) return [];
const r = a.map(({SCHEMA_NAME: e, TABLE_NAME: t}) => `("SCHEMA_NAME" = '${e}' AND "TABLE_NAME" = '${t}')`).join(" OR ");
const i = `SELECT * FROM "SYS"."TABLE_COLUMNS" WHERE ` + r + ` ORDER BY "POSITION"`;
const s = a.map(({SCHEMA_NAME: e, TABLE_NAME: t}) => `("SCHEMA_NAME" = '${e}' AND "TABLE_NAME" = '${t}')`).join(" OR ");
const o = `SELECT * FROM "SYS"."CONSTRAINTS" WHERE (${s}) ORDER BY "POSITION"`;
const c = a.map(({SCHEMA_NAME: e, TABLE_NAME: t}) => `("I"."SCHEMA_NAME" = '${e}' AND "I"."TABLE_NAME" = '${t}')`).join(" OR ");
const l = `SELECT "I"."INDEX_TYPE", "I"."SCHEMA_NAME", "I"."TABLE_NAME", "I"."INDEX_NAME", "IC"."COLUMN_NAME", "I"."CONSTRAINT" ` + `FROM "SYS"."INDEXES" "I" INNER JOIN "SYS"."INDEX_COLUMNS" "IC" ON "IC"."INDEX_OID" = "I"."INDEX_OID" ` + `WHERE (${c}) AND ("I"."CONSTRAINT" IS NULL OR "I"."CONSTRAINT" != 'PRIMARY KEY') AND "I"."INDEX_NAME" NOT LIKE '%_SYS_FULLTEXT_%' ORDER BY "IC"."POSITION"`;
const u = a.map(({SCHEMA_NAME: e, TABLE_NAME: t}) => `("SCHEMA_NAME" = '${e}' AND "TABLE_NAME" = '${t}')`).join(" OR ");
const h = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE (${u}) ORDER BY "POSITION"`;
const [d, p, m, f] = await Promise.all([ this.query(i), this.query(o), this.query(l), this.query(h) ]);
return Promise.all(a.map(async e => {
const a = new UA.Table;
const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
const i = r(e, "SCHEMA_NAME");
a.database = n;
a.schema = e["SCHEMA_NAME"];
a.name = this.driver.buildTableName(e["TABLE_NAME"], i);
a.columns = await Promise.all(d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["SCHEMA_NAME"] === e["SCHEMA_NAME"]).map(async t => {
const n = p.filter(e => e["TABLE_NAME"] === t["TABLE_NAME"] && e["SCHEMA_NAME"] === t["SCHEMA_NAME"] && e["COLUMN_NAME"] === t["COLUMN_NAME"]);
const r = m.filter(n => n["TABLE_NAME"] === e["TABLE_NAME"] && n["SCHEMA_NAME"] === e["SCHEMA_NAME"] && n["COLUMN_NAME"] === t["COLUMN_NAME"] && n["CONSTRAINT"] && n["CONSTRAINT"].indexOf("UNIQUE") !== -1);
const i = this.connection.entityMetadatas.find(e => this.getTablePath(a) === this.getTablePath(e));
const s = r.length > 0 && i && i.indices.some(e => r.some(t => e.name === t["INDEX_NAME"] && e.synchronize === false));
const o = r.every(e => m.some(n => n["INDEX_NAME"] === e["INDEX_NAME"] && n["COLUMN_NAME"] !== t["COLUMN_NAME"]));
const c = new FA.TableColumn;
c.name = t["COLUMN_NAME"];
c.type = t["DATA_TYPE_NAME"].toLowerCase();
if (c.type === "dec" || c.type === "decimal") {
if (t["LENGTH"] !== null && !this.isDefaultColumnPrecision(a, c, t["LENGTH"])) {
c.precision = t["LENGTH"];
} else if (t["SCALE"] !== null && !this.isDefaultColumnScale(a, c, t["SCALE"])) {
c.precision = undefined;
}
if (t["SCALE"] !== null && !this.isDefaultColumnScale(a, c, t["SCALE"])) {
c.scale = t["SCALE"];
} else if (t["LENGTH"] !== null && !this.isDefaultColumnPrecision(a, c, t["LENGTH"])) {
c.scale = undefined;
}
}
if (t["DATA_TYPE_NAME"].toLowerCase() === "array") {
c.isArray = true;
c.type = t["CS_DATA_TYPE_NAME"].toLowerCase();
}
if (this.driver.withLengthColumnTypes.indexOf(c.type) !== -1 && t["LENGTH"]) {
const e = t["LENGTH"].toString();
c.length = !this.isDefaultColumnLength(a, c, e) ? e : "";
}
c.isUnique = r.length > 0 && !s && !o;
c.isNullable = t["IS_NULLABLE"] === "TRUE";
c.isPrimary = !!n.find(e => e["IS_PRIMARY_KEY"] === "TRUE");
c.isGenerated = t["GENERATION_TYPE"] === "ALWAYS AS IDENTITY";
if (c.isGenerated) c.generationStrategy = "increment";
if (t["DEFAULT_VALUE"] === null || t["DEFAULT_VALUE"] === undefined) {
c.default = undefined;
} else {
if (c.type === "char" || c.type === "nchar" || c.type === "varchar" || c.type === "nvarchar" || c.type === "alphanum" || c.type === "shorttext") {
c.default = `'${t["DEFAULT_VALUE"]}'`;
} else if (c.type === "boolean") {
c.default = t["DEFAULT_VALUE"] === "1" ? "true" : "false";
} else {
c.default = t["DEFAULT_VALUE"];
}
}
if (t["COMMENTS"]) {
c.comment = t["COMMENTS"];
}
return c;
}));
const s = GA.OrmUtils.uniq(p.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["SCHEMA_NAME"] === e["SCHEMA_NAME"] && t["CHECK_CONDITION"] !== null && t["CHECK_CONDITION"] !== undefined), e => e["CONSTRAINT_NAME"]);
a.checks = s.map(e => {
const t = p.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new BA.TableCheck({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
expression: e["CHECK_CONDITION"]
});
});
const o = GA.OrmUtils.uniq(f.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["SCHEMA_NAME"] === e["SCHEMA_NAME"]), e => e["CONSTRAINT_NAME"]);
a.foreignKeys = o.map(e => {
const t = f.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
const n = r(e, "REFERENCED_SCHEMA_NAME");
const i = this.driver.buildTableName(e["REFERENCED_TABLE_NAME"], n);
return new jA.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
referencedDatabase: a.database,
referencedSchema: e["REFERENCED_SCHEMA_NAME"],
referencedTableName: i,
referencedColumnNames: t.map(e => e["REFERENCED_COLUMN_NAME"]),
onDelete: e["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : e["UPDATE_RULE"],
deferrable: e["CHECK_TIME"].replace("_", " ")
});
});
const c = GA.OrmUtils.uniq(m.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["SCHEMA_NAME"] === e["SCHEMA_NAME"]), e => e["INDEX_NAME"]);
a.indices = c.map(e => {
const t = m.filter(t => t["SCHEMA_NAME"] === e["SCHEMA_NAME"] && t["TABLE_NAME"] === e["TABLE_NAME"] && t["INDEX_NAME"] === e["INDEX_NAME"]);
return new kA.TableIndex({
table: a,
name: e["INDEX_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
isUnique: e["CONSTRAINT"] && e["CONSTRAINT"].indexOf("UNIQUE") !== -1,
isFulltext: e["INDEX_TYPE"] === "FULLTEXT"
});
});
return a;
}));
}
createTableSql(e, t) {
const n = e.columns.map(e => this.buildCreateColumnSql(e)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.indices.some(e => e.columnNames.length === 1 && !!e.isUnique && e.columnNames.indexOf(t.name) !== -1);
const a = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames.indexOf(t.name) !== -1);
if (!n && !a) e.indices.push(new kA.TableIndex({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
}));
});
if (e.uniques.length > 0) {
e.uniques.forEach(t => {
const n = e.indices.some(e => e.name === t.name);
if (!n) {
e.indices.push(new kA.TableIndex({
name: t.name,
columnNames: t.columnNames,
isUnique: true
}));
}
});
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT "${n}" CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `"${e}"`).join(", ");
let r = `CONSTRAINT "${t.name}" FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
if (t.onDelete) {
const e = t.onDelete === "NO ACTION" ? "RESTRICT" : t.onDelete;
r += ` ON DELETE ${e}`;
}
if (t.onUpdate) {
const e = t.onUpdate === "NO ACTION" ? "RESTRICT" : t.onUpdate;
r += ` ON UPDATE ${e}`;
}
if (t.deferrable) {
r += ` ${t.deferrable}`;
}
return r;
}).join(", ");
a += `, ${t}`;
}
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const t = this.connection.namingStrategy.primaryKeyName(e, r.map(e => e.name));
const n = r.map(e => `"${e.name}"`).join(", ");
a += `, CONSTRAINT "${t}" PRIMARY KEY (${n})`;
}
a += `)`;
return new YA.Query(a);
}
dropTableSql(e, t) {
const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
return new YA.Query(n);
}
createViewSql(e) {
if (typeof e.expression === "string") {
return new YA.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
} else {
return new YA.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression(this.connection).getQuery()}`);
}
}
async insertViewDefinitionSql(e) {
let {schema: t, tableName: n} = this.driver.parseTableName(e);
if (!t) {
t = await this.getCurrentSchema();
}
const a = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: zA.MetadataTableType.VIEW,
schema: t,
name: n,
value: a
});
}
dropViewSql(e) {
return new YA.Query(`DROP VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
let {schema: t, tableName: n} = this.driver.parseTableName(e);
if (!t) {
t = await this.getCurrentSchema();
}
return this.deleteTypeormMetadataSql({
type: zA.MetadataTableType.VIEW,
schema: t,
name: n
});
}
addColumnSql(e, t) {
return `ALTER TABLE ${this.escapePath(e)} ADD (${this.buildCreateColumnSql(t)})`;
}
dropColumnSql(e, t) {
return `ALTER TABLE ${this.escapePath(e)} DROP ("${t.name}")`;
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => `"${e}"`).join(", ");
let a = "";
if (t.isUnique) {
a += "UNIQUE ";
}
if (t.isFulltext && this.driver.isFullTextColumnTypeSupported()) {
a += "FULLTEXT ";
}
return new YA.Query(`CREATE ${a}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
}
dropIndexSql(e, t) {
const n = HA.InstanceChecker.isTableIndex(t) ? t.name : t;
const a = this.driver.parseTableName(e);
if (!a.schema) {
return new YA.Query(`DROP INDEX "${n}"`);
} else {
return new YA.Query(`DROP INDEX "${a.schema}"."${n}"`);
}
}
createPrimaryKeySql(e, t) {
const n = this.connection.namingStrategy.primaryKeyName(e, t);
const a = t.map(e => `"${e}"`).join(", ");
return new YA.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${n}" PRIMARY KEY (${a})`);
}
dropPrimaryKeySql(e) {
const t = e.primaryColumns.map(e => e.name);
const n = this.connection.namingStrategy.primaryKeyName(e, t);
return new YA.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createCheckConstraintSql(e, t) {
return new YA.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = HA.InstanceChecker.isTableCheck(t) ? t.name : t;
return new YA.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
const a = t.referencedColumnNames.map(e => `"` + e + `"`).join(",");
let r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))}(${a})`;
if (t.onDelete) {
const e = t.onDelete === "NO ACTION" ? "RESTRICT" : t.onDelete;
r += ` ON DELETE ${e}`;
}
if (t.onUpdate) {
const e = t.onUpdate === "NO ACTION" ? "RESTRICT" : t.onUpdate;
r += ` ON UPDATE ${e}`;
}
if (t.deferrable) {
r += ` ${t.deferrable}`;
}
return new YA.Query(r);
}
dropForeignKeySql(e, t) {
const n = HA.InstanceChecker.isTableForeignKey(t) ? t.name : t;
return new YA.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
}
escapeComment(e) {
if (!e) {
return "NULL";
}
e = e.replace(/'/g, "''").replace(/\u0000/g, "");
return `'${e}'`;
}
escapePath(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
if (t) {
return `"${t}"."${n}"`;
}
return `"${n}"`;
}
buildCreateColumnSql(e, t, n) {
let a = `"${e.name}" ` + this.connection.driver.createFullType(e);
if (e.default !== undefined && e.default !== null) {
a += " DEFAULT " + e.default;
} else if (t) {
a += " DEFAULT NULL";
}
if (!e.isGenerated) {
if (e.isNullable !== true) a += " NOT NULL"; else if (n) a += " NULL";
}
if (e.isGenerated === true && e.generationStrategy === "increment") {
a += " GENERATED ALWAYS AS IDENTITY";
}
if (e.comment) {
a += ` COMMENT ${this.escapeComment(e.comment)}`;
}
return a;
}
changeTableComment(e, t) {
throw new PA.TypeORMError(`spa driver does not support change table comment.`);
}
}
vA.SapQueryRunner = SapQueryRunner;
Object.defineProperty(OA, "__esModule", {
value: true
});
OA.SapDriver = void 0;
const JA = Tt();
const XA = D;
const ZA = Uh;
const eb = Um;
const tb = _s;
const nb = up;
const ab = qc;
const rb = vA;
const ib = jn;
const sb = Te;
class SapDriver {
constructor(e) {
this.slaves = [];
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "simple";
this.supportedDataTypes = [ "tinyint", "smallint", "int", "integer", "bigint", "smalldecimal", "decimal", "dec", "real", "double", "float", "date", "time", "seconddate", "timestamp", "boolean", "char", "nchar", "varchar", "nvarchar", "text", "alphanum", "shorttext", "array", "varbinary", "blob", "clob", "nclob", "st_geometry", "st_point" ];
this.supportedUpsertTypes = [];
this.spatialTypes = [ "st_geometry", "st_point" ];
this.withLengthColumnTypes = [ "varchar", "nvarchar", "alphanum", "shorttext", "varbinary" ];
this.withPrecisionColumnTypes = [ "decimal" ];
this.withScaleColumnTypes = [ "decimal" ];
this.mappedDataTypes = {
createDate: "timestamp",
createDateDefault: "CURRENT_TIMESTAMP",
updateDate: "timestamp",
updateDateDefault: "CURRENT_TIMESTAMP",
deleteDate: "timestamp",
deleteDateNullable: true,
version: "integer",
treeLevel: "integer",
migrationId: "integer",
migrationName: "nvarchar",
migrationTimestamp: "bigint",
cacheId: "integer",
cacheIdentifier: "nvarchar",
cacheTime: "bigint",
cacheDuration: "integer",
cacheQuery: "nvarchar(5000)",
cacheResult: "nclob",
metadataType: "nvarchar",
metadataDatabase: "nvarchar",
metadataSchema: "nvarchar",
metadataTable: "nvarchar",
metadataName: "nvarchar",
metadataValue: "nvarchar(5000)"
};
this.dataTypeDefaults = {
char: {
length: 1
},
nchar: {
length: 1
},
varchar: {
length: 255
},
nvarchar: {
length: 255
},
shorttext: {
length: 255
},
varbinary: {
length: 255
},
decimal: {
precision: 18,
scale: 0
}
};
this.maxAliasLength = 128;
this.cteCapabilities = {
enabled: true
};
this.dummyTableName = `SYS.DUMMY`;
this.connection = e;
this.options = e.options;
this.loadDependencies();
this.database = ib.DriverUtils.buildDriverOptions(this.options).database;
this.schema = ib.DriverUtils.buildDriverOptions(this.options).schema;
}
async connect() {
const e = {
hostName: this.options.host,
port: this.options.port,
userName: this.options.username,
password: this.options.password,
...this.options.extra
};
if (this.options.database) e.databaseName = this.options.database;
if (this.options.schema) e.currentSchema = this.options.schema;
if (this.options.encrypt) e.encrypt = this.options.encrypt;
if (this.options.sslValidateCertificate) e.validateCertificate = this.options.sslValidateCertificate;
if (this.options.key) e.key = this.options.key;
if (this.options.cert) e.cert = this.options.cert;
if (this.options.ca) e.ca = this.options.ca;
const t = {
min: this.options.pool && this.options.pool.min ? this.options.pool.min : 1,
max: this.options.pool && this.options.pool.max ? this.options.pool.max : 10
};
if (this.options.pool && this.options.pool.checkInterval) t.checkInterval = this.options.pool.checkInterval;
if (this.options.pool && this.options.pool.maxWaitingRequests) t.maxWaitingRequests = this.options.pool.maxWaitingRequests;
if (this.options.pool && this.options.pool.requestTimeout) t.requestTimeout = this.options.pool.requestTimeout;
if (this.options.pool && this.options.pool.idleTimeout) t.idleTimeout = this.options.pool.idleTimeout;
const {logger: n} = this.connection;
const a = t.poolErrorHandler || (e => n.log("warn", `SAP Hana pool raised an error. ${e}`));
this.client.eventEmitter.on("poolError", a);
this.master = this.client.createPool(e, t);
const r = this.createQueryRunner("master");
const {version: i, database: s} = await r.getDatabaseAndVersion();
this.version = i;
this.database = s;
if (!this.schema) {
this.schema = await r.getCurrentSchema();
}
await r.release();
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
const e = this.master.clear();
this.master = undefined;
return e;
}
createSchemaBuilder() {
return new eb.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new rb.SapQueryRunner(this, e);
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => {
if (n[e] instanceof Date) return nb.DateUtils.mixedDateToDatetimeString(n[e], true);
return n[e];
});
if (!t || !Object.keys(t).length) return [ e, a ];
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, r) => {
if (!t.hasOwnProperty(r)) {
return e;
}
const i = t[r];
if (n) {
return i.map(e => {
a.push(e);
return this.createParameter(r, a.length - 1);
}).join(", ");
}
if (typeof i === "function") {
return i();
}
if (i instanceof Date) {
return nb.DateUtils.mixedDateToDatetimeString(i, true);
}
a.push(i);
return this.createParameter(r, a.length - 1);
});
return [ e, a ];
}
escape(e) {
return `"${e}"`;
}
buildTableName(e, t) {
const n = [ e ];
if (t) {
n.unshift(t);
}
return n.join(".");
}
parseTableName(e) {
const t = this.database;
const n = this.schema;
if (sb.InstanceChecker.isTable(e) || sb.InstanceChecker.isView(e)) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (sb.InstanceChecker.isTableForeignKey(e)) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (sb.InstanceChecker.isEntityMetadata(e)) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: t,
schema: (a.length > 1 ? a[0] : undefined) || n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
preparePersistentValue(e, t) {
if (t.transformer) e = tb.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === Boolean) {
return e === true ? 1 : 0;
} else if (t.type === "date") {
return nb.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
return nb.DateUtils.mixedDateToTimeString(e);
} else if (t.type === "timestamp" || t.type === Date) {
return nb.DateUtils.mixedDateToDatetimeString(e, true);
} else if (t.type === "seconddate") {
return nb.DateUtils.mixedDateToDatetimeString(e, false);
} else if (t.type === "simple-array") {
return nb.DateUtils.simpleArrayToString(e);
} else if (t.type === "simple-json") {
return nb.DateUtils.simpleJsonToString(e);
} else if (t.type === "simple-enum") {
return nb.DateUtils.simpleEnumToString(e);
} else if (t.isArray) {
return () => `ARRAY(${e.map(e => `'${e}'`)})`;
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? tb.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean) {
e = e ? true : false;
} else if (t.type === "timestamp" || t.type === "seconddate" || t.type === Date) {
e = nb.DateUtils.normalizeHydratedDate(e);
} else if (t.type === "date") {
e = nb.DateUtils.mixedDateToDateString(e);
} else if (t.type === "time") {
e = nb.DateUtils.mixedTimeToString(e);
} else if (t.type === "simple-array") {
e = nb.DateUtils.stringToSimpleArray(e);
} else if (t.type === "simple-json") {
e = nb.DateUtils.stringToSimpleJson(e);
} else if (t.type === "simple-enum") {
e = nb.DateUtils.stringToSimpleEnum(e, t);
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = tb.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number || e.type === "int") {
return "integer";
} else if (e.type === "dec") {
return "decimal";
} else if (e.type === "float") {
const t = typeof e.length === "string" ? parseInt(e.length) : e.length;
if (t && t < 25) {
return "real";
}
return "double";
} else if (e.type === String) {
return "nvarchar";
} else if (e.type === Date) {
return "timestamp";
} else if (e.type === Boolean) {
return "boolean";
} else if (e.type === Buffer) {
return "blob";
} else if (e.type === "uuid") {
return "nvarchar";
} else if (e.type === "simple-array" || e.type === "simple-json") {
return "nclob";
} else if (e.type === "simple-enum") {
return "nvarchar";
}
if (ib.DriverUtils.isReleaseVersionOrGreater(this, "4.0")) {
if (e.type === "varchar" || e.type === "alphanum" || e.type === "shorttext") {
return "nvarchar";
} else if (e.type === "text" || e.type === "clob") {
return "nclob";
} else if (e.type === "char") {
return "nchar";
}
}
return e.type || "";
}
normalizeDefault(e) {
const t = e.default;
if (typeof t === "number") {
return `${t}`;
}
if (typeof t === "boolean") {
return t ? "true" : "false";
}
if (typeof t === "function") {
return t();
}
if (typeof t === "string") {
return `'${t}'`;
}
if (t === null || t === undefined) {
return undefined;
}
return `${t}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.indices.some(t => t.isUnique && t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
if (e.generationStrategy === "uuid") return "36";
switch (e.type) {
case "varchar":
case "nvarchar":
case "shorttext":
case String:
return "255";
case "alphanum":
return "127";
case "varbinary":
return "255";
}
return "";
}
createFullType(e) {
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += `(${e.precision},${e.scale})`;
} else if (e.precision !== null && e.precision !== undefined) {
t += `(${e.precision})`;
}
if (e.isArray) t += " array";
return t;
}
obtainMasterConnection() {
if (!this.master) {
throw new XA.TypeORMError("Driver not Connected");
}
return this.master.getConnection();
}
obtainSlaveConnection() {
return this.obtainMasterConnection();
}
createGeneratedMap(e, t) {
const n = e.generatedColumns.reduce((e, n) => {
let a;
if (n.generationStrategy === "increment" && t) {
a = t;
}
return ab.OrmUtils.mergeDeep(e, n.createValueMap(a));
}, {});
return Object.keys(n).length > 0 ? n : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) {
return false;
}
const a = this.normalizeDefault(t);
return n.name !== t.databaseName || n.type !== this.normalizeType(t) || t.length && n.length !== this.getColumnLength(t) || n.precision !== t.precision || n.scale !== t.scale || n.comment !== this.escapeComment(t.comment) || !n.isGenerated && a !== n.default || n.isPrimary !== t.isPrimary || n.isNullable !== t.isNullable || n.isUnique !== this.normalizeIsUnique(t) || t.generationStrategy !== "uuid" && n.isGenerated !== t.isGenerated;
});
}
isReturningSqlSupported() {
return false;
}
isUUIDGenerationSupported() {
return false;
}
isFullTextColumnTypeSupported() {
return !ib.DriverUtils.isReleaseVersionOrGreater(this, "4.0");
}
createParameter(e, t) {
return "?";
}
loadDependencies() {
try {
const e = this.options.driver || ZA.PlatformTools.load("hdb-pool");
this.client = e;
} catch (e) {
throw new JA.DriverPackageNotInstalledError("SAP Hana", "hdb-pool");
}
try {
if (!this.options.hanaClientDriver) {
ZA.PlatformTools.load("@sap/hana-client");
this.streamClient = ZA.PlatformTools.load("@sap/hana-client/extension/Stream");
}
} catch (e) {
throw new JA.DriverPackageNotInstalledError("SAP Hana", "@sap/hana-client");
}
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/\u0000/g, "");
return e;
}
}
OA.SapDriver = SapDriver;
var ob = {};
var cb = {};
var lb;
function ub() {
if (lb) return cb;
lb = 1;
Object.defineProperty(cb, "__esModule", {
value: true
});
cb.BetterSqlite3QueryRunner = void 0;
const e = Sn();
const t = nn();
const n = OE;
const a = hf;
const r = lf;
const i = sc;
let s = class BetterSqlite3QueryRunner extends n.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.stmtCache = new Map;
this.driver = e;
this.connection = e.connection;
this.broadcaster = new a.Broadcaster(this);
if (typeof this.driver.options.statementCacheSize === "number") {
this.cacheSize = this.driver.options.statementCacheSize;
} else {
this.cacheSize = 100;
}
}
async getStmt(e) {
if (this.cacheSize > 0) {
let t = this.stmtCache.get(e);
if (!t) {
const n = await this.connect();
t = n.prepare(e);
this.stmtCache.set(e, t);
while (this.stmtCache.size > this.cacheSize) {
const e = this.stmtCache.keys().next().value;
this.stmtCache.delete(e);
}
}
return t;
} else {
const t = await this.connect();
return t.prepare(e);
}
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async query(n, a, s = false) {
if (this.isReleased) throw new e.QueryRunnerAlreadyReleasedError;
const o = this.driver.connection;
const c = new i.BroadcasterResult;
this.driver.connection.logger.logQuery(n, a, this);
this.broadcaster.broadcastBeforeQueryEvent(c, n, a);
const l = Date.now();
const u = await this.getStmt(n);
try {
const e = new r.QueryResult;
if (u.reader) {
const t = u.all.apply(u, a);
e.raw = t;
if (Array.isArray(t)) {
e.records = t;
}
} else {
const t = u.run.apply(u, a);
e.affected = t.changes;
e.raw = t.lastInsertRowid;
}
const t = this.driver.options.maxQueryExecutionTime;
const i = Date.now();
const h = i - l;
if (t && h > t) o.logger.logQuerySlow(h, n, a, this);
this.broadcaster.broadcastAfterQueryEvent(c, n, a, true, h, e.raw, undefined);
if (!s) {
return e.raw;
}
return e;
} catch (e) {
o.logger.logQueryError(e, n, a, this);
throw new t.QueryFailedError(n, a, e);
}
}
async loadTableRecords(e, t) {
const [n, a] = this.splitTablePath(e);
const r = await this.query(`SELECT ${n ? `'${n}'` : null} as database, * FROM ${this.escapePath(`${n ? `${n}.` : ""}sqlite_master`)} WHERE "type" = '${t}' AND "${t === "table" ? "name" : "tbl_name"}" IN ('${a}')`);
return r;
}
async loadPragmaRecords(e, t) {
const [n, a] = this.splitTablePath(e);
const r = await this.query(`PRAGMA ${n ? `"${n}".` : ""}${t}("${a}")`);
return r;
}
};
cb.BetterSqlite3QueryRunner = s;
return cb;
}
Object.defineProperty(ob, "__esModule", {
value: true
});
ob.BetterSqlite3Driver = void 0;
const hb = e;
const db = hb.__importDefault(m);
const pb = hb.__importDefault(c);
const mb = P;
const fb = Uh;
const yb = KE;
const Eb = ub();
const Tb = Pd();
class BetterSqlite3Driver extends yb.AbstractSqliteDriver {
constructor(e) {
super(e);
this.connection = e;
this.options = e.options;
this.database = this.options.database;
this.loadDependencies();
}
async disconnect() {
this.queryRunner = undefined;
this.databaseConnection.close();
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new Eb.BetterSqlite3QueryRunner(this);
return this.queryRunner;
}
normalizeType(e) {
if (e.type === Buffer) {
return "blob";
}
return super.normalizeType(e);
}
async afterConnect() {
return this.attachDatabases();
}
buildTableName(e, t, n) {
if (!n) return e;
if (this.getAttachedDatabaseHandleByRelativePath(n)) return `${this.getAttachedDatabaseHandleByRelativePath(n)}.${e}`;
if (n === this.options.database) return e;
const a = (0, Tb.filepathToName)(n);
const r = (0, Tb.isAbsolute)(n) ? n : pb.default.join(this.getMainDatabasePath(), n);
this.attachedDatabases[n] = {
attachFilepathAbsolute: r,
attachFilepathRelative: n,
attachHandle: a
};
return `${a}.${e}`;
}
async createDatabaseConnection() {
if (this.options.database !== ":memory:") await this.createDatabaseDirectory(pb.default.dirname(this.options.database));
const {database: e, readonly: t = false, fileMustExist: n = false, timeout: a = 5e3, verbose: r = null, nativeBinding: i = null, prepareDatabase: s} = this.options;
const o = this.sqlite(e, {
readonly: t,
fileMustExist: n,
timeout: a,
verbose: r,
nativeBinding: i
});
if (this.options.key) {
o.exec(`PRAGMA key = ${JSON.stringify(this.options.key)}`);
}
if (typeof s === "function") {
s(o);
}
o.exec(`PRAGMA foreign_keys = ON`);
if (this.options.enableWAL) {
o.exec(`PRAGMA journal_mode = WAL`);
}
return o;
}
loadDependencies() {
try {
const e = this.options.driver || fb.PlatformTools.load("better-sqlite3");
this.sqlite = e;
} catch (e) {
throw new mb.DriverPackageNotInstalledError("SQLite", "better-sqlite3");
}
}
async createDatabaseDirectory(e) {
await db.default.mkdir(e, {
recursive: true
});
}
async attachDatabases() {
for await (const {attachHandle: e, attachFilepathAbsolute: t} of Object.values(this.attachedDatabases)) {
await this.createDatabaseDirectory(pb.default.dirname(t));
await this.connection.query(`ATTACH "${t}" AS "${e}"`);
}
}
getMainDatabasePath() {
const e = this.options.database;
return pb.default.dirname((0, Tb.isAbsolute)(e) ? e : pb.default.join(this.options.baseDirectory, e));
}
}
ob.BetterSqlite3Driver = BetterSqlite3Driver;
var gb = {};
var Nb = {};
Object.defineProperty(Nb, "__esModule", {
value: true
});
Nb.CapacitorQueryRunner = void 0;
const Ab = Sn();
const bb = nn();
const Cb = OE;
const Rb = hf;
const Sb = lf;
class CapacitorQueryRunner extends Cb.AbstractSqliteQueryRunner {
constructor(e) {
super();
this.driver = e;
this.connection = e.connection;
this.broadcaster = new Rb.Broadcaster(this);
}
async beforeMigration() {
await this.query(`PRAGMA foreign_keys = OFF`);
}
async afterMigration() {
await this.query(`PRAGMA foreign_keys = ON`);
}
async executeSet(e) {
if (this.isReleased) throw new Ab.QueryRunnerAlreadyReleasedError;
const t = await this.connect();
return t.executeSet(e, false);
}
async query(e, t, n = false) {
if (this.isReleased) throw new Ab.QueryRunnerAlreadyReleasedError;
const a = await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
const r = e.substring(0, e.indexOf(" ") !== -1 ? e.indexOf(" ") : undefined);
try {
let i;
if ([ "BEGIN", "ROLLBACK", "COMMIT", "CREATE", "ALTER", "DROP" ].indexOf(r) !== -1) {
i = await a.execute(e, false);
} else if ([ "INSERT", "UPDATE", "DELETE" ].indexOf(r) !== -1) {
i = await a.run(e, t, false);
} else {
i = await a.query(e, t || []);
}
const s = new Sb.QueryResult;
if (i?.hasOwnProperty("values")) {
s.raw = i.values;
s.records = i.values;
}
if (i?.hasOwnProperty("changes")) {
s.affected = i.changes.changes;
s.raw = i.changes.lastId || i.changes.changes;
}
if (!n) {
return s.raw;
}
return s;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
throw new bb.QueryFailedError(e, t, n);
}
}
parametrize(e) {
return Object.keys(e).map(e => `"${e}"` + "=?");
}
}
Nb.CapacitorQueryRunner = CapacitorQueryRunner;
Object.defineProperty(gb, "__esModule", {
value: true
});
gb.CapacitorDriver = void 0;
const wb = KE;
const Mb = Nb;
const Ob = P;
class CapacitorDriver extends wb.AbstractSqliteDriver {
constructor(e) {
super(e);
this.database = this.options.database;
this.driver = this.options.driver;
this.sqlite = this.options.driver;
}
async connect() {
this.databaseConnection = this.createDatabaseConnection();
await this.databaseConnection;
}
async disconnect() {
this.queryRunner = undefined;
const e = await this.databaseConnection;
return e.close().then(() => {
this.databaseConnection = undefined;
});
}
createQueryRunner(e) {
if (!this.queryRunner) this.queryRunner = new Mb.CapacitorQueryRunner(this);
return this.queryRunner;
}
async createDatabaseConnection() {
const e = this.options.mode || "no-encryption";
const t = e !== "no-encryption";
const n = typeof this.options.version === "undefined" ? 1 : this.options.version;
const a = await this.sqlite.createConnection(this.options.database, t, e, n);
await a.open();
await a.execute(`PRAGMA foreign_keys = ON`);
if (this.options.journalMode && [ "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL", "OFF" ].indexOf(this.options.journalMode) !== -1) {
await a.execute(`PRAGMA journal_mode = ${this.options.journalMode}`);
}
return a;
}
loadDependencies() {
this.sqlite = this.driver;
if (!this.driver) {
throw new Ob.DriverPackageNotInstalledError("Capacitor", "@capacitor-community/sqlite");
}
}
}
gb.CapacitorDriver = CapacitorDriver;
var vb = {};
var Ib = {};
Object.defineProperty(Ib, "__esModule", {
value: true
});
Ib.SpannerQueryRunner = void 0;
const Pb = P;
const Lb = nn();
const Db = Sn();
const _b = pe();
const $b = Zm;
const xb = lf;
const qb = fu;
const Ub = Su;
const Bb = yu;
const Fb = Nu;
const jb = Tu;
const kb = Cu;
const Qb = Bm;
const Vb = hf;
const Kb = sc;
const Wb = qc;
const Hb = ef;
const Gb = mf;
class SpannerQueryRunner extends $b.BaseQueryRunner {
constructor(e, t) {
super();
this.driver = e;
this.connection = e.connection;
this.mode = t;
this.broadcaster = new Vb.Broadcaster(this);
}
async connect() {
if (this.session) {
return Promise.resolve(this.session);
}
const [e] = await this.driver.instanceDatabase.createSession({});
this.session = e;
this.sessionTransaction = await e.transaction();
return this.session;
}
async release() {
this.isReleased = true;
if (this.session) {
await this.session.delete();
}
this.session = undefined;
return Promise.resolve();
}
async startTransaction(e) {
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
} catch (e) {
this.isTransactionActive = false;
throw e;
}
await this.connect();
await this.sessionTransaction.begin();
this.connection.logger.logQuery("START TRANSACTION");
await this.broadcaster.broadcast("AfterTransactionStart");
}
async commitTransaction() {
if (!this.isTransactionActive || !this.sessionTransaction) throw new _b.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionCommit");
await this.sessionTransaction.commit();
this.connection.logger.logQuery("COMMIT");
this.isTransactionActive = false;
await this.broadcaster.broadcast("AfterTransactionCommit");
}
async rollbackTransaction() {
if (!this.isTransactionActive || !this.sessionTransaction) throw new _b.TransactionNotStartedError;
await this.broadcaster.broadcast("BeforeTransactionRollback");
await this.sessionTransaction.rollback();
this.connection.logger.logQuery("ROLLBACK");
this.isTransactionActive = false;
await this.broadcaster.broadcast("AfterTransactionRollback");
}
async query(e, t, n = false) {
if (this.isReleased) throw new Db.QueryRunnerAlreadyReleasedError;
await this.connect();
this.driver.connection.logger.logQuery(e, t, this);
await this.broadcaster.broadcast("BeforeQuery", e, t);
const a = new Kb.BroadcasterResult;
try {
const r = Date.now();
let i = undefined;
const s = e.startsWith("SELECT");
const o = s && !this.isTransactionActive ? this.driver.instanceDatabase : this.sessionTransaction;
if (!this.isTransactionActive && !s) {
await this.sessionTransaction.begin();
}
try {
i = await o.run({
sql: e,
params: t ? t.reduce((e, t, n) => {
e["param" + n] = t;
return e;
}, {}) : undefined,
json: true
});
if (!this.isTransactionActive && !s) {
await this.sessionTransaction.commit();
}
} catch (e) {
try {
if (!this.isTransactionActive && !s) await this.sessionTransaction.rollback();
} catch (e) {}
throw e;
}
const c = this.driver.options.maxQueryExecutionTime;
const l = Date.now();
const u = l - r;
this.broadcaster.broadcastAfterQueryEvent(a, e, t, true, u, i, undefined);
if (c && u > c) this.driver.connection.logger.logQuerySlow(u, e, t, this);
const h = new xb.QueryResult;
h.raw = i;
h.records = i ? i[0] : [];
if (i && i[1] && i[1].rowCountExact) {
h.affected = parseInt(i[1].rowCountExact);
}
if (!n) {
return h.records;
}
return h;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
this.broadcaster.broadcastAfterQueryEvent(a, e, t, false, undefined, undefined, n);
throw new Lb.QueryFailedError(e, t, n);
} finally {
await a.wait();
}
}
async updateDDL(e, t) {
if (this.isReleased) throw new Db.QueryRunnerAlreadyReleasedError;
this.driver.connection.logger.logQuery(e, t, this);
try {
const n = Date.now();
const [a] = await this.driver.instanceDatabase.updateSchema(e);
await a.promise();
const r = this.driver.options.maxQueryExecutionTime;
const i = Date.now();
const s = i - n;
if (r && s > r) this.driver.connection.logger.logQuerySlow(s, e, t, this);
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
throw new Lb.QueryFailedError(e, t, n);
}
}
async stream(e, t, n, a) {
if (this.isReleased) throw new Db.QueryRunnerAlreadyReleasedError;
try {
this.driver.connection.logger.logQuery(e, t, this);
const r = {
sql: e,
params: t ? t.reduce((e, t, n) => {
e["param" + n] = t;
return e;
}, {}) : undefined,
json: true
};
const i = this.driver.instanceDatabase.runStream(r);
if (n) {
i.on("end", n);
}
if (a) {
i.on("error", a);
}
return i;
} catch (n) {
this.driver.connection.logger.logQueryError(n, e, t, this);
throw new Lb.QueryFailedError(e, t, n);
}
}
async getDatabases() {
return Promise.resolve([]);
}
async getSchemas(e) {
return Promise.resolve([]);
}
async hasDatabase(e) {
throw new Pb.TypeORMError(`Check database queries are not supported by Spanner driver.`);
}
async getCurrentDatabase() {
throw new Pb.TypeORMError(`Check database queries are not supported by Spanner driver.`);
}
async hasSchema(e) {
const t = await this.query(`SELECT * FROM "information_schema"."schemata" WHERE "schema_name" = '${e}'`);
return t.length ? true : false;
}
async getCurrentSchema() {
throw new Pb.TypeORMError(`Check schema queries are not supported by Spanner driver.`);
}
async hasTable(e) {
const t = e instanceof qb.Table ? e.name : e;
const n = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE' ` + `AND \`TABLE_NAME\` = '${t}'`;
const a = await this.query(n);
return a.length ? true : false;
}
async hasColumn(e, t) {
const n = e instanceof qb.Table ? e.name : e;
const a = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' ` + `AND \`TABLE_NAME\` = '${n}' AND \`COLUMN_NAME\` = '${t}'`;
const r = await this.query(a);
return r.length ? true : false;
}
async createDatabase(e, t) {
if (t) {
const t = await this.hasDatabase(e);
if (t) return Promise.resolve();
}
const n = `CREATE DATABASE "${e}"`;
const a = `DROP DATABASE "${e}"`;
await this.executeQueries(new Hb.Query(n), new Hb.Query(a));
}
async dropDatabase(e, t) {
const n = t ? `DROP DATABASE IF EXISTS "${e}"` : `DROP DATABASE "${e}"`;
const a = `CREATE DATABASE "${e}"`;
await this.executeQueries(new Hb.Query(n), new Hb.Query(a));
}
async createSchema(e, t) {
return Promise.resolve();
}
async dropSchema(e, t, n) {
return Promise.resolve();
}
async createTable(e, t = false, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (t) return Promise.resolve();
}
const r = [];
const i = [];
r.push(this.createTableSql(e, n));
i.push(this.dropTableSql(e));
if (n) e.foreignKeys.forEach(t => i.push(this.dropForeignKeySql(e, t)));
if (a) {
e.indices.forEach(t => {
if (!t.name) t.name = this.connection.namingStrategy.indexName(e, t.columnNames, t.where);
r.push(this.createIndexSql(e, t));
i.push(this.dropIndexSql(e, t));
});
}
const s = e.columns.filter(e => e.generatedType && e.asExpression);
for (const t of s) {
const n = this.insertTypeormMetadataSql({
table: e.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const a = this.deleteTypeormMetadataSql({
table: e.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(n);
i.push(a);
}
await this.executeQueries(r, i);
}
async dropTable(e, t, n = true, a = true) {
if (t) {
const t = await this.hasTable(e);
if (!t) return Promise.resolve();
}
const r = n;
const i = this.getTablePath(e);
const s = await this.getCachedTable(i);
const o = [];
const c = [];
if (a) {
s.indices.forEach(e => {
o.push(this.dropIndexSql(s, e));
c.push(this.createIndexSql(s, e));
});
}
if (n) s.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(s, e)));
o.push(this.dropTableSql(s));
c.push(this.createTableSql(s, r));
const l = s.columns.filter(e => e.generatedType && e.asExpression);
for (const e of l) {
const t = this.deleteTypeormMetadataSql({
table: s.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: e.name
});
const n = this.insertTypeormMetadataSql({
table: s.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: e.name,
value: e.asExpression
});
o.push(t);
c.push(n);
}
await this.executeQueries(o, c);
}
async createView(e) {
const t = [];
const n = [];
t.push(this.createViewSql(e));
t.push(await this.insertViewDefinitionSql(e));
n.push(this.dropViewSql(e));
n.push(await this.deleteViewDefinitionSql(e));
await this.executeQueries(t, n);
}
async dropView(e) {
const t = e instanceof Qb.View ? e.name : e;
const n = await this.getCachedView(t);
const a = [];
const r = [];
a.push(await this.deleteViewDefinitionSql(n));
a.push(this.dropViewSql(n));
r.push(await this.insertViewDefinitionSql(n));
r.push(this.createViewSql(n));
await this.executeQueries(a, r);
}
async renameTable(e, t) {
throw new Pb.TypeORMError(`Rename table queries are not supported by Spanner driver.`);
}
async addColumn(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
const a = n.clone();
const r = [];
const i = [];
r.push(new Hb.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t)}`));
i.push(new Hb.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN ${this.driver.escape(t.name)}`));
const s = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
if (s) {
r.push(this.createIndexSql(n, s));
i.push(this.dropIndexSql(n, s));
} else if (t.isUnique) {
const e = new jb.TableIndex({
name: this.connection.namingStrategy.indexName(n, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
});
a.indices.push(e);
a.uniques.push(new kb.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
r.push(this.createIndexSql(n, e));
i.push(this.dropIndexSql(n, e));
}
if (t.generatedType && t.asExpression) {
const e = this.insertTypeormMetadataSql({
table: n.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: t.name,
value: t.asExpression
});
const a = this.deleteTypeormMetadataSql({
table: n.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: t.name
});
r.push(e);
i.push(a);
}
await this.executeQueries(r, i);
a.addColumn(t);
this.replaceCachedTable(n, a);
}
async addColumns(e, t) {
for (const n of t) {
await this.addColumn(e, n);
}
}
async renameColumn(e, t, n) {
const a = e instanceof qb.Table ? e : await this.getCachedTable(e);
const r = t instanceof Bb.TableColumn ? t : a.columns.find(e => e.name === t);
if (!r) throw new Pb.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
let i;
if (n instanceof Bb.TableColumn) {
i = n;
} else {
i = r.clone();
i.name = n;
}
return this.changeColumn(a, r, i);
}
async changeColumn(e, t, n) {
const a = e instanceof qb.Table ? e : await this.getCachedTable(e);
let r = a.clone();
const i = [];
const s = [];
const o = t instanceof Bb.TableColumn ? t : a.columns.find(e => e.name === t);
if (!o) throw new Pb.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
if (o.name !== n.name || o.type !== n.type || o.length !== n.length || o.isArray !== n.isArray || o.generatedType !== n.generatedType || o.asExpression !== n.asExpression) {
await this.dropColumn(a, o);
await this.addColumn(a, n);
r = a.clone();
} else {
if (n.precision !== o.precision || n.scale !== o.scale) {
i.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
s.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(o)}`));
}
if (o.isNullable !== n.isNullable) {
if (n.isNullable) {
i.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" DROP NOT NULL`));
s.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" SET NOT NULL`));
} else {
i.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" SET NOT NULL`));
s.push(new Hb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" DROP NOT NULL`));
}
}
if (n.isUnique !== o.isUnique) {
if (n.isUnique === true) {
const e = new jb.TableIndex({
name: this.connection.namingStrategy.indexName(a, [ n.name ]),
columnNames: [ n.name ],
isUnique: true
});
r.indices.push(e);
r.uniques.push(new kb.TableUnique({
name: e.name,
columnNames: e.columnNames
}));
i.push(this.createIndexSql(a, e));
s.push(this.dropIndexSql(a, e));
} else {
const e = r.indices.find(e => e.columnNames.length === 1 && e.isUnique === true && !!e.columnNames.find(e => e === n.name));
r.indices.splice(r.indices.indexOf(e), 1);
const t = r.uniques.find(t => t.name === e.name);
r.uniques.splice(r.uniques.indexOf(t), 1);
i.push(this.dropIndexSql(a, e));
s.push(this.createIndexSql(a, e));
}
}
}
await this.executeQueries(i, s);
this.replaceCachedTable(a, r);
}
async changeColumns(e, t) {
for (const {oldColumn: n, newColumn: a} of t) {
await this.changeColumn(e, n, a);
}
}
async dropColumn(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
const a = t instanceof Bb.TableColumn ? t : n.findColumnByName(t);
if (!a) throw new Pb.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
const r = n.clone();
const i = [];
const s = [];
const o = r.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (o) {
r.indices.splice(r.indices.indexOf(o), 1);
i.push(this.dropIndexSql(n, o));
s.push(this.createIndexSql(n, o));
}
const c = r.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === a.name);
if (c) {
r.checks.splice(r.checks.indexOf(c), 1);
i.push(this.dropCheckConstraintSql(n, c));
s.push(this.createCheckConstraintSql(n, c));
}
i.push(new Hb.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN ${this.driver.escape(a.name)}`));
s.push(new Hb.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a)}`));
if (a.generatedType && a.asExpression) {
const e = this.deleteTypeormMetadataSql({
table: n.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: a.name
});
const t = this.insertTypeormMetadataSql({
table: n.name,
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: a.name,
value: a.asExpression
});
i.push(e);
s.push(t);
}
await this.executeQueries(i, s);
r.removeColumn(a);
this.replaceCachedTable(n, r);
}
async dropColumns(e, t) {
for (const n of t) {
await this.dropColumn(e, n);
}
}
async createPrimaryKey(e, t) {
throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
}
async updatePrimaryKeys(e, t) {
throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
}
async dropPrimaryKey(e) {
throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
}
async createUniqueConstraint(e, t) {
throw new Pb.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
}
async createUniqueConstraints(e, t) {
throw new Pb.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraint(e, t) {
throw new Pb.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
}
async dropUniqueConstraints(e, t) {
throw new Pb.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
}
async createCheckConstraint(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.checkConstraintName(n, t.expression);
const a = this.createCheckConstraintSql(n, t);
const r = this.dropCheckConstraintSql(n, t);
await this.executeQueries(a, r);
n.addCheckConstraint(t);
}
async createCheckConstraints(e, t) {
const n = t.map(t => this.createCheckConstraint(e, t));
await Promise.all(n);
}
async dropCheckConstraint(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
const a = t instanceof Ub.TableCheck ? t : n.checks.find(e => e.name === t);
if (!a) throw new Pb.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
const r = this.dropCheckConstraintSql(n, a);
const i = this.createCheckConstraintSql(n, a);
await this.executeQueries(r, i);
n.removeCheckConstraint(a);
}
async dropCheckConstraints(e, t) {
const n = t.map(t => this.dropCheckConstraint(e, t));
await Promise.all(n);
}
async createExclusionConstraint(e, t) {
throw new Pb.TypeORMError(`Spanner does not support exclusion constraints.`);
}
async createExclusionConstraints(e, t) {
throw new Pb.TypeORMError(`Spanner does not support exclusion constraints.`);
}
async dropExclusionConstraint(e, t) {
throw new Pb.TypeORMError(`Spanner does not support exclusion constraints.`);
}
async dropExclusionConstraints(e, t) {
throw new Pb.TypeORMError(`Spanner does not support exclusion constraints.`);
}
async createForeignKey(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(n, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = this.createForeignKeySql(n, t);
const r = this.dropForeignKeySql(n, t);
await this.executeQueries(a, r);
n.addForeignKey(t);
}
async createForeignKeys(e, t) {
for (const n of t) {
await this.createForeignKey(e, n);
}
}
async dropForeignKey(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
const a = t instanceof Fb.TableForeignKey ? t : n.foreignKeys.find(e => e.name === t);
if (!a) throw new Pb.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
const r = this.dropForeignKeySql(n, a);
const i = this.createForeignKeySql(n, a);
await this.executeQueries(r, i);
n.removeForeignKey(a);
}
async dropForeignKeys(e, t) {
for (const n of t) {
await this.dropForeignKey(e, n);
}
}
async createIndex(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
if (!t.name) t.name = this.generateIndexName(n, t);
const a = this.createIndexSql(n, t);
const r = this.dropIndexSql(n, t);
await this.executeQueries(a, r);
n.addIndex(t);
}
async createIndices(e, t) {
for (const n of t) {
await this.createIndex(e, n);
}
}
async dropIndex(e, t) {
const n = e instanceof qb.Table ? e : await this.getCachedTable(e);
const a = t instanceof jb.TableIndex ? t : n.indices.find(e => e.name === t);
if (!a) throw new Pb.TypeORMError(`Supplied index ${t} was not found in table ${n.name}`);
if (!a.name) a.name = this.generateIndexName(n, a);
const r = this.dropIndexSql(n, a);
const i = this.createIndexSql(n, a);
await this.executeQueries(r, i);
n.removeIndex(a);
}
async dropIndices(e, t) {
for (const n of t) {
await this.dropIndex(e, n);
}
}
async clearTable(e) {
await this.query(`DELETE FROM ${this.escapePath(e)} WHERE true`);
}
async clearDatabase() {
const e = `SELECT concat('DROP INDEX \`', INDEX_NAME, '\`') AS \`query\` ` + `FROM \`INFORMATION_SCHEMA\`.\`INDEXES\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`INDEX_TYPE\` = 'INDEX' AND \`SPANNER_IS_MANAGED\` = false`;
const t = await this.query(e);
const n = `SELECT concat('ALTER TABLE \`', TABLE_NAME, '\`', ' DROP CONSTRAINT \`', CONSTRAINT_NAME, '\`') AS \`query\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`CONSTRAINT_TYPE\` = 'FOREIGN KEY'`;
const a = await this.query(n);
const r = `SELECT concat('DROP TABLE \`', TABLE_NAME, '\`') AS \`query\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE'`;
const i = await this.query(r);
if (!t.length && !a.length && !i.length) return;
const s = this.isTransactionActive;
if (!s) await this.startTransaction();
try {
for (const e of t) {
await this.updateDDL(e["query"]);
}
for (const e of a) {
await this.updateDDL(e["query"]);
}
for (const e of i) {
await this.updateDDL(e["query"]);
}
await this.commitTransaction();
} catch (e) {
try {
if (!s) await this.rollbackTransaction();
} catch (e) {}
throw e;
}
}
async executeMemoryUpSql() {
for (const {query: e, parameters: t} of this.sqlInMemory.upQueries) {
if (this.isDMLQuery(e)) {
await this.query(e, t);
} else {
await this.updateDDL(e, t);
}
}
}
async executeMemoryDownSql() {
for (const {query: e, parameters: t} of this.sqlInMemory.downQueries.reverse()) {
if (this.isDMLQuery(e)) {
await this.query(e, t);
} else {
await this.updateDDL(e, t);
}
}
}
async loadViews(e) {
return Promise.resolve([]);
}
async loadTables(e) {
if (e && e.length === 0) {
return [];
}
const t = [];
if (!e || !e.length) {
const e = `SELECT \`TABLE_NAME\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE'`;
t.push(...await this.query(e));
} else {
const n = `SELECT \`TABLE_NAME\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` + `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE' ` + `AND \`TABLE_NAME\` IN (${e.map(e => `'${e}'`).join(", ")})`;
t.push(...await this.query(n));
}
if (!t.length) return [];
const n = t.map(e => `'${e.TABLE_NAME}'`).join(", ");
const a = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_NAME\` IN (${n})`;
const r = `SELECT \`KCU\`.\`TABLE_NAME\`, \`KCU\`.\`COLUMN_NAME\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`KCU\` ON \`KCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'PRIMARY KEY' ` + `AND \`TC\`.\`TABLE_NAME\` IN (${n})`;
const i = `SELECT \`I\`.\`TABLE_NAME\`, \`I\`.\`INDEX_NAME\`, \`I\`.\`IS_UNIQUE\`, \`I\`.\`IS_NULL_FILTERED\`, \`IC\`.\`COLUMN_NAME\` ` + `FROM \`INFORMATION_SCHEMA\`.\`INDEXES\` \`I\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`INDEX_COLUMNS\` \`IC\` ON \`IC\`.\`INDEX_NAME\` = \`I\`.\`INDEX_NAME\` ` + `AND \`IC\`.\`TABLE_NAME\` = \`I\`.\`TABLE_NAME\` ` + `WHERE \`I\`.\`TABLE_CATALOG\` = '' AND \`I\`.\`TABLE_SCHEMA\` = '' AND \`I\`.\`TABLE_NAME\` IN (${n}) ` + `AND \`I\`.\`INDEX_TYPE\` = 'INDEX' AND \`I\`.\`SPANNER_IS_MANAGED\` = false`;
const s = `SELECT \`TC\`.\`TABLE_NAME\`, \`TC\`.\`CONSTRAINT_NAME\`, \`CC\`.\`CHECK_CLAUSE\`, \`CCU\`.\`COLUMN_NAME\`` + `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_COLUMN_USAGE\` \`CCU\` ON \`CCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`CHECK_CONSTRAINTS\` \`CC\` ON \`CC\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'CHECK' ` + `AND \`TC\`.\`TABLE_NAME\` IN (${n}) AND \`TC\`.\`CONSTRAINT_NAME\` NOT LIKE 'CK_IS_NOT_NULL%'`;
const o = `SELECT \`TC\`.\`TABLE_NAME\`, \`TC\`.\`CONSTRAINT_NAME\`, \`KCU\`.\`COLUMN_NAME\`, ` + `\`CTU\`.\`TABLE_NAME\` AS \`REFERENCED_TABLE_NAME\`, \`CCU\`.\`COLUMN_NAME\` AS \`REFERENCED_COLUMN_NAME\`, ` + `\`RC\`.\`UPDATE_RULE\`, \`RC\`.\`DELETE_RULE\` ` + `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`KCU\` ON \`KCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_TABLE_USAGE\` \`CTU\` ON \`CTU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`RC\` ON \`RC\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_COLUMN_USAGE\` \`CCU\` ON \`CCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` + `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'FOREIGN KEY' ` + `AND \`TC\`.\`TABLE_NAME\` IN (${n})`;
const [c, l, u, h, d] = await Promise.all([ this.query(a), this.query(r), this.query(i), this.query(s), this.query(o) ]);
return Promise.all(t.map(async e => {
const t = new qb.Table;
t.name = this.driver.buildTableName(e["TABLE_NAME"]);
t.columns = await Promise.all(c.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"]).map(async n => {
const a = u.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"] && t["COLUMN_NAME"] === n["COLUMN_NAME"] && t["IS_UNIQUE"] === true);
const r = this.connection.entityMetadatas.find(e => this.getTablePath(t) === this.getTablePath(e));
const i = a.length > 0 && r && r.indices.some(e => a.some(t => e.name === t["INDEX_NAME"] && e.synchronize === false));
const s = a.every(e => u.some(t => t["INDEX_NAME"] === e["INDEX_NAME"] && t["COLUMN_NAME"] !== n["COLUMN_NAME"]));
const o = new Bb.TableColumn;
o.name = n["COLUMN_NAME"];
let c = n["SPANNER_TYPE"].toLowerCase();
if (c.indexOf("array") !== -1) {
o.isArray = true;
c = c.substring(c.indexOf("<") + 1, c.indexOf(">"));
}
if (c.indexOf("(") !== -1) {
o.type = c.substring(0, c.indexOf("("));
} else {
o.type = c;
}
if (this.driver.withLengthColumnTypes.indexOf(o.type) !== -1) {
o.length = c.substring(c.indexOf("(") + 1, c.indexOf(")"));
}
if (n["IS_GENERATED"] === "ALWAYS") {
o.asExpression = n["GENERATION_EXPRESSION"];
o.generatedType = "STORED";
const t = this.selectTypeormMetadataSql({
table: e["TABLE_NAME"],
type: Gb.MetadataTableType.GENERATED_COLUMN,
name: o.name
});
const a = await this.query(t.query, t.parameters);
if (a[0] && a[0].value) {
o.asExpression = a[0].value;
} else {
o.asExpression = "";
}
}
o.isUnique = a.length > 0 && !i && !s;
o.isNullable = n["IS_NULLABLE"] === "YES";
o.isPrimary = l.some(e => e["TABLE_NAME"] === n["TABLE_NAME"] && e["COLUMN_NAME"] === n["COLUMN_NAME"]);
return o;
}));
const n = d.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"]);
t.foreignKeys = Wb.OrmUtils.uniq(n, e => e["CONSTRAINT_NAME"]).map(e => {
const t = n.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new Fb.TableForeignKey({
name: e["CONSTRAINT_NAME"],
columnNames: Wb.OrmUtils.uniq(t.map(e => e["COLUMN_NAME"])),
referencedDatabase: e["REFERENCED_TABLE_SCHEMA"],
referencedTableName: e["REFERENCED_TABLE_NAME"],
referencedColumnNames: Wb.OrmUtils.uniq(t.map(e => e["REFERENCED_COLUMN_NAME"])),
onDelete: e["DELETE_RULE"],
onUpdate: e["UPDATE_RULE"]
});
});
const a = u.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"]);
t.indices = Wb.OrmUtils.uniq(a, e => e["INDEX_NAME"]).map(e => {
const n = a.filter(t => t["INDEX_NAME"] === e["INDEX_NAME"]);
return new jb.TableIndex({
table: t,
name: e["INDEX_NAME"],
columnNames: n.map(e => e["COLUMN_NAME"]),
isUnique: e["IS_UNIQUE"],
isNullFiltered: e["IS_NULL_FILTERED"]
});
});
const r = h.filter(t => t["TABLE_NAME"] === e["TABLE_NAME"]);
t.checks = Wb.OrmUtils.uniq(r, e => e["CONSTRAINT_NAME"]).map(e => {
const t = r.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
return new Ub.TableCheck({
name: e["CONSTRAINT_NAME"],
columnNames: t.map(e => e["COLUMN_NAME"]),
expression: e["CHECK_CLAUSE"]
});
});
return t;
}));
}
createTableSql(e, t) {
const n = e.columns.map(e => this.buildCreateColumnSql(e)).join(", ");
let a = `CREATE TABLE ${this.escapePath(e)} (${n}`;
e.columns.filter(e => e.isUnique).forEach(t => {
const n = e.indices.some(e => e.columnNames.length === 1 && !!e.isUnique && e.columnNames.indexOf(t.name) !== -1);
const a = e.uniques.some(e => e.columnNames.length === 1 && e.columnNames.indexOf(t.name) !== -1);
if (!n && !a) e.indices.push(new jb.TableIndex({
name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
columnNames: [ t.name ],
isUnique: true
}));
});
if (e.uniques.length > 0) {
e.uniques.forEach(t => {
const n = e.indices.some(e => e.name === t.name);
if (!n) {
e.indices.push(new jb.TableIndex({
name: t.name,
columnNames: t.columnNames,
isUnique: true
}));
}
});
}
if (e.checks.length > 0) {
const t = e.checks.map(t => {
const n = t.name ? t.name : this.connection.namingStrategy.checkConstraintName(e, t.expression);
return `CONSTRAINT \`${n}\` CHECK (${t.expression})`;
}).join(", ");
a += `, ${t}`;
}
if (e.foreignKeys.length > 0 && t) {
const t = e.foreignKeys.map(t => {
const n = t.columnNames.map(e => `\`${e}\``).join(", ");
if (!t.name) t.name = this.connection.namingStrategy.foreignKeyName(e, t.columnNames, this.getTablePath(t), t.referencedColumnNames);
const a = t.referencedColumnNames.map(e => `\`${e}\``).join(", ");
return `CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
}).join(", ");
a += `, ${t}`;
}
a += `)`;
const r = e.columns.filter(e => e.isPrimary);
if (r.length > 0) {
const e = r.map(e => this.driver.escape(e.name)).join(", ");
a += ` PRIMARY KEY (${e})`;
}
return new Hb.Query(a);
}
dropTableSql(e) {
return new Hb.Query(`DROP TABLE ${this.escapePath(e)}`);
}
createViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
const n = this.escapePath(e);
const a = typeof e.expression === "string" ? e.expression : e.expression(this.connection).getQuery();
return new Hb.Query(`CREATE ${t}VIEW ${n} SQL SECURITY INVOKER AS ${a}`);
}
async insertViewDefinitionSql(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
const a = e.materialized ? Gb.MetadataTableType.MATERIALIZED_VIEW : Gb.MetadataTableType.VIEW;
const r = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
return this.insertTypeormMetadataSql({
type: a,
schema: t,
name: n,
value: r
});
}
dropViewSql(e) {
const t = e.materialized ? "MATERIALIZED " : "";
return new Hb.Query(`DROP ${t}VIEW ${this.escapePath(e)}`);
}
async deleteViewDefinitionSql(e) {
const {schema: t, tableName: n} = this.driver.parseTableName(e);
const a = e.materialized ? Gb.MetadataTableType.MATERIALIZED_VIEW : Gb.MetadataTableType.VIEW;
return this.deleteTypeormMetadataSql({
type: a,
schema: t,
name: n
});
}
createIndexSql(e, t) {
const n = t.columnNames.map(e => this.driver.escape(e)).join(", ");
let a = "";
if (t.isUnique) a += "UNIQUE ";
if (t.isNullFiltered) a += "NULL_FILTERED ";
return new Hb.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})`);
}
dropIndexSql(e, t) {
const n = t instanceof jb.TableIndex ? t.name : t;
return new Hb.Query(`DROP INDEX \`${n}\``);
}
createCheckConstraintSql(e, t) {
return new Hb.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT \`${t.name}\` CHECK (${t.expression})`);
}
dropCheckConstraintSql(e, t) {
const n = t instanceof Ub.TableCheck ? t.name : t;
return new Hb.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT \`${n}\``);
}
createForeignKeySql(e, t) {
const n = t.columnNames.map(e => this.driver.escape(e)).join(", ");
const a = t.referencedColumnNames.map(e => this.driver.escape(e)).join(",");
const r = `ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT \`${t.name}\` FOREIGN KEY (${n}) ` + `REFERENCES ${this.escapePath(this.getTablePath(t))} (${a})`;
return new Hb.Query(r);
}
dropForeignKeySql(e, t) {
const n = t instanceof Fb.TableForeignKey ? t.name : t;
return new Hb.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT \`${n}\``);
}
escapePath(e) {
const {tableName: t} = this.driver.parseTableName(e);
return `\`${t}\``;
}
buildCreateColumnSql(e) {
let t = `${this.driver.escape(e.name)} ${this.connection.driver.createFullType(e)}`;
if (e.generatedType === "STORED" && e.asExpression) {
t += ` AS (${e.asExpression}) STORED`;
} else {
if (!e.isNullable) t += " NOT NULL";
}
return t;
}
async executeQueries(e, t) {
if (e instanceof Hb.Query) e = [ e ];
if (t instanceof Hb.Query) t = [ t ];
this.sqlInMemory.upQueries.push(...e);
this.sqlInMemory.downQueries.push(...t);
if (this.sqlMemoryMode === true) return Promise.resolve();
for (const {query: t, parameters: n} of e) {
if (this.isDMLQuery(t)) {
await this.query(t, n);
} else {
await this.updateDDL(t, n);
}
}
}
isDMLQuery(e) {
return e.startsWith("INSERT") || e.startsWith("UPDATE") || e.startsWith("DELETE");
}
changeTableComment(e, t) {
throw new Pb.TypeORMError(`spanner driver does not support change table comment.`);
}
}
Ib.SpannerQueryRunner = SpannerQueryRunner;
Object.defineProperty(vb, "__esModule", {
value: true
});
vb.SpannerDriver = void 0;
const Yb = Tt();
const zb = Ib;
const Jb = up;
const Xb = Uh;
const Zb = Um;
const eC = vp;
const tC = qc;
const nC = _s;
const aC = fu;
const rC = Bm;
const iC = Nu;
class SpannerDriver {
constructor(e) {
this.isReplicated = false;
this.treeSupport = true;
this.transactionSupport = "none";
this.supportedDataTypes = [ "bool", "int64", "float64", "numeric", "string", "json", "bytes", "date", "timestamp", "array" ];
this.supportedUpsertTypes = [];
this.spatialTypes = [];
this.withLengthColumnTypes = [ "string", "bytes" ];
this.withWidthColumnTypes = [];
this.withPrecisionColumnTypes = [];
this.withScaleColumnTypes = [];
this.mappedDataTypes = {
createDate: "timestamp",
createDateDefault: "",
updateDate: "timestamp",
updateDateDefault: "",
deleteDate: "timestamp",
deleteDateNullable: true,
version: "int64",
treeLevel: "int64",
migrationId: "int64",
migrationName: "string",
migrationTimestamp: "int64",
cacheId: "string",
cacheIdentifier: "string",
cacheTime: "int64",
cacheDuration: "int64",
cacheQuery: "string",
cacheResult: "string",
metadataType: "string",
metadataDatabase: "string",
metadataSchema: "string",
metadataTable: "string",
metadataName: "string",
metadataValue: "string"
};
this.parametersPrefix = "@param";
this.dataTypeDefaults = {};
this.maxAliasLength = 63;
this.cteCapabilities = {
enabled: true
};
this.connection = e;
this.options = e.options;
this.isReplicated = this.options.replication ? true : false;
this.loadDependencies();
}
async connect() {
this.instance = this.spanner.instance(this.options.instanceId);
this.instanceDatabase = this.instance.database(this.options.databaseId);
}
afterConnect() {
return Promise.resolve();
}
async disconnect() {
this.instanceDatabase.close();
}
createSchemaBuilder() {
return new Zb.RdbmsSchemaBuilder(this.connection);
}
createQueryRunner(e) {
return new zb.SpannerQueryRunner(this, e);
}
escapeQueryWithParameters(e, t, n) {
const a = Object.keys(n).map(e => n[e]);
if (!t || !Object.keys(t).length) return [ e, a ];
const r = new Map;
e = e.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
if (r.has(i)) {
return this.parametersPrefix + r.get(i);
}
const s = t[i];
if (s === null) {
return e;
}
if (n) {
return s.map(e => {
a.push(e);
return this.createParameter(i, a.length - 1);
}).join(", ");
}
if (s instanceof Function) {
return s();
}
a.push(s);
r.set(i, a.length - 1);
return this.createParameter(i, a.length - 1);
});
e = e.replace(/([ ]+)?=([ ]+)?:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, a, r, i) => {
if (!t.hasOwnProperty(i)) {
return e;
}
const s = t[i];
if (s === null) {
return " IS NULL";
}
return e;
});
return [ e, a ];
}
escape(e) {
return `\`${e}\``;
}
buildTableName(e, t, n) {
const a = [ e ];
if (n) {
a.unshift(n);
}
return a.join(".");
}
parseTableName(e) {
const t = this.database;
const n = undefined;
if (e instanceof aC.Table || e instanceof rC.View) {
const a = this.parseTableName(e.name);
return {
database: e.database || a.database || t,
schema: e.schema || a.schema || n,
tableName: a.tableName
};
}
if (e instanceof iC.TableForeignKey) {
const a = this.parseTableName(e.referencedTableName);
return {
database: e.referencedDatabase || a.database || t,
schema: e.referencedSchema || a.schema || n,
tableName: a.tableName
};
}
if (e instanceof eC.EntityMetadata) {
return {
database: e.database || t,
schema: e.schema || n,
tableName: e.tableName
};
}
const a = e.split(".");
return {
database: (a.length > 1 ? a[0] : undefined) || t,
schema: n,
tableName: a.length > 1 ? a[1] : a[0]
};
}
preparePersistentValue(e, t) {
if (t.transformer) e = nC.ApplyValueTransformers.transformTo(t.transformer, e);
if (e === null || e === undefined) return e;
if (t.type === "numeric") {
const t = this.options.driver || Xb.PlatformTools.load("spanner");
return t.Spanner.numeric(e.toString());
} else if (t.type === "date") {
return Jb.DateUtils.mixedDateToDateString(e);
} else if (t.type === "json") {
return e;
} else if (t.type === "timestamp" || t.type === Date) {
return Jb.DateUtils.mixedDateToDate(e);
}
return e;
}
prepareHydratedValue(e, t) {
if (e === null || e === undefined) return t.transformer ? nC.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
if (t.type === Boolean || t.type === "bool") {
e = e ? true : false;
} else if (t.type === "timestamp" || t.type === Date) {
e = new Date(e);
} else if (t.type === "numeric") {
e = e.value;
} else if (t.type === "date") {
e = Jb.DateUtils.mixedDateToDateString(e);
} else if (t.type === "json") {
e = typeof e === "string" ? JSON.parse(e) : e;
} else if (t.type === Number) {
e = !isNaN(+e) ? parseInt(e) : e;
}
if (t.transformer) e = nC.ApplyValueTransformers.transformFrom(t.transformer, e);
return e;
}
normalizeType(e) {
if (e.type === Number) {
return "int64";
} else if (e.type === String || e.type === "uuid") {
return "string";
} else if (e.type === Date) {
return "timestamp";
} else if (e.type === Buffer) {
return "bytes";
} else if (e.type === Boolean) {
return "bool";
} else {
return e.type || "";
}
}
normalizeDefault(e) {
return e.default === "" ? `"${e.default}"` : `${e.default}`;
}
normalizeIsUnique(e) {
return e.entityMetadata.indices.some(t => t.isUnique && t.columns.length === 1 && t.columns[0] === e);
}
getColumnLength(e) {
if (e.length) return e.length.toString();
if (e.generationStrategy === "uuid") return "36";
switch (e.type) {
case String:
case "string":
case "bytes":
return "max";
default:
return "";
}
}
createFullType(e) {
let t = e.type;
if (this.getColumnLength(e)) {
t += `(${this.getColumnLength(e)})`;
} else if (e.width) {
t += `(${e.width})`;
} else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
t += `(${e.precision},${e.scale})`;
} else if (e.precision !== null && e.precision !== undefined) {
t += `(${e.precision})`;
}
if (e.isArray) t = `array<${t}>`;
return t;
}
obtainMasterConnection() {
return this.instanceDatabase;
}
obtainSlaveConnection() {
return this.instanceDatabase;
}
createGeneratedMap(e, t, n) {
if (!t) {
return undefined;
}
if (t.insertId === undefined) {
return Object.keys(t).reduce((n, a) => {
const r = e.findColumnWithDatabaseName(a);
if (r) {
tC.OrmUtils.mergeDeep(n, r.createValueMap(t[a]));
}
return n;
}, {});
}
const a = e.generatedColumns.reduce((e, a) => {
let r;
if (a.generationStrategy === "increment" && t.insertId) {
r = t.insertId + n;
}
return tC.OrmUtils.mergeDeep(e, a.createValueMap(r));
}, {});
return Object.keys(a).length > 0 ? a : undefined;
}
findChangedColumns(e, t) {
return t.filter(t => {
const n = e.find(e => e.name === t.databaseName);
if (!n) return false;
const a = n.name !== t.databaseName || n.type !== this.normalizeType(t) || n.length !== this.getColumnLength(t) || n.asExpression !== t.asExpression || n.generatedType !== t.generatedType || n.isPrimary !== t.isPrimary || !this.compareNullableValues(t, n) || n.isUnique !== this.normalizeIsUnique(t);
return a;
});
}
isReturningSqlSupported() {
return true;
}
isUUIDGenerationSupported() {
return true;
}
isFullTextColumnTypeSupported() {
return false;
}
createParameter(e, t) {
return this.parametersPrefix + t;
}
loadDependencies() {
try {
const e = this.options.driver || Xb.PlatformTools.load("spanner");
this.spanner = new e.Spanner({
projectId: this.options.projectId
});
} catch (e) {
console.error(e);
throw new Yb.DriverPackageNotInstalledError("Spanner", "@google-cloud/spanner");
}
}
compareNullableValues(e, t) {
if (e.generatedType) {
return true;
}
return e.isNullable === t.isNullable;
}
compareDefaultValues(e, t) {
if (typeof e === "string" && typeof t === "string") {
e = e.replace(/^'+|'+$/g, "");
t = t.replace(/^'+|'+$/g, "");
}
return e === t;
}
normalizeDatetimeFunction(e) {
if (!e) return e;
const t = e.toUpperCase().indexOf("CURRENT_TIMESTAMP") !== -1 || e.toUpperCase().indexOf("NOW") !== -1;
if (t) {
const t = e.match(/\(\d+\)/);
return t ? `CURRENT_TIMESTAMP${t[0]}` : "CURRENT_TIMESTAMP";
} else {
return e;
}
}
escapeComment(e) {
if (!e) return e;
e = e.replace(/\u0000/g, "");
return e;
}
}
vb.SpannerDriver = SpannerDriver;
Object.defineProperty(xm, "__esModule", {
value: true
});
xm.DriverFactory = void 0;
const sC = ft();
const oC = qm;
const cC = Yf;
const lC = hy;
const uC = Gy;
const hC = wE;
const dC = oT;
const pC = gT;
const mC = _T;
const fC = VT;
const yC = ig;
const EC = Ug;
const TC = gN;
const gC = QN;
const NC = yA;
const AC = OA;
const bC = ob;
const CC = gb;
const RC = vb;
class DriverFactory {
create(e) {
const {type: t} = e.options;
switch (t) {
case "mysql":
return new yC.MysqlDriver(e);
case "postgres":
return new EC.PostgresDriver(e);
case "cockroachdb":
return new oC.CockroachDriver(e);
case "sap":
return new AC.SapDriver(e);
case "mariadb":
return new yC.MysqlDriver(e);
case "sqlite":
return new hC.SqliteDriver(e);
case "better-sqlite3":
return new bC.BetterSqlite3Driver(e);
case "cordova":
return new dC.CordovaDriver(e);
case "nativescript":
return new mC.NativescriptDriver(e);
case "react-native":
return new pC.ReactNativeDriver(e);
case "sqljs":
return new fC.SqljsDriver(e);
case "oracle":
return new uC.OracleDriver(e);
case "mssql":
return new lC.SqlServerDriver(e);
case "mongodb":
return new cC.MongoDriver(e);
case "expo":
return new TC.ExpoDriverFactory(e).create();
case "aurora-mysql":
return new gC.AuroraMysqlDriver(e);
case "aurora-postgres":
return new NC.AuroraPostgresDriver(e);
case "capacitor":
return new CC.CapacitorDriver(e);
case "spanner":
return new RC.SpannerDriver(e);
default:
throw new sC.MissingDriverError(t, [ "aurora-mysql", "aurora-postgres", "better-sqlite3", "capacitor", "cockroachdb", "cordova", "expo", "mariadb", "mongodb", "mssql", "mysql", "nativescript", "oracle", "postgres", "react-native", "sap", "sqlite", "sqljs", "spanner" ]);
}
}
}
xm.DriverFactory = DriverFactory;
var SC = {};
var wC = {};
var MC = {};
var OC = {};
var vC;
var IC;
function PC() {
if (IC) return vC;
IC = 1;
vC = e;
function e(e, a, r) {
if (e instanceof RegExp) e = t(e, r);
if (a instanceof RegExp) a = t(a, r);
var i = n(e, a, r);
return i && {
start: i[0],
end: i[1],
pre: r.slice(0, i[0]),
body: r.slice(i[0] + e.length, i[1]),
post: r.slice(i[1] + a.length)
};
}
function t(e, t) {
var n = t.match(e);
return n ? n[0] : null;
}
e.range = n;
function n(e, t, n) {
var a, r, i, s, o;
var c = n.indexOf(e);
var l = n.indexOf(t, c + 1);
var u = c;
if (c >= 0 && l > 0) {
if (e === t) {
return [ c, l ];
}
a = [];
i = n.length;
while (u >= 0 && !o) {
if (u == c) {
a.push(u);
c = n.indexOf(e, u + 1);
} else if (a.length == 1) {
o = [ a.pop(), l ];
} else {
r = a.pop();
if (r < i) {
i = r;
s = l;
}
l = n.indexOf(t, u + 1);
}
u = c < l && c >= 0 ? c : l;
}
if (a.length) {
o = [ i, s ];
}
}
return o;
}
return vC;
}
var LC;
var DC;
function _C() {
if (DC) return LC;
DC = 1;
var e = PC();
LC = u;
var t = "\0SLASH" + Math.random() + "\0";
var n = "\0OPEN" + Math.random() + "\0";
var a = "\0CLOSE" + Math.random() + "\0";
var r = "\0COMMA" + Math.random() + "\0";
var i = "\0PERIOD" + Math.random() + "\0";
function s(e) {
return parseInt(e, 10) == e ? parseInt(e, 10) : e.charCodeAt(0);
}
function o(e) {
return e.split("\\\\").join(t).split("\\{").join(n).split("\\}").join(a).split("\\,").join(r).split("\\.").join(i);
}
function c(e) {
return e.split(t).join("\\").split(n).join("{").split(a).join("}").split(r).join(",").split(i).join(".");
}
function l(t) {
if (!t) return [ "" ];
var n = [];
var a = e("{", "}", t);
if (!a) return t.split(",");
var r = a.pre;
var i = a.body;
var s = a.post;
var o = r.split(",");
o[o.length - 1] += "{" + i + "}";
var c = l(s);
if (s.length) {
o[o.length - 1] += c.shift();
o.push.apply(o, c);
}
n.push.apply(n, o);
return n;
}
function u(e) {
if (!e) return [];
if (e.substr(0, 2) === "{}") {
e = "\\{\\}" + e.substr(2);
}
return f(o(e), true).map(c);
}
function h(e) {
return "{" + e + "}";
}
function d(e) {
return /^-?0\d/.test(e);
}
function p(e, t) {
return e <= t;
}
function m(e, t) {
return e >= t;
}
function f(t, n) {
var r = [];
var i = e("{", "}", t);
if (!i) return [ t ];
var o = i.pre;
var c = i.post.length ? f(i.post, false) : [ "" ];
if (/\$$/.test(i.pre)) {
for (var u = 0; u < c.length; u++) {
var y = o + "{" + i.body + "}" + c[u];
r.push(y);
}
} else {
var E = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body);
var T = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body);
var g = E || T;
var N = i.body.indexOf(",") >= 0;
if (!g && !N) {
if (i.post.match(/,(?!,).*\}/)) {
t = i.pre + "{" + i.body + a + i.post;
return f(t);
}
return [ t ];
}
var A;
if (g) {
A = i.body.split(/\.\./);
} else {
A = l(i.body);
if (A.length === 1) {
A = f(A[0], false).map(h);
if (A.length === 1) {
return c.map(function(e) {
return i.pre + A[0] + e;
});
}
}
}
var b;
if (g) {
var C = s(A[0]);
var R = s(A[1]);
var S = Math.max(A[0].length, A[1].length);
var w = A.length == 3 ? Math.abs(s(A[2])) : 1;
var M = p;
var O = R < C;
if (O) {
w *= -1;
M = m;
}
var v = A.some(d);
b = [];
for (var I = C; M(I, R); I += w) {
var P;
if (T) {
P = String.fromCharCode(I);
if (P === "\\") P = "";
} else {
P = String(I);
if (v) {
var L = S - P.length;
if (L > 0) {
var D = new Array(L + 1).join("0");
if (I < 0) P = "-" + D + P.slice(1); else P = D + P;
}
}
}
b.push(P);
}
} else {
b = [];
for (var _ = 0; _ < A.length; _++) {
b.push.apply(b, f(A[_], false));
}
}
for (var _ = 0; _ < b.length; _++) {
for (var u = 0; u < c.length; u++) {
var y = o + b[_] + c[u];
if (!n || g || y) r.push(y);
}
}
}
return r;
}
return LC;
}
var $C = {};
var xC;
function qC() {
if (xC) return $C;
xC = 1;
Object.defineProperty($C, "__esModule", {
value: true
});
$C.assertValidPattern = void 0;
const e = 1024 * 64;
const t = t => {
if (typeof t !== "string") {
throw new TypeError("invalid pattern");
}
if (t.length > e) {
throw new TypeError("pattern is too long");
}
};
$C.assertValidPattern = t;
return $C;
}
var UC = {};
var BC = {};
var FC;
function jC() {
if (FC) return BC;
FC = 1;
Object.defineProperty(BC, "__esModule", {
value: true
});
BC.parseClass = void 0;
const e = {
"[:alnum:]": [ "\\p{L}\\p{Nl}\\p{Nd}", true ],
"[:alpha:]": [ "\\p{L}\\p{Nl}", true ],
"[:ascii:]": [ "\\x" + "00-\\x" + "7f", false ],
"[:blank:]": [ "\\p{Zs}\\t", true ],
"[:cntrl:]": [ "\\p{Cc}", true ],
"[:digit:]": [ "\\p{Nd}", true ],
"[:graph:]": [ "\\p{Z}\\p{C}", true, true ],
"[:lower:]": [ "\\p{Ll}", true ],
"[:print:]": [ "\\p{C}", true ],
"[:punct:]": [ "\\p{P}", true ],
"[:space:]": [ "\\p{Z}\\t\\r\\n\\v\\f", true ],
"[:upper:]": [ "\\p{Lu}", true ],
"[:word:]": [ "\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true ],
"[:xdigit:]": [ "A-Fa-f0-9", false ]
};
const t = e => e.replace(/[[\]\\-]/g, "\\$&");
const n = e => e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
const a = e => e.join("");
const r = (r, i) => {
const s = i;
if (r.charAt(s) !== "[") {
throw new Error("not in a brace expression");
}
const o = [];
const c = [];
let l = s + 1;
let u = false;
let h = false;
let d = false;
let p = false;
let m = s;
let f = "";
e: while (l < r.length) {
const n = r.charAt(l);
if ((n === "!" || n === "^") && l === s + 1) {
p = true;
l++;
continue;
}
if (n === "]" && u && !d) {
m = l + 1;
break;
}
u = true;
if (n === "\\") {
if (!d) {
d = true;
l++;
continue;
}
}
if (n === "[" && !d) {
for (const [t, [n, a, i]] of Object.entries(e)) {
if (r.startsWith(t, l)) {
if (f) {
return [ "$.", false, r.length - s, true ];
}
l += t.length;
if (i) c.push(n); else o.push(n);
h = h || a;
continue e;
}
}
}
d = false;
if (f) {
if (n > f) {
o.push(t(f) + "-" + t(n));
} else if (n === f) {
o.push(t(n));
}
f = "";
l++;
continue;
}
if (r.startsWith("-]", l + 1)) {
o.push(t(n + "-"));
l += 2;
continue;
}
if (r.startsWith("-", l + 1)) {
f = n;
l += 2;
continue;
}
o.push(t(n));
l++;
}
if (m < l) {
return [ "", false, 0, false ];
}
if (!o.length && !c.length) {
return [ "$.", false, r.length - s, true ];
}
if (c.length === 0 && o.length === 1 && /^\\?.$/.test(o[0]) && !p) {
const e = o[0].length === 2 ? o[0].slice(-1) : o[0];
return [ n(e), false, m - s, false ];
}
const y = "[" + (p ? "^" : "") + a(o) + "]";
const E = "[" + (p ? "" : "^") + a(c) + "]";
const T = o.length && c.length ? "(" + y + "|" + E + ")" : o.length ? y : E;
return [ T, h, m - s, true ];
};
BC.parseClass = r;
return BC;
}
var kC = {};
var QC;
function VC() {
if (QC) return kC;
QC = 1;
Object.defineProperty(kC, "__esModule", {
value: true
});
kC.unescape = void 0;
const e = (e, {windowsPathsNoEscape: t = false} = {}) => t ? e.replace(/\[([^\/\\])\]/g, "$1") : e.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
kC.unescape = e;
return kC;
}
var KC;
function WC() {
if (KC) return UC;
KC = 1;
Object.defineProperty(UC, "__esModule", {
value: true
});
UC.AST = void 0;
const e = jC();
const t = VC();
const n = new Set([ "!", "?", "+", "*", "@" ]);
const a = e => n.has(e);
const r = "(?!(?:^|/)\\.\\.?(?:$|/))";
const i = "(?!\\.)";
const s = new Set([ "[", "." ]);
const o = new Set([ "..", "." ]);
const c = new Set("().*{}+?[]^$\\!");
const l = e => e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
const u = "[^/]";
const h = u + "*?";
const d = u + "+?";
class AST {
type;
#e;
#t;
#n=false;
#a=[];
#r;
#i;
#s;
#o=false;
#c;
#l;
#u=false;
constructor(e, t, n = {}) {
this.type = e;
if (e) this.#t = true;
this.#r = t;
this.#e = this.#r ? this.#r.#e : this;
this.#c = this.#e === this ? n : this.#e.#c;
this.#s = this.#e === this ? [] : this.#e.#s;
if (e === "!" && !this.#e.#o) this.#s.push(this);
this.#i = this.#r ? this.#r.#a.length : 0;
}
get hasMagic() {
if (this.#t !== undefined) return this.#t;
for (const e of this.#a) {
if (typeof e === "string") continue;
if (e.type || e.hasMagic) return this.#t = true;
}
return this.#t;
}
toString() {
if (this.#l !== undefined) return this.#l;
if (!this.type) {
return this.#l = this.#a.map(e => String(e)).join("");
} else {
return this.#l = this.type + "(" + this.#a.map(e => String(e)).join("|") + ")";
}
}
#h() {
if (this !== this.#e) throw new Error("should only call on root");
if (this.#o) return this;
this.toString();
this.#o = true;
let e;
while (e = this.#s.pop()) {
if (e.type !== "!") continue;
let t = e;
let n = t.#r;
while (n) {
for (let a = t.#i + 1; !n.type && a < n.#a.length; a++) {
for (const t of e.#a) {
if (typeof t === "string") {
throw new Error("string part in extglob AST??");
}
t.copyIn(n.#a[a]);
}
}
t = n;
n = t.#r;
}
}
return this;
}
push(...e) {
for (const t of e) {
if (t === "") continue;
if (typeof t !== "string" && !(t instanceof AST && t.#r === this)) {
throw new Error("invalid part: " + t);
}
this.#a.push(t);
}
}
toJSON() {
const e = this.type === null ? this.#a.slice().map(e => typeof e === "string" ? e : e.toJSON()) : [ this.type, ...this.#a.map(e => e.toJSON()) ];
if (this.isStart() && !this.type) e.unshift([]);
if (this.isEnd() && (this === this.#e || this.#e.#o && this.#r?.type === "!")) {
e.push({});
}
return e;
}
isStart() {
if (this.#e === this) return true;
if (!this.#r?.isStart()) return false;
if (this.#i === 0) return true;
const e = this.#r;
for (let t = 0; t < this.#i; t++) {
const n = e.#a[t];
if (!(n instanceof AST && n.type === "!")) {
return false;
}
}
return true;
}
isEnd() {
if (this.#e === this) return true;
if (this.#r?.type === "!") return true;
if (!this.#r?.isEnd()) return false;
if (!this.type) return this.#r?.isEnd();
const e = this.#r ? this.#r.#a.length : 0;
return this.#i === e - 1;
}
copyIn(e) {
if (typeof e === "string") this.push(e); else this.push(e.clone(this));
}
clone(e) {
const t = new AST(this.type, e);
for (const e of this.#a) {
t.copyIn(e);
}
return t;
}
static #d(e, t, n, r) {
let i = false;
let s = false;
let o = -1;
let c = false;
if (t.type === null) {
let l = n;
let u = "";
while (l < e.length) {
const n = e.charAt(l++);
if (i || n === "\\") {
i = !i;
u += n;
continue;
}
if (s) {
if (l === o + 1) {
if (n === "^" || n === "!") {
c = true;
}
} else if (n === "]" && !(l === o + 2 && c)) {
s = false;
}
u += n;
continue;
} else if (n === "[") {
s = true;
o = l;
c = false;
u += n;
continue;
}
if (!r.noext && a(n) && e.charAt(l) === "(") {
t.push(u);
u = "";
const a = new AST(n, t);
l = AST.#d(e, a, l, r);
t.push(a);
continue;
}
u += n;
}
t.push(u);
return l;
}
let l = n + 1;
let u = new AST(null, t);
const h = [];
let d = "";
while (l < e.length) {
const n = e.charAt(l++);
if (i || n === "\\") {
i = !i;
d += n;
continue;
}
if (s) {
if (l === o + 1) {
if (n === "^" || n === "!") {
c = true;
}
} else if (n === "]" && !(l === o + 2 && c)) {
s = false;
}
d += n;
continue;
} else if (n === "[") {
s = true;
o = l;
c = false;
d += n;
continue;
}
if (a(n) && e.charAt(l) === "(") {
u.push(d);
d = "";
const t = new AST(n, u);
u.push(t);
l = AST.#d(e, t, l, r);
continue;
}
if (n === "|") {
u.push(d);
d = "";
h.push(u);
u = new AST(null, t);
continue;
}
if (n === ")") {
if (d === "" && t.#a.length === 0) {
t.#u = true;
}
u.push(d);
d = "";
t.push(...h, u);
return l;
}
d += n;
}
t.type = null;
t.#t = undefined;
t.#a = [ e.substring(n - 1) ];
return l;
}
static fromGlob(e, t = {}) {
const n = new AST(null, undefined, t);
AST.#d(e, n, 0, t);
return n;
}
toMMPattern() {
if (this !== this.#e) return this.#e.toMMPattern();
const e = this.toString();
const [t, n, a, r] = this.toRegExpSource();
const i = a || this.#t || this.#c.nocase && !this.#c.nocaseMagicOnly && e.toUpperCase() !== e.toLowerCase();
if (!i) {
return n;
}
const s = (this.#c.nocase ? "i" : "") + (r ? "u" : "");
return Object.assign(new RegExp(`^${t}$`, s), {
_src: t,
_glob: e
});
}
get options() {
return this.#c;
}
toRegExpSource(e) {
const n = e ?? !!this.#c.dot;
if (this.#e === this) this.#h();
if (!this.type) {
const a = this.isStart() && this.isEnd();
const c = this.#a.map(t => {
const [n, r, i, s] = typeof t === "string" ? AST.#p(t, this.#t, a) : t.toRegExpSource(e);
this.#t = this.#t || i;
this.#n = this.#n || s;
return n;
}).join("");
let l = "";
if (this.isStart()) {
if (typeof this.#a[0] === "string") {
const t = this.#a.length === 1 && o.has(this.#a[0]);
if (!t) {
const t = s;
const a = n && t.has(c.charAt(0)) || c.startsWith("\\.") && t.has(c.charAt(2)) || c.startsWith("\\.\\.") && t.has(c.charAt(4));
const o = !n && !e && t.has(c.charAt(0));
l = a ? r : o ? i : "";
}
}
}
let u = "";
if (this.isEnd() && this.#e.#o && this.#r?.type === "!") {
u = "(?:$|\\/)";
}
const h = l + c + u;
return [ h, (0, t.unescape)(c), this.#t = !!this.#t, this.#n ];
}
const a = this.type === "*" || this.type === "+";
const c = this.type === "!" ? "(?:(?!(?:" : "(?:";
let l = this.#m(n);
if (this.isStart() && this.isEnd() && !l && this.type !== "!") {
const e = this.toString();
this.#a = [ e ];
this.type = null;
this.#t = undefined;
return [ e, (0, t.unescape)(this.toString()), false, false ];
}
let u = !a || e || n || !i ? "" : this.#m(true);
if (u === l) {
u = "";
}
if (u) {
l = `(?:${l})(?:${u})*?`;
}
let p = "";
if (this.type === "!" && this.#u) {
p = (this.isStart() && !n ? i : "") + d;
} else {
const t = this.type === "!" ? "))" + (this.isStart() && !n && !e ? i : "") + h + ")" : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && u ? ")" : this.type === "*" && u ? `)?` : `)${this.type}`;
p = c + l + t;
}
return [ p, (0, t.unescape)(l), this.#t = !!this.#t, this.#n ];
}
#m(e) {
return this.#a.map(t => {
if (typeof t === "string") {
throw new Error("string type in extglob ast??");
}
const [n, a, r, i] = t.toRegExpSource(e);
this.#n = this.#n || i;
return n;
}).filter(e => !(this.isStart() && this.isEnd()) || !!e).join("|");
}
static #p(n, a, r = false) {
let i = false;
let s = "";
let o = false;
for (let t = 0; t < n.length; t++) {
const p = n.charAt(t);
if (i) {
i = false;
s += (c.has(p) ? "\\" : "") + p;
continue;
}
if (p === "\\") {
if (t === n.length - 1) {
s += "\\\\";
} else {
i = true;
}
continue;
}
if (p === "[") {
const [r, i, c, l] = (0, e.parseClass)(n, t);
if (c) {
s += r;
o = o || i;
t += c - 1;
a = a || l;
continue;
}
}
if (p === "*") {
if (r && n === "*") s += d; else s += h;
a = true;
continue;
}
if (p === "?") {
s += u;
a = true;
continue;
}
s += l(p);
}
return [ s, (0, t.unescape)(n), !!a, o ];
}
}
UC.AST = AST;
return UC;
}
var HC = {};
var GC;
function YC() {
if (GC) return HC;
GC = 1;
Object.defineProperty(HC, "__esModule", {
value: true
});
HC.escape = void 0;
const e = (e, {windowsPathsNoEscape: t = false} = {}) => t ? e.replace(/[?*()[\]]/g, "[$&]") : e.replace(/[?*()[\]\\]/g, "\\$&");
HC.escape = e;
return HC;
}
var zC;
function JC() {
if (zC) return OC;
zC = 1;
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
Object.defineProperty(e, "__esModule", {
value: true
});
e.unescape = e.escape = e.AST = e.Minimatch = e.match = e.makeRe = e.braceExpand = e.defaults = e.filter = e.GLOBSTAR = e.sep = e.minimatch = void 0;
const n = t(_C());
const a = qC();
const i = WC();
const s = YC();
const o = VC();
const c = (e, t, n = {}) => {
(0, a.assertValidPattern)(t);
if (!n.nocomment && t.charAt(0) === "#") {
return false;
}
return new Minimatch(t, n).match(e);
};
e.minimatch = c;
const l = /^\*+([^+@!?\*\[\(]*)$/;
const u = e => t => !t.startsWith(".") && t.endsWith(e);
const h = e => t => t.endsWith(e);
const d = e => {
e = e.toLowerCase();
return t => !t.startsWith(".") && t.toLowerCase().endsWith(e);
};
const p = e => {
e = e.toLowerCase();
return t => t.toLowerCase().endsWith(e);
};
const m = /^\*+\.\*+$/;
const f = e => !e.startsWith(".") && e.includes(".");
const y = e => e !== "." && e !== ".." && e.includes(".");
const E = /^\.\*+$/;
const T = e => e !== "." && e !== ".." && e.startsWith(".");
const g = /^\*+$/;
const N = e => e.length !== 0 && !e.startsWith(".");
const A = e => e.length !== 0 && e !== "." && e !== "..";
const b = /^\?+([^+@!?\*\[\(]*)?$/;
const C = ([e, t = ""]) => {
const n = M([ e ]);
if (!t) return n;
t = t.toLowerCase();
return e => n(e) && e.toLowerCase().endsWith(t);
};
const R = ([e, t = ""]) => {
const n = O([ e ]);
if (!t) return n;
t = t.toLowerCase();
return e => n(e) && e.toLowerCase().endsWith(t);
};
const S = ([e, t = ""]) => {
const n = O([ e ]);
return !t ? n : e => n(e) && e.endsWith(t);
};
const w = ([e, t = ""]) => {
const n = M([ e ]);
return !t ? n : e => n(e) && e.endsWith(t);
};
const M = ([e]) => {
const t = e.length;
return e => e.length === t && !e.startsWith(".");
};
const O = ([e]) => {
const t = e.length;
return e => e.length === t && e !== "." && e !== "..";
};
const v = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
const I = {
win32: {
sep: "\\"
},
posix: {
sep: "/"
}
};
e.sep = v === "win32" ? I.win32.sep : I.posix.sep;
e.minimatch.sep = e.sep;
e.GLOBSTAR = Symbol("globstar **");
e.minimatch.GLOBSTAR = e.GLOBSTAR;
const P = "[^/]";
const L = P + "*?";
const D = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
const _ = "(?:(?!(?:\\/|^)\\.).)*?";
const $ = (t, n = {}) => a => (0, e.minimatch)(a, t, n);
e.filter = $;
e.minimatch.filter = e.filter;
const x = (e, t = {}) => Object.assign({}, e, t);
const q = t => {
if (!t || typeof t !== "object" || !Object.keys(t).length) {
return e.minimatch;
}
const n = e.minimatch;
const a = (e, a, r = {}) => n(e, a, x(t, r));
return Object.assign(a, {
Minimatch: class Minimatch extends n.Minimatch {
constructor(e, n = {}) {
super(e, x(t, n));
}
static defaults(e) {
return n.defaults(x(t, e)).Minimatch;
}
},
AST: class AST extends n.AST {
constructor(e, n, a = {}) {
super(e, n, x(t, a));
}
static fromGlob(e, a = {}) {
return n.AST.fromGlob(e, x(t, a));
}
},
unescape: (e, a = {}) => n.unescape(e, x(t, a)),
escape: (e, a = {}) => n.escape(e, x(t, a)),
filter: (e, a = {}) => n.filter(e, x(t, a)),
defaults: e => n.defaults(x(t, e)),
makeRe: (e, a = {}) => n.makeRe(e, x(t, a)),
braceExpand: (e, a = {}) => n.braceExpand(e, x(t, a)),
match: (e, a, r = {}) => n.match(e, a, x(t, r)),
sep: n.sep,
GLOBSTAR: e.GLOBSTAR
});
};
e.defaults = q;
e.minimatch.defaults = e.defaults;
const U = (e, t = {}) => {
(0, a.assertValidPattern)(e);
if (t.nobrace || !/\{(?:(?!\{).)*\}/.test(e)) {
return [ e ];
}
return (0, n.default)(e);
};
e.braceExpand = U;
e.minimatch.braceExpand = e.braceExpand;
const B = (e, t = {}) => new Minimatch(e, t).makeRe();
e.makeRe = B;
e.minimatch.makeRe = e.makeRe;
const F = (e, t, n = {}) => {
const a = new Minimatch(t, n);
e = e.filter(e => a.match(e));
if (a.options.nonull && !e.length) {
e.push(t);
}
return e;
};
e.match = F;
e.minimatch.match = e.match;
const j = /[?*]|[+@!]\(.*?\)|\[|\]/;
const k = e => e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
class Minimatch {
options;
set;
pattern;
windowsPathsNoEscape;
nonegate;
negate;
comment;
empty;
preserveMultipleSlashes;
partial;
globSet;
globParts;
nocase;
isWindows;
platform;
windowsNoMagicRoot;
regexp;
constructor(e, t = {}) {
(0, a.assertValidPattern)(e);
t = t || {};
this.options = t;
this.pattern = e;
this.platform = t.platform || v;
this.isWindows = this.platform === "win32";
this.windowsPathsNoEscape = !!t.windowsPathsNoEscape || t.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, "/");
}
this.preserveMultipleSlashes = !!t.preserveMultipleSlashes;
this.regexp = null;
this.negate = false;
this.nonegate = !!t.nonegate;
this.comment = false;
this.empty = false;
this.partial = !!t.partial;
this.nocase = !!this.options.nocase;
this.windowsNoMagicRoot = t.windowsNoMagicRoot !== undefined ? t.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
this.globSet = [];
this.globParts = [];
this.set = [];
this.make();
}
hasMagic() {
if (this.options.magicalBraces && this.set.length > 1) {
return true;
}
for (const e of this.set) {
for (const t of e) {
if (typeof t !== "string") return true;
}
}
return false;
}
debug(...e) {}
make() {
const e = this.pattern;
const t = this.options;
if (!t.nocomment && e.charAt(0) === "#") {
this.comment = true;
return;
}
if (!e) {
this.empty = true;
return;
}
this.parseNegate();
this.globSet = [ ...new Set(this.braceExpand()) ];
if (t.debug) {
this.debug = (...e) => console.error(...e);
}
this.debug(this.pattern, this.globSet);
const n = this.globSet.map(e => this.slashSplit(e));
this.globParts = this.preprocess(n);
this.debug(this.pattern, this.globParts);
let a = this.globParts.map((e, t, n) => {
if (this.isWindows && this.windowsNoMagicRoot) {
const t = e[0] === "" && e[1] === "" && (e[2] === "?" || !j.test(e[2])) && !j.test(e[3]);
const n = /^[a-z]:/i.test(e[0]);
if (t) {
return [ ...e.slice(0, 4), ...e.slice(4).map(e => this.parse(e)) ];
} else if (n) {
return [ e[0], ...e.slice(1).map(e => this.parse(e)) ];
}
}
return e.map(e => this.parse(e));
});
this.debug(this.pattern, a);
this.set = a.filter(e => e.indexOf(false) === -1);
if (this.isWindows) {
for (let e = 0; e < this.set.length; e++) {
const t = this.set[e];
if (t[0] === "" && t[1] === "" && this.globParts[e][2] === "?" && typeof t[3] === "string" && /^[a-z]:$/i.test(t[3])) {
t[2] = "?";
}
}
}
this.debug(this.pattern, this.set);
}
preprocess(e) {
if (this.options.noglobstar) {
for (let t = 0; t < e.length; t++) {
for (let n = 0; n < e[t].length; n++) {
if (e[t][n] === "**") {
e[t][n] = "*";
}
}
}
}
const {optimizationLevel: t = 1} = this.options;
if (t >= 2) {
e = this.firstPhasePreProcess(e);
e = this.secondPhasePreProcess(e);
} else if (t >= 1) {
e = this.levelOneOptimize(e);
} else {
e = this.adjascentGlobstarOptimize(e);
}
return e;
}
adjascentGlobstarOptimize(e) {
return e.map(e => {
let t = -1;
while (-1 !== (t = e.indexOf("**", t + 1))) {
let n = t;
while (e[n + 1] === "**") {
n++;
}
if (n !== t) {
e.splice(t, n - t);
}
}
return e;
});
}
levelOneOptimize(e) {
return e.map(e => {
e = e.reduce((e, t) => {
const n = e[e.length - 1];
if (t === "**" && n === "**") {
return e;
}
if (t === "..") {
if (n && n !== ".." && n !== "." && n !== "**") {
e.pop();
return e;
}
}
e.push(t);
return e;
}, []);
return e.length === 0 ? [ "" ] : e;
});
}
levelTwoFileOptimize(e) {
if (!Array.isArray(e)) {
e = this.slashSplit(e);
}
let t = false;
do {
t = false;
if (!this.preserveMultipleSlashes) {
for (let n = 1; n < e.length - 1; n++) {
const a = e[n];
if (n === 1 && a === "" && e[0] === "") continue;
if (a === "." || a === "") {
t = true;
e.splice(n, 1);
n--;
}
}
if (e[0] === "." && e.length === 2 && (e[1] === "." || e[1] === "")) {
t = true;
e.pop();
}
}
let n = 0;
while (-1 !== (n = e.indexOf("..", n + 1))) {
const a = e[n - 1];
if (a && a !== "." && a !== ".." && a !== "**") {
t = true;
e.splice(n - 1, 2);
n -= 2;
}
}
} while (t);
return e.length === 0 ? [ "" ] : e;
}
firstPhasePreProcess(e) {
let t = false;
do {
t = false;
for (let n of e) {
let a = -1;
while (-1 !== (a = n.indexOf("**", a + 1))) {
let r = a;
while (n[r + 1] === "**") {
r++;
}
if (r > a) {
n.splice(a + 1, r - a);
}
let i = n[a + 1];
const s = n[a + 2];
const o = n[a + 3];
if (i !== "..") continue;
if (!s || s === "." || s === ".." || !o || o === "." || o === "..") {
continue;
}
t = true;
n.splice(a, 1);
const c = n.slice(0);
c[a] = "**";
e.push(c);
a--;
}
if (!this.preserveMultipleSlashes) {
for (let e = 1; e < n.length - 1; e++) {
const a = n[e];
if (e === 1 && a === "" && n[0] === "") continue;
if (a === "." || a === "") {
t = true;
n.splice(e, 1);
e--;
}
}
if (n[0] === "." && n.length === 2 && (n[1] === "." || n[1] === "")) {
t = true;
n.pop();
}
}
let r = 0;
while (-1 !== (r = n.indexOf("..", r + 1))) {
const e = n[r - 1];
if (e && e !== "." && e !== ".." && e !== "**") {
t = true;
const e = r === 1 && n[r + 1] === "**";
const a = e ? [ "." ] : [];
n.splice(r - 1, 2, ...a);
if (n.length === 0) n.push("");
r -= 2;
}
}
}
} while (t);
return e;
}
secondPhasePreProcess(e) {
for (let t = 0; t < e.length - 1; t++) {
for (let n = t + 1; n < e.length; n++) {
const a = this.partsMatch(e[t], e[n], !this.preserveMultipleSlashes);
if (a) {
e[t] = [];
e[n] = a;
break;
}
}
}
return e.filter(e => e.length);
}
partsMatch(e, t, n = false) {
let a = 0;
let r = 0;
let i = [];
let s = "";
while (a < e.length && r < t.length) {
if (e[a] === t[r]) {
i.push(s === "b" ? t[r] : e[a]);
a++;
r++;
} else if (n && e[a] === "**" && t[r] === e[a + 1]) {
i.push(e[a]);
a++;
} else if (n && t[r] === "**" && e[a] === t[r + 1]) {
i.push(t[r]);
r++;
} else if (e[a] === "*" && t[r] && (this.options.dot || !t[r].startsWith(".")) && t[r] !== "**") {
if (s === "b") return false;
s = "a";
i.push(e[a]);
a++;
r++;
} else if (t[r] === "*" && e[a] && (this.options.dot || !e[a].startsWith(".")) && e[a] !== "**") {
if (s === "a") return false;
s = "b";
i.push(t[r]);
a++;
r++;
} else {
return false;
}
}
return e.length === t.length && i;
}
parseNegate() {
if (this.nonegate) return;
const e = this.pattern;
let t = false;
let n = 0;
for (let a = 0; a < e.length && e.charAt(a) === "!"; a++) {
t = !t;
n++;
}
if (n) this.pattern = e.slice(n);
this.negate = t;
}
matchOne(t, n, a = false) {
const r = this.options;
if (this.isWindows) {
const e = typeof t[0] === "string" && /^[a-z]:$/i.test(t[0]);
const a = !e && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]);
const r = typeof n[0] === "string" && /^[a-z]:$/i.test(n[0]);
const i = !r && n[0] === "" && n[1] === "" && n[2] === "?" && typeof n[3] === "string" && /^[a-z]:$/i.test(n[3]);
const s = a ? 3 : e ? 0 : undefined;
const o = i ? 3 : r ? 0 : undefined;
if (typeof s === "number" && typeof o === "number") {
const [e, a] = [ t[s], n[o] ];
if (e.toLowerCase() === a.toLowerCase()) {
n[o] = e;
if (o > s) {
n = n.slice(o);
} else if (s > o) {
t = t.slice(s);
}
}
}
}
const {optimizationLevel: i = 1} = this.options;
if (i >= 2) {
t = this.levelTwoFileOptimize(t);
}
this.debug("matchOne", this, {
file: t,
pattern: n
});
this.debug("matchOne", t.length, n.length);
for (var s = 0, o = 0, c = t.length, l = n.length; s < c && o < l; s++, o++) {
this.debug("matchOne loop");
var u = n[o];
var h = t[s];
this.debug(n, u, h);
if (u === false) {
return false;
}
if (u === e.GLOBSTAR) {
this.debug("GLOBSTAR", [ n, u, h ]);
var d = s;
var p = o + 1;
if (p === l) {
this.debug("** at the end");
for (;s < c; s++) {
if (t[s] === "." || t[s] === ".." || !r.dot && t[s].charAt(0) === ".") return false;
}
return true;
}
while (d < c) {
var m = t[d];
this.debug("\nglobstar while", t, d, n, p, m);
if (this.matchOne(t.slice(d), n.slice(p), a)) {
this.debug("globstar found match!", d, c, m);
return true;
} else {
if (m === "." || m === ".." || !r.dot && m.charAt(0) === ".") {
this.debug("dot detected!", t, d, n, p);
break;
}
this.debug("globstar swallow a segment, and continue");
d++;
}
}
if (a) {
this.debug("\n>>> no match, partial?", t, d, n, p);
if (d === c) {
return true;
}
}
return false;
}
let i;
if (typeof u === "string") {
i = h === u;
this.debug("string match", u, h, i);
} else {
i = u.test(h);
this.debug("pattern match", u, h, i);
}
if (!i) return false;
}
if (s === c && o === l) {
return true;
} else if (s === c) {
return a;
} else if (o === l) {
return s === c - 1 && t[s] === "";
} else {
throw new Error("wtf?");
}
}
braceExpand() {
return (0, e.braceExpand)(this.pattern, this.options);
}
parse(t) {
(0, a.assertValidPattern)(t);
const n = this.options;
if (t === "**") return e.GLOBSTAR;
if (t === "") return "";
let r;
let s = null;
if (r = t.match(g)) {
s = n.dot ? A : N;
} else if (r = t.match(l)) {
s = (n.nocase ? n.dot ? p : d : n.dot ? h : u)(r[1]);
} else if (r = t.match(b)) {
s = (n.nocase ? n.dot ? R : C : n.dot ? S : w)(r);
} else if (r = t.match(m)) {
s = n.dot ? y : f;
} else if (r = t.match(E)) {
s = T;
}
const o = i.AST.fromGlob(t, this.options).toMMPattern();
if (s && typeof o === "object") {
Reflect.defineProperty(o, "test", {
value: s
});
}
return o;
}
makeRe() {
if (this.regexp || this.regexp === false) return this.regexp;
const t = this.set;
if (!t.length) {
this.regexp = false;
return this.regexp;
}
const n = this.options;
const a = n.noglobstar ? L : n.dot ? D : _;
const r = new Set(n.nocase ? [ "i" ] : []);
let i = t.map(t => {
const n = t.map(t => {
if (t instanceof RegExp) {
for (const e of t.flags.split("")) r.add(e);
}
return typeof t === "string" ? k(t) : t === e.GLOBSTAR ? e.GLOBSTAR : t._src;
});
n.forEach((t, r) => {
const i = n[r + 1];
const s = n[r - 1];
if (t !== e.GLOBSTAR || s === e.GLOBSTAR) {
return;
}
if (s === undefined) {
if (i !== undefined && i !== e.GLOBSTAR) {
n[r + 1] = "(?:\\/|" + a + "\\/)?" + i;
} else {
n[r] = a;
}
} else if (i === undefined) {
n[r - 1] = s + "(?:\\/|" + a + ")?";
} else if (i !== e.GLOBSTAR) {
n[r - 1] = s + "(?:\\/|\\/" + a + "\\/)" + i;
n[r + 1] = e.GLOBSTAR;
}
});
return n.filter(t => t !== e.GLOBSTAR).join("/");
}).join("|");
const [s, o] = t.length > 1 ? [ "(?:", ")" ] : [ "", "" ];
i = "^" + s + i + o + "$";
if (this.negate) i = "^(?!" + i + ").+$";
try {
this.regexp = new RegExp(i, [ ...r ].join(""));
} catch (e) {
this.regexp = false;
}
return this.regexp;
}
slashSplit(e) {
if (this.preserveMultipleSlashes) {
return e.split("/");
} else if (this.isWindows && /^\/\/[^\/]+/.test(e)) {
return [ "", ...e.split(/\/+/) ];
} else {
return e.split(/\/+/);
}
}
match(e, t = this.partial) {
this.debug("match", e, this.pattern);
if (this.comment) {
return false;
}
if (this.empty) {
return e === "";
}
if (e === "/" && t) {
return true;
}
const n = this.options;
if (this.isWindows) {
e = e.split("\\").join("/");
}
const a = this.slashSplit(e);
this.debug(this.pattern, "split", a);
const r = this.set;
this.debug(this.pattern, "set", r);
let i = a[a.length - 1];
if (!i) {
for (let e = a.length - 2; !i && e >= 0; e--) {
i = a[e];
}
}
for (let e = 0; e < r.length; e++) {
const s = r[e];
let o = a;
if (n.matchBase && s.length === 1) {
o = [ i ];
}
const c = this.matchOne(o, s, t);
if (c) {
if (n.flipNegate) {
return true;
}
return !this.negate;
}
}
if (n.flipNegate) {
return false;
}
return this.negate;
}
static defaults(t) {
return e.minimatch.defaults(t).Minimatch;
}
}
e.Minimatch = Minimatch;
var Q = WC();
Object.defineProperty(e, "AST", {
enumerable: true,
get: function() {
return Q.AST;
}
});
var V = YC();
Object.defineProperty(e, "escape", {
enumerable: true,
get: function() {
return V.escape;
}
});
var K = VC();
Object.defineProperty(e, "unescape", {
enumerable: true,
get: function() {
return K.unescape;
}
});
e.minimatch.AST = i.AST;
e.minimatch.Minimatch = Minimatch;
e.minimatch.escape = s.escape;
e.minimatch.unescape = o.unescape;
})(OC);
return OC;
}
var XC = {};
var ZC = {};
var eR = {};
var tR;
function nR() {
if (tR) return eR;
tR = 1;
Object.defineProperty(eR, "__esModule", {
value: true
});
eR.LRUCache = void 0;
const e = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
const t = new Set;
const n = typeof process === "object" && !!process ? process : {};
const a = (e, t, a, r) => {
typeof n.emitWarning === "function" ? n.emitWarning(e, t, a, r) : console.error(`[${a}] ${t}: ${e}`);
};
let r = globalThis.AbortController;
let i = globalThis.AbortSignal;
if (typeof r === "undefined") {
i = class AbortSignal {
onabort;
_onabort=[];
reason;
aborted=false;
addEventListener(e, t) {
this._onabort.push(t);
}
};
r = class AbortController {
constructor() {
t();
}
signal=new i;
abort(e) {
if (this.signal.aborted) return;
this.signal.reason = e;
this.signal.aborted = true;
for (const t of this.signal._onabort) {
t(e);
}
this.signal.onabort?.(e);
}
};
let e = n.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
const t = () => {
if (!e) return;
e = false;
a("AbortController is not defined. If using lru-cache in " + "node 14, load an AbortController polyfill from the " + "`node-abort-controller` package. A minimal polyfill is " + "provided for use by LRUCache.fetch(), but it should not be " + "relied upon in other contexts (eg, passing it to other APIs that " + "use AbortController/AbortSignal might have undesirable effects). " + "You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", t);
};
}
const s = e => !t.has(e);
const o = e => e && e === Math.floor(e) && e > 0 && isFinite(e);
const c = e => !o(e) ? null : e <= Math.pow(2, 8) ? Uint8Array : e <= Math.pow(2, 16) ? Uint16Array : e <= Math.pow(2, 32) ? Uint32Array : e <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
class ZeroArray extends Array {
constructor(e) {
super(e);
this.fill(0);
}
}
class Stack {
heap;
length;
static #f=false;
static create(e) {
const t = c(e);
if (!t) return [];
Stack.#f = true;
const n = new Stack(e, t);
Stack.#f = false;
return n;
}
constructor(e, t) {
if (!Stack.#f) {
throw new TypeError("instantiate Stack using Stack.create(n)");
}
this.heap = new t(e);
this.length = 0;
}
push(e) {
this.heap[this.length++] = e;
}
pop() {
return this.heap[--this.length];
}
}
class LRUCache {
#y;
#E;
#T;
#g;
#N;
#A;
ttl;
ttlResolution;
ttlAutopurge;
updateAgeOnGet;
updateAgeOnHas;
allowStale;
noDisposeOnSet;
noUpdateTTL;
maxEntrySize;
sizeCalculation;
noDeleteOnFetchRejection;
noDeleteOnStaleGet;
allowStaleOnFetchAbort;
allowStaleOnFetchRejection;
ignoreFetchAbort;
#b;
#C;
#R;
#S;
#w;
#M;
#O;
#v;
#I;
#P;
#L;
#D;
#_;
#$;
#x;
#q;
#U;
static unsafeExposeInternals(e) {
return {
starts: e.#_,
ttls: e.#$,
sizes: e.#D,
keyMap: e.#R,
keyList: e.#S,
valList: e.#w,
next: e.#M,
prev: e.#O,
get head() {
return e.#v;
},
get tail() {
return e.#I;
},
free: e.#P,
isBackgroundFetch: t => e.#B(t),
backgroundFetch: (t, n, a, r) => e.#F(t, n, a, r),
moveToTail: t => e.#j(t),
indexes: t => e.#k(t),
rindexes: t => e.#Q(t),
isStale: t => e.#V(t)
};
}
get max() {
return this.#y;
}
get maxSize() {
return this.#E;
}
get calculatedSize() {
return this.#C;
}
get size() {
return this.#b;
}
get fetchMethod() {
return this.#N;
}
get memoMethod() {
return this.#A;
}
get dispose() {
return this.#T;
}
get disposeAfter() {
return this.#g;
}
constructor(e) {
const {max: n = 0, ttl: r, ttlResolution: i = 1, ttlAutopurge: l, updateAgeOnGet: u, updateAgeOnHas: h, allowStale: d, dispose: p, disposeAfter: m, noDisposeOnSet: f, noUpdateTTL: y, maxSize: E = 0, maxEntrySize: T = 0, sizeCalculation: g, fetchMethod: N, memoMethod: A, noDeleteOnFetchRejection: b, noDeleteOnStaleGet: C, allowStaleOnFetchRejection: R, allowStaleOnFetchAbort: S, ignoreFetchAbort: w} = e;
if (n !== 0 && !o(n)) {
throw new TypeError("max option must be a nonnegative integer");
}
const M = n ? c(n) : Array;
if (!M) {
throw new Error("invalid max value: " + n);
}
this.#y = n;
this.#E = E;
this.maxEntrySize = T || this.#E;
this.sizeCalculation = g;
if (this.sizeCalculation) {
if (!this.#E && !this.maxEntrySize) {
throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
}
if (typeof this.sizeCalculation !== "function") {
throw new TypeError("sizeCalculation set to non-function");
}
}
if (A !== undefined && typeof A !== "function") {
throw new TypeError("memoMethod must be a function if defined");
}
this.#A = A;
if (N !== undefined && typeof N !== "function") {
throw new TypeError("fetchMethod must be a function if specified");
}
this.#N = N;
this.#q = !!N;
this.#R = new Map;
this.#S = new Array(n).fill(undefined);
this.#w = new Array(n).fill(undefined);
this.#M = new M(n);
this.#O = new M(n);
this.#v = 0;
this.#I = 0;
this.#P = Stack.create(n);
this.#b = 0;
this.#C = 0;
if (typeof p === "function") {
this.#T = p;
}
if (typeof m === "function") {
this.#g = m;
this.#L = [];
} else {
this.#g = undefined;
this.#L = undefined;
}
this.#x = !!this.#T;
this.#U = !!this.#g;
this.noDisposeOnSet = !!f;
this.noUpdateTTL = !!y;
this.noDeleteOnFetchRejection = !!b;
this.allowStaleOnFetchRejection = !!R;
this.allowStaleOnFetchAbort = !!S;
this.ignoreFetchAbort = !!w;
if (this.maxEntrySize !== 0) {
if (this.#E !== 0) {
if (!o(this.#E)) {
throw new TypeError("maxSize must be a positive integer if specified");
}
}
if (!o(this.maxEntrySize)) {
throw new TypeError("maxEntrySize must be a positive integer if specified");
}
this.#K();
}
this.allowStale = !!d;
this.noDeleteOnStaleGet = !!C;
this.updateAgeOnGet = !!u;
this.updateAgeOnHas = !!h;
this.ttlResolution = o(i) || i === 0 ? i : 1;
this.ttlAutopurge = !!l;
this.ttl = r || 0;
if (this.ttl) {
if (!o(this.ttl)) {
throw new TypeError("ttl must be a positive integer if specified");
}
this.#W();
}
if (this.#y === 0 && this.ttl === 0 && this.#E === 0) {
throw new TypeError("At least one of max, maxSize, or ttl is required");
}
if (!this.ttlAutopurge && !this.#y && !this.#E) {
const e = "LRU_CACHE_UNBOUNDED";
if (s(e)) {
t.add(e);
const n = "TTL caching without ttlAutopurge, max, or maxSize can " + "result in unbounded memory consumption.";
a(n, "UnboundedCacheWarning", e, LRUCache);
}
}
}
getRemainingTTL(e) {
return this.#R.has(e) ? Infinity : 0;
}
#W() {
const t = new ZeroArray(this.#y);
const n = new ZeroArray(this.#y);
this.#$ = t;
this.#_ = n;
this.#H = (a, r, i = e.now()) => {
n[a] = r !== 0 ? i : 0;
t[a] = r;
if (r !== 0 && this.ttlAutopurge) {
const e = setTimeout(() => {
if (this.#V(a)) {
this.#G(this.#S[a], "expire");
}
}, r + 1);
if (e.unref) {
e.unref();
}
}
};
this.#Y = a => {
n[a] = t[a] !== 0 ? e.now() : 0;
};
this.#z = (e, i) => {
if (t[i]) {
const s = t[i];
const o = n[i];
if (!s || !o) return;
e.ttl = s;
e.start = o;
e.now = a || r();
const c = e.now - o;
e.remainingTTL = s - c;
}
};
let a = 0;
const r = () => {
const t = e.now();
if (this.ttlResolution > 0) {
a = t;
const e = setTimeout(() => a = 0, this.ttlResolution);
if (e.unref) {
e.unref();
}
}
return t;
};
this.getRemainingTTL = e => {
const i = this.#R.get(e);
if (i === undefined) {
return 0;
}
const s = t[i];
const o = n[i];
if (!s || !o) {
return Infinity;
}
const c = (a || r()) - o;
return s - c;
};
this.#V = e => {
const i = n[e];
const s = t[e];
return !!s && !!i && (a || r()) - i > s;
};
}
#Y=() => {};
#z=() => {};
#H=() => {};
#V=() => false;
#K() {
const e = new ZeroArray(this.#y);
this.#C = 0;
this.#D = e;
this.#J = t => {
this.#C -= e[t];
e[t] = 0;
};
this.#X = (e, t, n, a) => {
if (this.#B(t)) {
return 0;
}
if (!o(n)) {
if (a) {
if (typeof a !== "function") {
throw new TypeError("sizeCalculation must be a function");
}
n = a(t, e);
if (!o(n)) {
throw new TypeError("sizeCalculation return invalid (expect positive integer)");
}
} else {
throw new TypeError("invalid size value (must be positive integer). " + "When maxSize or maxEntrySize is used, sizeCalculation " + "or size must be set.");
}
}
return n;
};
this.#Z = (t, n, a) => {
e[t] = n;
if (this.#E) {
const n = this.#E - e[t];
while (this.#C > n) {
this.#ee(true);
}
}
this.#C += e[t];
if (a) {
a.entrySize = n;
a.totalCalculatedSize = this.#C;
}
};
}
#J=e => {};
#Z=(e, t, n) => {};
#X=(e, t, n, a) => {
if (n || a) {
throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
}
return 0;
};
* #k({allowStale: e = this.allowStale} = {}) {
if (this.#b) {
for (let t = this.#I; true; ) {
if (!this.#te(t)) {
break;
}
if (e || !this.#V(t)) {
yield t;
}
if (t === this.#v) {
break;
} else {
t = this.#O[t];
}
}
}
}
* #Q({allowStale: e = this.allowStale} = {}) {
if (this.#b) {
for (let t = this.#v; true; ) {
if (!this.#te(t)) {
break;
}
if (e || !this.#V(t)) {
yield t;
}
if (t === this.#I) {
break;
} else {
t = this.#M[t];
}
}
}
}
#te(e) {
return e !== undefined && this.#R.get(this.#S[e]) === e;
}
* entries() {
for (const e of this.#k()) {
if (this.#w[e] !== undefined && this.#S[e] !== undefined && !this.#B(this.#w[e])) {
yield [ this.#S[e], this.#w[e] ];
}
}
}
* rentries() {
for (const e of this.#Q()) {
if (this.#w[e] !== undefined && this.#S[e] !== undefined && !this.#B(this.#w[e])) {
yield [ this.#S[e], this.#w[e] ];
}
}
}
* keys() {
for (const e of this.#k()) {
const t = this.#S[e];
if (t !== undefined && !this.#B(this.#w[e])) {
yield t;
}
}
}
* rkeys() {
for (const e of this.#Q()) {
const t = this.#S[e];
if (t !== undefined && !this.#B(this.#w[e])) {
yield t;
}
}
}
* values() {
for (const e of this.#k()) {
const t = this.#w[e];
if (t !== undefined && !this.#B(this.#w[e])) {
yield this.#w[e];
}
}
}
* rvalues() {
for (const e of this.#Q()) {
const t = this.#w[e];
if (t !== undefined && !this.#B(this.#w[e])) {
yield this.#w[e];
}
}
}
[Symbol.iterator]() {
return this.entries();
}
[Symbol.toStringTag]="LRUCache";
find(e, t = {}) {
for (const n of this.#k()) {
const a = this.#w[n];
const r = this.#B(a) ? a.__staleWhileFetching : a;
if (r === undefined) continue;
if (e(r, this.#S[n], this)) {
return this.get(this.#S[n], t);
}
}
}
forEach(e, t = this) {
for (const n of this.#k()) {
const a = this.#w[n];
const r = this.#B(a) ? a.__staleWhileFetching : a;
if (r === undefined) continue;
e.call(t, r, this.#S[n], this);
}
}
rforEach(e, t = this) {
for (const n of this.#Q()) {
const a = this.#w[n];
const r = this.#B(a) ? a.__staleWhileFetching : a;
if (r === undefined) continue;
e.call(t, r, this.#S[n], this);
}
}
purgeStale() {
let e = false;
for (const t of this.#Q({
allowStale: true
})) {
if (this.#V(t)) {
this.#G(this.#S[t], "expire");
e = true;
}
}
return e;
}
info(t) {
const n = this.#R.get(t);
if (n === undefined) return undefined;
const a = this.#w[n];
const r = this.#B(a) ? a.__staleWhileFetching : a;
if (r === undefined) return undefined;
const i = {
value: r
};
if (this.#$ && this.#_) {
const t = this.#$[n];
const a = this.#_[n];
if (t && a) {
const n = t - (e.now() - a);
i.ttl = n;
i.start = Date.now();
}
}
if (this.#D) {
i.size = this.#D[n];
}
return i;
}
dump() {
const t = [];
for (const n of this.#k({
allowStale: true
})) {
const a = this.#S[n];
const r = this.#w[n];
const i = this.#B(r) ? r.__staleWhileFetching : r;
if (i === undefined || a === undefined) continue;
const s = {
value: i
};
if (this.#$ && this.#_) {
s.ttl = this.#$[n];
const t = e.now() - this.#_[n];
s.start = Math.floor(Date.now() - t);
}
if (this.#D) {
s.size = this.#D[n];
}
t.unshift([ a, s ]);
}
return t;
}
load(t) {
this.clear();
for (const [n, a] of t) {
if (a.start) {
const t = Date.now() - a.start;
a.start = e.now() - t;
}
this.set(n, a.value, a);
}
}
set(e, t, n = {}) {
if (t === undefined) {
this.delete(e);
return this;
}
const {ttl: a = this.ttl, start: r, noDisposeOnSet: i = this.noDisposeOnSet, sizeCalculation: s = this.sizeCalculation, status: o} = n;
let {noUpdateTTL: c = this.noUpdateTTL} = n;
const l = this.#X(e, t, n.size || 0, s);
if (this.maxEntrySize && l > this.maxEntrySize) {
if (o) {
o.set = "miss";
o.maxEntrySizeExceeded = true;
}
this.#G(e, "set");
return this;
}
let u = this.#b === 0 ? undefined : this.#R.get(e);
if (u === undefined) {
u = this.#b === 0 ? this.#I : this.#P.length !== 0 ? this.#P.pop() : this.#b === this.#y ? this.#ee(false) : this.#b;
this.#S[u] = e;
this.#w[u] = t;
this.#R.set(e, u);
this.#M[this.#I] = u;
this.#O[u] = this.#I;
this.#I = u;
this.#b++;
this.#Z(u, l, o);
if (o) o.set = "add";
c = false;
} else {
this.#j(u);
const n = this.#w[u];
if (t !== n) {
if (this.#q && this.#B(n)) {
n.__abortController.abort(new Error("replaced"));
const {__staleWhileFetching: t} = n;
if (t !== undefined && !i) {
if (this.#x) {
this.#T?.(t, e, "set");
}
if (this.#U) {
this.#L?.push([ t, e, "set" ]);
}
}
} else if (!i) {
if (this.#x) {
this.#T?.(n, e, "set");
}
if (this.#U) {
this.#L?.push([ n, e, "set" ]);
}
}
this.#J(u);
this.#Z(u, l, o);
this.#w[u] = t;
if (o) {
o.set = "replace";
const e = n && this.#B(n) ? n.__staleWhileFetching : n;
if (e !== undefined) o.oldValue = e;
}
} else if (o) {
o.set = "update";
}
}
if (a !== 0 && !this.#$) {
this.#W();
}
if (this.#$) {
if (!c) {
this.#H(u, a, r);
}
if (o) this.#z(o, u);
}
if (!i && this.#U && this.#L) {
const e = this.#L;
let t;
while (t = e?.shift()) {
this.#g?.(...t);
}
}
return this;
}
pop() {
try {
while (this.#b) {
const e = this.#w[this.#v];
this.#ee(true);
if (this.#B(e)) {
if (e.__staleWhileFetching) {
return e.__staleWhileFetching;
}
} else if (e !== undefined) {
return e;
}
}
} finally {
if (this.#U && this.#L) {
const e = this.#L;
let t;
while (t = e?.shift()) {
this.#g?.(...t);
}
}
}
}
#ee(e) {
const t = this.#v;
const n = this.#S[t];
const a = this.#w[t];
if (this.#q && this.#B(a)) {
a.__abortController.abort(new Error("evicted"));
} else if (this.#x || this.#U) {
if (this.#x) {
this.#T?.(a, n, "evict");
}
if (this.#U) {
this.#L?.push([ a, n, "evict" ]);
}
}
this.#J(t);
if (e) {
this.#S[t] = undefined;
this.#w[t] = undefined;
this.#P.push(t);
}
if (this.#b === 1) {
this.#v = this.#I = 0;
this.#P.length = 0;
} else {
this.#v = this.#M[t];
}
this.#R.delete(n);
this.#b--;
return t;
}
has(e, t = {}) {
const {updateAgeOnHas: n = this.updateAgeOnHas, status: a} = t;
const r = this.#R.get(e);
if (r !== undefined) {
const e = this.#w[r];
if (this.#B(e) && e.__staleWhileFetching === undefined) {
return false;
}
if (!this.#V(r)) {
if (n) {
this.#Y(r);
}
if (a) {
a.has = "hit";
this.#z(a, r);
}
return true;
} else if (a) {
a.has = "stale";
this.#z(a, r);
}
} else if (a) {
a.has = "miss";
}
return false;
}
peek(e, t = {}) {
const {allowStale: n = this.allowStale} = t;
const a = this.#R.get(e);
if (a === undefined || !n && this.#V(a)) {
return;
}
const r = this.#w[a];
return this.#B(r) ? r.__staleWhileFetching : r;
}
#F(e, t, n, a) {
const i = t === undefined ? undefined : this.#w[t];
if (this.#B(i)) {
return i;
}
const s = new r;
const {signal: o} = n;
o?.addEventListener("abort", () => s.abort(o.reason), {
signal: s.signal
});
const c = {
signal: s.signal,
options: n,
context: a
};
const l = (a, r = false) => {
const {aborted: i} = s.signal;
const o = n.ignoreFetchAbort && a !== undefined;
if (n.status) {
if (i && !r) {
n.status.fetchAborted = true;
n.status.fetchError = s.signal.reason;
if (o) n.status.fetchAbortIgnored = true;
} else {
n.status.fetchResolved = true;
}
}
if (i && !o && !r) {
return h(s.signal.reason);
}
const l = p;
if (this.#w[t] === p) {
if (a === undefined) {
if (l.__staleWhileFetching) {
this.#w[t] = l.__staleWhileFetching;
} else {
this.#G(e, "fetch");
}
} else {
if (n.status) n.status.fetchUpdated = true;
this.set(e, a, c.options);
}
}
return a;
};
const u = e => {
if (n.status) {
n.status.fetchRejected = true;
n.status.fetchError = e;
}
return h(e);
};
const h = a => {
const {aborted: r} = s.signal;
const i = r && n.allowStaleOnFetchAbort;
const o = i || n.allowStaleOnFetchRejection;
const c = o || n.noDeleteOnFetchRejection;
const l = p;
if (this.#w[t] === p) {
const n = !c || l.__staleWhileFetching === undefined;
if (n) {
this.#G(e, "fetch");
} else if (!i) {
this.#w[t] = l.__staleWhileFetching;
}
}
if (o) {
if (n.status && l.__staleWhileFetching !== undefined) {
n.status.returnedStale = true;
}
return l.__staleWhileFetching;
} else if (l.__returned === l) {
throw a;
}
};
const d = (t, a) => {
const r = this.#N?.(e, i, c);
if (r && r instanceof Promise) {
r.then(e => t(e === undefined ? undefined : e), a);
}
s.signal.addEventListener("abort", () => {
if (!n.ignoreFetchAbort || n.allowStaleOnFetchAbort) {
t(undefined);
if (n.allowStaleOnFetchAbort) {
t = e => l(e, true);
}
}
});
};
if (n.status) n.status.fetchDispatched = true;
const p = new Promise(d).then(l, u);
const m = Object.assign(p, {
__abortController: s,
__staleWhileFetching: i,
__returned: undefined
});
if (t === undefined) {
this.set(e, m, {
...c.options,
status: undefined
});
t = this.#R.get(e);
} else {
this.#w[t] = m;
}
return m;
}
#B(e) {
if (!this.#q) return false;
const t = e;
return !!t && t instanceof Promise && t.hasOwnProperty("__staleWhileFetching") && t.__abortController instanceof r;
}
async fetch(e, t = {}) {
const {allowStale: n = this.allowStale, updateAgeOnGet: a = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, ttl: i = this.ttl, noDisposeOnSet: s = this.noDisposeOnSet, size: o = 0, sizeCalculation: c = this.sizeCalculation, noUpdateTTL: l = this.noUpdateTTL, noDeleteOnFetchRejection: u = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: h = this.allowStaleOnFetchRejection, ignoreFetchAbort: d = this.ignoreFetchAbort, allowStaleOnFetchAbort: p = this.allowStaleOnFetchAbort, context: m, forceRefresh: f = false, status: y, signal: E} = t;
if (!this.#q) {
if (y) y.fetch = "get";
return this.get(e, {
allowStale: n,
updateAgeOnGet: a,
noDeleteOnStaleGet: r,
status: y
});
}
const T = {
allowStale: n,
updateAgeOnGet: a,
noDeleteOnStaleGet: r,
ttl: i,
noDisposeOnSet: s,
size: o,
sizeCalculation: c,
noUpdateTTL: l,
noDeleteOnFetchRejection: u,
allowStaleOnFetchRejection: h,
allowStaleOnFetchAbort: p,
ignoreFetchAbort: d,
status: y,
signal: E
};
let g = this.#R.get(e);
if (g === undefined) {
if (y) y.fetch = "miss";
const t = this.#F(e, g, T, m);
return t.__returned = t;
} else {
const t = this.#w[g];
if (this.#B(t)) {
const e = n && t.__staleWhileFetching !== undefined;
if (y) {
y.fetch = "inflight";
if (e) y.returnedStale = true;
}
return e ? t.__staleWhileFetching : t.__returned = t;
}
const r = this.#V(g);
if (!f && !r) {
if (y) y.fetch = "hit";
this.#j(g);
if (a) {
this.#Y(g);
}
if (y) this.#z(y, g);
return t;
}
const i = this.#F(e, g, T, m);
const s = i.__staleWhileFetching !== undefined;
const o = s && n;
if (y) {
y.fetch = r ? "stale" : "refresh";
if (o && r) y.returnedStale = true;
}
return o ? i.__staleWhileFetching : i.__returned = i;
}
}
async forceFetch(e, t = {}) {
const n = await this.fetch(e, t);
if (n === undefined) throw new Error("fetch() returned undefined");
return n;
}
memo(e, t = {}) {
const n = this.#A;
if (!n) {
throw new Error("no memoMethod provided to constructor");
}
const {context: a, forceRefresh: r, ...i} = t;
const s = this.get(e, i);
if (!r && s !== undefined) return s;
const o = n(e, s, {
options: i,
context: a
});
this.set(e, o, i);
return o;
}
get(e, t = {}) {
const {allowStale: n = this.allowStale, updateAgeOnGet: a = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, status: i} = t;
const s = this.#R.get(e);
if (s !== undefined) {
const t = this.#w[s];
const o = this.#B(t);
if (i) this.#z(i, s);
if (this.#V(s)) {
if (i) i.get = "stale";
if (!o) {
if (!r) {
this.#G(e, "expire");
}
if (i && n) i.returnedStale = true;
return n ? t : undefined;
} else {
if (i && n && t.__staleWhileFetching !== undefined) {
i.returnedStale = true;
}
return n ? t.__staleWhileFetching : undefined;
}
} else {
if (i) i.get = "hit";
if (o) {
return t.__staleWhileFetching;
}
this.#j(s);
if (a) {
this.#Y(s);
}
return t;
}
} else if (i) {
i.get = "miss";
}
}
#ne(e, t) {
this.#O[t] = e;
this.#M[e] = t;
}
#j(e) {
if (e !== this.#I) {
if (e === this.#v) {
this.#v = this.#M[e];
} else {
this.#ne(this.#O[e], this.#M[e]);
}
this.#ne(this.#I, e);
this.#I = e;
}
}
delete(e) {
return this.#G(e, "delete");
}
#G(e, t) {
let n = false;
if (this.#b !== 0) {
const a = this.#R.get(e);
if (a !== undefined) {
n = true;
if (this.#b === 1) {
this.#ae(t);
} else {
this.#J(a);
const n = this.#w[a];
if (this.#B(n)) {
n.__abortController.abort(new Error("deleted"));
} else if (this.#x || this.#U) {
if (this.#x) {
this.#T?.(n, e, t);
}
if (this.#U) {
this.#L?.push([ n, e, t ]);
}
}
this.#R.delete(e);
this.#S[a] = undefined;
this.#w[a] = undefined;
if (a === this.#I) {
this.#I = this.#O[a];
} else if (a === this.#v) {
this.#v = this.#M[a];
} else {
const e = this.#O[a];
this.#M[e] = this.#M[a];
const t = this.#M[a];
this.#O[t] = this.#O[a];
}
this.#b--;
this.#P.push(a);
}
}
}
if (this.#U && this.#L?.length) {
const e = this.#L;
let t;
while (t = e?.shift()) {
this.#g?.(...t);
}
}
return n;
}
clear() {
return this.#ae("delete");
}
#ae(e) {
for (const t of this.#Q({
allowStale: true
})) {
const n = this.#w[t];
if (this.#B(n)) {
n.__abortController.abort(new Error("deleted"));
} else {
const a = this.#S[t];
if (this.#x) {
this.#T?.(n, a, e);
}
if (this.#U) {
this.#L?.push([ n, a, e ]);
}
}
}
this.#R.clear();
this.#w.fill(undefined);
this.#S.fill(undefined);
if (this.#$ && this.#_) {
this.#$.fill(0);
this.#_.fill(0);
}
if (this.#D) {
this.#D.fill(0);
}
this.#v = 0;
this.#I = 0;
this.#P.length = 0;
this.#C = 0;
this.#b = 0;
if (this.#U && this.#L) {
const e = this.#L;
let t;
while (t = e?.shift()) {
this.#g?.(...t);
}
}
}
}
eR.LRUCache = LRUCache;
return eR;
}
var aR = {};
var rR;
function iR() {
if (rR) return aR;
rR = 1;
(function(e) {
var t = r && r.__importDefault || function(e) {
return e && e.__esModule ? e : {
default: e
};
};
Object.defineProperty(e, "__esModule", {
value: true
});
e.Minipass = e.isWritable = e.isReadable = e.isStream = void 0;
const n = typeof process === "object" && process ? process : {
stdout: null,
stderr: null
};
const a = A;
const i = t(b);
const s = C;
const o = t => !!t && typeof t === "object" && (t instanceof Minipass || t instanceof i.default || (0,
e.isReadable)(t) || (0, e.isWritable)(t));
e.isStream = o;
const c = e => !!e && typeof e === "object" && e instanceof a.EventEmitter && typeof e.pipe === "function" && e.pipe !== i.default.Writable.prototype.pipe;
e.isReadable = c;
const l = e => !!e && typeof e === "object" && e instanceof a.EventEmitter && typeof e.write === "function" && typeof e.end === "function";
e.isWritable = l;
const u = Symbol("EOF");
const h = Symbol("maybeEmitEnd");
const d = Symbol("emittedEnd");
const p = Symbol("emittingEnd");
const m = Symbol("emittedError");
const f = Symbol("closed");
const y = Symbol("read");
const E = Symbol("flush");
const T = Symbol("flushChunk");
const g = Symbol("encoding");
const N = Symbol("decoder");
const R = Symbol("flowing");
const S = Symbol("paused");
const w = Symbol("resume");
const M = Symbol("buffer");
const O = Symbol("pipes");
const v = Symbol("bufferLength");
const I = Symbol("bufferPush");
const P = Symbol("bufferShift");
const L = Symbol("objectMode");
const D = Symbol("destroyed");
const _ = Symbol("error");
const $ = Symbol("emitData");
const x = Symbol("emitEnd");
const q = Symbol("emitEnd2");
const U = Symbol("async");
const B = Symbol("abort");
const F = Symbol("aborted");
const j = Symbol("signal");
const k = Symbol("dataListeners");
const Q = Symbol("discarded");
const V = e => Promise.resolve().then(e);
const K = e => e();
const W = e => e === "end" || e === "finish" || e === "prefinish";
const H = e => e instanceof ArrayBuffer || !!e && typeof e === "object" && e.constructor && e.constructor.name === "ArrayBuffer" && e.byteLength >= 0;
const G = e => !Buffer.isBuffer(e) && ArrayBuffer.isView(e);
class Pipe {
src;
dest;
opts;
ondrain;
constructor(e, t, n) {
this.src = e;
this.dest = t;
this.opts = n;
this.ondrain = () => e[w]();
this.dest.on("drain", this.ondrain);
}
unpipe() {
this.dest.removeListener("drain", this.ondrain);
}
proxyErrors(e) {}
end() {
this.unpipe();
if (this.opts.end) this.dest.end();
}
}
class PipeProxyErrors extends Pipe {
unpipe() {
this.src.removeListener("error", this.proxyErrors);
super.unpipe();
}
constructor(e, t, n) {
super(e, t, n);
this.proxyErrors = e => t.emit("error", e);
e.on("error", this.proxyErrors);
}
}
const Y = e => !!e.objectMode;
const z = e => !e.objectMode && !!e.encoding && e.encoding !== "buffer";
class Minipass extends a.EventEmitter {
[R]=false;
[S]=false;
[O]=[];
[M]=[];
[L];
[g];
[U];
[N];
[u]=false;
[d]=false;
[p]=false;
[f]=false;
[m]=null;
[v]=0;
[D]=false;
[j];
[F]=false;
[k]=0;
[Q]=false;
writable=true;
readable=true;
constructor(...e) {
const t = e[0] || {};
super();
if (t.objectMode && typeof t.encoding === "string") {
throw new TypeError("Encoding and objectMode may not be used together");
}
if (Y(t)) {
this[L] = true;
this[g] = null;
} else if (z(t)) {
this[g] = t.encoding;
this[L] = false;
} else {
this[L] = false;
this[g] = null;
}
this[U] = !!t.async;
this[N] = this[g] ? new s.StringDecoder(this[g]) : null;
if (t && t.debugExposeBuffer === true) {
Object.defineProperty(this, "buffer", {
get: () => this[M]
});
}
if (t && t.debugExposePipes === true) {
Object.defineProperty(this, "pipes", {
get: () => this[O]
});
}
const {signal: n} = t;
if (n) {
this[j] = n;
if (n.aborted) {
this[B]();
} else {
n.addEventListener("abort", () => this[B]());
}
}
}
get bufferLength() {
return this[v];
}
get encoding() {
return this[g];
}
set encoding(e) {
throw new Error("Encoding must be set at instantiation time");
}
setEncoding(e) {
throw new Error("Encoding must be set at instantiation time");
}
get objectMode() {
return this[L];
}
set objectMode(e) {
throw new Error("objectMode must be set at instantiation time");
}
get ["async"]() {
return this[U];
}
set ["async"](e) {
this[U] = this[U] || !!e;
}
[B]() {
this[F] = true;
this.emit("abort", this[j]?.reason);
this.destroy(this[j]?.reason);
}
get aborted() {
return this[F];
}
set aborted(e) {}
write(e, t, n) {
if (this[F]) return false;
if (this[u]) throw new Error("write after end");
if (this[D]) {
this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), {
code: "ERR_STREAM_DESTROYED"
}));
return true;
}
if (typeof t === "function") {
n = t;
t = "utf8";
}
if (!t) t = "utf8";
const a = this[U] ? V : K;
if (!this[L] && !Buffer.isBuffer(e)) {
if (G(e)) {
e = Buffer.from(e.buffer, e.byteOffset, e.byteLength);
} else if (H(e)) {
e = Buffer.from(e);
} else if (typeof e !== "string") {
throw new Error("Non-contiguous data written to non-objectMode stream");
}
}
if (this[L]) {
if (this[R] && this[v] !== 0) this[E](true);
if (this[R]) this.emit("data", e); else this[I](e);
if (this[v] !== 0) this.emit("readable");
if (n) a(n);
return this[R];
}
if (!e.length) {
if (this[v] !== 0) this.emit("readable");
if (n) a(n);
return this[R];
}
if (typeof e === "string" && !(t === this[g] && !this[N]?.lastNeed)) {
e = Buffer.from(e, t);
}
if (Buffer.isBuffer(e) && this[g]) {
e = this[N].write(e);
}
if (this[R] && this[v] !== 0) this[E](true);
if (this[R]) this.emit("data", e); else this[I](e);
if (this[v] !== 0) this.emit("readable");
if (n) a(n);
return this[R];
}
read(e) {
if (this[D]) return null;
this[Q] = false;
if (this[v] === 0 || e === 0 || e && e > this[v]) {
this[h]();
return null;
}
if (this[L]) e = null;
if (this[M].length > 1 && !this[L]) {
this[M] = [ this[g] ? this[M].join("") : Buffer.concat(this[M], this[v]) ];
}
const t = this[y](e || null, this[M][0]);
this[h]();
return t;
}
[y](e, t) {
if (this[L]) this[P](); else {
const n = t;
if (e === n.length || e === null) this[P](); else if (typeof n === "string") {
this[M][0] = n.slice(e);
t = n.slice(0, e);
this[v] -= e;
} else {
this[M][0] = n.subarray(e);
t = n.subarray(0, e);
this[v] -= e;
}
}
this.emit("data", t);
if (!this[M].length && !this[u]) this.emit("drain");
return t;
}
end(e, t, n) {
if (typeof e === "function") {
n = e;
e = undefined;
}
if (typeof t === "function") {
n = t;
t = "utf8";
}
if (e !== undefined) this.write(e, t);
if (n) this.once("end", n);
this[u] = true;
this.writable = false;
if (this[R] || !this[S]) this[h]();
return this;
}
[w]() {
if (this[D]) return;
if (!this[k] && !this[O].length) {
this[Q] = true;
}
this[S] = false;
this[R] = true;
this.emit("resume");
if (this[M].length) this[E](); else if (this[u]) this[h](); else this.emit("drain");
}
resume() {
return this[w]();
}
pause() {
this[R] = false;
this[S] = true;
this[Q] = false;
}
get destroyed() {
return this[D];
}
get flowing() {
return this[R];
}
get paused() {
return this[S];
}
[I](e) {
if (this[L]) this[v] += 1; else this[v] += e.length;
this[M].push(e);
}
[P]() {
if (this[L]) this[v] -= 1; else this[v] -= this[M][0].length;
return this[M].shift();
}
[E](e = false) {
do {} while (this[T](this[P]()) && this[M].length);
if (!e && !this[M].length && !this[u]) this.emit("drain");
}
[T](e) {
this.emit("data", e);
return this[R];
}
pipe(e, t) {
if (this[D]) return e;
this[Q] = false;
const a = this[d];
t = t || {};
if (e === n.stdout || e === n.stderr) t.end = false; else t.end = t.end !== false;
t.proxyErrors = !!t.proxyErrors;
if (a) {
if (t.end) e.end();
} else {
this[O].push(!t.proxyErrors ? new Pipe(this, e, t) : new PipeProxyErrors(this, e, t));
if (this[U]) V(() => this[w]()); else this[w]();
}
return e;
}
unpipe(e) {
const t = this[O].find(t => t.dest === e);
if (t) {
if (this[O].length === 1) {
if (this[R] && this[k] === 0) {
this[R] = false;
}
this[O] = [];
} else this[O].splice(this[O].indexOf(t), 1);
t.unpipe();
}
}
addListener(e, t) {
return this.on(e, t);
}
on(e, t) {
const n = super.on(e, t);
if (e === "data") {
this[Q] = false;
this[k]++;
if (!this[O].length && !this[R]) {
this[w]();
}
} else if (e === "readable" && this[v] !== 0) {
super.emit("readable");
} else if (W(e) && this[d]) {
super.emit(e);
this.removeAllListeners(e);
} else if (e === "error" && this[m]) {
const e = t;
if (this[U]) V(() => e.call(this, this[m])); else e.call(this, this[m]);
}
return n;
}
removeListener(e, t) {
return this.off(e, t);
}
off(e, t) {
const n = super.off(e, t);
if (e === "data") {
this[k] = this.listeners("data").length;
if (this[k] === 0 && !this[Q] && !this[O].length) {
this[R] = false;
}
}
return n;
}
removeAllListeners(e) {
const t = super.removeAllListeners(e);
if (e === "data" || e === undefined) {
this[k] = 0;
if (!this[Q] && !this[O].length) {
this[R] = false;
}
}
return t;
}
get emittedEnd() {
return this[d];
}
[h]() {
if (!this[p] && !this[d] && !this[D] && this[M].length === 0 && this[u]) {
this[p] = true;
this.emit("end");
this.emit("prefinish");
this.emit("finish");
if (this[f]) this.emit("close");
this[p] = false;
}
}
emit(e, ...t) {
const n = t[0];
if (e !== "error" && e !== "close" && e !== D && this[D]) {
return false;
} else if (e === "data") {
return !this[L] && !n ? false : this[U] ? (V(() => this[$](n)), true) : this[$](n);
} else if (e === "end") {
return this[x]();
} else if (e === "close") {
this[f] = true;
if (!this[d] && !this[D]) return false;
const e = super.emit("close");
this.removeAllListeners("close");
return e;
} else if (e === "error") {
this[m] = n;
super.emit(_, n);
const e = !this[j] || this.listeners("error").length ? super.emit("error", n) : false;
this[h]();
return e;
} else if (e === "resume") {
const e = super.emit("resume");
this[h]();
return e;
} else if (e === "finish" || e === "prefinish") {
const t = super.emit(e);
this.removeAllListeners(e);
return t;
}
const a = super.emit(e, ...t);
this[h]();
return a;
}
[$](e) {
for (const t of this[O]) {
if (t.dest.write(e) === false) this.pause();
}
const t = this[Q] ? false : super.emit("data", e);
this[h]();
return t;
}
[x]() {
if (this[d]) return false;
this[d] = true;
this.readable = false;
return this[U] ? (V(() => this[q]()), true) : this[q]();
}
[q]() {
if (this[N]) {
const e = this[N].end();
if (e) {
for (const t of this[O]) {
t.dest.write(e);
}
if (!this[Q]) super.emit("data", e);
}
}
for (const e of this[O]) {
e.end();
}
const e = super.emit("end");
this.removeAllListeners("end");
return e;
}
async collect() {
const e = Object.assign([], {
dataLength: 0
});
if (!this[L]) e.dataLength = 0;
const t = this.promise();
this.on("data", t => {
e.push(t);
if (!this[L]) e.dataLength += t.length;
});
await t;
return e;
}
async concat() {
if (this[L]) {
throw new Error("cannot concat in objectMode");
}
const e = await this.collect();
return this[g] ? e.join("") : Buffer.concat(e, e.dataLength);
}
async promise() {
return new Promise((e, t) => {
this.on(D, () => t(new Error("stream destroyed")));
this.on("error", e => t(e));
this.on("end", () => e());
});
}
[Symbol.asyncIterator]() {
this[Q] = false;
let e = false;
const t = async () => {
this.pause();
e = true;
return {
value: undefined,
done: true
};
};
const n = () => {
if (e) return t();
const n = this.read();
if (n !== null) return Promise.resolve({
done: false,
value: n
});
if (this[u]) return t();
let a;
let r;
const i = e => {
this.off("data", s);
this.off("end", o);
this.off(D, c);
t();
r(e);
};
const s = e => {
this.off("error", i);
this.off("end", o);
this.off(D, c);
this.pause();
a({
value: e,
done: !!this[u]
});
};
const o = () => {
this.off("error", i);
this.off("data", s);
this.off(D, c);
t();
a({
done: true,
value: undefined
});
};
const c = () => i(new Error("stream destroyed"));
return new Promise((e, t) => {
r = t;
a = e;
this.once(D, c);
this.once("error", i);
this.once("end", o);
this.once("data", s);
});
};
return {
next: n,
throw: t,
return: t,
[Symbol.asyncIterator]() {
return this;
}
};
}
[Symbol.iterator]() {
this[Q] = false;
let e = false;
const t = () => {
this.pause();
this.off(_, t);
this.off(D, t);
this.off("end", t);
e = true;
return {
done: true,
value: undefined
};
};
const n = () => {
if (e) return t();
const n = this.read();
return n === null ? t() : {
done: false,
value: n
};
};
this.once("end", t);
this.once(_, t);
this.once(D, t);
return {
next: n,
throw: t,
return: t,
[Symbol.iterator]() {
return this;
}
};
}
destroy(e) {
if (this[D]) {
if (e) this.emit("error", e); else this.emit(D);
return this;
}
this[D] = true;
this[Q] = true;
this[M].length = 0;
this[v] = 0;
const t = this;
if (typeof t.close === "function" && !this[f]) t.close();
if (e) this.emit("error", e); else this.emit(D);
return this;
}
static get isStream() {
return e.isStream;
}
}
e.Minipass = Minipass;
})(aR);
return aR;
}
var sR;
function oR() {
if (sR) return ZC;
sR = 1;
var e = r && r.__createBinding || (Object.create ? function(e, t, n, a) {
if (a === undefined) a = n;
var r = Object.getOwnPropertyDescriptor(t, n);
if (!r || ("get" in r ? !t.__esModule : r.writable || r.configurable)) {
r = {
enumerable: true,
get: function() {
return t[n];
}
};
}
Object.defineProperty(e, a, r);
} : function(e, t, n, a) {
if (a === undefined) a = n;
e[a] = t[n];
});
var t = r && r.__setModuleDefault || (Object.create ? function(e, t) {
Object.defineProperty(e, "default", {
enumerable: true,
value: t
});
} : function(e, t) {
e["default"] = t;
});
var n = r && r.__importStar || function(n) {
if (n && n.__esModule) return n;
var a = {};
if (n != null) for (var r in n) if (r !== "default" && Object.prototype.hasOwnProperty.call(n, r)) e(a, n, r);
t(a, n);
return a;
};
Object.defineProperty(ZC, "__esModule", {
value: true
});
ZC.PathScurry = ZC.Path = ZC.PathScurryDarwin = ZC.PathScurryPosix = ZC.PathScurryWin32 = ZC.PathScurryBase = ZC.PathPosix = ZC.PathWin32 = ZC.PathBase = ZC.ChildrenCache = ZC.ResolveCache = void 0;
const a = nR();
const i = T;
const s = E;
const c = o;
const l = n(g);
const u = c.realpathSync.native;
const h = N;
const d = iR();
const p = {
lstatSync: c.lstatSync,
readdir: c.readdir,
readdirSync: c.readdirSync,
readlinkSync: c.readlinkSync,
realpathSync: u,
promises: {
lstat: h.lstat,
readdir: h.readdir,
readlink: h.readlink,
realpath: h.realpath
}
};
const m = e => !e || e === p || e === l ? p : {
...p,
...e,
promises: {
...p.promises,
...e.promises || {}
}
};
const f = /^\\\\\?\\([a-z]:)\\?$/i;
const y = e => e.replace(/\//g, "\\").replace(f, "$1\\");
const A = /[\\\/]/;
const b = 0;
const C = 1;
const R = 2;
const S = 4;
const w = 6;
const M = 8;
const O = 10;
const v = 12;
const I = 15;
const P = ~I;
const L = 16;
const D = 32;
const _ = 64;
const $ = 128;
const x = 256;
const q = 512;
const U = _ | $ | q;
const B = 1023;
const F = e => e.isFile() ? M : e.isDirectory() ? S : e.isSymbolicLink() ? O : e.isCharacterDevice() ? R : e.isBlockDevice() ? w : e.isSocket() ? v : e.isFIFO() ? C : b;
const j = new Map;
const k = e => {
const t = j.get(e);
if (t) return t;
const n = e.normalize("NFKD");
j.set(e, n);
return n;
};
const Q = new Map;
const V = e => {
const t = Q.get(e);
if (t) return t;
const n = k(e.toLowerCase());
Q.set(e, n);
return n;
};
class ResolveCache extends a.LRUCache {
constructor() {
super({
max: 256
});
}
}
ZC.ResolveCache = ResolveCache;
class ChildrenCache extends a.LRUCache {
constructor(e = 16 * 1024) {
super({
maxSize: e,
sizeCalculation: e => e.length + 1
});
}
}
ZC.ChildrenCache = ChildrenCache;
const K = Symbol("PathScurry setAsCwd");
class PathBase {
name;
root;
roots;
parent;
nocase;
isCWD=false;
#re;
#ie;
get dev() {
return this.#ie;
}
#se;
get mode() {
return this.#se;
}
#oe;
get nlink() {
return this.#oe;
}
#ce;
get uid() {
return this.#ce;
}
#le;
get gid() {
return this.#le;
}
#ue;
get rdev() {
return this.#ue;
}
#he;
get blksize() {
return this.#he;
}
#de;
get ino() {
return this.#de;
}
#b;
get size() {
return this.#b;
}
#pe;
get blocks() {
return this.#pe;
}
#me;
get atimeMs() {
return this.#me;
}
#fe;
get mtimeMs() {
return this.#fe;
}
#ye;
get ctimeMs() {
return this.#ye;
}
#Ee;
get birthtimeMs() {
return this.#Ee;
}
#Te;
get atime() {
return this.#Te;
}
#ge;
get mtime() {
return this.#ge;
}
#Ne;
get ctime() {
return this.#Ne;
}
#Ae;
get birthtime() {
return this.#Ae;
}
#be;
#Ce;
#Re;
#Se;
#we;
#Me;
#Oe;
#ve;
#Ie;
#Pe;
get parentPath() {
return (this.parent || this).fullpath();
}
get path() {
return this.parentPath;
}
constructor(e, t = b, n, a, r, i, s) {
this.name = e;
this.#be = r ? V(e) : k(e);
this.#Oe = t & B;
this.nocase = r;
this.roots = a;
this.root = n || this;
this.#ve = i;
this.#Re = s.fullpath;
this.#we = s.relative;
this.#Me = s.relativePosix;
this.parent = s.parent;
if (this.parent) {
this.#re = this.parent.#re;
} else {
this.#re = m(s.fs);
}
}
depth() {
if (this.#Ce !== undefined) return this.#Ce;
if (!this.parent) return this.#Ce = 0;
return this.#Ce = this.parent.depth() + 1;
}
childrenCache() {
return this.#ve;
}
resolve(e) {
if (!e) {
return this;
}
const t = this.getRootString(e);
const n = e.substring(t.length);
const a = n.split(this.splitSep);
const r = t ? this.getRoot(t).#Le(a) : this.#Le(a);
return r;
}
#Le(e) {
let t = this;
for (const n of e) {
t = t.child(n);
}
return t;
}
children() {
const e = this.#ve.get(this);
if (e) {
return e;
}
const t = Object.assign([], {
provisional: 0
});
this.#ve.set(this, t);
this.#Oe &= ~L;
return t;
}
child(e, t) {
if (e === "" || e === ".") {
return this;
}
if (e === "..") {
return this.parent || this;
}
const n = this.children();
const a = this.nocase ? V(e) : k(e);
for (const e of n) {
if (e.#be === a) {
return e;
}
}
const r = this.parent ? this.sep : "";
const i = this.#Re ? this.#Re + r + e : undefined;
const s = this.newChild(e, b, {
...t,
parent: this,
fullpath: i
});
if (!this.canReaddir()) {
s.#Oe |= $;
}
n.push(s);
return s;
}
relative() {
if (this.isCWD) return "";
if (this.#we !== undefined) {
return this.#we;
}
const e = this.name;
const t = this.parent;
if (!t) {
return this.#we = this.name;
}
const n = t.relative();
return n + (!n || !t.parent ? "" : this.sep) + e;
}
relativePosix() {
if (this.sep === "/") return this.relative();
if (this.isCWD) return "";
if (this.#Me !== undefined) return this.#Me;
const e = this.name;
const t = this.parent;
if (!t) {
return this.#Me = this.fullpathPosix();
}
const n = t.relativePosix();
return n + (!n || !t.parent ? "" : "/") + e;
}
fullpath() {
if (this.#Re !== undefined) {
return this.#Re;
}
const e = this.name;
const t = this.parent;
if (!t) {
return this.#Re = this.name;
}
const n = t.fullpath();
const a = n + (!t.parent ? "" : this.sep) + e;
return this.#Re = a;
}
fullpathPosix() {
if (this.#Se !== undefined) return this.#Se;
if (this.sep === "/") return this.#Se = this.fullpath();
if (!this.parent) {
const e = this.fullpath().replace(/\\/g, "/");
if (/^[a-z]:\//i.test(e)) {
return this.#Se = `//?/${e}`;
} else {
return this.#Se = e;
}
}
const e = this.parent;
const t = e.fullpathPosix();
const n = t + (!t || !e.parent ? "" : "/") + this.name;
return this.#Se = n;
}
isUnknown() {
return (this.#Oe & I) === b;
}
isType(e) {
return this[`is${e}`]();
}
getType() {
return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : this.isSocket() ? "Socket" : "Unknown";
}
isFile() {
return (this.#Oe & I) === M;
}
isDirectory() {
return (this.#Oe & I) === S;
}
isCharacterDevice() {
return (this.#Oe & I) === R;
}
isBlockDevice() {
return (this.#Oe & I) === w;
}
isFIFO() {
return (this.#Oe & I) === C;
}
isSocket() {
return (this.#Oe & I) === v;
}
isSymbolicLink() {
return (this.#Oe & O) === O;
}
lstatCached() {
return this.#Oe & D ? this : undefined;
}
readlinkCached() {
return this.#Ie;
}
realpathCached() {
return this.#Pe;
}
readdirCached() {
const e = this.children();
return e.slice(0, e.provisional);
}
canReadlink() {
if (this.#Ie) return true;
if (!this.parent) return false;
const e = this.#Oe & I;
return !(e !== b && e !== O || this.#Oe & x || this.#Oe & $);
}
calledReaddir() {
return !!(this.#Oe & L);
}
isENOENT() {
return !!(this.#Oe & $);
}
isNamed(e) {
return !this.nocase ? this.#be === k(e) : this.#be === V(e);
}
async readlink() {
const e = this.#Ie;
if (e) {
return e;
}
if (!this.canReadlink()) {
return undefined;
}
if (!this.parent) {
return undefined;
}
try {
const e = await this.#re.promises.readlink(this.fullpath());
const t = (await this.parent.realpath())?.resolve(e);
if (t) {
return this.#Ie = t;
}
} catch (e) {
this.#De(e.code);
return undefined;
}
}
readlinkSync() {
const e = this.#Ie;
if (e) {
return e;
}
if (!this.canReadlink()) {
return undefined;
}
if (!this.parent) {
return undefined;
}
try {
const e = this.#re.readlinkSync(this.fullpath());
const t = this.parent.realpathSync()?.resolve(e);
if (t) {
return this.#Ie = t;
}
} catch (e) {
this.#De(e.code);
return undefined;
}
}
#_e(e) {
this.#Oe |= L;
for (let t = e.provisional; t < e.length; t++) {
const n = e[t];
if (n) n.#$e();
}
}
#$e() {
if (this.#Oe & $) return;
this.#Oe = (this.#Oe | $) & P;
this.#xe();
}
#xe() {
const e = this.children();
e.provisional = 0;
for (const t of e) {
t.#$e();
}
}
#qe() {
this.#Oe |= q;
this.#Ue();
}
#Ue() {
if (this.#Oe & _) return;
let e = this.#Oe;
if ((e & I) === S) e &= P;
this.#Oe = e | _;
this.#xe();
}
#Be(e = "") {
if (e === "ENOTDIR" || e === "EPERM") {
this.#Ue();
} else if (e === "ENOENT") {
this.#$e();
} else {
this.children().provisional = 0;
}
}
#Fe(e = "") {
if (e === "ENOTDIR") {
const e = this.parent;
e.#Ue();
} else if (e === "ENOENT") {
this.#$e();
}
}
#De(e = "") {
let t = this.#Oe;
t |= x;
if (e === "ENOENT") t |= $;
if (e === "EINVAL" || e === "UNKNOWN") {
t &= P;
}
this.#Oe = t;
if (e === "ENOTDIR" && this.parent) {
this.parent.#Ue();
}
}
#je(e, t) {
return this.#ke(e, t) || this.#Qe(e, t);
}
#Qe(e, t) {
const n = F(e);
const a = this.newChild(e.name, n, {
parent: this
});
const r = a.#Oe & I;
if (r !== S && r !== O && r !== b) {
a.#Oe |= _;
}
t.unshift(a);
t.provisional++;
return a;
}
#ke(e, t) {
for (let n = t.provisional; n < t.length; n++) {
const a = t[n];
const r = this.nocase ? V(e.name) : k(e.name);
if (r !== a.#be) {
continue;
}
return this.#Ve(e, a, n, t);
}
}
#Ve(e, t, n, a) {
const r = t.name;
t.#Oe = t.#Oe & P | F(e);
if (r !== e.name) t.name = e.name;
if (n !== a.provisional) {
if (n === a.length - 1) a.pop(); else a.splice(n, 1);
a.unshift(t);
}
a.provisional++;
return t;
}
async lstat() {
if ((this.#Oe & $) === 0) {
try {
this.#Ke(await this.#re.promises.lstat(this.fullpath()));
return this;
} catch (e) {
this.#Fe(e.code);
}
}
}
lstatSync() {
if ((this.#Oe & $) === 0) {
try {
this.#Ke(this.#re.lstatSync(this.fullpath()));
return this;
} catch (e) {
this.#Fe(e.code);
}
}
}
#Ke(e) {
const {atime: t, atimeMs: n, birthtime: a, birthtimeMs: r, blksize: i, blocks: s, ctime: o, ctimeMs: c, dev: l, gid: u, ino: h, mode: d, mtime: p, mtimeMs: m, nlink: f, rdev: y, size: E, uid: T} = e;
this.#Te = t;
this.#me = n;
this.#Ae = a;
this.#Ee = r;
this.#he = i;
this.#pe = s;
this.#Ne = o;
this.#ye = c;
this.#ie = l;
this.#le = u;
this.#de = h;
this.#se = d;
this.#ge = p;
this.#fe = m;
this.#oe = f;
this.#ue = y;
this.#b = E;
this.#ce = T;
const g = F(e);
this.#Oe = this.#Oe & P | g | D;
if (g !== b && g !== S && g !== O) {
this.#Oe |= _;
}
}
#We=[];
#He=false;
#Ge(e) {
this.#He = false;
const t = this.#We.slice();
this.#We.length = 0;
t.forEach(t => t(null, e));
}
readdirCB(e, t = false) {
if (!this.canReaddir()) {
if (t) e(null, []); else queueMicrotask(() => e(null, []));
return;
}
const n = this.children();
if (this.calledReaddir()) {
const a = n.slice(0, n.provisional);
if (t) e(null, a); else queueMicrotask(() => e(null, a));
return;
}
this.#We.push(e);
if (this.#He) {
return;
}
this.#He = true;
const a = this.fullpath();
this.#re.readdir(a, {
withFileTypes: true
}, (e, t) => {
if (e) {
this.#Be(e.code);
n.provisional = 0;
} else {
for (const e of t) {
this.#je(e, n);
}
this.#_e(n);
}
this.#Ge(n.slice(0, n.provisional));
return;
});
}
#Ye;
async readdir() {
if (!this.canReaddir()) {
return [];
}
const e = this.children();
if (this.calledReaddir()) {
return e.slice(0, e.provisional);
}
const t = this.fullpath();
if (this.#Ye) {
await this.#Ye;
} else {
let n = () => {};
this.#Ye = new Promise(e => n = e);
try {
for (const n of await this.#re.promises.readdir(t, {
withFileTypes: true
})) {
this.#je(n, e);
}
this.#_e(e);
} catch (t) {
this.#Be(t.code);
e.provisional = 0;
}
this.#Ye = undefined;
n();
}
return e.slice(0, e.provisional);
}
readdirSync() {
if (!this.canReaddir()) {
return [];
}
const e = this.children();
if (this.calledReaddir()) {
return e.slice(0, e.provisional);
}
const t = this.fullpath();
try {
for (const n of this.#re.readdirSync(t, {
withFileTypes: true
})) {
this.#je(n, e);
}
this.#_e(e);
} catch (t) {
this.#Be(t.code);
e.provisional = 0;
}
return e.slice(0, e.provisional);
}
canReaddir() {
if (this.#Oe & U) return false;
const e = I & this.#Oe;
if (!(e === b || e === S || e === O)) {
return false;
}
return true;
}
shouldWalk(e, t) {
return (this.#Oe & S) === S && !(this.#Oe & U) && !e.has(this) && (!t || t(this));
}
async realpath() {
if (this.#Pe) return this.#Pe;
if ((q | x | $) & this.#Oe) return undefined;
try {
const e = await this.#re.promises.realpath(this.fullpath());
return this.#Pe = this.resolve(e);
} catch (e) {
this.#qe();
}
}
realpathSync() {
if (this.#Pe) return this.#Pe;
if ((q | x | $) & this.#Oe) return undefined;
try {
const e = this.#re.realpathSync(this.fullpath());
return this.#Pe = this.resolve(e);
} catch (e) {
this.#qe();
}
}
[K](e) {
if (e === this) return;
e.isCWD = false;
this.isCWD = true;
const t = new Set([]);
let n = [];
let a = this;
while (a && a.parent) {
t.add(a);
a.#we = n.join(this.sep);
a.#Me = n.join("/");
a = a.parent;
n.push("..");
}
a = e;
while (a && a.parent && !t.has(a)) {
a.#we = undefined;
a.#Me = undefined;
a = a.parent;
}
}
}
ZC.PathBase = PathBase;
class PathWin32 extends PathBase {
sep="\\";
splitSep=A;
constructor(e, t = b, n, a, r, i, s) {
super(e, t, n, a, r, i, s);
}
newChild(e, t = b, n = {}) {
return new PathWin32(e, t, this.root, this.roots, this.nocase, this.childrenCache(), n);
}
getRootString(e) {
return i.win32.parse(e).root;
}
getRoot(e) {
e = y(e.toUpperCase());
if (e === this.root.name) {
return this.root;
}
for (const [t, n] of Object.entries(this.roots)) {
if (this.sameRoot(e, t)) {
return this.roots[e] = n;
}
}
return this.roots[e] = new PathScurryWin32(e, this).root;
}
sameRoot(e, t = this.root.name) {
e = e.toUpperCase().replace(/\//g, "\\").replace(f, "$1\\");
return e === t;
}
}
ZC.PathWin32 = PathWin32;
class PathPosix extends PathBase {
splitSep="/";
sep="/";
constructor(e, t = b, n, a, r, i, s) {
super(e, t, n, a, r, i, s);
}
getRootString(e) {
return e.startsWith("/") ? "/" : "";
}
getRoot(e) {
return this.root;
}
newChild(e, t = b, n = {}) {
return new PathPosix(e, t, this.root, this.roots, this.nocase, this.childrenCache(), n);
}
}
ZC.PathPosix = PathPosix;
class PathScurryBase {
root;
rootPath;
roots;
cwd;
#ze;
#Je;
#ve;
nocase;
#re;
constructor(e = process.cwd(), t, n, {nocase: a, childrenCacheSize: r = 16 * 1024, fs: i = p} = {}) {
this.#re = m(i);
if (e instanceof URL || e.startsWith("file://")) {
e = (0, s.fileURLToPath)(e);
}
const o = t.resolve(e);
this.roots = Object.create(null);
this.rootPath = this.parseRootPath(o);
this.#ze = new ResolveCache;
this.#Je = new ResolveCache;
this.#ve = new ChildrenCache(r);
const c = o.substring(this.rootPath.length).split(n);
if (c.length === 1 && !c[0]) {
c.pop();
}
if (a === undefined) {
throw new TypeError("must provide nocase setting to PathScurryBase ctor");
}
this.nocase = a;
this.root = this.newRoot(this.#re);
this.roots[this.rootPath] = this.root;
let l = this.root;
let u = c.length - 1;
const h = t.sep;
let d = this.rootPath;
let f = false;
for (const e of c) {
const t = u--;
l = l.child(e, {
relative: new Array(t).fill("..").join(h),
relativePosix: new Array(t).fill("..").join("/"),
fullpath: d += (f ? "" : h) + e
});
f = true;
}
this.cwd = l;
}
depth(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.depth();
}
childrenCache() {
return this.#ve;
}
resolve(...e) {
let t = "";
for (let n = e.length - 1; n >= 0; n--) {
const a = e[n];
if (!a || a === ".") continue;
t = t ? `${a}/${t}` : a;
if (this.isAbsolute(a)) {
break;
}
}
const n = this.#ze.get(t);
if (n !== undefined) {
return n;
}
const a = this.cwd.resolve(t).fullpath();
this.#ze.set(t, a);
return a;
}
resolvePosix(...e) {
let t = "";
for (let n = e.length - 1; n >= 0; n--) {
const a = e[n];
if (!a || a === ".") continue;
t = t ? `${a}/${t}` : a;
if (this.isAbsolute(a)) {
break;
}
}
const n = this.#Je.get(t);
if (n !== undefined) {
return n;
}
const a = this.cwd.resolve(t).fullpathPosix();
this.#Je.set(t, a);
return a;
}
relative(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.relative();
}
relativePosix(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.relativePosix();
}
basename(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.name;
}
dirname(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return (e.parent || e).fullpath();
}
async readdir(e = this.cwd, t = {
withFileTypes: true
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n} = t;
if (!e.canReaddir()) {
return [];
} else {
const t = await e.readdir();
return n ? t : t.map(e => e.name);
}
}
readdirSync(e = this.cwd, t = {
withFileTypes: true
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true} = t;
if (!e.canReaddir()) {
return [];
} else if (n) {
return e.readdirSync();
} else {
return e.readdirSync().map(e => e.name);
}
}
async lstat(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.lstat();
}
lstatSync(e = this.cwd) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
}
return e.lstatSync();
}
async readlink(e = this.cwd, {withFileTypes: t} = {
withFileTypes: false
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e.withFileTypes;
e = this.cwd;
}
const n = await e.readlink();
return t ? n : n?.fullpath();
}
readlinkSync(e = this.cwd, {withFileTypes: t} = {
withFileTypes: false
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e.withFileTypes;
e = this.cwd;
}
const n = e.readlinkSync();
return t ? n : n?.fullpath();
}
async realpath(e = this.cwd, {withFileTypes: t} = {
withFileTypes: false
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e.withFileTypes;
e = this.cwd;
}
const n = await e.realpath();
return t ? n : n?.fullpath();
}
realpathSync(e = this.cwd, {withFileTypes: t} = {
withFileTypes: false
}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e.withFileTypes;
e = this.cwd;
}
const n = e.realpathSync();
return t ? n : n?.fullpath();
}
async walk(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true, follow: a = false, filter: r, walkFilter: i} = t;
const s = [];
if (!r || r(e)) {
s.push(n ? e : e.fullpath());
}
const o = new Set;
const c = (e, t) => {
o.add(e);
e.readdirCB((e, l) => {
if (e) {
return t(e);
}
let u = l.length;
if (!u) return t();
const h = () => {
if (--u === 0) {
t();
}
};
for (const e of l) {
if (!r || r(e)) {
s.push(n ? e : e.fullpath());
}
if (a && e.isSymbolicLink()) {
e.realpath().then(e => e?.isUnknown() ? e.lstat() : e).then(e => e?.shouldWalk(o, i) ? c(e, h) : h());
} else {
if (e.shouldWalk(o, i)) {
c(e, h);
} else {
h();
}
}
}
}, true);
};
const l = e;
return new Promise((e, t) => {
c(l, n => {
if (n) return t(n);
e(s);
});
});
}
walkSync(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true, follow: a = false, filter: r, walkFilter: i} = t;
const s = [];
if (!r || r(e)) {
s.push(n ? e : e.fullpath());
}
const o = new Set([ e ]);
for (const e of o) {
const t = e.readdirSync();
for (const e of t) {
if (!r || r(e)) {
s.push(n ? e : e.fullpath());
}
let t = e;
if (e.isSymbolicLink()) {
if (!(a && (t = e.realpathSync()))) continue;
if (t.isUnknown()) t.lstatSync();
}
if (t.shouldWalk(o, i)) {
o.add(t);
}
}
}
return s;
}
[Symbol.asyncIterator]() {
return this.iterate();
}
iterate(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
return this.stream(e, t)[Symbol.asyncIterator]();
}
[Symbol.iterator]() {
return this.iterateSync();
}
* iterateSync(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true, follow: a = false, filter: r, walkFilter: i} = t;
if (!r || r(e)) {
yield n ? e : e.fullpath();
}
const s = new Set([ e ]);
for (const e of s) {
const t = e.readdirSync();
for (const e of t) {
if (!r || r(e)) {
yield n ? e : e.fullpath();
}
let t = e;
if (e.isSymbolicLink()) {
if (!(a && (t = e.realpathSync()))) continue;
if (t.isUnknown()) t.lstatSync();
}
if (t.shouldWalk(s, i)) {
s.add(t);
}
}
}
}
stream(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true, follow: a = false, filter: r, walkFilter: i} = t;
const s = new d.Minipass({
objectMode: true
});
if (!r || r(e)) {
s.write(n ? e : e.fullpath());
}
const o = new Set;
const c = [ e ];
let l = 0;
const u = () => {
let e = false;
while (!e) {
const t = c.shift();
if (!t) {
if (l === 0) s.end();
return;
}
l++;
o.add(t);
const h = (t, p, m = false) => {
if (t) return s.emit("error", t);
if (a && !m) {
const e = [];
for (const t of p) {
if (t.isSymbolicLink()) {
e.push(t.realpath().then(e => e?.isUnknown() ? e.lstat() : e));
}
}
if (e.length) {
Promise.all(e).then(() => h(null, p, true));
return;
}
}
for (const t of p) {
if (t && (!r || r(t))) {
if (!s.write(n ? t : t.fullpath())) {
e = true;
}
}
}
l--;
for (const e of p) {
const t = e.realpathCached() || e;
if (t.shouldWalk(o, i)) {
c.push(t);
}
}
if (e && !s.flowing) {
s.once("drain", u);
} else if (!d) {
u();
}
};
let d = true;
t.readdirCB(h, true);
d = false;
}
};
u();
return s;
}
streamSync(e = this.cwd, t = {}) {
if (typeof e === "string") {
e = this.cwd.resolve(e);
} else if (!(e instanceof PathBase)) {
t = e;
e = this.cwd;
}
const {withFileTypes: n = true, follow: a = false, filter: r, walkFilter: i} = t;
const s = new d.Minipass({
objectMode: true
});
const o = new Set;
if (!r || r(e)) {
s.write(n ? e : e.fullpath());
}
const c = [ e ];
let l = 0;
const u = () => {
let e = false;
while (!e) {
const t = c.shift();
if (!t) {
if (l === 0) s.end();
return;
}
l++;
o.add(t);
const u = t.readdirSync();
for (const t of u) {
if (!r || r(t)) {
if (!s.write(n ? t : t.fullpath())) {
e = true;
}
}
}
l--;
for (const e of u) {
let t = e;
if (e.isSymbolicLink()) {
if (!(a && (t = e.realpathSync()))) continue;
if (t.isUnknown()) t.lstatSync();
}
if (t.shouldWalk(o, i)) {
c.push(t);
}
}
}
if (e && !s.flowing) s.once("drain", u);
};
u();
return s;
}
chdir(e = this.cwd) {
const t = this.cwd;
this.cwd = typeof e === "string" ? this.cwd.resolve(e) : e;
this.cwd[K](t);
}
}
ZC.PathScurryBase = PathScurryBase;
class PathScurryWin32 extends PathScurryBase {
sep="\\";
constructor(e = process.cwd(), t = {}) {
const {nocase: n = true} = t;
super(e, i.win32, "\\", {
...t,
nocase: n
});
this.nocase = n;
for (let e = this.cwd; e; e = e.parent) {
e.nocase = this.nocase;
}
}
parseRootPath(e) {
return i.win32.parse(e).root.toUpperCase();
}
newRoot(e) {
return new PathWin32(this.rootPath, S, undefined, this.roots, this.nocase, this.childrenCache(), {
fs: e
});
}
isAbsolute(e) {
return e.startsWith("/") || e.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(e);
}
}
ZC.PathScurryWin32 = PathScurryWin32;
class PathScurryPosix extends PathScurryBase {
sep="/";
constructor(e = process.cwd(), t = {}) {
const {nocase: n = false} = t;
super(e, i.posix, "/", {
...t,
nocase: n
});
this.nocase = n;
}
parseRootPath(e) {
return "/";
}
newRoot(e) {
return new PathPosix(this.rootPath, S, undefined, this.roots, this.nocase, this.childrenCache(), {
fs: e
});
}
isAbsolute(e) {
return e.startsWith("/");
}
}
ZC.PathScurryPosix = PathScurryPosix;
class PathScurryDarwin extends PathScurryPosix {
constructor(e = process.cwd(), t = {}) {
const {nocase: n = true} = t;
super(e, {
...t,
nocase: n
});
}
}
ZC.PathScurryDarwin = PathScurryDarwin;
ZC.Path = process.platform === "win32" ? PathWin32 : PathPosix;
ZC.PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
return ZC;
}
var cR = {};
var lR;
function uR() {
if (lR) return cR;
lR = 1;
Object.defineProperty(cR, "__esModule", {
value: true
});
cR.Pattern = void 0;
const e = JC();
const t = e => e.length >= 1;
const n = e => e.length >= 1;
class Pattern {
#Xe;
#Ze;
#et;
length;
#tt;
#nt;
#at;
#rt;
#it;
#st;
#ot=true;
constructor(e, a, r, i) {
if (!t(e)) {
throw new TypeError("empty pattern list");
}
if (!n(a)) {
throw new TypeError("empty glob list");
}
if (a.length !== e.length) {
throw new TypeError("mismatched pattern list and glob list lengths");
}
this.length = e.length;
if (r < 0 || r >= this.length) {
throw new TypeError("index out of range");
}
this.#Xe = e;
this.#Ze = a;
this.#et = r;
this.#tt = i;
if (this.#et === 0) {
if (this.isUNC()) {
const [e, t, n, a, ...r] = this.#Xe;
const [i, s, o, c, ...l] = this.#Ze;
if (r[0] === "") {
r.shift();
l.shift();
}
const u = [ e, t, n, a, "" ].join("/");
const h = [ i, s, o, c, "" ].join("/");
this.#Xe = [ u, ...r ];
this.#Ze = [ h, ...l ];
this.length = this.#Xe.length;
} else if (this.isDrive() || this.isAbsolute()) {
const [e, ...t] = this.#Xe;
const [n, ...a] = this.#Ze;
if (t[0] === "") {
t.shift();
a.shift();
}
const r = e + "/";
const i = n + "/";
this.#Xe = [ r, ...t ];
this.#Ze = [ i, ...a ];
this.length = this.#Xe.length;
}
}
}
pattern() {
return this.#Xe[this.#et];
}
isString() {
return typeof this.#Xe[this.#et] === "string";
}
isGlobstar() {
return this.#Xe[this.#et] === e.GLOBSTAR;
}
isRegExp() {
return this.#Xe[this.#et] instanceof RegExp;
}
globString() {
return this.#at = this.#at || (this.#et === 0 ? this.isAbsolute() ? this.#Ze[0] + this.#Ze.slice(1).join("/") : this.#Ze.join("/") : this.#Ze.slice(this.#et).join("/"));
}
hasMore() {
return this.length > this.#et + 1;
}
rest() {
if (this.#nt !== undefined) return this.#nt;
if (!this.hasMore()) return this.#nt = null;
this.#nt = new Pattern(this.#Xe, this.#Ze, this.#et + 1, this.#tt);
this.#nt.#st = this.#st;
this.#nt.#it = this.#it;
this.#nt.#rt = this.#rt;
return this.#nt;
}
isUNC() {
const e = this.#Xe;
return this.#it !== undefined ? this.#it : this.#it = this.#tt === "win32" && this.#et === 0 && e[0] === "" && e[1] === "" && typeof e[2] === "string" && !!e[2] && typeof e[3] === "string" && !!e[3];
}
isDrive() {
const e = this.#Xe;
return this.#rt !== undefined ? this.#rt : this.#rt = this.#tt === "win32" && this.#et === 0 && this.length > 1 && typeof e[0] === "string" && /^[a-z]:$/i.test(e[0]);
}
isAbsolute() {
const e = this.#Xe;
return this.#st !== undefined ? this.#st : this.#st = e[0] === "" && e.length > 1 || this.isDrive() || this.isUNC();
}
root() {
const e = this.#Xe[0];
return typeof e === "string" && this.isAbsolute() && this.#et === 0 ? e : "";
}
checkFollowGlobstar() {
return !(this.#et === 0 || !this.isGlobstar() || !this.#ot);
}
markFollowGlobstar() {
if (this.#et === 0 || !this.isGlobstar() || !this.#ot) return false;
this.#ot = false;
return true;
}
}
cR.Pattern = Pattern;
return cR;
}
var hR = {};
var dR = {};
var pR;
function mR() {
if (pR) return dR;
pR = 1;
Object.defineProperty(dR, "__esModule", {
value: true
});
dR.Ignore = void 0;
const e = JC();
const t = uR();
const n = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
class Ignore {
relative;
relativeChildren;
absolute;
absoluteChildren;
platform;
mmopts;
constructor(e, {nobrace: t, nocase: a, noext: r, noglobstar: i, platform: s = n}) {
this.relative = [];
this.absolute = [];
this.relativeChildren = [];
this.absoluteChildren = [];
this.platform = s;
this.mmopts = {
dot: true,
nobrace: t,
nocase: a,
noext: r,
noglobstar: i,
optimizationLevel: 2,
platform: s,
nocomment: true,
nonegate: true
};
for (const t of e) this.add(t);
}
add(n) {
const a = new e.Minimatch(n, this.mmopts);
for (let n = 0; n < a.set.length; n++) {
const r = a.set[n];
const i = a.globParts[n];
if (!r || !i) {
throw new Error("invalid pattern object");
}
while (r[0] === "." && i[0] === ".") {
r.shift();
i.shift();
}
const s = new t.Pattern(r, i, 0, this.platform);
const o = new e.Minimatch(s.globString(), this.mmopts);
const c = i[i.length - 1] === "**";
const l = s.isAbsolute();
if (l) this.absolute.push(o); else this.relative.push(o);
if (c) {
if (l) this.absoluteChildren.push(o); else this.relativeChildren.push(o);
}
}
}
ignored(e) {
const t = e.fullpath();
const n = `${t}/`;
const a = e.relative() || ".";
const r = `${a}/`;
for (const e of this.relative) {
if (e.match(a) || e.match(r)) return true;
}
for (const e of this.absolute) {
if (e.match(t) || e.match(n)) return true;
}
return false;
}
childrenIgnored(e) {
const t = e.fullpath() + "/";
const n = (e.relative() || ".") + "/";
for (const e of this.relativeChildren) {
if (e.match(n)) return true;
}
for (const e of this.absoluteChildren) {
if (e.match(t)) return true;
}
return false;
}
}
dR.Ignore = Ignore;
return dR;
}
var fR = {};
var yR;
function ER() {
if (yR) return fR;
yR = 1;
Object.defineProperty(fR, "__esModule", {
value: true
});
fR.Processor = fR.SubWalks = fR.MatchRecord = fR.HasWalkedCache = void 0;
const e = JC();
class HasWalkedCache {
store;
constructor(e = new Map) {
this.store = e;
}
copy() {
return new HasWalkedCache(new Map(this.store));
}
hasWalked(e, t) {
return this.store.get(e.fullpath())?.has(t.globString());
}
storeWalked(e, t) {
const n = e.fullpath();
const a = this.store.get(n);
if (a) a.add(t.globString()); else this.store.set(n, new Set([ t.globString() ]));
}
}
fR.HasWalkedCache = HasWalkedCache;
class MatchRecord {
store=new Map;
add(e, t, n) {
const a = (t ? 2 : 0) | (n ? 1 : 0);
const r = this.store.get(e);
this.store.set(e, r === undefined ? a : a & r);
}
entries() {
return [ ...this.store.entries() ].map(([e, t]) => [ e, !!(t & 2), !!(t & 1) ]);
}
}
fR.MatchRecord = MatchRecord;
class SubWalks {
store=new Map;
add(e, t) {
if (!e.canReaddir()) {
return;
}
const n = this.store.get(e);
if (n) {
if (!n.find(e => e.globString() === t.globString())) {
n.push(t);
}
} else this.store.set(e, [ t ]);
}
get(e) {
const t = this.store.get(e);
if (!t) {
throw new Error("attempting to walk unknown path");
}
return t;
}
entries() {
return this.keys().map(e => [ e, this.store.get(e) ]);
}
keys() {
return [ ...this.store.keys() ].filter(e => e.canReaddir());
}
}
fR.SubWalks = SubWalks;
class Processor {
hasWalkedCache;
matches=new MatchRecord;
subwalks=new SubWalks;
patterns;
follow;
dot;
opts;
constructor(e, t) {
this.opts = e;
this.follow = !!e.follow;
this.dot = !!e.dot;
this.hasWalkedCache = t ? t.copy() : new HasWalkedCache;
}
processPatterns(t, n) {
this.patterns = n;
const a = n.map(e => [ t, e ]);
for (let [t, n] of a) {
this.hasWalkedCache.storeWalked(t, n);
const a = n.root();
const r = n.isAbsolute() && this.opts.absolute !== false;
if (a) {
t = t.resolve(a === "/" && this.opts.root !== undefined ? this.opts.root : a);
const e = n.rest();
if (!e) {
this.matches.add(t, true, false);
continue;
} else {
n = e;
}
}
if (t.isENOENT()) continue;
let i;
let s;
let o = false;
while (typeof (i = n.pattern()) === "string" && (s = n.rest())) {
const e = t.resolve(i);
t = e;
n = s;
o = true;
}
i = n.pattern();
s = n.rest();
if (o) {
if (this.hasWalkedCache.hasWalked(t, n)) continue;
this.hasWalkedCache.storeWalked(t, n);
}
if (typeof i === "string") {
const e = i === ".." || i === "" || i === ".";
this.matches.add(t.resolve(i), r, e);
continue;
} else if (i === e.GLOBSTAR) {
if (!t.isSymbolicLink() || this.follow || n.checkFollowGlobstar()) {
this.subwalks.add(t, n);
}
const e = s?.pattern();
const a = s?.rest();
if (!s || (e === "" || e === ".") && !a) {
this.matches.add(t, r, e === "" || e === ".");
} else {
if (e === "..") {
const e = t.parent || t;
if (!a) this.matches.add(e, r, true); else if (!this.hasWalkedCache.hasWalked(e, a)) {
this.subwalks.add(e, a);
}
}
}
} else if (i instanceof RegExp) {
this.subwalks.add(t, n);
}
}
return this;
}
subwalkTargets() {
return this.subwalks.keys();
}
child() {
return new Processor(this.opts, this.hasWalkedCache);
}
filterEntries(t, n) {
const a = this.subwalks.get(t);
const r = this.child();
for (const t of n) {
for (const n of a) {
const a = n.isAbsolute();
const i = n.pattern();
const s = n.rest();
if (i === e.GLOBSTAR) {
r.testGlobstar(t, n, s, a);
} else if (i instanceof RegExp) {
r.testRegExp(t, i, s, a);
} else {
r.testString(t, i, s, a);
}
}
}
return r;
}
testGlobstar(e, t, n, a) {
if (this.dot || !e.name.startsWith(".")) {
if (!t.hasMore()) {
this.matches.add(e, a, false);
}
if (e.canReaddir()) {
if (this.follow || !e.isSymbolicLink()) {
this.subwalks.add(e, t);
} else if (e.isSymbolicLink()) {
if (n && t.checkFollowGlobstar()) {
this.subwalks.add(e, n);
} else if (t.markFollowGlobstar()) {
this.subwalks.add(e, t);
}
}
}
}
if (n) {
const t = n.pattern();
if (typeof t === "string" && t !== ".." && t !== "" && t !== ".") {
this.testString(e, t, n.rest(), a);
} else if (t === "..") {
const t = e.parent || e;
this.subwalks.add(t, n);
} else if (t instanceof RegExp) {
this.testRegExp(e, t, n.rest(), a);
}
}
}
testRegExp(e, t, n, a) {
if (!t.test(e.name)) return;
if (!n) {
this.matches.add(e, a, false);
} else {
this.subwalks.add(e, n);
}
}
testString(e, t, n, a) {
if (!e.isNamed(t)) return;
if (!n) {
this.matches.add(e, a, false);
} else {
this.subwalks.add(e, n);
}
}
}
fR.Processor = Processor;
return fR;
}
var TR;
function gR() {
if (TR) return hR;
TR = 1;
Object.defineProperty(hR, "__esModule", {
value: true
});
hR.GlobStream = hR.GlobWalker = hR.GlobUtil = void 0;
const e = iR();
const t = mR();
const n = ER();
const a = (e, n) => typeof e === "string" ? new t.Ignore([ e ], n) : Array.isArray(e) ? new t.Ignore(e, n) : e;
class GlobUtil {
path;
patterns;
opts;
seen=new Set;
paused=false;
aborted=false;
#ct=[];
#lt;
#ut;
signal;
maxDepth;
includeChildMatches;
constructor(e, t, n) {
this.patterns = e;
this.path = t;
this.opts = n;
this.#ut = !n.posix && n.platform === "win32" ? "\\" : "/";
this.includeChildMatches = n.includeChildMatches !== false;
if (n.ignore || !this.includeChildMatches) {
this.#lt = a(n.ignore ?? [], n);
if (!this.includeChildMatches && typeof this.#lt.add !== "function") {
const e = "cannot ignore child matches, ignore lacks add() method.";
throw new Error(e);
}
}
this.maxDepth = n.maxDepth || Infinity;
if (n.signal) {
this.signal = n.signal;
this.signal.addEventListener("abort", () => {
this.#ct.length = 0;
});
}
}
#ht(e) {
return this.seen.has(e) || !!this.#lt?.ignored?.(e);
}
#dt(e) {
return !!this.#lt?.childrenIgnored?.(e);
}
pause() {
this.paused = true;
}
resume() {
if (this.signal?.aborted) return;
this.paused = false;
let e = undefined;
while (!this.paused && (e = this.#ct.shift())) {
e();
}
}
onResume(e) {
if (this.signal?.aborted) return;
if (!this.paused) {
e();
} else {
this.#ct.push(e);
}
}
async matchCheck(e, t) {
if (t && this.opts.nodir) return undefined;
let n;
if (this.opts.realpath) {
n = e.realpathCached() || await e.realpath();
if (!n) return undefined;
e = n;
}
const a = e.isUnknown() || this.opts.stat;
const r = a ? await e.lstat() : e;
if (this.opts.follow && this.opts.nodir && r?.isSymbolicLink()) {
const e = await r.realpath();
if (e && (e.isUnknown() || this.opts.stat)) {
await e.lstat();
}
}
return this.matchCheckTest(r, t);
}
matchCheckTest(e, t) {
return e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!t || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e.isSymbolicLink() || !e.realpathCached()?.isDirectory()) && !this.#ht(e) ? e : undefined;
}
matchCheckSync(e, t) {
if (t && this.opts.nodir) return undefined;
let n;
if (this.opts.realpath) {
n = e.realpathCached() || e.realpathSync();
if (!n) return undefined;
e = n;
}
const a = e.isUnknown() || this.opts.stat;
const r = a ? e.lstatSync() : e;
if (this.opts.follow && this.opts.nodir && r?.isSymbolicLink()) {
const e = r.realpathSync();
if (e && (e?.isUnknown() || this.opts.stat)) {
e.lstatSync();
}
}
return this.matchCheckTest(r, t);
}
matchFinish(e, t) {
if (this.#ht(e)) return;
if (!this.includeChildMatches && this.#lt?.add) {
const t = `${e.relativePosix()}/**`;
this.#lt.add(t);
}
const n = this.opts.absolute === undefined ? t : this.opts.absolute;
this.seen.add(e);
const a = this.opts.mark && e.isDirectory() ? this.#ut : "";
if (this.opts.withFileTypes) {
this.matchEmit(e);
} else if (n) {
const t = this.opts.posix ? e.fullpathPosix() : e.fullpath();
this.matchEmit(t + a);
} else {
const t = this.opts.posix ? e.relativePosix() : e.relative();
const n = this.opts.dotRelative && !t.startsWith(".." + this.#ut) ? "." + this.#ut : "";
this.matchEmit(!t ? "." + a : n + t + a);
}
}
async match(e, t, n) {
const a = await this.matchCheck(e, n);
if (a) this.matchFinish(a, t);
}
matchSync(e, t, n) {
const a = this.matchCheckSync(e, n);
if (a) this.matchFinish(a, t);
}
walkCB(e, t, a) {
if (this.signal?.aborted) a();
this.walkCB2(e, t, new n.Processor(this.opts), a);
}
walkCB2(e, t, n, a) {
if (this.#dt(e)) return a();
if (this.signal?.aborted) a();
if (this.paused) {
this.onResume(() => this.walkCB2(e, t, n, a));
return;
}
n.processPatterns(e, t);
let r = 1;
const i = () => {
if (--r === 0) a();
};
for (const [e, t, a] of n.matches.entries()) {
if (this.#ht(e)) continue;
r++;
this.match(e, t, a).then(() => i());
}
for (const e of n.subwalkTargets()) {
if (this.maxDepth !== Infinity && e.depth() >= this.maxDepth) {
continue;
}
r++;
const t = e.readdirCached();
if (e.calledReaddir()) this.walkCB3(e, t, n, i); else {
e.readdirCB((t, a) => this.walkCB3(e, a, n, i), true);
}
}
i();
}
walkCB3(e, t, n, a) {
n = n.filterEntries(e, t);
let r = 1;
const i = () => {
if (--r === 0) a();
};
for (const [e, t, a] of n.matches.entries()) {
if (this.#ht(e)) continue;
r++;
this.match(e, t, a).then(() => i());
}
for (const [e, t] of n.subwalks.entries()) {
r++;
this.walkCB2(e, t, n.child(), i);
}
i();
}
walkCBSync(e, t, a) {
if (this.signal?.aborted) a();
this.walkCB2Sync(e, t, new n.Processor(this.opts), a);
}
walkCB2Sync(e, t, n, a) {
if (this.#dt(e)) return a();
if (this.signal?.aborted) a();
if (this.paused) {
this.onResume(() => this.walkCB2Sync(e, t, n, a));
return;
}
n.processPatterns(e, t);
let r = 1;
const i = () => {
if (--r === 0) a();
};
for (const [e, t, a] of n.matches.entries()) {
if (this.#ht(e)) continue;
this.matchSync(e, t, a);
}
for (const e of n.subwalkTargets()) {
if (this.maxDepth !== Infinity && e.depth() >= this.maxDepth) {
continue;
}
r++;
const t = e.readdirSync();
this.walkCB3Sync(e, t, n, i);
}
i();
}
walkCB3Sync(e, t, n, a) {
n = n.filterEntries(e, t);
let r = 1;
const i = () => {
if (--r === 0) a();
};
for (const [e, t, a] of n.matches.entries()) {
if (this.#ht(e)) continue;
this.matchSync(e, t, a);
}
for (const [e, t] of n.subwalks.entries()) {
r++;
this.walkCB2Sync(e, t, n.child(), i);
}
i();
}
}
hR.GlobUtil = GlobUtil;
class GlobWalker extends GlobUtil {
matches=new Set;
constructor(e, t, n) {
super(e, t, n);
}
matchEmit(e) {
this.matches.add(e);
}
async walk() {
if (this.signal?.aborted) throw this.signal.reason;
if (this.path.isUnknown()) {
await this.path.lstat();
}
await new Promise((e, t) => {
this.walkCB(this.path, this.patterns, () => {
if (this.signal?.aborted) {
t(this.signal.reason);
} else {
e(this.matches);
}
});
});
return this.matches;
}
walkSync() {
if (this.signal?.aborted) throw this.signal.reason;
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => {
if (this.signal?.aborted) throw this.signal.reason;
});
return this.matches;
}
}
hR.GlobWalker = GlobWalker;
class GlobStream extends GlobUtil {
results;
constructor(t, n, a) {
super(t, n, a);
this.results = new e.Minipass({
signal: this.signal,
objectMode: true
});
this.results.on("drain", () => this.resume());
this.results.on("resume", () => this.resume());
}
matchEmit(e) {
this.results.write(e);
if (!this.results.flowing) this.pause();
}
stream() {
const e = this.path;
if (e.isUnknown()) {
e.lstat().then(() => {
this.walkCB(e, this.patterns, () => this.results.end());
});
} else {
this.walkCB(e, this.patterns, () => this.results.end());
}
return this.results;
}
streamSync() {
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => this.results.end());
return this.results;
}
}
hR.GlobStream = GlobStream;
return hR;
}
var NR;
function AR() {
if (NR) return XC;
NR = 1;
Object.defineProperty(XC, "__esModule", {
value: true
});
XC.Glob = void 0;
const e = JC();
const t = E;
const n = oR();
const a = uR();
const r = gR();
const i = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
class Glob {
absolute;
cwd;
root;
dot;
dotRelative;
follow;
ignore;
magicalBraces;
mark;
matchBase;
maxDepth;
nobrace;
nocase;
nodir;
noext;
noglobstar;
pattern;
platform;
realpath;
scurry;
stat;
signal;
windowsPathsNoEscape;
withFileTypes;
includeChildMatches;
opts;
patterns;
constructor(r, s) {
if (!s) throw new TypeError("glob options required");
this.withFileTypes = !!s.withFileTypes;
this.signal = s.signal;
this.follow = !!s.follow;
this.dot = !!s.dot;
this.dotRelative = !!s.dotRelative;
this.nodir = !!s.nodir;
this.mark = !!s.mark;
if (!s.cwd) {
this.cwd = "";
} else if (s.cwd instanceof URL || s.cwd.startsWith("file://")) {
s.cwd = (0, t.fileURLToPath)(s.cwd);
}
this.cwd = s.cwd || "";
this.root = s.root;
this.magicalBraces = !!s.magicalBraces;
this.nobrace = !!s.nobrace;
this.noext = !!s.noext;
this.realpath = !!s.realpath;
this.absolute = s.absolute;
this.includeChildMatches = s.includeChildMatches !== false;
this.noglobstar = !!s.noglobstar;
this.matchBase = !!s.matchBase;
this.maxDepth = typeof s.maxDepth === "number" ? s.maxDepth : Infinity;
this.stat = !!s.stat;
this.ignore = s.ignore;
if (this.withFileTypes && this.absolute !== undefined) {
throw new Error("cannot set absolute and withFileTypes:true");
}
if (typeof r === "string") {
r = [ r ];
}
this.windowsPathsNoEscape = !!s.windowsPathsNoEscape || s.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
r = r.map(e => e.replace(/\\/g, "/"));
}
if (this.matchBase) {
if (s.noglobstar) {
throw new TypeError("base matching requires globstar");
}
r = r.map(e => e.includes("/") ? e : `./**/${e}`);
}
this.pattern = r;
this.platform = s.platform || i;
this.opts = {
...s,
platform: this.platform
};
if (s.scurry) {
this.scurry = s.scurry;
if (s.nocase !== undefined && s.nocase !== s.scurry.nocase) {
throw new Error("nocase option contradicts provided scurry option");
}
} else {
const e = s.platform === "win32" ? n.PathScurryWin32 : s.platform === "darwin" ? n.PathScurryDarwin : s.platform ? n.PathScurryPosix : n.PathScurry;
this.scurry = new e(this.cwd, {
nocase: s.nocase,
fs: s.fs
});
}
this.nocase = this.scurry.nocase;
const o = this.platform === "darwin" || this.platform === "win32";
const c = {
...s,
dot: this.dot,
matchBase: this.matchBase,
nobrace: this.nobrace,
nocase: this.nocase,
nocaseMagicOnly: o,
nocomment: true,
noext: this.noext,
nonegate: true,
optimizationLevel: 2,
platform: this.platform,
windowsPathsNoEscape: this.windowsPathsNoEscape,
debug: !!this.opts.debug
};
const l = this.pattern.map(t => new e.Minimatch(t, c));
const [u, h] = l.reduce((e, t) => {
e[0].push(...t.set);
e[1].push(...t.globParts);
return e;
}, [ [], [] ]);
this.patterns = u.map((e, t) => {
const n = h[t];
if (!n) throw new Error("invalid pattern object");
return new a.Pattern(e, n, 0, this.platform);
});
}
async walk() {
return [ ...await new r.GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).walk() ];
}
walkSync() {
return [ ...new r.GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).walkSync() ];
}
stream() {
return new r.GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).stream();
}
streamSync() {
return new r.GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).streamSync();
}
iterateSync() {
return this.streamSync()[Symbol.iterator]();
}
[Symbol.iterator]() {
return this.iterateSync();
}
iterate() {
return this.stream()[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
}
XC.Glob = Glob;
return XC;
}
var bR = {};
var CR;
function RR() {
if (CR) return bR;
CR = 1;
Object.defineProperty(bR, "__esModule", {
value: true
});
bR.hasMagic = void 0;
const e = JC();
const t = (t, n = {}) => {
if (!Array.isArray(t)) {
t = [ t ];
}
for (const a of t) {
if (new e.Minimatch(a, n).hasMagic()) return true;
}
return false;
};
bR.hasMagic = t;
return bR;
}
var SR;
function wR() {
if (SR) return MC;
SR = 1;
(function(e) {
Object.defineProperty(e, "__esModule", {
value: true
});
e.glob = e.sync = e.iterate = e.iterateSync = e.stream = e.streamSync = e.Ignore = e.hasMagic = e.Glob = e.unescape = e.escape = void 0;
e.globStreamSync = c;
e.globStream = l;
e.globSync = u;
e.globIterateSync = d;
e.globIterate = p;
const t = JC();
const n = AR();
const a = RR();
var r = JC();
Object.defineProperty(e, "escape", {
enumerable: true,
get: function() {
return r.escape;
}
});
Object.defineProperty(e, "unescape", {
enumerable: true,
get: function() {
return r.unescape;
}
});
var i = AR();
Object.defineProperty(e, "Glob", {
enumerable: true,
get: function() {
return i.Glob;
}
});
var s = RR();
Object.defineProperty(e, "hasMagic", {
enumerable: true,
get: function() {
return s.hasMagic;
}
});
var o = mR();
Object.defineProperty(e, "Ignore", {
enumerable: true,
get: function() {
return o.Ignore;
}
});
function c(e, t = {}) {
return new n.Glob(e, t).streamSync();
}
function l(e, t = {}) {
return new n.Glob(e, t).stream();
}
function u(e, t = {}) {
return new n.Glob(e, t).walkSync();
}
async function h(e, t = {}) {
return new n.Glob(e, t).walk();
}
function d(e, t = {}) {
return new n.Glob(e, t).iterateSync();
}
function p(e, t = {}) {
return new n.Glob(e, t).iterate();
}
e.streamSync = c;
e.stream = Object.assign(l, {
sync: c
});
e.iterateSync = d;
e.iterate = Object.assign(p, {
sync: d
});
e.sync = Object.assign(u, {
stream: c,
iterate: d
});
e.glob = Object.assign(h, {
glob: h,
globSync: u,
sync: e.sync,
globStream: l,
stream: e.stream,
globStreamSync: c,
streamSync: e.streamSync,
globIterate: p,
iterate: e.iterate,
globIterateSync: d,
iterateSync: e.iterateSync,
Glob: n.Glob,
hasMagic: a.hasMagic,
escape: t.escape,
unescape: t.unescape
});
e.glob.glob = e.glob;
})(MC);
return MC;
}
Object.defineProperty(wC, "__esModule", {
value: true
});
wC.importClassesFromDirectories = DR;
wC.importJsonsFromDirectories = _R;
const MR = e;
const OR = MR.__importStar(wR());
const vR = Uh;
const IR = Od();
const PR = I;
const LR = Te;
async function DR(e, t, n = [ ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts" ]) {
const a = "info";
const r = "No classes were found using the provided glob pattern: ";
const i = "All classes found using provided glob pattern";
function s(e, t) {
if (typeof e === "function" || LR.InstanceChecker.isEntitySchema(e)) {
t.push(e);
} else if (Array.isArray(e)) {
e.forEach(e => s(e, t));
} else if (PR.ObjectUtils.isObject(e)) {
Object.values(e).forEach(e => s(e, t));
}
return t;
}
const o = t.reduce((e, t) => e.concat(OR.sync(vR.PlatformTools.pathNormalize(t))), []);
if (t.length > 0 && o.length === 0) {
e.log(a, `${r} "${t}"`);
} else if (o.length > 0) {
e.log(a, `${i} "${t}" : "${o}"`);
}
const c = o.filter(e => {
const t = e.substring(e.length - 5, e.length);
return n.indexOf(vR.PlatformTools.pathExtname(e)) !== -1 && t !== ".d.ts";
}).map(async e => {
const [t] = await (0, IR.importOrRequireFile)(vR.PlatformTools.pathResolve(e));
return t;
});
const l = await Promise.all(c);
return s(l, []);
}
function _R(e, t = ".json") {
const n = e.reduce((e, t) => e.concat(OR.sync(vR.PlatformTools.pathNormalize(t))), []);
return n.filter(e => vR.PlatformTools.pathExtname(e) === t).map(e => s(vR.PlatformTools.pathResolve(e)));
}
var $R = {};
var xR = {};
Object.defineProperty(xR, "__esModule", {
value: true
});
xR.ColumnMetadata = void 0;
const qR = qc;
const UR = _s;
const BR = I;
const FR = Te;
class ColumnMetadata {
constructor(e) {
this["@instanceof"] = Symbol.for("ColumnMetadata");
this.length = "";
this.isPrimary = false;
this.isGenerated = false;
this.isNullable = false;
this.isSelect = true;
this.isInsert = true;
this.isUpdate = true;
this.zerofill = false;
this.unsigned = false;
this.isArray = false;
this.isVirtual = false;
this.isVirtualProperty = false;
this.isDiscriminator = false;
this.isTreeLevel = false;
this.isCreateDate = false;
this.isUpdateDate = false;
this.isDeleteDate = false;
this.isVersion = false;
this.isObjectId = false;
this.isNestedSetLeft = false;
this.isNestedSetRight = false;
this.isMaterializedPath = false;
this.entityMetadata = e.entityMetadata;
this.embeddedMetadata = e.embeddedMetadata;
this.referencedColumn = e.referencedColumn;
if (e.args.target) this.target = e.args.target;
if (e.args.propertyName) this.propertyName = e.args.propertyName;
if (e.args.options.name) this.givenDatabaseName = e.args.options.name;
if (e.args.options.type) this.type = e.args.options.type;
if (e.args.options.length) this.length = e.args.options.length ? e.args.options.length.toString() : "";
if (e.args.options.width) this.width = e.args.options.width;
if (e.args.options.charset) this.charset = e.args.options.charset;
if (e.args.options.collation) this.collation = e.args.options.collation;
if (e.args.options.primary) this.isPrimary = e.args.options.primary;
if (e.args.options.default === null) this.isNullable = true;
if (e.args.options.nullable !== undefined) this.isNullable = e.args.options.nullable;
if (e.args.options.select !== undefined) this.isSelect = e.args.options.select;
if (e.args.options.insert !== undefined) this.isInsert = e.args.options.insert;
if (e.args.options.update !== undefined) this.isUpdate = e.args.options.update;
if (e.args.options.readonly !== undefined) this.isUpdate = !e.args.options.readonly;
if (e.args.options.comment) this.comment = e.args.options.comment;
if (e.args.options.default !== undefined) this.default = e.args.options.default;
if (e.args.options.onUpdate) this.onUpdate = e.args.options.onUpdate;
if (e.args.options.generatedIdentity) this.generatedIdentity = e.args.options.generatedIdentity;
if (e.args.options.scale !== null && e.args.options.scale !== undefined) this.scale = e.args.options.scale;
if (e.args.options.zerofill) {
this.zerofill = e.args.options.zerofill;
this.unsigned = true;
}
if (e.args.options.unsigned) this.unsigned = e.args.options.unsigned;
if (e.args.options.precision !== null) this.precision = e.args.options.precision;
if (e.args.options.enum) {
if (BR.ObjectUtils.isObject(e.args.options.enum) && !Array.isArray(e.args.options.enum)) {
this.enum = Object.keys(e.args.options.enum).filter(t => isNaN(+t) && typeof e.args.options.enum[t] !== "function").map(t => e.args.options.enum[t]);
} else {
this.enum = e.args.options.enum;
}
}
if (e.args.options.enumName) {
this.enumName = e.args.options.enumName;
}
if (e.args.options.primaryKeyConstraintName) {
this.primaryKeyConstraintName = e.args.options.primaryKeyConstraintName;
}
if (e.args.options.foreignKeyConstraintName) {
this.foreignKeyConstraintName = e.args.options.foreignKeyConstraintName;
}
if (e.args.options.asExpression) {
this.asExpression = e.args.options.asExpression;
this.generatedType = e.args.options.generatedType ? e.args.options.generatedType : "VIRTUAL";
}
if (e.args.options.hstoreType) this.hstoreType = e.args.options.hstoreType;
if (e.args.options.array) this.isArray = e.args.options.array;
if (e.args.mode) {
this.isVirtualProperty = e.args.mode === "virtual-property";
this.isVirtual = e.args.mode === "virtual";
this.isTreeLevel = e.args.mode === "treeLevel";
this.isCreateDate = e.args.mode === "createDate";
this.isUpdateDate = e.args.mode === "updateDate";
this.isDeleteDate = e.args.mode === "deleteDate";
this.isVersion = e.args.mode === "version";
this.isObjectId = e.args.mode === "objectId";
}
if (this.isVirtualProperty) {
this.isInsert = false;
this.isUpdate = false;
}
if (e.args.options.transformer) this.transformer = e.args.options.transformer;
if (e.args.options.spatialFeatureType) this.spatialFeatureType = e.args.options.spatialFeatureType;
if (e.args.options.srid !== undefined) this.srid = e.args.options.srid;
if (e.args.options.query) this.query = e.args.options.query;
if (this.isTreeLevel) this.type = e.connection.driver.mappedDataTypes.treeLevel;
if (this.isCreateDate) {
if (!this.type) this.type = e.connection.driver.mappedDataTypes.createDate;
if (!this.default) this.default = () => e.connection.driver.mappedDataTypes.createDateDefault;
if (this.precision === undefined && e.args.options.precision === undefined && e.connection.driver.mappedDataTypes.createDatePrecision) this.precision = e.connection.driver.mappedDataTypes.createDatePrecision;
}
if (this.isUpdateDate) {
if (!this.type) this.type = e.connection.driver.mappedDataTypes.updateDate;
if (!this.default) this.default = () => e.connection.driver.mappedDataTypes.updateDateDefault;
if (!this.onUpdate) this.onUpdate = e.connection.driver.mappedDataTypes.updateDateDefault;
if (this.precision === undefined && e.args.options.precision === undefined && e.connection.driver.mappedDataTypes.updateDatePrecision) this.precision = e.connection.driver.mappedDataTypes.updateDatePrecision;
}
if (this.isDeleteDate) {
if (!this.type) this.type = e.connection.driver.mappedDataTypes.deleteDate;
if (!this.isNullable) this.isNullable = e.connection.driver.mappedDataTypes.deleteDateNullable;
if (this.precision === undefined && e.args.options.precision === undefined && e.connection.driver.mappedDataTypes.deleteDatePrecision) this.precision = e.connection.driver.mappedDataTypes.deleteDatePrecision;
}
if (this.isVersion) this.type = e.connection.driver.mappedDataTypes.version;
if (e.closureType) this.closureType = e.closureType;
if (e.nestedSetLeft) this.isNestedSetLeft = e.nestedSetLeft;
if (e.nestedSetRight) this.isNestedSetRight = e.nestedSetRight;
if (e.materializedPath) this.isMaterializedPath = e.materializedPath;
}
createValueMap(e, t = false) {
if (this.embeddedMetadata) {
const n = [ ...this.embeddedMetadata.parentPropertyNames ];
const a = (n, r) => {
const i = n.shift();
if (i) {
r[i] = {};
a(n, r[i]);
return r;
}
if ((this.generationStrategy === "increment" || this.generationStrategy === "rowid") && this.type === "bigint" && e !== null) e = String(e);
r[t ? this.databaseName : this.propertyName] = e;
return r;
};
return a(n, {});
} else {
if ((this.generationStrategy === "increment" || this.generationStrategy === "rowid") && this.type === "bigint" && e !== null) e = String(e);
return {
[t ? this.databaseName : this.propertyName]: e
};
}
}
getEntityValueMap(e, t) {
const n = false;
if (this.embeddedMetadata) {
const t = [ ...this.embeddedMetadata.parentPropertyNames ];
const a = this.embeddedMetadata.isArray;
const r = (e, t) => {
if (t === undefined) {
return {};
}
const i = e.shift();
if (i) {
const n = r(e, t[i]);
if (Object.keys(n).length > 0) {
return {
[i]: n
};
}
return {};
}
if (a && Array.isArray(t)) {
return t.map(e => ({
[this.propertyName]: e[this.propertyName]
}));
}
if (t[this.propertyName] !== undefined && n === false) {
return {
[this.propertyName]: t[this.propertyName]
};
}
return {};
};
const i = r(t, e);
return Object.keys(i).length > 0 ? i : undefined;
} else {
if (this.relationMetadata && !Object.getOwnPropertyDescriptor(e, this.relationMetadata.propertyName)?.get && e[this.relationMetadata.propertyName] && BR.ObjectUtils.isObject(e[this.relationMetadata.propertyName])) {
if (this.relationMetadata.joinColumns.length > 1) {
const t = this.relationMetadata.joinColumns.reduce((t, n) => {
const a = n.referencedColumn.getEntityValueMap(e[this.relationMetadata.propertyName]);
if (a === undefined) return t;
return qR.OrmUtils.mergeDeep(t, a);
}, {});
if (Object.keys(t).length > 0) return {
[this.propertyName]: t
};
} else {
const t = this.relationMetadata.joinColumns[0].referencedColumn.getEntityValue(e[this.relationMetadata.propertyName]);
if (t) {
return {
[this.propertyName]: t
};
}
}
return undefined;
} else {
if (e[this.propertyName] !== undefined && n === false) {
return {
[this.propertyName]: e[this.propertyName]
};
}
return undefined;
}
}
}
getEntityValue(e, t = false) {
if (e === undefined || e === null) return undefined;
let n = undefined;
if (this.embeddedMetadata) {
const t = [ ...this.embeddedMetadata.parentPropertyNames ];
const a = this.embeddedMetadata.isArray;
const r = (e, t) => {
const n = e.shift();
return n && t ? r(e, t[n]) : t;
};
const i = r(t, e);
if (i) {
if (this.relationMetadata && this.referencedColumn) {
const e = this.relationMetadata.getEntityValue(i);
if (e && BR.ObjectUtils.isObject(e) && !FR.InstanceChecker.isFindOperator(e) && !Buffer.isBuffer(e)) {
n = this.referencedColumn.getEntityValue(e);
} else if (i[this.propertyName] && BR.ObjectUtils.isObject(i[this.propertyName]) && !FR.InstanceChecker.isFindOperator(i[this.propertyName]) && !Buffer.isBuffer(i[this.propertyName]) && !(i[this.propertyName] instanceof Date)) {
n = this.referencedColumn.getEntityValue(i[this.propertyName]);
} else {
n = i[this.propertyName];
}
} else if (this.referencedColumn) {
n = this.referencedColumn.getEntityValue(i[this.propertyName]);
} else if (a && Array.isArray(i)) {
n = i.map(e => e[this.propertyName]);
} else {
n = i[this.propertyName];
}
}
} else {
if (this.relationMetadata && this.referencedColumn) {
const t = this.relationMetadata.getEntityValue(e);
if (t && BR.ObjectUtils.isObject(t) && !FR.InstanceChecker.isFindOperator(t) && !(typeof t === "function") && !Buffer.isBuffer(t)) {
n = this.referencedColumn.getEntityValue(t);
} else if (e[this.propertyName] && BR.ObjectUtils.isObject(e[this.propertyName]) && !FR.InstanceChecker.isFindOperator(e[this.propertyName]) && !(typeof e[this.propertyName] === "function") && !Buffer.isBuffer(e[this.propertyName]) && !(e[this.propertyName] instanceof Date)) {
n = this.referencedColumn.getEntityValue(e[this.propertyName]);
} else {
n = e[this.propertyName];
}
} else if (this.referencedColumn) {
n = this.referencedColumn.getEntityValue(e[this.propertyName]);
} else {
n = e[this.propertyName];
}
}
if (t && this.transformer) n = UR.ApplyValueTransformers.transformTo(this.transformer, n);
return n;
}
setEntityValue(e, t) {
if (this.embeddedMetadata) {
const n = (e, a) => {
const r = e.shift();
if (r) {
if (!a[r.propertyName]) a[r.propertyName] = r.create();
n(e, a[r.propertyName]);
return a;
}
a[this.propertyName] = t;
return a;
};
return n([ ...this.embeddedMetadata.embeddedMetadataTree ], e);
} else {
if (!this.entityMetadata.isJunction && this.isVirtual && this.referencedColumn && this.referencedColumn.propertyName !== this.propertyName) {
if (!(this.propertyName in e)) {
e[this.propertyName] = {};
}
e[this.propertyName][this.referencedColumn.propertyName] = t;
} else {
e[this.propertyName] = t;
}
}
}
compareEntityValue(e, t) {
const n = this.getEntityValue(e);
if (typeof n?.equals === "function") {
return n.equals(t);
}
return n === t;
}
build(e) {
this.propertyPath = this.buildPropertyPath();
this.propertyAliasName = this.propertyPath.replace(".", "_");
this.databaseName = this.buildDatabaseName(e);
this.databasePath = this.buildDatabasePath();
this.databaseNameWithoutPrefixes = e.namingStrategy.columnName(this.propertyName, this.givenDatabaseName, []);
return this;
}
buildPropertyPath() {
let e = "";
if (this.embeddedMetadata && this.embeddedMetadata.parentPropertyNames.length) e = this.embeddedMetadata.parentPropertyNames.join(".") + ".";
e += this.propertyName;
if (!this.entityMetadata.isJunction && this.isVirtual && this.referencedColumn && this.referencedColumn.propertyName !== this.propertyName) e += "." + this.referencedColumn.propertyName;
return e;
}
buildDatabasePath() {
let e = "";
if (this.embeddedMetadata && this.embeddedMetadata.parentPropertyNames.length) e = this.embeddedMetadata.parentPropertyNames.join(".") + ".";
e += this.databaseName;
if (!this.entityMetadata.isJunction && this.isVirtual && this.referencedColumn && this.referencedColumn.databaseName !== this.databaseName) e += "." + this.referencedColumn.databaseName;
return e;
}
buildDatabaseName(e) {
let t = this.embeddedMetadata ? this.embeddedMetadata.parentPrefixes : [];
if (e.driver.options.type === "mongodb") t = [];
return e.namingStrategy.columnName(this.propertyName, this.givenDatabaseName, t);
}
}
xR.ColumnMetadata = ColumnMetadata;
var jR = {};
Object.defineProperty(jR, "__esModule", {
value: true
});
jR.IndexMetadata = void 0;
const kR = P;
class IndexMetadata {
constructor(e) {
this.isUnique = false;
this.isSpatial = false;
this.isFulltext = false;
this.isNullFiltered = false;
this.synchronize = true;
this.columns = [];
this.columnNamesWithOrderingMap = {};
this.entityMetadata = e.entityMetadata;
this.embeddedMetadata = e.embeddedMetadata;
if (e.columns) this.columns = e.columns;
if (e.args) {
this.target = e.args.target;
if (e.args.synchronize !== null && e.args.synchronize !== undefined) this.synchronize = e.args.synchronize;
this.isUnique = !!e.args.unique;
this.isSpatial = !!e.args.spatial;
this.isFulltext = !!e.args.fulltext;
this.isNullFiltered = !!e.args.nullFiltered;
this.parser = e.args.parser;
this.where = e.args.where;
this.isSparse = e.args.sparse;
this.isBackground = e.args.background;
this.isConcurrent = e.args.concurrent;
this.expireAfterSeconds = e.args.expireAfterSeconds;
this.givenName = e.args.name;
this.givenColumnNames = e.args.columns;
}
}
build(e) {
if (this.synchronize === false) {
this.name = this.givenName;
return this;
}
const t = {};
if (this.givenColumnNames) {
let e = [];
if (Array.isArray(this.givenColumnNames)) {
e = this.givenColumnNames.map(e => {
if (this.embeddedMetadata) return this.embeddedMetadata.propertyPath + "." + e;
return e.trim();
});
e.forEach(e => t[e] = 1);
} else {
const n = this.givenColumnNames(this.entityMetadata.propertiesMap);
if (Array.isArray(n)) {
e = n.map(e => String(e));
e.forEach(e => t[e] = 1);
} else {
e = Object.keys(n).map(e => String(e));
Object.keys(n).forEach(e => t[e] = n[e]);
}
}
this.columns = e.map(e => {
const t = this.entityMetadata.columns.find(t => t.propertyPath === e);
if (t) {
return [ t ];
}
const n = this.entityMetadata.relations.find(t => t.isWithJoinColumn && t.propertyName === e);
if (n) {
return n.joinColumns;
}
const a = this.givenName ? '"' + this.givenName + '" ' : "";
const r = this.entityMetadata.targetName;
throw new kR.TypeORMError(`Index ${a}contains column that is missing in the entity (${r}): ` + e);
}).reduce((e, t) => e.concat(t));
}
this.columnNamesWithOrderingMap = Object.keys(t).reduce((e, n) => {
const a = this.entityMetadata.columns.find(e => e.propertyPath === n);
if (a) e[a.databasePath] = t[n];
return e;
}, {});
this.name = this.givenName ? this.givenName : e.indexName(this.entityMetadata.tableName, this.columns.map(e => e.databaseName), this.where);
return this;
}
}
jR.IndexMetadata = IndexMetadata;
var QR = {};
Object.defineProperty(QR, "__esModule", {
value: true
});
QR.RelationMetadata = void 0;
const VR = vp;
const KR = P;
const WR = I;
const HR = Te;
class RelationMetadata {
constructor(e) {
this.isTreeParent = false;
this.isTreeChildren = false;
this.isPrimary = false;
this.isLazy = false;
this.isEager = false;
this.persistenceEnabled = true;
this.isCascadeInsert = false;
this.isCascadeUpdate = false;
this.isCascadeRemove = false;
this.isCascadeSoftRemove = false;
this.isCascadeRecover = false;
this.isNullable = true;
this.createForeignKeyConstraints = true;
this.isOwning = false;
this.isOneToOne = false;
this.isOneToOneOwner = false;
this.isWithJoinColumn = false;
this.isOneToOneNotOwner = false;
this.isOneToMany = false;
this.isManyToOne = false;
this.isManyToMany = false;
this.isManyToManyOwner = false;
this.isManyToManyNotOwner = false;
this.foreignKeys = [];
this.joinColumns = [];
this.inverseJoinColumns = [];
this.entityMetadata = e.entityMetadata;
this.embeddedMetadata = e.embeddedMetadata;
const t = e.args;
this.target = t.target;
this.propertyName = t.propertyName;
this.relationType = t.relationType;
if (t.inverseSideProperty) this.givenInverseSidePropertyFactory = t.inverseSideProperty;
this.isLazy = t.isLazy || false;
this.isCascadeInsert = t.options.cascade === true || Array.isArray(t.options.cascade) && t.options.cascade.indexOf("insert") !== -1;
this.isCascadeUpdate = t.options.cascade === true || Array.isArray(t.options.cascade) && t.options.cascade.indexOf("update") !== -1;
this.isCascadeRemove = t.options.cascade === true || Array.isArray(t.options.cascade) && t.options.cascade.indexOf("remove") !== -1;
this.isCascadeSoftRemove = t.options.cascade === true || Array.isArray(t.options.cascade) && t.options.cascade.indexOf("soft-remove") !== -1;
this.isCascadeRecover = t.options.cascade === true || Array.isArray(t.options.cascade) && t.options.cascade.indexOf("recover") !== -1;
this.isNullable = t.options.nullable === false || this.isPrimary ? false : true;
this.onDelete = t.options.onDelete;
this.onUpdate = t.options.onUpdate;
this.deferrable = t.options.deferrable;
this.createForeignKeyConstraints = t.options.createForeignKeyConstraints === false ? false : true;
this.isEager = t.options.eager || false;
this.persistenceEnabled = t.options.persistence === false ? false : true;
this.orphanedRowAction = t.options.orphanedRowAction || "nullify";
this.isTreeParent = t.isTreeParent || false;
this.isTreeChildren = t.isTreeChildren || false;
if (typeof t.type === "function") {
this.type = typeof t.type === "function" ? t.type() : t.type;
} else if (HR.InstanceChecker.isEntitySchema(t.type)) {
this.type = t.type.options.name;
} else if (WR.ObjectUtils.isObject(t.type) && typeof t.type.name === "string") {
this.type = t.type.name;
} else {
this.type = t.type;
}
this.isOneToOne = this.relationType === "one-to-one";
this.isOneToMany = this.relationType === "one-to-many";
this.isManyToOne = this.relationType === "many-to-one";
this.isManyToMany = this.relationType === "many-to-many";
this.isOneToOneNotOwner = this.isOneToOne ? true : false;
this.isManyToManyNotOwner = this.isManyToMany ? true : false;
}
getRelationIdMap(e) {
const t = this.isOwning ? this.joinColumns : this.inverseRelation.joinColumns;
const n = t.map(e => e.referencedColumn);
return VR.EntityMetadata.getValueMap(e, n);
}
ensureRelationIdMap(e) {
if (WR.ObjectUtils.isObject(e)) return e;
const t = this.isOwning ? this.joinColumns : this.inverseRelation.joinColumns;
const n = t.map(e => e.referencedColumn);
if (n.length > 1) throw new KR.TypeORMError(`Cannot create relation id map for a single value because relation contains multiple referenced columns.`);
return n[0].createValueMap(e);
}
getEntityValue(e, t = false) {
if (e === null || e === undefined) return undefined;
if (this.embeddedMetadata) {
const n = [ ...this.embeddedMetadata.parentPropertyNames ];
const a = (e, t) => {
const n = e.shift();
if (n) {
if (t[n]) {
return a(e, t[n]);
}
return undefined;
}
return t;
};
const r = a(n, e);
if (this.isLazy) {
if (r["__" + this.propertyName + "__"] !== undefined) return r["__" + this.propertyName + "__"];
if (t === true) return r[this.propertyName];
return undefined;
}
return r ? r[this.isLazy ? "__" + this.propertyName + "__" : this.propertyName] : undefined;
} else {
if (this.isLazy) {
if (e["__" + this.propertyName + "__"] !== undefined) return e["__" + this.propertyName + "__"];
if (t === true) return e[this.propertyName];
return undefined;
}
return e[this.propertyName];
}
}
setEntityValue(e, t) {
const n = this.isLazy ? "__" + this.propertyName + "__" : this.propertyName;
if (this.embeddedMetadata) {
const a = (e, r) => {
const i = e.shift();
if (i) {
if (!r[i.propertyName]) r[i.propertyName] = i.create();
a(e, r[i.propertyName]);
return r;
}
r[n] = t;
return r;
};
return a([ ...this.embeddedMetadata.embeddedMetadataTree ], e);
} else {
e[n] = t;
}
}
createValueMap(e) {
if (this.embeddedMetadata) {
const t = [ ...this.embeddedMetadata.parentPropertyNames ];
const n = (t, a) => {
const r = t.shift();
if (r) {
a[r] = {};
n(t, a[r]);
return a;
}
a[this.propertyName] = e;
return a;
};
return n(t, {});
} else {
return {
[this.propertyName]: e
};
}
}
build() {
this.propertyPath = this.buildPropertyPath();
}
registerForeignKeys(...e) {
this.foreignKeys.push(...e);
}
registerJoinColumns(e = [], t = []) {
this.joinColumns = e;
this.inverseJoinColumns = t;
this.isOwning = this.isManyToOne || (this.isManyToMany || this.isOneToOne) && this.joinColumns.length > 0;
this.isOneToOneOwner = this.isOneToOne && this.isOwning;
this.isOneToOneNotOwner = this.isOneToOne && !this.isOwning;
this.isManyToManyOwner = this.isManyToMany && this.isOwning;
this.isManyToManyNotOwner = this.isManyToMany && !this.isOwning;
this.isWithJoinColumn = this.isManyToOne || this.isOneToOneOwner;
}
registerJunctionEntityMetadata(e) {
this.junctionEntityMetadata = e;
this.joinTableName = e.tableName;
if (this.inverseRelation) {
this.inverseRelation.junctionEntityMetadata = e;
this.joinTableName = e.tableName;
}
}
buildInverseSidePropertyPath() {
if (this.givenInverseSidePropertyFactory) {
const e = this.inverseEntityMetadata.propertiesMap;
if (typeof this.givenInverseSidePropertyFactory === "function") return this.givenInverseSidePropertyFactory(e);
if (typeof this.givenInverseSidePropertyFactory === "string") return this.givenInverseSidePropertyFactory;
} else if (this.isTreeParent && this.entityMetadata.treeChildrenRelation) {
return this.entityMetadata.treeChildrenRelation.propertyName;
} else if (this.isTreeChildren && this.entityMetadata.treeParentRelation) {
return this.entityMetadata.treeParentRelation.propertyName;
}
return "";
}
buildPropertyPath() {
if (!this.embeddedMetadata || !this.embeddedMetadata.parentPropertyNames.length) return this.propertyName;
return this.embeddedMetadata.parentPropertyNames.join(".") + "." + this.propertyName;
}
}
QR.RelationMetadata = RelationMetadata;
var GR = {};
Object.defineProperty(GR, "__esModule", {
value: true
});
GR.EmbeddedMetadata = void 0;
const YR = P;
class EmbeddedMetadata {
constructor(e) {
this.columns = [];
this.relations = [];
this.listeners = [];
this.indices = [];
this.uniques = [];
this.relationIds = [];
this.relationCounts = [];
this.embeddeds = [];
this.isAlwaysUsingConstructor = true;
this.isArray = false;
this.parentPropertyNames = [];
this.parentPrefixes = [];
this.embeddedMetadataTree = [];
this.columnsFromTree = [];
this.relationsFromTree = [];
this.listenersFromTree = [];
this.indicesFromTree = [];
this.uniquesFromTree = [];
this.relationIdsFromTree = [];
this.relationCountsFromTree = [];
this.entityMetadata = e.entityMetadata;
this.type = e.args.type();
this.propertyName = e.args.propertyName;
this.customPrefix = e.args.prefix;
this.isArray = e.args.isArray;
}
create(e) {
if (!(typeof this.type === "function")) {
return {};
}
if (e?.fromDeserializer || !this.isAlwaysUsingConstructor) {
return Object.create(this.type.prototype);
} else {
return new this.type;
}
}
build(e) {
this.embeddeds.forEach(t => t.build(e));
this.prefix = this.buildPrefix(e);
this.parentPropertyNames = this.buildParentPropertyNames();
this.parentPrefixes = this.buildParentPrefixes();
this.propertyPath = this.parentPropertyNames.join(".");
this.embeddedMetadataTree = this.buildEmbeddedMetadataTree();
this.columnsFromTree = this.buildColumnsFromTree();
this.relationsFromTree = this.buildRelationsFromTree();
this.listenersFromTree = this.buildListenersFromTree();
this.indicesFromTree = this.buildIndicesFromTree();
this.uniquesFromTree = this.buildUniquesFromTree();
this.relationIdsFromTree = this.buildRelationIdsFromTree();
this.relationCountsFromTree = this.buildRelationCountsFromTree();
if (e.options.entitySkipConstructor) {
this.isAlwaysUsingConstructor = !e.options.entitySkipConstructor;
}
return this;
}
buildPartialPrefix() {
if (this.customPrefix === undefined || this.customPrefix === true) {
return [ this.propertyName ];
}
if (this.customPrefix === "" || this.customPrefix === false) {
return [];
}
if (typeof this.customPrefix === "string") {
return [ this.customPrefix ];
}
throw new YR.TypeORMError(`Invalid prefix option given for ${this.entityMetadata.targetName}#${this.propertyName}`);
}
buildPrefix(e) {
if (e.driver.options.type === "mongodb") return this.propertyName;
const t = [];
if (this.parentEmbeddedMetadata) t.push(this.parentEmbeddedMetadata.buildPrefix(e));
t.push(...this.buildPartialPrefix());
return t.join("_");
}
buildParentPropertyNames() {
return this.parentEmbeddedMetadata ? this.parentEmbeddedMetadata.buildParentPropertyNames().concat(this.propertyName) : [ this.propertyName ];
}
buildParentPrefixes() {
return this.parentEmbeddedMetadata ? this.parentEmbeddedMetadata.buildParentPrefixes().concat(this.buildPartialPrefix()) : this.buildPartialPrefix();
}
buildEmbeddedMetadataTree() {
return this.parentEmbeddedMetadata ? this.parentEmbeddedMetadata.buildEmbeddedMetadataTree().concat(this) : [ this ];
}
buildColumnsFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildColumnsFromTree()), this.columns);
}
buildRelationsFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildRelationsFromTree()), this.relations);
}
buildListenersFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildListenersFromTree()), this.listeners);
}
buildIndicesFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildIndicesFromTree()), this.indices);
}
buildUniquesFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildUniquesFromTree()), this.uniques);
}
buildRelationIdsFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildRelationIdsFromTree()), this.relationIds);
}
buildRelationCountsFromTree() {
return this.embeddeds.reduce((e, t) => e.concat(t.buildRelationCountsFromTree()), this.relationCounts);
}
}
GR.EmbeddedMetadata = EmbeddedMetadata;
var zR = {};
Object.defineProperty(zR, "__esModule", {
value: true
});
zR.RelationIdMetadata = void 0;
const JR = P;
class RelationIdMetadata {
constructor(e) {
this.entityMetadata = e.entityMetadata;
this.target = e.args.target;
this.propertyName = e.args.propertyName;
this.relationNameOrFactory = e.args.relation;
this.alias = e.args.alias;
this.queryBuilderFactory = e.args.queryBuilderFactory;
}
setValue(e) {
const t = this.relation.getEntityValue(e);
if (Array.isArray(t)) {
e[this.propertyName] = t.map(e => this.relation.inverseEntityMetadata.getEntityIdMixedMap(e)).filter(e => e !== null && e !== undefined);
} else {
const n = this.relation.inverseEntityMetadata.getEntityIdMixedMap(t);
if (n !== undefined) e[this.propertyName] = n;
}
}
build() {
const e = typeof this.relationNameOrFactory === "function" ? this.relationNameOrFactory(this.entityMetadata.propertiesMap) : this.relationNameOrFactory;
const t = this.entityMetadata.findRelationWithPropertyPath(e);
if (!t) throw new JR.TypeORMError(`Cannot find relation ${e}. Wrong relation specified for @RelationId decorator.`);
this.relation = t;
}
}
zR.RelationIdMetadata = RelationIdMetadata;
var XR = {};
Object.defineProperty(XR, "__esModule", {
value: true
});
XR.RelationCountMetadata = void 0;
const ZR = P;
class RelationCountMetadata {
constructor(e) {
this.entityMetadata = e.entityMetadata;
this.target = e.args.target;
this.propertyName = e.args.propertyName;
this.relationNameOrFactory = e.args.relation;
this.alias = e.args.alias;
this.queryBuilderFactory = e.args.queryBuilderFactory;
}
build() {
const e = typeof this.relationNameOrFactory === "function" ? this.relationNameOrFactory(this.entityMetadata.propertiesMap) : this.relationNameOrFactory;
const t = this.entityMetadata.findRelationWithPropertyPath(e);
if (!t) throw new ZR.TypeORMError(`Cannot find relation ${e}. Wrong relation specified for @RelationCount decorator.`);
this.relation = t;
}
}
XR.RelationCountMetadata = RelationCountMetadata;
var eS = {};
Object.defineProperty(eS, "__esModule", {
value: true
});
eS.EventListenerTypes = void 0;
class EventListenerTypes {}
eS.EventListenerTypes = EventListenerTypes;
EventListenerTypes.AFTER_LOAD = "after-load";
EventListenerTypes.BEFORE_INSERT = "before-insert";
EventListenerTypes.AFTER_INSERT = "after-insert";
EventListenerTypes.BEFORE_UPDATE = "before-update";
EventListenerTypes.AFTER_UPDATE = "after-update";
EventListenerTypes.BEFORE_REMOVE = "before-remove";
EventListenerTypes.AFTER_REMOVE = "after-remove";
EventListenerTypes.BEFORE_SOFT_REMOVE = "before-soft-remove";
EventListenerTypes.AFTER_SOFT_REMOVE = "after-soft-remove";
EventListenerTypes.BEFORE_RECOVER = "before-recover";
EventListenerTypes.AFTER_RECOVER = "after-recover";
var tS = {};
var nS = {};
Object.defineProperty(nS, "__esModule", {
value: true
});
nS.ForeignKeyMetadata = void 0;
class ForeignKeyMetadata {
constructor(e) {
this.columns = [];
this.referencedColumns = [];
this.columnNames = [];
this.referencedColumnNames = [];
this.entityMetadata = e.entityMetadata;
this.referencedEntityMetadata = e.referencedEntityMetadata;
this.columns = e.columns;
this.referencedColumns = e.referencedColumns;
this.onDelete = e.onDelete || "NO ACTION";
this.onUpdate = e.onUpdate || "NO ACTION";
this.deferrable = e.deferrable;
this.givenName = e.name;
if (e.namingStrategy) this.build(e.namingStrategy);
}
build(e) {
this.columnNames = this.columns.map(e => e.databaseName);
this.referencedColumnNames = this.referencedColumns.map(e => e.databaseName);
this.referencedTablePath = this.referencedEntityMetadata.tablePath;
this.name = this.givenName ? this.givenName : e.foreignKeyName(this.entityMetadata.tableName, this.columnNames, this.referencedEntityMetadata.tableName, this.referencedColumnNames);
}
}
nS.ForeignKeyMetadata = ForeignKeyMetadata;
Object.defineProperty(tS, "__esModule", {
value: true
});
tS.JunctionEntityMetadataBuilder = void 0;
const aS = xR;
const rS = vp;
const iS = nS;
const sS = jR;
const oS = P;
const cS = jn;
class JunctionEntityMetadataBuilder {
constructor(e) {
this.connection = e;
}
build(e, t) {
const n = this.collectReferencedColumns(e, t);
const a = this.collectInverseReferencedColumns(e, t);
const r = t.name || this.connection.namingStrategy.joinTableName(e.entityMetadata.tableNameWithoutPrefix, e.inverseEntityMetadata.tableNameWithoutPrefix, e.propertyPath, e.inverseRelation ? e.inverseRelation.propertyName : "");
const i = new rS.EntityMetadata({
connection: this.connection,
args: {
target: "",
name: r,
type: "junction",
database: t.database || e.entityMetadata.database,
schema: t.schema || e.entityMetadata.schema,
synchronize: t.synchronize
}
});
i.build();
const s = n.map(n => {
const a = t.joinColumns ? t.joinColumns.find(e => (!e.referencedColumnName || e.referencedColumnName === n.propertyName) && !!e.name) : undefined;
const r = a && a.name ? a.name : this.connection.namingStrategy.joinTableColumnName(e.entityMetadata.tableNameWithoutPrefix, n.propertyName, n.databaseName);
return new aS.ColumnMetadata({
connection: this.connection,
entityMetadata: i,
referencedColumn: n,
args: {
target: "",
mode: "virtual",
propertyName: r,
options: {
name: r,
length: !n.length && (cS.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.normalizeType(n) !== "uuid" && (n.generationStrategy === "uuid" || n.type === "uuid") ? "36" : n.length,
width: n.width,
type: n.type,
precision: n.precision,
scale: n.scale,
charset: n.charset,
collation: n.collation,
zerofill: n.zerofill,
unsigned: n.zerofill ? true : n.unsigned,
enum: n.enum,
enumName: n.enumName,
foreignKeyConstraintName: a?.foreignKeyConstraintName,
nullable: false,
primary: true
}
}
});
});
const o = a.map(n => {
const a = t.inverseJoinColumns ? t.inverseJoinColumns.find(e => (!e.referencedColumnName || e.referencedColumnName === n.propertyName) && !!e.name) : undefined;
const r = a && a.name ? a.name : this.connection.namingStrategy.joinTableInverseColumnName(e.inverseEntityMetadata.tableNameWithoutPrefix, n.propertyName, n.databaseName);
return new aS.ColumnMetadata({
connection: this.connection,
entityMetadata: i,
referencedColumn: n,
args: {
target: "",
mode: "virtual",
propertyName: r,
options: {
length: !n.length && (cS.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.normalizeType(n) !== "uuid" && (n.generationStrategy === "uuid" || n.type === "uuid") ? "36" : n.length,
width: n.width,
type: n.type,
precision: n.precision,
scale: n.scale,
charset: n.charset,
collation: n.collation,
zerofill: n.zerofill,
unsigned: n.zerofill ? true : n.unsigned,
enum: n.enum,
enumName: n.enumName,
foreignKeyConstraintName: a?.foreignKeyConstraintName,
name: r,
nullable: false,
primary: true
}
}
});
});
this.changeDuplicatedColumnNames(s, o);
i.ownerColumns = s;
i.inverseColumns = o;
i.ownColumns = [ ...s, ...o ];
i.ownColumns.forEach(t => t.relationMetadata = e);
i.foreignKeys = e.createForeignKeyConstraints ? [ new iS.ForeignKeyMetadata({
entityMetadata: i,
referencedEntityMetadata: e.entityMetadata,
columns: s,
referencedColumns: n,
name: s[0]?.foreignKeyConstraintName,
onDelete: this.connection.driver.options.type === "spanner" ? "NO ACTION" : e.onDelete || "CASCADE",
onUpdate: this.connection.driver.options.type === "oracle" || this.connection.driver.options.type === "spanner" ? "NO ACTION" : e.onUpdate || "CASCADE"
}), new iS.ForeignKeyMetadata({
entityMetadata: i,
referencedEntityMetadata: e.inverseEntityMetadata,
columns: o,
referencedColumns: a,
name: o[0]?.foreignKeyConstraintName,
onDelete: this.connection.driver.options.type === "spanner" ? "NO ACTION" : e.inverseRelation ? e.inverseRelation.onDelete : "CASCADE",
onUpdate: this.connection.driver.options.type === "oracle" || this.connection.driver.options.type === "spanner" ? "NO ACTION" : e.inverseRelation ? e.inverseRelation.onUpdate : "CASCADE"
}) ] : [];
i.ownIndices = [ new sS.IndexMetadata({
entityMetadata: i,
columns: s,
args: {
target: i.target,
synchronize: true
}
}), new sS.IndexMetadata({
entityMetadata: i,
columns: o,
args: {
target: i.target,
synchronize: true
}
}) ];
return i;
}
collectReferencedColumns(e, t) {
const n = t.joinColumns ? t.joinColumns.find(e => !!e.referencedColumnName) : false;
if (!t.joinColumns || t.joinColumns && !n) {
return e.entityMetadata.columns.filter(e => e.isPrimary);
} else {
return t.joinColumns.map(t => {
const n = e.entityMetadata.columns.find(e => e.propertyName === t.referencedColumnName);
if (!n) throw new oS.TypeORMError(`Referenced column ${t.referencedColumnName} was not found in entity ${e.entityMetadata.name}`);
return n;
});
}
}
collectInverseReferencedColumns(e, t) {
const n = !!t.inverseJoinColumns;
const a = n ? t.inverseJoinColumns.find(e => !!e.referencedColumnName) : false;
if (!n || n && !a) {
return e.inverseEntityMetadata.primaryColumns;
} else {
return t.inverseJoinColumns.map(t => {
const n = e.inverseEntityMetadata.ownColumns.find(e => e.propertyName === t.referencedColumnName);
if (!n) throw new oS.TypeORMError(`Referenced column ${t.referencedColumnName} was not found in entity ${e.inverseEntityMetadata.name}`);
return n;
});
}
}
changeDuplicatedColumnNames(e, t) {
e.forEach(e => {
t.forEach(t => {
if (e.givenDatabaseName === t.givenDatabaseName) {
const n = this.connection.namingStrategy.joinTableColumnDuplicationPrefix(e.propertyName, 1);
e.propertyName = n;
e.givenDatabaseName = n;
const a = this.connection.namingStrategy.joinTableColumnDuplicationPrefix(t.propertyName, 2);
t.propertyName = a;
t.givenDatabaseName = a;
}
});
});
}
}
tS.JunctionEntityMetadataBuilder = JunctionEntityMetadataBuilder;
var lS = {};
Object.defineProperty(lS, "__esModule", {
value: true
});
lS.ClosureJunctionEntityMetadataBuilder = void 0;
const uS = vp;
const hS = xR;
const dS = nS;
const pS = jR;
class ClosureJunctionEntityMetadataBuilder {
constructor(e) {
this.connection = e;
}
build(e) {
const t = new uS.EntityMetadata({
parentClosureEntityMetadata: e,
connection: this.connection,
args: {
target: "",
name: e.treeOptions && e.treeOptions.closureTableName ? e.treeOptions.closureTableName : e.tableNameWithoutPrefix,
type: "closure-junction"
}
});
t.build();
e.primaryColumns.forEach(n => {
t.ownColumns.push(new hS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
closureType: "ancestor",
referencedColumn: n,
args: {
target: "",
mode: "virtual",
propertyName: e.treeOptions && e.treeOptions.ancestorColumnName ? e.treeOptions.ancestorColumnName(n) : n.propertyName + "_ancestor",
options: {
primary: true,
length: n.length,
type: n.type
}
}
}));
t.ownColumns.push(new hS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
closureType: "descendant",
referencedColumn: n,
args: {
target: "",
mode: "virtual",
propertyName: e.treeOptions && e.treeOptions.descendantColumnName ? e.treeOptions.descendantColumnName(n) : n.propertyName + "_descendant",
options: {
primary: true,
length: n.length,
type: n.type
}
}
}));
});
t.ownIndices = [ new pS.IndexMetadata({
entityMetadata: t,
columns: [ t.ownColumns[0] ],
args: {
target: t.target,
synchronize: true
}
}), new pS.IndexMetadata({
entityMetadata: t,
columns: [ t.ownColumns[1] ],
args: {
target: t.target,
synchronize: true
}
}) ];
if (e.treeLevelColumn) {
t.ownColumns.push(new hS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
args: {
target: "",
mode: "virtual",
propertyName: "level",
options: {
type: this.connection.driver.mappedDataTypes.treeLevel
}
}
}));
}
t.foreignKeys = [ new dS.ForeignKeyMetadata({
entityMetadata: t,
referencedEntityMetadata: e,
columns: [ t.ownColumns[0] ],
referencedColumns: e.primaryColumns,
onDelete: this.connection.driver.options.type === "mssql" ? "NO ACTION" : "CASCADE"
}), new dS.ForeignKeyMetadata({
entityMetadata: t,
referencedEntityMetadata: e,
columns: [ t.ownColumns[1] ],
referencedColumns: e.primaryColumns,
onDelete: this.connection.driver.options.type === "mssql" ? "NO ACTION" : "CASCADE"
}) ];
return t;
}
}
lS.ClosureJunctionEntityMetadataBuilder = ClosureJunctionEntityMetadataBuilder;
var mS = {};
var fS = {};
Object.defineProperty(fS, "__esModule", {
value: true
});
fS.UniqueMetadata = void 0;
const yS = P;
class UniqueMetadata {
constructor(e) {
this.columns = [];
this.columnNamesWithOrderingMap = {};
this.entityMetadata = e.entityMetadata;
this.embeddedMetadata = e.embeddedMetadata;
if (e.columns) this.columns = e.columns;
if (e.args) {
this.target = e.args.target;
this.givenName = e.args.name;
this.givenColumnNames = e.args.columns;
this.deferrable = e.args.deferrable;
}
}
build(e) {
const t = {};
if (this.givenColumnNames) {
let e = [];
if (Array.isArray(this.givenColumnNames)) {
e = this.givenColumnNames.map(e => {
if (this.embeddedMetadata) return this.embeddedMetadata.propertyPath + "." + e;
return e.trim();
});
e.forEach(e => t[e] = 1);
} else {
const n = this.givenColumnNames(this.entityMetadata.propertiesMap);
if (Array.isArray(n)) {
e = n.map(e => String(e));
e.forEach(e => t[e] = 1);
} else {
e = Object.keys(n).map(e => String(e));
Object.keys(n).forEach(e => t[e] = n[e]);
}
}
this.columns = e.map(e => {
const t = this.entityMetadata.columns.find(t => t.propertyPath === e);
if (t) {
return [ t ];
}
const n = this.entityMetadata.relations.find(t => t.isWithJoinColumn && t.propertyName === e);
if (n) {
return n.joinColumns;
}
const a = this.givenName ? '"' + this.givenName + '" ' : "";
const r = this.entityMetadata.targetName;
throw new yS.TypeORMError(`Unique constraint ${a}contains column that is missing in the entity (${r}): ` + e);
}).reduce((e, t) => e.concat(t));
}
this.columnNamesWithOrderingMap = Object.keys(t).reduce((e, n) => {
const a = this.entityMetadata.columns.find(e => e.propertyPath === n);
if (a) e[a.databasePath] = t[n];
return e;
}, {});
this.name = this.givenName ? this.givenName : e.uniqueConstraintName(this.entityMetadata.tableName, this.columns.map(e => e.databaseName));
return this;
}
}
fS.UniqueMetadata = UniqueMetadata;
Object.defineProperty(mS, "__esModule", {
value: true
});
mS.RelationJoinColumnBuilder = void 0;
const ES = xR;
const TS = fS;
const gS = nS;
const NS = P;
const AS = jn;
class RelationJoinColumnBuilder {
constructor(e) {
this.connection = e;
}
build(e, t) {
const n = this.collectReferencedColumns(e, t);
const a = this.collectColumns(e, t, n);
if (!n.length || !t.createForeignKeyConstraints) return {
foreignKey: undefined,
columns: a,
uniqueConstraint: undefined
};
const r = new gS.ForeignKeyMetadata({
name: e[0]?.foreignKeyConstraintName,
entityMetadata: t.entityMetadata,
referencedEntityMetadata: t.inverseEntityMetadata,
namingStrategy: this.connection.namingStrategy,
columns: a,
referencedColumns: n,
onDelete: t.onDelete,
onUpdate: t.onUpdate,
deferrable: t.deferrable
});
if (a.every(e => e.isPrimary) || !t.isOneToOne) {
return {
foreignKey: r,
columns: a,
uniqueConstraint: undefined
};
}
const i = new TS.UniqueMetadata({
entityMetadata: t.entityMetadata,
columns: r.columns,
args: {
name: this.connection.namingStrategy.relationConstraintName(t.entityMetadata.tableName, r.columns.map(e => e.databaseName)),
target: t.entityMetadata.target
}
});
i.build(this.connection.namingStrategy);
return {
foreignKey: r,
columns: a,
uniqueConstraint: i
};
}
collectReferencedColumns(e, t) {
const n = e.find(e => !!e.referencedColumnName);
const a = e.length === 0 && t.isManyToOne;
const r = e.length > 0 && !n;
if (a || r) {
return t.inverseEntityMetadata.primaryColumns;
} else {
return e.map(e => {
const n = t.inverseEntityMetadata.ownColumns.find(t => t.propertyName === e.referencedColumnName);
if (!n) throw new NS.TypeORMError(`Referenced column ${e.referencedColumnName} was not found in entity ${t.inverseEntityMetadata.name}`);
return n;
});
}
}
collectColumns(e, t, n) {
return n.map(n => {
const a = e.find(e => (!e.referencedColumnName || e.referencedColumnName === n.propertyName) && !!e.name);
const r = a ? a.name : this.connection.namingStrategy.joinColumnName(t.propertyName, n.propertyName);
const i = t.embeddedMetadata ? t.embeddedMetadata.columns : t.entityMetadata.ownColumns;
let s = i.find(e => e.databaseNameWithoutPrefixes === r);
if (!s) {
s = new ES.ColumnMetadata({
connection: this.connection,
entityMetadata: t.entityMetadata,
embeddedMetadata: t.embeddedMetadata,
args: {
target: "",
mode: "virtual",
propertyName: t.propertyName,
options: {
name: r,
type: n.type,
length: !n.length && (AS.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.normalizeType(n) !== "uuid" && (n.generationStrategy === "uuid" || n.type === "uuid") ? "36" : n.length,
width: n.width,
charset: n.charset,
collation: n.collation,
precision: n.precision,
scale: n.scale,
zerofill: n.zerofill,
unsigned: n.unsigned,
comment: n.comment,
enum: n.enum,
enumName: n.enumName,
primary: t.isPrimary,
nullable: t.isNullable
}
}
});
t.entityMetadata.registerColumn(s);
}
s.referencedColumn = n;
s.type = n.type;
s.relationMetadata = t;
s.build(this.connection);
return s;
});
}
}
mS.RelationJoinColumnBuilder = RelationJoinColumnBuilder;
var bS = {};
Object.defineProperty(bS, "__esModule", {
value: true
});
bS.EntityListenerMetadata = void 0;
class EntityListenerMetadata {
constructor(e) {
this.entityMetadata = e.entityMetadata;
this.embeddedMetadata = e.embeddedMetadata;
this.target = e.args.target;
this.propertyName = e.args.propertyName;
this.type = e.args.type;
}
isAllowed(e) {
return this.entityMetadata.target === e.constructor || typeof this.entityMetadata.target === "function" && e.constructor.prototype instanceof this.entityMetadata.target;
}
execute(e) {
if (!this.embeddedMetadata) {
const t = e[this.propertyName];
if (!t) throw new Error(`Entity listener method "${this.propertyName}" does not exist in entity "${e.constructor.name}".`);
if (typeof t !== "function") throw new Error(`Entity listener method "${this.propertyName}" in entity "${e.constructor.name}" must be a function but got "${typeof t}".`);
return t.call(e);
}
this.callEntityEmbeddedMethod(e, this.embeddedMetadata.propertyPath.split("."));
}
callEntityEmbeddedMethod(e, t) {
const n = t.shift();
if (!n || !e[n]) return;
if (t.length === 0) {
if (Array.isArray(e[n])) {
e[n].map(e => e[this.propertyName]());
} else {
e[n][this.propertyName]();
}
} else {
if (e[n]) this.callEntityEmbeddedMethod(e[n], t);
}
}
}
bS.EntityListenerMetadata = EntityListenerMetadata;
var CS = {};
Object.defineProperty(CS, "__esModule", {
value: true
});
CS.CheckMetadata = void 0;
class CheckMetadata {
constructor(e) {
this.entityMetadata = e.entityMetadata;
if (e.args) {
this.target = e.args.target;
this.expression = e.args.expression;
this.givenName = e.args.name;
}
}
build(e) {
this.name = this.givenName ? this.givenName : e.checkConstraintName(this.entityMetadata.tableName, this.expression);
return this;
}
}
CS.CheckMetadata = CheckMetadata;
var RS = {};
Object.defineProperty(RS, "__esModule", {
value: true
});
RS.ExclusionMetadata = void 0;
class ExclusionMetadata {
constructor(e) {
this.entityMetadata = e.entityMetadata;
if (e.args) {
this.target = e.args.target;
this.expression = e.args.expression;
this.givenName = e.args.name;
}
}
build(e) {
this.name = this.givenName ? this.givenName : e.exclusionConstraintName(this.entityMetadata.tableName, this.expression);
return this;
}
}
RS.ExclusionMetadata = ExclusionMetadata;
Object.defineProperty($R, "__esModule", {
value: true
});
$R.EntityMetadataBuilder = void 0;
const SS = vp;
const wS = xR;
const MS = jR;
const OS = QR;
const vS = GR;
const IS = zR;
const PS = XR;
const LS = eS;
const DS = xh;
const _S = tS;
const $S = lS;
const xS = mS;
const qS = bS;
const US = fS;
const BS = CS;
const FS = RS;
const jS = P;
const kS = jn;
const QS = nS;
const VS = Te;
class EntityMetadataBuilder {
constructor(e, t) {
this.connection = e;
this.metadataArgsStorage = t;
this.junctionEntityMetadataBuilder = new _S.JunctionEntityMetadataBuilder(e);
this.closureJunctionEntityMetadataBuilder = new $S.ClosureJunctionEntityMetadataBuilder(e);
this.relationJoinColumnBuilder = new xS.RelationJoinColumnBuilder(e);
}
build(e) {
const t = e ? this.metadataArgsStorage.filterTables(e) : this.metadataArgsStorage.tables;
const n = t.filter(e => e.type === "regular" || e.type === "closure" || e.type === "entity-child" || e.type === "view");
const a = n.map(e => this.createEntityMetadata(e));
a.forEach(e => this.computeParentEntityMetadata(a, e));
a.forEach(e => {
e.childEntityMetadatas = a.filter(t => typeof e.target === "function" && typeof t.target === "function" && DS.MetadataUtils.isInherited(t.target, e.target));
});
a.filter(e => e.tableType !== "entity-child").forEach(e => e.build());
a.filter(e => e.tableType === "entity-child").forEach(e => e.build());
a.filter(e => e.tableType !== "entity-child").forEach(e => this.computeEntityMetadataStep1(a, e));
a.filter(e => e.tableType === "entity-child").forEach(e => this.computeEntityMetadataStep1(a, e));
a.forEach(e => this.computeEntityMetadataStep2(e));
a.forEach(e => this.computeInverseProperties(e, a));
a.filter(e => e.tableType !== "entity-child").forEach(e => {
e.relations.filter(e => e.isOneToOne || e.isManyToOne).forEach(t => {
const n = this.metadataArgsStorage.filterJoinColumns(t.target, t.propertyName);
const {foreignKey: a, columns: r, uniqueConstraint: i} = this.relationJoinColumnBuilder.build(n, t);
if (a) {
t.registerForeignKeys(a);
e.foreignKeys.push(a);
}
if (r) {
t.registerJoinColumns(r);
}
if (i) {
if (kS.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql" || this.connection.driver.options.type === "mssql" || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
const n = new MS.IndexMetadata({
entityMetadata: i.entityMetadata,
columns: i.columns,
args: {
target: i.target,
name: i.name,
unique: true,
synchronize: true
}
});
if (this.connection.driver.options.type === "mssql") {
n.where = n.columns.map(e => `${this.connection.driver.escape(e.databaseName)} IS NOT NULL`).join(" AND ");
}
if (this.connection.driver.options.type === "spanner") {
n.isNullFiltered = true;
}
if (t.embeddedMetadata) {
t.embeddedMetadata.indices.push(n);
} else {
t.entityMetadata.ownIndices.push(n);
}
this.computeEntityMetadataStep2(e);
} else {
if (t.embeddedMetadata) {
t.embeddedMetadata.uniques.push(i);
} else {
t.entityMetadata.ownUniques.push(i);
}
this.computeEntityMetadataStep2(e);
}
}
if (a && this.connection.driver.options.type === "cockroachdb") {
const n = new MS.IndexMetadata({
entityMetadata: t.entityMetadata,
columns: a.columns,
args: {
target: t.entityMetadata.target,
synchronize: true
}
});
if (t.embeddedMetadata) {
t.embeddedMetadata.indices.push(n);
} else {
t.entityMetadata.ownIndices.push(n);
}
this.computeEntityMetadataStep2(e);
}
});
e.relations.filter(e => e.isManyToMany).forEach(e => {
const t = this.metadataArgsStorage.findJoinTable(e.target, e.propertyName);
if (!t) return;
const n = this.junctionEntityMetadataBuilder.build(e, t);
e.registerForeignKeys(...n.foreignKeys);
e.registerJoinColumns(n.ownIndices[0].columns, n.ownIndices[1].columns);
e.registerJunctionEntityMetadata(n);
this.computeEntityMetadataStep2(n);
this.computeInverseProperties(n, a);
a.push(n);
});
});
a.forEach(e => {
e.relationsWithJoinColumns = e.relations.filter(e => e.isWithJoinColumn);
e.hasNonNullableRelations = e.relationsWithJoinColumns.some(e => !e.isNullable || e.isPrimary);
});
a.filter(e => e.treeType === "closure-table").forEach(e => {
const t = this.closureJunctionEntityMetadataBuilder.build(e);
e.closureJunctionTable = t;
this.computeEntityMetadataStep2(t);
this.computeInverseProperties(t, a);
a.push(t);
});
a.filter(e => e.inheritancePattern === "STI" && e.discriminatorColumn).forEach(e => this.createKeysForTableInheritance(e));
a.forEach(e => {
e.indices.forEach(e => e.build(this.connection.namingStrategy));
});
a.forEach(e => {
e.uniques.forEach(e => e.build(this.connection.namingStrategy));
});
a.forEach(e => {
e.checks.forEach(e => e.build(this.connection.namingStrategy));
});
a.forEach(e => {
e.exclusions.forEach(e => e.build(this.connection.namingStrategy));
});
a.forEach(e => this.createForeignKeys(e, a));
a.filter(e => typeof e.target === "function").forEach(e => {
e.relations.filter(e => e.isLazy).forEach(t => {
this.connection.relationLoader.enableLazyLoad(t, e.target.prototype);
});
});
a.forEach(e => {
e.columns.forEach(t => {
const n = this.metadataArgsStorage.findGenerated(t.target, t.propertyName);
if (n) {
t.isGenerated = true;
t.generationStrategy = n.strategy;
if (n.strategy === "uuid") {
t.type = "uuid";
} else if (n.strategy === "rowid") {
t.type = "int";
} else {
t.type = t.type || Number;
}
t.build(this.connection);
this.computeEntityMetadataStep2(e);
}
});
});
return a;
}
createEntityMetadata(e) {
const t = typeof e.target === "function" ? DS.MetadataUtils.getInheritanceTree(e.target) : [ e.target ];
const n = this.metadataArgsStorage.findInheritanceType(e.target);
const a = this.metadataArgsStorage.findTree(e.target);
let r;
if (n && n.pattern === "STI" || e.type === "entity-child") {
r = this.metadataArgsStorage.filterSingleTableChildren(e.target).map(e => e.target).filter(e => typeof e === "function");
t.push(...r);
}
return new SS.EntityMetadata({
connection: this.connection,
args: e,
inheritanceTree: t,
tableTree: a,
inheritancePattern: n ? n.pattern : undefined
});
}
computeParentEntityMetadata(e, t) {
if (t.tableType === "entity-child") {
t.parentEntityMetadata = e.find(e => e.inheritanceTree.indexOf(t.target) !== -1 && e.inheritancePattern === "STI");
}
}
computeEntityMetadataStep1(e, t) {
const n = this.metadataArgsStorage.findInheritanceType(t.target);
const a = this.metadataArgsStorage.findDiscriminatorValue(t.target);
if (typeof a !== "undefined") {
t.discriminatorValue = a.value;
} else {
t.discriminatorValue = t.target.name;
}
t.embeddeds = this.createEmbeddedsRecursively(t, this.metadataArgsStorage.filterEmbeddeds(t.inheritanceTree)).map(e => {
if (t.inheritancePattern === "STI") {
e.columns = e.columns.map(e => {
e.isNullable = true;
return e;
});
}
return e;
});
t.ownColumns = this.metadataArgsStorage.filterColumns(t.inheritanceTree).map(n => {
if (t.tableType === "entity-child") return t.parentEntityMetadata.ownColumns.find(e => e.propertyName === n.propertyName);
if (t.tableType === "regular" && n.target !== t.target) {
const e = this.metadataArgsStorage.columns.find(e => e.propertyName === n.propertyName && e.target === t.target);
if (e && e.options.default) {
n.options.default = e.options.default;
}
}
const a = new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
args: n
});
const r = e.find(e => e.tableType === "entity-child" && e.target === n.target);
if (r) a.isNullable = true;
return a;
});
if (n && n.column) {
const e = n.column && n.column.name ? n.column.name : "type";
let a = t.ownColumns.find(t => t.propertyName === e);
if (!a) {
a = new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
args: {
target: t.target,
mode: "virtual",
propertyName: e,
options: n.column || {
name: e,
type: "varchar",
nullable: false
}
}
});
a.isVirtual = true;
a.isDiscriminator = true;
t.ownColumns.push(a);
} else {
a.isDiscriminator = true;
}
}
if (t.tableType === "entity-child") {
const e = t.parentEntityMetadata.ownColumns.find(e => e.isDiscriminator);
if (e && !t.ownColumns.find(t => t === e)) {
t.ownColumns.push(e);
}
t.inheritancePattern = t.parentEntityMetadata.inheritancePattern;
if (!t.treeType && !!t.parentEntityMetadata.treeType) {
t.treeType = t.parentEntityMetadata.treeType;
t.treeOptions = t.parentEntityMetadata.treeOptions;
t.treeParentRelation = t.parentEntityMetadata.treeParentRelation;
t.treeLevelColumn = t.parentEntityMetadata.treeLevelColumn;
}
}
const {namingStrategy: r} = this.connection;
if (t.treeType === "materialized-path") {
t.ownColumns.push(new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
materializedPath: true,
args: {
target: t.target,
mode: "virtual",
propertyName: "mpath",
options: {
name: r.materializedPathColumnName,
type: String,
nullable: true,
default: ""
}
}
}));
} else if (t.treeType === "nested-set") {
const {left: e, right: n} = r.nestedSetColumnNames;
t.ownColumns.push(new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
nestedSetLeft: true,
args: {
target: t.target,
mode: "virtual",
propertyName: e,
options: {
name: e,
type: Number,
nullable: false,
default: 1
}
}
}));
t.ownColumns.push(new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: t,
nestedSetRight: true,
args: {
target: t.target,
mode: "virtual",
propertyName: n,
options: {
name: n,
type: Number,
nullable: false,
default: 2
}
}
}));
}
t.ownRelations = this.metadataArgsStorage.filterRelations(t.inheritanceTree).map(e => {
if (t.tableType === "entity-child") {
const n = t.parentEntityMetadata.ownRelations.find(t => t.propertyName === e.propertyName);
const a = typeof e.type === "function" ? e.type() : e.type;
if (n.type !== a) {
const e = Object.create(n);
e.type = a;
return e;
}
return n;
}
return new OS.RelationMetadata({
entityMetadata: t,
args: e
});
});
t.relationIds = this.metadataArgsStorage.filterRelationIds(t.inheritanceTree).map(e => {
if (t.tableType === "entity-child") return t.parentEntityMetadata.relationIds.find(t => t.propertyName === e.propertyName);
return new IS.RelationIdMetadata({
entityMetadata: t,
args: e
});
});
t.relationCounts = this.metadataArgsStorage.filterRelationCounts(t.inheritanceTree).map(e => {
if (t.tableType === "entity-child") return t.parentEntityMetadata.relationCounts.find(t => t.propertyName === e.propertyName);
return new PS.RelationCountMetadata({
entityMetadata: t,
args: e
});
});
t.ownListeners = this.metadataArgsStorage.filterListeners(t.inheritanceTree).map(e => new qS.EntityListenerMetadata({
entityMetadata: t,
args: e
}));
t.checks = this.metadataArgsStorage.filterChecks(t.inheritanceTree).map(e => new BS.CheckMetadata({
entityMetadata: t,
args: e
}));
if (this.connection.driver.options.type === "postgres") {
t.exclusions = this.metadataArgsStorage.filterExclusions(t.inheritanceTree).map(e => new FS.ExclusionMetadata({
entityMetadata: t,
args: e
}));
}
if (this.connection.driver.options.type === "cockroachdb") {
t.ownIndices = this.metadataArgsStorage.filterIndices(t.inheritanceTree).filter(e => !e.unique).map(e => new MS.IndexMetadata({
entityMetadata: t,
args: e
}));
const e = this.metadataArgsStorage.filterIndices(t.inheritanceTree).filter(e => e.unique).map(e => new US.UniqueMetadata({
entityMetadata: t,
args: {
target: e.target,
name: e.name,
columns: e.columns
}
}));
t.ownUniques.push(...e);
} else {
t.ownIndices = this.metadataArgsStorage.filterIndices(t.inheritanceTree).map(e => new MS.IndexMetadata({
entityMetadata: t,
args: e
}));
}
if (kS.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql" || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
const e = this.metadataArgsStorage.filterUniques(t.inheritanceTree).map(e => new MS.IndexMetadata({
entityMetadata: t,
args: {
target: e.target,
name: e.name,
columns: e.columns,
unique: true,
synchronize: true
}
}));
t.ownIndices.push(...e);
} else {
const e = this.metadataArgsStorage.filterUniques(t.inheritanceTree).map(e => new US.UniqueMetadata({
entityMetadata: t,
args: e
}));
t.ownUniques.push(...e);
}
}
createEmbeddedsRecursively(e, t) {
return t.map(t => {
const n = new vS.EmbeddedMetadata({
entityMetadata: e,
args: t
});
const a = typeof n.type === "function" ? DS.MetadataUtils.getInheritanceTree(n.type) : [ n.type ];
n.columns = this.metadataArgsStorage.filterColumns(a).map(t => new wS.ColumnMetadata({
connection: this.connection,
entityMetadata: e,
embeddedMetadata: n,
args: t
}));
n.relations = this.metadataArgsStorage.filterRelations(a).map(t => new OS.RelationMetadata({
entityMetadata: e,
embeddedMetadata: n,
args: t
}));
n.listeners = this.metadataArgsStorage.filterListeners(a).map(t => new qS.EntityListenerMetadata({
entityMetadata: e,
embeddedMetadata: n,
args: t
}));
n.indices = this.metadataArgsStorage.filterIndices(a).map(t => new MS.IndexMetadata({
entityMetadata: e,
embeddedMetadata: n,
args: t
}));
n.uniques = this.metadataArgsStorage.filterUniques(a).map(t => new US.UniqueMetadata({
entityMetadata: e,
embeddedMetadata: n,
args: t
}));
n.relationIds = this.metadataArgsStorage.filterRelationIds(a).map(t => new IS.RelationIdMetadata({
entityMetadata: e,
args: t
}));
n.relationCounts = this.metadataArgsStorage.filterRelationCounts(a).map(t => new PS.RelationCountMetadata({
entityMetadata: e,
args: t
}));
n.embeddeds = this.createEmbeddedsRecursively(e, this.metadataArgsStorage.filterEmbeddeds(a));
n.embeddeds.forEach(e => e.parentEmbeddedMetadata = n);
e.allEmbeddeds.push(n);
return n;
});
}
computeEntityMetadataStep2(e) {
e.embeddeds.forEach(e => e.build(this.connection));
e.embeddeds.forEach(e => {
e.columnsFromTree.forEach(e => e.build(this.connection));
e.relationsFromTree.forEach(e => e.build());
});
e.ownColumns.forEach(e => e.build(this.connection));
e.ownRelations.forEach(e => e.build());
e.relations = e.embeddeds.reduce((e, t) => e.concat(t.relationsFromTree), e.ownRelations);
e.eagerRelations = e.relations.filter(e => e.isEager);
e.lazyRelations = e.relations.filter(e => e.isLazy);
e.oneToOneRelations = e.relations.filter(e => e.isOneToOne);
e.oneToManyRelations = e.relations.filter(e => e.isOneToMany);
e.manyToOneRelations = e.relations.filter(e => e.isManyToOne);
e.manyToManyRelations = e.relations.filter(e => e.isManyToMany);
e.ownerOneToOneRelations = e.relations.filter(e => e.isOneToOneOwner);
e.ownerManyToManyRelations = e.relations.filter(e => e.isManyToManyOwner);
e.treeParentRelation = e.relations.find(e => e.isTreeParent);
e.treeChildrenRelation = e.relations.find(e => e.isTreeChildren);
e.columns = e.embeddeds.reduce((e, t) => e.concat(t.columnsFromTree), e.ownColumns);
e.listeners = e.embeddeds.reduce((e, t) => e.concat(t.listenersFromTree), e.ownListeners);
e.afterLoadListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_LOAD);
e.afterInsertListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_INSERT);
e.afterUpdateListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_UPDATE);
e.afterRemoveListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_REMOVE);
e.afterSoftRemoveListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_SOFT_REMOVE);
e.afterRecoverListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.AFTER_RECOVER);
e.beforeInsertListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.BEFORE_INSERT);
e.beforeUpdateListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.BEFORE_UPDATE);
e.beforeRemoveListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.BEFORE_REMOVE);
e.beforeSoftRemoveListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.BEFORE_SOFT_REMOVE);
e.beforeRecoverListeners = e.listeners.filter(e => e.type === LS.EventListenerTypes.BEFORE_RECOVER);
e.indices = e.embeddeds.reduce((e, t) => e.concat(t.indicesFromTree), e.ownIndices);
e.uniques = e.embeddeds.reduce((e, t) => e.concat(t.uniquesFromTree), e.ownUniques);
e.primaryColumns = e.columns.filter(e => e.isPrimary);
e.nonVirtualColumns = e.columns.filter(e => !e.isVirtual);
e.ancestorColumns = e.columns.filter(e => e.closureType === "ancestor");
e.descendantColumns = e.columns.filter(e => e.closureType === "descendant");
e.hasMultiplePrimaryKeys = e.primaryColumns.length > 1;
e.generatedColumns = e.columns.filter(e => e.isGenerated || e.isObjectId);
e.hasUUIDGeneratedColumns = e.columns.filter(e => e.isGenerated || e.generationStrategy === "uuid").length > 0;
e.createDateColumn = e.columns.find(e => e.isCreateDate);
e.updateDateColumn = e.columns.find(e => e.isUpdateDate);
e.deleteDateColumn = e.columns.find(e => e.isDeleteDate);
e.versionColumn = e.columns.find(e => e.isVersion);
e.discriminatorColumn = e.columns.find(e => e.isDiscriminator);
e.treeLevelColumn = e.columns.find(e => e.isTreeLevel);
e.nestedSetLeftColumn = e.columns.find(e => e.isNestedSetLeft);
e.nestedSetRightColumn = e.columns.find(e => e.isNestedSetRight);
e.materializedPathColumn = e.columns.find(e => e.isMaterializedPath);
e.objectIdColumn = e.columns.find(e => e.isObjectId);
e.foreignKeys.forEach(e => e.build(this.connection.namingStrategy));
e.propertiesMap = e.createPropertiesMap();
e.relationIds.forEach(e => e.build());
e.relationCounts.forEach(e => e.build());
e.embeddeds.forEach(e => {
e.relationIdsFromTree.forEach(e => e.build());
e.relationCountsFromTree.forEach(e => e.build());
});
}
computeInverseProperties(e, t) {
e.relations.forEach(n => {
const a = t.find(e => e.target === n.type || typeof n.type === "string" && (e.targetName === n.type || e.givenTableName === n.type));
if (!a) throw new jS.TypeORMError("Entity metadata for " + e.name + "#" + n.propertyPath + " was not found. Check if you specified a correct entity object and if it's connected in the connection options.");
n.inverseEntityMetadata = a;
n.inverseSidePropertyPath = n.buildInverseSidePropertyPath();
n.inverseRelation = a.relations.find(e => e.propertyPath === n.inverseSidePropertyPath);
});
}
createKeysForTableInheritance(e) {
const t = e.indices.some(({givenColumnNames: t}) => !!t && Array.isArray(t) && t.length === 1 && t[0] === e.discriminatorColumn?.databaseName);
if (t) {
return;
}
e.indices.push(new MS.IndexMetadata({
entityMetadata: e,
columns: [ e.discriminatorColumn ],
args: {
target: e.target,
unique: false
}
}));
}
createForeignKeys(e, t) {
this.metadataArgsStorage.filterForeignKeys(e.inheritanceTree).forEach(n => {
const a = typeof n.type === "function" ? n.type() : n.type;
const r = t.find(e => typeof a === "string" ? e.targetName === a || e.givenTableName === a : VS.InstanceChecker.isEntitySchema(a) ? e.target === a.options.name || e.target === a.options.target : e.target === a);
if (!r) {
throw new jS.TypeORMError("Entity metadata for " + e.name + (n.propertyName ? "#" + n.propertyName : "") + " was not found. Check if you specified a correct entity object and if it's connected in the connection options.");
}
const i = n.columnNames ?? [];
const s = n.referencedColumnNames ?? [];
const o = [];
const c = [];
if (n.propertyName) {
i.push(n.propertyName);
if (n.inverseSide) {
if (typeof n.inverseSide === "function") {
s.push(n.inverseSide(r.propertiesMap));
} else {
s.push(n.inverseSide);
}
}
}
if (!s.length) {
c.push(...r.primaryColumns);
}
const l = (e, t) => {
const a = t.columns.find(t => t.propertyName === e || t.databaseName === e);
if (a) return a;
const r = n.name ? '"' + n.name + '" ' : "";
const i = t.targetName;
throw new jS.TypeORMError(`Foreign key constraint ${r}contains column that is missing in the entity (${i}): ${e}`);
};
o.push(...i.map(t => l(t, e)));
c.push(...s.map(e => l(e, r)));
e.foreignKeys.push(new QS.ForeignKeyMetadata({
entityMetadata: e,
referencedEntityMetadata: r,
namingStrategy: this.connection.namingStrategy,
columns: o,
referencedColumns: c,
...n
}));
});
}
}
$R.EntityMetadataBuilder = EntityMetadataBuilder;
var KS = {};
var WS = {};
Object.defineProperty(WS, "__esModule", {
value: true
});
WS.EntitySchemaEmbeddedError = void 0;
const HS = P;
class EntitySchemaEmbeddedError extends HS.TypeORMError {
static createEntitySchemaIsRequiredException(e) {
return new EntitySchemaEmbeddedError(`EntitySchema is required for ${e} embedded field`);
}
static createTargetIsRequired(e) {
return new EntitySchemaEmbeddedError(`Target field is required for ${e} embedded EntitySchema`);
}
constructor(e) {
super(e);
}
}
WS.EntitySchemaEmbeddedError = EntitySchemaEmbeddedError;
Object.defineProperty(KS, "__esModule", {
value: true
});
KS.EntitySchemaTransformer = void 0;
const GS = $h;
const YS = WS;
class EntitySchemaTransformer {
transform(e) {
const t = new GS.MetadataArgsStorage;
e.forEach(e => {
const n = e.options;
const a = {
target: n.target || n.name,
name: n.tableName,
database: n.database,
schema: n.schema,
type: n.type || "regular",
orderBy: n.orderBy,
synchronize: n.synchronize,
withoutRowid: !!n.withoutRowid,
expression: n.expression
};
t.tables.push(a);
const {inheritance: r} = n;
if (r) {
t.inheritances.push({
target: n.target,
pattern: r.pattern ?? "STI",
column: r.column ? typeof r.column === "string" ? {
name: r.column
} : r.column : undefined
});
}
const {discriminatorValue: i} = n;
if (i) {
t.discriminatorValues.push({
target: n.target || n.name,
value: i
});
}
this.transformColumnsRecursive(n, t);
});
return t;
}
transformColumnsRecursive(e, t) {
Object.keys(e.columns).forEach(n => {
const a = e.columns[n];
const r = a;
let i = "regular";
if (r.createDate) i = "createDate";
if (r.updateDate) i = "updateDate";
if (r.deleteDate) i = "deleteDate";
if (r.version) i = "version";
if (r.treeChildrenCount) i = "treeChildrenCount";
if (r.treeLevel) i = "treeLevel";
if (r.objectId) i = "objectId";
const s = {
target: e.target || e.name,
mode: i,
propertyName: n,
options: {
type: r.type,
name: r.objectId ? "_id" : r.name,
primaryKeyConstraintName: r.primaryKeyConstraintName,
length: r.length,
width: r.width,
nullable: r.nullable,
readonly: r.readonly,
update: r.update,
select: r.select,
insert: r.insert,
primary: r.primary,
unique: r.unique,
comment: r.comment,
default: r.default,
onUpdate: r.onUpdate,
precision: r.precision,
scale: r.scale,
zerofill: r.zerofill,
unsigned: r.unsigned,
charset: r.charset,
collation: r.collation,
enum: r.enum,
enumName: r.enumName,
asExpression: r.asExpression,
generatedType: r.generatedType,
hstoreType: r.hstoreType,
array: r.array,
transformer: r.transformer,
spatialFeatureType: r.spatialFeatureType,
srid: r.srid
}
};
t.columns.push(s);
if (r.generated) {
const a = {
target: e.target || e.name,
propertyName: n,
strategy: typeof r.generated === "string" ? r.generated : "increment"
};
t.generations.push(a);
}
if (r.unique) t.uniques.push({
target: e.target || e.name,
columns: [ n ]
});
if (r.foreignKey) {
const a = r.foreignKey;
const i = {
target: e.target || e.name,
type: a.target,
propertyName: n,
inverseSide: a.inverseSide,
name: a.name,
onDelete: a.onDelete,
onUpdate: a.onUpdate,
deferrable: a.deferrable
};
t.foreignKeys.push(i);
}
});
if (e.relations) {
Object.keys(e.relations).forEach(n => {
const a = e.relations[n];
const r = {
target: e.target || e.name,
propertyName: n,
relationType: a.type,
isLazy: a.lazy || false,
type: a.target,
inverseSideProperty: a.inverseSide,
isTreeParent: a.treeParent,
isTreeChildren: a.treeChildren,
options: {
eager: a.eager || false,
cascade: a.cascade,
nullable: a.nullable,
onDelete: a.onDelete,
onUpdate: a.onUpdate,
deferrable: a.deferrable,
createForeignKeyConstraints: a.createForeignKeyConstraints,
persistence: a.persistence,
orphanedRowAction: a.orphanedRowAction
}
};
t.relations.push(r);
if (a.joinColumn) {
if (typeof a.joinColumn === "boolean") {
const a = {
target: e.target || e.name,
propertyName: n
};
t.joinColumns.push(a);
} else {
const r = Array.isArray(a.joinColumn) ? a.joinColumn : [ a.joinColumn ];
for (const a of r) {
const r = {
target: e.target || e.name,
propertyName: n,
name: a.name,
referencedColumnName: a.referencedColumnName,
foreignKeyConstraintName: a.foreignKeyConstraintName
};
t.joinColumns.push(r);
}
}
}
if (a.joinTable) {
if (typeof a.joinTable === "boolean") {
const a = {
target: e.target || e.name,
propertyName: n
};
t.joinTables.push(a);
} else {
const r = {
target: e.target || e.name,
propertyName: n,
name: a.joinTable.name,
database: a.joinTable.database,
schema: a.joinTable.schema,
joinColumns: a.joinTable.joinColumn ? [ a.joinTable.joinColumn ] : a.joinTable.joinColumns,
inverseJoinColumns: a.joinTable.inverseJoinColumn ? [ a.joinTable.inverseJoinColumn ] : a.joinTable.inverseJoinColumns
};
t.joinTables.push(r);
}
}
});
}
if (e.relationIds) {
Object.keys(e.relationIds).forEach(n => {
const a = e.relationIds[n];
const r = {
propertyName: n,
relation: a.relationName,
target: e.target || e.name,
alias: a.alias,
queryBuilderFactory: a.queryBuilderFactory
};
t.relationIds.push(r);
});
}
if (e.indices) {
e.indices.forEach(n => {
const a = {
target: e.target || e.name,
name: n.name,
unique: n.unique === true ? true : false,
spatial: n.spatial === true ? true : false,
fulltext: n.fulltext === true ? true : false,
nullFiltered: n.nullFiltered === true ? true : false,
parser: n.parser,
synchronize: n.synchronize === false ? false : true,
where: n.where,
sparse: n.sparse,
columns: n.columns
};
t.indices.push(a);
});
}
if (e.foreignKeys) {
e.foreignKeys.forEach(n => {
const a = {
target: e.target || e.name,
type: n.target,
columnNames: n.columnNames,
referencedColumnNames: n.referencedColumnNames,
name: n.name,
onDelete: n.onDelete,
onUpdate: n.onUpdate,
deferrable: n.deferrable
};
t.foreignKeys.push(a);
});
}
if (e.uniques) {
e.uniques.forEach(n => {
const a = {
target: e.target || e.name,
name: n.name,
columns: n.columns,
deferrable: n.deferrable
};
t.uniques.push(a);
});
}
if (e.checks) {
e.checks.forEach(n => {
const a = {
target: e.target || e.name,
name: n.name,
expression: n.expression
};
t.checks.push(a);
});
}
if (e.exclusions) {
e.exclusions.forEach(n => {
const a = {
target: e.target || e.name,
name: n.name,
expression: n.expression
};
t.exclusions.push(a);
});
}
if (e.embeddeds) {
Object.keys(e.embeddeds).forEach(n => {
const a = e.embeddeds[n];
if (!a.schema) throw YS.EntitySchemaEmbeddedError.createEntitySchemaIsRequiredException(n);
const r = a.schema.options;
t.embeddeds.push({
target: e.target || e.name,
propertyName: n,
isArray: a.array === true,
prefix: a.prefix !== undefined ? a.prefix : undefined,
type: () => r?.target || r.name
});
this.transformColumnsRecursive(r, t);
});
}
}
}
KS.EntitySchemaTransformer = EntitySchemaTransformer;
var zS;
function JS() {
if (zS) return SC;
zS = 1;
Object.defineProperty(SC, "__esModule", {
value: true
});
SC.ConnectionMetadataBuilder = void 0;
const e = wC;
const t = qc;
const n = Hd;
const a = np();
const r = $R;
const i = KS;
const s = Te;
let o = class ConnectionMetadataBuilder {
constructor(e) {
this.connection = e;
}
async buildMigrations(a) {
const [r, i] = t.OrmUtils.splitClassesAndStrings(a);
const s = [ ...r, ...await (0, e.importClassesFromDirectories)(this.connection.logger, i) ];
return s.map(e => (0, n.getFromContainer)(e));
}
async buildSubscribers(r) {
const [i, s] = t.OrmUtils.splitClassesAndStrings(r || []);
const o = [ ...i, ...await (0, e.importClassesFromDirectories)(this.connection.logger, s) ];
return (0, a.getMetadataArgsStorage)().filterSubscribers(o).map(e => (0, n.getFromContainer)(e.target));
}
async buildEntityMetadatas(n) {
const [o, c] = t.OrmUtils.splitClassesAndStrings(n || []);
const l = o.filter(e => !s.InstanceChecker.isEntitySchema(e));
const u = o.filter(e => s.InstanceChecker.isEntitySchema(e));
const h = [ ...l, ...await (0, e.importClassesFromDirectories)(this.connection.logger, c) ];
h.forEach(e => {
if (s.InstanceChecker.isEntitySchema(e)) {
u.push(e);
}
});
const d = new r.EntityMetadataBuilder(this.connection, (0, a.getMetadataArgsStorage)()).build(h);
const p = (new i.EntitySchemaTransformer).transform(u);
const m = new r.EntityMetadataBuilder(this.connection, p).build();
return [ ...d, ...m ];
}
};
SC.ConnectionMetadataBuilder = o;
return SC;
}
var XS = {};
var ZS = {};
var ew = {};
Object.defineProperty(ew, "__esModule", {
value: true
});
var tw = ew.AbstractLogger = void 0;
const nw = Uh;
class AbstractLogger {
constructor(e) {
this.options = e;
}
logQuery(e, t, n) {
if (!this.isLogEnabledFor("query")) {
return;
}
this.writeLog("query", {
type: "query",
prefix: "query",
message: e,
format: "sql",
parameters: t
}, n);
}
logQueryError(e, t, n, a) {
if (!this.isLogEnabledFor("query-error")) {
return;
}
this.writeLog("warn", [ {
type: "query-error",
prefix: "query failed",
message: t,
format: "sql",
parameters: n
}, {
type: "query-error",
prefix: "error",
message: e
} ], a);
}
logQuerySlow(e, t, n, a) {
if (!this.isLogEnabledFor("query-slow")) {
return;
}
this.writeLog("warn", [ {
type: "query-slow",
prefix: "query is slow",
message: t,
format: "sql",
parameters: n,
additionalInfo: {
time: e
}
}, {
type: "query-slow",
prefix: "execution time",
message: e
} ], a);
}
logSchemaBuild(e, t) {
if (!this.isLogEnabledFor("schema-build")) {
return;
}
this.writeLog("schema", {
type: "schema-build",
message: e
}, t);
}
logMigration(e, t) {
if (!this.isLogEnabledFor("migration")) {
return;
}
this.writeLog("log", {
type: "migration",
message: e
}, t);
}
log(e, t, n) {
switch (e) {
case "log":
if (!this.isLogEnabledFor("log")) {
return;
}
this.writeLog("log", {
type: "log",
message: t
}, n);
break;
case "info":
if (!this.isLogEnabledFor("info")) {
return;
}
this.writeLog("info", {
type: "info",
prefix: "info",
message: t
}, n);
break;
case "warn":
if (!this.isLogEnabledFor("warn")) {
return;
}
this.writeLog("warn", {
type: "warn",
message: t
}, n);
break;
}
}
isLogEnabledFor(e) {
switch (e) {
case "query":
return this.options === "all" || this.options === true || Array.isArray(this.options) && this.options.indexOf("query") !== -1;
case "error":
case "query-error":
return this.options === "all" || this.options === true || Array.isArray(this.options) && this.options.indexOf("error") !== -1;
case "query-slow":
return true;
case "schema":
case "schema-build":
return this.options === "all" || Array.isArray(this.options) && this.options.indexOf("schema") !== -1;
case "migration":
return true;
case "log":
return this.options === "all" || Array.isArray(this.options) && this.options.indexOf("log") !== -1;
case "info":
return this.options === "all" || Array.isArray(this.options) && this.options.indexOf("info") !== -1;
case "warn":
return this.options === "all" || Array.isArray(this.options) && this.options.indexOf("warn") !== -1;
default:
return false;
}
}
prepareLogMessages(e, t, n) {
t = {
...{
addColonToPrefix: true,
appendParameterAsComment: true,
highlightSql: true,
formatSql: false
},
...t
};
const a = Array.isArray(e) ? e : [ e ];
for (let e of a) {
if (typeof e !== "object") {
e = {
message: e
};
}
if (e.format === "sql") {
let a = String(e.message);
if (t.formatSql) {
a = nw.PlatformTools.formatSql(a, n?.connection?.options.type);
}
if (t.appendParameterAsComment && e.parameters && e.parameters.length) {
a += ` -- PARAMETERS: ${this.stringifyParams(e.parameters)}`;
}
if (t.highlightSql) {
a = nw.PlatformTools.highlightSql(a);
}
e.message = a;
}
if (t.addColonToPrefix && e.prefix) {
e.prefix += ":";
}
}
return a;
}
stringifyParams(e) {
try {
return JSON.stringify(e);
} catch (t) {
return e;
}
}
}
tw = ew.AbstractLogger = AbstractLogger;
Object.defineProperty(ZS, "__esModule", {
value: true
});
var aw = ZS.SimpleConsoleLogger = void 0;
const rw = ew;
class SimpleConsoleLogger extends rw.AbstractLogger {
writeLog(e, t, n) {
const a = this.prepareLogMessages(t, {
highlightSql: false
});
for (const t of a) {
switch (t.type ?? e) {
case "log":
case "schema-build":
case "migration":
console.log(t.message);
break;
case "info":
case "query":
if (t.prefix) {
console.info(t.prefix, t.message);
} else {
console.info(t.message);
}
break;
case "warn":
case "query-slow":
if (t.prefix) {
console.warn(t.prefix, t.message);
} else {
console.warn(t.message);
}
break;
case "error":
case "query-error":
if (t.prefix) {
console.error(t.prefix, t.message);
} else {
console.error(t.message);
}
break;
}
}
}
}
aw = ZS.SimpleConsoleLogger = SimpleConsoleLogger;
var iw = {};
Object.defineProperty(iw, "__esModule", {
value: true
});
var sw = iw.AdvancedConsoleLogger = void 0;
const ow = Uh;
const cw = ew;
class AdvancedConsoleLogger extends cw.AbstractLogger {
writeLog(e, t, n) {
const a = this.prepareLogMessages(t);
for (const t of a) {
switch (t.type ?? e) {
case "log":
case "schema-build":
case "migration":
ow.PlatformTools.log(String(t.message));
break;
case "info":
case "query":
if (t.prefix) {
ow.PlatformTools.logInfo(t.prefix, t.message);
} else {
ow.PlatformTools.log(String(t.message));
}
break;
case "warn":
case "query-slow":
if (t.prefix) {
ow.PlatformTools.logWarn(t.prefix, t.message);
} else {
console.warn(ow.PlatformTools.warn(String(t.message)));
}
break;
case "error":
case "query-error":
if (t.prefix) {
ow.PlatformTools.logError(t.prefix, String(t.message));
} else {
console.error(ow.PlatformTools.error(String(t.message)));
}
break;
}
}
}
}
sw = iw.AdvancedConsoleLogger = AdvancedConsoleLogger;
var lw = {};
Object.defineProperty(lw, "__esModule", {
value: true
});
var uw = lw.FileLogger = void 0;
const hw = e;
const dw = hw.__importDefault(Sd());
const pw = Uh;
const mw = ew;
class FileLogger extends mw.AbstractLogger {
constructor(e, t) {
super(e);
this.fileLoggerOptions = t;
}
writeLog(e, t, n) {
const a = this.prepareLogMessages(t, {
highlightSql: false,
addColonToPrefix: false
});
const r = [];
for (const t of a) {
switch (t.type ?? e) {
case "log":
r.push(`[LOG]: ${t.message}`);
break;
case "schema-build":
case "migration":
r.push(String(t.message));
break;
case "info":
r.push(`[INFO]: ${t.message}`);
break;
case "query":
r.push(`[QUERY]: ${t.message}`);
break;
case "warn":
r.push(`[WARN]: ${t.message}`);
break;
case "query-slow":
if (t.prefix === "execution time") {
continue;
}
this.write(`[SLOW QUERY: ${t.additionalInfo?.time} ms]: ${t.message}`);
break;
case "error":
case "query-error":
if (t.prefix === "query failed") {
r.push(`[FAILED QUERY]: ${t.message}`);
} else if (t.type === "query-error") {
r.push(`[QUERY ERROR]: ${t.message}`);
} else {
r.push(`[ERROR]: ${t.message}`);
}
break;
}
}
this.write(r);
}
write(e) {
e = Array.isArray(e) ? e : [ e ];
const t = dw.default.path + "/";
let n = "ormlogs.log";
if (this.fileLoggerOptions && this.fileLoggerOptions.logPath) {
n = pw.PlatformTools.pathNormalize(this.fileLoggerOptions.logPath);
}
e = e.map(e => "[" + (new Date).toISOString() + "]" + e);
pw.PlatformTools.appendFileSync(t + n, e.join("\r\n") + "\r\n");
}
}
uw = lw.FileLogger = FileLogger;
var fw = {};
Object.defineProperty(fw, "__esModule", {
value: true
});
fw.DebugLogger = void 0;
const yw = ew;
const Ew = a;
class DebugLogger extends yw.AbstractLogger {
constructor() {
super(...arguments);
this.logger = {
log: (0, Ew.debug)("typeorm:log"),
info: (0, Ew.debug)("typeorm:info"),
warn: (0, Ew.debug)("typeorm:warn"),
error: (0, Ew.debug)("typeorm:error"),
query: (0, Ew.debug)("typeorm:query:log"),
"query-error": (0, Ew.debug)("typeorm:query:error"),
"query-slow": (0, Ew.debug)("typeorm:query:slow"),
"schema-build": (0, Ew.debug)("typeorm:schema"),
migration: (0, Ew.debug)("typeorm:migration")
};
}
isLogEnabledFor(e) {
switch (e) {
case "query":
return this.logger["query"].enabled;
case "query-error":
return this.logger["query-error"].enabled;
case "query-slow":
return true;
case "schema":
case "schema-build":
return this.logger["schema-build"].enabled;
case "migration":
return this.logger["migration"].enabled;
case "log":
return this.logger["log"].enabled;
case "info":
return this.logger["info"].enabled;
case "warn":
return this.logger["warn"].enabled;
default:
return false;
}
}
writeLog(e, t, n) {
const a = this.prepareLogMessages(t, {
appendParameterAsComment: false
});
for (const t of a) {
const n = t.type ?? e;
if (n in this.logger) {
if (t.prefix) {
this.logger[n](t.prefix, t.message);
} else {
this.logger[n](t.message);
}
if (t.parameters && t.parameters.length) {
this.logger[n]("parameters:", t.parameters);
}
}
}
}
}
fw.DebugLogger = DebugLogger;
var Tw = {};
Object.defineProperty(Tw, "__esModule", {
value: true
});
Tw.FormattedConsoleLogger = void 0;
const gw = Uh;
const Nw = ew;
class FormattedConsoleLogger extends Nw.AbstractLogger {
writeLog(e, t, n) {
const a = this.prepareLogMessages(t, {
highlightSql: true,
formatSql: true
}, n);
for (let t of a) {
switch (t.type ?? e) {
case "log":
case "schema-build":
case "migration":
gw.PlatformTools.log(String(t.message));
break;
case "info":
case "query":
if (t.prefix) {
gw.PlatformTools.logInfo(t.prefix, t.message);
} else {
gw.PlatformTools.log(String(t.message));
}
break;
case "warn":
case "query-slow":
if (t.prefix) {
gw.PlatformTools.logWarn(t.prefix, t.message);
} else {
console.warn(gw.PlatformTools.warn(String(t.message)));
}
break;
case "error":
case "query-error":
if (t.prefix) {
gw.PlatformTools.logError(t.prefix, String(t.message));
} else {
console.error(gw.PlatformTools.error(String(t.message)));
}
break;
}
}
}
}
Tw.FormattedConsoleLogger = FormattedConsoleLogger;
Object.defineProperty(XS, "__esModule", {
value: true
});
XS.LoggerFactory = void 0;
const Aw = ZS;
const bw = iw;
const Cw = lw;
const Rw = fw;
const Sw = I;
const ww = Tw;
class LoggerFactory {
create(e, t) {
if (Sw.ObjectUtils.isObject(e)) return e;
if (e) {
switch (e) {
case "simple-console":
return new Aw.SimpleConsoleLogger(t);
case "file":
return new Cw.FileLogger(t);
case "advanced-console":
return new bw.AdvancedConsoleLogger(t);
case "formatted-console":
return new ww.FormattedConsoleLogger(t);
case "debug":
return new Rw.DebugLogger;
}
}
return new bw.AdvancedConsoleLogger(t);
}
}
XS.LoggerFactory = LoggerFactory;
var Mw = {};
var Ow = {};
Object.defineProperty(Ow, "__esModule", {
value: true
});
Ow.RedisQueryResultCache = void 0;
const vw = Uh;
const Iw = D;
class RedisQueryResultCache {
constructor(e, t) {
this.connection = e;
this.clientType = t;
this.redis = this.loadRedis();
}
async connect() {
const e = this.connection.options.cache;
if (this.clientType === "redis") {
this.client = this.redis.createClient({
...e?.options,
legacyMode: true
});
if (typeof this.connection.options.cache === "object" && this.connection.options.cache.ignoreErrors) {
this.client.on("error", e => {
this.connection.logger.log("warn", e);
});
}
if ("connect" in this.client) {
await this.client.connect();
}
} else if (this.clientType === "ioredis") {
if (e && e.port) {
if (e.options) {
this.client = new this.redis(e.port, e.options);
} else {
this.client = new this.redis(e.port);
}
} else if (e && e.options) {
this.client = new this.redis(e.options);
} else {
this.client = new this.redis;
}
} else if (this.clientType === "ioredis/cluster") {
if (e && e.options && Array.isArray(e.options)) {
this.client = new this.redis.Cluster(e.options);
} else if (e && e.options && e.options.startupNodes) {
this.client = new this.redis.Cluster(e.options.startupNodes, e.options.options);
} else {
throw new Iw.TypeORMError(`options.startupNodes required for ${this.clientType}.`);
}
}
}
async disconnect() {
return new Promise((e, t) => {
this.client.quit((n, a) => {
if (n) return t(n);
e();
this.client = undefined;
});
});
}
async synchronize(e) {}
getFromCache(e, t) {
return new Promise((t, n) => {
if (e.identifier) {
this.client.get(e.identifier, (e, a) => {
if (e) return n(e);
t(JSON.parse(a));
});
} else if (e.query) {
this.client.get(e.query, (e, a) => {
if (e) return n(e);
t(JSON.parse(a));
});
} else {
t(undefined);
}
});
}
isExpired(e) {
return e.time + e.duration < Date.now();
}
async storeInCache(e, t, n) {
return new Promise((t, n) => {
if (e.identifier) {
this.client.set(e.identifier, JSON.stringify(e), "PX", e.duration, (e, a) => {
if (e) return n(e);
t();
});
} else if (e.query) {
this.client.set(e.query, JSON.stringify(e), "PX", e.duration, (e, a) => {
if (e) return n(e);
t();
});
}
});
}
async clear(e) {
return new Promise((e, t) => {
this.client.flushdb((n, a) => {
if (n) return t(n);
e();
});
});
}
async remove(e, t) {
await Promise.all(e.map(e => this.deleteKey(e)));
}
deleteKey(e) {
return new Promise((t, n) => {
this.client.del(e, (e, a) => {
if (e) return n(e);
t();
});
});
}
loadRedis() {
try {
if (this.clientType === "ioredis/cluster") {
return vw.PlatformTools.load("ioredis");
} else {
return vw.PlatformTools.load(this.clientType);
}
} catch (e) {
throw new Iw.TypeORMError(`Cannot use cache because ${this.clientType} is not installed. Please run "npm i ${this.clientType} --save".`);
}
}
}
Ow.RedisQueryResultCache = RedisQueryResultCache;
var Pw = {};
Object.defineProperty(Pw, "__esModule", {
value: true
});
Pw.DbQueryResultCache = void 0;
const Lw = Bu;
const Dw = fu;
const _w = ic;
class DbQueryResultCache {
constructor(e) {
this.connection = e;
const {schema: t} = this.connection.driver.options;
const n = this.connection.driver.database;
const a = typeof this.connection.options.cache === "object" ? this.connection.options.cache : {};
const r = a.tableName || "query-result-cache";
this.queryResultCacheDatabase = n;
this.queryResultCacheSchema = t;
this.queryResultCacheTable = this.connection.driver.buildTableName(r, t, n);
}
async connect() {}
async disconnect() {}
async synchronize(e) {
e = this.getQueryRunner(e);
const t = this.connection.driver;
const n = await e.hasTable(this.queryResultCacheTable);
if (n) return;
await e.createTable(new Dw.Table({
database: this.queryResultCacheDatabase,
schema: this.queryResultCacheSchema,
name: this.queryResultCacheTable,
columns: [ {
name: "id",
isPrimary: true,
isNullable: false,
type: t.normalizeType({
type: t.mappedDataTypes.cacheId
}),
generationStrategy: t.options.type === "spanner" ? "uuid" : "increment",
isGenerated: true
}, {
name: "identifier",
type: t.normalizeType({
type: t.mappedDataTypes.cacheIdentifier
}),
isNullable: true
}, {
name: "time",
type: t.normalizeType({
type: t.mappedDataTypes.cacheTime
}),
isPrimary: false,
isNullable: false
}, {
name: "duration",
type: t.normalizeType({
type: t.mappedDataTypes.cacheDuration
}),
isPrimary: false,
isNullable: false
}, {
name: "query",
type: t.normalizeType({
type: t.mappedDataTypes.cacheQuery
}),
isPrimary: false,
isNullable: false
}, {
name: "result",
type: t.normalizeType({
type: t.mappedDataTypes.cacheResult
}),
isNullable: false
} ]
}));
}
getFromCache(e, t) {
t = this.getQueryRunner(t);
const n = this.connection.createQueryBuilder(t).select().from(this.queryResultCacheTable, "cache");
if (e.identifier) {
return n.where(`${n.escape("cache")}.${n.escape("identifier")} = :identifier`).setParameters({
identifier: this.connection.driver.options.type === "mssql" ? new Lw.MssqlParameter(e.identifier, "nvarchar") : e.identifier
}).cache(false).getRawOne();
} else if (e.query) {
if (this.connection.driver.options.type === "oracle") {
return n.where(`dbms_lob.compare(${n.escape("cache")}.${n.escape("query")}, :query) = 0`, {
query: e.query
}).cache(false).getRawOne();
}
return n.where(`${n.escape("cache")}.${n.escape("query")} = :query`).setParameters({
query: this.connection.driver.options.type === "mssql" ? new Lw.MssqlParameter(e.query, "nvarchar") : e.query
}).cache(false).getRawOne();
}
return Promise.resolve(undefined);
}
isExpired(e) {
const t = typeof e.duration === "string" ? parseInt(e.duration) : e.duration;
return (typeof e.time === "string" ? parseInt(e.time) : e.time) + t < Date.now();
}
async storeInCache(e, t, n) {
const a = n === undefined || n?.getReplicationMode() === "slave";
if (n === undefined || a) {
n = this.connection.createQueryRunner("master");
}
let r = e;
if (this.connection.driver.options.type === "mssql") {
r = {
identifier: new Lw.MssqlParameter(e.identifier, "nvarchar"),
time: new Lw.MssqlParameter(e.time, "bigint"),
duration: new Lw.MssqlParameter(e.duration, "int"),
query: new Lw.MssqlParameter(e.query, "nvarchar"),
result: new Lw.MssqlParameter(e.result, "nvarchar")
};
}
if (t && t.identifier) {
const e = n.manager.createQueryBuilder().update(this.queryResultCacheTable).set(r);
e.where(`${e.escape("identifier")} = :condition`, {
condition: r.identifier
});
await e.execute();
} else if (t && t.query) {
const e = n.manager.createQueryBuilder().update(this.queryResultCacheTable).set(r);
if (this.connection.driver.options.type === "oracle") {
e.where(`dbms_lob.compare("query", :condition) = 0`, {
condition: r.query
});
} else {
e.where(`${e.escape("query")} = :condition`, {
condition: r.query
});
}
await e.execute();
} else {
if (this.connection.driver.options.type === "spanner" && !r.id) {
r.id = (0, _w.v4)();
}
await n.manager.createQueryBuilder().insert().into(this.queryResultCacheTable).values(r).execute();
}
if (a) {
await n.release();
}
}
async clear(e) {
return this.getQueryRunner(e).clearTable(this.queryResultCacheTable);
}
async remove(e, t) {
const n = t || this.getQueryRunner();
await Promise.all(e.map(e => {
const t = n.manager.createQueryBuilder();
return t.delete().from(this.queryResultCacheTable).where(`${t.escape("identifier")} = :identifier`, {
identifier: e
}).execute();
}));
if (!t) {
await n.release();
}
}
getQueryRunner(e) {
if (e) return e;
return this.connection.createQueryRunner();
}
}
Pw.DbQueryResultCache = DbQueryResultCache;
Object.defineProperty(Mw, "__esModule", {
value: true
});
Mw.QueryResultCacheFactory = void 0;
const $w = Ow;
const xw = Pw;
const qw = D;
class QueryResultCacheFactory {
constructor(e) {
this.connection = e;
}
create() {
if (!this.connection.options.cache) throw new qw.TypeORMError(`To use cache you need to enable it in connection options by setting cache: true or providing some caching options. Example: { host: ..., username: ..., cache: true }`);
const e = this.connection.options.cache;
if (e.provider && typeof e.provider === "function") {
return e.provider(this.connection);
}
if (e.type === "redis" || e.type === "ioredis" || e.type === "ioredis/cluster") {
return new $w.RedisQueryResultCache(this.connection, e.type);
} else {
return new xw.DbQueryResultCache(this.connection);
}
}
}
Mw.QueryResultCacheFactory = QueryResultCacheFactory;
var Uw = {};
Object.defineProperty(Uw, "__esModule", {
value: true
});
Uw.RelationLoader = void 0;
const Bw = Zc;
class RelationLoader {
constructor(e) {
this.connection = e;
}
load(e, t, n, a) {
if (n && n.isReleased) n = undefined;
if (e.isManyToOne || e.isOneToOneOwner) {
return this.loadManyToOneOrOneToOneOwner(e, t, n, a);
} else if (e.isOneToMany || e.isOneToOneNotOwner) {
return this.loadOneToManyOrOneToOneNotOwner(e, t, n, a);
} else if (e.isManyToManyOwner) {
return this.loadManyToManyOwner(e, t, n, a);
} else {
return this.loadManyToManyNotOwner(e, t, n, a);
}
}
loadManyToOneOrOneToOneOwner(e, t, n, a) {
const r = Array.isArray(t) ? t : [ t ];
const i = e.entityMetadata.name;
const s = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
const o = s.expressionMap.mainAlias.name;
const c = e.entityMetadata.primaryColumns;
const l = e.isOwning ? e.joinColumns : e.inverseRelation.joinColumns;
const u = l.map(t => `${e.entityMetadata.name}.${t.propertyName} = ${o}.${t.referencedColumn.propertyName}`).join(" AND ");
s.innerJoin(e.entityMetadata.target, i, u);
if (c.length === 1) {
s.where(`${i}.${c[0].propertyPath} IN (:...${i + "_" + c[0].propertyName})`);
s.setParameter(i + "_" + c[0].propertyName, r.map(e => c[0].getEntityValue(e, true)));
} else {
const e = r.map((e, t) => c.map((n, a) => {
const r = i + "_entity_" + t + "_" + a;
s.setParameter(r, n.getEntityValue(e, true));
return i + "." + n.propertyPath + " = :" + r;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
s.where(e);
}
Bw.FindOptionsUtils.joinEagerRelations(s, s.alias, s.expressionMap.mainAlias.metadata);
return s.getMany();
}
loadOneToManyOrOneToOneNotOwner(e, t, n, a) {
const r = Array.isArray(t) ? t : [ t ];
const i = e.inverseRelation.joinColumns;
const s = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.inverseRelation.entityMetadata.target, e.propertyName);
const o = s.expressionMap.mainAlias.name;
if (i.length === 1) {
s.where(`${o}.${i[0].propertyPath} IN (:...${o + "_" + i[0].propertyName})`);
s.setParameter(o + "_" + i[0].propertyName, r.map(e => i[0].referencedColumn.getEntityValue(e, true)));
} else {
const e = r.map((e, t) => i.map((n, a) => {
const r = o + "_entity_" + t + "_" + a;
s.setParameter(r, n.referencedColumn.getEntityValue(e, true));
return o + "." + n.propertyPath + " = :" + r;
}).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
s.where(e);
}
Bw.FindOptionsUtils.joinEagerRelations(s, s.alias, s.expressionMap.mainAlias.metadata);
return s.getMany();
}
loadManyToManyOwner(e, t, n, a) {
const r = Array.isArray(t) ? t : [ t ];
const i = e.joinColumns.reduce((e, t) => {
e[t.propertyName] = r.map(e => t.referencedColumn.getEntityValue(e, true));
return e;
}, {});
const s = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
const o = s.expressionMap.mainAlias.name;
const c = e.junctionEntityMetadata.tableName;
const l = e.joinColumns.map(e => `${c}.${e.propertyName} IN (:...${e.propertyName})`);
const u = e.inverseJoinColumns.map(e => `${c}.${e.propertyName}=${o}.${e.referencedColumn.propertyName}`);
s.innerJoin(c, c, [ ...l, ...u ].join(" AND ")).setParameters(i);
Bw.FindOptionsUtils.joinEagerRelations(s, s.alias, s.expressionMap.mainAlias.metadata);
return s.getMany();
}
loadManyToManyNotOwner(e, t, n, a) {
const r = Array.isArray(t) ? t : [ t ];
const i = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
const s = i.expressionMap.mainAlias.name;
const o = e.junctionEntityMetadata.tableName;
const c = e.inverseRelation.joinColumns.map(e => `${o}.${e.propertyName} = ${s}.${e.referencedColumn.propertyName}`);
const l = e.inverseRelation.inverseJoinColumns.map(e => `${o}.${e.propertyName} IN (:...${e.propertyName})`);
const u = e.inverseRelation.inverseJoinColumns.reduce((e, t) => {
e[t.propertyName] = r.map(e => t.referencedColumn.getEntityValue(e, true));
return e;
}, {});
i.innerJoin(o, o, [ ...c, ...l ].join(" AND ")).setParameters(u);
Bw.FindOptionsUtils.joinEagerRelations(i, i.alias, i.expressionMap.mainAlias.metadata);
return i.getMany();
}
enableLazyLoad(e, t, n) {
const a = this;
const r = "__" + e.propertyName + "__";
const i = "__promise_" + e.propertyName + "__";
const s = "__has_" + e.propertyName + "__";
const o = (e, t) => {
e[r] = t;
e[s] = true;
delete e[i];
return t;
};
const c = (e, t) => {
delete e[s];
delete e[r];
e[i] = t;
t.then(n => e[i] === t ? o(e, n) : n);
return t;
};
Object.defineProperty(t, e.propertyName, {
get: function() {
if (this[s] === true || this[r] !== undefined) return Promise.resolve(this[r]);
if (this[i]) return this[i];
const t = a.load(e, this, n).then(t => e.isOneToOne || e.isManyToOne ? t.length === 0 ? null : t[0] : t);
return c(this, t);
},
set: function(e) {
if (e instanceof Promise) {
c(this, e);
} else {
o(this, e);
}
},
configurable: true,
enumerable: false
});
}
}
Uw.RelationLoader = RelationLoader;
var Fw;
function jw() {
if (Fw) return R;
Fw = 1;
Object.defineProperty(R, "__esModule", {
value: true
});
R.DataSource = void 0;
const e = S;
const t = lu;
const n = P;
const a = mu;
const r = Hu;
const i = $m();
const s = xm;
const o = JS();
const c = $c;
const l = XS;
const u = Mw;
const h = Uw;
const d = I;
const p = Wc;
const m = jn;
const f = Te;
const y = lh;
(0, e.registerQueryBuilders)();
let E = class DataSource {
constructor(n) {
this["@instanceof"] = Symbol.for("DataSource");
this.migrations = [];
this.subscribers = [];
this.entityMetadatas = [];
this.entityMetadatasMap = new Map;
(0, e.registerQueryBuilders)();
this.name = n.name || "default";
this.options = n;
this.logger = (new l.LoggerFactory).create(this.options.logger, this.options.logging);
this.driver = (new s.DriverFactory).create(this);
this.manager = this.createEntityManager();
this.namingStrategy = n.namingStrategy || new t.DefaultNamingStrategy;
this.metadataTableName = n.metadataTableName || "typeorm_metadata";
this.queryResultCache = n.cache ? new u.QueryResultCacheFactory(this).create() : undefined;
this.relationLoader = new h.RelationLoader(this);
this.relationIdLoader = new p.RelationIdLoader(this);
this.isInitialized = false;
}
get isConnected() {
return this.isInitialized;
}
get mongoManager() {
if (!f.InstanceChecker.isMongoEntityManager(this.manager)) throw new n.TypeORMError(`MongoEntityManager is only available for MongoDB databases.`);
return this.manager;
}
get sqljsManager() {
if (!f.InstanceChecker.isSqljsEntityManager(this.manager)) throw new n.TypeORMError(`SqljsEntityManager is only available for Sqljs databases.`);
return this.manager;
}
setOptions(e) {
Object.assign(this.options, e);
if (e.logger || e.logging) {
this.logger = (new l.LoggerFactory).create(e.logger || this.options.logger, e.logging || this.options.logging);
}
if (e.namingStrategy) {
this.namingStrategy = e.namingStrategy;
}
if (e.cache) {
this.queryResultCache = new u.QueryResultCacheFactory(this).create();
}
if (e.database) {
this.driver.database = m.DriverUtils.buildDriverOptions(this.options).database;
}
return this;
}
async initialize() {
if (this.isInitialized) throw new n.CannotConnectAlreadyConnectedError(this.name);
await this.driver.connect();
if (this.queryResultCache) await this.queryResultCache.connect();
d.ObjectUtils.assign(this, {
isInitialized: true
});
try {
await this.buildMetadatas();
await this.driver.afterConnect();
if (this.options.dropSchema) await this.dropDatabase();
if (this.options.migrationsRun) await this.runMigrations({
transaction: this.options.migrationsTransactionMode
});
if (this.options.synchronize) await this.synchronize();
} catch (e) {
await this.destroy();
throw e;
}
return this;
}
async connect() {
return this.initialize();
}
async destroy() {
if (!this.isInitialized) throw new n.CannotExecuteNotConnectedError(this.name);
await this.driver.disconnect();
if (this.queryResultCache) await this.queryResultCache.disconnect();
d.ObjectUtils.assign(this, {
isInitialized: false
});
}
async close() {
return this.destroy();
}
async synchronize(e = false) {
if (!this.isInitialized) throw new n.CannotExecuteNotConnectedError(this.name);
if (e) await this.dropDatabase();
const t = this.driver.createSchemaBuilder();
await t.build();
}
async dropDatabase() {
const e = this.createQueryRunner();
try {
if (this.driver.options.type === "mssql" || m.DriverUtils.isMySQLFamily(this.driver) || this.driver.options.type === "aurora-mysql" || m.DriverUtils.isSQLiteFamily(this.driver)) {
const t = [];
this.entityMetadatas.forEach(e => {
if (e.database && t.indexOf(e.database) === -1) t.push(e.database);
});
if (t.length === 0 && this.driver.database) {
t.push(this.driver.database);
}
if (t.length === 0) {
await e.clearDatabase();
} else {
for (const n of t) {
await e.clearDatabase(n);
}
}
} else {
await e.clearDatabase();
}
} finally {
await e.release();
}
}
async runMigrations(e) {
if (!this.isInitialized) throw new n.CannotExecuteNotConnectedError(this.name);
const t = new a.MigrationExecutor(this);
t.transaction = e?.transaction || this.options?.migrationsTransactionMode || "all";
t.fake = e && e.fake || false;
const r = await t.executePendingMigrations();
return r;
}
async undoLastMigration(e) {
if (!this.isInitialized) throw new n.CannotExecuteNotConnectedError(this.name);
const t = new a.MigrationExecutor(this);
t.transaction = e && e.transaction || "all";
t.fake = e && e.fake || false;
await t.undoLastMigration();
}
async showMigrations() {
if (!this.isInitialized) {
throw new n.CannotExecuteNotConnectedError(this.name);
}
const e = new a.MigrationExecutor(this);
return await e.showMigrations();
}
hasMetadata(e) {
return !!this.findMetadata(e);
}
getMetadata(e) {
const t = this.findMetadata(e);
if (!t) throw new n.EntityMetadataNotFoundError(e);
return t;
}
getRepository(e) {
return this.manager.getRepository(e);
}
getTreeRepository(e) {
return this.manager.getTreeRepository(e);
}
getMongoRepository(e) {
if (!(this.driver.options.type === "mongodb")) throw new n.TypeORMError(`You can use getMongoRepository only for MongoDB connections.`);
return this.manager.getRepository(e);
}
getCustomRepository(e) {
return this.manager.getCustomRepository(e);
}
async transaction(e, t) {
return this.manager.transaction(e, t);
}
async query(e, t, a) {
if (f.InstanceChecker.isMongoEntityManager(this.manager)) throw new n.TypeORMError(`Queries aren't supported by MongoDB.`);
if (a && a.isReleased) throw new n.QueryRunnerProviderAlreadyReleasedError;
const r = a || this.createQueryRunner();
try {
return await r.query(e, t);
} finally {
if (!a) await r.release();
}
}
async sql(e, ...t) {
const {query: n, parameters: a} = (0, y.buildSqlTag)({
driver: this.driver,
strings: e,
expressions: t
});
return await this.query(n, a);
}
createQueryBuilder(e, t, a) {
if (f.InstanceChecker.isMongoEntityManager(this.manager)) throw new n.TypeORMError(`Query Builder is not supported by MongoDB.`);
if (t) {
t = m.DriverUtils.buildAlias(this.driver, undefined, t);
const n = this.getMetadata(e);
return new c.SelectQueryBuilder(this, a).select(t).from(n.target, t);
} else {
return new c.SelectQueryBuilder(this, e);
}
}
createQueryRunner(e = "master") {
const t = this.driver.createQueryRunner(e);
const n = this.createEntityManager(t);
Object.assign(t, {
manager: n
});
return t;
}
getManyToManyMetadata(e, t) {
const a = this.getMetadata(e).findRelationWithPropertyPath(t);
if (!a) throw new n.TypeORMError(`Relation "${t}" was not found in ${e} entity.`);
if (!a.isManyToMany) throw new n.TypeORMError(`Relation "${e}#${t}" does not have a many-to-many relationship.` + `You can use this method only on many-to-many relations.`);
return a.junctionEntityMetadata;
}
createEntityManager(e) {
return (new i.EntityManagerFactory).create(this, e);
}
findMetadata(e) {
const t = this.entityMetadatasMap.get(e);
if (t) return t;
for (const [t, n] of this.entityMetadatasMap) {
if (f.InstanceChecker.isEntitySchema(e) && n.name === e.options.name) {
return n;
}
if (typeof e === "string") {
if (e.indexOf(".") !== -1) {
if (n.tablePath === e) {
return n;
}
} else {
if (n.name === e || n.tableName === e) {
return n;
}
}
}
if (d.ObjectUtils.isObjectWithName(e) && typeof e.name === "string") {
if (e.name.indexOf(".") !== -1) {
if (n.tablePath === e.name) {
return n;
}
} else {
if (n.name === e.name || n.tableName === e.name) {
return n;
}
}
}
}
return undefined;
}
async buildMetadatas() {
const e = new o.ConnectionMetadataBuilder(this);
const t = new r.EntityMetadataValidator;
const n = d.ObjectUtils.mixedListToArray(this.options.subscribers || []);
const a = await e.buildSubscribers(n);
d.ObjectUtils.assign(this, {
subscribers: a
});
const i = d.ObjectUtils.mixedListToArray(this.options.entities || []);
const s = await e.buildEntityMetadatas(i);
d.ObjectUtils.assign(this, {
entityMetadatas: s,
entityMetadatasMap: new Map(s.map(e => [ e.target, e ]))
});
const c = d.ObjectUtils.mixedListToArray(this.options.migrations || []);
const l = await e.buildMigrations(c);
d.ObjectUtils.assign(this, {
migrations: l
});
t.validateMany(this.entityMetadatas.filter(e => e.tableType !== "view"), this.driver);
for (const e of s) {
if (f.InstanceChecker.isBaseEntityConstructor(e.target)) {
e.target.useDataSource(this);
}
}
}
defaultReplicationModeForReads() {
if ("replication" in this.driver.options && this.driver.options.replication) {
const e = this.driver.options.replication.defaultMode;
if (e) {
return e;
}
}
return "slave";
}
};
R.DataSource = E;
return R;
}
export { gu as $, el as A, Ps as B, An as C, lu as D, eS as E, Ds as F, tw as G, sw as H, Te as I, aw as J, uw as K, Ip as L, Uu as M, yh as N, I as O, De as P, Ks as Q, uu as R, rl as S, Ch as T, Kl as U, Rh as V, Th as W, wu as X, Eu as Y, Ou as Z, Au as _, np as a, Ru as a0, vu as a1, Fu as a2, Od as b, Uh as c, ts as d, P as e, wm as f, rp as g, Im as h, $d as i, no as j, hc as k, vc as l, Ls as m, cc as n, Dl as o, to as p, uf as q, jw as r, nd as s, ju as t, hu as u, ge as v, Gd as w, Yd as x, Bs as y, $s as z };