UNPKG

lakutata

Version:

An IoC-based universal application framework.

48,343 lines 1.89 MB
/* Build Date: Mon Jan 05 2026 23:52:23 GMT+0800 (China Standard Time) */
"use strict";

const e = require("./Package.internal.310.cjs");

const t = require("./Package.internal.52.cjs");

const n = require("./Package.internal.2.cjs");

const a = require("./Package.internal.6.cjs");

const r = require("fs");

const s = require("path");

const i = require("os");

const o = require("crypto");

const c = require("events");

const l = require("stream");

const u = require("module");

const h = require("fs/promises");

const d = require("url");

const p = require("util");

const m = require("node:url");

const f = require("node:path");

const y = require("node:fs");

const E = require("node:fs/promises");

const T = require("node:events");

const g = require("node:stream");

const N = require("node:string_decoder");

const b = e => e && e.__esModule ? e : {
    default: e
};

const A = b(r);

const C = b(s);

const R = b(i);

const S = b(o);

const w = b(c);

const O = b(l);

const M = b(u);

const v = b(h);

const I = b(d);

const P = b(p);

const L = b(m);

const _ = b(f);

const D = b(y);

const x = b(E);

const $ = b(T);

const q = b(g);

const U = b(N);

var B = {};

var j = {};

var F = {};

var k = {};

var Q = {};

var V = {};

exports.ObjectUtils = {};

Object.defineProperty(exports.ObjectUtils, "__esModule", {
    value: true
});

exports.ObjectUtils.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;
        }
    }
}

exports.ObjectUtils.ObjectUtils = ObjectUtils;

exports.error = {};

var K = {};

var W = {};

Object.defineProperty(W, "__esModule", {
    value: true
});

W.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;
        }
    }
}

W.TypeORMError = TypeORMError;

var H;

function G() {
    if (H) return K;
    H = 1;
    Object.defineProperty(K, "__esModule", {
        value: true
    });
    K.CannotReflectMethodParameterTypeError = void 0;
    const e = W;
    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.`);
        }
    };
    K.CannotReflectMethodParameterTypeError = t;
    return K;
}

var Y = {};

var z;

function J() {
    if (z) return Y;
    z = 1;
    Object.defineProperty(Y, "__esModule", {
        value: true
    });
    Y.AlreadyHasActiveConnectionError = void 0;
    const e = W;
    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.`);
        }
    };
    Y.AlreadyHasActiveConnectionError = t;
    return Y;
}

var X = {};

var Z;

function ee() {
    if (Z) return X;
    Z = 1;
    Object.defineProperty(X, "__esModule", {
        value: true
    });
    X.SubjectWithoutIdentifierError = void 0;
    const e = W;
    let t = class SubjectWithoutIdentifierError extends e.TypeORMError {
        constructor(e) {
            super(`Internal error. Subject ${e.metadata.targetName} must have an identifier to perform operation.`);
        }
    };
    X.SubjectWithoutIdentifierError = t;
    return X;
}

var te = {};

var ne;

function ae() {
    if (ne) return te;
    ne = 1;
    Object.defineProperty(te, "__esModule", {
        value: true
    });
    te.CannotConnectAlreadyConnectedError = void 0;
    const e = W;
    let t = class CannotConnectAlreadyConnectedError extends e.TypeORMError {
        constructor(e) {
            super(`Cannot create a "${e}" connection because connection to the database already established.`);
        }
    };
    te.CannotConnectAlreadyConnectedError = t;
    return te;
}

var re = {};

Object.defineProperty(re, "__esModule", {
    value: true
});

re.LockNotSupportedOnGivenDriverError = void 0;

const se = W;

class LockNotSupportedOnGivenDriverError extends se.TypeORMError {
    constructor() {
        super(`Locking not supported on given driver.`);
    }
}

re.LockNotSupportedOnGivenDriverError = LockNotSupportedOnGivenDriverError;

var ie = {};

var oe;

function ce() {
    if (oe) return ie;
    oe = 1;
    Object.defineProperty(ie, "__esModule", {
        value: true
    });
    ie.ConnectionIsNotSetError = void 0;
    const e = W;
    let t = class ConnectionIsNotSetError extends e.TypeORMError {
        constructor(e) {
            super(`Connection with ${e} database is not established. Check connection configuration.`);
        }
    };
    ie.ConnectionIsNotSetError = t;
    return ie;
}

var le = {};

Object.defineProperty(le, "__esModule", {
    value: true
});

le.CannotCreateEntityIdMapError = void 0;

const ue = W;

class CannotCreateEntityIdMapError extends ue.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.`;
    }
}

le.CannotCreateEntityIdMapError = CannotCreateEntityIdMapError;

var he = {};

var de;

function pe() {
    if (de) return he;
    de = 1;
    Object.defineProperty(he, "__esModule", {
        value: true
    });
    he.MetadataAlreadyExistsError = void 0;
    const e = W;
    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."));
        }
    };
    he.MetadataAlreadyExistsError = t;
    return he;
}

var me = {};

var fe;

function ye() {
    if (fe) return me;
    fe = 1;
    Object.defineProperty(me, "__esModule", {
        value: true
    });
    me.CannotDetermineEntityError = void 0;
    const e = W;
    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.`);
        }
    };
    me.CannotDetermineEntityError = t;
    return me;
}

var Ee = {};

Object.defineProperty(Ee, "__esModule", {
    value: true
});

Ee.UpdateValuesMissingError = void 0;

const Te = W;

class UpdateValuesMissingError extends Te.TypeORMError {
    constructor() {
        super(`Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values.`);
    }
}

Ee.UpdateValuesMissingError = UpdateValuesMissingError;

var ge = {};

var Ne;

function be() {
    if (Ne) return ge;
    Ne = 1;
    Object.defineProperty(ge, "__esModule", {
        value: true
    });
    ge.TreeRepositoryNotSupportedError = void 0;
    const e = W;
    let t = class TreeRepositoryNotSupportedError extends e.TypeORMError {
        constructor(e) {
            super(`Tree repositories are not supported in ${e.options.type} driver.`);
        }
    };
    ge.TreeRepositoryNotSupportedError = t;
    return ge;
}

var Ae = {};

Object.defineProperty(Ae, "__esModule", {
    value: true
});

Ae.CustomRepositoryNotFoundError = void 0;

const Ce = W;

class CustomRepositoryNotFoundError extends Ce.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?`);
    }
}

Ae.CustomRepositoryNotFoundError = CustomRepositoryNotFoundError;

var Re = {};

var Se;

function we() {
    if (Se) return Re;
    Se = 1;
    Object.defineProperty(Re, "__esModule", {
        value: true
    });
    Re.TransactionNotStartedError = void 0;
    const e = W;
    let t = class TransactionNotStartedError extends e.TypeORMError {
        constructor() {
            super(`Transaction is not started yet, start transaction before committing or rolling it back.`);
        }
    };
    Re.TransactionNotStartedError = t;
    return Re;
}

var Oe = {};

var Me;

function ve() {
    if (Me) return Oe;
    Me = 1;
    Object.defineProperty(Oe, "__esModule", {
        value: true
    });
    Oe.TransactionAlreadyStartedError = void 0;
    const e = W;
    let t = class TransactionAlreadyStartedError extends e.TypeORMError {
        constructor() {
            super(`Transaction already started for the given connection, commit current transaction before starting a new one.`);
        }
    };
    Oe.TransactionAlreadyStartedError = t;
    return Oe;
}

var Ie = {};

exports.InstanceChecker = {};

Object.defineProperty(exports.InstanceChecker, "__esModule", {
    value: true
});

exports.InstanceChecker_2 = exports.InstanceChecker.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);
    }
}

exports.InstanceChecker_2 = exports.InstanceChecker.InstanceChecker = InstanceChecker;

Object.defineProperty(Ie, "__esModule", {
    value: true
});

Ie.EntityNotFoundError = void 0;

const Pe = W;

const Le = exports.ObjectUtils;

const _e = exports.InstanceChecker;

class EntityNotFoundError extends Pe.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 (_e.InstanceChecker.isEntitySchema(e)) {
            return e.options.name;
        } else if (typeof e === "function") {
            return e.name;
        } else if (Le.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;
    }
}

Ie.EntityNotFoundError = EntityNotFoundError;

var De = {};

var xe;

function $e() {
    if (xe) return De;
    xe = 1;
    Object.defineProperty(De, "__esModule", {
        value: true
    });
    De.EntityMetadataNotFoundError = void 0;
    const e = W;
    const t = exports.ObjectUtils;
    const n = exports.InstanceChecker;
    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;
            }
        }
    };
    De.EntityMetadataNotFoundError = a;
    return De;
}

var qe = {};

var Ue;

function Be() {
    if (Ue) return qe;
    Ue = 1;
    Object.defineProperty(qe, "__esModule", {
        value: true
    });
    qe.MustBeEntityError = void 0;
    const e = W;
    let t = class MustBeEntityError extends e.TypeORMError {
        constructor(e, t) {
            super(`Cannot ${e}, given value must be an entity, instead "${t}" is given.`);
        }
    };
    qe.MustBeEntityError = t;
    return qe;
}

var je = {};

Object.defineProperty(je, "__esModule", {
    value: true
});

je.OptimisticLockVersionMismatchError = void 0;

const Fe = W;

class OptimisticLockVersionMismatchError extends Fe.TypeORMError {
    constructor(e, t, n) {
        super(`The optimistic lock on entity ${e} failed, version ${t} was expected, but is actually ${n}.`);
    }
}

je.OptimisticLockVersionMismatchError = OptimisticLockVersionMismatchError;

var ke = {};

Object.defineProperty(ke, "__esModule", {
    value: true
});

ke.LimitOnUpdateNotSupportedError = void 0;

const Qe = W;

class LimitOnUpdateNotSupportedError extends Qe.TypeORMError {
    constructor() {
        super(`Your database does not support LIMIT on UPDATE statements.`);
    }
}

ke.LimitOnUpdateNotSupportedError = LimitOnUpdateNotSupportedError;

exports.PrimaryColumnCannotBeNullableError = {};

Object.defineProperty(exports.PrimaryColumnCannotBeNullableError, "__esModule", {
    value: true
});

exports.PrimaryColumnCannotBeNullableError.PrimaryColumnCannotBeNullableError = void 0;

const Ve = W;

class PrimaryColumnCannotBeNullableError extends Ve.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.`);
    }
}

exports.PrimaryColumnCannotBeNullableError.PrimaryColumnCannotBeNullableError = PrimaryColumnCannotBeNullableError;

var Ke = {};

var We;

function He() {
    if (We) return Ke;
    We = 1;
    Object.defineProperty(Ke, "__esModule", {
        value: true
    });
    Ke.CustomRepositoryCannotInheritRepositoryError = void 0;
    const e = W;
    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.`);
        }
    };
    Ke.CustomRepositoryCannotInheritRepositoryError = t;
    return Ke;
}

var Ge = {};

Object.defineProperty(Ge, "__esModule", {
    value: true
});

Ge.QueryRunnerProviderAlreadyReleasedError = void 0;

const Ye = W;

class QueryRunnerProviderAlreadyReleasedError extends Ye.TypeORMError {
    constructor() {
        super(`Database connection provided by a query runner was already ` + `released, cannot continue to use its querying methods anymore.`);
    }
}

Ge.QueryRunnerProviderAlreadyReleasedError = QueryRunnerProviderAlreadyReleasedError;

var ze = {};

var Je;

function Xe() {
    if (Je) return ze;
    Je = 1;
    Object.defineProperty(ze, "__esModule", {
        value: true
    });
    ze.CannotAttachTreeChildrenEntityError = void 0;
    const e = W;
    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.`);
        }
    };
    ze.CannotAttachTreeChildrenEntityError = t;
    return ze;
}

var Ze = {};

Object.defineProperty(Ze, "__esModule", {
    value: true
});

Ze.CustomRepositoryDoesNotHaveEntityError = void 0;

const et = W;

class CustomRepositoryDoesNotHaveEntityError extends et.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)? `);
    }
}

Ze.CustomRepositoryDoesNotHaveEntityError = CustomRepositoryDoesNotHaveEntityError;

var tt = {};

var nt;

function at() {
    if (nt) return tt;
    nt = 1;
    Object.defineProperty(tt, "__esModule", {
        value: true
    });
    tt.MissingDeleteDateColumnError = void 0;
    const e = W;
    let t = class MissingDeleteDateColumnError extends e.TypeORMError {
        constructor(e) {
            super(`Entity "${e.name}" does not have delete date columns.`);
        }
    };
    tt.MissingDeleteDateColumnError = t;
    return tt;
}

var rt = {};

var st;

function it() {
    if (st) return rt;
    st = 1;
    Object.defineProperty(rt, "__esModule", {
        value: true
    });
    rt.NoConnectionForRepositoryError = void 0;
    const e = W;
    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.`);
        }
    };
    rt.NoConnectionForRepositoryError = t;
    return rt;
}

var ot = {};

var ct;

function lt() {
    if (ct) return ot;
    ct = 1;
    Object.defineProperty(ot, "__esModule", {
        value: true
    });
    ot.CircularRelationsError = void 0;
    const e = W;
    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.`);
        }
    };
    ot.CircularRelationsError = t;
    return ot;
}

var ut = {};

Object.defineProperty(ut, "__esModule", {
    value: true
});

ut.ReturningStatementNotSupportedError = void 0;

const ht = W;

class ReturningStatementNotSupportedError extends ht.TypeORMError {
    constructor() {
        super(`OUTPUT or RETURNING clause only supported by PostgreSQL, MariaDB, Microsoft SqlServer or Google Spanner.`);
    }
}

ut.ReturningStatementNotSupportedError = ReturningStatementNotSupportedError;

var dt = {};

var pt;

function mt() {
    if (pt) return dt;
    pt = 1;
    Object.defineProperty(dt, "__esModule", {
        value: true
    });
    dt.UsingJoinTableIsNotAllowedError = void 0;
    const e = W;
    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.`);
        }
    };
    dt.UsingJoinTableIsNotAllowedError = t;
    return dt;
}

var ft = {};

var yt;

function Et() {
    if (yt) return ft;
    yt = 1;
    Object.defineProperty(ft, "__esModule", {
        value: true
    });
    ft.MissingJoinColumnError = void 0;
    const e = W;
    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.`;
            }
        }
    };
    ft.MissingJoinColumnError = t;
    return ft;
}

var Tt = {};

var gt;

function Nt() {
    if (gt) return Tt;
    gt = 1;
    Object.defineProperty(Tt, "__esModule", {
        value: true
    });
    Tt.MissingPrimaryColumnError = void 0;
    const e = W;
    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.`);
        }
    };
    Tt.MissingPrimaryColumnError = t;
    return Tt;
}

var bt = {};

Object.defineProperty(bt, "__esModule", {
    value: true
});

bt.EntityPropertyNotFoundError = void 0;

const At = W;

class EntityPropertyNotFoundError extends At.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.`;
    }
}

bt.EntityPropertyNotFoundError = EntityPropertyNotFoundError;

var Ct = {};

var Rt;

function St() {
    if (Rt) return Ct;
    Rt = 1;
    Object.defineProperty(Ct, "__esModule", {
        value: true
    });
    Ct.MissingDriverError = void 0;
    const e = W;
    let t = class MissingDriverError extends e.TypeORMError {
        constructor(e, t = []) {
            super(`Wrong driver: "${e}" given. Supported drivers are: ` + `${t.map(e => `"${e}"`).join(", ")}.`);
        }
    };
    Ct.MissingDriverError = t;
    return Ct;
}

var wt = {};

var Ot;

function Mt() {
    if (Ot) return wt;
    Ot = 1;
    Object.defineProperty(wt, "__esModule", {
        value: true
    });
    wt.DriverPackageNotInstalledError = void 0;
    const e = W;
    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`);
        }
    };
    wt.DriverPackageNotInstalledError = t;
    return wt;
}

var vt = {};

var It;

function Pt() {
    if (It) return vt;
    It = 1;
    Object.defineProperty(vt, "__esModule", {
        value: true
    });
    vt.CannotGetEntityManagerNotConnectedError = void 0;
    const e = W;
    let t = class CannotGetEntityManagerNotConnectedError extends e.TypeORMError {
        constructor(e) {
            super(`Cannot get entity manager for "${e}" connection because connection is not yet established.`);
        }
    };
    vt.CannotGetEntityManagerNotConnectedError = t;
    return vt;
}

var Lt = {};

var _t;

function Dt() {
    if (_t) return Lt;
    _t = 1;
    Object.defineProperty(Lt, "__esModule", {
        value: true
    });
    Lt.ConnectionNotFoundError = void 0;
    const e = W;
    let t = class ConnectionNotFoundError extends e.TypeORMError {
        constructor(e) {
            super(`Connection "${e}" was not found.`);
        }
    };
    Lt.ConnectionNotFoundError = t;
    return Lt;
}

var xt = {};

Object.defineProperty(xt, "__esModule", {
    value: true
});

xt.NoVersionOrUpdateDateColumnError = void 0;

const $t = W;

class NoVersionOrUpdateDateColumnError extends $t.TypeORMError {
    constructor(e) {
        super(`Entity ${e} does not have version or update date columns.`);
    }
}

xt.NoVersionOrUpdateDateColumnError = NoVersionOrUpdateDateColumnError;

var qt = {};

Object.defineProperty(qt, "__esModule", {
    value: true
});

qt.InsertValuesMissingError = void 0;

const Ut = W;

class InsertValuesMissingError extends Ut.TypeORMError {
    constructor() {
        super(`Cannot perform insert query because values are not defined. ` + `Call "qb.values(...)" method to specify inserted values.`);
    }
}

qt.InsertValuesMissingError = InsertValuesMissingError;

var Bt = {};

Object.defineProperty(Bt, "__esModule", {
    value: true
});

Bt.OptimisticLockCanNotBeUsedError = void 0;

const jt = W;

class OptimisticLockCanNotBeUsedError extends jt.TypeORMError {
    constructor() {
        super(`The optimistic lock can be used only with getOne() method.`);
    }
}

Bt.OptimisticLockCanNotBeUsedError = OptimisticLockCanNotBeUsedError;

var Ft = {};

var kt;

function Qt() {
    if (kt) return Ft;
    kt = 1;
    Object.defineProperty(Ft, "__esModule", {
        value: true
    });
    Ft.MetadataWithSuchNameAlreadyExistsError = void 0;
    const e = W;
    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?");
        }
    };
    Ft.MetadataWithSuchNameAlreadyExistsError = t;
    return Ft;
}

var Vt = {};

var Kt;

function Wt() {
    if (Kt) return Vt;
    Kt = 1;
    Object.defineProperty(Vt, "__esModule", {
        value: true
    });
    Vt.DriverOptionNotSetError = void 0;
    const e = W;
    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.`);
        }
    };
    Vt.DriverOptionNotSetError = t;
    return Vt;
}

var Ht = {};

var Gt;

function Yt() {
    if (Gt) return Ht;
    Gt = 1;
    Object.defineProperty(Ht, "__esModule", {
        value: true
    });
    Ht.FindRelationsNotFoundError = void 0;
    const e = W;
    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.`;
            }
        }
    };
    Ht.FindRelationsNotFoundError = t;
    return Ht;
}

var zt = {};

Object.defineProperty(zt, "__esModule", {
    value: true
});

zt.PessimisticLockTransactionRequiredError = void 0;

const Jt = W;

class PessimisticLockTransactionRequiredError extends Jt.TypeORMError {
    constructor() {
        super(`An open transaction is required for pessimistic lock.`);
    }
}

zt.PessimisticLockTransactionRequiredError = PessimisticLockTransactionRequiredError;

var Xt = {};

var Zt;

function en() {
    if (Zt) return Xt;
    Zt = 1;
    Object.defineProperty(Xt, "__esModule", {
        value: true
    });
    Xt.RepositoryNotTreeError = void 0;
    const e = W;
    const t = exports.ObjectUtils;
    const n = exports.InstanceChecker;
    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.`;
        }
    };
    Xt.RepositoryNotTreeError = a;
    return Xt;
}

var tn = {};

var nn;

function an() {
    if (nn) return tn;
    nn = 1;
    Object.defineProperty(tn, "__esModule", {
        value: true
    });
    tn.DataTypeNotSupportedError = void 0;
    const e = W;
    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.`;
        }
    };
    tn.DataTypeNotSupportedError = t;
    return tn;
}

var rn = {};

var sn;

function on() {
    if (sn) return rn;
    sn = 1;
    Object.defineProperty(rn, "__esModule", {
        value: true
    });
    rn.InitializedRelationError = void 0;
    const e = W;
    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.`);
        }
    };
    rn.InitializedRelationError = t;
    return rn;
}

var cn = {};

var ln;

function un() {
    if (ln) return cn;
    ln = 1;
    Object.defineProperty(cn, "__esModule", {
        value: true
    });
    cn.MissingJoinTableError = void 0;
    const e = W;
    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.`;
            }
        }
    };
    cn.MissingJoinTableError = t;
    return cn;
}

var hn = {};

var dn;

function pn() {
    if (dn) return hn;
    dn = 1;
    Object.defineProperty(hn, "__esModule", {
        value: true
    });
    hn.QueryFailedError = void 0;
    const e = exports.ObjectUtils;
    const t = W;
    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
                });
            }
        }
    };
    hn.QueryFailedError = n;
    return hn;
}

var mn = {};

Object.defineProperty(mn, "__esModule", {
    value: true
});

mn.NoNeedToReleaseEntityManagerError = void 0;

const fn = W;

class NoNeedToReleaseEntityManagerError extends fn.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.`);
    }
}

mn.NoNeedToReleaseEntityManagerError = NoNeedToReleaseEntityManagerError;

var yn = {};

var En;

function Tn() {
    if (En) return yn;
    En = 1;
    Object.defineProperty(yn, "__esModule", {
        value: true
    });
    yn.UsingJoinColumnOnlyOnOneSideAllowedError = void 0;
    const e = W;
    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.`);
        }
    };
    yn.UsingJoinColumnOnlyOnOneSideAllowedError = t;
    return yn;
}

var gn = {};

var Nn;

function bn() {
    if (Nn) return gn;
    Nn = 1;
    Object.defineProperty(gn, "__esModule", {
        value: true
    });
    gn.UsingJoinTableOnlyOnOneSideAllowedError = void 0;
    const e = W;
    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.`);
        }
    };
    gn.UsingJoinTableOnlyOnOneSideAllowedError = t;
    return gn;
}

var An = {};

var Cn;

function Rn() {
    if (Cn) return An;
    Cn = 1;
    Object.defineProperty(An, "__esModule", {
        value: true
    });
    An.SubjectRemovedAndUpdatedError = void 0;
    const e = W;
    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).`);
        }
    };
    An.SubjectRemovedAndUpdatedError = t;
    return An;
}

var Sn = {};

var wn;

function On() {
    if (wn) return Sn;
    wn = 1;
    Object.defineProperty(Sn, "__esModule", {
        value: true
    });
    Sn.PersistedEntityNotFoundError = void 0;
    const e = W;
    let t = class PersistedEntityNotFoundError extends e.TypeORMError {
        constructor() {
            super(`Internal error. Persisted entity was not found in the list of prepared operated entities.`);
        }
    };
    Sn.PersistedEntityNotFoundError = t;
    return Sn;
}

var Mn = {};

var vn;

function In() {
    if (vn) return Mn;
    vn = 1;
    Object.defineProperty(Mn, "__esModule", {
        value: true
    });
    Mn.UsingJoinColumnIsNotAllowedError = void 0;
    const e = W;
    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.`);
        }
    };
    Mn.UsingJoinColumnIsNotAllowedError = t;
    return Mn;
}

exports.ColumnTypeUndefinedError = {};

Object.defineProperty(exports.ColumnTypeUndefinedError, "__esModule", {
    value: true
});

exports.ColumnTypeUndefinedError.ColumnTypeUndefinedError = void 0;

const Pn = W;

class ColumnTypeUndefinedError extends Pn.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.`);
    }
}

exports.ColumnTypeUndefinedError.ColumnTypeUndefinedError = ColumnTypeUndefinedError;

var Ln = {};

var _n;

function Dn() {
    if (_n) return Ln;
    _n = 1;
    Object.defineProperty(Ln, "__esModule", {
        value: true
    });
    Ln.QueryRunnerAlreadyReleasedError = void 0;
    const e = W;
    let t = class QueryRunnerAlreadyReleasedError extends e.TypeORMError {
        constructor() {
            super(`Query runner already released. Cannot run queries anymore.`);
        }
    };
    Ln.QueryRunnerAlreadyReleasedError = t;
    return Ln;
}

var xn = {};

Object.defineProperty(xn, "__esModule", {
    value: true
});

xn.OffsetWithoutLimitNotSupportedError = void 0;

const $n = W;

class OffsetWithoutLimitNotSupportedError extends $n.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).`);
    }
}

xn.OffsetWithoutLimitNotSupportedError = OffsetWithoutLimitNotSupportedError;

var qn = {};

var Un;

function Bn() {
    if (Un) return qn;
    Un = 1;
    Object.defineProperty(qn, "__esModule", {
        value: true
    });
    qn.CannotExecuteNotConnectedError = void 0;
    const e = W;
    let t = class CannotExecuteNotConnectedError extends e.TypeORMError {
        constructor(e) {
            super(`Cannot execute operation on "${e}" connection because connection is not yet established.`);
        }
    };
    qn.CannotExecuteNotConnectedError = t;
    return qn;
}

var jn = {};

var Fn;

function kn() {
    if (Fn) return jn;
    Fn = 1;
    Object.defineProperty(jn, "__esModule", {
        value: true
    });
    jn.NoConnectionOptionError = void 0;
    const e = W;
    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`);
        }
    };
    jn.NoConnectionOptionError = t;
    return jn;
}

var Qn = {};

var Vn;

function Kn() {
    if (Vn) return Qn;
    Vn = 1;
    Object.defineProperty(Qn, "__esModule", {
        value: true
    });
    Qn.ForbiddenTransactionModeOverrideError = void 0;
    const e = W;
    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"`);
        }
    };
    Qn.ForbiddenTransactionModeOverrideError = t;
    return Qn;
}

(function(t) {
    Object.defineProperty(t, "__esModule", {
        value: true
    });
    const n = e.require$$0;
    n.__exportStar(G(), t);
    n.__exportStar(J(), 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(be(), t);
    n.__exportStar(Ae, t);
    n.__exportStar(we(), t);
    n.__exportStar(ve(), t);
    n.__exportStar(Ie, t);
    n.__exportStar($e(), t);
    n.__exportStar(Be(), t);
    n.__exportStar(je, t);
    n.__exportStar(ke, t);
    n.__exportStar(exports.PrimaryColumnCannotBeNullableError, t);
    n.__exportStar(He(), t);
    n.__exportStar(Ge, t);
    n.__exportStar(Xe(), t);
    n.__exportStar(Ze, t);
    n.__exportStar(at(), t);
    n.__exportStar(it(), t);
    n.__exportStar(lt(), t);
    n.__exportStar(ut, t);
    n.__exportStar(mt(), t);
    n.__exportStar(Et(), t);
    n.__exportStar(Nt(), t);
    n.__exportStar(bt, t);
    n.__exportStar(St(), t);
    n.__exportStar(Mt(), t);
    n.__exportStar(Pt(), t);
    n.__exportStar(Dt(), t);
    n.__exportStar(xt, t);
    n.__exportStar(qt, t);
    n.__exportStar(Bt, t);
    n.__exportStar(Qt(), t);
    n.__exportStar(Wt(), t);
    n.__exportStar(Yt(), t);
    n.__exportStar(zt, t);
    n.__exportStar(en(), t);
    n.__exportStar(an(), t);
    n.__exportStar(on(), t);
    n.__exportStar(un(), t);
    n.__exportStar(pn(), t);
    n.__exportStar(mn, t);
    n.__exportStar(Tn(), t);
    n.__exportStar(bn(), t);
    n.__exportStar(Rn(), t);
    n.__exportStar(On(), t);
    n.__exportStar(In(), t);
    n.__exportStar(exports.ColumnTypeUndefinedError, t);
    n.__exportStar(Dn(), t);
    n.__exportStar(xn, t);
    n.__exportStar(Bn(), t);
    n.__exportStar(kn(), t);
    n.__exportStar(W, t);
    n.__exportStar(Kn(), t);
})(exports.error);

Object.defineProperty(V, "__esModule", {
    value: true
});

V.Alias = void 0;

const Wn = exports.ObjectUtils;

const Hn = exports.error;

class Alias {
    constructor(e) {
        Wn.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 Hn.TypeORMError(`Cannot get entity metadata for the given alias "${this.name}"`);
        return this._metadata;
    }
}

V.Alias = Alias;

var Gn = {};

var Yn = {};

Object.defineProperty(Yn, "__esModule", {
    value: true
});

Yn.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;
    }
}

Yn.QueryBuilderUtils = QueryBuilderUtils;

var zn = {};

var Jn = {};

var Xn = {
    exports: {}
};

var Zn;

var ea;

function ta() {
    if (ea) return Zn;
    ea = 1;
    var e = {}.toString;
    Zn = Array.isArray || function(t) {
        return e.call(t) == "[object Array]";
    };
    return Zn;
}

var na;

var aa;

function ra() {
    if (aa) return na;
    aa = 1;
    na = TypeError;
    return na;
}

var sa;

var ia;

function oa() {
    if (ia) return sa;
    ia = 1;
    sa = Object;
    return sa;
}

var ca;

var la;

function ua() {
    if (la) return ca;
    la = 1;
    ca = Error;
    return ca;
}

var ha;

var da;

function pa() {
    if (da) return ha;
    da = 1;
    ha = EvalError;
    return ha;
}

var ma;

var fa;

function ya() {
    if (fa) return ma;
    fa = 1;
    ma = RangeError;
    return ma;
}

var Ea;

var Ta;

function ga() {
    if (Ta) return Ea;
    Ta = 1;
    Ea = ReferenceError;
    return Ea;
}

var Na;

var ba;

function Aa() {
    if (ba) return Na;
    ba = 1;
    Na = SyntaxError;
    return Na;
}

var Ca;

var Ra;

function Sa() {
    if (Ra) return Ca;
    Ra = 1;
    Ca = URIError;
    return Ca;
}

var wa;

var Oa;

function Ma() {
    if (Oa) return wa;
    Oa = 1;
    wa = Math.abs;
    return wa;
}

var va;

var Ia;

function Pa() {
    if (Ia) return va;
    Ia = 1;
    va = Math.floor;
    return va;
}

var La;

var _a;

function Da() {
    if (_a) return La;
    _a = 1;
    La = Math.max;
    return La;
}

var xa;

var $a;

function qa() {
    if ($a) return xa;
    $a = 1;
    xa = Math.min;
    return xa;
}

var Ua;

var Ba;

function ja() {
    if (Ba) return Ua;
    Ba = 1;
    Ua = Math.pow;
    return Ua;
}

var Fa;

var ka;

function Qa() {
    if (ka) return Fa;
    ka = 1;
    Fa = Math.round;
    return Fa;
}

var Va;

var Ka;

function Wa() {
    if (Ka) return Va;
    Ka = 1;
    Va = Number.isNaN || function e(t) {
        return t !== t;
    };
    return Va;
}

var Ha;

var Ga;

function Ya() {
    if (Ga) return Ha;
    Ga = 1;
    var e = Wa();
    Ha = function t(n) {
        if (e(n) || n === 0) {
            return n;
        }
        return n < 0 ? -1 : 1;
    };
    return Ha;
}

var za;

var Ja;

function Xa() {
    if (Ja) return za;
    Ja = 1;
    za = Object.getOwnPropertyDescriptor;
    return za;
}

var Za;

var er;

function tr() {
    if (er) return Za;
    er = 1;
    var e = Xa();
    if (e) {
        try {
            e([], "length");
        } catch (t) {
            e = null;
        }
    }
    Za = e;
    return Za;
}

var nr;

var ar;

function rr() {
    if (ar) return nr;
    ar = 1;
    var e = Object.defineProperty || false;
    if (e) {
        try {
            e({}, "a", {
                value: 1
            });
        } catch (t) {
            e = false;
        }
    }
    nr = e;
    return nr;
}

var sr;

var ir;

function or() {
    if (ir) return sr;
    ir = 1;
    sr = 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 s 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 i = Object.getOwnPropertySymbols(t);
        if (i.length !== 1 || i[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 sr;
}

var cr;

var lr;

function ur() {
    if (lr) return cr;
    lr = 1;
    var e = typeof Symbol !== "undefined" && Symbol;
    var t = or();
    cr = 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 cr;
}

var hr;

var dr;

function pr() {
    if (dr) return hr;
    dr = 1;
    hr = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
    return hr;
}

var mr;

var fr;

function yr() {
    if (fr) return mr;
    fr = 1;
    var e = oa();
    mr = e.getPrototypeOf || null;
    return mr;
}

var Er;

var Tr;

function gr() {
    if (Tr) return Er;
    Tr = 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 s = 0; s < n.length; s += 1) {
            a[s + t.length] = n[s];
        }
        return a;
    };
    var s = function e(t, n) {
        var a = [];
        for (var r = n || 0, s = 0; r < t.length; r += 1, s += 1) {
            a[s] = t[r];
        }
        return a;
    };
    var i = 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;
    };
    Er = function o(c) {
        var l = this;
        if (typeof l !== "function" || t.apply(l) !== a) {
            throw new TypeError(e + l);
        }
        var u = s(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 (" + i(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 Er;
}

var Nr;

var br;

function Ar() {
    if (br) return Nr;
    br = 1;
    var e = gr();
    Nr = Function.prototype.bind || e;
    return Nr;
}

var Cr;

var Rr;

function Sr() {
    if (Rr) return Cr;
    Rr = 1;
    Cr = Function.prototype.call;
    return Cr;
}

var wr;

var Or;

function Mr() {
    if (Or) return wr;
    Or = 1;
    wr = Function.prototype.apply;
    return wr;
}

var vr;

var Ir;

function Pr() {
    if (Ir) return vr;
    Ir = 1;
    vr = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
    return vr;
}

var Lr;

var _r;

function Dr() {
    if (_r) return Lr;
    _r = 1;
    var e = Ar();
    var t = Mr();
    var n = Sr();
    var a = Pr();
    Lr = a || e.call(n, t);
    return Lr;
}

var xr;

var $r;

function qr() {
    if ($r) return xr;
    $r = 1;
    var e = Ar();
    var t = ra();
    var n = Sr();
    var a = Dr();
    xr = function r(s) {
        if (s.length < 1 || typeof s[0] !== "function") {
            throw new t("a function is required");
        }
        return a(e, n, s);
    };
    return xr;
}

var Ur;

var Br;

function jr() {
    if (Br) return Ur;
    Br = 1;
    var e = qr();
    var t = tr();
    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 s = r.getPrototypeOf;
    Ur = a && typeof a.get === "function" ? e([ a.get ]) : typeof s === "function" ? function e(t) {
        return s(t == null ? t : r(t));
    } : false;
    return Ur;
}

var Fr;

var kr;

function Qr() {
    if (kr) return Fr;
    kr = 1;
    var e = pr();
    var t = yr();
    var n = jr();
    Fr = 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 Fr;
}

var Vr;

var Kr;

function Wr() {
    if (Kr) return Vr;
    Kr = 1;
    var e = Function.prototype.call;
    var t = Object.prototype.hasOwnProperty;
    var n = Ar();
    Vr = n.call(e, t);
    return Vr;
}

var Hr;

var Gr;

function Yr() {
    if (Gr) return Hr;
    Gr = 1;
    var e;
    var t = oa();
    var n = ua();
    var a = pa();
    var r = ya();
    var s = ga();
    var i = Aa();
    var o = ra();
    var c = Sa();
    var l = Ma();
    var u = Pa();
    var h = Da();
    var d = qa();
    var p = ja();
    var m = Qa();
    var f = Ya();
    var y = Function;
    var E = function(e) {
        try {
            return y('"use strict"; return (' + e + ").constructor;")();
        } catch (e) {}
    };
    var T = tr();
    var g = rr();
    var N = function() {
        throw new o;
    };
    var b = T ? function() {
        try {
            arguments.callee;
            return N;
        } catch (e) {
            try {
                return T(arguments, "callee").get;
            } catch (e) {
                return N;
            }
        }
    }() : N;
    var A = ur()();
    var C = Qr();
    var R = yr();
    var S = pr();
    var w = Mr();
    var O = Sr();
    var M = {};
    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%": A && C ? C([][Symbol.iterator]()) : e,
        "%AsyncFromSyncIteratorPrototype%": e,
        "%AsyncFunction%": M,
        "%AsyncGenerator%": M,
        "%AsyncGeneratorFunction%": M,
        "%AsyncIteratorPrototype%": M,
        "%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%": M,
        "%Int8Array%": typeof Int8Array === "undefined" ? e : Int8Array,
        "%Int16Array%": typeof Int16Array === "undefined" ? e : Int16Array,
        "%Int32Array%": typeof Int32Array === "undefined" ? e : Int32Array,
        "%isFinite%": isFinite,
        "%isNaN%": isNaN,
        "%IteratorPrototype%": A && C ? C(C([][Symbol.iterator]())) : e,
        "%JSON%": typeof JSON === "object" ? JSON : e,
        "%Map%": typeof Map === "undefined" ? e : Map,
        "%MapIteratorPrototype%": typeof Map === "undefined" || !A || !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%": s,
        "%Reflect%": typeof Reflect === "undefined" ? e : Reflect,
        "%RegExp%": RegExp,
        "%Set%": typeof Set === "undefined" ? e : Set,
        "%SetIteratorPrototype%": typeof Set === "undefined" || !A || !C ? e : C((new Set)[Symbol.iterator]()),
        "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? e : SharedArrayBuffer,
        "%String%": String,
        "%StringIteratorPrototype%": A && C ? C(""[Symbol.iterator]()) : e,
        "%Symbol%": A ? Symbol : e,
        "%SyntaxError%": i,
        "%ThrowTypeError%": b,
        "%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%": O,
        "%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 _ = {
        __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 D = Ar();
    var x = Wr();
    var $ = D.call(O, Array.prototype.concat);
    var q = D.call(w, Array.prototype.splice);
    var U = D.call(O, String.prototype.replace);
    var B = D.call(O, String.prototype.slice);
    var j = D.call(O, RegExp.prototype.exec);
    var F = /[^%.[\]]+|\[(?:(-?\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 i("invalid intrinsic syntax, expected closing `%`");
        } else if (a === "%" && n !== "%") {
            throw new i("invalid intrinsic syntax, expected opening `%`");
        }
        var r = [];
        U(t, F, 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 (x(_, a)) {
            r = _[a];
            a = "%" + r[0] + "%";
        }
        if (x(I, a)) {
            var s = I[a];
            if (s === M) {
                s = L(a);
            }
            if (typeof s === "undefined" && !n) {
                throw new o("intrinsic " + t + " exists, but is not available. Please file an issue!");
            }
            return {
                alias: r,
                name: a,
                value: s
            };
        }
        throw new i("intrinsic " + t + " does not exist!");
    };
    Hr = 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 (j(/^%?[^%]*%?$/, n) === null) {
            throw new i("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
        }
        var r = Q(n);
        var s = r.length > 0 ? r[0] : "";
        var c = V("%" + s + "%", a);
        var l = c.name;
        var u = c.value;
        var h = false;
        var d = c.alias;
        if (d) {
            s = d[0];
            q(r, $([ 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 i("property names with quotes must have matching quotes");
            }
            if (f === "constructor" || !m) {
                h = true;
            }
            s += "." + f;
            l = "%" + s + "%";
            if (x(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 = x(u, f);
                    u = u[f];
                }
                if (m && !h) {
                    I[l] = u;
                }
            }
        }
        return u;
    };
    return Hr;
}

var zr;

var Jr;

function Xr() {
    if (Jr) return zr;
    Jr = 1;
    var e = Yr();
    var t = qr();
    var n = t([ e("%String.prototype.indexOf%") ]);
    zr = function a(r, s) {
        var i = e(r, !!s);
        if (typeof i === "function" && n(r, ".prototype.") > -1) {
            return t([ i ]);
        }
        return i;
    };
    return zr;
}

var Zr;

var es;

function ts() {
    if (es) return Zr;
    es = 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 s = function t(n) {
        try {
            var a = e.call(n);
            return r.test(a);
        } catch (e) {
            return false;
        }
    };
    var i = function t(n) {
        try {
            if (s(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;
            };
        }
    }
    Zr = 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 !s(r) && i(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 i(t);
        }
        if (s(t)) {
            return false;
        }
        var n = o.call(t);
        if (n !== l && n !== u && !/^\[object HTML/.test(n)) {
            return false;
        }
        return i(t);
    };
    return Zr;
}

var ns;

var as;

function rs() {
    if (as) return ns;
    as = 1;
    var e = ts();
    var t = Object.prototype.toString;
    var n = Object.prototype.hasOwnProperty;
    var a = function e(t, a, r) {
        for (var s = 0, i = t.length; s < i; s++) {
            if (n.call(t, s)) {
                if (r == null) {
                    a(t[s], s, t);
                } else {
                    a.call(r, t[s], s, t);
                }
            }
        }
    };
    var r = function e(t, n, a) {
        for (var r = 0, s = t.length; r < s; r++) {
            if (a == null) {
                n(t.charAt(r), r, t);
            } else {
                n.call(a, t.charAt(r), r, t);
            }
        }
    };
    var s = function e(t, a, r) {
        for (var s in t) {
            if (n.call(t, s)) {
                if (r == null) {
                    a(t[s], s, t);
                } else {
                    a.call(r, t[s], s, t);
                }
            }
        }
    };
    function i(e) {
        return t.call(e) === "[object Array]";
    }
    ns = 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 (i(n)) {
            a(n, o, l);
        } else if (typeof n === "string") {
            r(n, o, l);
        } else {
            s(n, o, l);
        }
    };
    return ns;
}

var ss;

var is;

function os() {
    if (is) return ss;
    is = 1;
    ss = [ "Float16Array", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "BigInt64Array", "BigUint64Array" ];
    return ss;
}

var cs;

var ls;

function us() {
    if (ls) return cs;
    ls = 1;
    var e = os();
    var t = typeof globalThis === "undefined" ? n.commonjsGlobal : globalThis;
    cs = 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 cs;
}

var hs = {
    exports: {}
};

var ds;

var ps;

function ms() {
    if (ps) return ds;
    ps = 1;
    var e = rr();
    var t = Aa();
    var n = ra();
    var a = tr();
    ds = function r(s, i, o) {
        if (!s || typeof s !== "object" && typeof s !== "function") {
            throw new n("`obj` must be an object or a function`");
        }
        if (typeof i !== "string" && typeof i !== "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(s, i);
        if (e) {
            e(s, i, {
                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) {
            s[i] = o;
        } else {
            throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
        }
    };
    return ds;
}

var fs;

var ys;

function Es() {
    if (ys) return fs;
    ys = 1;
    var e = rr();
    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;
        }
    };
    fs = t;
    return fs;
}

var Ts;

var gs;

function Ns() {
    if (gs) return Ts;
    gs = 1;
    var e = Yr();
    var t = ms();
    var n = Es()();
    var a = tr();
    var r = ra();
    var s = e("%Math.floor%");
    Ts = function e(i, o) {
        if (typeof i !== "function") {
            throw new r("`fn` is not a function");
        }
        if (typeof o !== "number" || o < 0 || o > 4294967295 || s(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 i && a) {
            var h = a(i, "length");
            if (h && !h.configurable) {
                l = false;
            }
            if (h && !h.writable) {
                u = false;
            }
        }
        if (l || u || !c) {
            if (n) {
                t(i, "length", o, true, true);
            } else {
                t(i, "length", o);
            }
        }
        return i;
    };
    return Ts;
}

var bs;

var As;

function Cs() {
    if (As) return bs;
    As = 1;
    var e = Ar();
    var t = Mr();
    var n = Dr();
    bs = function a() {
        return n(e, t, arguments);
    };
    return bs;
}

hs.exports;

var Rs;

function Ss() {
    if (Rs) return hs.exports;
    Rs = 1;
    (function(e) {
        var t = Ns();
        var n = rr();
        var a = qr();
        var r = Cs();
        e.exports = function e(n) {
            var r = a(arguments);
            var s = n.length - (arguments.length - 1);
            return t(r, 1 + (s > 0 ? s : 0), true);
        };
        if (n) {
            n(e.exports, "apply", {
                value: r
            });
        } else {
            e.exports.apply = r;
        }
    })(hs);
    return hs.exports;
}

var ws;

var Os;

function Ms() {
    if (Os) return ws;
    Os = 1;
    var e = or();
    ws = function t() {
        return e() && !!Symbol.toStringTag;
    };
    return ws;
}

var vs;

var Is;

function Ps() {
    if (Is) return vs;
    Is = 1;
    var e = rs();
    var t = us();
    var a = Ss();
    var r = Xr();
    var s = tr();
    var i = Qr();
    var o = r("Object.prototype.toString");
    var c = Ms()();
    var l = typeof globalThis === "undefined" ? n.commonjsGlobal : globalThis;
    var u = t();
    var h = r("String.prototype.slice");
    var d = r("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 && s && i) {
        e(u, function(e) {
            var t = new l[e];
            if (Symbol.toStringTag in t && i) {
                var n = i(t);
                var r = s(n, Symbol.toStringTag);
                if (!r && n) {
                    var o = i(n);
                    r = s(o, Symbol.toStringTag);
                }
                p["$" + e] = a(r.get);
            }
        });
    } else {
        e(u, function(e) {
            var t = new l[e];
            var n = t.slice || t.set;
            if (n) {
                p["$" + e] = a(n);
            }
        });
    }
    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;
    };
    vs = 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 (!s) {
            return null;
        }
        return m(t);
    };
    return vs;
}

var Ls;

var _s;

function Ds() {
    if (_s) return Ls;
    _s = 1;
    var e = Ps();
    Ls = function t(n) {
        return !!e(n);
    };
    return Ls;
}

var xs;

var $s;

function qs() {
    if ($s) return xs;
    $s = 1;
    var e = ra();
    var t = Xr();
    var n = t("TypedArray.prototype.buffer", true);
    var a = Ds();
    xs = n || function t(n) {
        if (!a(n)) {
            throw new e("Not a Typed Array");
        }
        return n.buffer;
    };
    return xs;
}

var Us;

var Bs;

function js() {
    if (Bs) return Us;
    Bs = 1;
    var e = t.requireSafeBuffer().Buffer;
    var n = ta();
    var a = qs();
    var r = ArrayBuffer.isView || function e(t) {
        try {
            a(t);
            return true;
        } catch (e) {
            return false;
        }
    };
    var s = typeof Uint8Array !== "undefined";
    var i = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
    var o = i && (e.prototype instanceof Uint8Array || e.TYPED_ARRAY_SUPPORT);
    Us = 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 (i && 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 (s && 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 Us;
}

var Fs;

var ks;

function Qs() {
    if (ks) return Fs;
    ks = 1;
    var e = t.requireSafeBuffer().Buffer;
    var n = js();
    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 s = e.length;
        var i = this._len;
        for (var o = 0; o < s; ) {
            var c = i % r;
            var l = Math.min(s - o, r - c);
            for (var u = 0; u < l; u++) {
                a[c + u] = e[o + u];
            }
            i += l;
            o += l;
            if (i % r === 0) {
                this._update(a);
            }
        }
        this._len += s;
        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 s = this._hash();
        return e ? s.toString(e) : s;
    };
    a.prototype._update = function() {
        throw new Error("_update must be implemented by subclass");
    };
    Fs = a;
    return Fs;
}

var Vs;

var Ks;

function Ws() {
    if (Ks) return Vs;
    Ks = 1;
    var e = t.requireInherits();
    var n = Qs();
    var a = t.requireSafeBuffer().Buffer;
    var r = [ 1518500249, 1859775393, 2400959708 | 0, 3395469782 | 0 ];
    var s = new Array(80);
    function i() {
        this.init();
        this._w = s;
        n.call(this, 64, 56);
    }
    e(i, n);
    i.prototype.init = function() {
        this._a = 1732584193;
        this._b = 4023233417;
        this._c = 2562383102;
        this._d = 271733878;
        this._e = 3285377520;
        return this;
    };
    function o(e) {
        return e << 5 | e >>> 27;
    }
    function c(e) {
        return e << 30 | e >>> 2;
    }
    function l(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;
    }
    i.prototype._update = function(e) {
        var t = this._w;
        var n = this._a | 0;
        var a = this._b | 0;
        var s = this._c | 0;
        var i = this._d | 0;
        var u = 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 = o(n) + l(p, a, s, i) + u + t[d] + r[p] | 0;
            u = i;
            i = s;
            s = c(a);
            a = n;
            n = m;
        }
        this._a = n + this._a | 0;
        this._b = a + this._b | 0;
        this._c = s + this._c | 0;
        this._d = i + this._d | 0;
        this._e = u + this._e | 0;
    };
    i.prototype._hash = function() {
        var e = a.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;
    };
    Vs = i;
    return Vs;
}

var Hs;

var Gs;

function Ys() {
    if (Gs) return Hs;
    Gs = 1;
    var e = t.requireInherits();
    var n = Qs();
    var a = t.requireSafeBuffer().Buffer;
    var r = [ 1518500249, 1859775393, 2400959708 | 0, 3395469782 | 0 ];
    var s = new Array(80);
    function i() {
        this.init();
        this._w = s;
        n.call(this, 64, 56);
    }
    e(i, n);
    i.prototype.init = function() {
        this._a = 1732584193;
        this._b = 4023233417;
        this._c = 2562383102;
        this._d = 271733878;
        this._e = 3285377520;
        return this;
    };
    function o(e) {
        return e << 1 | e >>> 31;
    }
    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;
    }
    i.prototype._update = function(e) {
        var t = this._w;
        var n = this._a | 0;
        var a = this._b | 0;
        var s = this._c | 0;
        var i = this._d | 0;
        var h = this._e | 0;
        for (var d = 0; d < 16; ++d) {
            t[d] = e.readInt32BE(d * 4);
        }
        for (;d < 80; ++d) {
            t[d] = o(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 = c(n) + u(m, a, s, i) + h + t[p] + r[m] | 0;
            h = i;
            i = s;
            s = l(a);
            a = n;
            n = f;
        }
        this._a = n + this._a | 0;
        this._b = a + this._b | 0;
        this._c = s + this._c | 0;
        this._d = i + this._d | 0;
        this._e = h + this._e | 0;
    };
    i.prototype._hash = function() {
        var e = a.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;
    };
    Hs = i;
    return Hs;
}

var zs;

var Js;

function Xs() {
    if (Js) return zs;
    Js = 1;
    var e = t.requireInherits();
    var n = Qs();
    var a = t.requireSafeBuffer().Buffer;
    var r = [ 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 i() {
        this.init();
        this._w = s;
        n.call(this, 64, 56);
    }
    e(i, n);
    i.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 o(e, t, n) {
        return n ^ e & (t ^ n);
    }
    function c(e, t, n) {
        return e & t | n & (e | t);
    }
    function l(e) {
        return (e >>> 2 | e << 30) ^ (e >>> 13 | e << 19) ^ (e >>> 22 | e << 10);
    }
    function u(e) {
        return (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
    }
    function h(e) {
        return (e >>> 7 | e << 25) ^ (e >>> 18 | e << 14) ^ e >>> 3;
    }
    function d(e) {
        return (e >>> 17 | e << 15) ^ (e >>> 19 | e << 13) ^ e >>> 10;
    }
    i.prototype._update = function(e) {
        var t = this._w;
        var n = this._a | 0;
        var a = this._b | 0;
        var s = this._c | 0;
        var i = this._d | 0;
        var p = 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] = d(t[E - 2]) + t[E - 7] + h(t[E - 15]) + t[E - 16] | 0;
        }
        for (var T = 0; T < 64; ++T) {
            var g = y + u(p) + o(p, m, f) + r[T] + t[T] | 0;
            var N = l(n) + c(n, a, s) | 0;
            y = f;
            f = m;
            m = p;
            p = i + g | 0;
            i = s;
            s = a;
            a = n;
            n = g + N | 0;
        }
        this._a = n + this._a | 0;
        this._b = a + this._b | 0;
        this._c = s + this._c | 0;
        this._d = i + this._d | 0;
        this._e = p + this._e | 0;
        this._f = m + this._f | 0;
        this._g = f + this._g | 0;
        this._h = y + this._h | 0;
    };
    i.prototype._hash = function() {
        var e = a.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;
    };
    zs = i;
    return zs;
}

var Zs;

var ei;

function ti() {
    if (ei) return Zs;
    ei = 1;
    var e = t.requireInherits();
    var n = Xs();
    var a = Qs();
    var r = t.requireSafeBuffer().Buffer;
    var s = new Array(64);
    function i() {
        this.init();
        this._w = s;
        a.call(this, 64, 56);
    }
    e(i, n);
    i.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;
    };
    i.prototype._hash = function() {
        var e = r.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;
    };
    Zs = i;
    return Zs;
}

var ni;

var ai;

function ri() {
    if (ai) return ni;
    ai = 1;
    var e = t.requireInherits();
    var n = Qs();
    var a = t.requireSafeBuffer().Buffer;
    var r = [ 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 i() {
        this.init();
        this._w = s;
        n.call(this, 128, 112);
    }
    e(i, n);
    i.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 o(e, t, n) {
        return n ^ e & (t ^ n);
    }
    function c(e, t, n) {
        return e & t | n & (e | t);
    }
    function l(e, t) {
        return (e >>> 28 | t << 4) ^ (t >>> 2 | e << 30) ^ (t >>> 7 | e << 25);
    }
    function u(e, t) {
        return (e >>> 14 | t << 18) ^ (e >>> 18 | t << 14) ^ (t >>> 9 | e << 23);
    }
    function h(e, t) {
        return (e >>> 1 | t << 31) ^ (e >>> 8 | t << 24) ^ e >>> 7;
    }
    function d(e, t) {
        return (e >>> 1 | t << 31) ^ (e >>> 8 | t << 24) ^ (e >>> 7 | t << 25);
    }
    function p(e, t) {
        return (e >>> 19 | t << 13) ^ (t >>> 29 | e << 3) ^ e >>> 6;
    }
    function m(e, t) {
        return (e >>> 19 | t << 13) ^ (t >>> 29 | e << 3) ^ (e >>> 6 | t << 26);
    }
    function f(e, t) {
        return e >>> 0 < t >>> 0 ? 1 : 0;
    }
    i.prototype._update = function(e) {
        var t = this._w;
        var n = this._ah | 0;
        var a = this._bh | 0;
        var s = this._ch | 0;
        var i = this._dh | 0;
        var y = this._eh | 0;
        var E = this._fh | 0;
        var T = this._gh | 0;
        var g = this._hh | 0;
        var N = this._al | 0;
        var b = this._bl | 0;
        var A = this._cl | 0;
        var C = this._dl | 0;
        var R = this._el | 0;
        var S = this._fl | 0;
        var w = this._gl | 0;
        var O = this._hl | 0;
        for (var M = 0; M < 32; M += 2) {
            t[M] = e.readInt32BE(M * 4);
            t[M + 1] = e.readInt32BE(M * 4 + 4);
        }
        for (;M < 160; M += 2) {
            var v = t[M - 15 * 2];
            var I = t[M - 15 * 2 + 1];
            var P = h(v, I);
            var L = d(I, v);
            v = t[M - 2 * 2];
            I = t[M - 2 * 2 + 1];
            var _ = p(v, I);
            var D = m(I, v);
            var x = t[M - 7 * 2];
            var $ = t[M - 7 * 2 + 1];
            var q = t[M - 16 * 2];
            var U = t[M - 16 * 2 + 1];
            var B = L + $ | 0;
            var j = P + x + f(B, L) | 0;
            B = B + D | 0;
            j = j + _ + f(B, D) | 0;
            B = B + U | 0;
            j = j + q + f(B, U) | 0;
            t[M] = j;
            t[M + 1] = B;
        }
        for (var F = 0; F < 160; F += 2) {
            j = t[F];
            B = t[F + 1];
            var k = c(n, a, s);
            var Q = c(N, b, A);
            var V = l(n, N);
            var K = l(N, n);
            var W = u(y, R);
            var H = u(R, y);
            var G = r[F];
            var Y = r[F + 1];
            var z = o(y, E, T);
            var J = o(R, S, w);
            var X = O + H | 0;
            var Z = g + W + f(X, O) | 0;
            X = X + J | 0;
            Z = Z + z + f(X, J) | 0;
            X = X + Y | 0;
            Z = Z + G + f(X, Y) | 0;
            X = X + B | 0;
            Z = Z + j + f(X, B) | 0;
            var ee = K + Q | 0;
            var te = V + k + f(ee, K) | 0;
            g = T;
            O = w;
            T = E;
            w = S;
            E = y;
            S = R;
            R = C + X | 0;
            y = i + Z + f(R, C) | 0;
            i = s;
            C = A;
            s = a;
            A = b;
            a = n;
            b = N;
            N = X + ee | 0;
            n = Z + te + f(N, X) | 0;
        }
        this._al = this._al + N | 0;
        this._bl = this._bl + b | 0;
        this._cl = this._cl + A | 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 + O | 0;
        this._ah = this._ah + n + f(this._al, N) | 0;
        this._bh = this._bh + a + f(this._bl, b) | 0;
        this._ch = this._ch + s + f(this._cl, A) | 0;
        this._dh = this._dh + i + f(this._dl, C) | 0;
        this._eh = this._eh + y + f(this._el, R) | 0;
        this._fh = this._fh + E + f(this._fl, S) | 0;
        this._gh = this._gh + T + f(this._gl, w) | 0;
        this._hh = this._hh + g + f(this._hl, O) | 0;
    };
    i.prototype._hash = function() {
        var e = a.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;
    };
    ni = i;
    return ni;
}

var si;

var ii;

function oi() {
    if (ii) return si;
    ii = 1;
    var e = t.requireInherits();
    var n = ri();
    var a = Qs();
    var r = t.requireSafeBuffer().Buffer;
    var s = new Array(160);
    function i() {
        this.init();
        this._w = s;
        a.call(this, 128, 112);
    }
    e(i, n);
    i.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;
    };
    i.prototype._hash = function() {
        var e = r.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;
    };
    si = i;
    return si;
}

Xn.exports;

var ci;

function li() {
    if (ci) return Xn.exports;
    ci = 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 = Ws();
        e.exports.sha1 = Ys();
        e.exports.sha224 = ti();
        e.exports.sha256 = Xs();
        e.exports.sha384 = oi();
        e.exports.sha512 = ri();
    })(Xn);
    return Xn.exports;
}

Object.defineProperty(Jn, "__esModule", {
    value: true
});

exports.camelCase_1 = Jn.camelCase = di;

Jn.snakeCase = pi;

Jn.titleCase = mi;

Jn.abbreviate = fi;

Jn.shorten = yi;

Jn.hash = Ei;

const ui = e.require$$0;

const hi = ui.__importDefault(li());

function di(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 pi(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 mi(e) {
    return e.replace(/\w\S*/g, e => e.charAt(0).toUpperCase() + e.substr(1).toLowerCase());
}

function fi(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 yi(e, t = {}) {
    const {segmentLength: n = 4, separator: a = "__", termLength: r = 2} = t;
    const s = e.split(a);
    const i = s.reduce((e, t) => {
        const a = t.replace(/([a-z\xE0-\xFF])([A-Z\xC0-\xDF])/g, "$1 $2").split(" ");
        const s = a.length > 1 ? r : n;
        const i = a.map(e => e.substr(0, s)).join("");
        e.push(i);
        return e;
    }, []);
    return i.join(a);
}

function Ei(e, t = {}) {
    const n = (0, hi.default)("sha1");
    n.update(e, "utf8");
    const a = n.digest("hex");
    if (t.length) {
        return a.slice(0, t.length);
    }
    return a;
}

var Ti = {};

Object.defineProperty(Ti, "__esModule", {
    value: true
});

Ti.VersionUtils = void 0;

class VersionUtils {
    static isGreaterOrEqual(e, t) {
        if (!e) {
            return false;
        }
        const n = gi(e);
        const a = gi(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;
    }
}

Ti.VersionUtils = VersionUtils;

function gi(e) {
    return e.split(".").map(e => parseInt(e, 10));
}

Object.defineProperty(zn, "__esModule", {
    value: true
});

zn.DriverUtils = void 0;

const Ni = Jn;

const bi = Ti;

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 bi.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, Ni.shorten)(r);
                if (t.length < e) {
                    return t;
                }
            }
            return (0, Ni.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 s = r !== -1 ? a.substr(0, r) : a;
        let i = r !== -1 ? a.substr(r + 1) : undefined;
        if (i && i.indexOf("?") !== -1) {
            i = i.substr(0, i.indexOf("?"));
        }
        const o = s.lastIndexOf("@");
        const c = s.substr(0, o);
        const l = s.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: i || undefined
        };
    }
    static parseMongoDBConnectionUrl(e) {
        const t = e.split(":")[0];
        const n = e.indexOf("//");
        const a = e.substr(n + 2);
        const r = a.indexOf("/");
        const s = r !== -1 ? a.substr(0, r) : a;
        let i = r !== -1 ? a.substr(r + 1) : undefined;
        let o = "";
        let c = undefined;
        let l = undefined;
        let u = undefined;
        let h = undefined;
        const d = {};
        if (i && i.indexOf("?") !== -1) {
            o = i.substr(i.indexOf("?") + 1, i.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"];
            i = i.substr(0, i.indexOf("?"));
        }
        const p = s.lastIndexOf("@");
        const m = s.substr(0, p);
        const f = s.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: i || undefined
        };
        for (const [e, t] of Object.entries(d)) {
            g[e] = t;
        }
        return g;
    }
}

zn.DriverUtils = DriverUtils;

Object.defineProperty(Gn, "__esModule", {
    value: true
});

Gn.JoinAttribute = void 0;

const Ai = Yn;

const Ci = exports.ObjectUtils;

const Ri = exports.error;

const Si = zn;

class JoinAttribute {
    constructor(e, t, n) {
        this.connection = e;
        this.queryExpressionMap = t;
        this.isSelectedEvaluated = false;
        this.relationEvaluated = false;
        if (n) {
            Ci.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 (!Ai.QueryBuilderUtils.isAliasProperty(this.entityOrProperty)) return undefined;
        return this.entityOrProperty.substr(0, this.entityOrProperty.indexOf("."));
    }
    get relationPropertyPath() {
        if (!Ai.QueryBuilderUtils.isAliasProperty(this.entityOrProperty)) return undefined;
        return this.entityOrProperty.substr(this.entityOrProperty.indexOf(".") + 1);
    }
    get relation() {
        if (!this.relationEvaluated) {
            const e = () => {
                if (!Ai.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 Ri.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 Ri.TypeORMError(`Cannot get junction table for join without relation.`);
        }
        if (typeof this.entityOrProperty !== "string") {
            throw new Ri.TypeORMError(`Junction property is not defined.`);
        }
        const e = this.entityOrProperty.substr(0, this.entityOrProperty.indexOf("."));
        if (this.relation.isOwning) {
            return Si.DriverUtils.buildAlias(this.connection.driver, undefined, e, this.alias.name);
        } else {
            return Si.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];
    }
}

Gn.JoinAttribute = JoinAttribute;

var wi = {};

Object.defineProperty(wi, "__esModule", {
    value: true
});

wi.RelationIdAttribute = void 0;

const Oi = Yn;

const Mi = exports.ObjectUtils;

const vi = W;

class RelationIdAttribute {
    constructor(e, t) {
        this.queryExpressionMap = e;
        this.disableMixedMap = false;
        Mi.ObjectUtils.assign(this, t || {});
    }
    get joinInverseSideMetadata() {
        return this.relation.inverseEntityMetadata;
    }
    get parentAlias() {
        if (!Oi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new vi.TypeORMError(`Given value must be a string representation of alias property`);
        return this.relationName.substr(0, this.relationName.indexOf("."));
    }
    get relationPropertyPath() {
        if (!Oi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new vi.TypeORMError(`Given value must be a string representation of alias property`);
        return this.relationName.substr(this.relationName.indexOf(".") + 1);
    }
    get relation() {
        if (!Oi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new vi.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 vi.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);
    }
}

wi.RelationIdAttribute = RelationIdAttribute;

var Ii = {};

Object.defineProperty(Ii, "__esModule", {
    value: true
});

Ii.RelationCountAttribute = void 0;

const Pi = Yn;

const Li = exports.ObjectUtils;

const _i = W;

class RelationCountAttribute {
    constructor(e, t) {
        this.expressionMap = e;
        Li.ObjectUtils.assign(this, t || {});
    }
    get joinInverseSideMetadata() {
        return this.relation.inverseEntityMetadata;
    }
    get parentAlias() {
        if (!Pi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new _i.TypeORMError(`Given value must be a string representation of alias property`);
        return this.relationName.split(".")[0];
    }
    get relationProperty() {
        if (!Pi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new _i.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 (!Pi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new _i.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 _i.TypeORMError(`Relation with property path ${t} in entity was not found.`);
        return a;
    }
    get metadata() {
        if (!Pi.QueryBuilderUtils.isAliasProperty(this.relationName)) throw new _i.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];
    }
}

Ii.RelationCountAttribute = RelationCountAttribute;

Object.defineProperty(Q, "__esModule", {
    value: true
});

Q.QueryExpressionMap = void 0;

const Di = V;

const xi = Gn;

const $i = wi;

const qi = Ii;

const Ui = exports.error;

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 Di.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 Ui.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 Ui.TypeORMError(`Entity to work with is not specified!`);
        const e = this.mainAlias.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
        if (!e) throw new Ui.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 Di.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 xi.JoinAttribute(this.connection, this, e));
        e.relationIdAttributes = this.relationIdAttributes.map(e => new $i.RelationIdAttribute(this, e));
        e.relationCountAttributes = this.relationCountAttributes.map(e => new qi.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;
    }
}

Q.QueryExpressionMap = QueryExpressionMap;

exports.Brackets = {};

Object.defineProperty(exports.Brackets, "__esModule", {
    value: true
});

exports.Brackets_2 = exports.Brackets.Brackets = void 0;

class Brackets {
    constructor(e) {
        this["@instanceof"] = Symbol.for("Brackets");
        this.whereFactory = e;
    }
}

exports.Brackets_2 = exports.Brackets.Brackets = Brackets;

exports.FindOperator = {};

var Bi = {};

Object.defineProperty(Bi, "__esModule", {
    value: true
});

Bi.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);
    }
}

Bi.ApplyValueTransformers = ApplyValueTransformers;

Object.defineProperty(exports.FindOperator, "__esModule", {
    value: true
});

exports.FindOperator_2 = exports.FindOperator.FindOperator = void 0;

const ji = exports.InstanceChecker;

const Fi = Bi;

class FindOperator {
    constructor(e, t, n = true, a = false, r, s) {
        this["@instanceof"] = Symbol.for("FindOperator");
        this._type = e;
        this._value = t;
        this._useParameter = n;
        this._multipleParameters = a;
        this._getSql = r;
        this._objectLiteralParameters = s;
    }
    get useParameter() {
        if (ji.InstanceChecker.isFindOperator(this._value)) return this._value.useParameter;
        return this._useParameter;
    }
    get multipleParameters() {
        if (ji.InstanceChecker.isFindOperator(this._value)) return this._value.multipleParameters;
        return this._multipleParameters;
    }
    get type() {
        return this._type;
    }
    get value() {
        if (ji.InstanceChecker.isFindOperator(this._value)) return this._value.value;
        return this._value;
    }
    get objectLiteralParameters() {
        if (ji.InstanceChecker.isFindOperator(this._value)) return this._value.objectLiteralParameters;
        return this._objectLiteralParameters;
    }
    get child() {
        if (ji.InstanceChecker.isFindOperator(this._value)) return this._value;
        return undefined;
    }
    get getSql() {
        if (ji.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 && Fi.ApplyValueTransformers.transformTo(e, t)) : Fi.ApplyValueTransformers.transformTo(e, this._value);
        }
    }
}

exports.FindOperator_2 = exports.FindOperator.FindOperator = FindOperator;

var ki = {};

Object.defineProperty(ki, "__esModule", {
    value: true
});

exports.In_2 = ki.In = Vi;

const Qi = exports.FindOperator;

function Vi(e) {
    return new Qi.FindOperator("in", e, true, true);
}

var Ki = {};

Object.defineProperty(Ki, "__esModule", {
    value: true
});

Ki.escapeRegExp = void 0;

const Wi = /[.*+\-?^${}()|[\]\\]/g;

const Hi = e => e.replace(Wi, "\\$&");

Ki.escapeRegExp = Hi;

Object.defineProperty(k, "__esModule", {
    value: true
});

exports.QueryBuilder_2 = k.QueryBuilder = void 0;

const Gi = Q;

const Yi = exports.Brackets;

const zi = exports.FindOperator;

const Ji = ki;

const Xi = exports.error;

const Zi = bt;

const eo = exports.InstanceChecker;

const to = Ki;

class QueryBuilder {
    constructor(e, t) {
        this["@instanceof"] = Symbol.for("QueryBuilder");
        this.parameterIndex = 0;
        if (eo.InstanceChecker.isDataSource(e)) {
            this.connection = e;
            this.queryRunner = t;
            this.expressionMap = new Gi.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 Xi.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 (eo.InstanceChecker.isSelectQueryBuilder(this)) return this;
        return QueryBuilder.queryBuilderRegistry["SelectQueryBuilder"](this);
    }
    insert() {
        this.expressionMap.queryType = "insert";
        if (eo.InstanceChecker.isInsertQueryBuilder(this)) return this;
        return QueryBuilder.queryBuilderRegistry["InsertQueryBuilder"](this);
    }
    update(e, t) {
        const n = t ? t : e;
        e = eo.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 (eo.InstanceChecker.isUpdateQueryBuilder(this)) return this;
        return QueryBuilder.queryBuilderRegistry["UpdateQueryBuilder"](this);
    }
    delete() {
        this.expressionMap.queryType = "delete";
        if (eo.InstanceChecker.isDeleteQueryBuilder(this)) return this;
        return QueryBuilder.queryBuilderRegistry["DeleteQueryBuilder"](this);
    }
    softDelete() {
        this.expressionMap.queryType = "soft-delete";
        if (eo.InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
        return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this);
    }
    restore() {
        this.expressionMap.queryType = "restore";
        if (eo.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 (eo.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 Xi.TypeORMError(`Function parameter isn't supported in the parameters. Please check "${e}" parameter.`);
        }
        if (!e.match(/^([A-Za-z0-9_.]+)$/)) {
            throw new Xi.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 Xi.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, to.escapeRegExp)(e)).join("|");
        if (n.length > 0) {
            e = e.replace(new RegExp(`([ =(]|^.{0})` + `${a ? "(" + a + ")" : ""}([^ =(),]+)` + `(?=[ =),]|.{0}$)`, "gm"), (...e) => {
                let n, r, s;
                if (a) {
                    n = e[0];
                    r = e[1];
                    s = e[3];
                    if (t[e[2]][s]) {
                        return `${r}${this.escape(e[2].substring(0, e[2].length - 1))}.${this.escape(t[e[2]][s])}`;
                    }
                } else {
                    n = e[0];
                    r = e[1];
                    s = e[2];
                    if (t[""][s]) {
                        return `${r}${this.escape(t[""][s])}`;
                    }
                }
                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 ${zi.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 Xi.TypeORMError(`Nested CTEs aren't supported (CTE: ${t.alias})`);
                }
                n = t.queryBuilder.getQuery();
                if (!this.connection.driver.cteCapabilities.writable && !eo.InstanceChecker.isSelectQueryBuilder(t.queryBuilder)) {
                    throw new Xi.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 (eo.InstanceChecker.isSelectQueryBuilder(t.queryBuilder)) {
                    if (t.queryBuilder.expressionMap.selects.length && t.options.columnNames.length !== t.queryBuilder.expressionMap.selects.length) {
                        throw new Xi.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 s = "";
            if (this.connection.driver.cteCapabilities.materializedHint && t.options.materialized !== undefined) {
                s = t.options.materialized ? "MATERIALIZED" : "NOT MATERIALIZED";
            }
            return [ r, a, "AS", s, `(${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, Ji.In)(n.map(t => e.getEntityValue(t, false)))
                };
            }
        }
        return new Yi.Brackets(e => {
            for (const t of n) {
                e.orWhere(new Yi.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 s = t.metadata.findColumnsWithPropertyPath(r);
        if (!s.length) {
            throw new Zi.EntityPropertyNotFoundError(e, t.metadata);
        }
        return [ t, n, s ];
    }
    createPropertyPath(e, t, n = "") {
        const a = [];
        for (const r of Object.keys(t)) {
            const s = n ? `${n}.${r}` : r;
            if (t[r] === null || typeof t[r] !== "object" || eo.InstanceChecker.isFindOperator(t[r])) {
                a.push(s);
                continue;
            }
            if (e.hasEmbeddedWithPropertyPath(s)) {
                const n = this.createPropertyPath(e, t[r], s);
                a.push(...n);
                continue;
            }
            if (e.hasRelationWithPropertyPath(s)) {
                const n = e.findRelationWithPropertyPath(s);
                if (n.relationType === "one-to-one" || n.relationType === "many-to-one") {
                    const e = n.joinColumns.map(e => e.referencedColumn).filter(e => !!e);
                    const i = e.length > 0 && e.every(e => e.getEntityValue(t[r], false));
                    if (i) {
                        a.push(s);
                        continue;
                    }
                }
                if (n.relationType === "one-to-many" || n.relationType === "many-to-many") {
                    throw new Error(`Cannot query across ${n.relationType} for property ${s}`);
                }
                const i = n.inverseEntityMetadata.primaryColumns;
                const o = i.length > 0 && i.every(e => e.getEntityValue(t[r], false));
                if (o) {
                    const e = i.map(e => `${s}.${e.propertyPath}`);
                    a.push(...e);
                    continue;
                }
                const c = this.createPropertyPath(n.inverseEntityMetadata, t[r]).map(e => `${s}.${e}`);
                a.push(...c);
                continue;
            }
            a.push(s);
        }
        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 s = this.expressionMap.aliasNamePrefixingEnabled ? `${t.name}.${n.propertyPath}` : n.propertyPath;
                    const i = n.getEntityValue(r, true);
                    yield [ s, i ];
                }
            }
        } 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 (eo.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 (eo.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: eo.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;
    }
}

exports.QueryBuilder_2 = k.QueryBuilder = QueryBuilder;

QueryBuilder.queryBuilderRegistry = {};

var no = {};

Object.defineProperty(no, "__esModule", {
    value: true
});

exports.DeleteResult_2 = no.DeleteResult = void 0;

class DeleteResult {
    static from(e) {
        const t = new this;
        t.raw = e.records;
        t.affected = e.affected;
        return t;
    }
}

exports.DeleteResult_2 = no.DeleteResult = DeleteResult;

Object.defineProperty(F, "__esModule", {
    value: true
});

exports.DeleteQueryBuilder_2 = F.DeleteQueryBuilder = void 0;

const ao = k;

const ro = no;

const so = ut;

const io = exports.InstanceChecker;

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 s = 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 s;
        } catch (e) {
            if (a) {
                try {
                    await n.rollbackTransaction();
                } catch (e) {}
            }
            throw e;
        } finally {
            if (n !== this.queryRunner) {
                await n.release();
            }
        }
    }
    from(e, t) {
        e = io.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 so.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}`;
    }
}

exports.DeleteQueryBuilder_2 = F.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 bo(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 s = go();
        Ao(No, e, s);
        a = Co(s, No.msecs, No.nsecs, r ? undefined : No.clockseq, r ? undefined : No.node, t, n);
    }
    return t ?? fo(a);
}

function Ao(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, s, i = 0) {
    if (e.length < 16) {
        throw new Error("Random bytes length must be >= 16");
    }
    if (!s) {
        s = new Uint8Array(16);
        i = 0;
    } else {
        if (i < 0 || i + 16 > s.length) {
            throw new RangeError(`UUID byte range ${i}:${i + 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;
    s[i++] = o >>> 24 & 255;
    s[i++] = o >>> 16 & 255;
    s[i++] = o >>> 8 & 255;
    s[i++] = o & 255;
    const c = t / 4294967296 * 1e4 & 268435455;
    s[i++] = c >>> 8 & 255;
    s[i++] = c & 255;
    s[i++] = c >>> 24 & 15 | 16;
    s[i++] = c >>> 16 & 255;
    s[i++] = a >>> 8 | 128;
    s[i++] = a & 255;
    for (let e = 0; e < 6; ++e) {
        s[i++] = r[e];
    }
    return s;
}

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 Oo(n);
}

function Oo(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 Mo(e) {
    return (e + 64 >>> 9 << 4) + 14 + 1;
}

function vo(e, t) {
    const n = new Uint32Array(Mo(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 s = -1732584194;
    let i = 271733878;
    for (let t = 0; t < e.length; t += 16) {
        const n = a;
        const o = r;
        const c = s;
        const l = i;
        a = Do(a, r, s, i, e[t], 7, -680876936);
        i = Do(i, a, r, s, e[t + 1], 12, -389564586);
        s = Do(s, i, a, r, e[t + 2], 17, 606105819);
        r = Do(r, s, i, a, e[t + 3], 22, -1044525330);
        a = Do(a, r, s, i, e[t + 4], 7, -176418897);
        i = Do(i, a, r, s, e[t + 5], 12, 1200080426);
        s = Do(s, i, a, r, e[t + 6], 17, -1473231341);
        r = Do(r, s, i, a, e[t + 7], 22, -45705983);
        a = Do(a, r, s, i, e[t + 8], 7, 1770035416);
        i = Do(i, a, r, s, e[t + 9], 12, -1958414417);
        s = Do(s, i, a, r, e[t + 10], 17, -42063);
        r = Do(r, s, i, a, e[t + 11], 22, -1990404162);
        a = Do(a, r, s, i, e[t + 12], 7, 1804603682);
        i = Do(i, a, r, s, e[t + 13], 12, -40341101);
        s = Do(s, i, a, r, e[t + 14], 17, -1502002290);
        r = Do(r, s, i, a, e[t + 15], 22, 1236535329);
        a = xo(a, r, s, i, e[t + 1], 5, -165796510);
        i = xo(i, a, r, s, e[t + 6], 9, -1069501632);
        s = xo(s, i, a, r, e[t + 11], 14, 643717713);
        r = xo(r, s, i, a, e[t], 20, -373897302);
        a = xo(a, r, s, i, e[t + 5], 5, -701558691);
        i = xo(i, a, r, s, e[t + 10], 9, 38016083);
        s = xo(s, i, a, r, e[t + 15], 14, -660478335);
        r = xo(r, s, i, a, e[t + 4], 20, -405537848);
        a = xo(a, r, s, i, e[t + 9], 5, 568446438);
        i = xo(i, a, r, s, e[t + 14], 9, -1019803690);
        s = xo(s, i, a, r, e[t + 3], 14, -187363961);
        r = xo(r, s, i, a, e[t + 8], 20, 1163531501);
        a = xo(a, r, s, i, e[t + 13], 5, -1444681467);
        i = xo(i, a, r, s, e[t + 2], 9, -51403784);
        s = xo(s, i, a, r, e[t + 7], 14, 1735328473);
        r = xo(r, s, i, a, e[t + 12], 20, -1926607734);
        a = $o(a, r, s, i, e[t + 5], 4, -378558);
        i = $o(i, a, r, s, e[t + 8], 11, -2022574463);
        s = $o(s, i, a, r, e[t + 11], 16, 1839030562);
        r = $o(r, s, i, a, e[t + 14], 23, -35309556);
        a = $o(a, r, s, i, e[t + 1], 4, -1530992060);
        i = $o(i, a, r, s, e[t + 4], 11, 1272893353);
        s = $o(s, i, a, r, e[t + 7], 16, -155497632);
        r = $o(r, s, i, a, e[t + 10], 23, -1094730640);
        a = $o(a, r, s, i, e[t + 13], 4, 681279174);
        i = $o(i, a, r, s, e[t], 11, -358537222);
        s = $o(s, i, a, r, e[t + 3], 16, -722521979);
        r = $o(r, s, i, a, e[t + 6], 23, 76029189);
        a = $o(a, r, s, i, e[t + 9], 4, -640364487);
        i = $o(i, a, r, s, e[t + 12], 11, -421815835);
        s = $o(s, i, a, r, e[t + 15], 16, 530742520);
        r = $o(r, s, i, a, e[t + 2], 23, -995338651);
        a = qo(a, r, s, i, e[t], 6, -198630844);
        i = qo(i, a, r, s, e[t + 7], 10, 1126891415);
        s = qo(s, i, a, r, e[t + 14], 15, -1416354905);
        r = qo(r, s, i, a, e[t + 5], 21, -57434055);
        a = qo(a, r, s, i, e[t + 12], 6, 1700485571);
        i = qo(i, a, r, s, e[t + 3], 10, -1894986606);
        s = qo(s, i, a, r, e[t + 10], 15, -1051523);
        r = qo(r, s, i, a, e[t + 1], 21, -2054922799);
        a = qo(a, r, s, i, e[t + 8], 6, 1873313359);
        i = qo(i, a, r, s, e[t + 15], 10, -30611744);
        s = qo(s, i, a, r, e[t + 6], 15, -1560198380);
        r = qo(r, s, i, a, e[t + 13], 21, 1309151649);
        a = qo(a, r, s, i, e[t + 4], 6, -145523070);
        i = qo(i, a, r, s, e[t + 11], 10, -1120210379);
        s = qo(s, i, a, r, e[t + 2], 15, 718787259);
        r = qo(r, s, i, a, e[t + 9], 21, -343485551);
        a = Po(a, n);
        r = Po(r, o);
        s = Po(s, c);
        i = Po(i, l);
    }
    return Uint32Array.of(a, r, s, i);
}

function Io(e) {
    if (e.length === 0) {
        return new Uint32Array;
    }
    const t = new Uint32Array(Mo(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 _o(e, t, n, a, r, s) {
    return Po(Lo(Po(Po(t, e), Po(a, s)), r), n);
}

function Do(e, t, n, a, r, s, i) {
    return _o(t & n | ~t & a, e, t, r, s, i);
}

function xo(e, t, n, a, r, s, i) {
    return _o(t & a | n & ~a, e, t, r, s, i);
}

function $o(e, t, n, a, r, s, i) {
    return _o(t ^ n ^ a, e, t, r, s, i);
}

function qo(e, t, n, a, r, s, i) {
    return _o(n ^ (t | ~a), e, t, r, s, i);
}

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 jo = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";

function Fo(e, t, n, a, r, s) {
    const i = 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 + i.length);
    c.set(o);
    c.set(i, o.length);
    c = t(c);
    c[6] = c[6] & 15 | e;
    c[8] = c[8] & 63 | 128;
    if (r) {
        s = s || 0;
        for (let e = 0; e < 16; ++e) {
            r[s + e] = c[e];
        }
        return r;
    }
    return fo(c);
}

function ko(e, t, n, a) {
    return Fo(48, wo, e, t, n, a);
}

ko.DNS = Bo;

ko.URL = jo;

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 s = Math.ceil(r / 16);
    const i = new Array(s);
    for (let t = 0; t < s; ++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];
        }
        i[t] = n;
    }
    i[s - 1][14] = (e.length - 1) * 8 / Math.pow(2, 32);
    i[s - 1][14] = Math.floor(i[s - 1][14]);
    i[s - 1][15] = (e.length - 1) * 8 & 4294967295;
    for (let e = 0; e < s; ++e) {
        const a = new Uint32Array(80);
        for (let t = 0; t < 16; ++t) {
            a[t] = i[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 s = 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 i = Ho(r, 5) + Wo(n, s, o, c) + l + t[n] + a[e] >>> 0;
            l = c;
            c = o;
            o = Ho(s, 30) >>> 0;
            s = r;
            r = i;
        }
        n[0] = n[0] + r >>> 0;
        n[1] = n[1] + s >>> 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 Fo(80, Go, e, t, n, a);
}

Yo.DNS = Bo;

Yo.URL = jo;

function zo(e, t, n) {
    e ??= {};
    n ??= 0;
    let a = bo({
        ...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: bo,
    v1ToV6: Ro,
    v3: ko,
    v4: Ko,
    v5: Yo,
    v6: zo,
    v6ToV1: Jo,
    v7: ec,
    validate: ho,
    version: ac
}, Symbol.toStringTag, {
    value: "Module"
}));

const sc = n.getAugmentedNamespace(rc);

var ic = {};

Object.defineProperty(ic, "__esModule", {
    value: true
});

ic.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;
    }
}

ic.BroadcasterResult = BroadcasterResult;

var oc = {};

Object.defineProperty(oc, "__esModule", {
    value: true
});

exports.InsertResult_2 = oc.InsertResult = void 0;

class InsertResult {
    constructor() {
        this.identifiers = [];
        this.generatedMaps = [];
    }
    static from(e) {
        const t = new this;
        t.raw = e.raw;
        return t;
    }
}

exports.InsertResult_2 = oc.InsertResult = InsertResult;

var cc = {};

Object.defineProperty(cc, "__esModule", {
    value: true
});

cc.ReturningResultsEntityUpdator = void 0;

const lc = exports.error;

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 s = this.queryRunner.connection.driver.createGeneratedMap(n, r);
                if (s) {
                    this.queryRunner.manager.merge(n.target, t, s);
                    e.generatedMaps.push(s);
                }
            } else {
                const a = this.expressionMap.extraReturningColumns;
                if (a.length > 0) {
                    const r = this.expressionMap.mainAlias.metadata.getEntityIdMap(t);
                    if (!r) throw new lc.TypeORMError(`Cannot update entity because entity id is not set in the entity.`);
                    const s = 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 (s) {
                        this.queryRunner.manager.merge(n.target, t, s);
                        e.generatedMaps.push(s);
                    }
                }
            }
        }));
    }
    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 s = 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 s = Array.isArray(e.raw) ? e.raw[r] : e.raw;
            const i = this.queryRunner.connection.driver.createGeneratedMap(n, s, r, t.length) || {};
            if (r in this.expressionMap.locallyGenerated) {
                this.queryRunner.manager.merge(n.target, i, this.expressionMap.locallyGenerated[r]);
            }
            this.queryRunner.manager.merge(n.target, a, i);
            return i;
        });
        if (a.length > 0 && !this.queryRunner.connection.driver.isReturningSqlSupported("insert")) {
            const e = t.map(e => {
                const t = n.getEntityIdMap(e);
                if (!t) throw new lc.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, s[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(s[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);
    }
}

cc.ReturningResultsEntityUpdator = ReturningResultsEntityUpdator;

Object.defineProperty(oo, "__esModule", {
    value: true
});

exports.InsertQueryBuilder_2 = oo.InsertQueryBuilder = void 0;

const uc = sc;

const hc = zn;

const dc = exports.error;

const pc = qt;

const mc = ut;

const fc = ic;

const yc = exports.InstanceChecker;

const Ec = exports.ObjectUtils;

const Tc = k;

const gc = oc;

const Nc = cc;

class InsertQueryBuilder extends Tc.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 gc.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 fc.BroadcasterResult;
                e.forEach(e => {
                    t.broadcaster.broadcastBeforeInsertEvent(n, this.expressionMap.mainAlias.metadata, e);
                });
                await n.wait();
            }
            let a = null;
            let r = null;
            const s = new Nc.ReturningResultsEntityUpdator(t, 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) {
                if (!(e.length > 1 && this.connection.driver.options.type === "oracle")) {
                    this.expressionMap.extraReturningColumns = this.expressionMap.mainAlias.metadata.getInsertionReturningColumns();
                }
                i.push(...this.expressionMap.extraReturningColumns.filter(e => !i.includes(e)));
            }
            if (i.length > 0 && this.connection.driver.options.type === "mssql") {
                a = this.connection.driver.buildTableVariableDeclaration("@OutputTable", i);
                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 = gc.InsertResult.from(h);
            if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata) {
                await s.insert(d, e);
            }
            if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
                const n = new fc.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 = yc.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 mc.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 (hc.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() && hc.DriverUtils.isPostgresFamily(this.connection.driver)) {
            r += ` AS "${this.alias}"`;
        }
        if (a) {
            r += `(${a})`;
        } else {
            if (!t && (hc.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 (hc.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: s} = this.expressionMap.onUpdate;
                    let i = "ON CONFLICT";
                    if (Array.isArray(n)) {
                        i += ` ( ${n.map(e => this.escape(e)).join(", ")} )`;
                        if (s && !hc.DriverUtils.isPostgresFamily(this.connection.driver)) {
                            throw new dc.TypeORMError(`indexPredicate option is not supported by the current database driver`);
                        }
                        if (s && hc.DriverUtils.isPostgresFamily(this.connection.driver)) {
                            i += ` WHERE ( ${s} )`;
                        }
                    } else if (n) {
                        i += ` 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 += ` ${i} 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 || hc.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 && hc.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 dc.TypeORMError(`onUpdate is not supported by the current database driver`);
                }
            }
        }
        if (n && (hc.DriverUtils.isPostgresFamily(this.connection.driver) || this.connection.driver.options.type === "oracle" || this.connection.driver.options.type === "cockroachdb" || hc.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") && !hc.DriverUtils.isSQLiteFamily(this.connection.driver) && !hc.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((s, i) => {
                    if (i === 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 = s.getEntityValue(a);
                    if (!(typeof o === "function")) {
                        o = this.connection.driver.preparePersistentValue(o, s);
                    }
                    if (s.isVersion && o === undefined) {
                        n += "1";
                    } else if (s.isDiscriminator) {
                        n += this.createParameter(this.expressionMap.mainAlias.metadata.discriminatorValue);
                    } else if (s.isGenerated && s.generationStrategy === "uuid" && !this.connection.driver.isUUIDGenerationSupported() && o === undefined) {
                        o = (0, uc.v4)();
                        n += this.createParameter(o);
                        if (!(r in this.expressionMap.locallyGenerated)) {
                            this.expressionMap.locallyGenerated[r] = {};
                        }
                        s.setEntityValue(this.expressionMap.locallyGenerated[r], o);
                    } else if (o === undefined) {
                        if (this.connection.driver.options.type === "oracle" && e.length > 1 || hc.DriverUtils.isSQLiteFamily(this.connection.driver) || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
                            if (s.default !== undefined && s.default !== null) {
                                n += this.connection.driver.normalizeDefault(s);
                            } else if (this.connection.driver.options.type === "spanner" && s.isGenerated && s.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(s, o);
                        const e = this.createParameter(o);
                        if ((hc.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") && this.connection.driver.spatialTypes.indexOf(s.type) !== -1) {
                            const t = this.connection.driver.options.legacySpatialSupport;
                            const a = t ? "GeomFromText" : "ST_GeomFromText";
                            if (s.srid != null) {
                                n += `${a}(${e}, ${s.srid})`;
                            } else {
                                n += `${a}(${e})`;
                            }
                        } else if (hc.DriverUtils.isPostgresFamily(this.connection.driver) && this.connection.driver.spatialTypes.indexOf(s.type) !== -1) {
                            if (s.srid != null) {
                                n += `ST_SetSRID(ST_GeomFromGeoJSON(${e}), ${s.srid})::${s.type}`;
                            } else {
                                n += `ST_GeomFromGeoJSON(${e})::${s.type}`;
                            }
                        } else if (this.connection.driver.options.type === "mssql" && this.connection.driver.spatialTypes.indexOf(s.type) !== -1) {
                            n += s.type + "::STGeomFromText(" + e + ", " + (s.srid || "0") + ")";
                        } else {
                            n += e;
                        }
                    }
                    if (i === 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, s) => {
                    if (s === 0) {
                        t += "(";
                    }
                    const i = n[r];
                    if (typeof i === "function") {
                        t += i();
                    } else if (i === undefined) {
                        if (this.connection.driver.options.type === "oracle" && e.length > 1 || hc.DriverUtils.isSQLiteFamily(this.connection.driver) || this.connection.driver.options.type === "sap" || this.connection.driver.options.type === "spanner") {
                            t += "NULL";
                        } else {
                            t += "DEFAULT";
                        }
                    } else if (i === null && this.connection.driver.options.type === "spanner") ; else {
                        t += this.createParameter(i);
                    }
                    if (s === 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 (Ec.ObjectUtils.isObject(this.expressionMap.valuesSet)) return [ this.expressionMap.valuesSet ];
        throw new pc.InsertValuesMissingError;
    }
    isOverridingAutoIncrementBehavior(e) {
        return e.isPrimary && e.isGenerated && e.generationStrategy === "increment" && this.getValueSets().some(t => e.getEntityValue(t) !== undefined && e.getEntityValue(t) !== null);
    }
}

exports.InsertQueryBuilder_2 = oo.InsertQueryBuilder = InsertQueryBuilder;

var bc = {};

var Ac = {};

Object.defineProperty(Ac, "__esModule", {
    value: true
});

Ac.RelationUpdater = void 0;

const Cc = exports.error;

const Rc = exports.ObjectUtils;

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 = Rc.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, s) => {
                    const i = "joinColumn_" + n + "_" + s;
                    a[i] = Rc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
                    r.push(`${t.propertyPath} = :${i}`);
                });
            });
            const s = r.map(e => "(" + e + ")").join(" OR ");
            if (!s) return;
            await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(e).where(s).setParameters(a).execute();
        } else if (t.isOneToOneNotOwner || t.isOneToMany) {
            if (Array.isArray(this.expressionMap.of)) throw new Cc.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 = Rc.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 s = t.isManyToManyOwner ? a : r;
            const i = t.isManyToManyOwner ? r : a;
            const o = [];
            s.forEach(e => {
                i.forEach(t => {
                    const a = {};
                    n.ownerColumns.forEach(t => {
                        a[t.databaseName] = Rc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
                    });
                    n.inverseColumns.forEach(e => {
                        a[e.databaseName] = Rc.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();
            }
        }
    }
}

Ac.RelationUpdater = RelationUpdater;

var Sc = {};

Object.defineProperty(Sc, "__esModule", {
    value: true
});

Sc.RelationRemover = void 0;

const wc = exports.ObjectUtils;

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 s = {};
            const i = [];
            n.forEach((e, n) => {
                i.push(...a.map((a, r) => [ ...t.inverseRelation.joinColumns.map((t, a) => {
                    const i = "joinColumn_" + n + "_" + r + "_" + a;
                    s[i] = wc.ObjectUtils.isObject(e) ? t.referencedColumn.getEntityValue(e) : e;
                    return `${t.propertyPath} = :${i}`;
                }), ...t.inverseRelation.entityMetadata.primaryColumns.map((e, t) => {
                    const n = "primaryColumn_" + r + "_" + r + "_" + t;
                    s[n] = wc.ObjectUtils.isObject(a) ? e.getEntityValue(a) : a;
                    return `${e.propertyPath} = :${n}`;
                }) ].join(" AND ")));
            });
            const o = i.map(e => "(" + e + ")").join(" OR ");
            if (!o) return;
            await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(r).where(o).setParameters(s).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 s = t.isManyToManyOwner ? a : r;
            const i = t.isManyToManyOwner ? r : a;
            const o = {};
            const c = [];
            s.forEach((e, t) => {
                c.push(...i.map((a, r) => [ ...n.ownerColumns.map((n, a) => {
                    const s = "firstValue_" + t + "_" + r + "_" + a;
                    o[s] = wc.ObjectUtils.isObject(e) ? n.referencedColumn.getEntityValue(e) : e;
                    return `${n.databaseName} = :${s}`;
                }), ...n.inverseColumns.map((e, n) => {
                    const s = "secondValue_" + t + "_" + r + "_" + n;
                    o[s] = wc.ObjectUtils.isObject(a) ? e.referencedColumn.getEntityValue(a) : a;
                    return `${e.databaseName} = :${s}`;
                }) ].join(" AND ")));
            });
            const l = c.map(e => "(" + e + ")").join(" OR ");
            await this.queryBuilder.createQueryBuilder().delete().from(n.tableName).where(l).setParameters(o).execute();
        }
    }
}

Sc.RelationRemover = RelationRemover;

Object.defineProperty(bc, "__esModule", {
    value: true
});

exports.RelationQueryBuilder_2 = bc.RelationQueryBuilder = void 0;

const Oc = k;

const Mc = Ac;

const vc = Sc;

const Ic = exports.error;

const Pc = exports.ObjectUtils;

class RelationQueryBuilder extends Oc.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 Ic.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 Ic.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 && (!Pc.ObjectUtils.isObject(e) || Object.keys(e).length < t.joinColumns.length)) throw new Ic.TypeORMError(`Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })`);
        const n = new Mc.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 Ic.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 Ic.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 && (!Pc.ObjectUtils.isObject(e) || Object.keys(e).length < t.joinColumns.length)) throw new Ic.TypeORMError(`Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })`);
        const n = new Mc.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 Ic.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 Ic.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 vc.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 (!Pc.ObjectUtils.isObject(e)) {
            const t = this.expressionMap.mainAlias.metadata;
            if (t.hasMultiplePrimaryKeys) throw new Ic.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);
    }
}

exports.RelationQueryBuilder_2 = bc.RelationQueryBuilder = RelationQueryBuilder;

var Lc = {};

var _c = {};

var Dc = {};

Object.defineProperty(Dc, "__esModule", {
    value: true
});

Dc.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 s = "";
            const i = [];
            for (let e = 0; e < a.length; e++) {
                const t = a[e];
                switch (t) {
                  case ",":
                    if (r == "") {
                        i.push(s);
                        s = "";
                    } else {
                        s += t;
                    }
                    break;

                  case "'":
                    if (r == t) {
                        const n = a[e + 1] === t;
                        if (n) {
                            s += t;
                            e += 1;
                        } else {
                            r = "";
                        }
                    } else {
                        r = t;
                    }
                    break;

                  case ")":
                    if (r == "") {
                        i.push(s);
                        return i;
                    } else {
                        s += t;
                    }
                    break;

                  default:
                    if (r != "") {
                        s += 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);
            }
        }
    }
}

Dc.OrmUtils = OrmUtils;

Object.defineProperty(_c, "__esModule", {
    value: true
});

_c.RawSqlResultsToEntityTransformer = void 0;

const xc = Dc;

const $c = zn;

const qc = exports.ObjectUtils;

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 = $c.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 (qc.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 s = this.transformJoins(e, a, t, n);
        const i = 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 && (s || i || o)) return a;
        return undefined;
    }
    transformColumns(e, t, n, a) {
        let r = false;
        const s = e[0];
        for (const [e, i] of this.getColumnsToProcess(t.name, a)) {
            const t = s[e];
            if (t === undefined) continue; else if (t !== null && !i.isVirtualProperty) r = true;
            i.setEntityValue(n, this.driver.prepareHydratedValue(t, i));
        }
        return r;
    }
    transformJoins(e, t, n, a) {
        let r = false;
        for (const s of this.expressionMap.joinAttributes) {
            if (!s.metadata) continue;
            if (!s.isSelected) continue;
            if (s.relation && !a.relations.find(e => e === s.relation)) continue;
            if (s.mapToProperty) {
                if (s.mapToPropertyParentAlias !== n.name) continue;
            } else {
                if (!s.relation || s.parentAlias !== n.name || s.relationPropertyPath !== s.relation.propertyPath) continue;
            }
            let i = this.transform(e, s.alias);
            i = !s.isMany ? i[0] : i;
            i = !s.isMany && i === undefined ? null : i;
            if (i === undefined) continue;
            if (s.mapToPropertyPropertyName) {
                t[s.mapToPropertyPropertyName] = i;
            } else {
                s.relation.setEntityValue(t, i);
            }
            r = true;
        }
        return r;
    }
    transformRelationIds(e, t, n, a) {
        let r = false;
        for (const [a, s] of this.rawRelationIdResults.entries()) {
            if (s.relationIdAttribute.parentAlias !== t.name) continue;
            const i = s.relationIdAttribute.relation;
            const o = this.createValueMapFromJoinColumns(i, s.relationIdAttribute.parentAlias, e);
            if (o === undefined || o === null) {
                continue;
            }
            this.prepareDataForTransformRelationIds();
            const c = this.hashEntityIds(i, o);
            const l = this.relationIdMaps[a][c] || [];
            const u = s.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 (i.isOneToOne || i.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 s = r.relationCountAttribute.relation;
            let i;
            if (s.isOneToMany) {
                i = s.inverseRelation.joinColumns[0].referencedColumn.databaseName;
            } else {
                i = s.isOwning ? s.joinColumns[0].referencedColumn.databaseName : s.inverseRelation.joinColumns[0].referencedColumn.databaseName;
            }
            const o = e[0][this.buildAlias(t.name, i)];
            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 s of n) {
                if (e.isManyToOne || e.isOneToOneOwner) {
                    a[r.databaseName] = this.driver.prepareHydratedValue(s[this.buildAlias(t, r.databaseName)], r);
                } else {
                    a[r.databaseName] = this.driver.prepareHydratedValue(s[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 s = 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 xc.OrmUtils.mergeDeep(e, n.createValueMap(a));
                    }
                    if (!n.isPrimary && n.referencedColumn.referencedColumn) {
                        a = n.referencedColumn.referencedColumn.createValueMap(a);
                    }
                    return xc.OrmUtils.mergeDeep(e, n.referencedColumn.createValueMap(a));
                }, {});
                if (n.length === 1 && !e.relationIdAttribute.disableMixedMap) {
                    if (t.isOneToMany || t.isOneToOneNotOwner) {
                        s = n[0].getEntityValue(s);
                    } else {
                        s = n[0].referencedColumn.getEntityValue(s);
                    }
                }
                if (s !== undefined) {
                    const e = this.hashEntityIds(t, r);
                    if (a[e]) {
                        a[e].push(s);
                    } else {
                        a[e] = [ s ];
                    }
                }
                return a;
            }, {});
        });
    }
    hashEntityIds(e, t) {
        const n = this.extractEntityPrimaryIds(e, t);
        return JSON.stringify(n);
    }
}

_c.RawSqlResultsToEntityTransformer = RawSqlResultsToEntityTransformer;

var Uc = {};

Object.defineProperty(Uc, "__esModule", {
    value: true
});

Uc.RelationIdLoader = void 0;

const Bc = zn;

const jc = W;

const Fc = Dc;

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 jc.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[Bc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, n.databaseName)], n.referencedColumn);
                        const s = `${n.databaseName}:${a[n.databaseName]}`;
                        if (r.indexOf(s) === -1) {
                            r.push(s);
                        }
                    });
                    t.relation.entityMetadata.primaryColumns.forEach(n => {
                        a[n.databaseName] = this.connection.driver.prepareHydratedValue(e[Bc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, n.databaseName)], n);
                        const s = `${n.databaseName}:${a[n.databaseName]}`;
                        if (r.indexOf(s) === -1) {
                            r.push(s);
                        }
                    });
                    r.sort();
                    const s = r.join("::");
                    if (n[s]) {
                        return null;
                    }
                    n[s] = 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 s = n.inverseEntityMetadata.tableName;
                const i = t.alias || s;
                const o = {};
                const c = {};
                const l = e.map((e, n) => {
                    const r = [];
                    const s = {};
                    const l = a.map(a => {
                        const o = a.databaseName + n;
                        const c = e[Bc.DriverUtils.buildAlias(this.connection.driver, undefined, t.parentAlias, a.referencedColumn.databaseName)];
                        const l = `${i}:${a.propertyPath}:${c}`;
                        if (r.indexOf(l) !== -1) {
                            return "";
                        }
                        r.push(l);
                        s[o] = c;
                        return i + "." + a.propertyPath + " = :" + o;
                    }).filter(e => e).join(" AND ");
                    r.sort();
                    const u = r.join("::");
                    if (o[u]) {
                        return "";
                    }
                    o[u] = true;
                    Object.assign(c, s);
                    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 = Fc.OrmUtils.uniq([ ...a, ...n.inverseRelation.entityMetadata.primaryColumns ], e => e.propertyPath);
                h.forEach(e => {
                    u.addSelect(i + "." + e.propertyPath, e.databaseName);
                });
                u.from(r, i).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 s = t.junctionAlias;
                const i = t.joinInverseSideMetadata.tableName;
                const o = t.alias || i;
                const c = n.isOwning ? n.junctionEntityMetadata.tableName : n.inverseRelation.junctionEntityMetadata.tableName;
                const l = e.map(e => a.reduce((n, a) => {
                    n[a.propertyPath] = e[Bc.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 i = r + t;
                        const o = e[r];
                        const c = `${s}:${r}:${o}`;
                        if (n.indexOf(c) !== -1) {
                            return "";
                        }
                        n.push(c);
                        a[i] = o;
                        return s + "." + r + " = :" + i;
                    }).filter(e => e).join(" AND ");
                    n.sort();
                    const i = n.join("::");
                    if (h[i]) {
                        return "";
                    }
                    h[i] = true;
                    Object.assign(u, a);
                    return r;
                }).filter(e => e);
                const p = r.map(e => s + "." + 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(s + "." + e.propertyPath, e.databaseName).addOrderBy(s + "." + e.propertyPath);
                });
                a.forEach(e => {
                    f.addSelect(s + "." + e.propertyPath, e.databaseName).addOrderBy(s + "." + e.propertyPath);
                });
                f.from(i, o).innerJoin(c, s, 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);
    }
};

Uc.RelationIdLoader = kc;

var Qc = {};

Object.defineProperty(Qc, "__esModule", {
    value: true
});

Qc.RelationIdLoader = void 0;

const Vc = zn;

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 s = Array.isArray(t) ? t : [ t ];
        if (!n) {
            n = await this.connection.relationLoader.load(e, t, this.queryRunner, a);
            if (!n.length) return s.map(e => ({
                entity: e,
                related: r ? [] : undefined
            }));
        }
        const i = 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 s.map(t => {
            const n = {
                entity: t,
                related: r ? [] : undefined
            };
            const a = i.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 s = c.every(n => n.compareEntityValue(t, a[Vc.DriverUtils.buildAlias(this.connection.driver, undefined, n.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + n.propertyPath.replace(".", "_"))]));
                    if (s) {
                        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 s = e.isOwning ? a.ownerColumns : a.inverseColumns;
        const i = e.isOwning ? a.inverseColumns : a.ownerColumns;
        const o = this.connection.createQueryBuilder(this.queryRunner);
        s.forEach(e => {
            const t = Vc.DriverUtils.buildAlias(this.connection.driver, undefined, e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_"));
            o.addSelect(r + "." + e.propertyPath, t);
        });
        i.forEach(t => {
            const n = Vc.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 (s.length === 1) {
            const e = t.map(e => s[0].referencedColumn.getEntityValue(e));
            const n = e.every(e => typeof e === "number");
            if (n) {
                c = `${r}.${s[0].propertyPath} IN (${e.join(", ")})`;
            } else {
                o.setParameter("values1", e);
                c = r + "." + s[0].propertyPath + " IN (:...values1)";
            }
        } else {
            c = "(" + t.map((e, t) => s.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 (i.length === 1) {
                const e = n.map(e => i[0].referencedColumn.getEntityValue(e));
                const t = e.every(e => typeof e === "number");
                if (t) {
                    l = `${r}.${i[0].propertyPath} IN (${e.join(", ")})`;
                } else {
                    o.setParameter("values2", e);
                    l = r + "." + i[0].propertyPath + " IN (:...values2)";
                }
            } else {
                l = "(" + n.map((e, t) => i.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 s = a.getEntityValue(t);
                        const i = a.referencedColumn.getEntityValue(n);
                        if (s === undefined || i === undefined) return;
                        if (s === i) {
                            const t = a.referencedColumn.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + a.referencedColumn.propertyPath.replace(".", "_");
                            r[t] = i;
                        }
                    });
                });
                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 s = this.connection.createQueryBuilder(this.queryRunner);
        e.entityMetadata.primaryColumns.forEach(e => {
            const t = Vc.DriverUtils.buildAlias(this.connection.driver, undefined, e.entityMetadata.name + "_" + e.propertyPath.replace(".", "_"));
            s.addSelect(a + "." + e.propertyPath, t);
        });
        e.joinColumns.forEach(t => {
            const n = Vc.DriverUtils.buildAlias(this.connection.driver, undefined, t.referencedColumn.entityMetadata.name + "_" + e.propertyPath.replace(".", "_") + "_" + t.referencedColumn.propertyPath.replace(".", "_"));
            s.addSelect(a + "." + t.propertyPath, n);
        });
        let i = "";
        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) {
                i = `${a}.${e.entityMetadata.primaryColumns[0].propertyPath} IN (${n.join(", ")})`;
            } else {
                s.setParameter("values", n);
                i = a + "." + e.entityMetadata.primaryColumns[0].propertyPath + " IN (:...values)";
            }
        } else {
            i = t.map((t, n) => e.entityMetadata.primaryColumns.map((e, r) => {
                const i = "entity" + n + "_" + r;
                s.setParameter(i, e.getEntityValue(t));
                return a + "." + e.propertyPath + " = :" + i;
            }).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
        }
        return s.from(e.entityMetadata.target, a).where(i).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 s = e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_");
                        const i = e.entityMetadata.name + "_" + a.propertyPath.replace(".", "_") + "_" + e.propertyPath.replace(".", "_");
                        n[s] = r;
                        n[i] = r;
                    });
                    return n;
                }));
            }
        }
        const r = e.entityMetadata.targetName;
        const s = this.connection.createQueryBuilder(this.queryRunner);
        e.entityMetadata.primaryColumns.forEach(e => {
            const t = Vc.DriverUtils.buildAlias(this.connection.driver, undefined, e.entityMetadata.name + "_" + a.propertyPath.replace(".", "_") + "_" + e.propertyPath.replace(".", "_"));
            s.addSelect(r + "." + e.propertyPath, t);
        });
        e.joinColumns.forEach(e => {
            const t = Vc.DriverUtils.buildAlias(this.connection.driver, undefined, e.referencedColumn.entityMetadata.name + "_" + e.referencedColumn.propertyPath.replace(".", "_"));
            s.addSelect(r + "." + e.propertyPath, t);
        });
        let i = "";
        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) {
                i = `${r}.${e.joinColumns[0].propertyPath} IN (${n.join(", ")})`;
            } else {
                s.setParameter("values", n);
                i = r + "." + e.joinColumns[0].propertyPath + " IN (:...values)";
            }
        } else {
            i = t.map((t, n) => e.joinColumns.map((e, a) => {
                const i = "entity" + n + "_" + a;
                s.setParameter(i, e.referencedColumn.getEntityValue(t));
                return r + "." + e.propertyPath + " = :" + i;
            }).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
        }
        return s.from(e.entityMetadata.target, r).where(i).getRawMany();
    }
}

Qc.RelationIdLoader = RelationIdLoader;

var Kc = {};

Object.defineProperty(Kc, "__esModule", {
    value: true
});

Kc.RelationIdMetadataToAttributeTransformer = void 0;

const Wc = wi;

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 Wc.RelationIdAttribute(this.expressionMap, {
            relationName: e + "." + t.relation.propertyName,
            mapToProperty: e + "." + t.propertyName,
            alias: t.alias,
            queryBuilderFactory: t.queryBuilderFactory
        });
    }
}

Kc.RelationIdMetadataToAttributeTransformer = RelationIdMetadataToAttributeTransformer;

var Hc = {};

Object.defineProperty(Hc, "__esModule", {
    value: true
});

Hc.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 s = r.joinColumns[0].referencedColumn.propertyName;
                const i = 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 + "_" + s]).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(i, 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 s;
                let i;
                if (n.relation.isOwning) {
                    a = n.relation.joinColumns[0].referencedColumn.databaseName;
                    r = n.relation.inverseJoinColumns[0].referencedColumn.databaseName;
                    s = n.relation.junctionEntityMetadata.columns[0];
                    i = n.relation.junctionEntityMetadata.columns[1];
                } else {
                    a = n.relation.inverseRelation.inverseJoinColumns[0].referencedColumn.databaseName;
                    r = n.relation.inverseRelation.joinColumns[0].referencedColumn.databaseName;
                    s = n.relation.junctionEntityMetadata.columns[1];
                    i = 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 + "." + s.propertyName + " IN (" + o.map(e => isNaN(e) ? "'" + e + "'" : e) + ")" + " AND " + c + "." + i.propertyName + " = " + u + "." + r;
                const p = this.connection.createQueryBuilder(this.queryRunner);
                p.select(c + "." + s.propertyName, "parentId").addSelect("COUNT(" + p.escape(u) + "." + p.escape(r) + ")", "cnt").from(l, u).innerJoin(h, c, d).addGroupBy(c + "." + s.propertyName);
                if (n.queryBuilderFactory) n.queryBuilderFactory(p);
                return {
                    relationCountAttribute: n,
                    results: await p.getRawMany()
                };
            }
        });
        return Promise.all(n);
    }
}

Hc.RelationCountLoader = RelationCountLoader;

var Gc = {};

Object.defineProperty(Gc, "__esModule", {
    value: true
});

Gc.RelationCountMetadataToAttributeTransformer = void 0;

const Yc = Ii;

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 Yc.RelationCountAttribute(this.expressionMap, {
            relationName: e + "." + t.relation.propertyName,
            mapToProperty: e + "." + t.propertyName,
            alias: t.alias,
            queryBuilderFactory: t.queryBuilderFactory
        });
    }
}

Gc.RelationCountMetadataToAttributeTransformer = RelationCountMetadataToAttributeTransformer;

var zc = {};

Object.defineProperty(zc, "__esModule", {
    value: true
});

exports.FindOptionsUtils_2 = zc.FindOptionsUtils = void 0;

const Jc = exports.error;

const Xc = zn;

const Zc = exports.error;

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 Jc.FindRelationsNotFoundError(n);
        }
        return e;
    }
    static applyRelationsRecursively(e, t, n, a, r) {
        let s = [];
        if (r) {
            const e = new RegExp("^" + r.replace(".", "\\.") + "\\.");
            s = t.filter(t => t.match(e)).map(t => a.findRelationWithPropertyPath(t.replace(e, ""))).filter(e => e);
        } else {
            s = t.map(e => a.findRelationWithPropertyPath(e)).filter(e => e);
        }
        s.forEach(s => {
            const i = Xc.DriverUtils.buildAlias(e.connection.driver, {
                joiner: "__"
            }, n, s.propertyPath);
            const o = n + "." + s.propertyPath;
            if (e.expressionMap.relationLoadStrategy === "query") {
                e.concatRelationMetadata(s);
            } else {
                e.leftJoinAndSelect(o, i);
            }
            t.splice(t.indexOf(r ? r + "." + s.propertyPath : s.propertyPath), 1);
            let c;
            let l;
            if (e.expressionMap.relationLoadStrategy === "query") {
                c = s.inverseEntityMetadata;
                l = i;
            } else {
                const t = e.expressionMap.joinAttributes.find(e => e.entityOrProperty === o);
                c = t.metadata;
                l = t.alias.name;
            }
            if (!l || !c) {
                throw new Zc.EntityPropertyNotFoundError(s.propertyPath, a);
            }
            this.applyRelationsRecursively(e, t, l, c, r ? r + "." + s.propertyPath : s.propertyPath);
            if (e.expressionMap.relationLoadStrategy === "join") {
                const t = a.relations.find(e => e.propertyName === s.propertyPath);
                if (t) {
                    this.joinEagerRelations(e, i, t.inverseEntityMetadata);
                }
            }
        });
    }
    static joinEagerRelations(e, t, n) {
        n.eagerRelations.forEach(n => {
            let a = Xc.DriverUtils.buildAlias(e.connection.driver, {
                joiner: "__"
            }, t, n.propertyName);
            let r = true;
            for (const s of e.expressionMap.joinAttributes) {
                if (s.condition !== undefined || s.mapToProperty !== undefined || s.isMappingMany !== undefined || s.direction !== "LEFT" || s.entityOrProperty !== `${t}.${n.propertyPath}`) {
                    continue;
                }
                r = false;
                a = s.alias.name;
                break;
            }
            const s = Boolean(e.expressionMap.joinAttributes.find(e => e.alias.name === a));
            if (r && !s) {
                e.leftJoin(t + "." + n.propertyPath, a);
            }
            let i = true;
            for (const t of e.expressionMap.selects) {
                if (t.aliasName !== undefined || t.virtual !== undefined || t.selection !== a) {
                    continue;
                }
                i = false;
                break;
            }
            if (i) {
                e.addSelect(a);
            }
            this.joinEagerRelations(e, a, n.inverseEntityMetadata);
        });
    }
}

exports.FindOptionsUtils_2 = zc.FindOptionsUtils = FindOptionsUtils;

Object.defineProperty(Lc, "__esModule", {
    value: true
});

exports.SelectQueryBuilder_2 = Lc.SelectQueryBuilder = void 0;

const el = _c;

const tl = zt;

const nl = xt;

const al = je;

const rl = Bt;

const sl = Gn;

const il = wi;

const ol = Ii;

const cl = Uc;

const ll = Qc;

const ul = Kc;

const hl = Hc;

const dl = Gc;

const pl = k;

const ml = re;

const fl = xn;

const yl = exports.ObjectUtils;

const El = zn;

const Tl = Ie;

const gl = exports.error;

const Nl = zc;

const bl = Dc;

const Al = bt;

const Cl = exports.InstanceChecker;

const Rl = exports.FindOperator;

const Sl = Bi;

class SelectQueryBuilder extends pl.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, s) {
        this.addSelect(n);
        this.join("INNER", t, n, a, r, e, false, s);
        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, s) {
        this.addSelect(n);
        this.join("LEFT", t, n, a, r, e, false, s);
        return this;
    }
    loadRelationIdAndMap(e, t, n, a) {
        const r = new il.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 ol.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 gl.TypeORMError(`SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.`);
        if (n !== undefined && n !== "NULLS FIRST" && n !== "NULLS LAST") throw new gl.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 gl.TypeORMError(`SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.`);
        if (n !== undefined && n !== "NULLS FIRST" && n !== "NULLS LAST") throw new gl.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 gl.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 gl.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 gl.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 gl.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 rl.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 al.OptimisticLockVersionMismatchError(e.name, this.expressionMap.lockVersion, n);
            } else {
                const n = e.versionColumn.getEntityValue(t);
                if (n !== this.expressionMap.lockVersion) throw new al.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 Tl.EntityNotFoundError(this.expressionMap.mainAlias.target, this.expressionMap.parameters);
        }
        return e;
    }
    async getMany() {
        if (this.expressionMap.lockMode === "optimistic") throw new rl.OptimisticLockCanNotBeUsedError;
        const e = await this.getRawAndEntities();
        return e.entities;
    }
    async getCount() {
        if (this.expressionMap.lockMode === "optimistic") throw new rl.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 rl.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 rl.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 s = [ n.entities, r ];
            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();
        }
    }
    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 s = n.stream(e, t, r, r);
            if (a) {
                await n.commitTransaction();
            }
            return s;
        } 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, s, i, o) {
        if (r) {
            this.setParameters(r);
        }
        const c = new sl.JoinAttribute(this.connection, this.expressionMap);
        c.direction = e;
        c.mapAsEntity = o;
        c.mapToProperty = s;
        c.isMappingMany = i;
        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 gl.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 (El.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 s = e.map(e => e.selection + (e.aliasName ? " AS " + this.escape(e.aliasName) : "")).join(", ");
        return r + s + " 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 (El.DriverUtils.isMySQLFamily(a)) {
                r += `/*+ MAX_EXECUTION_TIME(${this.expressionMap.maxExecutionTime}) */ `;
            }
        }
        if (El.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 s = e.parentAlias;
            if (!s || !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 i = t.joinColumns.map(e => a + "." + e.referencedColumn.propertyPath + "=" + s + "." + t.propertyPath + "." + e.referencedColumn.propertyPath).join(" AND ");
                return " " + e.direction + " JOIN " + this.getTableName(n) + " " + this.escape(a) + this.createTableLockExpression() + " ON " + this.replacePropertyNames(i + r);
            } else if (t.isOneToMany || t.isOneToOneNotOwner) {
                const i = 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 + "=" + s + "." + e.referencedColumn.propertyPath;
                }).join(" AND ");
                if (!i) throw new gl.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(i + r);
            } else {
                const i = t.junctionEntityMetadata.tablePath;
                const o = e.junctionAlias;
                let c = "", l = "";
                if (t.isOwning) {
                    c = t.joinColumns.map(e => o + "." + e.propertyPath + "=" + s + "." + 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 + "=" + s + "." + 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(i) + " " + 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 s = this.expressionMap.aliases.find(e => e.name === a);
                if (s) {
                    const e = s.metadata.findColumnWithPropertyPath(r);
                    if (e) {
                        const t = El.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 (El.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 fl.OffsetWithoutLimitNotSupportedError;
        } else if (El.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 (!(El.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb")) {
                throw new gl.TypeORMError("Lock tables not supported in selected driver");
            }
            if (this.expressionMap.lockTables.length < 1) {
                throw new gl.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 (El.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 (El.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 ml.LockNotSupportedOnGivenDriverError;
            }

          case "pessimistic_write":
            if (El.DriverUtils.isMySQLFamily(e) || e.options.type === "aurora-mysql" || e.options.type === "oracle") {
                return " FOR UPDATE" + n;
            } else if (El.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
                return " FOR UPDATE" + t + n;
            } else if (e.options.type === "mssql") {
                return "";
            } else {
                throw new ml.LockNotSupportedOnGivenDriverError;
            }

          case "pessimistic_partial_write":
            if (El.DriverUtils.isPostgresFamily(e)) {
                return " FOR UPDATE" + t + " SKIP LOCKED";
            } else if (El.DriverUtils.isMySQLFamily(e)) {
                return " FOR UPDATE SKIP LOCKED";
            } else {
                throw new ml.LockNotSupportedOnGivenDriverError;
            }

          case "pessimistic_write_or_fail":
            if (El.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
                return " FOR UPDATE" + t + " NOWAIT";
            } else if (El.DriverUtils.isMySQLFamily(e)) {
                return " FOR UPDATE NOWAIT";
            } else {
                throw new ml.LockNotSupportedOnGivenDriverError;
            }

          case "for_no_key_update":
            if (El.DriverUtils.isPostgresFamily(e) || e.options.type === "cockroachdb") {
                return " FOR NO KEY UPDATE" + t + n;
            } else {
                throw new ml.LockNotSupportedOnGivenDriverError;
            }

          case "for_key_share":
            if (El.DriverUtils.isPostgresFamily(e)) {
                return " FOR KEY SHARE" + t + n;
            } else {
                throw new ml.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 s = [ ...a, ...r ];
        const i = [];
        const o = this.escape(e);
        s.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 (El.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 (El.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 => {
                    i.push({
                        selection: a,
                        aliasName: n.aliasName ? n.aliasName : El.DriverUtils.buildAlias(this.connection.driver, undefined, e, t.databaseName),
                        virtual: n.virtual
                    });
                });
            } else {
                i.push({
                    selection: a,
                    aliasName: El.DriverUtils.buildAlias(this.connection.driver, undefined, e, t.databaseName),
                    virtual: n
                });
            }
        });
        return i;
    }
    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" || El.DriverUtils.isPostgresFamily(this.connection.driver)) {
            return "COUNT(DISTINCT(" + n.map(e => `${a}.${this.escape(e.databaseName)}`).join(", ") + "))";
        }
        if (El.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) ? bl.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) ? bl.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 gl.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) {
                Nl.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 gl.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 tl.PessimisticLockTransactionRequiredError;
        if (this.expressionMap.lockMode === "optimistic") {
            const e = this.expressionMap.mainAlias.metadata;
            if (!e.versionColumn && !e.updateDateColumn) throw new nl.NoVersionOrUpdateDateColumnError(e.name);
        }
        const t = new cl.RelationIdLoader(this.connection, e, this.expressionMap.relationIdAttributes);
        const n = new hl.RelationCountLoader(this.connection, e, this.expressionMap.relationCountAttributes);
        const a = new ul.RelationIdMetadataToAttributeTransformer(this.expressionMap);
        a.transform();
        const r = new dl.RelationCountMetadataToAttributeTransformer(this.expressionMap);
        r.transform();
        let s = [], i = [];
        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 i = a.primaryColumns.map(e => {
                const t = this.escape("distinctAlias");
                const a = this.escape(El.DriverUtils.buildAlias(this.connection.driver, undefined, r, e.databaseName));
                if (!n[a]) n[a] = "ASC";
                const s = El.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, e.databaseName);
                return `${t}.${a} AS ${this.escape(s)}`;
            });
            const o = this.clone();
            const c = o.expressionMap.timeTravel;
            s = await new SelectQueryBuilder(this.connection, e).select(`DISTINCT ${i.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 (s.length > 0) {
                let t = "";
                const n = {};
                if (a.hasMultiplePrimaryKeys) {
                    t = s.map((e, t) => a.primaryColumns.map(a => {
                        const s = `orm_distinct_ids_${t}_${a.databaseName}`;
                        const i = El.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, a.databaseName);
                        n[s] = e[i];
                        return `${r}.${a.propertyPath}=:${s}`;
                    }).join(" AND ")).join(" OR ");
                } else {
                    const e = El.DriverUtils.buildAlias(this.connection.driver, undefined, "ids_" + r, a.primaryColumns[0].databaseName);
                    const i = s.map(t => t[e]);
                    const o = i.every(e => typeof e === "number");
                    if (o) {
                        t = `${r}.${a.primaryColumns[0].propertyPath} IN (${i.join(", ")})`;
                    } else {
                        n["orm_distinct_ids"] = i;
                        t = r + "." + a.primaryColumns[0].propertyPath + " IN (:...orm_distinct_ids)";
                    }
                }
                s = await this.clone().mergeExpressionMap({
                    extraAppendedAndWhereCondition: t
                }).setParameters(n).loadRawResults(e);
            }
        } else {
            s = await this.loadRawResults(e);
        }
        if (s.length > 0) {
            const a = await t.load(s);
            const r = await n.load(s);
            const o = new el.RawSqlResultsToEntityTransformer(this.expressionMap, this.connection.driver, a, r, this.queryRunner);
            i = o.transform(s, this.expressionMap.mainAlias);
            if (this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata) {
                await e.broadcaster.broadcast("Load", this.expressionMap.mainAlias.metadata, i);
            }
        }
        if (this.expressionMap.relationLoadStrategy === "query") {
            const t = new ll.RelationIdLoader(this.connection, e);
            await Promise.all(this.relationMetadatas.map(async n => {
                const a = n.inverseEntityMetadata.target;
                const r = n.inverseEntityMetadata.targetName;
                const s = Array.isArray(this.findOptions.select) ? bl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.select) : this.findOptions.select;
                const o = Array.isArray(this.findOptions.relations) ? bl.OrmUtils.propertyPathsToTruthyObject(this.findOptions.relations) : this.findOptions.relations;
                const c = this.createQueryBuilder(e).select(r).from(a, r).setFindOptions({
                    select: s ? bl.OrmUtils.deepValue(s, n.propertyPath) : undefined,
                    order: this.findOptions.order ? bl.OrmUtils.deepValue(this.findOptions.order, n.propertyPath) : undefined,
                    relations: o ? bl.OrmUtils.deepValue(o, n.propertyPath) : undefined,
                    withDeleted: this.findOptions.withDeleted,
                    relationLoadStrategy: this.findOptions.relationLoadStrategy
                });
                if (i.length > 0) {
                    const e = await t.loadManyToManyRelationIdsAndGroup(n, i, undefined, c);
                    i.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: s,
            entities: i
        };
    }
    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 s = this.expressionMap.findAliasByName(a);
                const i = s.metadata.findColumnWithPropertyPath(r);
                return this.escape(e) + "." + this.escape(El.DriverUtils.buildAlias(this.connection.driver, undefined, a, i.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 s = r[0];
                const i = r.slice(1).join(".");
                const o = this.expressionMap.findAliasByName(s);
                const c = o.metadata.findColumnWithPropertyPath(i);
                a[this.escape(e) + "." + this.escape(El.DriverUtils.buildAlias(this.connection.driver, undefined, s, 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 s = undefined;
        const i = r.alwaysEnabled && this.expressionMap.cache !== false || this.expressionMap.cache === true;
        let o = false;
        if (this.connection.queryResultCache && i) {
            try {
                s = await this.connection.queryResultCache.getFromCache({
                    identifier: this.expressionMap.cacheId,
                    query: a,
                    duration: this.expressionMap.cacheDuration || r.duration || 1e3
                }, e);
                if (s && !this.connection.queryResultCache.isExpired(s)) {
                    return JSON.parse(s.result);
                }
            } catch (e) {
                if (!r.ignoreErrors) {
                    throw e;
                }
                o = true;
            }
        }
        const c = await e.query(t, n, true);
        if (!o && this.connection.queryResultCache && i) {
            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)
                }, s, e);
            } catch (e) {
                if (!r.ignoreErrors) {
                    throw e;
                }
            }
        }
        return c.records;
    }
    mergeExpressionMap(e) {
        yl.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 s = a ? a + "." + r : r;
            const i = t.findColumnWithPropertyPathStrict(s);
            const o = t.findEmbeddedWithPropertyPath(s);
            const c = t.findRelationWithPropertyPath(s);
            if (!o && !i && !c) throw new Al.EntityPropertyNotFoundError(s, t);
            if (i) {
                this.selects.push(n + "." + s);
            } else if (o) {
                this.buildSelect(e[r], t, n, s);
            }
        }
    }
    buildRelations(e, t, n, a, r) {
        if (!e) return;
        Object.keys(e).forEach(s => {
            const i = e[s];
            const o = r ? r + "." + s : s;
            const c = n.findEmbeddedWithPropertyPath(o);
            const l = n.findRelationWithPropertyPath(o);
            if (!c && !l) throw new Al.EntityPropertyNotFoundError(o, n);
            if (c) {
                this.buildRelations(i, typeof t === "object" ? bl.OrmUtils.deepValue(t, c.propertyPath) : undefined, n, a, o);
            } else if (l) {
                let e = a + "_" + o.replace(".", "_");
                e = El.DriverUtils.buildAlias(this.connection.driver, {
                    joiner: "__"
                }, a, e);
                if (i === true || typeof i === "object") {
                    if (this.expressionMap.relationLoadStrategy === "query") {
                        this.concatRelationMetadata(l);
                    } else {
                        this.joins.push({
                            type: "left",
                            select: true,
                            selection: t && typeof t[s] === "object" ? t[s] : undefined,
                            alias: e,
                            parentAlias: a,
                            relationMetadata: l
                        });
                        if (t && typeof t[s] === "object") {
                            this.buildSelect(t[s], l.inverseEntityMetadata, e);
                        }
                    }
                }
                if (typeof i === "object" && this.expressionMap.relationLoadStrategy === "join") {
                    this.buildRelations(i, typeof t === "object" ? bl.OrmUtils.deepValue(t, l.propertyPath) : undefined, l.inverseEntityMetadata, e, undefined);
                }
            }
        });
    }
    buildEagerRelations(e, t, n, a, r) {
        if (!e) return;
        Object.keys(e).forEach(s => {
            const i = e[s];
            const o = r ? r + "." + s : s;
            const c = n.findEmbeddedWithPropertyPath(o);
            const l = n.findRelationWithPropertyPath(o);
            if (!c && !l) throw new Al.EntityPropertyNotFoundError(o, n);
            if (c) {
                this.buildEagerRelations(i, typeof t === "object" ? bl.OrmUtils.deepValue(t, c.propertyPath) : undefined, n, a, o);
            } else if (l) {
                let e = a + "_" + o.replace(".", "_");
                e = El.DriverUtils.buildAlias(this.connection.driver, {
                    joiner: "__"
                }, a, e);
                if (i === true || typeof i === "object") {
                    l.inverseEntityMetadata.eagerRelations.forEach(n => {
                        let a = e + "_" + n.propertyPath.replace(".", "_");
                        a = El.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[s] === "object") {
                            this.buildSelect(t[s], l.inverseEntityMetadata, e);
                        }
                    });
                }
                if (typeof i === "object") {
                    this.buildEagerRelations(i, typeof t === "object" ? bl.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 s = a ? a + "." + r : r;
            const i = t.findColumnWithPropertyPathStrict(s);
            const o = t.findEmbeddedWithPropertyPath(s);
            const c = t.findRelationWithPropertyPath(s);
            if (!o && !i && !c) throw new Al.EntityPropertyNotFoundError(s, t);
            if (i) {
                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 i = `${n}.${s}`;
                this.addOrderBy(i, t, a);
            } else if (o) {
                this.buildOrder(e[r], t, n, s);
            } else if (c) {
                let t = n + "_" + s.replace(".", "_");
                t = El.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 s = [];
            for (const r in e) {
                if (e[r] === undefined || e[r] === null) continue;
                const i = a ? a + "." + r : r;
                const o = t.findColumnWithPropertyPathStrict(i);
                const c = t.findEmbeddedWithPropertyPath(i);
                const l = t.findRelationWithPropertyPath(i);
                if (!c && !o && !l) throw new Al.EntityPropertyNotFoundError(i, t);
                if (o) {
                    let t = `${n}.${i}`;
                    if (o.isVirtualProperty && o.query) {
                        t = `(${o.query(this.escape(n))})`;
                    }
                    let a = e[r];
                    if (Cl.InstanceChecker.isEqualOperator(e[r])) {
                        a = e[r].value;
                    }
                    if (o.transformer) {
                        if (a instanceof Rl.FindOperator) {
                            a.transformValue(o.transformer);
                        } else {
                            a = Sl.ApplyValueTransformers.transformTo(o.transformer, a);
                        }
                    }
                    if (this.connection.driver.options.type === "mssql") {
                        a = this.connection.driver.parametrizeValues(o, a);
                    }
                    s.push(this.createWhereConditionExpression(this.getWherePredicateCondition(t, a)));
                } else if (c) {
                    const a = this.buildWhere(e[r], t, n, i);
                    if (a) s.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 (Cl.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}.${i}`;
                                s.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 = El.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 i = this.buildWhere(e[r], l.inverseEntityMetadata, t);
                        if (i) {
                            s.push(i);
                        }
                    }
                }
            }
            r = s.length ? "(" + s.join(") AND (") + ")" : s.join(" AND ");
        }
        return r.length ? "(" + r + ")" : r;
    }
}

exports.SelectQueryBuilder_2 = Lc.SelectQueryBuilder = SelectQueryBuilder;

var wl = {};

var Ol = {};

Object.defineProperty(Ol, "__esModule", {
    value: true
});

exports.UpdateResult_2 = Ol.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;
    }
}

exports.UpdateResult_2 = Ol.UpdateResult = UpdateResult;

Object.defineProperty(wl, "__esModule", {
    value: true
});

wl.SoftDeleteQueryBuilder = void 0;

const Ml = k;

const vl = Ol;

const Il = ut;

const Pl = cc;

const Ll = ke;

const _l = at();

const Dl = Ee;

const xl = exports.error;

const $l = zn;

const ql = exports.InstanceChecker;

class SoftDeleteQueryBuilder extends Ml.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 Pl.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 s = await e.query(a, r, true);
            const i = vl.UpdateResult.from(s);
            if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata && this.expressionMap.whereEntities.length > 0) {
                await n.update(i, 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 i;
        } 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 Il.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.expressionMap.mainAlias.hasMetadata ? this.expressionMap.mainAlias.metadata : undefined;
        if (!e) throw new xl.TypeORMError(`Cannot get entity metadata for the given alias "${this.expressionMap.mainAlias}"`);
        if (!e.deleteDateColumn) {
            throw new _l.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 xl.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 Dl.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 ($l.DriverUtils.isMySQLFamily(this.connection.driver)) {
                return " LIMIT " + e;
            } else {
                throw new Ll.LimitOnUpdateNotSupportedError;
            }
        }
        return "";
    }
}

wl.SoftDeleteQueryBuilder = SoftDeleteQueryBuilder;

var Ul = {};

Object.defineProperty(Ul, "__esModule", {
    value: true
});

exports.UpdateQueryBuilder_2 = Ul.UpdateQueryBuilder = void 0;

const Bl = k;

const jl = Ol;

const Fl = ut;

const kl = cc;

const Ql = ke;

const Vl = Ee;

const Kl = exports.error;

const Wl = bt;

const Hl = zn;

class UpdateQueryBuilder extends Bl.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 kl.ReturningResultsEntityUpdator(e, 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 && this.expressionMap.whereEntities.length > 0) {
                this.expressionMap.extraReturningColumns = r.getUpdationReturningColumns();
                s.push(...this.expressionMap.extraReturningColumns.filter(e => !s.includes(e)));
            }
            if (s.length > 0 && this.connection.driver.options.type === "mssql") {
                n = this.connection.driver.buildTableVariableDeclaration("@OutputTable", s);
                a = `SELECT * FROM @OutputTable`;
            }
            const [i, o] = this.getQueryAndParameters();
            const c = [ n, i, a ];
            const l = await e.query(c.filter(e => e != null).join(";\n\n"), o, true);
            const u = jl.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 Fl.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 Kl.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 Kl.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 s = t.findColumnsWithPropertyPath(e);
                if (s.length <= 0) {
                    throw new Wl.EntityPropertyNotFoundError(e, t);
                }
                s.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 ((Hl.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 (Hl.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 Vl.UpdateValuesMissingError;
        }
        const s = this.createWhereExpression();
        const i = this.createReturningExpression("update");
        if (i === "") {
            return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${s}`;
        }
        if (this.connection.driver.options.type === "mssql") {
            return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")} OUTPUT ${i}${s}`;
        }
        if (this.connection.driver.options.type === "spanner") {
            return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${s} THEN RETURN ${i}`;
        }
        return `UPDATE ${this.getTableName(this.getMainTableName())} SET ${a.join(", ")}${s} RETURNING ${i}`;
    }
    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 (Hl.DriverUtils.isMySQLFamily(this.connection.driver) || this.connection.driver.options.type === "aurora-mysql") {
                return " LIMIT " + e;
            } else {
                throw new Ql.LimitOnUpdateNotSupportedError;
            }
        }
        return "";
    }
    getValueSet() {
        if (typeof this.expressionMap.valuesSet === "object") return this.expressionMap.valuesSet;
        throw new Vl.UpdateValuesMissingError;
    }
}

exports.UpdateQueryBuilder_2 = Ul.UpdateQueryBuilder = UpdateQueryBuilder;

Object.defineProperty(j, "__esModule", {
    value: true
});

j.registerQueryBuilders = tu;

const Gl = F;

const Yl = oo;

const zl = k;

const Jl = bc;

const Xl = Lc;

const Zl = wl;

const eu = Ul;

function tu() {
    zl.QueryBuilder.registerQueryBuilderClass("DeleteQueryBuilder", e => new Gl.DeleteQueryBuilder(e));
    zl.QueryBuilder.registerQueryBuilderClass("InsertQueryBuilder", e => new Yl.InsertQueryBuilder(e));
    zl.QueryBuilder.registerQueryBuilderClass("RelationQueryBuilder", e => new Jl.RelationQueryBuilder(e));
    zl.QueryBuilder.registerQueryBuilderClass("SelectQueryBuilder", e => new Xl.SelectQueryBuilder(e));
    zl.QueryBuilder.registerQueryBuilderClass("SoftDeleteQueryBuilder", e => new Zl.SoftDeleteQueryBuilder(e));
    zl.QueryBuilder.registerQueryBuilderClass("UpdateQueryBuilder", e => new eu.UpdateQueryBuilder(e));
}

exports.DefaultNamingStrategy = {};

exports.RandomGenerator = {};

Object.defineProperty(exports.RandomGenerator, "__esModule", {
    value: true
});

exports.RandomGenerator.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, s;
        const i = 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) {
            s = e.charCodeAt(r) << 24 | e.charCodeAt(r + 1) << 16 | e.charCodeAt(r + 2) << 8 | e.charCodeAt(r + 3);
            g.push(s);
        }
        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++) {
                i[r] = g[a + r];
            }
            for (r = 16; r <= 79; r++) {
                i[r] = t(i[r - 3] ^ i[r - 8] ^ i[r - 14] ^ i[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 + i[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 + i[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 + i[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 + i[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();
    }
}

exports.RandomGenerator.RandomGenerator = RandomGenerator;

Object.defineProperty(exports.DefaultNamingStrategy, "__esModule", {
    value: true
});

exports.DefaultNamingStrategy_2 = exports.DefaultNamingStrategy.DefaultNamingStrategy = void 0;

const nu = exports.RandomGenerator;

const au = Jn;

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, au.snakeCase)(e);
    }
    closureJunctionTableName(e) {
        return e + "_closure";
    }
    columnName(e, t, n) {
        const a = t || e;
        if (n.length) return (0, au.camelCase)(n.join("_")) + (0, au.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 s = `${r}_${n.join("_")}`;
        return "PK_" + nu.RandomGenerator.sha1(s).substr(0, 27);
    }
    uniqueConstraintName(e, t) {
        const n = [ ...t ];
        n.sort();
        const a = this.getTableName(e);
        const r = a.replace(".", "_");
        const s = `${r}_${n.join("_")}`;
        return "UQ_" + nu.RandomGenerator.sha1(s).substr(0, 27);
    }
    relationConstraintName(e, t, n) {
        const a = [ ...t ];
        a.sort();
        const r = this.getTableName(e);
        const s = r.replace(".", "_");
        let i = `${s}_${a.join("_")}`;
        if (n) i += `_${n}`;
        return "REL_" + nu.RandomGenerator.sha1(i).substr(0, 26);
    }
    defaultConstraintName(e, t) {
        const n = this.getTableName(e);
        const a = n.replace(".", "_");
        const r = `${a}_${t}`;
        return "DF_" + nu.RandomGenerator.sha1(r).substr(0, 27);
    }
    foreignKeyName(e, t, n, a) {
        const r = [ ...t ];
        r.sort();
        const s = this.getTableName(e);
        const i = s.replace(".", "_");
        const o = `${i}_${r.join("_")}`;
        return "FK_" + nu.RandomGenerator.sha1(o).substr(0, 27);
    }
    indexName(e, t, n) {
        const a = [ ...t ];
        a.sort();
        const r = this.getTableName(e);
        const s = r.replace(".", "_");
        let i = `${s}_${a.join("_")}`;
        if (n) i += `_${n}`;
        return "IDX_" + nu.RandomGenerator.sha1(i).substr(0, 26);
    }
    checkConstraintName(e, t, n) {
        const a = this.getTableName(e);
        const r = a.replace(".", "_");
        const s = `${r}_${t}`;
        const i = "CHK_" + nu.RandomGenerator.sha1(s).substr(0, 26);
        return n ? `${i}_ENUM` : i;
    }
    exclusionConstraintName(e, t) {
        const n = this.getTableName(e);
        const a = n.replace(".", "_");
        const r = `${a}_${t}`;
        return "XCL_" + nu.RandomGenerator.sha1(r).substr(0, 26);
    }
    joinColumnName(e, t) {
        return (0, au.camelCase)(e + "_" + t);
    }
    joinTableName(e, t, n, a) {
        return (0, au.snakeCase)(e + "_" + n.replace(/\./gi, "_") + "_" + t);
    }
    joinTableColumnDuplicationPrefix(e, t) {
        return e + "_" + t;
    }
    joinTableColumnName(e, t, n) {
        return (0, au.camelCase)(e + "_" + (n ? n : t));
    }
    joinTableInverseColumnName(e, t, n) {
        return this.joinTableColumnName(e, t, n);
    }
    prefixTableName(e, t) {
        return e + t;
    }
}

exports.DefaultNamingStrategy_2 = exports.DefaultNamingStrategy.DefaultNamingStrategy = DefaultNamingStrategy;

var ru = {};

var su = {};

var iu = {};

Object.defineProperty(iu, "__esModule", {
    value: true
});

exports.TableColumn_2 = iu.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
        });
    }
}

exports.TableColumn_2 = iu.TableColumn = TableColumn;

var ou = {};

Object.defineProperty(ou, "__esModule", {
    value: true
});

exports.TableIndex_2 = ou.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
        });
    }
}

exports.TableIndex_2 = ou.TableIndex = TableIndex;

var cu = {};

Object.defineProperty(cu, "__esModule", {
    value: true
});

exports.TableForeignKey_2 = cu.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
        });
    }
}

exports.TableForeignKey_2 = cu.TableForeignKey = TableForeignKey;

var lu = {};

Object.defineProperty(lu, "__esModule", {
    value: true
});

lu.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
        };
    }
}

lu.TableUtils = TableUtils;

var uu = {};

Object.defineProperty(uu, "__esModule", {
    value: true
});

exports.TableUnique_2 = uu.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
        });
    }
}

exports.TableUnique_2 = uu.TableUnique = TableUnique;

var hu = {};

Object.defineProperty(hu, "__esModule", {
    value: true
});

exports.TableCheck_2 = hu.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
        });
    }
}

exports.TableCheck_2 = hu.TableCheck = TableCheck;

var du = {};

Object.defineProperty(du, "__esModule", {
    value: true
});

exports.TableExclusion_2 = du.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
        });
    }
}

exports.TableExclusion_2 = du.TableExclusion = TableExclusion;

Object.defineProperty(su, "__esModule", {
    value: true
});

exports.Table_2 = su.Table = void 0;

const pu = iu;

const mu = ou;

const fu = cu;

const yu = lu;

const Eu = uu;

const Tu = hu;

const gu = du;

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 pu.TableColumn(e));
            if (e.indices) this.indices = e.indices.map(e => new mu.TableIndex(e));
            if (e.foreignKeys) this.foreignKeys = e.foreignKeys.map(t => new fu.TableForeignKey({
                ...t,
                referencedDatabase: t?.referencedDatabase || e.database,
                referencedSchema: t?.referencedSchema || e.schema
            }));
            if (e.uniques) this.uniques = e.uniques.map(e => new Eu.TableUnique(e));
            if (e.checks) this.checks = e.checks.map(e => new Tu.TableCheck(e));
            if (e.exclusions) this.exclusions = e.exclusions.map(e => new gu.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 => yu.TableUtils.createTableColumnOptions(e, t)),
            indices: e.indices.filter(e => e.synchronize === true).map(e => mu.TableIndex.create(e)),
            uniques: e.uniques.map(e => Eu.TableUnique.create(e)),
            checks: e.checks.map(e => Tu.TableCheck.create(e)),
            exclusions: e.exclusions.map(e => gu.TableExclusion.create(e)),
            comment: e.comment
        };
        return new Table(r);
    }
}

exports.Table_2 = su.Table = Table;

var Nu = {};

Object.defineProperty(Nu, "__esModule", {
    value: true
});

exports.Migration_2 = Nu.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;
    }
}

exports.Migration_2 = Nu.Migration = Migration;

var bu = {};

Object.defineProperty(bu, "__esModule", {
    value: true
});

exports.MssqlParameter_2 = 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 || [];
    }
}

exports.MssqlParameter_2 = bu.MssqlParameter = MssqlParameter;

Object.defineProperty(ru, "__esModule", {
    value: true
});

exports.MigrationExecutor_2 = ru.MigrationExecutor = void 0;

const Au = su;

const Cu = Nu;

const Ru = bu;

const Su = exports.error;

const wu = exports.InstanceChecker;

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 s = [];
        const i = r.filter(e => {
            const t = n.find(t => t.name === e.name);
            if (t) return false;
            return true;
        });
        if (!i.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(`${i.length} migrations are new migrations must be executed.`);
        if (this.transaction === "all") {
            const e = i.filter(e => !(e.instance?.transaction === undefined));
            if (e.length > 0) {
                const t = new Su.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 i) {
            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 i) {
                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(() => {
                    s.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 s;
    }
    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 s = r.find(e => e.name === a.name);
        if (!s) throw new Su.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 i = false;
        if (this.transaction !== "none" && !e.isTransactionActive) {
            await e.startTransaction();
            i = true;
        }
        try {
            if (!this.fake) {
                await e.beforeMigration();
                await s.instance.down(e);
                await e.afterMigration();
            }
            await this.deleteExecutedMigration(e, s);
            this.connection.logger.logSchemaBuild(`Migration ${s.name} has been ${this.fake ? "(fake) " : ""}reverted successfully.`);
            if (i) await e.commitTransaction();
        } catch (t) {
            if (i) {
                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 Au.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 Cu.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 Su.TypeORMError(`${t} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`);
            }
            return new Cu.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 Ru.MssqlParameter(t.timestamp, this.connection.driver.normalizeType({
                type: this.connection.driver.mappedDataTypes.migrationTimestamp
            }));
            n["name"] = new Ru.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 Ru.MssqlParameter(t.timestamp, this.connection.driver.normalizeType({
                type: this.connection.driver.mappedDataTypes.migrationTimestamp
            }));
            n["name"] = new Ru.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();
            }
        }
    }
}

exports.MigrationExecutor_2 = ru.MigrationExecutor = MigrationExecutor;

var Ou = {};

var Mu = {};

Object.defineProperty(Mu, "__esModule", {
    value: true
});

Mu.DepGraph = void 0;

const vu = exports.error;

function Iu(e, t, n) {
    const a = [];
    const r = {};
    return function s(i) {
        r[i] = true;
        a.push(i);
        e[i].forEach(function(e) {
            if (!r[e]) {
                s(e);
            } else if (a.indexOf(e) >= 0) {
                a.push(e);
                throw new vu.TypeORMError(`Dependency Cycle Found: ${a.join(" -> ")}`);
            }
        });
        a.pop();
        if ((!t || e[i].length === 0) && n.indexOf(i) === -1) {
            n.push(i);
        }
    };
}

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 vu.TypeORMError(`Node does not exist: ${e}`);
        }
    }
    setNodeData(e, t) {
        if (this.hasNode(e)) {
            this.nodes[e] = t;
        } else {
            throw new vu.TypeORMError(`Node does not exist: ${e}`);
        }
    }
    addDependency(e, t) {
        if (!this.hasNode(e)) {
            throw new vu.TypeORMError(`Node does not exist: ${e}`);
        }
        if (!this.hasNode(t)) {
            throw new vu.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 = Iu(this.outgoingEdges, t, n);
            a(e);
            const r = n.indexOf(e);
            if (r >= 0) {
                n.splice(r, 1);
            }
            return n;
        } else {
            throw new vu.TypeORMError(`Node does not exist: ${e}`);
        }
    }
    dependantsOf(e, t) {
        if (this.hasNode(e)) {
            const n = [];
            const a = Iu(this.incomingEdges, t, n);
            a(e);
            const r = n.indexOf(e);
            if (r >= 0) {
                n.splice(r, 1);
            }
            return n;
        } else {
            throw new vu.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 = Iu(this.outgoingEdges, false, []);
            a.forEach(function(e) {
                r(e);
            });
            const s = Iu(this.outgoingEdges, e, n);
            a.filter(function(e) {
                return t.incomingEdges[e].length === 0;
            }).forEach(function(e) {
                s(e);
            });
            return n;
        }
    }
}

Mu.DepGraph = DepGraph;

Object.defineProperty(Ou, "__esModule", {
    value: true
});

Ou.EntityMetadataValidator = void 0;

const Pu = Nt();

const Lu = lt();

const _u = Mu;

const Du = an();

const xu = kn();

const $u = on();

const qu = exports.error;

const Uu = zn;

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 Pu.MissingPrimaryColumnError(e);
        if (e.primaryColumns.length > 1) {
            const t = e.primaryColumns.every((e, t, n) => e.primaryKeyConstraintName === n[0].primaryKeyConstraintName);
            if (!t) {
                throw new qu.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 qu.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 qu.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 qu.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 qu.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 Du.DataTypeNotSupportedError(t, a, n.options.type);
                if (t.length && n.withLengthColumnTypes.indexOf(a) === -1) throw new qu.TypeORMError(`Column ${t.propertyName} of Entity ${e.name} does not support length property.`);
                if (t.type === "enum" && !t.enum && !t.enumName) throw new qu.TypeORMError(`Column "${t.propertyName}" of Entity "${e.name}" is defined as enum, but missing "enum" or "enumName" properties.`);
            });
        }
        if (Uu.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 qu.TypeORMError(`Error in ${e.name} entity. There can be only one auto-increment column in MySql table.`);
        }
        if (Uu.DriverUtils.isMySQLFamily(n)) {
            const e = t.filter(e => e.database);
            if (e.length === 0 && !n.database) throw new xu.NoConnectionOptionError("database");
        }
        if (n.options.type === "mssql") {
            const t = e.columns.filter(e => e.charset);
            if (t.length > 1) throw new qu.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 qu.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 $u.InitializedRelationError(e);
            }
        });
        e.relations.forEach(e => {
            if (n.supportedOnDeleteTypes && e.onDelete && !n.supportedOnDeleteTypes.includes(e.onDelete)) {
                throw new qu.TypeORMError(`OnDeleteType "${e.onDelete}" is not supported for ${n.options.type}!`);
            }
            if (n.supportedOnUpdateTypes && e.onUpdate && !n.supportedOnUpdateTypes.includes(e.onUpdate)) {
                throw new qu.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 qu.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 _u.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 Lu.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 qu.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.`);
            });
        });
    }
}

Ou.EntityMetadataValidator = EntityMetadataValidator;

var Bu = {};

var ju = {};

var Fu = {};

var ku = {};

var Qu = {};

var Vu = {
    exports: {}
};

Vu.exports;

var Ku;

function Wu() {
    if (Ku) return Vu.exports;
    Ku = 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: s = false, escapeSpecialCharacters: i = Array.isArray(t), trimWhitespace: o = true} = e;
                let c = "";
                for (let e = 0; e < a.length; e++) {
                    let t = a[e];
                    if (i) {
                        t = t.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
                    }
                    c += t;
                    if (e < n.length) {
                        const t = s ? 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 (i) {
                    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;
    })(Vu, Vu.exports);
    return Vu.exports;
}

Object.defineProperty(Qu, "__esModule", {
    value: true
});

Qu.buildSqlTag = Yu;

const Hu = e.require$$0;

const Gu = Hu.__importDefault(Wu());

function Yu({driver: e, strings: t, expressions: n}) {
    let a = "";
    const r = [];
    let s = 0;
    for (const [i, o] of n.entries()) {
        a += t[i];
        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 ${i} 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_${s + 1}`, s++));
                a += n.join(", ");
                r.push(...t);
                continue;
            }
            throw new Error(`Expression ${i} 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_${s + 1}`, s++);
        r.push(o);
    }
    a += t[t.length - 1];
    a = (0, Gu.default)(a);
    return {
        query: a,
        parameters: r
    };
}

Object.defineProperty(ku, "__esModule", {
    value: true
});

exports.Repository_2 = ku.Repository = void 0;

const zu = Qu;

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, zu.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 s = class extends t {
            constructor(e, t, n) {
                super(e, t, n);
            }
        };
        for (const t in e) s.prototype[t] = e[t];
        return new s(n, a, r);
    }
}

exports.Repository_2 = ku.Repository = Repository;

Object.defineProperty(Fu, "__esModule", {
    value: true
});

exports.MongoRepository_2 = Fu.MongoRepository = void 0;

const Ju = ku;

const Xu = W;

class MongoRepository extends Ju.Repository {
    query(e, t) {
        throw new Xu.TypeORMError(`Queries aren't supported by MongoDB.`);
    }
    createQueryBuilder(e, t) {
        throw new Xu.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);
    }
}

exports.MongoRepository_2 = Fu.MongoRepository = MongoRepository;

var Zu = {};

var eh = {};

Object.defineProperty(eh, "__esModule", {
    value: true
});

exports.TreeRepositoryUtils_2 = eh.TreeRepositoryUtils = void 0;

class TreeRepositoryUtils {
    static createRelationMaps(e, t, n, a) {
        return a.map(a => {
            const r = t.treeParentRelation.joinColumns[0];
            const s = r.referencedColumn ?? t.primaryColumns[0];
            const i = r.givenDatabaseName || r.databaseName;
            const o = s.givenDatabaseName || s.databaseName;
            const c = a[n + "_" + o];
            const l = a[n + "_" + i];
            return {
                id: e.connection.driver.prepareHydratedValue(c, s),
                parentId: e.connection.driver.prepareHydratedValue(l, r)
            };
        });
    }
    static buildChildrenEntityTree(e, t, n, a, r) {
        const s = e.treeChildrenRelation.propertyName;
        if (r.depth === 0) {
            t[s] = [];
            return;
        }
        const i = e.treeParentRelation.joinColumns[0];
        const o = i.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[s] = n.filter(e => u.has(o.getEntityValue(e)));
        t[s].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 s = e.treeParentRelation.joinColumns[0];
        const i = s.referencedColumn ?? e.primaryColumns[0];
        const o = i.getEntityValue(t);
        const c = a.find(e => e.id === o);
        const l = n.find(e => {
            if (!c) return false;
            return i.getEntityValue(e) === c.parentId;
        });
        if (l) {
            t[r] = l;
            TreeRepositoryUtils.buildParentEntityTree(e, t[r], n, a);
        }
    }
}

exports.TreeRepositoryUtils_2 = eh.TreeRepositoryUtils = TreeRepositoryUtils;

Object.defineProperty(Zu, "__esModule", {
    value: true
});

exports.TreeRepository_2 = Zu.TreeRepository = void 0;

const th = zn;

const nh = W;

const ah = zc;

const rh = eh;

const sh = ku;

class TreeRepository extends sh.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 s = this.createQueryBuilder("treeEntity");
        ah.FindOptionsUtils.applyOptionsToTreeQueryBuilder(s, e);
        return s.where(`${t("treeEntity")}.${n(r)} IS NULL`).getMany();
    }
    findDescendants(e, t) {
        const n = this.createDescendantsQueryBuilder("treeEntity", "treeClosure", e);
        ah.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
        return n.getMany();
    }
    async findDescendantsTree(e, t) {
        const n = this.createDescendantsQueryBuilder("treeEntity", "treeClosure", e);
        ah.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
        const a = await n.getRawAndEntities();
        const r = rh.TreeRepositoryUtils.createRelationMaps(this.manager, this.metadata, "treeEntity", a.raw);
        rh.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 s = {};
            const i = this.metadata.closureJunctionTable.ancestorColumns.map(e => {
                s[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(i).setParameters(s);
        } 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 (th.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 nh.TypeORMError(`Supported only in tree entities`);
    }
    findAncestors(e, t) {
        const n = this.createAncestorsQueryBuilder("treeEntity", "treeClosure", e);
        ah.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
        return n.getMany();
    }
    async findAncestorsTree(e, t) {
        const n = this.createAncestorsQueryBuilder("treeEntity", "treeClosure", e);
        ah.FindOptionsUtils.applyOptionsToTreeQueryBuilder(n, t);
        const a = await n.getRawAndEntities();
        const r = rh.TreeRepositoryUtils.createRelationMaps(this.manager, this.metadata, "treeEntity", a.raw);
        rh.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 s = 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(s).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 (th.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 nh.TypeORMError(`Supported only in tree entities`);
    }
}

exports.TreeRepository_2 = Zu.TreeRepository = TreeRepository;

var ih = {};

Object.defineProperty(ih, "__esModule", {
    value: true
});

ih.PlainObjectToNewEntityTransformer = void 0;

const oh = exports.ObjectUtils;

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 s = n.getEntityValue(t, a);
                if (s === undefined) return;
                if (n.isOneToMany || n.isManyToMany) {
                    if (!Array.isArray(s)) return;
                    if (!r) {
                        r = [];
                        n.setEntityValue(e, r);
                    }
                    s.forEach(e => {
                        let t = r.find(t => n.inverseEntityMetadata.compareEntities(e, t));
                        const s = n.inverseEntityMetadata.findInheritanceMetadata(e);
                        if (!t) {
                            t = s.create(undefined, {
                                fromDeserializer: true
                            });
                            r.push(t);
                        }
                        this.groupAndTransform(t, e, s, a);
                    });
                } else {
                    if (!oh.ObjectUtils.isObject(s)) {
                        if (!oh.ObjectUtils.isObject(r)) n.setEntityValue(e, s);
                        return;
                    }
                    const t = n.inverseEntityMetadata.findInheritanceMetadata(s);
                    if (!r) {
                        r = t.create(undefined, {
                            fromDeserializer: true
                        });
                        n.setEntityValue(e, r);
                    }
                    this.groupAndTransform(r, s, t, a);
                }
            });
        }
    }
}

ih.PlainObjectToNewEntityTransformer = PlainObjectToNewEntityTransformer;

var ch = {};

Object.defineProperty(ch, "__esModule", {
    value: true
});

ch.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, s, i) => {
            const o = new LoadMapItem(e, r, s, i);
            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;
    }
}

ch.PlainObjectToDatabaseEntityTransformer = PlainObjectToDatabaseEntityTransformer;

var lh = {};

var uh = {};

var hh = {};

var dh = {};

Object.defineProperty(dh, "__esModule", {
    value: true
});

dh.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);
    }
}

dh.MetadataUtils = MetadataUtils;

Object.defineProperty(hh, "__esModule", {
    value: true
});

hh.MetadataArgsStorage = void 0;

const ph = dh;

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" && ph.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;
    }
}

hh.MetadataArgsStorage = MetadataArgsStorage;

exports.PlatformTools = {};

var mh = {
    exports: {}
};

mh.exports;

var fh;

function yh() {
    if (fh) return mh.exports;
    fh = 1;
    let {defineProperty: e, setPrototypeOf: t, create: n, keys: a} = Object, r = "", {round: s, max: i} = 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 : s((e - 8) / 247 * 24) + 232 : 16 + 36 * s(e / 51) + 6 * s(t / 51) + s(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 * i(t, n, a), r ? 30 + (s(a) << 2 | s(n) << 1 | s(t)) + (2 ^ r ? 0 : 60) : 30);
    }, u = (() => {
        let e = e => i.some(t => e.test(t)), t = globalThis, n = t.Deno, r = !!n, s = t.process || n || {}, i = s.argv || s.args || [], o = s.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) : !!s.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, s = "," + a(e).join(",");
            return {
                "24bit": 3,
                truecolor: 3,
                ansi256: 2,
                ansi: 1
            }[e.COLORTERM] || (e.TF_BUILD ? 1 : /,TEAMCI/.test(s) ? 2 : e.CI ? /,GIT(HUB|EA)/.test(s) ? 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 : s.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), b = e => p(`38;5;${e}`, m), A = e => p(`48;5;${e}`, f);
    2 === u ? (g = E(b), N = E(A)) : 1 === u && (g = y(0, m), N = y(10, f), b = e => p(l(e), m), 
    A = e => p(l(e) + 10, f));
    let C, R = {
        ansi256: b,
        bgAnsi256: A,
        fg: b,
        bg: A,
        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 O, M = {}, v = ({_p: e}, {open: n, close: a}) => {
        let s = (e, ...t) => {
            if (!e) {
                if (n && n === a) return n;
                if (null == e || r === e) return r;
            }
            let i = e.raw ? String.raw(e, ...t).replace(/\\n/g, "\n") : r + e, o = s._p, {_a: c, _b: l} = o;
            if (i.includes("")) for (;o; ) {
                let e, t = o.close, n = o.open, a = t.length, s = r, c = 0;
                if (a) {
                    for (;~(e = i.indexOf(t, c)); c = e + a) s += i.slice(c, e) + n;
                    i = s + i.slice(c);
                }
                o = o._p;
            }
            return i.includes("\n") && (i = i.replace(/(\r?\n)/g, l + "$1" + c)), c + i + l;
        }, i = n, o = a;
        return e && (i = e._a + n, o = a + e._b), t(s, O), s._p = {
            open: n,
            close: a,
            _a: i,
            _b: o,
            _p: e
        }, s.open = i, s.close = o, s;
    };
    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], s = "s" === a ? g(...o(n)) : n;
                    M[t] = "f" === a ? {
                        get() {
                            return (...e) => v(this, n(...e));
                        }
                    } : {
                        get() {
                            let n = v(this, s);
                            return e(this, t, {
                                value: n
                            }), n;
                        }
                    };
                }
                return O = n({}, M), t(a, O), a;
            }
        };
        return a.extend(R);
    }, P = new I;
    mh.exports = P, P.default = P;
    return mh.exports;
}

var Eh = {
    exports: {}
};

var Th = "16.6.1";

const gh = {
    version: Th
};

Eh.exports;

var Nh;

function bh() {
    if (Nh) return Eh.exports;
    Nh = 1;
    const e = A.default;
    const t = C.default;
    const n = R.default;
    const a = S.default;
    const r = gh;
    const s = r.version;
    const i = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
    function o(e) {
        const t = {};
        let n = e.toString();
        n = n.replace(/\r\n?/gm, "\n");
        let a;
        while ((a = i.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 c(e) {
        e = e || {};
        const t = m(e);
        e.path = t;
        const n = b.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 = d(e).split(",");
        const r = a.length;
        let s;
        for (let e = 0; e < r; e++) {
            try {
                const t = a[e].trim();
                const r = p(n, t);
                s = b.decrypt(r.ciphertext, r.key);
                break;
            } catch (t) {
                if (e + 1 >= r) {
                    throw t;
                }
            }
        }
        return b.parse(s);
    }
    function l(e) {
        console.log(`[dotenv@${s}][WARN] ${e}`);
    }
    function u(e) {
        console.log(`[dotenv@${s}][DEBUG] ${e}`);
    }
    function h(e) {
        console.log(`[dotenv@${s}] ${e}`);
    }
    function d(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 p(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 s = `DOTENV_VAULT_${r.toUpperCase()}`;
        const i = e.parsed[s];
        if (!i) {
            const e = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);
            e.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
            throw e;
        }
        return {
            ciphertext: i,
            key: a
        };
    }
    function m(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 f(e) {
        return e[0] === "~" ? t.join(n.homedir(), e.slice(1)) : e;
    }
    function y(e) {
        const t = Boolean(e && e.debug);
        const n = e && "quiet" in e ? e.quiet : true;
        if (t || !n) {
            h("Loading env from encrypted .env.vault");
        }
        const a = b._parseVault(e);
        let r = process.env;
        if (e && e.processEnv != null) {
            r = e.processEnv;
        }
        b.populate(r, a, e);
        return {
            parsed: a
        };
    }
    function E(n) {
        const a = t.resolve(process.cwd(), ".env");
        let r = "utf8";
        const s = Boolean(n && n.debug);
        const i = n && "quiet" in n ? n.quiet : true;
        if (n && n.encoding) {
            r = n.encoding;
        } else {
            if (s) {
                u("No encoding is specified. UTF-8 is used by default");
            }
        }
        let o = [ a ];
        if (n && n.path) {
            if (!Array.isArray(n.path)) {
                o = [ f(n.path) ];
            } else {
                o = [];
                for (const e of n.path) {
                    o.push(f(e));
                }
            }
        }
        let c;
        const l = {};
        for (const t of o) {
            try {
                const a = b.parse(e.readFileSync(t, {
                    encoding: r
                }));
                b.populate(l, a, n);
            } catch (e) {
                if (s) {
                    u(`Failed to load ${t} ${e.message}`);
                }
                c = e;
            }
        }
        let d = process.env;
        if (n && n.processEnv != null) {
            d = n.processEnv;
        }
        b.populate(d, l, n);
        if (s || !i) {
            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 (s) {
                        u(`Failed to load ${e} ${t.message}`);
                    }
                    c = t;
                }
            }
            h(`injecting env (${e}) from ${n.join(",")}`);
        }
        if (c) {
            return {
                parsed: l,
                error: c
            };
        } else {
            return {
                parsed: l
            };
        }
    }
    function T(e) {
        if (d(e).length === 0) {
            return b.configDotenv(e);
        }
        const t = m(e);
        if (!t) {
            l(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`);
            return b.configDotenv(e);
        }
        return b._configVault(e);
    }
    function g(e, t) {
        const n = Buffer.from(t.slice(-64), "hex");
        let r = Buffer.from(e, "base64");
        const s = r.subarray(0, 12);
        const i = r.subarray(-16);
        r = r.subarray(12, -16);
        try {
            const e = a.createDecipheriv("aes-256-gcm", n, s);
            e.setAuthTag(i);
            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 N(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) {
                        u(`"${n}" is already defined and WAS overwritten`);
                    } else {
                        u(`"${n}" is already defined and was NOT overwritten`);
                    }
                }
            } else {
                e[n] = t[n];
            }
        }
    }
    const b = {
        configDotenv: E,
        _configVault: y,
        _parseVault: c,
        config: T,
        decrypt: g,
        parse: o,
        populate: N
    };
    Eh.exports.configDotenv = b.configDotenv;
    Eh.exports._configVault = b._configVault;
    Eh.exports._parseVault = b._parseVault;
    Eh.exports.config = b.config;
    Eh.exports.decrypt = b.decrypt;
    Eh.exports.parse = b.parse;
    Eh.exports.populate = b.populate;
    Eh.exports = b;
    return Eh.exports;
}

var Ah;

var Ch;

function Rh() {
    if (Ch) return Ah;
    Ch = 1;
    Ah = [ "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 Ah;
}

var Sh;

var wh;

function Oh() {
    if (wh) return Sh;
    wh = 1;
    const e = {
        34: "&quot;",
        38: "&amp;",
        39: "&#39;",
        60: "&lt;",
        62: "&gt;"
    };
    function t(t) {
        let n = "";
        let a = 0;
        for (let r = 0; r < t.length; r++) {
            const s = e[t.charCodeAt(r)];
            if (!s) continue;
            if (a !== r) {
                n += t.substring(a, r);
            }
            a = r + 1;
            n += s;
        }
        return n + t.substring(a);
    }
    Sh = t;
    return Sh;
}

var Mh;

var vh;

function Ih() {
    if (vh) return Mh;
    vh = 1;
    const e = Rh();
    const t = Oh();
    const n = {
        html: false,
        htmlEscaper: t,
        classPrefix: "sql-hl-",
        colors: {
            keyword: "",
            function: "",
            number: "",
            string: "",
            identifier: "",
            special: "",
            bracket: "",
            comment: "",
            clear: ""
        }
    };
    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 s(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 i(e, t) {
        const a = Object.assign({}, n, t);
        return s(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("");
    }
    Mh = {
        getSegments: s,
        highlight: i,
        DEFAULT_OPTIONS: n
    };
    return Mh;
}

exports.sqlFormatter = {};

var Ph = {};

var Lh = {};

var _h = {};

var Dh = {};

(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;
})(Dh);

var xh = {};

(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 = {}));
})(xh);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var a = t(Dh);
    var r = xh;
    var s = 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, a["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, a["default"])(e);
            } else {
                return "\\b" + e + "\\b";
            }
        };
        e.prototype.createPlaceholderRegex = function(e, t) {
            if (!e || e.length === 0) {
                return null;
            }
            var n = e.map(a["default"]).join("|");
            return new RegExp("^((?:".concat(n, ")(?:").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: r.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: r.TokenTypes.LINE_COMMENT,
                regex: this.LINE_COMMENT_REGEX
            });
        };
        e.prototype.getBlockCommentToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.BLOCK_COMMENT,
                regex: this.BLOCK_COMMENT_REGEX
            });
        };
        e.prototype.getStringToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.STRING,
                regex: this.STRING_REGEX
            });
        };
        e.prototype.getOpenParenToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.OPEN_PAREN,
                regex: this.OPEN_PAREN_REGEX
            });
        };
        e.prototype.getCloseParenToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.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: r.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, a = e.parseKey;
            var s = this.getTokenOnFirstMatch({
                input: t,
                regex: n,
                type: r.TokenTypes.PLACEHOLDER
            });
            if (s) {
                s.key = a(s.value);
            }
            return s;
        };
        e.prototype.getEscapedPlaceholderKey = function(e) {
            var t = e.key, n = e.quoteChar;
            return t.replace(new RegExp((0, a["default"])("\\" + n), "gu"), n);
        };
        e.prototype.getNumberToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.NUMBER,
                regex: this.NUMBER_REGEX
            });
        };
        e.prototype.getOperatorToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.OPERATOR,
                regex: this.OPERATOR_REGEX
            });
        };
        e.prototype.getAmbiguosOperatorToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.OPERATOR,
                regex: this.AMBIGUOS_OPERATOR_REGEX
            });
        };
        e.prototype.getNoSpaceOperatorToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.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: r.TokenTypes.RESERVED_TOP_LEVEL,
                regex: this.RESERVED_TOP_LEVEL_REGEX
            });
        };
        e.prototype.getNewlineReservedToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.RESERVED_NEWLINE,
                regex: this.RESERVED_NEWLINE_REGEX
            });
        };
        e.prototype.getPlainReservedToken = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.TokenTypes.RESERVED,
                regex: this.RESERVED_PLAIN_REGEX
            });
        };
        e.prototype.getTopLevelReservedTokenNoIndent = function(e) {
            return this.getTokenOnFirstMatch({
                input: e,
                type: r.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: r.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"] = s;
})(_h);

var $h = {};

var qh = {};

var Uh = {};

(function(e) {
    e.__esModule = true;
    var t = function(e) {
        if (e === void 0) {
            e = [];
        }
        return e[e.length - 1];
    };
    e["default"] = t;
})(Uh);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var a = t(Uh);
    var r = "top-level";
    var s = "block-level";
    var i = 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(r);
        };
        e.prototype.increaseBlockLevel = function() {
            this.indentTypes.push(s);
        };
        e.prototype.decreaseTopLevel = function() {
            if ((0, a["default"])(this.indentTypes) === r) {
                this.indentTypes.pop();
            }
        };
        e.prototype.decreaseBlockLevel = function() {
            while (this.indentTypes.length > 0) {
                var e = this.indentTypes.pop();
                if (e !== r) {
                    break;
                }
            }
        };
        e.prototype.resetIndentation = function() {
            this.indentTypes = [];
        };
        return e;
    }();
    e["default"] = i;
})(qh);

var Bh = {};

(function(e) {
    e.__esModule = true;
    var t = xh;
    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 s = 0;
            for (var i = a; i < e.length; i++) {
                var o = e[i];
                r += o.value.length;
                if (r > n) {
                    return false;
                }
                if (o.type === t.TokenTypes.OPEN_PAREN) {
                    s++;
                } else if (o.type === t.TokenTypes.CLOSE_PAREN) {
                    s--;
                    if (s === 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;
})(Bh);

var jh = {};

(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;
})(jh);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var a = xh;
    var r = t(qh);
    var s = t(Bh);
    var i = t(jh);
    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 r["default"](this.cfg.indent);
            this.inlineBlock = new s["default"];
            this.params = new i["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(n, r) {
                e.index = r;
                if (e.tokenOverride) n = e.tokenOverride(n, e.previousReservedWord) || n;
                if (n.type === a.TokenTypes.WHITESPACE) {
                    t = e.formatWhitespace(n, t);
                } else if (n.type === a.TokenTypes.LINE_COMMENT) {
                    t = e.formatLineComment(n, t);
                } else if (n.type === a.TokenTypes.BLOCK_COMMENT) {
                    t = e.formatBlockComment(n, t);
                } else if (n.type === a.TokenTypes.RESERVED_TOP_LEVEL || n.type === a.TokenTypes.RESERVED_TOP_LEVEL_NO_INDENT || n.type === a.TokenTypes.RESERVED_NEWLINE || n.type === a.TokenTypes.RESERVED) {
                    t = e.formatReserved(n, t);
                } else if (n.type === a.TokenTypes.OPEN_PAREN) {
                    t = e.formatOpeningParentheses(n, t);
                } else if (n.type === a.TokenTypes.CLOSE_PAREN) {
                    t = e.formatClosingParentheses(n, t);
                } else if (n.type === a.TokenTypes.NO_SPACE_OPERATOR) {
                    t = e.formatWithoutSpaces(n, t);
                } else if (n.type === a.TokenTypes.PLACEHOLDER || n.type === a.TokenTypes.SERVERVARIABLE) {
                    t = e.formatPlaceholder(n, t);
                } else if (n.value === ",") {
                    t = e.formatComma(n, t);
                } else if (n.value === ":") {
                    t = e.formatWithSpaceAfter(n, t);
                } else if (n.value === ".") {
                    t = e.formatWithoutSpaces(n, t);
                } else if (n.value === ";") {
                    t = e.formatQuerySeparator(n, t);
                } else {
                    t = e.formatWithSpaces(n, t);
                }
                if (n.type !== a.TokenTypes.WHITESPACE) {
                    e.previousNonWhiteSpace = n;
                }
            });
            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 === a.TokenTypes.RESERVED_NEWLINE && this.previousReservedWord && this.previousReservedWord.value && e.value.toUpperCase() === "AND" && this.previousReservedWord.value.toUpperCase() === "BETWEEN") {
                e.type = a.TokenTypes.RESERVED;
            }
            if (e.type === a.TokenTypes.RESERVED_TOP_LEVEL) {
                t = this.formatTopLevelReservedWord(e, t);
            } else if (e.type === a.TokenTypes.RESERVED_TOP_LEVEL_NO_INDENT) {
                t = this.formatTopLevelReservedWordNoIndent(e, t);
            } else if (e.type === a.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 n = this.previousToken().type;
            if (n !== a.TokenTypes.WHITESPACE && n !== a.TokenTypes.OPEN_PAREN && n !== a.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 n = e.type === a.TokenTypes.RESERVED ? this.formatReservedWord(e.value) : e.value;
            return t + n + " ";
        };
        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;
})($h);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var a = t(_h);
    var r = t($h);
    var s = function() {
        function e(e) {
            this.cfg = e;
        }
        e.prototype.format = function(e) {
            return new r["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 a["default"](this.getTokenizerConfig());
        };
        return e;
    }();
    e["default"] = s;
})(Lh);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var r = a(Lh);
    var s = function(e) {
        t(n, e);
        function n() {
            return e !== null && e.apply(this, arguments) || this;
        }
        n.prototype.getTokenizerConfig = function() {
            return {
                reservedWords: i,
                reservedTopLevelWords: o,
                reservedNewlineWords: l,
                reservedTopLevelWordsNoIndent: c,
                stringTypes: [ '""', "''", "``", "[]" ],
                openParens: [ "(" ],
                closeParens: [ ")" ],
                indexedPlaceholderTypes: [ "?" ],
                namedPlaceholderTypes: [ ":" ],
                lineCommentTypes: [ "--" ],
                specialWordChars: [ "#", "@" ]
            };
        };
        return n;
    }(r["default"]);
    e["default"] = s;
    var i = [ "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" ];
})(Ph);

var Fh = {};

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var r = a(Lh);
    var s = function(e) {
        t(n, e);
        function n() {
            return e !== null && e.apply(this, arguments) || this;
        }
        n.prototype.getTokenizerConfig = function() {
            return {
                reservedWords: i,
                reservedTopLevelWords: o,
                reservedNewlineWords: l,
                reservedTopLevelWordsNoIndent: c,
                stringTypes: [ '""', "''", "``" ],
                openParens: [ "(", "[", "{" ],
                closeParens: [ ")", "]", "}" ],
                namedPlaceholderTypes: [ "$" ],
                lineCommentTypes: [ "#", "--" ],
                specialWordChars: []
            };
        };
        return n;
    }(r["default"]);
    e["default"] = s;
    var i = [ "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" ];
})(Fh);

var kh = {};

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var r = a(Lh);
    var s = xh;
    var i = function(e) {
        t(n, e);
        function n() {
            var t = e !== null && e.apply(this, arguments) || this;
            t.tokenOverride = function(e, t) {
                if (e.type === s.TokenTypes.RESERVED_TOP_LEVEL && t.value && e.value.toUpperCase() === "SET" && t.value.toUpperCase() === "BY") {
                    e.type = s.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;
    }(r["default"]);
    e["default"] = i;
    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" ];
})(kh);

var Qh = {};

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    var r = a(Lh);
    var s = function(e) {
        t(n, e);
        function n() {
            return e !== null && e.apply(this, arguments) || this;
        }
        n.prototype.getTokenizerConfig = function() {
            return {
                reservedWords: i,
                reservedTopLevelWords: o,
                reservedNewlineWords: l,
                reservedTopLevelWordsNoIndent: c,
                stringTypes: [ '""', "N''", "''", "``", "[]", "E''" ],
                openParens: [ "(", "CASE" ],
                closeParens: [ ")", "END" ],
                indexedPlaceholderTypes: [ "?" ],
                namedPlaceholderTypes: [ "@", ":", "%", "$" ],
                lineCommentTypes: [ "#", "--" ],
                specialWordChars: []
            };
        };
        return n;
    }(r["default"]);
    e["default"] = s;
    var i = [ "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" ];
})(Qh);

(function(e) {
    var t = n.commonjsGlobal && n.commonjsGlobal.__importDefault || function(e) {
        return e && e.__esModule ? e : {
            default: e
        };
    };
    e.__esModule = true;
    e.tokenize = e.format = void 0;
    var a = t(Ph);
    var r = t(Fh);
    var s = t(kh);
    var i = t(Qh);
    var o = function(e, t) {
        if (t === void 0) {
            t = {};
        }
        switch (t.language) {
          case "db2":
            return new a["default"](t).format(e);

          case "n1ql":
            return new r["default"](t).format(e);

          case "pl/sql":
            return new s["default"](t).format(e);

          case "sql":
          default:
            return new i["default"](t).format(e);
        }
    };
    e.format = o;
    var c = function(e, t) {
        if (t === void 0) {
            t = {};
        }
        return new i["default"](t).tokenize(e);
    };
    e.tokenize = c;
    e["default"] = {
        format: e.format,
        tokenize: e.tokenize
    };
})(exports.sqlFormatter);

(function(t) {
    Object.defineProperty(t, "__esModule", {
        value: true
    });
    t.PlatformTools = t.Writable = t.Readable = t.ReadStream = t.EventEmitter = void 0;
    const r = e.require$$0;
    const s = r.__importDefault(yh());
    const i = r.__importDefault(bh());
    const o = r.__importDefault(A.default);
    const c = r.__importDefault(C.default);
    const l = Ih();
    const u = exports.sqlFormatter;
    var h = w.default;
    Object.defineProperty(t, "EventEmitter", {
        enumerable: true,
        get: function() {
            return h.EventEmitter;
        }
    });
    var d = A.default;
    Object.defineProperty(t, "ReadStream", {
        enumerable: true,
        get: function() {
            return d.ReadStream;
        }
    });
    var p = O.default;
    Object.defineProperty(t, "Readable", {
        enumerable: true,
        get: function() {
            return p.Readable;
        }
    });
    Object.defineProperty(t, "Writable", {
        enumerable: true,
        get: function() {
            return p.Writable;
        }
    });
    class PlatformTools {
        static getGlobalVariable() {
            return n.commonjsGlobal;
        }
        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 a.commonjsRequire(c.default.resolve(process.cwd() + "/node_modules/" + e));
            }
            throw new TypeError(`Invalid Package for PlatformTools.load: ${e}`);
        }
        static pathNormalize(e) {
            let t = c.default.normalize(e);
            if (process.platform === "win32") t = t.replace(/\\/g, "/");
            return t;
        }
        static pathExtname(e) {
            return c.default.extname(e);
        }
        static pathResolve(e) {
            return c.default.resolve(e);
        }
        static fileExist(e) {
            return o.default.existsSync(e);
        }
        static readFileSync(e) {
            return o.default.readFileSync(e);
        }
        static appendFileSync(e, t) {
            o.default.appendFileSync(e, t);
        }
        static async writeFile(e, t) {
            return o.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, l.highlight)(e, {
                colors: {
                    keyword: s.default.blueBright.open,
                    function: s.default.magentaBright.open,
                    number: s.default.green.open,
                    string: s.default.white.open,
                    identifier: s.default.white.open,
                    special: s.default.white.open,
                    bracket: s.default.white.open,
                    comment: s.default.gray.open,
                    clear: s.default.reset.open
                }
            });
        }
        static formatSql(e, t) {
            const n = {
                oracle: "pl/sql"
            };
            const a = t ? n[t] || "sql" : "sql";
            return (0, u.format)(e, {
                language: a,
                indent: "    "
            });
        }
        static logInfo(e, t) {
            console.log(s.default.gray.underline(e), t);
        }
        static logError(e, t) {
            console.log(s.default.underline.red(e), t);
        }
        static logWarn(e, t) {
            console.log(s.default.underline.yellow(e), t);
        }
        static log(e) {
            console.log(s.default.underline(e));
        }
        static info(e) {
            return s.default.gray(e);
        }
        static error(e) {
            return s.default.red(e);
        }
        static warn(e) {
            return s.default.yellow(e);
        }
        static logCmdErr(e, t) {
            console.log(s.default.black.bgRed(e));
            if (t) console.error(t);
        }
    }
    t.PlatformTools = PlatformTools;
    PlatformTools.type = "node";
})(exports.PlatformTools);

var Vh = {};

var Kh;

var Wh;

function Hh() {
    if (Wh) return Kh;
    Wh = 1;
    var e = C.default;
    var t = M.default.globalPaths;
    var n;
    if ("win32" === process.platform) {
        n = e.dirname(process.execPath);
    } else {
        n = e.dirname(e.dirname(process.execPath));
    }
    var r = e.resolve(n, "lib", "node_modules");
    var s = e.sep;
    var i = "function" === typeof __webpack_require__ || "function" === typeof __non_webpack_require__ ? __non_webpack_require__ : a.commonjsRequire;
    const o = function(e) {
        const n = s + ".pnpm";
        for (const a of t) {
            if (-1 !== a.indexOf(n) && -1 !== e.indexOf(n)) {
                return true;
            }
        }
        return false;
    };
    const c = function(e) {
        const t = s + "node_modules";
        if (-1 !== e.indexOf(t)) {
            const n = e.split(t);
            if (n.length) {
                return n[0];
            }
        }
        return null;
    };
    Kh = function n(a) {
        if (process.env.APP_ROOT_PATH) {
            return e.resolve(process.env.APP_ROOT_PATH);
        }
        if (process.versions.pnp) {
            try {
                var l = i("pnpapi");
                return l.getPackageInformation(l.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(a);
        var d = false;
        var p = null;
        if (o(h)) {
            p = c(h);
            if (p) {
                return p;
            }
        }
        t.forEach(function(e) {
            if (!d && 0 === h.indexOf(e)) {
                d = true;
            }
        });
        if (!d) {
            p = c(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(r) && p.length - 4 === p.indexOf(s + "bin")) {
            p = p.slice(0, -4);
        }
        return p;
    };
    return Kh;
}

var Gh;

var Yh;

function zh() {
    if (Yh) return Gh;
    Yh = 1;
    Gh = function(e) {
        var t = C.default;
        var n = Hh();
        var r = n(e);
        var s = {
            resolve: function(e) {
                return t.join(r, e);
            },
            require: function(e) {
                return a.commonjsRequire(s.resolve(e));
            },
            toString: function() {
                return r;
            },
            setPath: function(e) {
                r = t.resolve(e);
                s.path = r;
            },
            path: r
        };
        return s;
    };
    return Gh;
}

var Jh;

var Xh;

function Zh() {
    if (Xh) return Jh;
    Xh = 1;
    var e = zh();
    Jh = e(__dirname);
    return Jh;
}

var ed = {};

var td;

function nd() {
    if (td) return ed;
    td = 1;
    Object.defineProperty(ed, "__esModule", {
        value: true
    });
    ed.importOrRequireFile = i;
    const t = e.require$$0;
    const n = t.__importDefault(v.default);
    const r = t.__importDefault(C.default);
    const s = I.default;
    async function i(e) {
        const t = async () => [ await Function("return filePath => import(filePath)")()(e.startsWith("file://") ? e : (0, 
        s.pathToFileURL)(e).toString()), "esm" ];
        const n = async () => [ a.commonjsRequire(e), "commonjs" ];
        const r = e.substring(e.lastIndexOf(".") + ".".length);
        if (r === "mjs" || r === "mts") return t(); else if (r === "cjs" || r === "cts") return n(); else if (r === "js" || r === "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 !== r.default.dirname(t)) {
            t = r.default.dirname(t);
            const e = r.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 ed;
}

var ad = {};

var rd;

function sd() {
    if (rd) return ad;
    rd = 1;
    Object.defineProperty(ad, "__esModule", {
        value: true
    });
    ad.toPortablePath = a;
    ad.filepathToName = r;
    ad.isAbsolute = s;
    const e = Jn;
    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 s(e) {
        return !!e.match(/^(?:[a-z]:|[\\]|[/])/i);
    }
    return ad;
}

var id = {};

var od;

function cd() {
    if (od) return id;
    od = 1;
    Object.defineProperty(id, "__esModule", {
        value: true
    });
    id.ConnectionOptionsEnvReader = void 0;
    const e = exports.PlatformTools;
    const t = Dc;
    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);
        }
    };
    id.ConnectionOptionsEnvReader = n;
    return id;
}

Object.defineProperty(Vh, "__esModule", {
    value: true
});

exports.ConnectionOptionsReader_2 = Vh.ConnectionOptionsReader = void 0;

const ld = e.require$$0;

const ud = ld.__importDefault(Zh());

const hd = ld.__importDefault(C.default);

const dd = exports.error;

const pd = exports.PlatformTools;

const md = nd();

const fd = sd();

const yd = cd();

class ConnectionOptionsReader {
    constructor(e) {
        this.options = e;
    }
    async all() {
        const e = await this.load();
        if (!e) throw new dd.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 dd.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 r = t.find(e => `.${e}` === n);
        const s = r || t.find(e => pd.PlatformTools.fileExist(this.baseFilePath + "." + e));
        const i = r ? this.baseFilePath : this.baseFilePath + "." + s;
        if (s === "env") {
            pd.PlatformTools.dotenv(i);
        } else if (pd.PlatformTools.fileExist(this.baseDirectory + "/.env")) {
            pd.PlatformTools.dotenv(this.baseDirectory + "/.env");
        }
        if (pd.PlatformTools.getEnvVariable("TYPEORM_CONNECTION") || pd.PlatformTools.getEnvVariable("TYPEORM_URL")) {
            e = await (new yd.ConnectionOptionsEnvReader).read();
        } else if (s === "js" || s === "mjs" || s === "cjs" || s === "ts" || s === "mts" || s === "cts") {
            const [t, n] = await (0, md.importOrRequireFile)(i);
            const a = await t;
            if (n === "esm" || a && "__esModule" in a && "default" in a) {
                e = a.default;
            } else {
                e = a;
            }
        } else if (s === "json") {
            e = a.commonjsRequire(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, fd.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 hd.default.resolve(this.baseDirectory, this.baseConfigName);
    }
    get baseDirectory() {
        return this.options?.root ?? ud.default.path;
    }
    get baseConfigName() {
        return this.options?.configName ?? "ormconfig";
    }
}

exports.ConnectionOptionsReader_2 = Vh.ConnectionOptionsReader = ConnectionOptionsReader;

var Ed = {};

var Td;

function gd() {
    if (Td) return Ed;
    Td = 1;
    Object.defineProperty(Ed, "__esModule", {
        value: true
    });
    Ed.ConnectionManager = void 0;
    const e = sw();
    const t = Dt();
    const n = J();
    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;
        }
    };
    Ed.ConnectionManager = a;
    return Ed;
}

var Nd = {};

Object.defineProperty(Nd, "__esModule", {
    value: true
});

exports.useContainer_1 = Nd.useContainer = Rd;

exports.getFromContainer_1 = Nd.getFromContainer = Sd;

const bd = 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 Ad;

let Cd;

function Rd(e, t) {
    Ad = e;
    Cd = t;
}

function Sd(e) {
    if (Ad) {
        try {
            const t = Ad.get(e);
            if (t) return t;
            if (!Cd || !Cd.fallback) return t;
        } catch (e) {
            if (!Cd || !Cd.fallbackOnErrors) throw e;
        }
    }
    return bd.get(e);
}

var wd;

function Od() {
    if (wd) return uh;
    wd = 1;
    Object.defineProperty(uh, "__esModule", {
        value: true
    });
    uh.getMetadataArgsStorage = i;
    uh.getConnectionOptions = o;
    uh.getConnectionManager = c;
    uh.createConnection = l;
    uh.createConnections = u;
    uh.getConnection = h;
    uh.getManager = d;
    uh.getMongoManager = p;
    uh.getSqljsManager = m;
    uh.getRepository = f;
    uh.getTreeRepository = y;
    uh.getCustomRepository = E;
    uh.getMongoRepository = T;
    uh.createQueryBuilder = g;
    const e = hh;
    const t = exports.PlatformTools;
    const n = Vh;
    const a = gd();
    const r = Nd;
    const s = exports.ObjectUtils;
    function i() {
        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 = s.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 uh;
}

var Md;

function vd() {
    if (Md) return lh;
    Md = 1;
    Object.defineProperty(lh, "__esModule", {
        value: true
    });
    lh.AbstractRepository = void 0;
    const e = Ze;
    const t = Od();
    const n = Ae;
    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;
        }
    };
    lh.AbstractRepository = a;
    return lh;
}

var Id = {};

var Pd = {};

var Ld = {};

Object.defineProperty(Ld, "__esModule", {
    value: true
});

Ld.SubjectTopologicalSorter = void 0;

const _d = exports.error;

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 s = this.toposort(r);
        if (e === "insert") s = s.reverse();
        s.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), s = {}, i = a;
        while (i--) {
            if (!s[i]) o(n[i], i, []);
        }
        function o(t, i, c) {
            if (c.indexOf(t) >= 0) {
                throw new _d.TypeORMError("Cyclic dependency: " + JSON.stringify(t));
            }
            if (!~n.indexOf(t)) {
                throw new _d.TypeORMError("Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(t));
            }
            if (s[i]) return;
            s[i] = true;
            const l = e.filter(function(e) {
                return e[0] === t;
            });
            if (i = l.length) {
                const e = c.concat(t);
                do {
                    const t = l[--i][1];
                    o(t, n.indexOf(t), e);
                } while (i);
            }
            r[--a] = t;
        }
        return r;
    }
}

Ld.SubjectTopologicalSorter = SubjectTopologicalSorter;

var Dd = {};

var xd = {};

var $d = {
    exports: {}
};

$d.exports;

var qd;

function Ud() {
    if (qd) return $d.exports;
    qd = 1;
    (function(e, t) {
        !function(t, n) {
            e.exports = n();
        }(n.commonjsGlobal, function() {
            var e = 1e3, t = 6e4, n = 36e5, a = "millisecond", r = "second", s = "minute", i = "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), s = n - r < 0, i = t.clone().add(a + (s ? -1 : 1), l);
                    return +(-(a + (n - r) / (s ? r - i : i - 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: i,
                        m: s,
                        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 b = "$isDayjsObject", A = function(e) {
                return e instanceof w || !(!e || !e[b]);
            }, C = function e(t, n, a) {
                var r;
                if (!t) return g;
                if ("string" == typeof t) {
                    var s = t.toLowerCase();
                    N[s] && (r = s), n && (N[s] = n, r = s);
                    var i = t.split("-");
                    if (!r && i.length > 1) return e(i[0]);
                } else {
                    var o = t.name;
                    N[o] = t, r = o;
                }
                return !a && r && (g = r), r || !a && g;
            }, R = function(e, t) {
                if (A(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 = A, 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[b] = 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, s = (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, s)) : new Date(a[1], r, a[3] || 1, a[4] || 0, a[5] || 0, a[6] || 0, s);
                            }
                        }
                        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 i:
                        return m(T + "Minutes", 1);

                      case s:
                        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[i] = u + "Hours", 
                    n[s] = 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[s] = t, d[i] = 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), s = this.$H, i = this.$m, o = this.$M, c = n.weekdays, l = n.months, u = n.meridiem, h = function(e, n, r, s) {
                        return e && (e[n] || e(t, a)) || r[n].slice(0, s);
                    }, d = function(e) {
                        return S.s(s % 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(s);

                              case "HH":
                                return S.s(s, 2, "0");

                              case "h":
                                return d(1);

                              case "hh":
                                return d(2);

                              case "a":
                                return m(s, i, true);

                              case "A":
                                return m(s, i, false);

                              case "m":
                                return String(i);

                              case "mm":
                                return S.s(i, 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 i:
                        m = g / n;
                        break;

                      case s:
                        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;
            }(), O = w.prototype;
            return R.prototype = O, [ [ "$ms", a ], [ "$s", r ], [ "$m", s ], [ "$H", i ], [ "$W", o ], [ "$M", l ], [ "$y", h ], [ "$D", d ] ].forEach(function(e) {
                O[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 = A, R.unix = function(e) {
                return R(1e3 * e);
            }, R.en = N[g], R.Ls = N, R.p = {}, R;
        });
    })($d, $d.exports);
    return $d.exports;
}

Object.defineProperty(xd, "__esModule", {
    value: true
});

xd.DateUtils = void 0;

const Bd = e.require$$0;

const jd = Bd.__importDefault(Ud());

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, jd.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);
        }
    }
}

xd.DateUtils = DateUtils;

Object.defineProperty(Dd, "__esModule", {
    value: true
});

Dd.SubjectChangedColumnsComputer = void 0;

const Fd = xd;

const kd = Dc;

const Qd = Bi;

const Vd = exports.ObjectUtils;

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 s = a;
                if (a !== null) {
                    switch (t.type) {
                      case "date":
                        s = t.isArray ? a.map(e => Fd.DateUtils.mixedDateToDateString(e)) : Fd.DateUtils.mixedDateToDateString(a);
                        r = t.isArray ? r.map(e => Fd.DateUtils.mixedDateToDateString(e)) : Fd.DateUtils.mixedDateToDateString(r);
                        break;

                      case "time":
                      case "time with time zone":
                      case "time without time zone":
                      case "timetz":
                        s = t.isArray ? a.map(e => Fd.DateUtils.mixedDateToTimeString(e)) : Fd.DateUtils.mixedDateToTimeString(a);
                        r = t.isArray ? r.map(e => Fd.DateUtils.mixedDateToTimeString(e)) : Fd.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":
                        s = t.isArray ? a.map(e => Fd.DateUtils.mixedDateToUtcDatetimeString(e)) : Fd.DateUtils.mixedDateToUtcDatetimeString(a);
                        r = t.isArray ? r.map(e => Fd.DateUtils.mixedDateToUtcDatetimeString(e)) : Fd.DateUtils.mixedDateToUtcDatetimeString(r);
                        break;

                      case "json":
                      case "jsonb":
                        if (kd.OrmUtils.deepCompare(a, r)) return;
                        break;

                      case "simple-array":
                        s = Fd.DateUtils.simpleArrayToString(a);
                        r = Fd.DateUtils.simpleArrayToString(r);
                        break;

                      case "simple-enum":
                        s = Fd.DateUtils.simpleEnumToString(a);
                        r = Fd.DateUtils.simpleEnumToString(r);
                        break;

                      case "simple-json":
                        s = Fd.DateUtils.simpleJsonToString(a);
                        r = Fd.DateUtils.simpleJsonToString(r);
                        break;
                    }
                    if (t.transformer) {
                        s = Qd.ApplyValueTransformers.transformTo(t.transformer, a);
                    }
                }
                if (t.isArray) {
                    if (kd.OrmUtils.deepCompare(s, r)) return;
                } else if (Buffer.isBuffer(s) && Buffer.isBuffer(r)) {
                    if (s.equals(r)) {
                        return;
                    }
                } else {
                    if (s === 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 && Vd.ObjectUtils.isObject(e)) e = n.getRelationIdMap(e);
                const r = n.getEntityValue(t.databaseEntity);
                const s = kd.OrmUtils.compareIds(e, r);
                if (s) {
                    return;
                } else {
                    t.diffRelations.push(n);
                }
            }
            const r = e.find(e => e.mustBeInserted && e.entity === a);
            if (r) a = r;
            const s = t.changeMaps.find(e => e.relation === n);
            if (s) {
                s.value = a;
            } else {
                t.changeMaps.push({
                    relation: n,
                    value: a
                });
            }
        });
    }
}

Dd.SubjectChangedColumnsComputer = SubjectChangedColumnsComputer;

var Kd = {};

var Wd = {};

Object.defineProperty(Wd, "__esModule", {
    value: true
});

Wd.NestedSetMultipleRootError = void 0;

const Hd = W;

class NestedSetMultipleRootError extends Hd.TypeORMError {
    constructor() {
        super(`Nested sets do not support multiple root entities.`);
    }
}

Wd.NestedSetMultipleRootError = NestedSetMultipleRootError;

Object.defineProperty(Kd, "__esModule", {
    value: true
});

Kd.NestedSetSubjectExecutor = void 0;

const Gd = Dc;

const Yd = Wd;

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 s = e.metadata.treeParentRelation.getEntityValue(e.entity);
        if (!s && e.parentSubject && e.parentSubject.entity) s = e.parentSubject.insertedValueSet ? e.parentSubject.insertedValueSet : e.parentSubject.entity;
        const i = e.metadata.getEntityIdMap(s);
        let o = undefined;
        if (i) {
            o = await this.queryRunner.manager.createQueryBuilder().select(e.metadata.targetName + "." + e.metadata.nestedSetRightColumn.propertyPath, "right").from(e.metadata.target, e.metadata.targetName).whereInIds(i).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}`);
            Gd.OrmUtils.mergeDeep(e.insertedValueSet, e.metadata.nestedSetLeftColumn.createValueMap(o), e.metadata.nestedSetRightColumn.createValueMap(o + 1));
        } else {
            const t = await this.isUniqueRootEntity(e, s);
            if (!t) throw new Yd.NestedSetMultipleRootError;
            Gd.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 s = e.metadata.getEntityIdMap(t);
        if (Gd.OrmUtils.compareIds(r, s)) {
            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 i = 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 (s) {
                l = (await this.getNestedSetIds(e.metadata, s))[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 s = `WHEN ${r} >= ${c.left} AND ` + `${r} < ${c.right} ` + `THEN ${r} + ${n} `;
                const o = `WHEN ${i} > ${c.left} AND ` + `${i} <= ${c.right} ` + `THEN ${i} + ${n} `;
                if (e) {
                    await this.queryRunner.query(`UPDATE ${a} ` + `SET ${r} = CASE ` + `WHEN ${r} > ${c.right} AND ` + `${r} <= ${l.left} ` + `THEN ${r} - ${t} ` + s + `ELSE ${r} ` + `END, ` + `${i} = CASE ` + `WHEN ${i} > ${c.right} AND ` + `${i} < ${l.left} ` + `THEN ${i} - ${t} ` + o + `ELSE ${i} ` + `END`);
                } else {
                    await this.queryRunner.query(`UPDATE ${a} ` + `SET ${r} = CASE ` + `WHEN ${r} < ${c.left} AND ` + `${r} > ${l.right} ` + `THEN ${r} + ${t} ` + s + `ELSE ${r} ` + `END, ` + `${i} = CASE ` + `WHEN ${i} < ${c.left} AND ` + `${i} >= ${l.right} ` + `THEN ${i} + ${t} ` + o + `ELSE ${i} ` + `END`);
                }
            }
        } else {
            const n = await this.isUniqueRootEntity(e, t);
            if (!n) throw new Yd.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 s = n(t.nestedSetRightColumn.databaseName);
        const i = [];
        for (const n of e) {
            const e = t.getEntityIdMap(n.entity);
            if (e) {
                i.push(e);
            }
        }
        const o = await this.getNestedSetIds(t, i);
        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, ` + `${s} = CASE ` + `WHEN ${s} > ${e.right} THEN ${s} - ${t} ` + `ELSE ${s} ` + `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 s = e.metadata.treeParentRelation.joinColumns.map(e => {
            const a = n(e.databaseName);
            const s = e.getEntityValue(t);
            if (s == null) {
                return `${a} IS NULL`;
            }
            r.push(s);
            const i = this.queryRunner.connection.driver.createParameter("entity_" + e.databaseName, r.length - 1);
            return `${a} = ${i}`;
        }).join(" AND ");
        const i = "count";
        const o = await this.queryRunner.query(`SELECT COUNT(1) AS ${n(i)} FROM ${a} WHERE ${s}`, r, true);
        return parseInt(o.records[0][i]) === 0;
    }
    getTableName(e) {
        return e.split(".").map(e => e === "" ? e : this.queryRunner.connection.driver.escape(e)).join(".");
    }
}

Kd.NestedSetSubjectExecutor = NestedSetSubjectExecutor;

var zd = {};

Object.defineProperty(zd, "__esModule", {
    value: true
});

zd.ClosureSubjectExecutor = void 0;

const Jd = Xe();

const Xd = Dc;

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 s = e.metadata.closureJunctionTable.ancestorColumns.map(e => t(e.databaseName));
            const i = 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 s = t(a.databaseName);
                const i = a.referencedColumn.getEntityValue(n);
                if (!i) throw new Jd.CannotAttachTreeChildrenEntityError(e.metadata.name);
                r.push(i);
                const o = this.queryRunner.connection.driver.createParameter("parent_entity_" + a.referencedColumn.databaseName, r.length - 1);
                return `${s} = ${o}`;
            });
            await this.queryRunner.query(`INSERT INTO ${a} (${[ ...s, ...i ].join(", ")}) ` + `SELECT ${s.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 s = e.metadata.getEntityIdMap(t);
        if (Xd.OrmUtils.compareIds(r, s)) {
            return;
        }
        const i = e => this.queryRunner.connection.driver.escape(e);
        const o = e.metadata.closureJunctionTable;
        const c = o.ancestorColumns.map(e => i(e.databaseName));
        const l = o.descendantColumns.map(e => i(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(`${i(n)}.${i(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 s = i("supertree");
            const u = i("subtree");
            const h = [ ...c.map(e => `${s}.${e}`), ...l.map(e => `${u}.${e}`) ];
            const d = e.metadata.closureJunctionTable.ancestorColumns.map(e => {
                const t = i(e.databaseName);
                const r = e.referencedColumn.getEntityValue(n);
                a.push(r);
                const s = this.queryRunner.connection.driver.createParameter("entity_" + e.referencedColumn.databaseName, a.length - 1);
                return `${u}.${t} = ${s}`;
            });
            const p = e.metadata.closureJunctionTable.descendantColumns.map(n => {
                const r = i(n.databaseName);
                const o = n.referencedColumn.getEntityValue(t);
                if (!o) throw new Jd.CannotAttachTreeChildrenEntityError(e.metadata.name);
                a.push(o);
                const c = this.queryRunner.connection.driver.createParameter("parent_entity_" + n.referencedColumn.databaseName, a.length - 1);
                return `${s}.${r} = ${c}`;
            });
            await this.queryRunner.query(`INSERT INTO ${r} (${[ ...c, ...l ].join(", ")}) ` + `SELECT ${h.join(", ")} ` + `FROM ${r} AS ${s}, ${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 s = r(a.ancestorColumns);
        const i = r(a.descendantColumns);
        await this.queryRunner.manager.createQueryBuilder().delete().from(a.tablePath).where(s).orWhere(i).execute();
    }
    getTableName(e) {
        return e.split(".").map(e => e === "" ? e : this.queryRunner.connection.driver.escape(e)).join(".");
    }
}

zd.ClosureSubjectExecutor = ClosureSubjectExecutor;

var Zd = {};

var ep = {};

Object.defineProperty(ep, "__esModule", {
    value: true
});

exports.EntityMetadata_2 = ep.EntityMetadata = void 0;

const tp = le;

const np = Dc;

const ap = bt;

const rp = exports.ObjectUtils;

const sp = Jn;

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 (rp.ObjectUtils.isObject(e)) return e;
        if (this.hasMultiplePrimaryKeys) throw new tp.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 np.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 ap.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 s = n ? n + "." + r : r;
            if (e.hasEmbeddedWithPropertyPath(s)) {
                const n = this.createPropertyPath(e, t[r], s);
                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 => np.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 np.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, sp.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 => np.OrmUtils.mergeDeep(e, t.createValueMap(t.propertyPath)));
        this.relations.forEach(t => np.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);
    }
}

exports.EntityMetadata_2 = ep.EntityMetadata = EntityMetadata;

Object.defineProperty(Zd, "__esModule", {
    value: true
});

Zd.MaterializedPathSubjectExecutor = void 0;

const ip = Dc;

const op = ep;

const cp = exports.Brackets;

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 s = this.getEntityParentReferencedColumnMap(e, t);
        if (ip.OrmUtils.compareIds(r, s)) {
            return;
        }
        let i = "";
        if (s) {
            i = await this.getEntityPath(e, s);
        }
        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}.', '${i}${c}.')`
        }).where(`${l} LIKE :path`, {
            path: `${o}${c}.%`
        }).execute();
    }
    getEntityParentReferencedColumnMap(e, t) {
        if (!t) return undefined;
        return op.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 cp.Brackets(e => {
            for (const t of a) {
                e.orWhere(new cp.Brackets(e => e.where(t)));
            }
        })).getRawOne().then(e => e ? e["path"] : "");
    }
}

Zd.MaterializedPathSubjectExecutor = MaterializedPathSubjectExecutor;

Object.defineProperty(Pd, "__esModule", {
    value: true
});

Pd.SubjectExecutor = void 0;

const lp = Ld;

const up = Dd;

const hp = ee();

const dp = Rn();

const pp = ic;

const mp = Kd;

const fp = zd;

const yp = Zd;

const Ep = Dc;

const Tp = exports.ObjectUtils;

const gp = exports.InstanceChecker;

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 lp.SubjectTopologicalSorter(this.insertSubjects).sort("insert");
        await this.executeInsertOperations();
        this.updateSubjects = this.allSubjects.filter(e => e.mustBeUpdated);
        await this.executeUpdateOperations();
        this.removeSubjects = new lp.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 dp.SubjectRemovedAndUpdatedError(e);
        });
    }
    recompute() {
        (new up.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 pp.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 pp.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 s = [];
            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 => {
                    s.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") {
                        s.push(e);
                    } else {
                        r.push(e);
                        a.push(e.createValueSetAndPopChangeMap());
                    }
                });
            }
            if (gp.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 (s.length > 0) {
                    for (const e of s) {
                        e.insertedValueSet = e.createValueSetAndPopChangeMap();
                        if (e.metadata.treeType === "nested-set") await new mp.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 fp.ClosureSubjectExecutor(this.queryRunner).insert(e);
                        } else if (e.metadata.treeType === "materialized-path") {
                            await new yp.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 hp.SubjectWithoutIdentifierError(e);
            if (gp.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 mp.NestedSetSubjectExecutor(this.queryRunner).update(e);
                    break;

                  case "closure-table":
                    await new fp.ClosureSubjectExecutor(this.queryRunner).update(e);
                    break;

                  case "materialized-path":
                    await new yp.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 hp.SubjectWithoutIdentifierError(e);
                return e.identifier;
            });
            if (gp.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 mp.NestedSetSubjectExecutor(this.queryRunner).remove(t);
                    break;

                  case "closure-table":
                    await new fp.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) {
                Ep.OrmUtils.mergeDeep(t, n.getEntityValueMap(e.entity));
            }
        }
        return t;
    }
    async executeSoftRemoveOperations() {
        await Promise.all(this.softRemoveSubjects.map(async e => {
            if (!e.identifier) throw new hp.SubjectWithoutIdentifierError(e);
            let t;
            if (gp.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 hp.SubjectWithoutIdentifierError(e);
            let t;
            if (gp.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 (gp.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, Tp.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 s = t === "delete" || this.queryRunner.connection.driver.isReturningSqlSupported("insert") || r === false;
        e.forEach((e, t) => {
            const r = s || 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 ];
    }
}

Pd.SubjectExecutor = SubjectExecutor;

var Np = {};

Object.defineProperty(Np, "__esModule", {
    value: true
});

Np.Subject = void 0;

const bp = Dc;

const Ap = exports.ObjectUtils;

const Cp = exports.InstanceChecker;

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 (Cp.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 (Ap.ObjectUtils.isObject(a) && !Buffer.isBuffer(a)) {
                    const s = n.relation.getRelationIdMap(a);
                    if (s === undefined) {
                        e.push(n);
                        this.canBeUpdated = true;
                        return t;
                    }
                    r = n.relation.createValueMap(s);
                    this.updatedRelationMaps.push({
                        relation: n.relation,
                        value: s
                    });
                } else {
                    r = n.relation.createValueMap(a);
                    this.updatedRelationMaps.push({
                        relation: n.relation,
                        value: a
                    });
                }
            }
            bp.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);
        }
    }
}

Np.Subject = Subject;

var Rp = {};

Object.defineProperty(Rp, "__esModule", {
    value: true
});

Rp.OneToManySubjectBuilder = void 0;

const Sp = Np;

const wp = Dc;

const Op = ep;

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 s = t.inverseEntityMetadata.getEntityIdMap(a);
            let i = this.subjects.find(e => e.entity === a);
            if (i) s = i.identifier;
            if (!s) {
                if (!i) return;
                i.changeMaps.push({
                    relation: t.inverseRelation,
                    value: e
                });
                return;
            }
            const o = n.find(e => wp.OrmUtils.compareIds(s, e));
            if (!o) {
                if (!i) {
                    i = new Sp.Subject({
                        metadata: t.inverseEntityMetadata,
                        parentSubject: e,
                        canBeUpdated: true,
                        identifier: s
                    });
                    this.subjects.push(i);
                }
                i.changeMaps.push({
                    relation: t.inverseRelation,
                    value: e
                });
            }
            r.push(s);
        });
        if (t.inverseRelation?.orphanedRowAction !== "disable") {
            Op.EntityMetadata.difference(n, r).forEach(n => {
                const a = new Sp.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);
            });
        }
    }
}

Rp.OneToManySubjectBuilder = OneToManySubjectBuilder;

var Mp = {};

Object.defineProperty(Mp, "__esModule", {
    value: true
});

Mp.OneToOneInverseSideSubjectBuilder = void 0;

const vp = Np;

const Ip = Dc;

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 vp.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 s = this.subjects.find(e => !!e.entity && e.entity === a);
        if (s) r = s.identifier;
        if (!r) {
            if (!s) return;
            s.changeMaps.push({
                relation: t.inverseRelation,
                value: e
            });
        }
        const i = n && Ip.OrmUtils.compareIds(r, n);
        if (!i) {
            if (!s) {
                s = new vp.Subject({
                    metadata: t.inverseEntityMetadata,
                    canBeUpdated: true,
                    identifier: r
                });
                this.subjects.push(s);
            }
            s.changeMaps.push({
                relation: t.inverseRelation,
                value: e
            });
        }
    }
}

Mp.OneToOneInverseSideSubjectBuilder = OneToOneInverseSideSubjectBuilder;

var Pp = {};

Object.defineProperty(Pp, "__esModule", {
    value: true
});

Pp.ManyToManySubjectBuilder = void 0;

const Lp = Np;

const _p = Dc;

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 Lp.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 s = this.subjects.find(e => e.entity === a);
            if (s) r = s.identifier;
            if (!r) {
                if (!s) return;
            }
            const i = n.find(e => _p.OrmUtils.compareIds(e, r));
            if (i) return;
            const o = t.isOwning ? e : s || a;
            const c = t.isOwning ? s || a : e;
            const l = new Lp.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 s = n.filter(e => !r.find(t => _p.OrmUtils.compareIds(t, e)));
        s.forEach(n => {
            const a = new Lp.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 s = {};
        t.junctionEntityMetadata.ownerColumns.forEach(e => {
            _p.OrmUtils.mergeDeep(s, e.createValueMap(e.referencedColumn.getEntityValue(a)));
        });
        t.junctionEntityMetadata.inverseColumns.forEach(e => {
            _p.OrmUtils.mergeDeep(s, e.createValueMap(e.referencedColumn.getEntityValue(r)));
        });
        return s;
    }
}

Pp.ManyToManySubjectBuilder = ManyToManySubjectBuilder;

var Dp = {};

Object.defineProperty(Dp, "__esModule", {
    value: true
});

Dp.SubjectDatabaseEntityLoader = void 0;

const xp = Dc;

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 s = {
                loadEagerRelations: false,
                loadRelationIds: {
                    relations: r,
                    disableMixedMap: true
                },
                withDeleted: true
            };
            let i = [];
            if (this.queryRunner.connection.driver.options.type === "mongodb") {
                const e = this.queryRunner.manager.getRepository(t.target);
                i = await e.findByIds(n, s);
            } else {
                i = await this.queryRunner.manager.getRepository(t.target).createQueryBuilder().setFindOptions(s).whereInIds(n).getMany();
            }
            i.forEach(e => {
                const t = a[0].metadata.getEntityIdMap(e);
                a.forEach(n => {
                    if (n.databaseEntity) return;
                    if (xp.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;
        }, []);
    }
}

Dp.SubjectDatabaseEntityLoader = SubjectDatabaseEntityLoader;

var $p = {};

Object.defineProperty($p, "__esModule", {
    value: true
});

$p.CascadesSubjectBuilder = void 0;

const qp = Np;

const Up = exports.ObjectUtils;

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 (!Up.ObjectUtils.isObject(a)) return;
            const s = this.findByPersistEntityLike(r.target, a);
            if (s) {
                if (s.canBeInserted === false) s.canBeInserted = n.isCascadeInsert === true && t === "save";
                if (s.canBeUpdated === false) s.canBeUpdated = n.isCascadeUpdate === true && t === "save";
                if (s.canBeSoftRemoved === false) s.canBeSoftRemoved = n.isCascadeSoftRemove === true && t === "soft-remove";
                if (s.canBeRecovered === false) s.canBeRecovered = n.isCascadeRecover === true && t === "recover";
                return;
            }
            const i = new qp.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(i);
            this.build(i, 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);
        });
    }
}

$p.CascadesSubjectBuilder = CascadesSubjectBuilder;

Object.defineProperty(Id, "__esModule", {
    value: true
});

Id.EntityPersistExecutor = void 0;

const Bp = Be();

const jp = Pd;

const Fp = ye();

const kp = Np;

const Qp = Rp;

const Vp = Mp;

const Kp = Pp;

const Wp = Dp;

const Hp = $p;

const Gp = Dc;

class EntityPersistExecutor {
    constructor(e, t, n, a, r, s) {
        this.connection = e;
        this.queryRunner = t;
        this.mode = n;
        this.target = a;
        this.entity = r;
        this.options = s;
    }
    async execute() {
        if (!this.entity || typeof this.entity !== "object") return Promise.reject(new Bp.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 ? Gp.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 Fp.CannotDetermineEntityError(this.mode);
                    const a = this.connection.getMetadata(t).findInheritanceMetadata(e);
                    n.push(new kp.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 Hp.CascadesSubjectBuilder(n);
                n.forEach(e => {
                    a.build(e, this.mode);
                });
                await new Wp.SubjectDatabaseEntityLoader(e, n).load(this.mode);
                if (this.mode === "save" || this.mode === "soft-remove" || this.mode === "recover") {
                    new Qp.OneToManySubjectBuilder(n).build();
                    new Vp.OneToOneInverseSideSubjectBuilder(n).build();
                    new Kp.ManyToManySubjectBuilder(n).build();
                } else {
                    n.forEach(e => {
                        if (e.mustBeRemoved) {
                            new Kp.ManyToManySubjectBuilder(n).buildForAllRemoval(e);
                        }
                    });
                }
                return new jp.SubjectExecutor(e, n, this.options);
            }));
            const r = a.filter(e => e.hasExecutableOperations);
            if (r.length === 0) return;
            let s = false;
            try {
                if (!e.isTransactionActive) {
                    if (this.connection.driver.transactionSupport !== "none" && (!this.options || this.options.transaction !== false)) {
                        s = true;
                        await e.startTransaction();
                    }
                }
                for (const e of r) {
                    await e.execute();
                }
                if (s === true) await e.commitTransaction();
            } catch (t) {
                if (s) {
                    try {
                        await e.rollbackTransaction();
                    } catch (e) {}
                }
                throw t;
            }
        } finally {
            e.data = t;
            if (!this.queryRunner) await e.release();
        }
    }
}

Id.EntityPersistExecutor = EntityPersistExecutor;

var Yp;

function zp() {
    if (Yp) return ju;
    Yp = 1;
    Object.defineProperty(ju, "__esModule", {
        value: true
    });
    ju.EntityManager = void 0;
    const e = Ie;
    const t = Ge;
    const n = mn;
    const a = Fu;
    const r = Zu;
    const s = ku;
    const i = zc;
    const o = ih;
    const c = ch;
    const l = exports.error;
    const u = vd();
    const h = Id;
    const d = exports.ObjectUtils;
    const p = Od();
    const m = exports.InstanceChecker;
    const f = Qu;
    const y = Dc;
    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 s = this.queryRunner || this.connection.createQueryRunner();
            try {
                await s.startTransaction(a);
                const e = await r(s.manager);
                await s.commitTransaction();
                return e;
            } catch (e) {
                try {
                    await s.rollbackTransaction();
                } catch (e) {}
                throw e;
            } finally {
                if (!this.queryRunner) await s.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 s = 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, s).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 s = 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, s).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 s = 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, s).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 s = 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, s).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 s;
            if (!Array.isArray(t)) {
                s = [ t ];
            } else {
                s = t;
            }
            const i = a.mapPropertyPathsToColumns(Array.isArray(r.conflictPaths) ? r.conflictPaths : Object.keys(r.conflictPaths));
            const o = a.columns.filter(e => !i.includes(e) && s.some(t => typeof e.getEntityValue(t) !== "undefined"));
            return this.createQueryBuilder().insert().into(e).values(s).orUpdate([ ...i, ...o ].map(e => e.databaseName), i.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, i.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, i.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 s = r.columns.find(e => e.propertyPath === n);
            if (!s) {
                throw new l.TypeORMError(`Column "${n}" was not found in table "${r.name}"`);
            }
            const i = await this.createQueryBuilder(e, r.name).setFindOptions({
                where: a
            }).select(`${t}(${this.connection.driver.escape(s.databaseName)})`, t).getRawOne();
            return i[t] === null ? null : parseFloat(i[t]);
        }
        async find(e, t) {
            const n = this.connection.getMetadata(e);
            return this.createQueryBuilder(e, i.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, i.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 s = r.findColumnWithPropertyPath(n);
            if (!s) 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 i = n.split(".").reduceRight((e, t) => ({
                [t]: e
            }), () => this.connection.driver.escape(s.databaseName) + " + " + a);
            return this.createQueryBuilder(e, "entity").update(e).set(i).where(t).execute();
        }
        async decrement(e, t, n, a) {
            const r = this.connection.getMetadata(e);
            const s = r.findColumnWithPropertyPath(n);
            if (!s) 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 i = n.split(".").reduceRight((e, t) => ({
                [t]: e
            }), () => this.connection.driver.escape(s.databaseName) + " - " + a);
            return this.createQueryBuilder(e, "entity").update(e).set(i).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 s.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, ...s} = e;
            return Object.assign(new t(e.target, this), {
                ...s
            });
        }
        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();
        }
    };
    ju.EntityManager = E;
    return ju;
}

var Jp = {};

var Xp = {};

Object.defineProperty(Xp, "__esModule", {
    value: true
});

Xp.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: s} = t.objectIdColumn;
            const i = e[r];
            const o = e[s];
            if (i) {
                n[s] = i;
                a = true;
            } else if (o) {
                n[s] = 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 s = n.create({
                            fromDeserializer: true
                        });
                        n.columns.forEach(t => {
                            s[t.propertyName] = e[t.databaseNameWithoutPrefixes];
                        });
                        r(s, t[n.prefix][a], n.embeddeds);
                        return s;
                    });
                } 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;
    }
}

Xp.DocumentToEntityTransformer = DocumentToEntityTransformer;

var Zp;

function em() {
    if (Zp) return Jp;
    Zp = 1;
    Object.defineProperty(Jp, "__esModule", {
        value: true
    });
    Jp.MongoEntityManager = void 0;
    const e = zp();
    const t = Xp;
    const n = zc;
    const a = exports.PlatformTools;
    const r = oc;
    const s = Ol;
    const i = no;
    const o = exports.ObjectUtils;
    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 s = 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 (s && !t.withDeleted) {
                    this.filterSoftDeleted(r, s, a);
                }
            } else if (s) {
                this.filterSoftDeleted(r, s, 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 s = this.connection.getMetadata(e);
            const i = this.convertFindManyOptionsOrConditionsToMongodbQuery(r) || {};
            const o = a.PlatformTools.load("mongodb").ObjectId;
            i["_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 = s.objectIdColumn.propertyName;
                        if (e[t] instanceof o) {
                            return e[t];
                        }
                    }
                })
            };
            const c = this.createEntityCursor(e, i);
            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 s.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 s = await this.updateMany(e, this.convertMixedCriteria(r, t), {
                    $set: n
                });
                a.raw = s;
                a.affected = s.modifiedCount;
            }
            return a;
        }
        async delete(e, t) {
            const n = new i.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 s = r.transformAll(n, e);
                await a.broadcaster.broadcast("Load", e, s);
                return s;
            });
            n["__next_func"] = n.next;
            n.next = async () => n["__next_func"]().then(async n => {
                if (!n) {
                    return n;
                }
                const r = new t.DocumentToEntityTransformer;
                const s = r.transform(n, e);
                await a.broadcaster.broadcast("Load", e, [ s ]);
                return s;
            });
        }
        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 s = a.PlatformTools.load("mongodb").ObjectId;
            const i = t instanceof s || typeof t === "string" ? t : undefined;
            const o = i ? r : t;
            const c = this.convertFindOneOptionsOrConditionsToMongodbQuery(o) || {};
            if (i) {
                c["_id"] = i instanceof s ? i : new s(i);
            }
            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 s = 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 (s && !t.withDeleted) {
                    this.filterSoftDeleted(r, s, a);
                }
            } else if (s) {
                this.filterSoftDeleted(r, s, a);
            }
            return r.toArray();
        }
        async executeFindAndCount(e, t) {
            const a = this.convertFindManyOptionsOrConditionsToMongodbQuery(t);
            const r = await this.createEntityCursor(e, a);
            const s = 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 (s && !t.withDeleted) {
                    this.filterSoftDeleted(r, s, a);
                }
            } else if (s) {
                this.filterSoftDeleted(r, s, a);
            }
            const [i, o] = await Promise.all([ r.toArray(), this.count(e, a) ]);
            return [ i, parseInt(o) ];
        }
    };
    Jp.MongoEntityManager = c;
    return Jp;
}

var tm = {};

var nm;

function am() {
    if (nm) return tm;
    nm = 1;
    Object.defineProperty(tm, "__esModule", {
        value: true
    });
    tm.SqljsEntityManager = void 0;
    const e = zp();
    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();
        }
    };
    tm.SqljsEntityManager = t;
    return tm;
}

var rm;

function sm() {
    if (rm) return Bu;
    rm = 1;
    Object.defineProperty(Bu, "__esModule", {
        value: true
    });
    Bu.EntityManagerFactory = void 0;
    const e = zp();
    const t = em();
    const n = am();
    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);
        }
    };
    Bu.EntityManagerFactory = a;
    return Bu;
}

var im = {};

var om = {};

var cm = {};

var lm = {};

Object.defineProperty(lm, "__esModule", {
    value: true
});

lm.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);
    }
}

lm.View = View;

var um = {};

Object.defineProperty(um, "__esModule", {
    value: true
});

um.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;
    }
}

um.ViewUtils = ViewUtils;

Object.defineProperty(cm, "__esModule", {
    value: true
});

cm.RdbmsSchemaBuilder = void 0;

const hm = su;

const dm = iu;

const pm = cu;

const mm = ou;

const fm = lu;

const ym = uu;

const Em = hu;

const Tm = du;

const gm = lm;

const Nm = um;

const bm = zn;

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(Nm.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 (bm.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 (bm.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 = hm.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 = gm.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 s = typeof a.expression === "string" ? a.expression.trim() : a.expression(this.connection).getQuery();
            if (r === s) 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 [s, i] of n.entries()) {
                if (s === e) {
                    continue;
                }
                if (i.dependsOn && (i.dependsOn.has(t.target) || i.dependsOn.has(t.name))) {
                    r = r.concat(a(s));
                }
            }
            return r;
        };
        const r = new Set(e.map(e => a(e)).reduce((e, t) => e.concat(t), []).sort((e, t) => Nm.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 dm.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 dm.TableColumn(fm.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 (!(bm.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 = fm.TableUtils.createTableColumnOptions(e, this.connection.driver);
                const r = new dm.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 => mm.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" || !bm.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 => mm.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 (bm.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 => Em.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 => ym.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 => Tm.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 => pm.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 => fm.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 hm.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);
    }
}

cm.RdbmsSchemaBuilder = RdbmsSchemaBuilder;

var Am = {};

var Cm = {};

var Rm = {};

Object.defineProperty(Rm, "__esModule", {
    value: true
});

Rm.Query = void 0;

class Query {
    constructor(e, t) {
        this.query = e;
        this.parameters = t;
        this["@instanceof"] = Symbol.for("Query");
    }
}

Rm.Query = Query;

var Sm = {};

Object.defineProperty(Sm, "__esModule", {
    value: true
});

Sm.SqlInMemory = void 0;

class SqlInMemory {
    constructor() {
        this.upQueries = [];
        this.downQueries = [];
    }
}

Sm.SqlInMemory = SqlInMemory;

Object.defineProperty(Cm, "__esModule", {
    value: true
});

Cm.BaseQueryRunner = void 0;

const wm = Rm;

const Om = Sm;

const Mm = W;

const vm = Dc;

const Im = exports.InstanceChecker;

const Pm = Qu;

class BaseQueryRunner {
    constructor() {
        this.isReleased = false;
        this.isTransactionActive = false;
        this.data = {};
        this.loadedTables = [];
        this.loadedViews = [];
        this.sqlMemoryMode = false;
        this.sqlInMemory = new Om.SqlInMemory;
        this.transactionDepth = 0;
        this.cachedTablePaths = {};
    }
    async sql(e, ...t) {
        const {query: n, parameters: a} = (0, Pm.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 Om.SqlInMemory;
        this.sqlMemoryMode = true;
    }
    disableSqlMemory() {
        this.sqlInMemory = new Om.SqlInMemory;
        this.sqlMemoryMode = false;
    }
    clearSqlMemory() {
        this.sqlInMemory = new Om.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 Mm.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 Mm.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 s = this.connection.createQueryBuilder();
        const i = s.select().from(this.getTypeormMetadataTableName(), "t").where(`${s.escape("type")} = :type`, {
            type: a
        }).andWhere(`${s.escape("name")} = :name`, {
            name: r
        });
        if (e) {
            i.andWhere(`${s.escape("database")} = :database`, {
                database: e
            });
        }
        if (t) {
            i.andWhere(`${s.escape("schema")} = :schema`, {
                schema: t
            });
        }
        if (n) {
            i.andWhere(`${s.escape("table")} = :table`, {
                table: n
            });
        }
        const [o, c] = i.getQueryAndParameters();
        return new wm.Query(o, c);
    }
    insertTypeormMetadataSql({database: e, schema: t, table: n, type: a, name: r, value: s}) {
        const [i, o] = this.connection.createQueryBuilder().insert().into(this.getTypeormMetadataTableName()).values({
            database: e,
            schema: t,
            table: n,
            type: a,
            name: r,
            value: s
        }).getQueryAndParameters();
        return new wm.Query(i, o);
    }
    deleteTypeormMetadataSql({database: e, schema: t, table: n, type: a, name: r}) {
        const s = this.connection.createQueryBuilder();
        const i = s.delete().from(this.getTypeormMetadataTableName()).where(`${s.escape("type")} = :type`, {
            type: a
        }).andWhere(`${s.escape("name")} = :name`, {
            name: r
        });
        if (e) {
            i.andWhere(`${s.escape("database")} = :database`, {
                database: e
            });
        }
        if (t) {
            i.andWhere(`${s.escape("schema")} = :schema`, {
                schema: t
            });
        }
        if (n) {
            i.andWhere(`${s.escape("table")} = :table`, {
                table: n
            });
        }
        const [o, c] = i.getQueryAndParameters();
        return new wm.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 !vm.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 (Im.InstanceChecker.isQuery(e)) e = [ e ];
        if (Im.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);
    }
}

Cm.BaseQueryRunner = BaseQueryRunner;

var Lm = {};

Object.defineProperty(Lm, "__esModule", {
    value: true
});

exports.QueryResult_2 = Lm.QueryResult = void 0;

class QueryResult {
    constructor() {
        this.records = [];
    }
}

exports.QueryResult_2 = Lm.QueryResult = QueryResult;

var _m = {};

Object.defineProperty(_m, "__esModule", {
    value: true
});

_m.Broadcaster = void 0;

const Dm = exports.ObjectUtils;

const xm = ic;

class Broadcaster {
    constructor(e) {
        this.queryRunner = e;
    }
    async broadcast(e, ...t) {
        const n = new xm.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, s) {
        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(i => {
                if (this.isAllowedSubscriber(i, t.target) && i.beforeUpdate) {
                    const o = i.beforeUpdate({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        updatedColumns: r || [],
                        updatedRelations: s || []
                    });
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.beforeRemove) {
                    const i = s.beforeRemove({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.beforeSoftRemove) {
                    const i = s.beforeSoftRemove({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.beforeRecover) {
                    const i = s.beforeRecover({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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 s = r.afterInsert({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        entityId: t.getEntityIdMixedMap(a)
                    });
                    if (s instanceof Promise) e.promises.push(s);
                    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, s, i) {
        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: s,
                        error: i
                    });
                    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, s) {
        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(i => {
                if (this.isAllowedSubscriber(i, t.target) && i.afterUpdate) {
                    const o = i.afterUpdate({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        updatedColumns: r || [],
                        updatedRelations: s || []
                    });
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.afterRemove) {
                    const i = s.afterRemove({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.afterSoftRemove) {
                    const i = s.afterSoftRemove({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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(s => {
                if (this.isAllowedSubscriber(s, t.target) && s.afterRecover) {
                    const i = s.afterRecover({
                        connection: this.queryRunner.connection,
                        queryRunner: this.queryRunner,
                        manager: this.queryRunner.manager,
                        entity: n,
                        metadata: t,
                        databaseEntity: a,
                        entityId: t.getEntityIdMixedMap(a ?? r)
                    });
                    if (i instanceof Promise) e.promises.push(i);
                    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 (Dm.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);
    }
}

_m.Broadcaster = Broadcaster;

var $m = {};

Object.defineProperty($m, "__esModule", {
    value: true
});

$m.MetadataTableType = void 0;

var qm;

(function(e) {
    e["VIEW"] = "VIEW";
    e["MATERIALIZED_VIEW"] = "MATERIALIZED_VIEW";
    e["GENERATED_COLUMN"] = "GENERATED_COLUMN";
})(qm || ($m.MetadataTableType = qm = {}));

Object.defineProperty(Am, "__esModule", {
    value: true
});

Am.CockroachQueryRunner = void 0;

const Um = exports.error;

const Bm = pn();

const jm = Dn();

const Fm = we();

const km = Cm;

const Qm = Lm;

const Vm = su;

const Km = hu;

const Wm = iu;

const Hm = du;

const Gm = cu;

const Ym = ou;

const zm = uu;

const Jm = lm;

const Xm = _m;

const Zm = ic;

const ef = exports.InstanceChecker;

const tf = Dc;

const nf = Ti;

const af = Rm;

const rf = $m;

class CockroachQueryRunner extends km.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 Xm.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 Fm.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 Fm.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 jm.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new Zm.BroadcasterResult;
        const s = Date.now();
        if (this.isTransactionActive && this.storeQueries) {
            this.queries.push({
                query: e,
                parameters: t
            });
        }
        try {
            const i = 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 - s;
            if (o && l > o) {
                this.driver.connection.logger.logQuerySlow(l, e, t, this);
            }
            const u = new Qm.QueryResult;
            if (i.hasOwnProperty("rowCount")) {
                u.affected = i.rowCount;
            }
            if (i.hasOwnProperty("rows")) {
                u.records = i.rows;
            }
            switch (i.command) {
              case "DELETE":
                u.raw = [ i.rows, i.rowCount ];
                break;

              default:
                u.raw = i.rows;
            }
            this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, i, 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 Bm.QueryFailedError(e, t, n);
            }
        } finally {
            await r.wait();
        }
    }
    async stream(e, t, n, a) {
        const r = this.driver.loadStreamDependency();
        if (this.isReleased) {
            throw new jm.QueryRunnerAlreadyReleasedError;
        }
        const s = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        const i = s.query(new r(e, t));
        if (n) {
            i.on("end", n);
        }
        if (a) {
            i.on("error", a);
        }
        return i;
    }
    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 af.Query(n), new af.Query(a));
    }
    async dropDatabase(e, t) {
        const n = `DROP DATABASE ${t ? "IF EXISTS " : ""} "${e}"`;
        const a = `CREATE DATABASE "${e}"`;
        await this.executeQueries(new af.Query(n), new af.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 af.Query(a), new af.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 s = `CREATE SCHEMA "${a}"`;
        await this.executeQueries(new af.Query(r), new af.Query(s));
    }
    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 s = [];
        const i = e.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
        const o = [];
        for (const t of i) {
            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));
                s.push(this.dropEnumTypeSql(e, t, a));
            }
        }
        e.columns.filter(e => e.isGenerated && e.generationStrategy === "increment").forEach(t => {
            r.push(new af.Query(`CREATE SEQUENCE ${this.escapePath(this.buildSequencePath(e, t))}`));
            s.push(new af.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(e, t))}`));
        });
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.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 i = this.insertTypeormMetadataSql({
                schema: a,
                table: e.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const o = this.deleteTypeormMetadataSql({
                schema: a,
                table: e.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(i);
            s.push(o);
        }
        await this.executeQueries(r, s);
    }
    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 s = this.getTablePath(e);
        const i = await this.getCachedTable(s);
        const o = [];
        const c = [];
        if (n) i.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(i, e)));
        if (a) {
            i.indices.forEach(e => {
                o.push(this.dropIndexSql(i, e));
                c.push(this.createIndexSql(i, e));
            });
        }
        o.push(this.dropTableSql(i));
        c.push(this.createTableSql(i, r));
        i.columns.filter(e => e.isGenerated && e.generationStrategy === "increment").forEach(e => {
            o.push(new af.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(i, e))}`));
            c.push(new af.Query(`CREATE SEQUENCE ${this.escapePath(this.buildSequencePath(i, e))}`));
        });
        const l = i.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of l) {
            const t = await this.getCurrentSchema();
            let {schema: n} = this.driver.parseTableName(i);
            if (!n) {
                n = t;
            }
            const a = this.deleteTypeormMetadataSql({
                schema: n,
                table: i.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const r = this.insertTypeormMetadataSql({
                schema: n,
                table: i.name,
                type: rf.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 = ef.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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {schema: i, tableName: o} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new af.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
        a.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME TO "${o}"`));
        if (s.primaryColumns.length > 0 && !s.primaryColumns[0].primaryKeyConstraintName) {
            const e = s.primaryColumns.map(e => e.name);
            const t = this.connection.namingStrategy.primaryKeyName(r, e);
            const i = this.connection.namingStrategy.primaryKeyName(s, e);
            n.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${t}" TO "${i}"`));
            a.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${t}"`));
        }
        s.uniques.forEach(e => {
            const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.uniqueConstraintName(s, e.columnNames);
            n.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
            if (e.name !== t) return;
            const {schema: i} = this.driver.parseTableName(s);
            const o = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            const c = i ? `ALTER INDEX "${i}"."${e.name}" RENAME TO "${o}"` : `ALTER INDEX "${e.name}" RENAME TO "${o}"`;
            const l = i ? `ALTER INDEX "${i}"."${o}" RENAME TO "${e.name}"` : `ALTER INDEX "${o}" RENAME TO "${e.name}"`;
            n.push(new af.Query(c));
            a.push(new af.Query(l));
            e.name = o;
        });
        s.foreignKeys.forEach(e => {
            const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.foreignKeyName(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            n.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new af.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        const c = s.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 af.Query(`ALTER TYPE "${t.schema}"."${t.name}" RENAME TO ${this.buildEnumName(s, e, false)}`));
            a.push(new af.Query(`ALTER TYPE ${this.buildEnumName(s, e)} RENAME TO "${t.name}"`));
        }
        await this.executeQueries(n, a);
    }
    async addColumn(e, t) {
        const n = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        if (t.generationStrategy === "increment") {
            throw new Um.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));
                s.push(this.dropEnumTypeSql(n, t));
            }
        }
        r.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t)}`));
        s.push(new af.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 i = e.map(e => `"${e.name}"`).join(", ");
                r.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
                s.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${i})`));
            }
            e.push(t);
            const i = 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 af.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${i}" PRIMARY KEY (${o})`));
            s.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${i}"`));
        }
        if (t.generatedType && t.asExpression) {
            const e = await this.getCurrentSchema();
            let {schema: a} = this.driver.parseTableName(n);
            if (!a) {
                a = e;
            }
            const i = this.insertTypeormMetadataSql({
                schema: a,
                table: n.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const o = this.deleteTypeormMetadataSql({
                schema: a,
                table: n.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(i);
            s.push(o);
        }
        const i = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (i) {
            if (i.isUnique) {
                const e = new zm.TableUnique({
                    name: this.connection.namingStrategy.uniqueConstraintName(n, i.columnNames),
                    columnNames: i.columnNames
                });
                r.push(this.createUniqueConstraintSql(n, e));
                s.push(this.dropIndexSql(n, e));
                a.uniques.push(e);
            } else {
                r.push(this.createIndexSql(n, i));
                s.push(this.dropIndexSql(n, i));
            }
        }
        if (t.isUnique) {
            const e = new zm.TableUnique({
                name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
                columnNames: [ t.name ]
            });
            a.uniques.push(e);
            r.push(this.createUniqueConstraintSql(n, e));
            s.push(this.dropIndexSql(n, e.name));
        }
        if (t.comment) {
            r.push(new af.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
            s.push(new af.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
        }
        await this.executeQueries(r, s);
        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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = ef.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new Um.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s;
        if (ef.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        return this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        let o = false;
        const c = ef.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!c) throw new Um.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) {
                s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "${n.name}"`));
                i.push(new af.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);
                    s.push(new af.Query(`ALTER TYPE "${e.schema}"."${e.name}" RENAME TO ${this.buildEnumName(a, n, false)}`));
                    i.push(new af.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);
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${l}"`));
                    i.push(new af.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);
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
                    i.push(new af.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}"`;
                    s.push(new af.Query(u));
                    i.push(new af.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);
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
                    i.push(new af.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) {
                s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
                i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
            }
            if (c.isNullable !== n.isNullable) {
                if (n.isNullable) {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
                    i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
                } else {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
                    i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
                }
            }
            if (c.comment !== n.comment) {
                s.push(new af.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${c.name}" IS ${this.escapeComment(n.comment)}`));
                i.push(new af.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(", ");
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    i.push(new af.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(", ");
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
                    i.push(new af.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(", ");
                        s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
                        i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    }
                }
            }
            if (n.isUnique !== c.isUnique) {
                if (n.isUnique) {
                    const e = new zm.TableUnique({
                        name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
                        columnNames: [ n.name ]
                    });
                    r.uniques.push(e);
                    s.push(this.createUniqueConstraintSql(a, e));
                    i.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);
                    s.push(this.dropIndexSql(a, e));
                    i.push(this.createUniqueConstraintSql(a, e));
                }
            }
            if ((n.type === "enum" || n.type === "simple-enum") && (c.type === "enum" || c.type === "simple-enum") && (!tf.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);
                s.push(new af.Query(`ALTER TYPE ${r} RENAME TO ${h}`));
                i.push(new af.Query(`ALTER TYPE ${u} RENAME TO ${l}`));
                s.push(this.createEnumTypeSql(a, n, t));
                i.push(this.dropEnumTypeSql(a, n, t));
                if (c.default !== null && c.default !== undefined) {
                    o = true;
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
                    i.push(new af.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}`;
                s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${d}`));
                s.push(new af.Query(`SELECT pg_sleep(0.1)`));
                i.push(new af.Query(`SELECT pg_sleep(0.1)`));
                i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${p}`));
                if (n.default !== null && n.default !== undefined) {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
                    i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                }
                s.push(this.dropEnumTypeSql(a, c, u));
                i.push(this.createEnumTypeSql(a, c, u));
            }
            if (c.isGenerated !== n.isGenerated && n.generationStrategy !== "uuid") {
                if (n.isGenerated) {
                    if (n.generationStrategy === "increment") {
                        throw new Um.TypeORMError(`Adding sequential generated columns into existing table is not supported`);
                    } else if (n.generationStrategy === "rowid") {
                        s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT unique_rowid()`));
                        i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    }
                } else {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    i.push(new af.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) {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
                    if (c.default !== null && c.default !== undefined) {
                        i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
                    } else {
                        i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    }
                } else if (c.default !== null && c.default !== undefined) {
                    s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    i.push(new af.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) {
            s.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
            i.push(new af.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(c)}`));
        }
        await this.executeQueries(s, i);
        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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = ef.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new Um.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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(", ");
            s.push(new af.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
            i.push(new af.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(", ");
                s.push(new af.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
                i.push(new af.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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(this.dropCheckConstraintSql(n, c));
            i.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);
            s.push(this.dropIndexSql(n, l.name));
            i.push(this.createUniqueConstraintSql(n, l));
        }
        s.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
        i.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, a)}`));
        if (a.generationStrategy === "increment") {
            s.push(new af.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(n, a))}`));
            i.push(new af.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: rf.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const o = this.insertTypeormMetadataSql({
                schema: t,
                table: n.name,
                type: rf.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(r);
            i.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}"`;
                s.push(this.dropEnumTypeSql(n, a, t));
                i.push(this.createEnumTypeSql(n, a, t));
            }
        }
        await this.executeQueries(s, i);
        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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = a.clone();
        const s = this.createPrimaryKeySql(a, t, n);
        r.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        const i = this.dropPrimaryKeySql(r);
        await this.executeQueries(s, i);
        this.replaceCachedTable(a, r);
    }
    async updatePrimaryKeys(e, t) {
        const n = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = t.map(e => e.name);
        const s = [];
        const i = [];
        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(", ");
            s.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            i.push(new af.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(", ");
        s.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
        i.push(new af.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
        await this.executeQueries(s, i);
        this.replaceCachedTable(n, a);
    }
    async dropPrimaryKey(e, t) {
        const n = ef.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 = ef.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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = ef.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
        if (!a) throw new Um.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
        const r = this.dropIndexSql(n, a);
        const s = this.createUniqueConstraintSql(n, a);
        await this.executeQueries(r, s);
        n.removeUniqueConstraint(a);
    }
    async dropUniqueConstraints(e, t) {
        for (const n of t) {
            await this.dropUniqueConstraint(e, n);
        }
    }
    async createCheckConstraint(e, t) {
        const n = ef.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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = ef.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
        if (!a) throw new Um.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 Um.TypeORMError(`CockroachDB does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new Um.TypeORMError(`CockroachDB does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new Um.TypeORMError(`CockroachDB does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new Um.TypeORMError(`CockroachDB does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = ef.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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = ef.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new Um.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        n.removeForeignKey(a);
    }
    async dropForeignKeys(e, t) {
        for (const n of t) {
            await this.dropForeignKey(e, n);
        }
    }
    async createIndex(e, t) {
        const n = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        if (!t.name) t.name = this.generateIndexName(n, t);
        if (t.isUnique) {
            const e = new zm.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 = ef.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = ef.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new Um.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = `SELECT 'DROP TABLE IF EXISTS "' || table_schema || '"."' || table_name || '" CASCADE;' as "query" FROM "information_schema"."tables" WHERE "table_schema" IN (${t})`;
            const i = await this.query(s);
            await Promise.all(i.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 (nf.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 s = `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" = '${rf.MetadataTableType.VIEW}' ${r ? `AND (${r})` : ""}`;
        const i = await this.query(s);
        return i.map(e => {
            const t = new Jm.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 s = `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 i = 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 (${i})`;
        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 (${i})`;
        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(s), this.query(o), this.query(c), this.query(u), this.query(d) ]);
        return Promise.all(a.map(async e => {
            const a = new Vm.Table;
            const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
            const s = r(e, "table_schema");
            a.database = n;
            a.schema = e["table_schema"];
            a.name = this.driver.buildTableName(e["table_name"], s);
            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 Wm.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 s = t["udt_name"];
                if (s.indexOf("_") === 0) {
                    s = s.substr(1, s.length);
                }
                const i = E.find(e => e["name"] === s);
                if (i) {
                    const e = this.buildEnumName(a, r, false, true);
                    const t = e !== i["name"] ? i["name"] : undefined;
                    r.type = "enum";
                    r.enum = i["value"].split("|");
                    r.enumName = t;
                }
                if (t["data_type"].toLowerCase() === "array") {
                    r.isArray = true;
                    if (!i) {
                        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 s = this.connection.namingStrategy.primaryKeyName(a, n);
                    if (o["constraint_name"] !== s) {
                        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 (i) {
                            r.default = r.default.replace(`.${i["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: rf.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 i = tf.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 = i.map(e => {
                const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
                return new zm.TableUnique({
                    name: e["constraint_name"],
                    columnNames: t.map(e => e["column_name"])
                });
            });
            const o = tf.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 Km.TableCheck({
                    name: e["constraint_name"],
                    columnNames: t.map(e => e["column_name"]),
                    expression: e["expression"].replace(/^\s*CHECK\s*\((.*)\)\s*$/i, "$1")
                });
            });
            const c = tf.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 Hm.TableExclusion({
                name: e["constraint_name"],
                expression: e["expression"].substring(8)
            }));
            const l = tf.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 Gm.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 = tf.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 Ym.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 zm.TableUnique({
                name: this.connection.namingStrategy.uniqueConstraintName(e, [ t.name ]),
                columnNames: [ t.name ]
            }));
        });
        e.indices.filter(e => e.isUnique).forEach(t => {
            e.uniques.push(new zm.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 af.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 af.Query(`DROP TABLE ${this.escapePath(e)}`);
    }
    createViewSql(e) {
        if (typeof e.expression === "string") {
            return new af.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
        } else {
            return new af.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: rf.MetadataTableType.VIEW,
            schema: n,
            name: a,
            value: r
        });
    }
    dropViewSql(e) {
        return new af.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: rf.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 s = await this.query(r);
        return s.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 af.Query(`CREATE TYPE ${n} AS ENUM(${a})`);
    }
    dropEnumTypeSql(e, t, n) {
        if (!n) n = this.buildEnumName(e, t);
        return new af.Query(`DROP TYPE ${n}`);
    }
    createIndexSql(e, t) {
        const n = t.columnNames.map(e => `"${e}"`).join(", ");
        return new af.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 = ef.InstanceChecker.isTableIndex(t) || ef.InstanceChecker.isTableUnique(t) ? t.name : t;
        return new af.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 af.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
    }
    dropPrimaryKeySql(e) {
        if (!e.primaryColumns.length) throw new Um.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 af.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
    }
    createUniqueConstraintSql(e, t) {
        const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
        return new af.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
    }
    dropUniqueConstraintSql(e, t) {
        const n = ef.InstanceChecker.isTableUnique(t) ? t.name : t;
        return new af.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createCheckConstraintSql(e, t) {
        return new af.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
    }
    dropCheckConstraintSql(e, t) {
        const n = ef.InstanceChecker.isTableCheck(t) ? t.name : t;
        return new af.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 af.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = ef.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new af.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    buildSequenceName(e, t) {
        const {tableName: n} = this.driver.parseTableName(e);
        const a = ef.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: s, tableName: i} = this.driver.parseTableName(e);
        let o = t.enumName ? t.enumName : `${i}_${t.name.toLowerCase()}_enum`;
        if (s && n) o = `${s}.${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 s = r[0]["udt_name"];
        if (s.indexOf("_") === 0) {
            s = s.substr(1, s.length);
        }
        return {
            schema: r[0]["udt_schema"],
            name: s
        };
    }
    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 Um.TypeORMError(`cockroachdb driver does not support change table comment.`);
    }
}

Am.CockroachQueryRunner = CockroachQueryRunner;

Object.defineProperty(om, "__esModule", {
    value: true
});

om.CockroachDriver = void 0;

const sf = exports.error;

const of = ce();

const cf = Mt();

const lf = exports.PlatformTools;

const uf = cm;

const hf = Bi;

const df = xd;

const pf = exports.InstanceChecker;

const mf = exports.ObjectUtils;

const ff = Dc;

const yf = zn;

const Ef = Am;

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 = yf.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
        this.schema = yf.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 of.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 uf.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new Ef.CockroachQueryRunner(this, e);
    }
    preparePersistentValue(e, t) {
        if (t.transformer) e = hf.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 df.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return df.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 df.DateUtils.mixedDateToDate(e);
        } else if ([ "json", "jsonb", ...this.spatialTypes ].indexOf(t.type) >= 0) {
            return JSON.stringify(e);
        } else if (t.type === "simple-array") {
            return df.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return df.DateUtils.simpleJsonToString(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? hf.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 = df.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = df.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = df.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array") {
            e = df.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = df.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 = hf.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, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            if (r.has(s)) {
                return this.parametersPrefix + r.get(s);
            }
            const i = t[s];
            if (n) {
                return i.map(e => {
                    a.push(e);
                    return this.createParameter(s, a.length - 1);
                }).join(", ");
            }
            if (typeof i === "function") {
                return i();
            }
            a.push(i);
            r.set(s, a.length);
            return this.createParameter(s, 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 (pf.InstanceChecker.isTable(e) || pf.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 (pf.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 (pf.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 (mf.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 sf.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) {
                ff.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 && !ff.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 lf.PlatformTools.load("pg-query-stream");
        } catch (e) {
            throw new sf.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 || lf.PlatformTools.load("pg");
            this.postgres = e;
            try {
                const e = this.options.nativeDriver || lf.PlatformTools.load("pg-native");
                if (e && this.postgres.native) this.postgres = this.postgres.native;
            } catch (e) {}
        } catch (e) {
            throw new cf.DriverPackageNotInstalledError("Postgres", "pg");
        }
    }
    async createPool(e, t) {
        t = Object.assign({}, t, yf.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 s = e.poolErrorHandler || (e => r.log("warn", `Postgres pool raised an error. ${e}`));
        a.on("error", s);
        return new Promise((e, t) => {
            a.connect((n, r, s) => {
                if (n) return t(n);
                s();
                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(".");
    }
}

om.CockroachDriver = CockroachDriver;

var Tf = {};

var gf = {};

Object.defineProperty(gf, "__esModule", {
    value: true
});

gf.MongoQueryRunner = void 0;

const Nf = _m;

const bf = exports.error;

class MongoQueryRunner {
    constructor(e, t) {
        this.isReleased = false;
        this.isTransactionActive = false;
        this.data = {};
        this.connection = e;
        this.databaseConnection = t;
        this.broadcaster = new Nf.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 bf.TypeORMError(`Executing SQL query is not supported by MongoDB driver.`);
    }
    async sql(e, ...t) {
        throw new bf.TypeORMError(`Executing SQL query is not supported by MongoDB driver.`);
    }
    stream(e, t, n, a) {
        throw new bf.TypeORMError(`Stream is not supported by MongoDB driver. Use watch instead.`);
    }
    async getDatabases() {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async getSchemas(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async getTable(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async getTables(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async getView(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async getViews(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    getReplicationMode() {
        return "master";
    }
    async hasDatabase(e) {
        throw new bf.TypeORMError(`Check database queries are not supported by MongoDB driver.`);
    }
    async getCurrentDatabase() {
        throw new bf.TypeORMError(`Check database queries are not supported by MongoDB driver.`);
    }
    async hasSchema(e) {
        throw new bf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
    }
    async getCurrentSchema() {
        throw new bf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
    }
    async hasTable(e) {
        throw new bf.TypeORMError(`Check schema queries are not supported by MongoDB driver.`);
    }
    async hasColumn(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createDatabase(e) {
        throw new bf.TypeORMError(`Database create queries are not supported by MongoDB driver.`);
    }
    async dropDatabase(e, t) {
        throw new bf.TypeORMError(`Database drop queries are not supported by MongoDB driver.`);
    }
    async createSchema(e, t) {
        throw new bf.TypeORMError(`Schema create queries are not supported by MongoDB driver.`);
    }
    async dropSchema(e, t) {
        throw new bf.TypeORMError(`Schema drop queries are not supported by MongoDB driver.`);
    }
    async createTable(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropTable(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createView(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropView(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async renameTable(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async addColumn(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async addColumns(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async renameColumn(e, t, n) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async changeColumn(e, t, n) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async changeColumns(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropColumn(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropColumns(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createPrimaryKey(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async updatePrimaryKeys(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropPrimaryKey(e) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createUniqueConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createUniqueConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropUniqueConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropUniqueConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createCheckConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createCheckConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropCheckConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropCheckConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createExclusionConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createExclusionConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createForeignKey(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createForeignKeys(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropForeignKey(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropForeignKeys(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createIndex(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async createIndices(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropIndex(e, t) {
        throw new bf.TypeORMError(`Schema update queries are not supported by MongoDB driver.`);
    }
    async dropIndices(e, t) {
        throw new bf.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 bf.TypeORMError(`This operation is not supported by MongoDB driver.`);
    }
    disableSqlMemory() {
        throw new bf.TypeORMError(`This operation is not supported by MongoDB driver.`);
    }
    clearSqlMemory() {
        throw new bf.TypeORMError(`This operation is not supported by MongoDB driver.`);
    }
    getMemorySql() {
        throw new bf.TypeORMError(`This operation is not supported by MongoDB driver.`);
    }
    async executeMemoryUpSql() {
        throw new bf.TypeORMError(`This operation is not supported by MongoDB driver.`);
    }
    async executeMemoryDownSql() {
        throw new bf.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 bf.TypeORMError(`mongodb driver does not support change table comment.`);
    }
}

gf.MongoQueryRunner = MongoQueryRunner;

var Af = {};

Object.defineProperty(Af, "__esModule", {
    value: true
});

Af.MongoSchemaBuilder = void 0;

const Cf = Sm;

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 Cf.SqlInMemory);
    }
}

Af.MongoSchemaBuilder = MongoSchemaBuilder;

Object.defineProperty(Tf, "__esModule", {
    value: true
});

Tf.MongoDriver = void 0;

const Rf = ce();

const Sf = Mt();

const wf = gf;

const Of = exports.PlatformTools;

const Mf = Af;

const vf = exports.ObjectUtils;

const If = Bi;

const Pf = zn;

const Lf = exports.error;

const _f = exports.InstanceChecker;

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 = Pf.DriverUtils.buildMongoDBDriverOptions(this.options).database;
    }
    async connect() {
        const e = Pf.DriverUtils.buildMongoDBDriverOptions(this.options);
        const t = await this.mongodb.MongoClient.connect(this.buildConnectionUrl(e), this.buildConnectionOptions(e));
        this.queryRunner = new wf.MongoQueryRunner(this.connection, t);
        vf.ObjectUtils.assign(this.queryRunner, {
            manager: this.connection.manager
        });
    }
    afterConnect() {
        return Promise.resolve();
    }
    async disconnect() {
        if (!this.queryRunner) throw new Rf.ConnectionIsNotSetError("mongodb");
        this.queryRunner.databaseConnection.close();
        this.queryRunner = undefined;
    }
    createSchemaBuilder() {
        return new Mf.MongoSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return this.queryRunner;
    }
    escapeQueryWithParameters(e, t, n) {
        throw new Lf.TypeORMError(`This operation is not supported by Mongodb driver.`);
    }
    escape(e) {
        return e;
    }
    buildTableName(e, t, n) {
        return e;
    }
    parseTableName(e) {
        if (_f.InstanceChecker.isEntityMetadata(e)) {
            return {
                tableName: e.tableName
            };
        }
        if (_f.InstanceChecker.isTable(e) || _f.InstanceChecker.isView(e)) {
            return {
                tableName: e.name
            };
        }
        if (_f.InstanceChecker.isTableForeignKey(e)) {
            return {
                tableName: e.referencedTableName
            };
        }
        return {
            tableName: e
        };
    }
    preparePersistentValue(e, t) {
        if (t.transformer) e = If.ApplyValueTransformers.transformTo(t.transformer, e);
        return e;
    }
    prepareHydratedValue(e, t) {
        if (t.transformer) e = If.ApplyValueTransformers.transformFrom(t.transformer, e);
        return e;
    }
    normalizeType(e) {
        throw new Lf.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
    }
    normalizeDefault(e) {
        throw new Lf.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
    }
    normalizeIsUnique(e) {
        throw new Lf.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
    }
    getColumnLength(e) {
        throw new Lf.TypeORMError(`MongoDB is schema-less, not supported by this driver.`);
    }
    createFullType(e) {
        throw new Lf.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 Lf.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 || Of.PlatformTools.load("mongodb");
            this.mongodb = e;
        } catch (e) {
            throw new Sf.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;
    }
}

Tf.MongoDriver = MongoDriver;

var Df = {};

var xf = {};

var $f = {};

Object.defineProperty($f, "__esModule", {
    value: true
});

$f.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);
            }
        };
    }
}

$f.QueryLock = QueryLock;

Object.defineProperty(xf, "__esModule", {
    value: true
});

xf.SqlServerQueryRunner = void 0;

const qf = exports.error;

const Uf = pn();

const Bf = Dn();

const jf = we();

const Ff = Cm;

const kf = $f;

const Qf = Lm;

const Vf = su;

const Kf = hu;

const Wf = iu;

const Hf = cu;

const Gf = ou;

const Yf = uu;

const zf = lm;

const Jf = _m;

const Xf = ic;

const Zf = exports.InstanceChecker;

const ey = Dc;

const ty = Rm;

const ny = $m;

class SqlServerQueryRunner extends Ff.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.lock = new kf.QueryLock;
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new Jf.Broadcaster(this);
        this.mode = t;
    }
    connect() {
        return Promise.resolve();
    }
    release() {
        this.isReleased = true;
        return Promise.resolve();
    }
    async startTransaction(e) {
        if (this.isReleased) throw new Bf.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 Bf.QueryRunnerAlreadyReleasedError;
        if (!this.isTransactionActive) throw new jf.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 Bf.QueryRunnerAlreadyReleasedError;
        if (!this.isTransactionActive) throw new jf.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 Bf.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 Xf.BroadcasterResult;
        try {
            const a = await (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection());
            const s = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : a);
            if (t && t.length) {
                t.forEach((e, t) => {
                    const n = t.toString();
                    if (Zf.InstanceChecker.isMssqlParameter(e)) {
                        const t = this.mssqlParameterToNativeParameter(e);
                        if (t) {
                            s.input(n, t, e.value);
                        } else {
                            s.input(n, e.value);
                        }
                    } else {
                        s.input(n, e);
                    }
                });
            }
            const i = Date.now();
            const o = await new Promise((n, a) => {
                s.query(e, (s, o) => {
                    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);
                    }
                    if (s) {
                        a(new Uf.QueryFailedError(e, t, s));
                    }
                    n(o);
                });
            });
            const c = new Qf.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 Bf.QueryRunnerAlreadyReleasedError;
        const r = await this.lock.acquire();
        this.driver.connection.logger.logQuery(e, t, this);
        const s = await (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection());
        const i = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : s);
        if (t && t.length) {
            t.forEach((e, t) => {
                const n = t.toString();
                if (Zf.InstanceChecker.isMssqlParameter(e)) {
                    i.input(n, this.mssqlParameterToNativeParameter(e), e.value);
                } else {
                    i.input(n, e);
                }
            });
        }
        i.query(e);
        const o = i.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 ty.Query(n), new ty.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 ty.Query(n), new ty.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 ty.Query(r));
            a.push(new ty.Query(`DROP SCHEMA "${e}"`));
        } else {
            const r = e.split(".")[0];
            const s = e.split(".")[1];
            const i = await this.getCurrentDatabase();
            n.push(new ty.Query(`USE "${r}"`));
            a.push(new ty.Query(`USE "${i}"`));
            const o = t ? `IF SCHEMA_ID('${s}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${s}"') END` : `CREATE SCHEMA "${s}"`;
            n.push(new ty.Query(o));
            a.push(new ty.Query(`DROP SCHEMA "${s}"`));
            n.push(new ty.Query(`USE "${i}"`));
            a.push(new ty.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 ty.Query(r));
            a.push(new ty.Query(`CREATE SCHEMA "${e}"`));
        } else {
            const r = e.split(".")[0];
            const s = e.split(".")[1];
            const i = await this.getCurrentDatabase();
            n.push(new ty.Query(`USE "${r}"`));
            a.push(new ty.Query(`USE "${i}"`));
            const o = t ? `IF SCHEMA_ID('${s}') IS NULL BEGIN EXEC ('DROP SCHEMA "${s}"') END` : `DROP SCHEMA "${s}"`;
            n.push(new ty.Query(o));
            a.push(new ty.Query(`CREATE SCHEMA "${s}"`));
            n.push(new ty.Query(`USE "${i}"`));
            a.push(new ty.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 s = [];
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.push(this.dropIndexSql(e, t));
            });
        }
        const i = e.columns.filter(e => e.generatedType && e.asExpression);
        for (const t of i) {
            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: ny.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const i = this.deleteTypeormMetadataSql({
                database: n.database,
                schema: n.schema,
                table: n.tableName,
                type: ny.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(a);
            s.push(i);
        }
        await this.executeQueries(r, s);
    }
    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 s = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const i = [];
        const o = [];
        if (a) {
            s.indices.forEach(e => {
                i.push(this.dropIndexSql(s, e));
                o.push(this.createIndexSql(s, e));
            });
        }
        if (n) s.foreignKeys.forEach(e => i.push(this.dropForeignKeySql(s, e)));
        i.push(this.dropTableSql(s));
        o.push(this.createTableSql(s, r));
        const c = s.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of c) {
            const t = this.driver.parseTableName(s);
            if (!t.schema) {
                t.schema = await this.getCurrentSchema();
            }
            const n = this.deleteTypeormMetadataSql({
                database: t.database,
                schema: t.schema,
                table: t.tableName,
                type: ny.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const a = this.insertTypeormMetadataSql({
                database: t.database,
                schema: t.schema,
                table: t.tableName,
                type: ny.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            i.push(n);
            o.push(a);
        }
        await this.executeQueries(i, 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 = Zf.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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        let i = undefined;
        let o = undefined;
        let c = r.name;
        const l = r.name.split(".");
        if (l.length === 3) {
            i = l[0];
            c = l[2];
            if (l[1] !== "") o = l[1];
        } else if (l.length === 2) {
            o = l[0];
            c = l[1];
        }
        s.name = this.driver.buildTableName(t, o, i);
        const u = await this.getCurrentDatabase();
        if (i && i !== u) {
            n.push(new ty.Query(`USE "${i}"`));
            a.push(new ty.Query(`USE "${u}"`));
        }
        n.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(r)}", "${t}"`));
        a.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}", "${c}"`));
        if (s.primaryColumns.length > 0 && !s.primaryColumns[0].primaryKeyConstraintName) {
            const e = s.primaryColumns.map(e => e.name);
            const t = this.connection.namingStrategy.primaryKeyName(r, e);
            const i = this.connection.namingStrategy.primaryKeyName(s, e);
            n.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${t}", "${i}"`));
            a.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${i}", "${t}"`));
        }
        s.uniques.forEach(e => {
            const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.uniqueConstraintName(s, e.columnNames);
            n.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${e.name}", "${i}"`));
            a.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${i}", "${e.name}"`));
            e.name = i;
        });
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            n.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${e.name}", "${i}", "INDEX"`));
            a.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(s)}.${i}", "${e.name}", "INDEX"`));
            e.name = i;
        });
        s.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(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            n.push(new ty.Query(`EXEC sp_rename "${this.buildForeignKeyName(e.name, o, i)}", "${c}"`));
            a.push(new ty.Query(`EXEC sp_rename "${this.buildForeignKeyName(c, o, i)}", "${e.name}"`));
            e.name = c;
        });
        if (i && i !== u) {
            n.push(new ty.Query(`USE "${u}"`));
            a.push(new ty.Query(`USE "${i}"`));
        }
        await this.executeQueries(n, a);
        r.name = s.name;
        this.replaceCachedTable(r, s);
    }
    async addColumn(e, t) {
        const n = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        r.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t, false, true)}`));
        s.push(new ty.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 i = e.map(e => `"${e.name}"`).join(", ");
                r.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
                s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${i})`));
            }
            e.push(t);
            const i = 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 ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${i}" PRIMARY KEY (${o})`));
            s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${i}"`));
        }
        const i = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (i) {
            r.push(this.createIndexSql(n, i));
            s.push(this.dropIndexSql(n, i));
        }
        if (t.isUnique) {
            const e = new Yf.TableUnique({
                name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
                columnNames: [ t.name ]
            });
            a.uniques.push(e);
            r.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
            s.push(new ty.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);
            s.push(new ty.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: ny.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const i = this.deleteTypeormMetadataSql({
                database: e.database,
                schema: e.schema,
                table: e.tableName,
                type: ny.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(a);
            s.push(i);
        }
        await this.executeQueries(r, s);
        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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = Zf.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new qf.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s = undefined;
        if (Zf.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        await this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = Zf.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!o) throw new qf.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) {
                    s.push(new ty.Query(`USE "${e}"`));
                    i.push(new ty.Query(`USE "${l}"`));
                }
                s.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(a)}.${o.name}", "${n.name}"`));
                i.push(new ty.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);
                    s.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(r)}.${a}", "${c}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${a}", "INDEX"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`EXEC sp_rename "${this.buildForeignKeyName(a.name, t, e)}", "${l}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${t}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`EXEC sp_rename "${this.getTablePath(r)}.${e.name}", "${a}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
                    i.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e}" DEFAULT ${o.default} FOR "${n.name}"`));
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" DEFAULT ${o.default} FOR "${n.name}"`));
                    i.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                }
                if (e && e !== l) {
                    s.push(new ty.Query(`USE "${l}"`));
                    i.push(new ty.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)) {
                s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN ${this.buildCreateColumnSql(a, n, true, false, true)}`));
                i.push(new ty.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 Kf.TableCheck({
                    name: this.connection.namingStrategy.checkConstraintName(a, e, true),
                    expression: e
                });
                const r = this.getEnumExpression(n);
                const c = new Kf.TableCheck({
                    name: this.connection.namingStrategy.checkConstraintName(a, r, true),
                    expression: r
                });
                s.push(this.dropCheckConstraintSql(a, t));
                s.push(this.createCheckConstraintSql(a, c));
                i.push(this.dropCheckConstraintSql(a, c));
                i.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(", ");
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    i.push(new ty.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(", ");
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
                    i.push(new ty.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(", ");
                        s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
                        i.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    }
                }
            }
            if (n.isUnique !== o.isUnique) {
                if (n.isUnique === true) {
                    const e = new Yf.TableUnique({
                        name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
                        columnNames: [ n.name ]
                    });
                    r.uniques.push(e);
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
                    i.push(new ty.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);
                    s.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e}" DEFAULT ${n.default} FOR "${n.name}"`));
                    i.push(new ty.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e}"`));
                }
            }
            await this.executeQueries(s, i);
            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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Zf.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new qf.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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(", ");
            s.push(new ty.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
            i.push(new ty.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(", ");
                s.push(new ty.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
                i.push(new ty.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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(this.dropCheckConstraintSql(n, c));
            i.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);
            s.push(this.dropUniqueConstraintSql(n, l));
            i.push(this.createUniqueConstraintSql(n, l));
        }
        if (a.default !== null && a.default !== undefined) {
            const e = this.connection.namingStrategy.defaultConstraintName(n, a.name);
            s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            i.push(new ty.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: ny.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const r = this.insertTypeormMetadataSql({
                database: e.database,
                schema: e.schema,
                table: e.tableName,
                type: ny.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(t);
            i.push(r);
        }
        s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
        i.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, a, false, false)}`));
        await this.executeQueries(s, i);
        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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = a.clone();
        const s = this.createPrimaryKeySql(a, t, n);
        r.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        const i = this.dropPrimaryKeySql(r);
        await this.executeQueries(s, i);
        this.replaceCachedTable(a, r);
    }
    async updatePrimaryKeys(e, t) {
        const n = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = t.map(e => e.name);
        const s = [];
        const i = [];
        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(", ");
            s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            i.push(new ty.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(", ");
        s.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
        i.push(new ty.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
        await this.executeQueries(s, i);
        this.replaceCachedTable(n, a);
    }
    async dropPrimaryKey(e, t) {
        const n = Zf.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 = Zf.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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Zf.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
        if (!a) throw new qf.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
        const r = this.dropUniqueConstraintSql(n, a);
        const s = this.createUniqueConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 = Zf.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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Zf.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
        if (!a) throw new qf.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 qf.TypeORMError(`SqlServer does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new qf.TypeORMError(`SqlServer does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new qf.TypeORMError(`SqlServer does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new qf.TypeORMError(`SqlServer does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = Zf.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 qf.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 s = this.dropForeignKeySql(n, t);
        await this.executeQueries(r, s);
        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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Zf.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new qf.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 = Zf.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 = Zf.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Zf.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new qf.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = await this.query(r);
            if (s.length > 0) {
                const e = s.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(s.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 s = 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 i = 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" = '${ny.MetadataTableType.VIEW}' ${s ? `AND (${s})` : ""}`).join(" UNION ALL ");
        const o = await this.query(i);
        return o.map(e => {
            const t = new zf.View;
            const r = e["TABLE_CATALOG"] === a ? undefined : e["TABLE_CATALOG"];
            const s = 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"], s, 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 s = 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(s));
        }
        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 s = 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 i = 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(s), this.query(i), this.query(o), this.query(c), this.query(l), this.query(u) ]);
        return await Promise.all(a.map(async e => {
            const a = new Vf.Table;
            const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
            const s = e["TABLE_CATALOG"] === n ? undefined : e["TABLE_CATALOG"];
            const i = r(e, "TABLE_SCHEMA");
            a.database = e["TABLE_CATALOG"];
            a.schema = e["TABLE_SCHEMA"];
            a.name = this.driver.buildTableName(e["TABLE_NAME"], i, s);
            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 s = 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 i = !!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 Wf.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 && !s;
                c.isGenerated = i;
                if (i) 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: ny.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 = ey.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 Yf.TableUnique({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"])
                });
            });
            const l = ey.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 Kf.TableCheck({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    expression: e["definition"]
                });
            });
            const u = ey.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 s = r(e, "REF_SCHEMA");
                const i = this.driver.buildTableName(e["REF_TABLE"], s, a);
                return new Hf.TableForeignKey({
                    name: e["FK_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    referencedDatabase: e["TABLE_CATALOG"],
                    referencedSchema: e["REF_SCHEMA"],
                    referencedTableName: i,
                    referencedColumnNames: t.map(e => e["REF_COLUMN"]),
                    onDelete: e["ON_DELETE"].replace("_", " "),
                    onUpdate: e["ON_UPDATE"].replace("_", " ")
                });
            });
            const E = ey.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 Gf.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 Yf.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 ty.Query(a);
    }
    dropTableSql(e, t) {
        const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
        return new ty.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 ty.Query(`CREATE VIEW ${n} AS ${e.expression}`);
        } else {
            return new ty.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: ny.MetadataTableType.VIEW,
            database: t.database,
            schema: t.schema,
            name: t.tableName,
            value: n
        });
    }
    dropViewSql(e) {
        return new ty.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: ny.MetadataTableType.VIEW,
            database: t.database,
            schema: t.schema,
            name: t.tableName
        });
    }
    createIndexSql(e, t) {
        const n = t.columnNames.map(e => `"${e}"`).join(", ");
        return new ty.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
    }
    dropIndexSql(e, t) {
        const n = Zf.InstanceChecker.isTableIndex(t) ? t.name : t;
        return new ty.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 ty.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 ty.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
    }
    createUniqueConstraintSql(e, t) {
        const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
        return new ty.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
    }
    dropUniqueConstraintSql(e, t) {
        const n = Zf.InstanceChecker.isTableUnique(t) ? t.name : t;
        return new ty.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createCheckConstraintSql(e, t) {
        return new ty.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
    }
    dropCheckConstraintSql(e, t) {
        const n = Zf.InstanceChecker.isTableCheck(t) ? t.name : t;
        return new ty.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 ty.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = Zf.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new ty.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 s = `"${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);
            s += ` CONSTRAINT ${a} CHECK(${n})`;
        }
        if (t.collation) s += " COLLATE " + t.collation;
        if (t.asExpression) {
            s += ` AS (${t.asExpression})`;
            if (t.generatedType === "STORED") {
                s += ` PERSISTED`;
                if (t.isNullable !== true) s += " NOT NULL";
            }
        } else {
            if (t.isNullable !== true) s += " NOT NULL";
        }
        if (t.isGenerated === true && t.generationStrategy === "increment" && !n) s += " IDENTITY(1,1)";
        if (t.default !== undefined && t.default !== null && a) {
            const n = this.connection.namingStrategy.defaultConstraintName(e, t.name);
            s += ` CONSTRAINT "${n}" DEFAULT ${t.default}`;
        }
        if (t.isGenerated && t.generationStrategy === "uuid" && !t.default) {
            const n = this.connection.namingStrategy.defaultConstraintName(e, t.name);
            s += ` CONSTRAINT "${n}" DEFAULT NEWSEQUENTIALID()`;
        }
        return s;
    }
    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 qf.TypeORMError(`sqlserver driver does not support change table comment.`);
    }
}

xf.SqlServerQueryRunner = SqlServerQueryRunner;

Object.defineProperty(Df, "__esModule", {
    value: true
});

Df.SqlServerDriver = void 0;

const ay = ce();

const ry = Mt();

const sy = zn;

const iy = xf;

const oy = xd;

const cy = exports.PlatformTools;

const ly = cm;

const uy = bu;

const hy = iu;

const dy = Dc;

const py = Bi;

const my = exports.error;

const fy = exports.InstanceChecker;

const yy = exports.FindOperator;

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 = sy.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
        this.schema = sy.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 ay.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 ly.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new iy.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, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            if (r.has(s)) {
                return this.parametersPrefix + r.get(s);
            }
            const i = t[s];
            if (n) {
                return i.map(e => {
                    a.push(e);
                    return this.createParameter(s, a.length - 1);
                }).join(", ");
            }
            if (typeof i === "function") {
                return i();
            }
            a.push(i);
            r.set(s, a.length - 1);
            return this.createParameter(s, 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 (fy.InstanceChecker.isTable(e) || fy.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 (fy.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 (fy.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 = py.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 oy.DateUtils.mixedDateToDate(e);
        } else if (t.type === "time") {
            return oy.DateUtils.mixedTimeToDate(e);
        } else if (t.type === "datetime" || t.type === "smalldatetime" || t.type === Date) {
            return oy.DateUtils.mixedDateToDate(e, false, false);
        } else if (t.type === "datetime2" || t.type === "datetimeoffset") {
            return oy.DateUtils.mixedDateToDate(e, false, true);
        } else if (t.type === "simple-array") {
            return oy.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return oy.DateUtils.simpleJsonToString(e);
        } else if (t.type === "simple-enum") {
            return oy.DateUtils.simpleEnumToString(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? py.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 = oy.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = oy.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = oy.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array") {
            e = oy.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = oy.DateUtils.stringToSimpleJson(e);
        } else if (t.type === "simple-enum") {
            e = oy.DateUtils.stringToSimpleEnum(e, t);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = py.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 my.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) {
                dy.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 && !dy.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 (fy.InstanceChecker.isMssqlParameter(t)) return t;
        const n = this.normalizeType({
            type: e.type
        });
        if (e.length) {
            return new uy.MssqlParameter(t, n, e.length);
        } else if (e.precision !== null && e.precision !== undefined && e.scale !== null && e.scale !== undefined) {
            return new uy.MssqlParameter(t, n, e.precision, e.scale);
        } else if (e.precision !== null && e.precision !== undefined) {
            return new uy.MssqlParameter(t, n, e.precision);
        } else if (e.scale !== null && e.scale !== undefined) {
            return new uy.MssqlParameter(t, n, e.scale);
        }
        return new uy.MssqlParameter(t, n);
    }
    parametrizeValues(e, t) {
        if (t instanceof yy.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 s = n.findColumnWithDatabaseName(a);
            if (!s) return r;
            e[a] = this.parametrizeValue(s, r);
            return e;
        }, {});
    }
    buildTableVariableDeclaration(e, t) {
        const n = t.map(e => `${this.escape(e.databaseName)} ${this.createFullType(new hy.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 || cy.PlatformTools.load("mssql");
            this.mssql = e;
        } catch (e) {
            throw new ry.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, sy.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: s} = this.connection;
            const i = e.pool && e.pool.errorHandler || (e => s.log("warn", `MSSQL pool raised an error. ${e}`));
            r.on("error", i);
            const o = r.connect(e => {
                if (e) return n(e);
                t(o);
            });
        });
    }
}

Df.SqlServerDriver = SqlServerDriver;

var Ey = {};

var Ty = {};

Object.defineProperty(Ty, "__esModule", {
    value: true
});

Ty.OracleQueryRunner = void 0;

const gy = exports.error;

const Ny = pn();

const by = Dn();

const Ay = we();

const Cy = Cm;

const Ry = Lm;

const Sy = su;

const wy = hu;

const Oy = iu;

const My = cu;

const vy = ou;

const Iy = uu;

const Py = lm;

const Ly = _m;

const _y = ic;

const Dy = exports.InstanceChecker;

const xy = Dc;

const $y = Rm;

const qy = $m;

class OracleQueryRunner extends Cy.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new Ly.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 by.QueryRunnerAlreadyReleasedError;
        if (e !== "SERIALIZABLE" && e !== "READ COMMITTED") {
            throw new gy.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 Ay.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 Ay.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 by.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new _y.BroadcasterResult;
        const s = Date.now();
        try {
            const i = {
                autoCommit: !this.isTransactionActive,
                outFormat: this.driver.oracle.OUT_FORMAT_OBJECT
            };
            const o = await a.execute(e, t || {}, i);
            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);
            const h = new Ry.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 Ny.QueryFailedError(e, t, n);
        } finally {
            await r.wait();
        }
    }
    async stream(e, t, n, a) {
        if (this.isReleased) {
            throw new by.QueryRunnerAlreadyReleasedError;
        }
        const r = {
            autoCommit: !this.isTransactionActive,
            outFormat: this.driver.oracle.OUT_FORMAT_OBJECT
        };
        const s = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        try {
            const i = s.queryStream(e, t, 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 Ny.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 gy.TypeORMError(`Schema create queries are not supported by Oracle driver.`);
    }
    async dropSchema(e, t) {
        throw new gy.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 s = [];
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.push(this.dropIndexSql(t));
            });
        }
        const i = e.columns.filter(e => e.generatedType && e.asExpression);
        for (const t of i) {
            const n = this.insertTypeormMetadataSql({
                table: e.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const a = this.deleteTypeormMetadataSql({
                table: e.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(n);
            s.push(a);
        }
        await this.executeQueries(r, s);
    }
    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 s = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const i = [];
        const o = [];
        if (a) {
            s.indices.forEach(e => {
                i.push(this.dropIndexSql(e));
                o.push(this.createIndexSql(s, e));
            });
        }
        if (n) s.foreignKeys.forEach(e => i.push(this.dropForeignKeySql(s, e)));
        i.push(this.dropTableSql(s));
        o.push(this.createTableSql(s, r));
        const c = s.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of c) {
            const t = this.deleteTypeormMetadataSql({
                table: s.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const n = this.insertTypeormMetadataSql({
                table: s.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            i.push(t);
            o.push(n);
        }
        await this.executeQueries(i, 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 = Dy.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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {database: i, tableName: o} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new $y.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
        a.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME TO "${o}"`));
        if (s.primaryColumns.length > 0 && !s.primaryColumns[0].primaryKeyConstraintName) {
            const e = s.primaryColumns.map(e => e.name);
            const t = this.connection.namingStrategy.primaryKeyName(r, e);
            const i = this.connection.namingStrategy.primaryKeyName(s, e);
            n.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${t}" TO "${i}"`));
            a.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${t}"`));
        }
        s.uniques.forEach(e => {
            const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.uniqueConstraintName(s, e.columnNames);
            n.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            n.push(new $y.Query(`ALTER INDEX "${e.name}" RENAME TO "${i}"`));
            a.push(new $y.Query(`ALTER INDEX "${i}" RENAME TO "${e.name}"`));
            e.name = i;
        });
        s.foreignKeys.forEach(e => {
            const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.foreignKeyName(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            n.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new $y.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        await this.executeQueries(n, a);
        r.name = s.name;
        this.replaceCachedTable(r, s);
    }
    async addColumn(e, t) {
        const n = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        r.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t)}`));
        s.push(new $y.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 i = e.map(e => `"${e.name}"`).join(", ");
                r.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
                s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${i})`));
            }
            e.push(t);
            const i = 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 $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${i}" PRIMARY KEY (${o})`));
            s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${i}"`));
        }
        const i = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (i) {
            a.indices.splice(a.indices.indexOf(i), 1);
            r.push(this.createIndexSql(n, i));
            s.push(this.dropIndexSql(i));
        }
        if (t.isUnique) {
            const e = new Iy.TableUnique({
                name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
                columnNames: [ t.name ]
            });
            a.uniques.push(e);
            r.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
            s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e.name}"`));
        }
        if (t.generatedType && t.asExpression) {
            const e = this.insertTypeormMetadataSql({
                table: n.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const a = this.deleteTypeormMetadataSql({
                table: n.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(e);
            s.push(a);
        }
        await this.executeQueries(r, s);
        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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = Dy.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new gy.TypeORMError(`Column "${t}" was not found in the ${this.escapePath(a)} table.`);
        let s = undefined;
        if (Dy.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        await this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = Dy.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!o) throw new gy.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) {
                s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${o.name}" TO "${n.name}"`));
                i.push(new $y.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);
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${c}" TO "${l}"`));
                    i.push(new $y.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);
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${c}"`));
                    i.push(new $y.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);
                    s.push(new $y.Query(`ALTER INDEX "${e.name}" RENAME TO "${a}"`));
                    i.push(new $y.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);
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${c}"`));
                    i.push(new $y.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";
                    }
                }
                s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} MODIFY "${o.name}" ${this.connection.driver.createFullType(n)} ${e} ${r}`));
                i.push(new $y.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(", ");
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    i.push(new $y.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(", ");
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
                    i.push(new $y.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(", ");
                        s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
                        i.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    }
                }
            }
            if (n.isUnique !== o.isUnique) {
                if (n.isUnique === true) {
                    const e = new Iy.TableUnique({
                        name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
                        columnNames: [ n.name ]
                    });
                    r.uniques.push(e);
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
                    i.push(new $y.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);
                    s.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
                    i.push(new $y.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
                }
            }
            await this.executeQueries(s, i);
            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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Dy.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new gy.TypeORMError(`Column "${t}" was not found in table ${this.escapePath(n)}`);
        const r = n.clone();
        const s = [];
        const i = [];
        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(", ");
            s.push(new $y.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
            i.push(new $y.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(", ");
                s.push(new $y.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
                i.push(new $y.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) {
            s.push(this.dropIndexSql(o));
            i.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);
            s.push(this.dropCheckConstraintSql(n, c));
            i.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);
            s.push(this.dropUniqueConstraintSql(n, l));
            i.push(this.createUniqueConstraintSql(n, l));
        }
        s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
        i.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a)}`));
        if (a.generatedType && a.asExpression) {
            const e = this.deleteTypeormMetadataSql({
                table: n.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const t = this.insertTypeormMetadataSql({
                table: n.name,
                type: qy.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(e);
            i.push(t);
        }
        await this.executeQueries(s, i);
        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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = a.clone();
        const s = this.createPrimaryKeySql(a, t, n);
        r.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        const i = this.dropPrimaryKeySql(r);
        await this.executeQueries(s, i);
        this.replaceCachedTable(a, r);
    }
    async updatePrimaryKeys(e, t) {
        const n = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = t.map(e => e.name);
        const r = n.clone();
        const s = [];
        const i = [];
        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(", ");
            s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            i.push(new $y.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(", ");
        s.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
        i.push(new $y.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
        await this.executeQueries(s, i);
        this.replaceCachedTable(n, r);
    }
    async dropPrimaryKey(e, t) {
        const n = Dy.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 = Dy.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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Dy.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
        if (!a) throw new gy.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
        const r = this.dropUniqueConstraintSql(n, a);
        const s = this.createUniqueConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 = Dy.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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Dy.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
        if (!a) throw new gy.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 gy.TypeORMError(`Oracle does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new gy.TypeORMError(`Oracle does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new gy.TypeORMError(`Oracle does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new gy.TypeORMError(`Oracle does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = Dy.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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Dy.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new gy.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 = Dy.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 = Dy.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Dy.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new gy.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = `SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS' AS "query" FROM "USER_TABLES"`;
            const i = await this.query(s);
            await Promise.all(i.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 s = `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 ('${qy.MetadataTableType.MATERIALIZED_VIEW}', '${qy.MetadataTableType.VIEW}')`;
        if (r.length > 0) s += ` AND ${r}`;
        const i = await this.query(s);
        return i.map(e => {
            const t = this.driver.parseTableName(e["name"]);
            const r = new Py.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"] === qy.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 s = `SELECT * FROM "ALL_TAB_COLS" "C" WHERE (${r})`;
        const i = `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(s), this.query(i), this.query(o), this.query(c) ]);
        return await Promise.all(t.map(async e => {
            const t = new Sy.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 s = 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 i = new Oy.TableColumn;
                i.name = n["COLUMN_NAME"];
                i.type = n["DATA_TYPE"].toLowerCase();
                if (i.type.indexOf("(") !== -1) i.type = i.type.replace(/\([0-9]*\)/, "");
                if (this.driver.withLengthColumnTypes.indexOf(i.type) !== -1) {
                    const e = i.type === "raw" ? n["DATA_LENGTH"] : n["CHAR_COL_DECL_LENGTH"];
                    i.length = e && !this.isDefaultColumnLength(t, i, e) ? e.toString() : "";
                }
                if (i.type === "number" || i.type === "float") {
                    if (n["DATA_PRECISION"] !== null && !this.isDefaultColumnPrecision(t, i, n["DATA_PRECISION"])) i.precision = n["DATA_PRECISION"];
                    if (n["DATA_SCALE"] !== null && !this.isDefaultColumnScale(t, i, n["DATA_SCALE"])) i.scale = n["DATA_SCALE"];
                } else if ((i.type === "timestamp" || i.type === "timestamp with time zone" || i.type === "timestamp with local time zone") && n["DATA_SCALE"] !== null) {
                    i.precision = !this.isDefaultColumnPrecision(t, i, n["DATA_SCALE"]) ? n["DATA_SCALE"] : undefined;
                }
                i.default = n["DATA_DEFAULT"] !== null && n["DATA_DEFAULT"] !== undefined && n["VIRTUAL_COLUMN"] === "NO" && n["DATA_DEFAULT"].trim() !== "NULL" ? i.default = n["DATA_DEFAULT"].trim() : undefined;
                const o = a.find(e => e["CONSTRAINT_TYPE"] === "P");
                if (o) {
                    i.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) {
                        i.primaryKeyConstraintName = o["CONSTRAINT_NAME"];
                    }
                }
                i.isNullable = n["NULLABLE"] === "Y";
                i.isUnique = r.length > 0 && !s;
                i.isGenerated = n["IDENTITY_COLUMN"] === "YES";
                if (i.isGenerated) {
                    i.generationStrategy = "increment";
                    i.default = undefined;
                }
                i.comment = "";
                if (n["VIRTUAL_COLUMN"] === "YES") {
                    i.generatedType = "VIRTUAL";
                    const t = this.selectTypeormMetadataSql({
                        table: e["TABLE_NAME"],
                        type: qy.MetadataTableType.GENERATED_COLUMN,
                        name: i.name
                    });
                    const n = await this.query(t.query, t.parameters);
                    if (n[0] && n[0].value) {
                        i.asExpression = n[0].value;
                    } else {
                        i.asExpression = "";
                    }
                }
                return i;
            }));
            const s = xy.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 = s.map(e => {
                const t = d.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
                return new Iy.TableUnique({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"])
                });
            });
            const i = xy.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 = i.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 wy.TableCheck({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    expression: e["SEARCH_CONDITION"]
                });
            });
            const o = xy.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 My.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 vy.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 Iy.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 $y.Query(a);
    }
    dropTableSql(e, t) {
        const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
        return new $y.Query(n);
    }
    createViewSql(e) {
        const t = e.materialized ? "MATERIALIZED " : "";
        if (typeof e.expression === "string") {
            return new $y.Query(`CREATE ${t}VIEW ${this.escapePath(e)} AS ${e.expression}`);
        } else {
            return new $y.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 ? qy.MetadataTableType.MATERIALIZED_VIEW : qy.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 $y.Query(`DROP ${t}VIEW ${this.escapePath(e)}`);
    }
    deleteViewDefinitionSql(e) {
        const t = e.materialized ? qy.MetadataTableType.MATERIALIZED_VIEW : qy.MetadataTableType.VIEW;
        return this.deleteTypeormMetadataSql({
            type: t,
            name: e.name
        });
    }
    createIndexSql(e, t) {
        const n = t.columnNames.map(e => `"${e}"`).join(", ");
        return new $y.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n})`);
    }
    dropIndexSql(e) {
        const t = Dy.InstanceChecker.isTableIndex(e) ? e.name : e;
        return new $y.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 $y.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
    }
    dropPrimaryKeySql(e) {
        if (!e.primaryColumns.length) throw new gy.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 $y.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${a}"`);
    }
    createUniqueConstraintSql(e, t) {
        const n = t.columnNames.map(e => `"` + e + `"`).join(", ");
        return new $y.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" UNIQUE (${n})`);
    }
    dropUniqueConstraintSql(e, t) {
        const n = Dy.InstanceChecker.isTableUnique(t) ? t.name : t;
        return new $y.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createCheckConstraintSql(e, t) {
        return new $y.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
    }
    dropCheckConstraintSql(e, t) {
        const n = Dy.InstanceChecker.isTableCheck(t) ? t.name : t;
        return new $y.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 $y.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = Dy.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new $y.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 gy.TypeORMError(`oracle driver does not support change table comment.`);
    }
}

Ty.OracleQueryRunner = OracleQueryRunner;

Object.defineProperty(Ey, "__esModule", {
    value: true
});

Ey.OracleDriver = void 0;

const Uy = ce();

const By = Mt();

const jy = Ty;

const Fy = xd;

const ky = exports.PlatformTools;

const Qy = cm;

const Vy = zn;

const Ky = Dc;

const Wy = Bi;

const Hy = exports.error;

const Gy = exports.InstanceChecker;

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 = Vy.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
        this.schema = Vy.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 Uy.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 Qy.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new jy.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, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            if (r.has(s)) {
                return this.parametersPrefix + r.get(s);
            }
            const i = t[s];
            if (n) {
                return i.map(e => {
                    a.push(e);
                    return this.createParameter(s, a.length - 1);
                }).join(", ");
            }
            if (typeof i === "function") {
                return i();
            }
            if (typeof i === "boolean") {
                return i ? "1" : "0";
            }
            a.push(i);
            r.set(s, a.length);
            return this.createParameter(s, 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 (Gy.InstanceChecker.isTable(e) || Gy.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 (Gy.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 (Gy.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 = Wy.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('${Fy.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 Fy.DateUtils.mixedDateToDate(e);
        } else if (t.type === "simple-array") {
            return Fy.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return Fy.DateUtils.simpleJsonToString(e);
        } else if (t.type === "json") {
            return Fy.DateUtils.simpleJsonToString(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? Wy.ApplyValueTransformers.transformFrom(t.transformer, e) : e;
        if (t.type === Boolean) {
            e = !!e;
        } else if (t.type === "date") {
            e = Fy.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = Fy.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 = Fy.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "simple-array") {
            e = Fy.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = Fy.DateUtils.stringToSimpleJson(e);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = Wy.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 Hy.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) {
                Ky.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 || ky.PlatformTools.load("oracledb");
            this.oracle = e;
        } catch (e) {
            throw new By.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, Vy.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;
        });
    }
}

Ey.OracleDriver = OracleDriver;

var Yy = {};

var zy = {};

var Jy = {};

Object.defineProperty(Jy, "__esModule", {
    value: true
});

Jy.AbstractSqliteQueryRunner = void 0;

const Xy = we();

const Zy = iu;

const eE = su;

const tE = ou;

const nE = cu;

const aE = lm;

const rE = Rm;

const sE = uu;

const iE = Cm;

const oE = Dc;

const cE = hu;

const lE = exports.error;

const uE = $m;

const hE = exports.InstanceChecker;

class AbstractSqliteQueryRunner extends iE.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 lE.TypeORMError(`Transactions aren't supported by ${this.connection.driver.options.type}.`);
        if (this.isTransactionActive && this.driver.transactionSupport === "simple") throw new lE.TransactionAlreadyStartedError;
        if (e && e !== "READ UNCOMMITTED" && e !== "SERIALIZABLE") throw new lE.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 Xy.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 Xy.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 lE.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 lE.TypeORMError(`This driver does not support table schemas`);
    }
    async getCurrentSchema() {
        return Promise.resolve(undefined);
    }
    async hasTable(e) {
        const t = hE.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 = hE.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 s = [];
        if (t) {
            const t = await this.hasTable(e);
            if (t) return Promise.resolve();
        }
        r.push(this.createTableSql(e, n));
        s.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));
                s.push(this.dropIndexSql(t));
            });
        }
        const i = e.columns.filter(e => e.generatedType && e.asExpression);
        for (const t of i) {
            const n = this.insertTypeormMetadataSql({
                table: e.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const a = this.deleteTypeormMetadataSql({
                table: e.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(n);
            s.push(a);
        }
        await this.executeQueries(r, s);
    }
    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 s = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const i = [];
        const o = [];
        if (a) {
            s.indices.forEach(e => {
                i.push(this.dropIndexSql(e));
                o.push(this.createIndexSql(s, e));
            });
        }
        i.push(this.dropTableSql(s, t));
        o.push(this.createTableSql(s, r));
        const c = s.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of c) {
            const t = this.deleteTypeormMetadataSql({
                table: s.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const n = this.insertTypeormMetadataSql({
                table: s.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            i.push(t);
            o.push(n);
        }
        await this.executeQueries(i, 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 = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        a.name = t;
        const r = new rE.Query(`ALTER TABLE ${this.escapePath(n.name)} RENAME TO ${this.escapePath(t)}`);
        const s = new rE.Query(`ALTER TABLE ${this.escapePath(t)} RENAME TO ${this.escapePath(n.name)}`);
        await this.executeQueries(r, s);
        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 = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        return this.addColumns(n, [ t ]);
    }
    async addColumns(e, t) {
        const n = hE.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 = 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 lE.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s = undefined;
        if (hE.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        return this.changeColumn(a, r, s);
    }
    async changeColumn(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 lE.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 = hE.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 = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = hE.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new lE.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        await this.dropColumns(n, [ a ]);
    }
    async dropColumns(e, t) {
        const n = hE.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        t.forEach(e => {
            const t = hE.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 = hE.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 = hE.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 = hE.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 = 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 lE.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
        await this.dropUniqueConstraints(n, [ a ]);
    }
    async dropUniqueConstraints(e, t) {
        const n = hE.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 = hE.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 = 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 lE.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        await this.dropCheckConstraints(n, [ a ]);
    }
    async dropCheckConstraints(e, t) {
        const n = hE.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 lE.TypeORMError(`Sqlite does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new lE.TypeORMError(`Sqlite does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new lE.TypeORMError(`Sqlite does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new lE.TypeORMError(`Sqlite does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        await this.createForeignKeys(e, [ t ]);
    }
    async createForeignKeys(e, t) {
        const n = hE.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 = 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 lE.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        await this.dropForeignKeys(e, [ a ]);
    }
    async dropForeignKeys(e, t) {
        const n = hE.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 = 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 lE.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = await this.query(r);
            await Promise.all(s.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" = '${uE.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 aE.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 s = 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(s("table"))).reduce((e, t) => [ ...e, ...t ], []).filter(Boolean);
            n = (await Promise.all(s("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 s = new eE.Table({
                name: t,
                withoutRowid: r
            });
            const [i, 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);
                }
            }
            s.columns = await Promise.all(i.map(async e => {
                const t = new Zy.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: s.name,
                        type: uE.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 = oE.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 = oE.OrmUtils.uniq(c, e => e["id"]);
            s.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 nE.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 = s.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 sE.TableUnique({
                    name: r ? r.name : this.connection.namingStrategy.uniqueConstraintName(s, a),
                    columnNames: a
                });
            });
            s.uniques = await Promise.all(g);
            let N;
            const b = /CONSTRAINT "([^"]*)" CHECK ?(\(.*?\))([,]|[)]$)/g;
            while ((N = b.exec(a)) !== null) {
                s.checks.push(new cE.TableCheck({
                    name: N[1],
                    expression: N[2]
                }));
            }
            const A = 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 i = o.find(e => e["name"] === t);
                const c = await this.query(`PRAGMA index_info("${i["name"]}")`);
                const l = c.sort((e, t) => parseInt(e["seqno"]) - parseInt(t["seqno"])).map(e => e["name"]);
                const u = `${e["database"] ? `${e["database"]}.` : ""}${i["name"]}`;
                const h = i["unique"] === "1" || i["unique"] === 1;
                return new tE.TableIndex({
                    table: s,
                    name: u,
                    columnNames: l,
                    isUnique: h,
                    where: r ? r[1] : undefined
                });
            });
            const C = await Promise.all(A);
            s.indices = C.filter(e => !!e);
            return s;
        }));
    }
    createTableSql(e, t, n) {
        const a = e.columns.filter(e => e.isPrimary);
        const r = a.find(e => e.isGenerated && e.generationStrategy === "increment");
        const s = a.length > 1;
        if (s && r) throw new lE.TypeORMError(`Sqlite does not support AUTOINCREMENT on composite primary key`);
        const i = e.columns.map(e => this.buildCreateColumnSql(e, s)).join(", ");
        const [o] = this.splitTablePath(e.name);
        let c = `CREATE TABLE ${this.escapePath(e.name)} (${i}`;
        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 sE.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 rE.Query(c);
    }
    dropTableSql(e, t) {
        const n = hE.InstanceChecker.isTable(e) ? e.name : e;
        const a = t ? `DROP TABLE IF EXISTS ${this.escapePath(n)}` : `DROP TABLE ${this.escapePath(n)}`;
        return new rE.Query(a);
    }
    createViewSql(e) {
        if (typeof e.expression === "string") {
            return new rE.Query(`CREATE VIEW "${e.name}" AS ${e.expression}`);
        } else {
            return new rE.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: uE.MetadataTableType.VIEW,
            name: e.name,
            value: t
        });
    }
    dropViewSql(e) {
        const t = hE.InstanceChecker.isView(e) ? e.name : e;
        return new rE.Query(`DROP VIEW "${t}"`);
    }
    deleteViewDefinitionSql(e) {
        const t = hE.InstanceChecker.isView(e) ? e.name : e;
        return this.deleteTypeormMetadataSql({
            type: uE.MetadataTableType.VIEW,
            name: t
        });
    }
    createIndexSql(e, t) {
        const n = t.columnNames.map(e => `"${e}"`).join(", ");
        const [a, r] = this.splitTablePath(e.name);
        return new rE.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX ${a ? `"${a}".` : ""}${this.escapePath(t.name)} ON "${r}" (${n}) ${t.where ? "WHERE " + t.where : ""}`);
    }
    dropIndexSql(e) {
        const t = hE.InstanceChecker.isTableIndex(e) ? e.name : e;
        return new rE.Query(`DROP INDEX ${this.escapePath(t)}`);
    }
    buildCreateColumnSql(e, t) {
        let n = '"' + e.name + '"';
        if (hE.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 [s, i] = this.splitTablePath(e.name);
        const [, o] = this.splitTablePath(t.name);
        e.name = i = `${s ? `${s}.` : ""}temporary_${i}`;
        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 s = t.columns.filter(e => !e.generatedType).map(e => `"${e.name}"`);
            if (s.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 (s.length > n.length) {
                s = t.columns.filter(t => !t.generatedType && e.columns.find(e => e.name === t.name)).map(e => `"${e.name}"`);
            }
            a.push(new rE.Query(`INSERT INTO ${this.escapePath(e.name)}(${n.join(", ")}) SELECT ${s.join(", ")} FROM ${this.escapePath(t.name)}`));
            r.push(new rE.Query(`INSERT INTO ${this.escapePath(t.name)}(${s.join(", ")}) SELECT ${n.join(", ")} FROM ${this.escapePath(e.name)}`));
        }
        a.push(this.dropTableSql(t));
        r.push(this.createTableSql(t, true));
        a.push(new rE.Query(`ALTER TABLE ${this.escapePath(e.name)} RENAME TO ${this.escapePath(o)}`));
        r.push(new rE.Query(`ALTER TABLE ${this.escapePath(t.name)} RENAME TO ${this.escapePath(i)}`));
        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: uE.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const s = this.insertTypeormMetadataSql({
                table: t.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            a.push(n);
            r.push(s);
        });
        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: uE.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const s = this.deleteTypeormMetadataSql({
                table: e.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            a.push(n);
            r.push(s);
        });
        e.columns.filter(e => e.generatedType && e.asExpression).forEach(n => {
            const s = t.columns.find(e => e.name === n.name && e.generatedType && n.generatedType && e.asExpression !== n.asExpression);
            if (!s) return;
            const i = this.deleteTypeormMetadataSql({
                table: t.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: s.name
            });
            const o = this.insertTypeormMetadataSql({
                table: e.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: n.name,
                value: n.asExpression
            });
            a.push(i);
            a.push(o);
            const c = this.insertTypeormMetadataSql({
                table: e.name,
                type: uE.MetadataTableType.GENERATED_COLUMN,
                name: s.name,
                value: s.asExpression
            });
            const l = this.deleteTypeormMetadataSql({
                table: t.name,
                type: uE.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 = hE.InstanceChecker.isTable(e) || hE.InstanceChecker.isView(e) ? e.name : e;
        return n.replace(/^\.+|\.+$/g, "").split(".").map(e => t ? e : `"${e}"`).join(".");
    }
    changeTableComment(e, t) {
        throw new lE.TypeORMError(`sqlit driver does not support change comment.`);
    }
}

Jy.AbstractSqliteQueryRunner = AbstractSqliteQueryRunner;

var dE;

function pE() {
    if (dE) return zy;
    dE = 1;
    Object.defineProperty(zy, "__esModule", {
        value: true
    });
    zy.SqliteQueryRunner = void 0;
    const e = ce();
    const t = pn();
    const n = Dn();
    const a = Lm;
    const r = _m;
    const s = ic;
    const i = Jy;
    let o = class SqliteQueryRunner extends i.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, i, 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, i, this);
            await h.broadcast("BeforeQuery", r, i);
            const p = new s.BroadcasterResult;
            return new Promise(async (e, n) => {
                try {
                    const s = 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, i, g);
                        } else {
                            await d.all(r, i, 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 - s;
                        if (u && g > u) c.logger.logQuerySlow(g, r, i, T);
                        if (d) {
                            c.logger.logQueryError(d, r, i, T);
                            h.broadcastAfterQueryEvent(p, r, i, false, undefined, undefined, d);
                            return n(new t.QueryFailedError(r, i, d));
                        } else {
                            const t = new a.QueryResult;
                            if (m) {
                                t.raw = this["lastID"];
                            } else {
                                t.raw = f;
                            }
                            h.broadcastAfterQueryEvent(p, r, i, 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();
                }
            });
        }
    };
    zy.SqliteQueryRunner = o;
    return zy;
}

var mE = {};

Object.defineProperty(mE, "__esModule", {
    value: true
});

mE.AbstractSqliteDriver = void 0;

const fE = xd;

const yE = cm;

const EE = Dc;

const TE = Bi;

const gE = zn;

const NE = exports.error;

const bE = exports.InstanceChecker;

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 = gE.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 yE.RdbmsSchemaBuilder(this.connection);
    }
    preparePersistentValue(e, t) {
        if (t.transformer) e = TE.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 fE.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return fE.DateUtils.mixedDateToTimeString(e);
        } else if (t.type === "datetime" || t.type === Date) {
            return fE.DateUtils.mixedDateToUtcDatetimeString(e);
        } else if (t.type === "json" || t.type === "simple-json") {
            return fE.DateUtils.simpleJsonToString(e);
        } else if (t.type === "simple-array") {
            return fE.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-enum") {
            return fE.DateUtils.simpleEnumToString(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? TE.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 = fE.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = fE.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = fE.DateUtils.mixedTimeToString(e);
        } else if (t.type === "json" || t.type === "simple-json") {
            e = fE.DateUtils.stringToSimpleJson(e);
        } else if (t.type === "simple-array") {
            e = fE.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-enum") {
            e = fE.DateUtils.stringToSimpleEnum(e, t);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = TE.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 fE.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 s = t[r];
            if (n) {
                return s.map(e => {
                    a.push(e);
                    return this.createParameter(r, a.length - 1);
                }).join(", ");
            }
            if (typeof s === "function") {
                return s();
            } else if (typeof s === "number") {
                return String(s);
            }
            if (typeof s === "boolean") {
                a.push(+s);
                return this.createParameter(r, a.length - 1);
            }
            if (s instanceof Date) {
                a.push(fE.DateUtils.mixedDateToUtcDatetimeString(s));
                return this.createParameter(r, a.length - 1);
            }
            a.push(s);
            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 (bE.InstanceChecker.isTable(e) || bE.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 (bE.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 (bE.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 s;
            if (r.generationStrategy === "increment" && t) {
                s = t - a + n + 1;
            }
            if (!s) return e;
            return EE.OrmUtils.mergeDeep(e, r.createValueMap(s));
        }, {});
        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 && !EE.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 NE.TypeORMError("Do not use AbstractSqlite directly, it has to be used with one of the sqlite drivers");
    }
    loadDependencies() {}
}

mE.AbstractSqliteDriver = AbstractSqliteDriver;

Object.defineProperty(Yy, "__esModule", {
    value: true
});

Yy.SqliteDriver = void 0;

const AE = e.require$$0;

const CE = AE.__importDefault(v.default);

const RE = AE.__importDefault(C.default);

const SE = Mt();

const wE = pE();

const OE = exports.PlatformTools;

const ME = mE;

const vE = sd();

class SqliteDriver extends ME.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 wE.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, vE.filepathToName)(n);
        const r = (0, vE.isAbsolute)(n) ? n : RE.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 || OE.PlatformTools.load("sqlite3");
            this.sqlite = e.verbose();
        } catch (e) {
            throw new SE.DriverPackageNotInstalledError("SQLite", "sqlite3");
        }
    }
    async createDatabaseDirectory(e) {
        await CE.default.mkdir(RE.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 RE.default.dirname((0, vE.isAbsolute)(e) ? e : RE.default.join(process.cwd(), e));
    }
}

Yy.SqliteDriver = SqliteDriver;

var IE = {};

var PE = {};

Object.defineProperty(PE, "__esModule", {
    value: true
});

PE.CordovaQueryRunner = void 0;

const LE = exports.error;

const _E = pn();

const DE = Dn();

const xE = Lm;

const $E = _m;

const qE = ic;

const UE = Jy;

class CordovaQueryRunner extends UE.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new $E.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 DE.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new qE.BroadcasterResult;
        const s = Date.now();
        try {
            const i = 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 - s;
            this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, i, undefined);
            if (o && l > o) {
                this.driver.connection.logger.logQuerySlow(l, e, t, this);
            }
            const u = new xE.QueryResult;
            if (e.substr(0, 11) === "INSERT INTO") {
                u.raw = i.insertId;
            } else {
                const e = [];
                for (let t = 0; t < i.rows.length; t++) {
                    e.push(i.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 _E.QueryFailedError(e, t, n);
        } finally {
            await r.wait();
        }
    }
    async startTransaction() {
        throw new LE.TypeORMError("Transactions are not supported by the Cordova driver");
    }
    async commitTransaction() {
        throw new LE.TypeORMError("Transactions are not supported by the Cordova driver");
    }
    async rollbackTransaction() {
        throw new LE.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}"` + "=?");
    }
}

PE.CordovaQueryRunner = CordovaQueryRunner;

Object.defineProperty(IE, "__esModule", {
    value: true
});

IE.CordovaDriver = void 0;

const BE = mE;

const jE = PE;

const FE = Mt();

class CordovaDriver extends BE.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 jE.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 FE.DriverPackageNotInstalledError("Cordova-SQLite", "cordova-sqlite-storage");
        }
    }
}

IE.CordovaDriver = CordovaDriver;

var kE = {};

var QE = {};

Object.defineProperty(QE, "__esModule", {
    value: true
});

QE.ReactNativeQueryRunner = void 0;

const VE = pn();

const KE = Dn();

const WE = Lm;

const HE = _m;

const GE = ic;

const YE = Jy;

class ReactNativeQueryRunner extends YE.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new HE.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 KE.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new GE.BroadcasterResult;
        const s = Date.now();
        return new Promise(async (i, o) => {
            try {
                a.executeSql(e, t, async a => {
                    const o = this.driver.options.maxQueryExecutionTime;
                    const c = Date.now();
                    const l = c - s;
                    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 WE.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) {
                        i(u);
                    } else {
                        i(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 VE.QueryFailedError(e, t, n));
                });
            } catch (e) {
                o(e);
            } finally {
                await r.wait();
            }
        });
    }
    parametrize(e, t = 0) {
        return Object.keys(e).map((e, t) => `"${e}"` + "=?");
    }
}

QE.ReactNativeQueryRunner = ReactNativeQueryRunner;

Object.defineProperty(kE, "__esModule", {
    value: true
});

kE.ReactNativeDriver = void 0;

const zE = xd;

const JE = cm;

const XE = Dc;

const ZE = Bi;

const eT = exports.error;

const tT = exports.InstanceChecker;

const nT = QE;

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 nT.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 JE.RdbmsSchemaBuilder(this.connection);
    }
    preparePersistentValue(e, t) {
        if (t.transformer) e = ZE.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 zE.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return zE.DateUtils.mixedDateToTimeString(e);
        } else if (t.type === "datetime" || t.type === Date) {
            return zE.DateUtils.mixedDateToUtcDatetimeString(e);
        } else if (t.type === "simple-array") {
            return zE.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return zE.DateUtils.simpleJsonToString(e);
        } else if (t.type === "simple-enum") {
            return zE.DateUtils.simpleEnumToString(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? ZE.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 = zE.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = zE.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = zE.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array") {
            e = zE.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = zE.DateUtils.stringToSimpleJson(e);
        } else if (t.type === "simple-enum") {
            e = zE.DateUtils.stringToSimpleEnum(e, t);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = ZE.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 zE.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 s = t[r];
            if (n) {
                return s.map(e => {
                    a.push(e);
                    return this.createParameter(r, a.length - 1);
                }).join(", ");
            }
            if (typeof s === "function") {
                return s();
            } else if (typeof s === "number") {
                return String(s);
            }
            if (typeof s === "boolean") {
                a.push(+s);
                return this.createParameter(r, a.length - 1);
            }
            if (s instanceof Date) {
                a.push(zE.DateUtils.mixedDateToUtcDatetimeString(s));
                return this.createParameter(r, a.length - 1);
            }
            a.push(s);
            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 (tT.InstanceChecker.isTable(e) || tT.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 (tT.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 (tT.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 s;
            if (r.generationStrategy === "increment" && t) {
                s = t - a + n + 1;
            }
            if (!s) return e;
            return XE.OrmUtils.mergeDeep(e, r.createValueMap(s));
        }, {});
        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 && !XE.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 eT.DriverPackageNotInstalledError("React-Native", "react-native-sqlite-storage");
        }
    }
}

kE.ReactNativeDriver = ReactNativeDriver;

var aT = {};

var rT = {};

Object.defineProperty(rT, "__esModule", {
    value: true
});

rT.NativescriptQueryRunner = void 0;

const sT = pn();

const iT = Dn();

const oT = Lm;

const cT = _m;

const lT = Jy;

class NativescriptQueryRunner extends lT.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new cT.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 iT.QueryRunnerAlreadyReleasedError;
        }
        const a = this.driver.connection;
        const r = await this.connect();
        return new Promise(async (s, i) => {
            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);
                    i(new sT.QueryFailedError(e, t, r));
                }
                const p = new oT.QueryResult;
                p.raw = c;
                if (!o && Array.isArray(c)) {
                    p.records = c;
                }
                if (n) {
                    s(p);
                } else {
                    s(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}"` + "=?");
    }
}

rT.NativescriptQueryRunner = NativescriptQueryRunner;

Object.defineProperty(aT, "__esModule", {
    value: true
});

aT.NativescriptDriver = void 0;

const uT = mE;

const hT = rT;

const dT = Mt();

class NativescriptDriver extends uT.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 hT.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 dT.DriverPackageNotInstalledError("Nativescript", "nativescript-sqlite");
        }
    }
}

aT.NativescriptDriver = NativescriptDriver;

var pT = {};

var mT = {};

Object.defineProperty(mT, "__esModule", {
    value: true
});

mT.SqljsQueryRunner = void 0;

const fT = pn();

const yT = Dn();

const ET = Lm;

const TT = _m;

const gT = ic;

const NT = Jy;

class SqljsQueryRunner extends NT.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.isDirty = false;
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new TT.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 yT.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 s = new gT.BroadcasterResult;
        const i = 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 - i;
            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(s, e, t, true, u, h, undefined);
            const d = new ET.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(s, e, t, false, undefined, undefined, n);
            throw new fT.QueryFailedError(e, t, n);
        } finally {
            await s.wait();
        }
    }
}

mT.SqljsQueryRunner = SqljsQueryRunner;

Object.defineProperty(pT, "__esModule", {
    value: true
});

pT.SqljsDriver = void 0;

const bT = mE;

const AT = mT;

const CT = Mt();

const RT = Wt();

const ST = exports.PlatformTools;

const wT = Dc;

const OT = exports.error;

class SqljsDriver extends bT.AbstractSqliteDriver {
    constructor(e) {
        super(e);
        if (this.options.autoSave && !this.options.location && !this.options.autoSaveCallback) {
            throw new RT.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 AT.SqljsQueryRunner(this);
        return this.queryRunner;
    }
    async load(e, t = true) {
        if (typeof e === "string") {
            if (ST.PlatformTools.type === "node") {
                if (ST.PlatformTools.fileExist(e)) {
                    const t = ST.PlatformTools.readFileSync(e);
                    return this.createDatabaseConnectionWithImport(t);
                } else if (t) {
                    throw new OT.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 OT.TypeORMError(`localforage is not defined - please import localforage.js into your site`);
                    }
                } else {
                    n = ST.PlatformTools.getGlobalVariable().localStorage.getItem(e);
                }
                if (n != null) {
                    return this.createDatabaseConnectionWithImport(JSON.parse(n));
                } else if (t) {
                    throw new OT.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 OT.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 (ST.PlatformTools.type === "node") {
            try {
                const e = Buffer.from(this.databaseConnection.export());
                await ST.PlatformTools.writeFile(t, e);
            } catch (e) {
                throw new OT.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 OT.TypeORMError(`localforage is not defined - please import localforage.js into your site`);
                }
            } else {
                ST.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 wT.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 (ST.PlatformTools.type === "browser") {
            const e = this.options.driver || window.SQL;
            this.sqlite = e;
        } else {
            try {
                const e = this.options.driver || ST.PlatformTools.load("sql.js");
                this.sqlite = e;
            } catch (e) {
                throw new CT.DriverPackageNotInstalledError("sql.js", "sql.js");
            }
        }
    }
}

pT.SqljsDriver = SqljsDriver;

var MT = {};

var vT = {};

Object.defineProperty(vT, "__esModule", {
    value: true
});

vT.MysqlQueryRunner = void 0;

const IT = exports.error;

const PT = pn();

const LT = Dn();

const _T = we();

const DT = Cm;

const xT = Lm;

const $T = su;

const qT = iu;

const UT = cu;

const BT = ou;

const jT = uu;

const FT = lm;

const kT = _m;

const QT = ic;

const VT = exports.InstanceChecker;

const KT = Dc;

const WT = Ti;

const HT = Rm;

const GT = $m;

class MysqlQueryRunner extends DT.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new kT.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 _T.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 _T.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 LT.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new QT.BroadcasterResult;
        const s = Date.now();
        return new Promise(async (i, 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 - s;
                    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 PT.QueryFailedError(e, t, a));
                    }
                    this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, h, c, undefined);
                    const d = new xT.QueryResult;
                    d.raw = c;
                    try {
                        d.records = Array.from(c);
                    } catch {}
                    if (c?.hasOwnProperty("affectedRows")) {
                        d.affected = c.affectedRows;
                    }
                    if (n) {
                        i(d);
                    } else {
                        i(d.raw);
                    }
                });
            } catch (e) {
                o(e);
            } finally {
                await r.wait();
            }
        });
    }
    stream(e, t, n, a) {
        if (this.isReleased) throw new LT.QueryRunnerAlreadyReleasedError;
        return new Promise(async (r, s) => {
            try {
                const s = await this.connect();
                this.driver.connection.logger.logQuery(e, t, this);
                const i = s.query(e, t);
                if (n) i.on("end", n);
                if (a) i.on("error", a);
                r(i.stream());
            } catch (e) {
                s(e);
            }
        });
    }
    async getDatabases() {
        return Promise.resolve([]);
    }
    async getSchemas(e) {
        throw new IT.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 IT.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 = VT.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 s = await this.query(r);
        return s.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 HT.Query(n), new HT.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 HT.Query(n), new HT.Query(a));
    }
    async createSchema(e, t) {
        throw new IT.TypeORMError(`Schema create queries are not supported by MySql driver.`);
    }
    async dropSchema(e, t) {
        throw new IT.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 s = e.columns.filter(e => e.generatedType && e.asExpression);
        for (const t of s) {
            const n = await this.getCurrentDatabase();
            const s = this.insertTypeormMetadataSql({
                schema: n,
                table: e.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const i = this.deleteTypeormMetadataSql({
                schema: n,
                table: e.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            a.push(s);
            r.push(i);
        }
        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 s = await this.getCachedTable(r);
        const i = [];
        const o = [];
        if (n) s.foreignKeys.forEach(e => i.push(this.dropForeignKeySql(s, e)));
        s.indices.forEach(e => i.push(this.dropIndexSql(s, e)));
        i.push(this.dropTableSql(s));
        o.push(this.createTableSql(s, a));
        const c = s.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of c) {
            const t = await this.getCurrentDatabase();
            const n = this.deleteTypeormMetadataSql({
                schema: t,
                table: s.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const a = this.insertTypeormMetadataSql({
                schema: t,
                table: s.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            i.push(n);
            o.push(a);
        }
        await this.executeQueries(i, 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 = VT.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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {database: i} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new HT.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(s)}`));
        a.push(new HT.Query(`RENAME TABLE ${this.escapePath(s)} TO ${this.escapePath(r)}`));
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(r, e.columnNames);
            if (e.name !== t) return;
            const i = e.columnNames.map(e => `\`${e}\``).join(", ");
            const o = this.connection.namingStrategy.indexName(s, 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 HT.Query(`ALTER TABLE ${this.escapePath(s)} DROP INDEX \`${e.name}\`, ADD ${c}INDEX \`${o}\` (${i})${l}`));
            a.push(new HT.Query(`ALTER TABLE ${this.escapePath(s)} DROP INDEX \`${o}\`, ADD ${c}INDEX \`${e.name}\` (${i})${l}`));
            e.name = o;
        });
        s.foreignKeys.forEach(e => {
            const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            if (e.name !== t) return;
            const i = e.columnNames.map(e => `\`${e}\``).join(", ");
            const o = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
            const c = this.connection.namingStrategy.foreignKeyName(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            let l = `ALTER TABLE ${this.escapePath(s)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${c}\` FOREIGN KEY (${i}) ` + `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(s)} DROP FOREIGN KEY \`${c}\`, ADD CONSTRAINT \`${e.name}\` FOREIGN KEY (${i}) ` + `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 HT.Query(l));
            a.push(new HT.Query(u));
            e.name = c;
        });
        await this.executeQueries(n, a);
        r.name = s.name;
        this.replaceCachedTable(r, s);
    }
    async changeTableComment(e, t) {
        const n = [];
        const a = [];
        const r = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        t = this.escapeComment(t);
        const s = this.escapeComment(r.comment);
        if (t === s) {
            return;
        }
        const i = r.clone();
        n.push(new HT.Query(`ALTER TABLE ${this.escapePath(i)} COMMENT ${t}`));
        a.push(new HT.Query(`ALTER TABLE ${this.escapePath(r)} COMMENT ${s}`));
        await this.executeQueries(n, a);
        r.comment = i.comment;
        this.replaceCachedTable(r, i);
    }
    async addColumn(e, t) {
        const n = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        const i = a.primaryColumns.length > 0;
        r.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t, i, false)}`));
        s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${t.name}\``));
        if (t.isPrimary && i) {
            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 HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
            }
            const i = a.primaryColumns;
            let o = i.map(e => `\`${e.name}\``).join(", ");
            r.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
            i.push(t);
            o = i.map(e => `\`${e.name}\``).join(", ");
            r.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            if (e) {
                const a = e.clone();
                a.isGenerated = false;
                a.generationStrategy = undefined;
                r.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
                s.push(new HT.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: GT.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const i = this.deleteTypeormMetadataSql({
                schema: e,
                table: n.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(a);
            s.push(i);
        }
        const o = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (o) {
            r.push(this.createIndexSql(n, o));
            s.push(this.dropIndexSql(n, o));
        } else if (t.isUnique) {
            const e = new BT.TableIndex({
                name: this.connection.namingStrategy.indexName(n, [ t.name ]),
                columnNames: [ t.name ],
                isUnique: true
            });
            a.indices.push(e);
            a.uniques.push(new jT.TableUnique({
                name: e.name,
                columnNames: e.columnNames
            }));
            r.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${e.name}\` (\`${t.name}\`)`));
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${e.name}\``));
        }
        await this.executeQueries(r, s);
        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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = VT.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new IT.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s = undefined;
        if (VT.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        await this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = VT.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!o) throw new IT.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) {
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` \`${n.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
                i.push(new HT.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}` : "";
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\`, ADD ${u}INDEX \`${l}\` (${c})${h}`));
                    i.push(new HT.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}`;
                    s.push(new HT.Query(h));
                    i.push(new HT.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)) {
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(n, true)}`));
                i.push(new HT.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: GT.MetadataTableType.GENERATED_COLUMN,
                        name: o.name
                    });
                    const n = this.insertTypeormMetadataSql({
                        schema: e,
                        table: a.name,
                        type: GT.MetadataTableType.GENERATED_COLUMN,
                        name: o.name,
                        value: o.asExpression
                    });
                    s.push(t);
                    i.push(n);
                } else if (!o.generatedType && n.generatedType) {
                    const e = await this.getCurrentDatabase();
                    const t = this.insertTypeormMetadataSql({
                        schema: e,
                        table: a.name,
                        type: GT.MetadataTableType.GENERATED_COLUMN,
                        name: n.name,
                        value: n.asExpression
                    });
                    const r = this.deleteTypeormMetadataSql({
                        schema: e,
                        table: a.name,
                        type: GT.MetadataTableType.GENERATED_COLUMN,
                        name: n.name
                    });
                    s.push(t);
                    i.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: GT.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: GT.MetadataTableType.GENERATED_COLUMN
                    }).andWhere("`name` = :name", {
                        name: n.name
                    }).andWhere("`schema` = :schema", {
                        schema: e
                    }).andWhere("`table` = :table", {
                        table: a.name
                    }).getQueryAndParameters();
                    s.push(new HT.Query(t[0], t[1]));
                    i.push(new HT.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;
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
                    i.push(new HT.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(", ");
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
                    i.push(new HT.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(", ");
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${o})`));
                    i.push(new HT.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(", ");
                        s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
                        i.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
                    }
                }
                if (e) {
                    const t = e.clone();
                    t.isGenerated = false;
                    t.generationStrategy = undefined;
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
                    i.push(new HT.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 BT.TableIndex({
                        name: this.connection.namingStrategy.indexName(a, [ n.name ]),
                        columnNames: [ n.name ],
                        isUnique: true
                    });
                    r.indices.push(e);
                    r.uniques.push(new jT.TableUnique({
                        name: e.name,
                        columnNames: e.columnNames
                    }));
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
                    i.push(new HT.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);
                    s.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
                    i.push(new HT.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
                }
            }
        }
        await this.executeQueries(s, i);
        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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = VT.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new IT.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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;
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
                i.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
            }
            const t = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
            i.push(new HT.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(", ");
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${e})`));
                i.push(new HT.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;
                s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
                i.push(new HT.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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${o}\``));
            i.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${o}\` (\`${a.name}\`)`));
        }
        s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${a.name}\``));
        i.push(new HT.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: GT.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const r = this.insertTypeormMetadataSql({
                schema: e,
                table: n.name,
                type: GT.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(t);
            i.push(r);
        }
        await this.executeQueries(s, i);
        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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = this.createPrimaryKeySql(n, t);
        const s = this.dropPrimaryKeySql(n);
        await this.executeQueries(r, s);
        a.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        this.replaceCachedTable(n, a);
    }
    async updatePrimaryKeys(e, t) {
        const n = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = t.map(e => e.name);
        const s = [];
        const i = [];
        const o = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
        if (o) {
            const e = o.clone();
            e.isGenerated = false;
            e.generationStrategy = undefined;
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(e, true)}`));
            i.push(new HT.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(", ");
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            i.push(new HT.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(", ");
        s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${l})`));
        i.push(new HT.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;
            s.push(new HT.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(u, true)}`));
            i.push(new HT.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(s, i);
        this.replaceCachedTable(n, a);
    }
    async dropPrimaryKey(e) {
        const t = VT.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 IT.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async createUniqueConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraint(e, t) {
        throw new IT.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async createCheckConstraint(e, t) {
        throw new IT.TypeORMError(`MySql does not support check constraints.`);
    }
    async createCheckConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support check constraints.`);
    }
    async dropCheckConstraint(e, t) {
        throw new IT.TypeORMError(`MySql does not support check constraints.`);
    }
    async dropCheckConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support check constraints.`);
    }
    async createExclusionConstraint(e, t) {
        throw new IT.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new IT.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new IT.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = VT.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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = VT.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new IT.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 = VT.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 = VT.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = VT.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new IT.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 IT.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 s = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
            const i = `SET FOREIGN_KEY_CHECKS = 1;`;
            await this.query(r);
            const o = await this.query(s);
            await Promise.all(o.map(e => this.query(e["query"])));
            await this.query(i);
            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\` = '${GT.MetadataTableType.VIEW}' ${a ? `AND (${a})` : ""}`;
        const s = await this.query(r);
        return s.map(e => {
            const t = new FT.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 s = 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 i = 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 (${s}) \`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 (${s}) \`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(i), 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 $T.Table;
            const a = p.find(t => t["SCHEMA_NAME"] === e["TABLE_SCHEMA"]);
            const r = a["COLLATION"];
            const s = a["CHARSET"];
            const i = e["TABLE_SCHEMA"] === t ? undefined : e["TABLE_SCHEMA"];
            n.database = e["TABLE_SCHEMA"];
            n.name = this.driver.buildTableName(e["TABLE_NAME"], undefined, i);
            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 i = this.connection.entityMetadatas.find(e => this.getTablePath(n) === this.getTablePath(e));
                const o = a.length > 0 && i && i.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 qT.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 && WT.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: GT.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"] === s ? 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 = KT.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 UT.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 = KT.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 BT.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 BT.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 BT.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 HT.Query(a);
    }
    dropTableSql(e) {
        return new HT.Query(`DROP TABLE ${this.escapePath(e)}`);
    }
    createViewSql(e) {
        if (typeof e.expression === "string") {
            return new HT.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
        } else {
            return new HT.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: GT.MetadataTableType.VIEW,
            schema: t,
            name: e.name,
            value: n
        });
    }
    dropViewSql(e) {
        return new HT.Query(`DROP VIEW ${this.escapePath(e)}`);
    }
    async deleteViewDefinitionSql(e) {
        const t = await this.getCurrentDatabase();
        const n = VT.InstanceChecker.isView(e) ? e.name : e;
        return this.deleteTypeormMetadataSql({
            type: GT.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 HT.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})${r}`);
    }
    dropIndexSql(e, t) {
        const n = VT.InstanceChecker.isTableIndex(t) ? t.name : t;
        return new HT.Query(`DROP INDEX \`${n}\` ON ${this.escapePath(e)}`);
    }
    createPrimaryKeySql(e, t) {
        const n = t.map(e => `\`${e}\``).join(", ");
        return new HT.Query(`ALTER TABLE ${this.escapePath(e)} ADD PRIMARY KEY (${n})`);
    }
    dropPrimaryKeySql(e) {
        return new HT.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 HT.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = VT.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new HT.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;
    }
}

vT.MysqlQueryRunner = MysqlQueryRunner;

Object.defineProperty(MT, "__esModule", {
    value: true
});

MT.MysqlDriver = void 0;

const YT = ce();

const zT = Mt();

const JT = zn;

const XT = vT;

const ZT = xd;

const eg = exports.PlatformTools;

const tg = cm;

const ng = Dc;

const ag = Bi;

const rg = exports.error;

const sg = Ti;

const ig = exports.InstanceChecker;

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 = JT.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 (sg.VersionUtils.isGreaterOrEqual(this.version, "10.0.5")) {
                this._isReturningSqlSupported.delete = true;
            }
            if (sg.VersionUtils.isGreaterOrEqual(this.version, "10.5.0")) {
                this._isReturningSqlSupported.insert = true;
            }
            if (sg.VersionUtils.isGreaterOrEqual(this.version, "10.2.0")) {
                this.cteCapabilities.enabled = true;
            }
            if (sg.VersionUtils.isGreaterOrEqual(this.version, "10.7.0")) {
                this.uuidColumnTypeSuported = true;
            }
        } else if (this.options.type === "mysql") {
            if (sg.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 YT.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 tg.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new XT.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 s = t[r];
            if (n) {
                return s.map(e => {
                    a.push(e);
                    return this.createParameter(r, a.length - 1);
                }).join(", ");
            }
            if (typeof s === "function") {
                return s();
            }
            a.push(s);
            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 (ig.InstanceChecker.isTable(e) || ig.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 (ig.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 (ig.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 = ag.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 ZT.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return ZT.DateUtils.mixedDateToTimeString(e);
        } else if (t.type === "json") {
            return JSON.stringify(e);
        } else if (t.type === "timestamp" || t.type === "datetime" || t.type === Date) {
            return ZT.DateUtils.mixedDateToDate(e);
        } else if (t.type === "simple-array") {
            return ZT.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return ZT.DateUtils.simpleJsonToString(e);
        } else if (t.type === "enum" || t.type === "simple-enum") {
            return "" + e;
        } else if (t.type === "set") {
            return ZT.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 ? ag.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 = ZT.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = ZT.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "json") {
            e = typeof e === "string" ? JSON.parse(e) : e;
        } else if (t.type === "time") {
            e = ZT.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array") {
            e = ZT.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = ZT.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 = ZT.DateUtils.stringToSimpleArray(e);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = ag.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" && !sg.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 `'${ZT.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 rg.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) {
                    ng.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 ng.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 && !ng.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 || eg.PlatformTools.load(e);
            this.mysql = n;
            if (Object.keys(this.mysql).length === 0) {
                throw new rg.TypeORMError(`'${e}' was found but it is empty. Falling back to '${t}'.`);
            }
        } catch (n) {
            try {
                this.mysql = eg.PlatformTools.load(t);
            } catch (t) {
                throw new zT.DriverPackageNotInstalledError("Mysql", e);
            }
        }
    }
    createConnectionOptions(e, t) {
        t = Object.assign({}, t, JT.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);
    }
}

MT.MysqlDriver = MysqlDriver;

var og = {};

var cg = {};

Object.defineProperty(cg, "__esModule", {
    value: true
});

cg.PostgresQueryRunner = void 0;

const lg = exports.error;

const ug = pn();

const hg = Dn();

const dg = we();

const pg = Cm;

const mg = Lm;

const fg = su;

const yg = hu;

const Eg = iu;

const Tg = du;

const gg = cu;

const Ng = ou;

const bg = uu;

const Ag = lm;

const Cg = _m;

const Rg = ic;

const Sg = exports.InstanceChecker;

const wg = Dc;

const Og = zn;

const Mg = Rm;

const vg = $m;

class PostgresQueryRunner extends pg.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.mode = t;
        this.broadcaster = new Cg.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 dg.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 dg.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 hg.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const r = new Rg.BroadcasterResult;
        try {
            const s = Date.now();
            const i = await a.query(e, t);
            const o = this.driver.options.maxQueryExecutionTime;
            const c = Date.now();
            const l = c - s;
            this.broadcaster.broadcastAfterQueryEvent(r, e, t, true, l, i, undefined);
            if (o && l > o) this.driver.connection.logger.logQuerySlow(l, e, t, this);
            const u = new mg.QueryResult;
            if (i) {
                if (i.hasOwnProperty("rows")) {
                    u.records = i.rows;
                }
                if (i.hasOwnProperty("rowCount")) {
                    u.affected = i.rowCount;
                }
                switch (i.command) {
                  case "DELETE":
                  case "UPDATE":
                    u.raw = [ i.rows, i.rowCount ];
                    break;

                  default:
                    u.raw = i.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 ug.QueryFailedError(e, t, n);
        } finally {
            await r.wait();
        }
    }
    async stream(e, t, n, a) {
        const r = this.driver.loadStreamDependency();
        if (this.isReleased) throw new hg.QueryRunnerAlreadyReleasedError;
        const s = await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        const i = s.query(new r(e, t));
        if (n) i.on("end", n);
        if (a) i.on("error", a);
        return i;
    }
    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 Mg.Query(n), new Mg.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 Mg.Query(n), new Mg.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 Mg.Query(a), new Mg.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 s = `CREATE SCHEMA "${a}"`;
        await this.executeQueries(new Mg.Query(r), new Mg.Query(s));
    }
    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 s = [];
        const i = e.columns.filter(e => e.type === "enum" || e.type === "simple-enum");
        const o = [];
        for (const t of i) {
            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));
                s.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 i = n[0];
            const o = this.insertTypeormMetadataSql({
                database: this.driver.database,
                schema: i,
                table: a,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const c = this.deleteTypeormMetadataSql({
                database: this.driver.database,
                schema: i,
                table: a,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(o);
            s.push(c);
        }
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.push(this.dropIndexSql(e, t));
            });
        }
        if (e.comment) {
            r.push(new Mg.Query("COMMENT ON TABLE " + this.escapePath(e) + " IS '" + e.comment + "'"));
            s.push(new Mg.Query("COMMENT ON TABLE " + this.escapePath(e) + " IS NULL"));
        }
        await this.executeQueries(r, s);
    }
    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 s = this.getTablePath(e);
        const i = await this.getCachedTable(s);
        const o = [];
        const c = [];
        if (a) {
            i.indices.forEach(e => {
                o.push(this.dropIndexSql(i, e));
                c.push(this.createIndexSql(i, e));
            });
        }
        if (n) i.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(i, e)));
        o.push(this.dropTableSql(i));
        c.push(this.createTableSql(i, r));
        const l = i.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of l) {
            const t = (await this.getTableNameWithSchema(i.name)).split(".");
            const n = t[1];
            const a = t[0];
            const r = this.deleteTypeormMetadataSql({
                database: this.driver.database,
                schema: a,
                table: n,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const s = this.insertTypeormMetadataSql({
                database: this.driver.database,
                schema: a,
                table: n,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: e.name,
                value: e.asExpression
            });
            o.push(r);
            c.push(s);
        }
        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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {schema: i, tableName: o} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new Mg.Query(`ALTER TABLE ${this.escapePath(r)} RENAME TO "${t}"`));
        a.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME TO "${o}"`));
        if (s.primaryColumns.length > 0 && !s.primaryColumns[0].primaryKeyConstraintName) {
            const e = s.primaryColumns.map(e => e.name);
            const t = this.connection.namingStrategy.primaryKeyName(r, e);
            const i = this.connection.namingStrategy.primaryKeyName(s, e);
            n.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${t}" TO "${i}"`));
            a.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${t}"`));
        }
        s.columns.map(e => {
            if (e.isGenerated && e.generationStrategy === "increment") {
                const t = this.buildSequencePath(r, e.name);
                const i = this.buildSequenceName(r, e.name);
                const o = this.buildSequencePath(s, e.name);
                const c = this.buildSequenceName(s, e.name);
                const l = `ALTER SEQUENCE ${this.escapePath(t)} RENAME TO "${c}"`;
                const u = `ALTER SEQUENCE ${this.escapePath(o)} RENAME TO "${i}"`;
                n.push(new Mg.Query(l));
                a.push(new Mg.Query(u));
            }
        });
        s.uniques.forEach(e => {
            const t = this.connection.namingStrategy.uniqueConstraintName(r, e.columnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.uniqueConstraintName(s, e.columnNames);
            n.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(r, e.columnNames, e.where);
            if (e.name !== t) return;
            const {schema: i} = this.driver.parseTableName(s);
            const o = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            const c = i ? `ALTER INDEX "${i}"."${e.name}" RENAME TO "${o}"` : `ALTER INDEX "${e.name}" RENAME TO "${o}"`;
            const l = i ? `ALTER INDEX "${i}"."${o}" RENAME TO "${e.name}"` : `ALTER INDEX "${o}" RENAME TO "${e.name}"`;
            n.push(new Mg.Query(c));
            a.push(new Mg.Query(l));
            e.name = o;
        });
        s.foreignKeys.forEach(e => {
            const t = this.connection.namingStrategy.foreignKeyName(r, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            if (e.name !== t) return;
            const i = this.connection.namingStrategy.foreignKeyName(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            n.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${e.name}" TO "${i}"`));
            a.push(new Mg.Query(`ALTER TABLE ${this.escapePath(s)} RENAME CONSTRAINT "${i}" TO "${e.name}"`));
            e.name = i;
        });
        const c = s.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 Mg.Query(`ALTER TYPE "${t.schema}"."${t.name}" RENAME TO ${this.buildEnumName(s, e, false)}`));
            a.push(new Mg.Query(`ALTER TYPE ${this.buildEnumName(s, e)} RENAME TO "${t.name}"`));
        }
        await this.executeQueries(n, a);
    }
    async addColumn(e, t) {
        const n = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        if (t.type === "enum" || t.type === "simple-enum") {
            const e = await this.hasEnumType(n, t);
            if (!e) {
                r.push(this.createEnumTypeSql(n, t));
                s.push(this.dropEnumTypeSql(n, t));
            }
        }
        r.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(n, t)}`));
        s.push(new Mg.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 i = e.map(e => `"${e.name}"`).join(", ");
                r.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${t}"`));
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${t}" PRIMARY KEY (${i})`));
            }
            e.push(t);
            const i = 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 Mg.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${i}" PRIMARY KEY (${o})`));
            s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${i}"`));
        }
        const i = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (i) {
            r.push(this.createIndexSql(n, i));
            s.push(this.dropIndexSql(n, i));
        }
        if (t.isUnique) {
            const e = new bg.TableUnique({
                name: this.connection.namingStrategy.uniqueConstraintName(n, [ t.name ]),
                columnNames: [ t.name ]
            });
            a.uniques.push(e);
            r.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e.name}" UNIQUE ("${t.name}")`));
            s.push(new Mg.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 i = e[0];
            const o = this.insertTypeormMetadataSql({
                database: this.driver.database,
                schema: i,
                table: a,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const c = this.deleteTypeormMetadataSql({
                database: this.driver.database,
                schema: i,
                table: a,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(o);
            s.push(c);
        }
        if (t.comment) {
            r.push(new Mg.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
            s.push(new Mg.Query(`COMMENT ON COLUMN ${this.escapePath(n)}."${t.name}" IS ${this.escapeComment(t.comment)}`));
        }
        await this.executeQueries(r, s);
        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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = Sg.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new lg.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s;
        if (Sg.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        return this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        let o = false;
        const c = Sg.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!c) throw new lg.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) {
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "${n.name}"`));
                i.push(new Mg.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);
                    s.push(new Mg.Query(`ALTER TYPE "${e.schema}"."${e.name}" RENAME TO ${this.buildEnumName(a, n, false)}`));
                    i.push(new Mg.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);
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${o}" TO "${l}"`));
                    i.push(new Mg.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}"`;
                    s.push(new Mg.Query(l));
                    i.push(new Mg.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);
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
                    i.push(new Mg.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}"`;
                    s.push(new Mg.Query(u));
                    i.push(new Mg.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);
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} RENAME CONSTRAINT "${e.name}" TO "${o}"`));
                    i.push(new Mg.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) {
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
                i.push(new Mg.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") && (!wg.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);
                s.push(new Mg.Query(`ALTER TYPE ${r} RENAME TO ${h}`));
                i.push(new Mg.Query(`ALTER TYPE ${u} RENAME TO ${l}`));
                s.push(this.createEnumTypeSql(a, n, t));
                i.push(this.dropEnumTypeSql(a, n, t));
                if (c.default !== null && c.default !== undefined) {
                    o = true;
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
                    i.push(new Mg.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}`;
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${d}`));
                i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${p}`));
                if (n.default !== null && n.default !== undefined) {
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
                    i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                }
                s.push(this.dropEnumTypeSql(a, c, u));
                i.push(this.createEnumTypeSql(a, c, u));
            }
            if (c.isNullable !== n.isNullable) {
                if (n.isNullable) {
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
                    i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
                } else {
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET NOT NULL`));
                    i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP NOT NULL`));
                }
            }
            if (c.comment !== n.comment) {
                s.push(new Mg.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${c.name}" IS ${this.escapeComment(n.comment)}`));
                i.push(new Mg.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(", ");
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    i.push(new Mg.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(", ");
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
                    i.push(new Mg.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(", ");
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    }
                }
            }
            if (n.isUnique !== c.isUnique) {
                if (n.isUnique === true) {
                    const e = new bg.TableUnique({
                        name: this.connection.namingStrategy.uniqueConstraintName(a, [ n.name ]),
                        columnNames: [ n.name ]
                    });
                    r.uniques.push(e);
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${e.name}" UNIQUE ("${n.name}")`));
                    i.push(new Mg.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);
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${e.name}"`));
                    i.push(new Mg.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") {
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" DROP DEFAULT`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${c.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
                    } else if (c.generationStrategy === "increment") {
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
                        s.push(new Mg.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
                        i.push(new Mg.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) {
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    } else {
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${this.driver.uuidGenerator}`));
                    }
                } else if (n.generationStrategy === "increment") {
                    if (n.isGenerated === true) {
                        s.push(new Mg.Query(`CREATE SEQUENCE IF NOT EXISTS ${this.escapePath(this.buildSequencePath(a, n))} OWNED BY ${this.escapePath(a)}."${n.name}"`));
                        i.push(new Mg.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    } else {
                        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT nextval('${this.escapePath(this.buildSequencePath(a, n))}')`));
                        s.push(new Mg.Query(`DROP SEQUENCE ${this.escapePath(this.buildSequencePath(a, n))}`));
                        i.push(new Mg.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) {
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${n.default}`));
                    if (c.default !== null && c.default !== undefined) {
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" SET DEFAULT ${c.default}`));
                    } else {
                        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    }
                } else if (c.default !== null && c.default !== undefined) {
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" DROP DEFAULT`));
                    i.push(new Mg.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) {
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
                i.push(new Mg.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];
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} RENAME COLUMN "${c.name}" TO "TEMP_OLD_${c.name}"`));
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ADD ${this.buildCreateColumnSql(a, n)}`));
                    s.push(new Mg.Query(`UPDATE ${this.escapePath(a)} SET "${n.name}" = "TEMP_OLD_${c.name}"`));
                    s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} DROP COLUMN "TEMP_OLD_${c.name}"`));
                    s.push(this.deleteTypeormMetadataSql({
                        database: this.driver.database,
                        schema: r,
                        table: t,
                        type: vg.MetadataTableType.GENERATED_COLUMN,
                        name: c.name
                    }));
                    i.push(this.insertTypeormMetadataSql({
                        database: this.driver.database,
                        schema: r,
                        table: t,
                        type: vg.MetadataTableType.GENERATED_COLUMN,
                        name: c.name,
                        value: c.asExpression
                    }));
                    i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} ADD ${this.buildCreateColumnSql(a, c)}`));
                    i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(a)} DROP COLUMN "${n.name}"`));
                }
            }
        }
        await this.executeQueries(s, i);
        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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new lg.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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(", ");
            s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${e}"`));
            i.push(new Mg.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(", ");
                s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
                i.push(new Mg.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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(this.dropCheckConstraintSql(n, c));
            i.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);
            s.push(this.dropUniqueConstraintSql(n, l));
            i.push(this.createUniqueConstraintSql(n, l));
        }
        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN "${a.name}"`));
        i.push(new Mg.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}"`;
                s.push(this.dropEnumTypeSql(n, a, t));
                i.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: vg.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const c = this.insertTypeormMetadataSql({
                database: this.driver.database,
                schema: r,
                table: t,
                type: vg.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(o);
            i.push(c);
        }
        await this.executeQueries(s, i);
        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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = a.clone();
        const s = this.createPrimaryKeySql(a, t, n);
        r.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        const i = this.dropPrimaryKeySql(r);
        await this.executeQueries(s, i);
        this.replaceCachedTable(a, r);
    }
    async updatePrimaryKeys(e, t) {
        const n = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = t.map(e => e.name);
        const s = [];
        const i = [];
        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(", ");
            s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            i.push(new Mg.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(", ");
        s.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${c}" PRIMARY KEY (${l})`));
        i.push(new Mg.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${c}"`));
        await this.executeQueries(s, i);
        this.replaceCachedTable(n, a);
    }
    async dropPrimaryKey(e, t) {
        const n = Sg.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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableUnique(t) ? t : n.uniques.find(e => e.name === t);
        if (!a) throw new lg.TypeORMError(`Supplied unique constraint was not found in table ${n.name}`);
        const r = this.dropUniqueConstraintSql(n, a);
        const s = this.createUniqueConstraintSql(n, a);
        await this.executeQueries(r, s);
        n.removeUniqueConstraint(a);
    }
    async dropUniqueConstraints(e, t) {
        for (const n of t) {
            await this.dropUniqueConstraint(e, n);
        }
    }
    async createCheckConstraint(e, t) {
        const n = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
        if (!a) throw new lg.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableExclusion(t) ? t : n.exclusions.find(e => e.name === t);
        if (!a) throw new lg.TypeORMError(`Supplied exclusion constraint was not found in table ${n.name}`);
        const r = this.dropExclusionConstraintSql(n, a);
        const s = this.createExclusionConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new lg.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 s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        n.removeForeignKey(a);
    }
    async dropForeignKeys(e, t) {
        for (const n of t) {
            await this.dropForeignKey(e, n);
        }
    }
    async createIndex(e, t) {
        const n = Sg.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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = Sg.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new lg.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        n.removeIndex(a);
    }
    async dropViewIndex(e, t) {
        const n = Sg.InstanceChecker.isView(e) ? e : await this.getCachedView(e);
        const a = Sg.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new lg.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 s = this.createViewIndexSql(n, a);
        await this.executeQueries(r, s);
        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 (Og.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 s = await this.query(r);
            await Promise.all(s.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 s = 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 i = `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 (${s})`;
        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 ('${vg.MetadataTableType.VIEW}', '${vg.MetadataTableType.MATERIALIZED_VIEW}') ${r ? `AND (${r})` : ""}`;
        const c = await this.query(o);
        const l = await this.query(i);
        return c.map(e => {
            const t = wg.OrmUtils.uniq(l.filter(t => t["table_name"] === e["name"] && t["table_schema"] === e["schema"]), e => e["constraint_name"]);
            const r = new Ag.View;
            const s = e["schema"] === a && !this.driver.options.schema ? undefined : e["schema"];
            r.database = n;
            r.schema = e["schema"];
            r.name = this.driver.buildTableName(e["name"], s);
            r.expression = e["value"];
            r.materialized = e["type"] === vg.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 Ng.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 s = `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 i = 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 (${i})`;
        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 (${i})`;
        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(s), this.query(o), this.query(c), this.query(d) ]);
        return Promise.all(a.map(async e => {
            const a = new fg.Table;
            const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
            const s = 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"], s);
            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 s = new Eg.TableColumn;
                s.name = t["column_name"];
                s.type = t["regtype"].toLowerCase();
                if (s.type === "numeric" || s.type === "numeric[]" || s.type === "decimal" || s.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, s, e)) {
                        s.precision = e;
                    } else if (n !== null && !this.isDefaultColumnScale(a, s, n)) {
                        s.precision = undefined;
                    }
                    if (n !== null && !this.isDefaultColumnScale(a, s, n)) {
                        s.scale = n;
                    } else if (e !== null && !this.isDefaultColumnPrecision(a, s, e)) {
                        s.scale = undefined;
                    }
                }
                if (s.type === "interval" || s.type === "time without time zone" || s.type === "time with time zone" || s.type === "timestamp without time zone" || s.type === "timestamp with time zone") {
                    s.precision = !this.isDefaultColumnPrecision(a, s, t["datetime_precision"]) ? t["datetime_precision"] : undefined;
                }
                if (t["data_type"] === "USER-DEFINED" || t["data_type"] === "ARRAY") {
                    const {name: n} = await this.getUserDefinedTypeName(a, s);
                    const r = this.buildEnumName(a, s, false, true);
                    const i = 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" = '${i || n}'`;
                    const c = await this.query(o);
                    if (c.length) {
                        s.type = "enum";
                        s.enum = c.map(e => e["value"]);
                        s.enumName = i;
                    }
                    if (t["data_type"] === "ARRAY") {
                        s.isArray = true;
                        const e = s.type.replace("[]", "");
                        s.type = this.connection.driver.normalizeType({
                            type: e
                        });
                    }
                }
                if (s.type === "geometry" || s.type === "geography") {
                    const e = `SELECT * FROM (` + `SELECT "f_table_schema" "table_schema", "f_table_name" "table_name", ` + `"f_${s.type}_column" "column_name", "srid", "type" ` + `FROM "${s.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) {
                        s.spatialFeatureType = n[0].type;
                        s.srid = n[0].srid;
                    }
                }
                if (this.driver.withLengthColumnTypes.indexOf(s.type) !== -1) {
                    let e;
                    if (s.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) {
                        s.length = !this.isDefaultColumnLength(a, s, e) ? e : "";
                    }
                }
                s.isNullable = t["is_nullable"] === "YES";
                const i = r.find(e => e["constraint_type"] === "PRIMARY");
                if (i) {
                    s.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 (i["constraint_name"] !== r) {
                        s.primaryKeyConstraintName = i["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"]));
                s.isUnique = o.length > 0 && !c;
                if (t.is_identity === "YES") {
                    s.isGenerated = true;
                    s.generationStrategy = "identity";
                    s.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) {
                        s.isGenerated = true;
                        s.generationStrategy = "increment";
                    } else if (t["column_default"] === "gen_random_uuid()" || /^uuid_generate_v\d\(\)/.test(t["column_default"])) {
                        if (s.type === "uuid") {
                            s.isGenerated = true;
                            s.generationStrategy = "uuid";
                        } else {
                            s.default = t["column_default"];
                        }
                    } else if (t["column_default"] === "now()" || t["column_default"].indexOf("'now'::text") !== -1) {
                        s.default = t["column_default"];
                    } else {
                        s.default = t["column_default"].replace(/::[\w\s.[\]\-"]+/g, "");
                        s.default = s.default.replace(/^(-?\d+)$/, "'$1'");
                    }
                }
                if (t["is_generated"] === "ALWAYS" && t["generation_expression"]) {
                    s.generatedType = "STORED";
                    const t = this.selectTypeormMetadataSql({
                        database: n,
                        schema: e["table_schema"],
                        table: e["table_name"],
                        type: vg.MetadataTableType.GENERATED_COLUMN,
                        name: s.name
                    });
                    const a = await this.query(t.query, t.parameters);
                    if (a[0] && a[0].value) {
                        s.asExpression = a[0].value;
                    } else {
                        s.asExpression = "";
                    }
                }
                s.comment = t["description"] ? t["description"] : undefined;
                if (t["character_set_name"]) s.charset = t["character_set_name"];
                if (t["collation_name"]) s.collation = t["collation_name"];
                return s;
            }));
            const i = wg.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 = i.map(e => {
                const t = m.filter(t => t["constraint_name"] === e["constraint_name"]);
                return new bg.TableUnique({
                    name: e["constraint_name"],
                    columnNames: t.map(e => e["column_name"]),
                    deferrable: e["deferrable"] ? e["deferred"] : undefined
                });
            });
            const o = wg.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 yg.TableCheck({
                    name: e["constraint_name"],
                    columnNames: t.map(e => e["column_name"]),
                    expression: e["expression"].replace(/^\s*CHECK\s*\((.*)\)\s*$/i, "$1")
                });
            });
            const c = wg.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 Tg.TableExclusion({
                name: e["constraint_name"],
                expression: e["expression"].substring(8)
            }));
            const l = wg.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 gg.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 = wg.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 Ng.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 bg.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 Mg.Query(a);
    }
    async getVersion() {
        const e = await this.query(`SELECT version()`);
        return e[0].version.replace(/^PostgreSQL ([\d.]+).*$/, "$1");
    }
    dropTableSql(e) {
        return new Mg.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 Mg.Query(`CREATE ${t}VIEW ${n} AS ${e.expression}`);
        } else {
            return new Mg.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 ? vg.MetadataTableType.MATERIALIZED_VIEW : vg.MetadataTableType.VIEW;
        const s = typeof e.expression === "string" ? e.expression.trim() : e.expression(this.connection).getQuery();
        return this.insertTypeormMetadataSql({
            type: r,
            schema: n,
            name: a,
            value: s
        });
    }
    dropViewSql(e) {
        const t = e.materialized ? "MATERIALIZED " : "";
        return new Mg.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 ? vg.MetadataTableType.MATERIALIZED_VIEW : vg.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 s = await this.query(r);
        return s.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 Mg.Query(`CREATE TYPE ${n} AS ENUM(${a})`);
    }
    dropEnumTypeSql(e, t, n) {
        if (!n) n = this.buildEnumName(e, t);
        return new Mg.Query(`DROP TYPE ${n}`);
    }
    createIndexSql(e, t) {
        const n = t.columnNames.map(e => `"${e}"`).join(", ");
        return new Mg.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 Mg.Query(`CREATE ${t.isUnique ? "UNIQUE " : ""}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
    }
    dropIndexSql(e, t) {
        const n = Sg.InstanceChecker.isTableIndex(t) ? t.name : t;
        const a = Sg.InstanceChecker.isTableIndex(t) ? t.isConcurrent : false;
        const {schema: r} = this.driver.parseTableName(e);
        return r ? new Mg.Query(`DROP INDEX ${a ? "CONCURRENTLY " : ""}"${r}"."${n}"`) : new Mg.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 Mg.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${a}" PRIMARY KEY (${r})`);
    }
    dropPrimaryKeySql(e) {
        if (!e.primaryColumns.length) throw new lg.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 Mg.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 Mg.Query(a);
    }
    dropUniqueConstraintSql(e, t) {
        const n = Sg.InstanceChecker.isTableUnique(t) ? t.name : t;
        return new Mg.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createCheckConstraintSql(e, t) {
        return new Mg.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
    }
    dropCheckConstraintSql(e, t) {
        const n = Sg.InstanceChecker.isTableCheck(t) ? t.name : t;
        return new Mg.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createExclusionConstraintSql(e, t) {
        return new Mg.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" EXCLUDE ${t.expression}`);
    }
    dropExclusionConstraintSql(e, t) {
        const n = Sg.InstanceChecker.isTableExclusion(t) ? t.name : t;
        return new Mg.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 Mg.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = Sg.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new Mg.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    buildSequenceName(e, t) {
        const {tableName: n} = this.driver.parseTableName(e);
        const a = Sg.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: s, tableName: i} = this.driver.parseTableName(e);
        let o = t.enumName ? t.enumName : `${i}_${t.name.toLowerCase()}_enum`;
        if (s && n) o = `${s}.${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 s = r[0]["udt_name"];
        if (s.indexOf("_") === 0) {
            s = s.substr(1, s.length);
        }
        return {
            schema: r[0]["udt_schema"],
            name: s
        };
    }
    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 = Sg.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 = Sg.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        t = this.escapeComment(t);
        const s = this.escapeComment(r.comment);
        if (t === s) {
            return;
        }
        const i = r.clone();
        n.push(new Mg.Query(`COMMENT ON TABLE ${this.escapePath(i)} IS ${t}`));
        a.push(new Mg.Query(`COMMENT ON TABLE ${this.escapePath(r)} IS ${s}`));
        await this.executeQueries(n, a);
        r.comment = i.comment;
        this.replaceCachedTable(r, i);
    }
}

cg.PostgresQueryRunner = PostgresQueryRunner;

Object.defineProperty(og, "__esModule", {
    value: true
});

og.PostgresDriver = void 0;

const Ig = ce();

const Pg = Mt();

const Lg = exports.PlatformTools;

const _g = cm;

const Dg = Bi;

const xg = xd;

const $g = Dc;

const qg = Ti;

const Ug = cg;

const Bg = zn;

const jg = exports.error;

const Fg = exports.InstanceChecker;

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 = Bg.DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database;
        this.schema = Bg.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 = qg.VersionUtils.isGreaterOrEqual(this.version, "12.0");
        await n();
    }
    async enableExtensions(e, t) {
        const {logger: n} = this.connection;
        const {hasUuidColumns: a, hasCitextColumns: r, hasHstoreColumns: s, hasCubeColumns: i, 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 (s) 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 (i) 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 s = this.connection.entityMetadatas.some(e => e.columns.filter(e => e.type === "ltree").length > 0);
        const i = this.connection.entityMetadatas.some(e => e.exclusions.length > 0);
        return {
            hasUuidColumns: e,
            hasCitextColumns: t,
            hasHstoreColumns: n,
            hasCubeColumns: a,
            hasGeometryColumns: r,
            hasLtreeColumns: s,
            hasExclusionConstraints: i,
            hasExtensions: e || t || n || r || a || s || i
        };
    }
    async disconnect() {
        if (!this.master) return Promise.reject(new Ig.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 _g.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new Ug.PostgresQueryRunner(this, e);
    }
    preparePersistentValue(e, t) {
        if (t.transformer) e = Dg.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 xg.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return xg.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 xg.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 xg.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return xg.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 ? Dg.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 = xg.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = xg.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = xg.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, s) => {
                    a[t(n)] = r ? null : t(s);
                    return "";
                });
                e = a;
            }
        } else if (t.type === "simple-array") {
            e = xg.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = xg.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 = Dg.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, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            if (r.has(s)) {
                return this.parametersPrefix + r.get(s);
            }
            const i = t[s];
            if (n) {
                return i.map(e => {
                    a.push(e);
                    return this.createParameter(s, a.length - 1);
                }).join(", ");
            }
            if (typeof i === "function") {
                return i();
            }
            a.push(i);
            r.set(s, a.length);
            return this.createParameter(s, 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 (Fg.InstanceChecker.isTable(e) || Fg.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 (Fg.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 (Fg.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 $g.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 jg.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) {
                $g.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 && !$g.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 Lg.PlatformTools.load("pg-query-stream");
        } catch (e) {
            throw new jg.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 || Lg.PlatformTools.load("pg");
            this.postgres = e;
            try {
                const e = this.options.nativeDriver || Lg.PlatformTools.load("pg-native");
                if (e && this.postgres.native) this.postgres = this.postgres.native;
            } catch (e) {}
        } catch (e) {
            throw new Pg.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 s = e.poolErrorHandler || (e => n.log("warn", `Postgres pool raised an error. ${e}`));
        r.on("error", s);
        return new Promise((t, n) => {
            r.connect((a, s, i) => {
                if (a) return n(a);
                if (e.logNotifications) {
                    s.on("notice", e => {
                        e && this.connection.logger.log("info", e.message);
                    });
                    s.on("notification", e => {
                        e && this.connection.logger.log("info", `Received NOTIFY on channel ${e.channel}: ${e.payload}.`);
                    });
                }
                i();
                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;
    }
}

og.PostgresDriver = PostgresDriver;

var kg = {};

var Qg = {};

var Vg = {};

Object.defineProperty(Vg, "__esModule", {
    value: true
});

Vg.ExpoQueryRunner = void 0;

const Kg = pn();

const Wg = Dn();

const Hg = Lm;

const Gg = _m;

const Yg = ic;

const zg = Jy;

class ExpoQueryRunner extends zg.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new Gg.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 Wg.QueryRunnerAlreadyReleasedError;
        const a = await this.connect();
        const r = new Yg.BroadcasterResult;
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const s = Date.now();
        const i = await a.prepareAsync(e);
        try {
            const a = await i.executeAsync(t);
            const o = this.driver.options.maxQueryExecutionTime;
            const c = Date.now();
            const l = c - s;
            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 Hg.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 Kg.QueryFailedError(e, t, n);
        } finally {
            await r.wait();
            await i.finalizeAsync();
        }
    }
}

Vg.ExpoQueryRunner = ExpoQueryRunner;

Object.defineProperty(Qg, "__esModule", {
    value: true
});

Qg.ExpoDriver = void 0;

const Jg = mE;

const Xg = Vg;

class ExpoDriver extends Jg.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 Xg.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;
    }
}

Qg.ExpoDriver = ExpoDriver;

var Zg = {};

var eN = {};

Object.defineProperty(eN, "__esModule", {
    value: true
});

eN.ExpoLegacyQueryRunner = void 0;

const tN = Dn();

const nN = pn();

const aN = Jy;

const rN = we();

const sN = _m;

const iN = Lm;

const oN = ic;

class ExpoLegacyQueryRunner extends aN.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new sN.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 rN.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 rN.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 tN.QueryRunnerAlreadyReleasedError;
        return new Promise(async (a, r) => {
            const s = await this.connect();
            const i = new oN.BroadcasterResult;
            this.driver.connection.logger.logQuery(e, t, this);
            this.broadcaster.broadcastBeforeQueryEvent(i, e, t);
            const o = Date.now();
            s.transaction(async s => {
                if (typeof this.transaction === "undefined") {
                    await this.startTransaction();
                    this.transaction = s;
                }
                this.transaction.executeSql(e, t, async (r, s) => {
                    const c = this.driver.options.maxQueryExecutionTime;
                    const l = Date.now();
                    const u = l - o;
                    this.broadcaster.broadcastAfterQueryEvent(i, e, t, true, u, s, undefined);
                    await i.wait();
                    if (c && u > c) {
                        this.driver.connection.logger.logQuerySlow(u, e, t, this);
                    }
                    const h = new iN.QueryResult;
                    if (s?.hasOwnProperty("rowsAffected")) {
                        h.affected = s.rowsAffected;
                    }
                    if (s?.hasOwnProperty("rows")) {
                        let e = [];
                        for (let t = 0; t < s.rows.length; t++) {
                            e.push(s.rows.item(t));
                        }
                        h.raw = e;
                        h.records = e;
                    }
                    if (e.startsWith("INSERT INTO")) {
                        h.raw = s.insertId;
                    }
                    if (n) {
                        a(h);
                    } else {
                        a(h.raw);
                    }
                }, async (n, a) => {
                    this.driver.connection.logger.logQueryError(a, e, t, this);
                    this.broadcaster.broadcastAfterQueryEvent(i, e, t, false, undefined, undefined, a);
                    await i.wait();
                    r(new nN.QueryFailedError(e, t, a));
                });
            }, async e => {
                await this.rollbackTransaction();
                r(e);
            }, () => {
                this.isTransactionActive = false;
                this.transaction = undefined;
            });
        });
    }
}

eN.ExpoLegacyQueryRunner = ExpoLegacyQueryRunner;

Object.defineProperty(Zg, "__esModule", {
    value: true
});

Zg.ExpoLegacyDriver = void 0;

const cN = mE;

const lN = eN;

class ExpoLegacyDriver extends cN.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 lN.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);
            }
        });
    }
}

Zg.ExpoLegacyDriver = ExpoLegacyDriver;

Object.defineProperty(kg, "__esModule", {
    value: true
});

kg.ExpoDriverFactory = void 0;

const uN = Qg;

const hN = Zg;

class ExpoDriverFactory {
    constructor(e) {
        this.connection = e;
    }
    create() {
        if (this.isLegacyDriver) {
            return new hN.ExpoLegacyDriver(this.connection);
        }
        return new uN.ExpoDriver(this.connection);
    }
    get isLegacyDriver() {
        return !("openDatabaseAsync" in this.connection.options.driver);
    }
}

kg.ExpoDriverFactory = ExpoDriverFactory;

var dN = {};

var pN = {};

Object.defineProperty(pN, "__esModule", {
    value: true
});

pN.AuroraMysqlQueryRunner = void 0;

const mN = Lm;

const fN = we();

const yN = iu;

const EN = su;

const TN = cu;

const gN = ou;

const NN = Dn();

const bN = lm;

const AN = Rm;

const CN = Dc;

const RN = uu;

const SN = Cm;

const wN = _m;

const ON = exports.error;

const MN = $m;

const vN = exports.InstanceChecker;

class AuroraMysqlQueryRunner extends SN.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.client = t;
        this.broadcaster = new wN.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 fN.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 fN.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 NN.QueryRunnerAlreadyReleasedError;
        const a = await this.client.query(e, t);
        const r = new mN.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 NN.QueryRunnerAlreadyReleasedError;
        return new Promise(async (r, s) => {
            try {
                const s = await this.connect();
                const i = s.query(e, t);
                if (n) i.on("end", n);
                if (a) i.on("error", a);
                r(i);
            } catch (e) {
                s(e);
            }
        });
    }
    async getDatabases() {
        return Promise.resolve([]);
    }
    async getSchemas(e) {
        throw new ON.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 ON.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 = vN.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 s = await this.query(r);
        return s.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 AN.Query(n), new AN.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 AN.Query(n), new AN.Query(a));
    }
    async createSchema(e, t) {
        throw new ON.TypeORMError(`Schema create queries are not supported by MySql driver.`);
    }
    async dropSchema(e, t) {
        throw new ON.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 s = await this.getCachedTable(r);
        const i = [];
        const o = [];
        if (n) s.foreignKeys.forEach(e => i.push(this.dropForeignKeySql(s, e)));
        s.indices.forEach(e => i.push(this.dropIndexSql(s, e)));
        i.push(this.dropTableSql(s));
        o.push(this.createTableSql(s, a));
        await this.executeQueries(i, 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 = vN.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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {database: i} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new AN.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(s)}`));
        a.push(new AN.Query(`RENAME TABLE ${this.escapePath(s)} TO ${this.escapePath(r)}`));
        s.indices.forEach(e => {
            const t = e.columnNames.map(e => `\`${e}\``).join(", ");
            const r = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            let i = "";
            if (e.isUnique) i += "UNIQUE ";
            if (e.isSpatial) i += "SPATIAL ";
            if (e.isFulltext) i += "FULLTEXT ";
            n.push(new AN.Query(`ALTER TABLE ${this.escapePath(s)} DROP INDEX \`${e.name}\`, ADD ${i}INDEX \`${r}\` (${t})`));
            a.push(new AN.Query(`ALTER TABLE ${this.escapePath(s)} DROP INDEX \`${r}\`, ADD ${i}INDEX \`${e.name}\` (${t})`));
            e.name = r;
        });
        s.foreignKeys.forEach(e => {
            const t = e.columnNames.map(e => `\`${e}\``).join(", ");
            const r = e.referencedColumnNames.map(e => `\`${e}\``).join(",");
            const i = this.connection.namingStrategy.foreignKeyName(s, e.columnNames);
            let o = `ALTER TABLE ${this.escapePath(s)} DROP FOREIGN KEY \`${e.name}\`, ADD CONSTRAINT \`${i}\` 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(s)} DROP FOREIGN KEY \`${i}\`, 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 AN.Query(o));
            a.push(new AN.Query(c));
            e.name = i;
        });
        await this.executeQueries(n, a);
        r.name = s.name;
        this.replaceCachedTable(r, s);
    }
    async addColumn(e, t) {
        const n = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        const i = a.primaryColumns.length > 0;
        r.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t, i, false)}`));
        s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${t.name}\``));
        if (t.isPrimary && i) {
            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 AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(a, true)}`));
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
            }
            const i = a.primaryColumns;
            let o = i.map(e => `\`${e.name}\``).join(", ");
            r.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
            i.push(t);
            o = i.map(e => `\`${e.name}\``).join(", ");
            r.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${o})`));
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            if (e) {
                const a = e.clone();
                a.isGenerated = false;
                a.generationStrategy = undefined;
                r.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${a.name}\` ${this.buildCreateColumnSql(t, true)}`));
                s.push(new AN.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));
            s.push(this.dropIndexSql(n, o));
        } else if (t.isUnique) {
            const e = new gN.TableIndex({
                name: this.connection.namingStrategy.indexName(n, [ t.name ]),
                columnNames: [ t.name ],
                isUnique: true
            });
            a.indices.push(e);
            a.uniques.push(new RN.TableUnique({
                name: e.name,
                columnNames: e.columnNames
            }));
            r.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${e.name}\` (\`${t.name}\`)`));
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${e.name}\``));
        }
        await this.executeQueries(r, s);
        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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = vN.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new ON.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s = undefined;
        if (vN.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        await this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = vN.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!o) throw new ON.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) {
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` \`${n.name}\` ${this.buildCreateColumnSql(o, true, true)}`));
                i.push(new AN.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 ";
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\`, ADD ${l}INDEX \`${c}\` (${t})`));
                    i.push(new AN.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}`;
                    s.push(new AN.Query(u));
                    i.push(new AN.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)) {
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(n, true)}`));
                i.push(new AN.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;
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
                    i.push(new AN.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(", ");
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
                    i.push(new AN.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(", ");
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${o})`));
                    i.push(new AN.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(", ");
                        s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} ADD PRIMARY KEY (${e})`));
                        i.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} DROP PRIMARY KEY`));
                    }
                }
                if (e) {
                    const t = e.clone();
                    t.isGenerated = false;
                    t.generationStrategy = undefined;
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
                    i.push(new AN.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 gN.TableIndex({
                        name: this.connection.namingStrategy.indexName(a, [ n.name ]),
                        columnNames: [ n.name ],
                        isUnique: true
                    });
                    r.indices.push(e);
                    r.uniques.push(new RN.TableUnique({
                        name: e.name,
                        columnNames: e.columnNames
                    }));
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
                    i.push(new AN.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);
                    s.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} DROP INDEX \`${e.name}\``));
                    i.push(new AN.Query(`ALTER TABLE ${this.escapePath(a)} ADD UNIQUE INDEX \`${e.name}\` (\`${n.name}\`)`));
                }
            }
        }
        await this.executeQueries(s, i);
        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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = vN.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!a) throw new ON.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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;
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(t, true)}`));
                i.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
            }
            const t = r.primaryColumns.map(e => `\`${e.name}\``).join(", ");
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(r)} DROP PRIMARY KEY`));
            i.push(new AN.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(", ");
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(r)} ADD PRIMARY KEY (${e})`));
                i.push(new AN.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;
                s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${t.name}\` ${this.buildCreateColumnSql(e, true)}`));
                i.push(new AN.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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP INDEX \`${o}\``));
            i.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD UNIQUE INDEX \`${o}\` (\`${a.name}\`)`));
        }
        s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN \`${a.name}\``));
        i.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a, true)}`));
        await this.executeQueries(s, i);
        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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = this.createPrimaryKeySql(n, t);
        const s = this.dropPrimaryKeySql(n);
        await this.executeQueries(r, s);
        a.columns.forEach(e => {
            if (t.find(t => t === e.name)) e.isPrimary = true;
        });
        this.replaceCachedTable(n, a);
    }
    async updatePrimaryKeys(e, t) {
        const n = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = t.map(e => e.name);
        const s = [];
        const i = [];
        const o = a.columns.find(e => e.isGenerated && e.generationStrategy === "increment");
        if (o) {
            const e = o.clone();
            e.isGenerated = false;
            e.generationStrategy = undefined;
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${o.name}\` ${this.buildCreateColumnSql(e, true)}`));
            i.push(new AN.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(", ");
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} DROP PRIMARY KEY`));
            i.push(new AN.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(", ");
        s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} ADD PRIMARY KEY (${l})`));
        i.push(new AN.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;
            s.push(new AN.Query(`ALTER TABLE ${this.escapePath(n)} CHANGE \`${e.name}\` ${this.buildCreateColumnSql(u, true)}`));
            i.push(new AN.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(s, i);
        this.replaceCachedTable(n, a);
    }
    async dropPrimaryKey(e) {
        const t = vN.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 ON.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async createUniqueConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraint(e, t) {
        throw new ON.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
    }
    async createCheckConstraint(e, t) {
        throw new ON.TypeORMError(`MySql does not support check constraints.`);
    }
    async createCheckConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support check constraints.`);
    }
    async dropCheckConstraint(e, t) {
        throw new ON.TypeORMError(`MySql does not support check constraints.`);
    }
    async dropCheckConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support check constraints.`);
    }
    async createExclusionConstraint(e, t) {
        throw new ON.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new ON.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new ON.TypeORMError(`MySql does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = vN.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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = vN.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new ON.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 = vN.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 = vN.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = vN.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new ON.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 ON.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 s = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${t}'`;
            const i = `SET FOREIGN_KEY_CHECKS = 1;`;
            await this.query(r);
            const o = await this.query(s);
            await Promise.all(o.map(e => this.query(e["query"])));
            await this.query(i);
            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\` = '${MN.MetadataTableType.VIEW}' ${a ? `AND (${a})` : ""}`;
        const s = await this.query(r);
        return s.map(e => {
            const t = new bN.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 s = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` WHERE \`CONSTRAINT_NAME\` = 'PRIMARY' AND (${a})`;
        const i = `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(s), this.query(i), this.query(c), this.query(u) ]);
        return Promise.all(t.map(async e => {
            const t = new EN.Table;
            const a = p.find(t => t["SCHEMA_NAME"] === e["TABLE_SCHEMA"]);
            const r = a["COLLATION"];
            const s = a["CHARSET"];
            const i = e["TABLE_SCHEMA"] === n ? undefined : e["TABLE_SCHEMA"];
            t.database = e["TABLE_SCHEMA"];
            t.name = this.driver.buildTableName(e["TABLE_NAME"], undefined, i);
            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 i = this.connection.entityMetadatas.find(e => this.getTablePath(t) === this.getTablePath(e));
                const o = a.length > 0 && i && i.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 yN.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"] === s ? 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 = CN.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 TN.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 = CN.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 gN.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 gN.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 gN.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 AN.Query(a);
    }
    dropTableSql(e) {
        return new AN.Query(`DROP TABLE ${this.escapePath(e)}`);
    }
    createViewSql(e) {
        if (typeof e.expression === "string") {
            return new AN.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
        } else {
            return new AN.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: MN.MetadataTableType.VIEW,
            schema: t,
            name: e.name,
            value: n
        });
    }
    dropViewSql(e) {
        return new AN.Query(`DROP VIEW ${this.escapePath(e)}`);
    }
    async deleteViewDefinitionSql(e) {
        const t = await this.getCurrentDatabase();
        const n = vN.InstanceChecker.isView(e) ? e.name : e;
        return this.deleteTypeormMetadataSql({
            type: MN.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 AN.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})`);
    }
    dropIndexSql(e, t) {
        const n = vN.InstanceChecker.isTableIndex(t) ? t.name : t;
        return new AN.Query(`DROP INDEX \`${n}\` ON ${this.escapePath(e)}`);
    }
    createPrimaryKeySql(e, t) {
        const n = t.map(e => `\`${e}\``).join(", ");
        return new AN.Query(`ALTER TABLE ${this.escapePath(e)} ADD PRIMARY KEY (${n})`);
    }
    dropPrimaryKeySql(e) {
        return new AN.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 AN.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = vN.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new AN.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 ON.TypeORMError(`aurora-mysql driver does not support change table comment.`);
    }
}

pN.AuroraMysqlQueryRunner = AuroraMysqlQueryRunner;

Object.defineProperty(dN, "__esModule", {
    value: true
});

dN.AuroraMysqlDriver = void 0;

const IN = zn;

const PN = pN;

const LN = xd;

const _N = exports.PlatformTools;

const DN = cm;

const xN = Dc;

const $N = Bi;

const qN = exports.error;

const UN = exports.InstanceChecker;

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 = IN.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 DN.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new PN.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 s = t[r];
            if (n) {
                return s.map(e => {
                    a.push(e);
                    return this.createParameter(r, a.length - 1);
                }).join(", ");
            }
            if (typeof s === "function") {
                return s();
            }
            a.push(s);
            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 (UN.InstanceChecker.isTable(e) || UN.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 (UN.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 (UN.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 = $N.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 LN.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return LN.DateUtils.mixedDateToTimeString(e);
        } else if (t.type === "json") {
            return JSON.stringify(e);
        } else if (t.type === "timestamp" || t.type === "datetime" || t.type === Date) {
            return LN.DateUtils.mixedDateToDate(e);
        } else if (t.type === "simple-array" || t.type === "set") {
            return LN.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return LN.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 ? $N.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 = LN.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = LN.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "json") {
            e = typeof e === "string" ? JSON.parse(e) : e;
        } else if (t.type === "time") {
            e = LN.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array" || t.type === "set") {
            e = LN.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = LN.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 = $N.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 `'${LN.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 qN.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 xN.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 && !xN.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 || _N.PlatformTools.load("typeorm-aurora-data-api-driver");
        this.DataApiDriver = e;
        this.DataApiDriver = this.DataApiDriver.default || this.DataApiDriver;
    }
    createConnectionOptions(e, t) {
        t = Object.assign({}, t, IN.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;
    }
}

dN.AuroraMysqlDriver = AuroraMysqlDriver;

var BN = {};

var jN = {};

Object.defineProperty(jN, "__esModule", {
    value: true
});

jN.AuroraPostgresQueryRunner = void 0;

const FN = Dn();

const kN = we();

const QN = cg;

const VN = Lm;

const KN = exports.error;

class PostgresQueryRunnerWrapper extends QN.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 kN.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 kN.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 FN.QueryRunnerAlreadyReleasedError;
        const a = await this.client.query(e, t);
        const r = new VN.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 KN.TypeORMError(`aurora-postgres driver does not support change comment.`);
    }
}

jN.AuroraPostgresQueryRunner = AuroraPostgresQueryRunner;

Object.defineProperty(BN, "__esModule", {
    value: true
});

BN.AuroraPostgresDriver = void 0;

const WN = og;

const HN = exports.PlatformTools;

const GN = jN;

const YN = Bi;

const zN = zn;

class PostgresWrapper extends WN.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 = zN.DriverUtils.buildDriverOptions(this.options).database;
    }
    async connect() {}
    async disconnect() {}
    createQueryRunner(e) {
        return new GN.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 = YN.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 = YN.ApplyValueTransformers.transformFrom(t.transformer, e);
        return this.client.prepareHydratedValue(e, t);
    }
    loadDependencies() {
        const e = this.options.driver || HN.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();
    }
}

BN.AuroraPostgresDriver = AuroraPostgresDriver;

var JN = {};

var XN = {};

Object.defineProperty(XN, "__esModule", {
    value: true
});

XN.SapQueryRunner = void 0;

const ZN = P.default;

const eb = exports.error;

const tb = Dn();

const nb = ve();

const ab = we();

const rb = Cm;

const sb = $f;

const ib = Lm;

const ob = su;

const cb = hu;

const lb = iu;

const ub = cu;

const hb = ou;

const db = uu;

const pb = lm;

const mb = _m;

const fb = ic;

const yb = exports.InstanceChecker;

const Eb = Dc;

const Tb = Rm;

const gb = $m;

class SapQueryRunner extends rb.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.lock = new sb.QueryLock;
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new mb.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 tb.QueryRunnerAlreadyReleasedError;
        if (this.isTransactionActive && this.driver.transactionSupport === "simple") throw new nb.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 tb.QueryRunnerAlreadyReleasedError;
        if (!this.isTransactionActive) throw new ab.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 tb.QueryRunnerAlreadyReleasedError;
        if (!this.isTransactionActive) throw new ab.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, ZN.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 eb.QueryFailedError(a, [], e);
        }
    }
    async query(e, t, n = false) {
        if (this.isReleased) throw new tb.QueryRunnerAlreadyReleasedError;
        const a = await this.lock.acquire();
        const r = await this.connect();
        let s;
        const i = new ib.QueryResult;
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const o = new fb.BroadcasterResult;
        try {
            const n = Date.now();
            const a = e.substr(0, 11) === "INSERT INTO";
            if (t?.some(Array.isArray)) {
                s = await (0, ZN.promisify)(r.prepare).call(r, e);
            }
            let c;
            try {
                c = s ? await (0, ZN.promisify)(s.exec).call(s, t) : await (0, ZN.promisify)(r.exec).call(r, e, t, {});
            } catch (n) {
                throw new eb.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") {
                i.affected = c;
            } else if (Array.isArray(c)) {
                i.records = c;
            }
            i.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 eb.QueryFailedError(e, [], a)) : t(r));
                });
                i.raw = t[0]["CURRENT_IDENTITY_VALUE()"];
                i.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 (s?.drop) {
                await new Promise(e => s.drop(() => e()));
            }
            await o.wait();
            a();
        }
        if (n) {
            return i;
        } else {
            return i.raw;
        }
    }
    async stream(e, t, n, a) {
        if (this.isReleased) throw new tb.QueryRunnerAlreadyReleasedError;
        const r = await this.lock.acquire();
        let s;
        let i;
        const o = async () => {
            if (i) {
                await (0, ZN.promisify)(i.close).call(i);
            }
            if (s) {
                await (0, ZN.promisify)(s.drop).call(s);
            }
            r();
        };
        try {
            const r = await this.connect();
            this.driver.connection.logger.logQuery(e, t, this);
            s = await (0, ZN.promisify)(r.prepare).call(r, e);
            i = await (0, ZN.promisify)(s.executeQuery).call(s, t);
            const c = this.driver.streamClient.createObjectStream(i);
            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 eb.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 Tb.Query(e), new Tb.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 Tb.Query(e), new Tb.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 s = [];
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.push(this.dropIndexSql(e, t));
            });
        }
        await this.executeQueries(r, s);
    }
    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 s = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const i = [];
        const o = [];
        if (a) {
            s.indices.forEach(e => {
                i.push(this.dropIndexSql(s, e));
                o.push(this.createIndexSql(s, e));
            });
        }
        if (n) s.foreignKeys.forEach(e => i.push(this.dropForeignKeySql(s, e)));
        i.push(this.dropTableSql(s));
        o.push(this.createTableSql(s, r));
        await this.executeQueries(i, 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 = yb.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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const s = r.clone();
        const {schema: i, tableName: o} = this.driver.parseTableName(r);
        s.name = i ? `${i}.${t}` : t;
        n.push(new Tb.Query(`RENAME TABLE ${this.escapePath(r)} TO ${this.escapePath(s)}`));
        a.push(new Tb.Query(`RENAME TABLE ${this.escapePath(s)} TO ${this.escapePath(r)}`));
        s.foreignKeys.forEach(e => {
            n.push(this.dropForeignKeySql(s, e));
            a.push(this.createForeignKeySql(s, e));
        });
        const c = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${i}' 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 ub.TableForeignKey({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    referencedDatabase: s.database,
                    referencedSchema: s.schema,
                    referencedTableName: s.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 (s.primaryColumns.length > 0) {
            const e = s.primaryColumns.map(e => e.name);
            const t = e.map(e => `"${e}"`).join(", ");
            const i = this.connection.namingStrategy.primaryKeyName(r, e);
            const o = this.connection.namingStrategy.primaryKeyName(s, e);
            n.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} DROP CONSTRAINT "${i}"`));
            a.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} ADD CONSTRAINT "${i}" PRIMARY KEY (${t})`));
            n.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} ADD CONSTRAINT "${o}" PRIMARY KEY (${t})`));
            a.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} DROP CONSTRAINT "${o}"`));
        }
        s.foreignKeys.forEach(e => {
            e.name = this.connection.namingStrategy.foreignKeyName(s, e.columnNames, this.getTablePath(e), e.referencedColumnNames);
            n.push(this.createForeignKeySql(s, e));
            a.push(this.dropForeignKeySql(s, 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));
        });
        s.indices.forEach(e => {
            const t = this.connection.namingStrategy.indexName(s, e.columnNames, e.where);
            n.push(this.dropIndexSql(s, e));
            a.push(this.createIndexSql(s, e));
            e.name = t;
            n.push(this.createIndexSql(s, e));
            a.push(this.dropIndexSql(s, e));
        });
        await this.executeQueries(n, a);
        r.name = s.name;
        this.replaceCachedTable(r, s);
    }
    async addColumn(e, t) {
        const n = yb.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 s = [];
        const i = [];
        s.push(new Tb.Query(this.addColumnSql(n, t)));
        i.push(new Tb.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 ub.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);
                        s.push(this.dropForeignKeySql(t.tableName, e));
                        i.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(", ");
                s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${u}"`));
                i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${u}" PRIMARY KEY (${h})`));
                c.forEach(e => {
                    const t = l.find(t => t.fkName === e.name);
                    s.push(this.createForeignKeySql(t.tableName, e));
                    i.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(", ");
            s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
            i.push(new Tb.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) {
            s.push(this.createIndexSql(n, o));
            i.push(this.dropIndexSql(n, o));
        } else if (t.isUnique) {
            const e = new hb.TableIndex({
                name: this.connection.namingStrategy.indexName(n, [ t.name ]),
                columnNames: [ t.name ],
                isUnique: true
            });
            r.indices.push(e);
            r.uniques.push(new db.TableUnique({
                name: e.name,
                columnNames: e.columnNames
            }));
            s.push(this.createIndexSql(n, e));
            i.push(this.dropIndexSql(n, e));
        }
        await this.executeQueries(s, i);
        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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const r = yb.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!r) throw new eb.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s = undefined;
        if (yb.InstanceChecker.isTableColumn(n)) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        await this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = yb.InstanceChecker.isTableColumn(t) ? t : a.columns.find(e => e.name === t);
        if (!o) throw new eb.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) {
                s.push(new Tb.Query(`RENAME COLUMN ${this.escapePath(a)}."${o.name}" TO "${n.name}"`));
                i.push(new Tb.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(", ");
                    s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(r)} DROP CONSTRAINT "${a}"`));
                    i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${a}" PRIMARY KEY (${c})`));
                    const l = this.connection.namingStrategy.primaryKeyName(r, t);
                    s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(r)} ADD CONSTRAINT "${l}" PRIMARY KEY (${c})`));
                    i.push(new Tb.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);
                    s.push(this.dropIndexSql(r, e));
                    i.push(this.createIndexSql(r, e));
                    e.name = t;
                    s.push(this.createIndexSql(r, e));
                    i.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);
                    s.push(this.dropForeignKeySql(r, e));
                    i.push(this.createForeignKeySql(r, e));
                    e.name = t;
                    s.push(this.createForeignKeySql(r, e));
                    i.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);
                    s.push(this.dropCheckConstraintSql(r, e));
                    i.push(this.createCheckConstraintSql(r, e));
                    e.name = t;
                    s.push(this.createCheckConstraintSql(r, e));
                    i.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)) {
                s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER (${this.buildCreateColumnSql(n, !(o.default === null || o.default === undefined), !o.isNullable)})`));
                i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} ALTER (${this.buildCreateColumnSql(o, !(n.default === null || n.default === undefined), !n.isNullable)})`));
            } else if (o.comment !== n.comment) {
                s.push(new Tb.Query(`COMMENT ON COLUMN ${this.escapePath(a)}."${o.name}" IS ${this.escapeComment(n.comment)}`));
                i.push(new Tb.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(", ");
                    s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    i.push(new Tb.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(", ");
                    s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${o}" PRIMARY KEY (${c})`));
                    i.push(new Tb.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(", ");
                        s.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} ADD CONSTRAINT "${t}" PRIMARY KEY (${n})`));
                        i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(a)} DROP CONSTRAINT "${t}"`));
                    }
                }
            }
            if (n.isUnique !== o.isUnique) {
                if (n.isUnique === true) {
                    const e = new hb.TableIndex({
                        name: this.connection.namingStrategy.indexName(a, [ n.name ]),
                        columnNames: [ n.name ],
                        isUnique: true
                    });
                    r.indices.push(e);
                    r.uniques.push(new db.TableUnique({
                        name: e.name,
                        columnNames: e.columnNames
                    }));
                    s.push(this.createIndexSql(a, e));
                    i.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);
                    s.push(this.dropIndexSql(a, e));
                    i.push(this.createIndexSql(a, e));
                }
            }
            await this.executeQueries(s, i);
            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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = this.driver.parseTableName(n);
        if (!a.schema) {
            a.schema = await this.getCurrentSchema();
        }
        const r = yb.InstanceChecker.isTableColumn(t) ? t : n.findColumnByName(t);
        if (!r) throw new eb.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const s = n.clone();
        const i = [];
        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 ub.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);
                    i.push(this.dropForeignKeySql(t.tableName, e));
                    o.push(this.createForeignKeySql(t.tableName, e));
                });
            }
            const u = this.connection.namingStrategy.primaryKeyName(s, s.primaryColumns.map(e => e.name));
            const h = s.primaryColumns.map(e => `"${e.name}"`).join(", ");
            i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} DROP CONSTRAINT "${u}"`));
            o.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} ADD CONSTRAINT "${u}" PRIMARY KEY (${h})`));
            const d = s.findColumnByName(r.name);
            d.isPrimary = false;
            if (s.primaryColumns.length > 0) {
                const e = this.connection.namingStrategy.primaryKeyName(s, s.primaryColumns.map(e => e.name));
                const t = s.primaryColumns.map(e => `"${e.name}"`).join(", ");
                i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
                o.push(new Tb.Query(`ALTER TABLE ${this.escapePath(s)} DROP CONSTRAINT "${e}"`));
            }
            c.forEach(e => {
                const t = l.find(t => t.fkName === e.name);
                i.push(this.createForeignKeySql(t.tableName, e));
                o.push(this.dropForeignKeySql(t.tableName, e));
            });
        }
        const c = s.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === r.name);
        if (c) {
            s.indices.splice(s.indices.indexOf(c), 1);
            i.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 = s.uniques.find(t => t.name === e);
            if (t) {
                s.uniques.splice(s.uniques.indexOf(t), 1);
                i.push(this.dropIndexSql(n, e));
                o.push(new Tb.Query(`CREATE UNIQUE INDEX "${e}" ON ${this.escapePath(n)} ("${r.name}")`));
            }
            const a = this.connection.namingStrategy.indexName(n, [ r.name ]);
            const c = s.indices.find(e => e.name === a);
            if (c) {
                s.indices.splice(s.indices.indexOf(c), 1);
                i.push(this.dropIndexSql(n, a));
                o.push(new Tb.Query(`CREATE UNIQUE INDEX "${a}" ON ${this.escapePath(n)} ("${r.name}")`));
            }
        }
        const l = s.checks.find(e => !!e.columnNames && e.columnNames.length === 1 && e.columnNames[0] === r.name);
        if (l) {
            s.checks.splice(s.checks.indexOf(l), 1);
            i.push(this.dropCheckConstraintSql(n, l));
            o.push(this.createCheckConstraintSql(n, l));
        }
        i.push(new Tb.Query(this.dropColumnSql(n, r)));
        o.push(new Tb.Query(this.addColumnSql(n, r)));
        await this.executeQueries(i, o);
        s.removeColumn(r);
        this.replaceCachedTable(n, s);
    }
    async dropColumns(e, t) {
        for (const n of t) {
            await this.dropColumn(e, n);
        }
    }
    async createPrimaryKey(e, t) {
        const n = yb.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 s = this.dropPrimaryKeySql(a);
        await this.executeQueries(r, s);
        this.replaceCachedTable(n, a);
    }
    async updatePrimaryKeys(e, t) {
        const n = yb.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 s = t.map(e => e.name);
        const i = [];
        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 ub.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);
                i.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(", ");
            i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${e}"`));
            o.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${e}" PRIMARY KEY (${t})`));
        }
        r.columns.filter(e => s.indexOf(e.name) !== -1).forEach(e => e.isPrimary = true);
        const p = this.connection.namingStrategy.primaryKeyName(r, s);
        const m = s.map(e => `"${e}"`).join(", ");
        i.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} ADD CONSTRAINT "${p}" PRIMARY KEY (${m})`));
        o.push(new Tb.Query(`ALTER TABLE ${this.escapePath(n)} DROP CONSTRAINT "${p}"`));
        u.forEach(e => {
            const t = h.find(t => t.fkName === e.name);
            i.push(this.createForeignKeySql(t.tableName, e));
            o.push(this.dropForeignKeySql(t.tableName, e));
        });
        await this.executeQueries(i, o);
        this.replaceCachedTable(n, r);
    }
    async dropPrimaryKey(e) {
        const t = yb.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 s = `SELECT * FROM "SYS"."REFERENTIAL_CONSTRAINTS" WHERE "REFERENCED_SCHEMA_NAME" = '${n.schema}' AND "REFERENCED_TABLE_NAME" = '${n.tableName}'`;
        const i = await this.query(s);
        let o = [];
        const c = [];
        if (i.length > 0) {
            o = i.map(e => {
                const n = i.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
                c.push({
                    tableName: `${e["SCHEMA_NAME"]}.${e["TABLE_NAME"]}`,
                    fkName: e["CONSTRAINT_NAME"]
                });
                return new ub.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 eb.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
    }
    async createUniqueConstraints(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraint(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraints(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support unique constraints. Use unique index instead.`);
    }
    async createCheckConstraint(e, t) {
        const n = yb.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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = yb.InstanceChecker.isTableCheck(t) ? t : n.checks.find(e => e.name === t);
        if (!a) throw new eb.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 eb.TypeORMError(`SAP HANA does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new eb.TypeORMError(`SAP HANA does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = yb.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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = yb.InstanceChecker.isTableForeignKey(t) ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new eb.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 = yb.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 = yb.InstanceChecker.isTable(e) ? e : await this.getCachedTable(e);
        const a = yb.InstanceChecker.isTableIndex(t) ? t : n.indices.find(e => e.name === t);
        if (!a) throw new eb.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = `SELECT "t".* FROM ${this.escapePath(this.getTypeormMetadataTableName())} "t" WHERE "t"."type" = '${gb.MetadataTableType.VIEW}' ${r ? `AND (${r})` : ""}`;
        const i = await this.query(s);
        return i.map(e => {
            const t = new pb.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 s = `SELECT * FROM "SYS"."TABLE_COLUMNS" WHERE ` + r + ` ORDER BY "POSITION"`;
        const i = a.map(({SCHEMA_NAME: e, TABLE_NAME: t}) => `("SCHEMA_NAME" = '${e}' AND "TABLE_NAME" = '${t}')`).join(" OR ");
        const o = `SELECT * FROM "SYS"."CONSTRAINTS" WHERE (${i}) 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(s), this.query(o), this.query(l), this.query(h) ]);
        return Promise.all(a.map(async e => {
            const a = new ob.Table;
            const r = (e, n) => e[n] === t && (!this.driver.options.schema || this.driver.options.schema === t) ? undefined : e[n];
            const s = r(e, "SCHEMA_NAME");
            a.database = n;
            a.schema = e["SCHEMA_NAME"];
            a.name = this.driver.buildTableName(e["TABLE_NAME"], s);
            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 s = this.connection.entityMetadatas.find(e => this.getTablePath(a) === this.getTablePath(e));
                const i = r.length > 0 && s && s.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 lb.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 && !i && !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 i = Eb.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 = i.map(e => {
                const t = p.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
                return new cb.TableCheck({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    expression: e["CHECK_CONDITION"]
                });
            });
            const o = Eb.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 s = this.driver.buildTableName(e["REFERENCED_TABLE_NAME"], n);
                return new ub.TableForeignKey({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: t.map(e => e["COLUMN_NAME"]),
                    referencedDatabase: a.database,
                    referencedSchema: e["REFERENCED_SCHEMA_NAME"],
                    referencedTableName: s,
                    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 = Eb.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 hb.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 hb.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 hb.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 Tb.Query(a);
    }
    dropTableSql(e, t) {
        const n = t ? `DROP TABLE IF EXISTS ${this.escapePath(e)}` : `DROP TABLE ${this.escapePath(e)}`;
        return new Tb.Query(n);
    }
    createViewSql(e) {
        if (typeof e.expression === "string") {
            return new Tb.Query(`CREATE VIEW ${this.escapePath(e)} AS ${e.expression}`);
        } else {
            return new Tb.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: gb.MetadataTableType.VIEW,
            schema: t,
            name: n,
            value: a
        });
    }
    dropViewSql(e) {
        return new Tb.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: gb.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 Tb.Query(`CREATE ${a}INDEX "${t.name}" ON ${this.escapePath(e)} (${n}) ${t.where ? "WHERE " + t.where : ""}`);
    }
    dropIndexSql(e, t) {
        const n = yb.InstanceChecker.isTableIndex(t) ? t.name : t;
        const a = this.driver.parseTableName(e);
        if (!a.schema) {
            return new Tb.Query(`DROP INDEX "${n}"`);
        } else {
            return new Tb.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 Tb.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 Tb.Query(`ALTER TABLE ${this.escapePath(e)} DROP CONSTRAINT "${n}"`);
    }
    createCheckConstraintSql(e, t) {
        return new Tb.Query(`ALTER TABLE ${this.escapePath(e)} ADD CONSTRAINT "${t.name}" CHECK (${t.expression})`);
    }
    dropCheckConstraintSql(e, t) {
        const n = yb.InstanceChecker.isTableCheck(t) ? t.name : t;
        return new Tb.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 Tb.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = yb.InstanceChecker.isTableForeignKey(t) ? t.name : t;
        return new Tb.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 eb.TypeORMError(`spa driver does not support change table comment.`);
    }
}

XN.SapQueryRunner = SapQueryRunner;

Object.defineProperty(JN, "__esModule", {
    value: true
});

JN.SapDriver = void 0;

const Nb = Mt();

const bb = W;

const Ab = exports.PlatformTools;

const Cb = cm;

const Rb = Bi;

const Sb = xd;

const wb = Dc;

const Ob = XN;

const Mb = zn;

const vb = exports.InstanceChecker;

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 = Mb.DriverUtils.buildDriverOptions(this.options).database;
        this.schema = Mb.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: s, database: i} = await r.getDatabaseAndVersion();
        this.version = s;
        this.database = i;
        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 Cb.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new Ob.SapQueryRunner(this, e);
    }
    escapeQueryWithParameters(e, t, n) {
        const a = Object.keys(n).map(e => {
            if (n[e] instanceof Date) return Sb.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 s = t[r];
            if (n) {
                return s.map(e => {
                    a.push(e);
                    return this.createParameter(r, a.length - 1);
                }).join(", ");
            }
            if (typeof s === "function") {
                return s();
            }
            if (s instanceof Date) {
                return Sb.DateUtils.mixedDateToDatetimeString(s, true);
            }
            a.push(s);
            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 (vb.InstanceChecker.isTable(e) || vb.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 (vb.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 (vb.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 = Rb.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 Sb.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            return Sb.DateUtils.mixedDateToTimeString(e);
        } else if (t.type === "timestamp" || t.type === Date) {
            return Sb.DateUtils.mixedDateToDatetimeString(e, true);
        } else if (t.type === "seconddate") {
            return Sb.DateUtils.mixedDateToDatetimeString(e, false);
        } else if (t.type === "simple-array") {
            return Sb.DateUtils.simpleArrayToString(e);
        } else if (t.type === "simple-json") {
            return Sb.DateUtils.simpleJsonToString(e);
        } else if (t.type === "simple-enum") {
            return Sb.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 ? Rb.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 = Sb.DateUtils.normalizeHydratedDate(e);
        } else if (t.type === "date") {
            e = Sb.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "time") {
            e = Sb.DateUtils.mixedTimeToString(e);
        } else if (t.type === "simple-array") {
            e = Sb.DateUtils.stringToSimpleArray(e);
        } else if (t.type === "simple-json") {
            e = Sb.DateUtils.stringToSimpleJson(e);
        } else if (t.type === "simple-enum") {
            e = Sb.DateUtils.stringToSimpleEnum(e, t);
        } else if (t.type === Number) {
            e = !isNaN(+e) ? parseInt(e) : e;
        }
        if (t.transformer) e = Rb.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 (Mb.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 bb.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 wb.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 !Mb.DriverUtils.isReleaseVersionOrGreater(this, "4.0");
    }
    createParameter(e, t) {
        return "?";
    }
    loadDependencies() {
        try {
            const e = this.options.driver || Ab.PlatformTools.load("hdb-pool");
            this.client = e;
        } catch (e) {
            throw new Nb.DriverPackageNotInstalledError("SAP Hana", "hdb-pool");
        }
        try {
            if (!this.options.hanaClientDriver) {
                Ab.PlatformTools.load("@sap/hana-client");
                this.streamClient = Ab.PlatformTools.load("@sap/hana-client/extension/Stream");
            }
        } catch (e) {
            throw new Nb.DriverPackageNotInstalledError("SAP Hana", "@sap/hana-client");
        }
    }
    escapeComment(e) {
        if (!e) return e;
        e = e.replace(/\u0000/g, "");
        return e;
    }
}

JN.SapDriver = SapDriver;

var Ib = {};

var Pb = {};

var Lb;

function _b() {
    if (Lb) return Pb;
    Lb = 1;
    Object.defineProperty(Pb, "__esModule", {
        value: true
    });
    Pb.BetterSqlite3QueryRunner = void 0;
    const e = Dn();
    const t = pn();
    const n = Jy;
    const a = _m;
    const r = Lm;
    const s = ic;
    let i = 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, i = false) {
            if (this.isReleased) throw new e.QueryRunnerAlreadyReleasedError;
            const o = this.driver.connection;
            const c = new s.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 s = Date.now();
                const h = s - l;
                if (t && h > t) o.logger.logQuerySlow(h, n, a, this);
                this.broadcaster.broadcastAfterQueryEvent(c, n, a, true, h, e.raw, undefined);
                if (!i) {
                    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;
        }
    };
    Pb.BetterSqlite3QueryRunner = i;
    return Pb;
}

Object.defineProperty(Ib, "__esModule", {
    value: true
});

Ib.BetterSqlite3Driver = void 0;

const Db = e.require$$0;

const xb = Db.__importDefault(v.default);

const $b = Db.__importDefault(C.default);

const qb = exports.error;

const Ub = exports.PlatformTools;

const Bb = mE;

const jb = _b();

const Fb = sd();

class BetterSqlite3Driver extends Bb.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 jb.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, Fb.filepathToName)(n);
        const r = (0, Fb.isAbsolute)(n) ? n : $b.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($b.default.dirname(this.options.database));
        const {database: e, readonly: t = false, fileMustExist: n = false, timeout: a = 5e3, verbose: r = null, nativeBinding: s = null, prepareDatabase: i} = this.options;
        const o = this.sqlite(e, {
            readonly: t,
            fileMustExist: n,
            timeout: a,
            verbose: r,
            nativeBinding: s
        });
        if (this.options.key) {
            o.exec(`PRAGMA key = ${JSON.stringify(this.options.key)}`);
        }
        if (typeof i === "function") {
            i(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 || Ub.PlatformTools.load("better-sqlite3");
            this.sqlite = e;
        } catch (e) {
            throw new qb.DriverPackageNotInstalledError("SQLite", "better-sqlite3");
        }
    }
    async createDatabaseDirectory(e) {
        await xb.default.mkdir(e, {
            recursive: true
        });
    }
    async attachDatabases() {
        for await (const {attachHandle: e, attachFilepathAbsolute: t} of Object.values(this.attachedDatabases)) {
            await this.createDatabaseDirectory($b.default.dirname(t));
            await this.connection.query(`ATTACH "${t}" AS "${e}"`);
        }
    }
    getMainDatabasePath() {
        const e = this.options.database;
        return $b.default.dirname((0, Fb.isAbsolute)(e) ? e : $b.default.join(this.options.baseDirectory, e));
    }
}

Ib.BetterSqlite3Driver = BetterSqlite3Driver;

var kb = {};

var Qb = {};

Object.defineProperty(Qb, "__esModule", {
    value: true
});

Qb.CapacitorQueryRunner = void 0;

const Vb = Dn();

const Kb = pn();

const Wb = Jy;

const Hb = _m;

const Gb = Lm;

class CapacitorQueryRunner extends Wb.AbstractSqliteQueryRunner {
    constructor(e) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.broadcaster = new Hb.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 Vb.QueryRunnerAlreadyReleasedError;
        const t = await this.connect();
        return t.executeSet(e, false);
    }
    async query(e, t, n = false) {
        if (this.isReleased) throw new Vb.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 s;
            if ([ "BEGIN", "ROLLBACK", "COMMIT", "CREATE", "ALTER", "DROP" ].indexOf(r) !== -1) {
                s = await a.execute(e, false);
            } else if ([ "INSERT", "UPDATE", "DELETE" ].indexOf(r) !== -1) {
                s = await a.run(e, t, false);
            } else {
                s = await a.query(e, t || []);
            }
            const i = new Gb.QueryResult;
            if (s?.hasOwnProperty("values")) {
                i.raw = s.values;
                i.records = s.values;
            }
            if (s?.hasOwnProperty("changes")) {
                i.affected = s.changes.changes;
                i.raw = s.changes.lastId || s.changes.changes;
            }
            if (!n) {
                return i.raw;
            }
            return i;
        } catch (n) {
            this.driver.connection.logger.logQueryError(n, e, t, this);
            throw new Kb.QueryFailedError(e, t, n);
        }
    }
    parametrize(e) {
        return Object.keys(e).map(e => `"${e}"` + "=?");
    }
}

Qb.CapacitorQueryRunner = CapacitorQueryRunner;

Object.defineProperty(kb, "__esModule", {
    value: true
});

kb.CapacitorDriver = void 0;

const Yb = mE;

const zb = Qb;

const Jb = exports.error;

class CapacitorDriver extends Yb.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 zb.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 Jb.DriverPackageNotInstalledError("Capacitor", "@capacitor-community/sqlite");
        }
    }
}

kb.CapacitorDriver = CapacitorDriver;

var Xb = {};

var Zb = {};

Object.defineProperty(Zb, "__esModule", {
    value: true
});

Zb.SpannerQueryRunner = void 0;

const eA = exports.error;

const tA = pn();

const nA = Dn();

const aA = we();

const rA = Cm;

const sA = Lm;

const iA = su;

const oA = hu;

const cA = iu;

const lA = cu;

const uA = ou;

const hA = uu;

const dA = lm;

const pA = _m;

const mA = ic;

const fA = Dc;

const yA = Rm;

const EA = $m;

class SpannerQueryRunner extends rA.BaseQueryRunner {
    constructor(e, t) {
        super();
        this.driver = e;
        this.connection = e.connection;
        this.mode = t;
        this.broadcaster = new pA.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 aA.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 aA.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 nA.QueryRunnerAlreadyReleasedError;
        await this.connect();
        this.driver.connection.logger.logQuery(e, t, this);
        await this.broadcaster.broadcast("BeforeQuery", e, t);
        const a = new mA.BroadcasterResult;
        try {
            const r = Date.now();
            let s = undefined;
            const i = e.startsWith("SELECT");
            const o = i && !this.isTransactionActive ? this.driver.instanceDatabase : this.sessionTransaction;
            if (!this.isTransactionActive && !i) {
                await this.sessionTransaction.begin();
            }
            try {
                s = await o.run({
                    sql: e,
                    params: t ? t.reduce((e, t, n) => {
                        e["param" + n] = t;
                        return e;
                    }, {}) : undefined,
                    json: true
                });
                if (!this.isTransactionActive && !i) {
                    await this.sessionTransaction.commit();
                }
            } catch (e) {
                try {
                    if (!this.isTransactionActive && !i) 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, s, undefined);
            if (c && u > c) this.driver.connection.logger.logQuerySlow(u, e, t, this);
            const h = new sA.QueryResult;
            h.raw = s;
            h.records = s ? s[0] : [];
            if (s && s[1] && s[1].rowCountExact) {
                h.affected = parseInt(s[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 tA.QueryFailedError(e, t, n);
        } finally {
            await a.wait();
        }
    }
    async updateDDL(e, t) {
        if (this.isReleased) throw new nA.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 s = Date.now();
            const i = s - n;
            if (r && i > r) this.driver.connection.logger.logQuerySlow(i, e, t, this);
        } catch (n) {
            this.driver.connection.logger.logQueryError(n, e, t, this);
            throw new tA.QueryFailedError(e, t, n);
        }
    }
    async stream(e, t, n, a) {
        if (this.isReleased) throw new nA.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 s = this.driver.instanceDatabase.runStream(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 tA.QueryFailedError(e, t, n);
        }
    }
    async getDatabases() {
        return Promise.resolve([]);
    }
    async getSchemas(e) {
        return Promise.resolve([]);
    }
    async hasDatabase(e) {
        throw new eA.TypeORMError(`Check database queries are not supported by Spanner driver.`);
    }
    async getCurrentDatabase() {
        throw new eA.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 eA.TypeORMError(`Check schema queries are not supported by Spanner driver.`);
    }
    async hasTable(e) {
        const t = e instanceof iA.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 iA.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 yA.Query(n), new yA.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 yA.Query(n), new yA.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 s = [];
        r.push(this.createTableSql(e, n));
        s.push(this.dropTableSql(e));
        if (n) e.foreignKeys.forEach(t => s.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));
                s.push(this.dropIndexSql(e, t));
            });
        }
        const i = e.columns.filter(e => e.generatedType && e.asExpression);
        for (const t of i) {
            const n = this.insertTypeormMetadataSql({
                table: e.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const a = this.deleteTypeormMetadataSql({
                table: e.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(n);
            s.push(a);
        }
        await this.executeQueries(r, s);
    }
    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 s = this.getTablePath(e);
        const i = await this.getCachedTable(s);
        const o = [];
        const c = [];
        if (a) {
            i.indices.forEach(e => {
                o.push(this.dropIndexSql(i, e));
                c.push(this.createIndexSql(i, e));
            });
        }
        if (n) i.foreignKeys.forEach(e => o.push(this.dropForeignKeySql(i, e)));
        o.push(this.dropTableSql(i));
        c.push(this.createTableSql(i, r));
        const l = i.columns.filter(e => e.generatedType && e.asExpression);
        for (const e of l) {
            const t = this.deleteTypeormMetadataSql({
                table: i.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: e.name
            });
            const n = this.insertTypeormMetadataSql({
                table: i.name,
                type: EA.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 dA.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 eA.TypeORMError(`Rename table queries are not supported by Spanner driver.`);
    }
    async addColumn(e, t) {
        const n = e instanceof iA.Table ? e : await this.getCachedTable(e);
        const a = n.clone();
        const r = [];
        const s = [];
        r.push(new yA.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(t)}`));
        s.push(new yA.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN ${this.driver.escape(t.name)}`));
        const i = a.indices.find(e => e.columnNames.length === 1 && e.columnNames[0] === t.name);
        if (i) {
            r.push(this.createIndexSql(n, i));
            s.push(this.dropIndexSql(n, i));
        } else if (t.isUnique) {
            const e = new uA.TableIndex({
                name: this.connection.namingStrategy.indexName(n, [ t.name ]),
                columnNames: [ t.name ],
                isUnique: true
            });
            a.indices.push(e);
            a.uniques.push(new hA.TableUnique({
                name: e.name,
                columnNames: e.columnNames
            }));
            r.push(this.createIndexSql(n, e));
            s.push(this.dropIndexSql(n, e));
        }
        if (t.generatedType && t.asExpression) {
            const e = this.insertTypeormMetadataSql({
                table: n.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: t.name,
                value: t.asExpression
            });
            const a = this.deleteTypeormMetadataSql({
                table: n.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: t.name
            });
            r.push(e);
            s.push(a);
        }
        await this.executeQueries(r, s);
        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 iA.Table ? e : await this.getCachedTable(e);
        const r = t instanceof cA.TableColumn ? t : a.columns.find(e => e.name === t);
        if (!r) throw new eA.TypeORMError(`Column "${t}" was not found in the "${a.name}" table.`);
        let s;
        if (n instanceof cA.TableColumn) {
            s = n;
        } else {
            s = r.clone();
            s.name = n;
        }
        return this.changeColumn(a, r, s);
    }
    async changeColumn(e, t, n) {
        const a = e instanceof iA.Table ? e : await this.getCachedTable(e);
        let r = a.clone();
        const s = [];
        const i = [];
        const o = t instanceof cA.TableColumn ? t : a.columns.find(e => e.name === t);
        if (!o) throw new eA.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) {
                s.push(new yA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(n)}`));
                i.push(new yA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${n.name}" TYPE ${this.driver.createFullType(o)}`));
            }
            if (o.isNullable !== n.isNullable) {
                if (n.isNullable) {
                    s.push(new yA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" DROP NOT NULL`));
                    i.push(new yA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" SET NOT NULL`));
                } else {
                    s.push(new yA.Query(`ALTER TABLE ${this.escapePath(a)} ALTER COLUMN "${o.name}" SET NOT NULL`));
                    i.push(new yA.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 uA.TableIndex({
                        name: this.connection.namingStrategy.indexName(a, [ n.name ]),
                        columnNames: [ n.name ],
                        isUnique: true
                    });
                    r.indices.push(e);
                    r.uniques.push(new hA.TableUnique({
                        name: e.name,
                        columnNames: e.columnNames
                    }));
                    s.push(this.createIndexSql(a, e));
                    i.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);
                    s.push(this.dropIndexSql(a, e));
                    i.push(this.createIndexSql(a, e));
                }
            }
        }
        await this.executeQueries(s, i);
        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 iA.Table ? e : await this.getCachedTable(e);
        const a = t instanceof cA.TableColumn ? t : n.findColumnByName(t);
        if (!a) throw new eA.TypeORMError(`Column "${t}" was not found in table "${n.name}"`);
        const r = n.clone();
        const s = [];
        const i = [];
        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);
            s.push(this.dropIndexSql(n, o));
            i.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);
            s.push(this.dropCheckConstraintSql(n, c));
            i.push(this.createCheckConstraintSql(n, c));
        }
        s.push(new yA.Query(`ALTER TABLE ${this.escapePath(n)} DROP COLUMN ${this.driver.escape(a.name)}`));
        i.push(new yA.Query(`ALTER TABLE ${this.escapePath(n)} ADD ${this.buildCreateColumnSql(a)}`));
        if (a.generatedType && a.asExpression) {
            const e = this.deleteTypeormMetadataSql({
                table: n.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: a.name
            });
            const t = this.insertTypeormMetadataSql({
                table: n.name,
                type: EA.MetadataTableType.GENERATED_COLUMN,
                name: a.name,
                value: a.asExpression
            });
            s.push(e);
            i.push(t);
        }
        await this.executeQueries(s, i);
        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 eA.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
    }
    async createUniqueConstraints(e, t) {
        throw new eA.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraint(e, t) {
        throw new eA.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
    }
    async dropUniqueConstraints(e, t) {
        throw new eA.TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
    }
    async createCheckConstraint(e, t) {
        const n = e instanceof iA.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 iA.Table ? e : await this.getCachedTable(e);
        const a = t instanceof oA.TableCheck ? t : n.checks.find(e => e.name === t);
        if (!a) throw new eA.TypeORMError(`Supplied check constraint was not found in table ${n.name}`);
        const r = this.dropCheckConstraintSql(n, a);
        const s = this.createCheckConstraintSql(n, a);
        await this.executeQueries(r, s);
        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 eA.TypeORMError(`Spanner does not support exclusion constraints.`);
    }
    async createExclusionConstraints(e, t) {
        throw new eA.TypeORMError(`Spanner does not support exclusion constraints.`);
    }
    async dropExclusionConstraint(e, t) {
        throw new eA.TypeORMError(`Spanner does not support exclusion constraints.`);
    }
    async dropExclusionConstraints(e, t) {
        throw new eA.TypeORMError(`Spanner does not support exclusion constraints.`);
    }
    async createForeignKey(e, t) {
        const n = e instanceof iA.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 iA.Table ? e : await this.getCachedTable(e);
        const a = t instanceof lA.TableForeignKey ? t : n.foreignKeys.find(e => e.name === t);
        if (!a) throw new eA.TypeORMError(`Supplied foreign key was not found in table ${n.name}`);
        const r = this.dropForeignKeySql(n, a);
        const s = this.createForeignKeySql(n, a);
        await this.executeQueries(r, s);
        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 iA.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 iA.Table ? e : await this.getCachedTable(e);
        const a = t instanceof uA.TableIndex ? t : n.indices.find(e => e.name === t);
        if (!a) throw new eA.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 s = this.createIndexSql(n, a);
        await this.executeQueries(r, s);
        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 s = await this.query(r);
        if (!t.length && !a.length && !s.length) return;
        const i = this.isTransactionActive;
        if (!i) 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 s) {
                await this.updateDDL(e["query"]);
            }
            await this.commitTransaction();
        } catch (e) {
            try {
                if (!i) 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 s = `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 i = `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(s), this.query(i), this.query(o) ]);
        return Promise.all(t.map(async e => {
            const t = new iA.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 s = a.length > 0 && r && r.indices.some(e => a.some(t => e.name === t["INDEX_NAME"] && e.synchronize === false));
                const i = a.every(e => u.some(t => t["INDEX_NAME"] === e["INDEX_NAME"] && t["COLUMN_NAME"] !== n["COLUMN_NAME"]));
                const o = new cA.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: EA.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 && !s && !i;
                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 = fA.OrmUtils.uniq(n, e => e["CONSTRAINT_NAME"]).map(e => {
                const t = n.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
                return new lA.TableForeignKey({
                    name: e["CONSTRAINT_NAME"],
                    columnNames: fA.OrmUtils.uniq(t.map(e => e["COLUMN_NAME"])),
                    referencedDatabase: e["REFERENCED_TABLE_SCHEMA"],
                    referencedTableName: e["REFERENCED_TABLE_NAME"],
                    referencedColumnNames: fA.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 = fA.OrmUtils.uniq(a, e => e["INDEX_NAME"]).map(e => {
                const n = a.filter(t => t["INDEX_NAME"] === e["INDEX_NAME"]);
                return new uA.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 = fA.OrmUtils.uniq(r, e => e["CONSTRAINT_NAME"]).map(e => {
                const t = r.filter(t => t["CONSTRAINT_NAME"] === e["CONSTRAINT_NAME"]);
                return new oA.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 uA.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 uA.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 yA.Query(a);
    }
    dropTableSql(e) {
        return new yA.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 yA.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 ? EA.MetadataTableType.MATERIALIZED_VIEW : EA.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 yA.Query(`DROP ${t}VIEW ${this.escapePath(e)}`);
    }
    async deleteViewDefinitionSql(e) {
        const {schema: t, tableName: n} = this.driver.parseTableName(e);
        const a = e.materialized ? EA.MetadataTableType.MATERIALIZED_VIEW : EA.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 yA.Query(`CREATE ${a}INDEX \`${t.name}\` ON ${this.escapePath(e)} (${n})`);
    }
    dropIndexSql(e, t) {
        const n = t instanceof uA.TableIndex ? t.name : t;
        return new yA.Query(`DROP INDEX \`${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 = t instanceof oA.TableCheck ? t.name : t;
        return new yA.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 yA.Query(r);
    }
    dropForeignKeySql(e, t) {
        const n = t instanceof lA.TableForeignKey ? t.name : t;
        return new yA.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 yA.Query) e = [ e ];
        if (t instanceof yA.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 eA.TypeORMError(`spanner driver does not support change table comment.`);
    }
}

Zb.SpannerQueryRunner = SpannerQueryRunner;

Object.defineProperty(Xb, "__esModule", {
    value: true
});

Xb.SpannerDriver = void 0;

const TA = Mt();

const gA = Zb;

const NA = xd;

const bA = exports.PlatformTools;

const AA = cm;

const CA = ep;

const RA = Dc;

const SA = Bi;

const wA = su;

const OA = lm;

const MA = cu;

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 AA.RdbmsSchemaBuilder(this.connection);
    }
    createQueryRunner(e) {
        return new gA.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, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            if (r.has(s)) {
                return this.parametersPrefix + r.get(s);
            }
            const i = t[s];
            if (i === null) {
                return e;
            }
            if (n) {
                return i.map(e => {
                    a.push(e);
                    return this.createParameter(s, a.length - 1);
                }).join(", ");
            }
            if (i instanceof Function) {
                return i();
            }
            a.push(i);
            r.set(s, a.length - 1);
            return this.createParameter(s, a.length - 1);
        });
        e = e.replace(/([ ]+)?=([ ]+)?:(\.\.\.)?([A-Za-z0-9_.]+)/g, (e, n, a, r, s) => {
            if (!t.hasOwnProperty(s)) {
                return e;
            }
            const i = t[s];
            if (i === 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 wA.Table || e instanceof OA.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 MA.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 CA.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 = SA.ApplyValueTransformers.transformTo(t.transformer, e);
        if (e === null || e === undefined) return e;
        if (t.type === "numeric") {
            const t = this.options.driver || bA.PlatformTools.load("spanner");
            return t.Spanner.numeric(e.toString());
        } else if (t.type === "date") {
            return NA.DateUtils.mixedDateToDateString(e);
        } else if (t.type === "json") {
            return e;
        } else if (t.type === "timestamp" || t.type === Date) {
            return NA.DateUtils.mixedDateToDate(e);
        }
        return e;
    }
    prepareHydratedValue(e, t) {
        if (e === null || e === undefined) return t.transformer ? SA.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 = NA.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 = SA.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) {
                    RA.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 RA.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 || bA.PlatformTools.load("spanner");
            this.spanner = new e.Spanner({
                projectId: this.options.projectId
            });
        } catch (e) {
            console.error(e);
            throw new TA.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;
    }
}

Xb.SpannerDriver = SpannerDriver;

Object.defineProperty(im, "__esModule", {
    value: true
});

im.DriverFactory = void 0;

const vA = St();

const IA = om;

const PA = Tf;

const LA = Df;

const _A = Ey;

const DA = Yy;

const xA = IE;

const $A = kE;

const qA = aT;

const UA = pT;

const BA = MT;

const jA = og;

const FA = kg;

const kA = dN;

const QA = BN;

const VA = JN;

const KA = Ib;

const WA = kb;

const HA = Xb;

class DriverFactory {
    create(e) {
        const {type: t} = e.options;
        switch (t) {
          case "mysql":
            return new BA.MysqlDriver(e);

          case "postgres":
            return new jA.PostgresDriver(e);

          case "cockroachdb":
            return new IA.CockroachDriver(e);

          case "sap":
            return new VA.SapDriver(e);

          case "mariadb":
            return new BA.MysqlDriver(e);

          case "sqlite":
            return new DA.SqliteDriver(e);

          case "better-sqlite3":
            return new KA.BetterSqlite3Driver(e);

          case "cordova":
            return new xA.CordovaDriver(e);

          case "nativescript":
            return new qA.NativescriptDriver(e);

          case "react-native":
            return new $A.ReactNativeDriver(e);

          case "sqljs":
            return new UA.SqljsDriver(e);

          case "oracle":
            return new _A.OracleDriver(e);

          case "mssql":
            return new LA.SqlServerDriver(e);

          case "mongodb":
            return new PA.MongoDriver(e);

          case "expo":
            return new FA.ExpoDriverFactory(e).create();

          case "aurora-mysql":
            return new kA.AuroraMysqlDriver(e);

          case "aurora-postgres":
            return new QA.AuroraPostgresDriver(e);

          case "capacitor":
            return new WA.CapacitorDriver(e);

          case "spanner":
            return new HA.SpannerDriver(e);

          default:
            throw new vA.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" ]);
        }
    }
}

im.DriverFactory = DriverFactory;

var GA = {};

var YA = {};

var zA = {};

var JA = {};

var XA;

var ZA;

function eC() {
    if (ZA) return XA;
    ZA = 1;
    XA = e;
    function e(e, a, r) {
        if (e instanceof RegExp) e = t(e, r);
        if (a instanceof RegExp) a = t(a, r);
        var s = n(e, a, r);
        return s && {
            start: s[0],
            end: s[1],
            pre: r.slice(0, s[0]),
            body: r.slice(s[0] + e.length, s[1]),
            post: r.slice(s[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, s, i, 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 = [];
            s = 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 < s) {
                        s = r;
                        i = l;
                    }
                    l = n.indexOf(t, u + 1);
                }
                u = c < l && c >= 0 ? c : l;
            }
            if (a.length) {
                o = [ s, i ];
            }
        }
        return o;
    }
    return XA;
}

var tC;

var nC;

function aC() {
    if (nC) return tC;
    nC = 1;
    var e = eC();
    tC = 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 s = "\0PERIOD" + Math.random() + "\0";
    function i(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(s);
    }
    function c(e) {
        return e.split(t).join("\\").split(n).join("{").split(a).join("}").split(r).join(",").split(s).join(".");
    }
    function l(t) {
        if (!t) return [ "" ];
        var n = [];
        var a = e("{", "}", t);
        if (!a) return t.split(",");
        var r = a.pre;
        var s = a.body;
        var i = a.post;
        var o = r.split(",");
        o[o.length - 1] += "{" + s + "}";
        var c = l(i);
        if (i.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 s = e("{", "}", t);
        if (!s) return [ t ];
        var o = s.pre;
        var c = s.post.length ? f(s.post, false) : [ "" ];
        if (/\$$/.test(s.pre)) {
            for (var u = 0; u < c.length; u++) {
                var y = o + "{" + s.body + "}" + c[u];
                r.push(y);
            }
        } else {
            var E = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);
            var T = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);
            var g = E || T;
            var N = s.body.indexOf(",") >= 0;
            if (!g && !N) {
                if (s.post.match(/,(?!,).*\}/)) {
                    t = s.pre + "{" + s.body + a + s.post;
                    return f(t);
                }
                return [ t ];
            }
            var b;
            if (g) {
                b = s.body.split(/\.\./);
            } else {
                b = l(s.body);
                if (b.length === 1) {
                    b = f(b[0], false).map(h);
                    if (b.length === 1) {
                        return c.map(function(e) {
                            return s.pre + b[0] + e;
                        });
                    }
                }
            }
            var A;
            if (g) {
                var C = i(b[0]);
                var R = i(b[1]);
                var S = Math.max(b[0].length, b[1].length);
                var w = b.length == 3 ? Math.abs(i(b[2])) : 1;
                var O = p;
                var M = R < C;
                if (M) {
                    w *= -1;
                    O = m;
                }
                var v = b.some(d);
                A = [];
                for (var I = C; O(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 _ = new Array(L + 1).join("0");
                                if (I < 0) P = "-" + _ + P.slice(1); else P = _ + P;
                            }
                        }
                    }
                    A.push(P);
                }
            } else {
                A = [];
                for (var D = 0; D < b.length; D++) {
                    A.push.apply(A, f(b[D], false));
                }
            }
            for (var D = 0; D < A.length; D++) {
                for (var u = 0; u < c.length; u++) {
                    var y = o + A[D] + c[u];
                    if (!n || g || y) r.push(y);
                }
            }
        }
        return r;
    }
    return tC;
}

var rC = {};

var sC;

function iC() {
    if (sC) return rC;
    sC = 1;
    Object.defineProperty(rC, "__esModule", {
        value: true
    });
    rC.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");
        }
    };
    rC.assertValidPattern = t;
    return rC;
}

var oC = {};

var cC = {};

var lC;

function uC() {
    if (lC) return cC;
    lC = 1;
    Object.defineProperty(cC, "__esModule", {
        value: true
    });
    cC.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, s) => {
        const i = s;
        if (r.charAt(i) !== "[") {
            throw new Error("not in a brace expression");
        }
        const o = [];
        const c = [];
        let l = i + 1;
        let u = false;
        let h = false;
        let d = false;
        let p = false;
        let m = i;
        let f = "";
        e: while (l < r.length) {
            const n = r.charAt(l);
            if ((n === "!" || n === "^") && l === i + 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, s]] of Object.entries(e)) {
                    if (r.startsWith(t, l)) {
                        if (f) {
                            return [ "$.", false, r.length - i, true ];
                        }
                        l += t.length;
                        if (s) 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 - i, 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 - i, 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 - i, true ];
    };
    cC.parseClass = r;
    return cC;
}

var hC = {};

var dC;

function pC() {
    if (dC) return hC;
    dC = 1;
    Object.defineProperty(hC, "__esModule", {
        value: true
    });
    hC.unescape = void 0;
    const e = (e, {windowsPathsNoEscape: t = false} = {}) => t ? e.replace(/\[([^\/\\])\]/g, "$1") : e.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    hC.unescape = e;
    return hC;
}

var mC;

function fC() {
    if (mC) return oC;
    mC = 1;
    Object.defineProperty(oC, "__esModule", {
        value: true
    });
    oC.AST = void 0;
    const e = uC();
    const t = pC();
    const n = new Set([ "!", "?", "+", "*", "@" ]);
    const a = e => n.has(e);
    const r = "(?!(?:^|/)\\.\\.?(?:$|/))";
    const s = "(?!\\.)";
    const i = 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;
        #s;
        #i;
        #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.#i = this.#e === this ? [] : this.#e.#i;
            if (e === "!" && !this.#e.#o) this.#i.push(this);
            this.#s = 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.#i.pop()) {
                if (e.type !== "!") continue;
                let t = e;
                let n = t.#r;
                while (n) {
                    for (let a = t.#s + 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.#s === 0) return true;
            const e = this.#r;
            for (let t = 0; t < this.#s; 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.#s === 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 s = false;
            let i = 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 (s || n === "\\") {
                        s = !s;
                        u += n;
                        continue;
                    }
                    if (i) {
                        if (l === o + 1) {
                            if (n === "^" || n === "!") {
                                c = true;
                            }
                        } else if (n === "]" && !(l === o + 2 && c)) {
                            i = false;
                        }
                        u += n;
                        continue;
                    } else if (n === "[") {
                        i = 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 (s || n === "\\") {
                    s = !s;
                    d += n;
                    continue;
                }
                if (i) {
                    if (l === o + 1) {
                        if (n === "^" || n === "!") {
                            c = true;
                        }
                    } else if (n === "]" && !(l === o + 2 && c)) {
                        i = false;
                    }
                    d += n;
                    continue;
                } else if (n === "[") {
                    i = 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 s = a || this.#t || this.#c.nocase && !this.#c.nocaseMagicOnly && e.toUpperCase() !== e.toLowerCase();
            if (!s) {
                return n;
            }
            const i = (this.#c.nocase ? "i" : "") + (r ? "u" : "");
            return Object.assign(new RegExp(`^${t}$`, i), {
                _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, s, i] = typeof t === "string" ? AST.#p(t, this.#t, a) : t.toRegExpSource(e);
                    this.#t = this.#t || s;
                    this.#n = this.#n || i;
                    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 = i;
                            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 ? s : "";
                        }
                    }
                }
                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 || !s ? "" : this.#m(true);
            if (u === l) {
                u = "";
            }
            if (u) {
                l = `(?:${l})(?:${u})*?`;
            }
            let p = "";
            if (this.type === "!" && this.#u) {
                p = (this.isStart() && !n ? s : "") + d;
            } else {
                const t = this.type === "!" ? "))" + (this.isStart() && !n && !e ? s : "") + 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, s] = t.toRegExpSource(e);
                this.#n = this.#n || s;
                return n;
            }).filter(e => !(this.isStart() && this.isEnd()) || !!e).join("|");
        }
        static #p(n, a, r = false) {
            let s = false;
            let i = "";
            let o = false;
            for (let t = 0; t < n.length; t++) {
                const p = n.charAt(t);
                if (s) {
                    s = false;
                    i += (c.has(p) ? "\\" : "") + p;
                    continue;
                }
                if (p === "\\") {
                    if (t === n.length - 1) {
                        i += "\\\\";
                    } else {
                        s = true;
                    }
                    continue;
                }
                if (p === "[") {
                    const [r, s, c, l] = (0, e.parseClass)(n, t);
                    if (c) {
                        i += r;
                        o = o || s;
                        t += c - 1;
                        a = a || l;
                        continue;
                    }
                }
                if (p === "*") {
                    if (r && n === "*") i += d; else i += h;
                    a = true;
                    continue;
                }
                if (p === "?") {
                    i += u;
                    a = true;
                    continue;
                }
                i += l(p);
            }
            return [ i, (0, t.unescape)(n), !!a, o ];
        }
    }
    oC.AST = AST;
    return oC;
}

var yC = {};

var EC;

function TC() {
    if (EC) return yC;
    EC = 1;
    Object.defineProperty(yC, "__esModule", {
        value: true
    });
    yC.escape = void 0;
    const e = (e, {windowsPathsNoEscape: t = false} = {}) => t ? e.replace(/[?*()[\]]/g, "[$&]") : e.replace(/[?*()[\]\\]/g, "\\$&");
    yC.escape = e;
    return yC;
}

var gC;

function NC() {
    if (gC) return JA;
    gC = 1;
    (function(e) {
        var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = t(aC());
        const r = iC();
        const s = fC();
        const i = TC();
        const o = pC();
        const c = (e, t, n = {}) => {
            (0, r.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 b = e => e.length !== 0 && e !== "." && e !== "..";
        const A = /^\?+([^+@!?\*\[\(]*)?$/;
        const C = ([e, t = ""]) => {
            const n = O([ e ]);
            if (!t) return n;
            t = t.toLowerCase();
            return e => n(e) && e.toLowerCase().endsWith(t);
        };
        const R = ([e, t = ""]) => {
            const n = M([ e ]);
            if (!t) return n;
            t = t.toLowerCase();
            return e => n(e) && e.toLowerCase().endsWith(t);
        };
        const S = ([e, t = ""]) => {
            const n = M([ e ]);
            return !t ? n : e => n(e) && e.endsWith(t);
        };
        const w = ([e, t = ""]) => {
            const n = O([ e ]);
            return !t ? n : e => n(e) && e.endsWith(t);
        };
        const O = ([e]) => {
            const t = e.length;
            return e => e.length === t && !e.startsWith(".");
        };
        const M = ([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 _ = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
        const D = "(?:(?!(?:\\/|^)\\.).)*?";
        const x = (t, n = {}) => a => (0, e.minimatch)(a, t, n);
        e.filter = x;
        e.minimatch.filter = e.filter;
        const $ = (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, $(t, r));
            return Object.assign(a, {
                Minimatch: class Minimatch extends n.Minimatch {
                    constructor(e, n = {}) {
                        super(e, $(t, n));
                    }
                    static defaults(e) {
                        return n.defaults($(t, e)).Minimatch;
                    }
                },
                AST: class AST extends n.AST {
                    constructor(e, n, a = {}) {
                        super(e, n, $(t, a));
                    }
                    static fromGlob(e, a = {}) {
                        return n.AST.fromGlob(e, $(t, a));
                    }
                },
                unescape: (e, a = {}) => n.unescape(e, $(t, a)),
                escape: (e, a = {}) => n.escape(e, $(t, a)),
                filter: (e, a = {}) => n.filter(e, $(t, a)),
                defaults: e => n.defaults($(t, e)),
                makeRe: (e, a = {}) => n.makeRe(e, $(t, a)),
                braceExpand: (e, a = {}) => n.braceExpand(e, $(t, a)),
                match: (e, a, r = {}) => n.match(e, a, $(t, r)),
                sep: n.sep,
                GLOBSTAR: e.GLOBSTAR
            });
        };
        e.defaults = q;
        e.minimatch.defaults = e.defaults;
        const U = (e, t = {}) => {
            (0, r.assertValidPattern)(e);
            if (t.nobrace || !/\{(?:(?!\{).)*\}/.test(e)) {
                return [ e ];
            }
            return (0, a.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 j = (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 = j;
        e.minimatch.match = e.match;
        const F = /[?*]|[+@!]\(.*?\)|\[|\]/;
        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, r.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] === "?" || !F.test(e[2])) && !F.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 s = n[a + 1];
                            const i = n[a + 2];
                            const o = n[a + 3];
                            if (s !== "..") continue;
                            if (!i || i === "." || i === ".." || !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 s = [];
                let i = "";
                while (a < e.length && r < t.length) {
                    if (e[a] === t[r]) {
                        s.push(i === "b" ? t[r] : e[a]);
                        a++;
                        r++;
                    } else if (n && e[a] === "**" && t[r] === e[a + 1]) {
                        s.push(e[a]);
                        a++;
                    } else if (n && t[r] === "**" && e[a] === t[r + 1]) {
                        s.push(t[r]);
                        r++;
                    } else if (e[a] === "*" && t[r] && (this.options.dot || !t[r].startsWith(".")) && t[r] !== "**") {
                        if (i === "b") return false;
                        i = "a";
                        s.push(e[a]);
                        a++;
                        r++;
                    } else if (t[r] === "*" && e[a] && (this.options.dot || !e[a].startsWith(".")) && e[a] !== "**") {
                        if (i === "a") return false;
                        i = "b";
                        s.push(t[r]);
                        a++;
                        r++;
                    } else {
                        return false;
                    }
                }
                return e.length === t.length && s;
            }
            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 s = !r && n[0] === "" && n[1] === "" && n[2] === "?" && typeof n[3] === "string" && /^[a-z]:$/i.test(n[3]);
                    const i = a ? 3 : e ? 0 : undefined;
                    const o = s ? 3 : r ? 0 : undefined;
                    if (typeof i === "number" && typeof o === "number") {
                        const [e, a] = [ t[i], n[o] ];
                        if (e.toLowerCase() === a.toLowerCase()) {
                            n[o] = e;
                            if (o > i) {
                                n = n.slice(o);
                            } else if (i > o) {
                                t = t.slice(i);
                            }
                        }
                    }
                }
                const {optimizationLevel: s = 1} = this.options;
                if (s >= 2) {
                    t = this.levelTwoFileOptimize(t);
                }
                this.debug("matchOne", this, {
                    file: t,
                    pattern: n
                });
                this.debug("matchOne", t.length, n.length);
                for (var i = 0, o = 0, c = t.length, l = n.length; i < c && o < l; i++, o++) {
                    this.debug("matchOne loop");
                    var u = n[o];
                    var h = t[i];
                    this.debug(n, u, h);
                    if (u === false) {
                        return false;
                    }
                    if (u === e.GLOBSTAR) {
                        this.debug("GLOBSTAR", [ n, u, h ]);
                        var d = i;
                        var p = o + 1;
                        if (p === l) {
                            this.debug("** at the end");
                            for (;i < c; i++) {
                                if (t[i] === "." || t[i] === ".." || !r.dot && t[i].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 s;
                    if (typeof u === "string") {
                        s = h === u;
                        this.debug("string match", u, h, s);
                    } else {
                        s = u.test(h);
                        this.debug("pattern match", u, h, s);
                    }
                    if (!s) return false;
                }
                if (i === c && o === l) {
                    return true;
                } else if (i === c) {
                    return a;
                } else if (o === l) {
                    return i === c - 1 && t[i] === "";
                } else {
                    throw new Error("wtf?");
                }
            }
            braceExpand() {
                return (0, e.braceExpand)(this.pattern, this.options);
            }
            parse(t) {
                (0, r.assertValidPattern)(t);
                const n = this.options;
                if (t === "**") return e.GLOBSTAR;
                if (t === "") return "";
                let a;
                let i = null;
                if (a = t.match(g)) {
                    i = n.dot ? b : N;
                } else if (a = t.match(l)) {
                    i = (n.nocase ? n.dot ? p : d : n.dot ? h : u)(a[1]);
                } else if (a = t.match(A)) {
                    i = (n.nocase ? n.dot ? R : C : n.dot ? S : w)(a);
                } else if (a = t.match(m)) {
                    i = n.dot ? y : f;
                } else if (a = t.match(E)) {
                    i = T;
                }
                const o = s.AST.fromGlob(t, this.options).toMMPattern();
                if (i && typeof o === "object") {
                    Reflect.defineProperty(o, "test", {
                        value: i
                    });
                }
                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 s = 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 s = n[r + 1];
                        const i = n[r - 1];
                        if (t !== e.GLOBSTAR || i === e.GLOBSTAR) {
                            return;
                        }
                        if (i === undefined) {
                            if (s !== undefined && s !== e.GLOBSTAR) {
                                n[r + 1] = "(?:\\/|" + a + "\\/)?" + s;
                            } else {
                                n[r] = a;
                            }
                        } else if (s === undefined) {
                            n[r - 1] = i + "(?:\\/|" + a + ")?";
                        } else if (s !== e.GLOBSTAR) {
                            n[r - 1] = i + "(?:\\/|\\/" + a + "\\/)" + s;
                            n[r + 1] = e.GLOBSTAR;
                        }
                    });
                    return n.filter(t => t !== e.GLOBSTAR).join("/");
                }).join("|");
                const [i, o] = t.length > 1 ? [ "(?:", ")" ] : [ "", "" ];
                s = "^" + i + s + o + "$";
                if (this.negate) s = "^(?!" + s + ").+$";
                try {
                    this.regexp = new RegExp(s, [ ...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 s = a[a.length - 1];
                if (!s) {
                    for (let e = a.length - 2; !s && e >= 0; e--) {
                        s = a[e];
                    }
                }
                for (let e = 0; e < r.length; e++) {
                    const i = r[e];
                    let o = a;
                    if (n.matchBase && i.length === 1) {
                        o = [ s ];
                    }
                    const c = this.matchOne(o, i, 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 = fC();
        Object.defineProperty(e, "AST", {
            enumerable: true,
            get: function() {
                return Q.AST;
            }
        });
        var V = TC();
        Object.defineProperty(e, "escape", {
            enumerable: true,
            get: function() {
                return V.escape;
            }
        });
        var K = pC();
        Object.defineProperty(e, "unescape", {
            enumerable: true,
            get: function() {
                return K.unescape;
            }
        });
        e.minimatch.AST = s.AST;
        e.minimatch.Minimatch = Minimatch;
        e.minimatch.escape = i.escape;
        e.minimatch.unescape = o.unescape;
    })(JA);
    return JA;
}

var bC = {};

var AC = {};

var CC = {};

var RC;

function SC() {
    if (RC) return CC;
    RC = 1;
    Object.defineProperty(CC, "__esModule", {
        value: true
    });
    CC.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 s = globalThis.AbortSignal;
    if (typeof r === "undefined") {
        s = class AbortSignal {
            onabort;
            _onabort=[];
            reason;
            aborted=false;
            addEventListener(e, t) {
                this._onabort.push(t);
            }
        };
        r = class AbortController {
            constructor() {
                t();
            }
            signal=new s;
            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 i = 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;
        #b;
        ttl;
        ttlResolution;
        ttlAutopurge;
        updateAgeOnGet;
        updateAgeOnHas;
        allowStale;
        noDisposeOnSet;
        noUpdateTTL;
        maxEntrySize;
        sizeCalculation;
        noDeleteOnFetchRejection;
        noDeleteOnStaleGet;
        allowStaleOnFetchAbort;
        allowStaleOnFetchRejection;
        ignoreFetchAbort;
        #A;
        #C;
        #R;
        #S;
        #w;
        #O;
        #M;
        #v;
        #I;
        #P;
        #L;
        #_;
        #D;
        #x;
        #$;
        #q;
        #U;
        static unsafeExposeInternals(e) {
            return {
                starts: e.#D,
                ttls: e.#x,
                sizes: e.#_,
                keyMap: e.#R,
                keyList: e.#S,
                valList: e.#w,
                next: e.#O,
                prev: e.#M,
                get head() {
                    return e.#v;
                },
                get tail() {
                    return e.#I;
                },
                free: e.#P,
                isBackgroundFetch: t => e.#B(t),
                backgroundFetch: (t, n, a, r) => e.#j(t, n, a, r),
                moveToTail: t => e.#F(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.#A;
        }
        get fetchMethod() {
            return this.#N;
        }
        get memoMethod() {
            return this.#b;
        }
        get dispose() {
            return this.#T;
        }
        get disposeAfter() {
            return this.#g;
        }
        constructor(e) {
            const {max: n = 0, ttl: r, ttlResolution: s = 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: b, noDeleteOnFetchRejection: A, 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 O = n ? c(n) : Array;
            if (!O) {
                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 (b !== undefined && typeof b !== "function") {
                throw new TypeError("memoMethod must be a function if defined");
            }
            this.#b = b;
            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.#O = new O(n);
            this.#M = new O(n);
            this.#v = 0;
            this.#I = 0;
            this.#P = Stack.create(n);
            this.#A = 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.#$ = !!this.#T;
            this.#U = !!this.#g;
            this.noDisposeOnSet = !!f;
            this.noUpdateTTL = !!y;
            this.noDeleteOnFetchRejection = !!A;
            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(s) || s === 0 ? s : 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 (i(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.#x = t;
            this.#D = n;
            this.#H = (a, r, s = e.now()) => {
                n[a] = r !== 0 ? s : 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, s) => {
                if (t[s]) {
                    const i = t[s];
                    const o = n[s];
                    if (!i || !o) return;
                    e.ttl = i;
                    e.start = o;
                    e.now = a || r();
                    const c = e.now - o;
                    e.remainingTTL = i - 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 s = this.#R.get(e);
                if (s === undefined) {
                    return 0;
                }
                const i = t[s];
                const o = n[s];
                if (!i || !o) {
                    return Infinity;
                }
                const c = (a || r()) - o;
                return i - c;
            };
            this.#V = e => {
                const s = n[e];
                const i = t[e];
                return !!i && !!s && (a || r()) - s > i;
            };
        }
        #Y=() => {};
        #z=() => {};
        #H=() => {};
        #V=() => false;
        #K() {
            const e = new ZeroArray(this.#y);
            this.#C = 0;
            this.#_ = 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.#A) {
                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.#M[t];
                    }
                }
            }
        }
        * #Q({allowStale: e = this.allowStale} = {}) {
            if (this.#A) {
                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.#O[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 s = {
                value: r
            };
            if (this.#x && this.#D) {
                const t = this.#x[n];
                const a = this.#D[n];
                if (t && a) {
                    const n = t - (e.now() - a);
                    s.ttl = n;
                    s.start = Date.now();
                }
            }
            if (this.#_) {
                s.size = this.#_[n];
            }
            return s;
        }
        dump() {
            const t = [];
            for (const n of this.#k({
                allowStale: true
            })) {
                const a = this.#S[n];
                const r = this.#w[n];
                const s = this.#B(r) ? r.__staleWhileFetching : r;
                if (s === undefined || a === undefined) continue;
                const i = {
                    value: s
                };
                if (this.#x && this.#D) {
                    i.ttl = this.#x[n];
                    const t = e.now() - this.#D[n];
                    i.start = Math.floor(Date.now() - t);
                }
                if (this.#_) {
                    i.size = this.#_[n];
                }
                t.unshift([ a, i ]);
            }
            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: s = this.noDisposeOnSet, sizeCalculation: i = this.sizeCalculation, status: o} = n;
            let {noUpdateTTL: c = this.noUpdateTTL} = n;
            const l = this.#X(e, t, n.size || 0, i);
            if (this.maxEntrySize && l > this.maxEntrySize) {
                if (o) {
                    o.set = "miss";
                    o.maxEntrySizeExceeded = true;
                }
                this.#G(e, "set");
                return this;
            }
            let u = this.#A === 0 ? undefined : this.#R.get(e);
            if (u === undefined) {
                u = this.#A === 0 ? this.#I : this.#P.length !== 0 ? this.#P.pop() : this.#A === this.#y ? this.#ee(false) : this.#A;
                this.#S[u] = e;
                this.#w[u] = t;
                this.#R.set(e, u);
                this.#O[this.#I] = u;
                this.#M[u] = this.#I;
                this.#I = u;
                this.#A++;
                this.#Z(u, l, o);
                if (o) o.set = "add";
                c = false;
            } else {
                this.#F(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 && !s) {
                            if (this.#$) {
                                this.#T?.(t, e, "set");
                            }
                            if (this.#U) {
                                this.#L?.push([ t, e, "set" ]);
                            }
                        }
                    } else if (!s) {
                        if (this.#$) {
                            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.#x) {
                this.#W();
            }
            if (this.#x) {
                if (!c) {
                    this.#H(u, a, r);
                }
                if (o) this.#z(o, u);
            }
            if (!s && this.#U && this.#L) {
                const e = this.#L;
                let t;
                while (t = e?.shift()) {
                    this.#g?.(...t);
                }
            }
            return this;
        }
        pop() {
            try {
                while (this.#A) {
                    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.#$ || this.#U) {
                if (this.#$) {
                    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.#A === 1) {
                this.#v = this.#I = 0;
                this.#P.length = 0;
            } else {
                this.#v = this.#O[t];
            }
            this.#R.delete(n);
            this.#A--;
            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;
        }
        #j(e, t, n, a) {
            const s = t === undefined ? undefined : this.#w[t];
            if (this.#B(s)) {
                return s;
            }
            const i = new r;
            const {signal: o} = n;
            o?.addEventListener("abort", () => i.abort(o.reason), {
                signal: i.signal
            });
            const c = {
                signal: i.signal,
                options: n,
                context: a
            };
            const l = (a, r = false) => {
                const {aborted: s} = i.signal;
                const o = n.ignoreFetchAbort && a !== undefined;
                if (n.status) {
                    if (s && !r) {
                        n.status.fetchAborted = true;
                        n.status.fetchError = i.signal.reason;
                        if (o) n.status.fetchAbortIgnored = true;
                    } else {
                        n.status.fetchResolved = true;
                    }
                }
                if (s && !o && !r) {
                    return h(i.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} = i.signal;
                const s = r && n.allowStaleOnFetchAbort;
                const o = s || 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 (!s) {
                        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, s, c);
                if (r && r instanceof Promise) {
                    r.then(e => t(e === undefined ? undefined : e), a);
                }
                i.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: i,
                __staleWhileFetching: s,
                __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: s = this.ttl, noDisposeOnSet: i = 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: s,
                noDisposeOnSet: i,
                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.#j(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.#F(g);
                    if (a) {
                        this.#Y(g);
                    }
                    if (y) this.#z(y, g);
                    return t;
                }
                const s = this.#j(e, g, T, m);
                const i = s.__staleWhileFetching !== undefined;
                const o = i && n;
                if (y) {
                    y.fetch = r ? "stale" : "refresh";
                    if (o && r) y.returnedStale = true;
                }
                return o ? s.__staleWhileFetching : s.__returned = s;
            }
        }
        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.#b;
            if (!n) {
                throw new Error("no memoMethod provided to constructor");
            }
            const {context: a, forceRefresh: r, ...s} = t;
            const i = this.get(e, s);
            if (!r && i !== undefined) return i;
            const o = n(e, i, {
                options: s,
                context: a
            });
            this.set(e, o, s);
            return o;
        }
        get(e, t = {}) {
            const {allowStale: n = this.allowStale, updateAgeOnGet: a = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, status: s} = t;
            const i = this.#R.get(e);
            if (i !== undefined) {
                const t = this.#w[i];
                const o = this.#B(t);
                if (s) this.#z(s, i);
                if (this.#V(i)) {
                    if (s) s.get = "stale";
                    if (!o) {
                        if (!r) {
                            this.#G(e, "expire");
                        }
                        if (s && n) s.returnedStale = true;
                        return n ? t : undefined;
                    } else {
                        if (s && n && t.__staleWhileFetching !== undefined) {
                            s.returnedStale = true;
                        }
                        return n ? t.__staleWhileFetching : undefined;
                    }
                } else {
                    if (s) s.get = "hit";
                    if (o) {
                        return t.__staleWhileFetching;
                    }
                    this.#F(i);
                    if (a) {
                        this.#Y(i);
                    }
                    return t;
                }
            } else if (s) {
                s.get = "miss";
            }
        }
        #ne(e, t) {
            this.#M[t] = e;
            this.#O[e] = t;
        }
        #F(e) {
            if (e !== this.#I) {
                if (e === this.#v) {
                    this.#v = this.#O[e];
                } else {
                    this.#ne(this.#M[e], this.#O[e]);
                }
                this.#ne(this.#I, e);
                this.#I = e;
            }
        }
        delete(e) {
            return this.#G(e, "delete");
        }
        #G(e, t) {
            let n = false;
            if (this.#A !== 0) {
                const a = this.#R.get(e);
                if (a !== undefined) {
                    n = true;
                    if (this.#A === 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.#$ || this.#U) {
                            if (this.#$) {
                                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.#M[a];
                        } else if (a === this.#v) {
                            this.#v = this.#O[a];
                        } else {
                            const e = this.#M[a];
                            this.#O[e] = this.#O[a];
                            const t = this.#O[a];
                            this.#M[t] = this.#M[a];
                        }
                        this.#A--;
                        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.#$) {
                        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.#x && this.#D) {
                this.#x.fill(0);
                this.#D.fill(0);
            }
            if (this.#_) {
                this.#_.fill(0);
            }
            this.#v = 0;
            this.#I = 0;
            this.#P.length = 0;
            this.#C = 0;
            this.#A = 0;
            if (this.#U && this.#L) {
                const e = this.#L;
                let t;
                while (t = e?.shift()) {
                    this.#g?.(...t);
                }
            }
        }
    }
    CC.LRUCache = LRUCache;
    return CC;
}

var wC = {};

var OC;

function MC() {
    if (OC) return wC;
    OC = 1;
    (function(e) {
        var t = n.commonjsGlobal && n.commonjsGlobal.__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 a = typeof process === "object" && process ? process : {
            stdout: null,
            stderr: null
        };
        const r = $.default;
        const s = t(q.default);
        const i = U.default;
        const o = t => !!t && typeof t === "object" && (t instanceof Minipass || t instanceof s.default || (0, 
        e.isReadable)(t) || (0, e.isWritable)(t));
        e.isStream = o;
        const c = e => !!e && typeof e === "object" && e instanceof r.EventEmitter && typeof e.pipe === "function" && e.pipe !== s.default.Writable.prototype.pipe;
        e.isReadable = c;
        const l = e => !!e && typeof e === "object" && e instanceof r.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 b = Symbol("flowing");
        const A = Symbol("paused");
        const C = Symbol("resume");
        const R = Symbol("buffer");
        const S = Symbol("pipes");
        const w = Symbol("bufferLength");
        const O = Symbol("bufferPush");
        const M = Symbol("bufferShift");
        const v = Symbol("objectMode");
        const I = Symbol("destroyed");
        const P = Symbol("error");
        const L = Symbol("emitData");
        const _ = Symbol("emitEnd");
        const D = Symbol("emitEnd2");
        const x = Symbol("async");
        const B = Symbol("abort");
        const j = Symbol("aborted");
        const F = 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[C]();
                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 r.EventEmitter {
            [b]=false;
            [A]=false;
            [S]=[];
            [R]=[];
            [v];
            [g];
            [x];
            [N];
            [u]=false;
            [d]=false;
            [p]=false;
            [f]=false;
            [m]=null;
            [w]=0;
            [I]=false;
            [F];
            [j]=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[v] = true;
                    this[g] = null;
                } else if (z(t)) {
                    this[g] = t.encoding;
                    this[v] = false;
                } else {
                    this[v] = false;
                    this[g] = null;
                }
                this[x] = !!t.async;
                this[N] = this[g] ? new i.StringDecoder(this[g]) : null;
                if (t && t.debugExposeBuffer === true) {
                    Object.defineProperty(this, "buffer", {
                        get: () => this[R]
                    });
                }
                if (t && t.debugExposePipes === true) {
                    Object.defineProperty(this, "pipes", {
                        get: () => this[S]
                    });
                }
                const {signal: n} = t;
                if (n) {
                    this[F] = n;
                    if (n.aborted) {
                        this[B]();
                    } else {
                        n.addEventListener("abort", () => this[B]());
                    }
                }
            }
            get bufferLength() {
                return this[w];
            }
            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[v];
            }
            set objectMode(e) {
                throw new Error("objectMode must be set at instantiation time");
            }
            get ["async"]() {
                return this[x];
            }
            set ["async"](e) {
                this[x] = this[x] || !!e;
            }
            [B]() {
                this[j] = true;
                this.emit("abort", this[F]?.reason);
                this.destroy(this[F]?.reason);
            }
            get aborted() {
                return this[j];
            }
            set aborted(e) {}
            write(e, t, n) {
                if (this[j]) return false;
                if (this[u]) throw new Error("write after end");
                if (this[I]) {
                    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[x] ? V : K;
                if (!this[v] && !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[v]) {
                    if (this[b] && this[w] !== 0) this[E](true);
                    if (this[b]) this.emit("data", e); else this[O](e);
                    if (this[w] !== 0) this.emit("readable");
                    if (n) a(n);
                    return this[b];
                }
                if (!e.length) {
                    if (this[w] !== 0) this.emit("readable");
                    if (n) a(n);
                    return this[b];
                }
                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[b] && this[w] !== 0) this[E](true);
                if (this[b]) this.emit("data", e); else this[O](e);
                if (this[w] !== 0) this.emit("readable");
                if (n) a(n);
                return this[b];
            }
            read(e) {
                if (this[I]) return null;
                this[Q] = false;
                if (this[w] === 0 || e === 0 || e && e > this[w]) {
                    this[h]();
                    return null;
                }
                if (this[v]) e = null;
                if (this[R].length > 1 && !this[v]) {
                    this[R] = [ this[g] ? this[R].join("") : Buffer.concat(this[R], this[w]) ];
                }
                const t = this[y](e || null, this[R][0]);
                this[h]();
                return t;
            }
            [y](e, t) {
                if (this[v]) this[M](); else {
                    const n = t;
                    if (e === n.length || e === null) this[M](); else if (typeof n === "string") {
                        this[R][0] = n.slice(e);
                        t = n.slice(0, e);
                        this[w] -= e;
                    } else {
                        this[R][0] = n.subarray(e);
                        t = n.subarray(0, e);
                        this[w] -= e;
                    }
                }
                this.emit("data", t);
                if (!this[R].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[b] || !this[A]) this[h]();
                return this;
            }
            [C]() {
                if (this[I]) return;
                if (!this[k] && !this[S].length) {
                    this[Q] = true;
                }
                this[A] = false;
                this[b] = true;
                this.emit("resume");
                if (this[R].length) this[E](); else if (this[u]) this[h](); else this.emit("drain");
            }
            resume() {
                return this[C]();
            }
            pause() {
                this[b] = false;
                this[A] = true;
                this[Q] = false;
            }
            get destroyed() {
                return this[I];
            }
            get flowing() {
                return this[b];
            }
            get paused() {
                return this[A];
            }
            [O](e) {
                if (this[v]) this[w] += 1; else this[w] += e.length;
                this[R].push(e);
            }
            [M]() {
                if (this[v]) this[w] -= 1; else this[w] -= this[R][0].length;
                return this[R].shift();
            }
            [E](e = false) {
                do {} while (this[T](this[M]()) && this[R].length);
                if (!e && !this[R].length && !this[u]) this.emit("drain");
            }
            [T](e) {
                this.emit("data", e);
                return this[b];
            }
            pipe(e, t) {
                if (this[I]) return e;
                this[Q] = false;
                const n = this[d];
                t = t || {};
                if (e === a.stdout || e === a.stderr) t.end = false; else t.end = t.end !== false;
                t.proxyErrors = !!t.proxyErrors;
                if (n) {
                    if (t.end) e.end();
                } else {
                    this[S].push(!t.proxyErrors ? new Pipe(this, e, t) : new PipeProxyErrors(this, e, t));
                    if (this[x]) V(() => this[C]()); else this[C]();
                }
                return e;
            }
            unpipe(e) {
                const t = this[S].find(t => t.dest === e);
                if (t) {
                    if (this[S].length === 1) {
                        if (this[b] && this[k] === 0) {
                            this[b] = false;
                        }
                        this[S] = [];
                    } else this[S].splice(this[S].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[S].length && !this[b]) {
                        this[C]();
                    }
                } else if (e === "readable" && this[w] !== 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[x]) 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[S].length) {
                        this[b] = false;
                    }
                }
                return n;
            }
            removeAllListeners(e) {
                const t = super.removeAllListeners(e);
                if (e === "data" || e === undefined) {
                    this[k] = 0;
                    if (!this[Q] && !this[S].length) {
                        this[b] = false;
                    }
                }
                return t;
            }
            get emittedEnd() {
                return this[d];
            }
            [h]() {
                if (!this[p] && !this[d] && !this[I] && this[R].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 !== I && this[I]) {
                    return false;
                } else if (e === "data") {
                    return !this[v] && !n ? false : this[x] ? (V(() => this[L](n)), true) : this[L](n);
                } else if (e === "end") {
                    return this[_]();
                } else if (e === "close") {
                    this[f] = true;
                    if (!this[d] && !this[I]) return false;
                    const e = super.emit("close");
                    this.removeAllListeners("close");
                    return e;
                } else if (e === "error") {
                    this[m] = n;
                    super.emit(P, n);
                    const e = !this[F] || 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;
            }
            [L](e) {
                for (const t of this[S]) {
                    if (t.dest.write(e) === false) this.pause();
                }
                const t = this[Q] ? false : super.emit("data", e);
                this[h]();
                return t;
            }
            [_]() {
                if (this[d]) return false;
                this[d] = true;
                this.readable = false;
                return this[x] ? (V(() => this[D]()), true) : this[D]();
            }
            [D]() {
                if (this[N]) {
                    const e = this[N].end();
                    if (e) {
                        for (const t of this[S]) {
                            t.dest.write(e);
                        }
                        if (!this[Q]) super.emit("data", e);
                    }
                }
                for (const e of this[S]) {
                    e.end();
                }
                const e = super.emit("end");
                this.removeAllListeners("end");
                return e;
            }
            async collect() {
                const e = Object.assign([], {
                    dataLength: 0
                });
                if (!this[v]) e.dataLength = 0;
                const t = this.promise();
                this.on("data", t => {
                    e.push(t);
                    if (!this[v]) e.dataLength += t.length;
                });
                await t;
                return e;
            }
            async concat() {
                if (this[v]) {
                    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(I, () => 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 s = e => {
                        this.off("data", i);
                        this.off("end", o);
                        this.off(I, c);
                        t();
                        r(e);
                    };
                    const i = e => {
                        this.off("error", s);
                        this.off("end", o);
                        this.off(I, c);
                        this.pause();
                        a({
                            value: e,
                            done: !!this[u]
                        });
                    };
                    const o = () => {
                        this.off("error", s);
                        this.off("data", i);
                        this.off(I, c);
                        t();
                        a({
                            done: true,
                            value: undefined
                        });
                    };
                    const c = () => s(new Error("stream destroyed"));
                    return new Promise((e, t) => {
                        r = t;
                        a = e;
                        this.once(I, c);
                        this.once("error", s);
                        this.once("end", o);
                        this.once("data", i);
                    });
                };
                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(P, t);
                    this.off(I, 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(P, t);
                this.once(I, t);
                return {
                    next: n,
                    throw: t,
                    return: t,
                    [Symbol.iterator]() {
                        return this;
                    }
                };
            }
            destroy(e) {
                if (this[I]) {
                    if (e) this.emit("error", e); else this.emit(I);
                    return this;
                }
                this[I] = true;
                this[Q] = true;
                this[R].length = 0;
                this[w] = 0;
                const t = this;
                if (typeof t.close === "function" && !this[f]) t.close();
                if (e) this.emit("error", e); else this.emit(I);
                return this;
            }
            static get isStream() {
                return e.isStream;
            }
        }
        e.Minipass = Minipass;
    })(wC);
    return wC;
}

var vC;

function IC() {
    if (vC) return AC;
    vC = 1;
    var e = n.commonjsGlobal && n.commonjsGlobal.__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 = n.commonjsGlobal && n.commonjsGlobal.__setModuleDefault || (Object.create ? function(e, t) {
        Object.defineProperty(e, "default", {
            enumerable: true,
            value: t
        });
    } : function(e, t) {
        e["default"] = t;
    });
    var a = n.commonjsGlobal && n.commonjsGlobal.__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(AC, "__esModule", {
        value: true
    });
    AC.PathScurry = AC.Path = AC.PathScurryDarwin = AC.PathScurryPosix = AC.PathScurryWin32 = AC.PathScurryBase = AC.PathPosix = AC.PathWin32 = AC.PathBase = AC.ChildrenCache = AC.ResolveCache = void 0;
    const r = SC();
    const s = _.default;
    const i = L.default;
    const o = A.default;
    const c = a(D.default);
    const l = o.realpathSync.native;
    const u = x.default;
    const h = MC();
    const d = {
        lstatSync: o.lstatSync,
        readdir: o.readdir,
        readdirSync: o.readdirSync,
        readlinkSync: o.readlinkSync,
        realpathSync: l,
        promises: {
            lstat: u.lstat,
            readdir: u.readdir,
            readlink: u.readlink,
            realpath: u.realpath
        }
    };
    const p = e => !e || e === d || e === c ? d : {
        ...d,
        ...e,
        promises: {
            ...d.promises,
            ...e.promises || {}
        }
    };
    const m = /^\\\\\?\\([a-z]:)\\?$/i;
    const f = e => e.replace(/\//g, "\\").replace(m, "$1\\");
    const y = /[\\\/]/;
    const E = 0;
    const T = 1;
    const g = 2;
    const N = 4;
    const b = 6;
    const C = 8;
    const R = 10;
    const S = 12;
    const w = 15;
    const O = ~w;
    const M = 16;
    const v = 32;
    const I = 64;
    const P = 128;
    const $ = 256;
    const q = 512;
    const U = I | P | q;
    const B = 1023;
    const j = e => e.isFile() ? C : e.isDirectory() ? N : e.isSymbolicLink() ? R : e.isCharacterDevice() ? g : e.isBlockDevice() ? b : e.isSocket() ? S : e.isFIFO() ? T : E;
    const F = new Map;
    const k = e => {
        const t = F.get(e);
        if (t) return t;
        const n = e.normalize("NFKD");
        F.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 r.LRUCache {
        constructor() {
            super({
                max: 256
            });
        }
    }
    AC.ResolveCache = ResolveCache;
    class ChildrenCache extends r.LRUCache {
        constructor(e = 16 * 1024) {
            super({
                maxSize: e,
                sizeCalculation: e => e.length + 1
            });
        }
    }
    AC.ChildrenCache = ChildrenCache;
    const K = Symbol("PathScurry setAsCwd");
    class PathBase {
        name;
        root;
        roots;
        parent;
        nocase;
        isCWD=false;
        #re;
        #se;
        get dev() {
            return this.#se;
        }
        #ie;
        get mode() {
            return this.#ie;
        }
        #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;
        }
        #A;
        get size() {
            return this.#A;
        }
        #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;
        }
        #be;
        get birthtime() {
            return this.#be;
        }
        #Ae;
        #Ce;
        #Re;
        #Se;
        #we;
        #Oe;
        #Me;
        #ve;
        #Ie;
        #Pe;
        get parentPath() {
            return (this.parent || this).fullpath();
        }
        get path() {
            return this.parentPath;
        }
        constructor(e, t = E, n, a, r, s, i) {
            this.name = e;
            this.#Ae = r ? V(e) : k(e);
            this.#Me = t & B;
            this.nocase = r;
            this.roots = a;
            this.root = n || this;
            this.#ve = s;
            this.#Re = i.fullpath;
            this.#we = i.relative;
            this.#Oe = i.relativePosix;
            this.parent = i.parent;
            if (this.parent) {
                this.#re = this.parent.#re;
            } else {
                this.#re = p(i.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.#Me &= ~M;
            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.#Ae === a) {
                    return e;
                }
            }
            const r = this.parent ? this.sep : "";
            const s = this.#Re ? this.#Re + r + e : undefined;
            const i = this.newChild(e, E, {
                ...t,
                parent: this,
                fullpath: s
            });
            if (!this.canReaddir()) {
                i.#Me |= P;
            }
            n.push(i);
            return i;
        }
        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.#Oe !== undefined) return this.#Oe;
            const e = this.name;
            const t = this.parent;
            if (!t) {
                return this.#Oe = 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.#Me & w) === E;
        }
        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.#Me & w) === C;
        }
        isDirectory() {
            return (this.#Me & w) === N;
        }
        isCharacterDevice() {
            return (this.#Me & w) === g;
        }
        isBlockDevice() {
            return (this.#Me & w) === b;
        }
        isFIFO() {
            return (this.#Me & w) === T;
        }
        isSocket() {
            return (this.#Me & w) === S;
        }
        isSymbolicLink() {
            return (this.#Me & R) === R;
        }
        lstatCached() {
            return this.#Me & v ? 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.#Me & w;
            return !(e !== E && e !== R || this.#Me & $ || this.#Me & P);
        }
        calledReaddir() {
            return !!(this.#Me & M);
        }
        isENOENT() {
            return !!(this.#Me & P);
        }
        isNamed(e) {
            return !this.nocase ? this.#Ae === k(e) : this.#Ae === 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.#_e(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.#_e(e.code);
                return undefined;
            }
        }
        #De(e) {
            this.#Me |= M;
            for (let t = e.provisional; t < e.length; t++) {
                const n = e[t];
                if (n) n.#xe();
            }
        }
        #xe() {
            if (this.#Me & P) return;
            this.#Me = (this.#Me | P) & O;
            this.#$e();
        }
        #$e() {
            const e = this.children();
            e.provisional = 0;
            for (const t of e) {
                t.#xe();
            }
        }
        #qe() {
            this.#Me |= q;
            this.#Ue();
        }
        #Ue() {
            if (this.#Me & I) return;
            let e = this.#Me;
            if ((e & w) === N) e &= O;
            this.#Me = e | I;
            this.#$e();
        }
        #Be(e = "") {
            if (e === "ENOTDIR" || e === "EPERM") {
                this.#Ue();
            } else if (e === "ENOENT") {
                this.#xe();
            } else {
                this.children().provisional = 0;
            }
        }
        #je(e = "") {
            if (e === "ENOTDIR") {
                const e = this.parent;
                e.#Ue();
            } else if (e === "ENOENT") {
                this.#xe();
            }
        }
        #_e(e = "") {
            let t = this.#Me;
            t |= $;
            if (e === "ENOENT") t |= P;
            if (e === "EINVAL" || e === "UNKNOWN") {
                t &= O;
            }
            this.#Me = t;
            if (e === "ENOTDIR" && this.parent) {
                this.parent.#Ue();
            }
        }
        #Fe(e, t) {
            return this.#ke(e, t) || this.#Qe(e, t);
        }
        #Qe(e, t) {
            const n = j(e);
            const a = this.newChild(e.name, n, {
                parent: this
            });
            const r = a.#Me & w;
            if (r !== N && r !== R && r !== E) {
                a.#Me |= I;
            }
            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.#Ae) {
                    continue;
                }
                return this.#Ve(e, a, n, t);
            }
        }
        #Ve(e, t, n, a) {
            const r = t.name;
            t.#Me = t.#Me & O | j(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.#Me & P) === 0) {
                try {
                    this.#Ke(await this.#re.promises.lstat(this.fullpath()));
                    return this;
                } catch (e) {
                    this.#je(e.code);
                }
            }
        }
        lstatSync() {
            if ((this.#Me & P) === 0) {
                try {
                    this.#Ke(this.#re.lstatSync(this.fullpath()));
                    return this;
                } catch (e) {
                    this.#je(e.code);
                }
            }
        }
        #Ke(e) {
            const {atime: t, atimeMs: n, birthtime: a, birthtimeMs: r, blksize: s, blocks: i, ctime: o, ctimeMs: c, dev: l, gid: u, ino: h, mode: d, mtime: p, mtimeMs: m, nlink: f, rdev: y, size: T, uid: g} = e;
            this.#Te = t;
            this.#me = n;
            this.#be = a;
            this.#Ee = r;
            this.#he = s;
            this.#pe = i;
            this.#Ne = o;
            this.#ye = c;
            this.#se = l;
            this.#le = u;
            this.#de = h;
            this.#ie = d;
            this.#ge = p;
            this.#fe = m;
            this.#oe = f;
            this.#ue = y;
            this.#A = T;
            this.#ce = g;
            const b = j(e);
            this.#Me = this.#Me & O | b | v;
            if (b !== E && b !== N && b !== R) {
                this.#Me |= I;
            }
        }
        #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.#Fe(e, n);
                    }
                    this.#De(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.#Fe(n, e);
                    }
                    this.#De(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.#Fe(n, e);
                }
                this.#De(e);
            } catch (t) {
                this.#Be(t.code);
                e.provisional = 0;
            }
            return e.slice(0, e.provisional);
        }
        canReaddir() {
            if (this.#Me & U) return false;
            const e = w & this.#Me;
            if (!(e === E || e === N || e === R)) {
                return false;
            }
            return true;
        }
        shouldWalk(e, t) {
            return (this.#Me & N) === N && !(this.#Me & U) && !e.has(this) && (!t || t(this));
        }
        async realpath() {
            if (this.#Pe) return this.#Pe;
            if ((q | $ | P) & this.#Me) 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 | $ | P) & this.#Me) 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.#Oe = n.join("/");
                a = a.parent;
                n.push("..");
            }
            a = e;
            while (a && a.parent && !t.has(a)) {
                a.#we = undefined;
                a.#Oe = undefined;
                a = a.parent;
            }
        }
    }
    AC.PathBase = PathBase;
    class PathWin32 extends PathBase {
        sep="\\";
        splitSep=y;
        constructor(e, t = E, n, a, r, s, i) {
            super(e, t, n, a, r, s, i);
        }
        newChild(e, t = E, n = {}) {
            return new PathWin32(e, t, this.root, this.roots, this.nocase, this.childrenCache(), n);
        }
        getRootString(e) {
            return s.win32.parse(e).root;
        }
        getRoot(e) {
            e = f(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(m, "$1\\");
            return e === t;
        }
    }
    AC.PathWin32 = PathWin32;
    class PathPosix extends PathBase {
        splitSep="/";
        sep="/";
        constructor(e, t = E, n, a, r, s, i) {
            super(e, t, n, a, r, s, i);
        }
        getRootString(e) {
            return e.startsWith("/") ? "/" : "";
        }
        getRoot(e) {
            return this.root;
        }
        newChild(e, t = E, n = {}) {
            return new PathPosix(e, t, this.root, this.roots, this.nocase, this.childrenCache(), n);
        }
    }
    AC.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: s = d} = {}) {
            this.#re = p(s);
            if (e instanceof URL || e.startsWith("file://")) {
                e = (0, i.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 m = 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: m += (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: s} = t;
            const i = [];
            if (!r || r(e)) {
                i.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)) {
                            i.push(n ? e : e.fullpath());
                        }
                        if (a && e.isSymbolicLink()) {
                            e.realpath().then(e => e?.isUnknown() ? e.lstat() : e).then(e => e?.shouldWalk(o, s) ? c(e, h) : h());
                        } else {
                            if (e.shouldWalk(o, s)) {
                                c(e, h);
                            } else {
                                h();
                            }
                        }
                    }
                }, true);
            };
            const l = e;
            return new Promise((e, t) => {
                c(l, n => {
                    if (n) return t(n);
                    e(i);
                });
            });
        }
        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: s} = t;
            const i = [];
            if (!r || r(e)) {
                i.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)) {
                        i.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, s)) {
                        o.add(t);
                    }
                }
            }
            return i;
        }
        [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: s} = t;
            if (!r || r(e)) {
                yield n ? e : e.fullpath();
            }
            const i = new Set([ e ]);
            for (const e of i) {
                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(i, s)) {
                        i.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: s} = t;
            const i = new h.Minipass({
                objectMode: true
            });
            if (!r || r(e)) {
                i.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) i.end();
                        return;
                    }
                    l++;
                    o.add(t);
                    const h = (t, p, m = false) => {
                        if (t) return i.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 (!i.write(n ? t : t.fullpath())) {
                                    e = true;
                                }
                            }
                        }
                        l--;
                        for (const e of p) {
                            const t = e.realpathCached() || e;
                            if (t.shouldWalk(o, s)) {
                                c.push(t);
                            }
                        }
                        if (e && !i.flowing) {
                            i.once("drain", u);
                        } else if (!d) {
                            u();
                        }
                    };
                    let d = true;
                    t.readdirCB(h, true);
                    d = false;
                }
            };
            u();
            return i;
        }
        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: s} = t;
            const i = new h.Minipass({
                objectMode: true
            });
            const o = new Set;
            if (!r || r(e)) {
                i.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) i.end();
                        return;
                    }
                    l++;
                    o.add(t);
                    const u = t.readdirSync();
                    for (const t of u) {
                        if (!r || r(t)) {
                            if (!i.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, s)) {
                            c.push(t);
                        }
                    }
                }
                if (e && !i.flowing) i.once("drain", u);
            };
            u();
            return i;
        }
        chdir(e = this.cwd) {
            const t = this.cwd;
            this.cwd = typeof e === "string" ? this.cwd.resolve(e) : e;
            this.cwd[K](t);
        }
    }
    AC.PathScurryBase = PathScurryBase;
    class PathScurryWin32 extends PathScurryBase {
        sep="\\";
        constructor(e = process.cwd(), t = {}) {
            const {nocase: n = true} = t;
            super(e, s.win32, "\\", {
                ...t,
                nocase: n
            });
            this.nocase = n;
            for (let e = this.cwd; e; e = e.parent) {
                e.nocase = this.nocase;
            }
        }
        parseRootPath(e) {
            return s.win32.parse(e).root.toUpperCase();
        }
        newRoot(e) {
            return new PathWin32(this.rootPath, N, undefined, this.roots, this.nocase, this.childrenCache(), {
                fs: e
            });
        }
        isAbsolute(e) {
            return e.startsWith("/") || e.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(e);
        }
    }
    AC.PathScurryWin32 = PathScurryWin32;
    class PathScurryPosix extends PathScurryBase {
        sep="/";
        constructor(e = process.cwd(), t = {}) {
            const {nocase: n = false} = t;
            super(e, s.posix, "/", {
                ...t,
                nocase: n
            });
            this.nocase = n;
        }
        parseRootPath(e) {
            return "/";
        }
        newRoot(e) {
            return new PathPosix(this.rootPath, N, undefined, this.roots, this.nocase, this.childrenCache(), {
                fs: e
            });
        }
        isAbsolute(e) {
            return e.startsWith("/");
        }
    }
    AC.PathScurryPosix = PathScurryPosix;
    class PathScurryDarwin extends PathScurryPosix {
        constructor(e = process.cwd(), t = {}) {
            const {nocase: n = true} = t;
            super(e, {
                ...t,
                nocase: n
            });
        }
    }
    AC.PathScurryDarwin = PathScurryDarwin;
    AC.Path = process.platform === "win32" ? PathWin32 : PathPosix;
    AC.PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
    return AC;
}

var PC = {};

var LC;

function _C() {
    if (LC) return PC;
    LC = 1;
    Object.defineProperty(PC, "__esModule", {
        value: true
    });
    PC.Pattern = void 0;
    const e = NC();
    const t = e => e.length >= 1;
    const n = e => e.length >= 1;
    class Pattern {
        #Xe;
        #Ze;
        #et;
        length;
        #tt;
        #nt;
        #at;
        #rt;
        #st;
        #it;
        #ot=true;
        constructor(e, a, r, s) {
            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 = s;
            if (this.#et === 0) {
                if (this.isUNC()) {
                    const [e, t, n, a, ...r] = this.#Xe;
                    const [s, i, o, c, ...l] = this.#Ze;
                    if (r[0] === "") {
                        r.shift();
                        l.shift();
                    }
                    const u = [ e, t, n, a, "" ].join("/");
                    const h = [ s, i, 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 s = n + "/";
                    this.#Xe = [ r, ...t ];
                    this.#Ze = [ s, ...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.#it = this.#it;
            this.#nt.#st = this.#st;
            this.#nt.#rt = this.#rt;
            return this.#nt;
        }
        isUNC() {
            const e = this.#Xe;
            return this.#st !== undefined ? this.#st : this.#st = 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.#it !== undefined ? this.#it : this.#it = 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;
        }
    }
    PC.Pattern = Pattern;
    return PC;
}

var DC = {};

var xC = {};

var $C;

function qC() {
    if ($C) return xC;
    $C = 1;
    Object.defineProperty(xC, "__esModule", {
        value: true
    });
    xC.Ignore = void 0;
    const e = NC();
    const t = _C();
    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: s, platform: i = n}) {
            this.relative = [];
            this.absolute = [];
            this.relativeChildren = [];
            this.absoluteChildren = [];
            this.platform = i;
            this.mmopts = {
                dot: true,
                nobrace: t,
                nocase: a,
                noext: r,
                noglobstar: s,
                optimizationLevel: 2,
                platform: i,
                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 s = a.globParts[n];
                if (!r || !s) {
                    throw new Error("invalid pattern object");
                }
                while (r[0] === "." && s[0] === ".") {
                    r.shift();
                    s.shift();
                }
                const i = new t.Pattern(r, s, 0, this.platform);
                const o = new e.Minimatch(i.globString(), this.mmopts);
                const c = s[s.length - 1] === "**";
                const l = i.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;
        }
    }
    xC.Ignore = Ignore;
    return xC;
}

var UC = {};

var BC;

function jC() {
    if (BC) return UC;
    BC = 1;
    Object.defineProperty(UC, "__esModule", {
        value: true
    });
    UC.Processor = UC.SubWalks = UC.MatchRecord = UC.HasWalkedCache = void 0;
    const e = NC();
    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() ]));
        }
    }
    UC.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) ]);
        }
    }
    UC.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());
        }
    }
    UC.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 s;
                let i;
                let o = false;
                while (typeof (s = n.pattern()) === "string" && (i = n.rest())) {
                    const e = t.resolve(s);
                    t = e;
                    n = i;
                    o = true;
                }
                s = n.pattern();
                i = n.rest();
                if (o) {
                    if (this.hasWalkedCache.hasWalked(t, n)) continue;
                    this.hasWalkedCache.storeWalked(t, n);
                }
                if (typeof s === "string") {
                    const e = s === ".." || s === "" || s === ".";
                    this.matches.add(t.resolve(s), r, e);
                    continue;
                } else if (s === e.GLOBSTAR) {
                    if (!t.isSymbolicLink() || this.follow || n.checkFollowGlobstar()) {
                        this.subwalks.add(t, n);
                    }
                    const e = i?.pattern();
                    const a = i?.rest();
                    if (!i || (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 (s 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 s = n.pattern();
                    const i = n.rest();
                    if (s === e.GLOBSTAR) {
                        r.testGlobstar(t, n, i, a);
                    } else if (s instanceof RegExp) {
                        r.testRegExp(t, s, i, a);
                    } else {
                        r.testString(t, s, i, 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);
            }
        }
    }
    UC.Processor = Processor;
    return UC;
}

var FC;

function kC() {
    if (FC) return DC;
    FC = 1;
    Object.defineProperty(DC, "__esModule", {
        value: true
    });
    DC.GlobStream = DC.GlobWalker = DC.GlobUtil = void 0;
    const e = MC();
    const t = qC();
    const n = jC();
    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 s = () => {
                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(() => s());
            }
            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, s); else {
                    e.readdirCB((t, a) => this.walkCB3(e, a, n, s), true);
                }
            }
            s();
        }
        walkCB3(e, t, n, a) {
            n = n.filterEntries(e, t);
            let r = 1;
            const s = () => {
                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(() => s());
            }
            for (const [e, t] of n.subwalks.entries()) {
                r++;
                this.walkCB2(e, t, n.child(), s);
            }
            s();
        }
        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 s = () => {
                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, s);
            }
            s();
        }
        walkCB3Sync(e, t, n, a) {
            n = n.filterEntries(e, t);
            let r = 1;
            const s = () => {
                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(), s);
            }
            s();
        }
    }
    DC.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;
        }
    }
    DC.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;
        }
    }
    DC.GlobStream = GlobStream;
    return DC;
}

var QC;

function VC() {
    if (QC) return bC;
    QC = 1;
    Object.defineProperty(bC, "__esModule", {
        value: true
    });
    bC.Glob = void 0;
    const e = NC();
    const t = L.default;
    const n = IC();
    const a = _C();
    const r = kC();
    const s = 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, i) {
            if (!i) throw new TypeError("glob options required");
            this.withFileTypes = !!i.withFileTypes;
            this.signal = i.signal;
            this.follow = !!i.follow;
            this.dot = !!i.dot;
            this.dotRelative = !!i.dotRelative;
            this.nodir = !!i.nodir;
            this.mark = !!i.mark;
            if (!i.cwd) {
                this.cwd = "";
            } else if (i.cwd instanceof URL || i.cwd.startsWith("file://")) {
                i.cwd = (0, t.fileURLToPath)(i.cwd);
            }
            this.cwd = i.cwd || "";
            this.root = i.root;
            this.magicalBraces = !!i.magicalBraces;
            this.nobrace = !!i.nobrace;
            this.noext = !!i.noext;
            this.realpath = !!i.realpath;
            this.absolute = i.absolute;
            this.includeChildMatches = i.includeChildMatches !== false;
            this.noglobstar = !!i.noglobstar;
            this.matchBase = !!i.matchBase;
            this.maxDepth = typeof i.maxDepth === "number" ? i.maxDepth : Infinity;
            this.stat = !!i.stat;
            this.ignore = i.ignore;
            if (this.withFileTypes && this.absolute !== undefined) {
                throw new Error("cannot set absolute and withFileTypes:true");
            }
            if (typeof r === "string") {
                r = [ r ];
            }
            this.windowsPathsNoEscape = !!i.windowsPathsNoEscape || i.allowWindowsEscape === false;
            if (this.windowsPathsNoEscape) {
                r = r.map(e => e.replace(/\\/g, "/"));
            }
            if (this.matchBase) {
                if (i.noglobstar) {
                    throw new TypeError("base matching requires globstar");
                }
                r = r.map(e => e.includes("/") ? e : `./**/${e}`);
            }
            this.pattern = r;
            this.platform = i.platform || s;
            this.opts = {
                ...i,
                platform: this.platform
            };
            if (i.scurry) {
                this.scurry = i.scurry;
                if (i.nocase !== undefined && i.nocase !== i.scurry.nocase) {
                    throw new Error("nocase option contradicts provided scurry option");
                }
            } else {
                const e = i.platform === "win32" ? n.PathScurryWin32 : i.platform === "darwin" ? n.PathScurryDarwin : i.platform ? n.PathScurryPosix : n.PathScurry;
                this.scurry = new e(this.cwd, {
                    nocase: i.nocase,
                    fs: i.fs
                });
            }
            this.nocase = this.scurry.nocase;
            const o = this.platform === "darwin" || this.platform === "win32";
            const c = {
                ...i,
                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();
        }
    }
    bC.Glob = Glob;
    return bC;
}

var KC = {};

var WC;

function HC() {
    if (WC) return KC;
    WC = 1;
    Object.defineProperty(KC, "__esModule", {
        value: true
    });
    KC.hasMagic = void 0;
    const e = NC();
    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;
    };
    KC.hasMagic = t;
    return KC;
}

var GC;

function YC() {
    if (GC) return zA;
    GC = 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 = NC();
        const n = VC();
        const a = HC();
        var r = NC();
        Object.defineProperty(e, "escape", {
            enumerable: true,
            get: function() {
                return r.escape;
            }
        });
        Object.defineProperty(e, "unescape", {
            enumerable: true,
            get: function() {
                return r.unescape;
            }
        });
        var s = VC();
        Object.defineProperty(e, "Glob", {
            enumerable: true,
            get: function() {
                return s.Glob;
            }
        });
        var i = HC();
        Object.defineProperty(e, "hasMagic", {
            enumerable: true,
            get: function() {
                return i.hasMagic;
            }
        });
        var o = qC();
        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;
    })(zA);
    return zA;
}

Object.defineProperty(YA, "__esModule", {
    value: true
});

YA.importClassesFromDirectories = nR;

YA.importJsonsFromDirectories = aR;

const zC = e.require$$0;

const JC = zC.__importStar(YC());

const XC = exports.PlatformTools;

const ZC = nd();

const eR = exports.ObjectUtils;

const tR = exports.InstanceChecker;

async function nR(e, t, n = [ ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts" ]) {
    const a = "info";
    const r = "No classes were found using the provided glob pattern: ";
    const s = "All classes found using provided glob pattern";
    function i(e, t) {
        if (typeof e === "function" || tR.InstanceChecker.isEntitySchema(e)) {
            t.push(e);
        } else if (Array.isArray(e)) {
            e.forEach(e => i(e, t));
        } else if (eR.ObjectUtils.isObject(e)) {
            Object.values(e).forEach(e => i(e, t));
        }
        return t;
    }
    const o = t.reduce((e, t) => e.concat(JC.sync(XC.PlatformTools.pathNormalize(t))), []);
    if (t.length > 0 && o.length === 0) {
        e.log(a, `${r} "${t}"`);
    } else if (o.length > 0) {
        e.log(a, `${s} "${t}" : "${o}"`);
    }
    const c = o.filter(e => {
        const t = e.substring(e.length - 5, e.length);
        return n.indexOf(XC.PlatformTools.pathExtname(e)) !== -1 && t !== ".d.ts";
    }).map(async e => {
        const [t] = await (0, ZC.importOrRequireFile)(XC.PlatformTools.pathResolve(e));
        return t;
    });
    const l = await Promise.all(c);
    return i(l, []);
}

function aR(e, t = ".json") {
    const n = e.reduce((e, t) => e.concat(JC.sync(XC.PlatformTools.pathNormalize(t))), []);
    return n.filter(e => XC.PlatformTools.pathExtname(e) === t).map(e => a.commonjsRequire(XC.PlatformTools.pathResolve(e)));
}

var rR = {};

var sR = {};

Object.defineProperty(sR, "__esModule", {
    value: true
});

sR.ColumnMetadata = void 0;

const iR = Dc;

const oR = Bi;

const cR = exports.ObjectUtils;

const lR = exports.InstanceChecker;

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 (cR.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 s = n.shift();
                if (s) {
                    r[s] = {};
                    a(n, r[s]);
                    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 s = e.shift();
                if (s) {
                    const n = r(e, t[s]);
                    if (Object.keys(n).length > 0) {
                        return {
                            [s]: 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 s = r(t, e);
            return Object.keys(s).length > 0 ? s : undefined;
        } else {
            if (this.relationMetadata && !Object.getOwnPropertyDescriptor(e, this.relationMetadata.propertyName)?.get && e[this.relationMetadata.propertyName] && cR.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 iR.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 s = r(t, e);
            if (s) {
                if (this.relationMetadata && this.referencedColumn) {
                    const e = this.relationMetadata.getEntityValue(s);
                    if (e && cR.ObjectUtils.isObject(e) && !lR.InstanceChecker.isFindOperator(e) && !Buffer.isBuffer(e)) {
                        n = this.referencedColumn.getEntityValue(e);
                    } else if (s[this.propertyName] && cR.ObjectUtils.isObject(s[this.propertyName]) && !lR.InstanceChecker.isFindOperator(s[this.propertyName]) && !Buffer.isBuffer(s[this.propertyName]) && !(s[this.propertyName] instanceof Date)) {
                        n = this.referencedColumn.getEntityValue(s[this.propertyName]);
                    } else {
                        n = s[this.propertyName];
                    }
                } else if (this.referencedColumn) {
                    n = this.referencedColumn.getEntityValue(s[this.propertyName]);
                } else if (a && Array.isArray(s)) {
                    n = s.map(e => e[this.propertyName]);
                } else {
                    n = s[this.propertyName];
                }
            }
        } else {
            if (this.relationMetadata && this.referencedColumn) {
                const t = this.relationMetadata.getEntityValue(e);
                if (t && cR.ObjectUtils.isObject(t) && !lR.InstanceChecker.isFindOperator(t) && !(typeof t === "function") && !Buffer.isBuffer(t)) {
                    n = this.referencedColumn.getEntityValue(t);
                } else if (e[this.propertyName] && cR.ObjectUtils.isObject(e[this.propertyName]) && !lR.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 = oR.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);
    }
}

sR.ColumnMetadata = ColumnMetadata;

var uR = {};

Object.defineProperty(uR, "__esModule", {
    value: true
});

uR.IndexMetadata = void 0;

const hR = exports.error;

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 hR.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;
    }
}

uR.IndexMetadata = IndexMetadata;

var dR = {};

Object.defineProperty(dR, "__esModule", {
    value: true
});

dR.RelationMetadata = void 0;

const pR = ep;

const mR = exports.error;

const fR = exports.ObjectUtils;

const yR = exports.InstanceChecker;

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 (yR.InstanceChecker.isEntitySchema(t.type)) {
            this.type = t.type.options.name;
        } else if (fR.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 pR.EntityMetadata.getValueMap(e, n);
    }
    ensureRelationIdMap(e) {
        if (fR.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 mR.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 s = e.shift();
                if (s) {
                    if (!r[s.propertyName]) r[s.propertyName] = s.create();
                    a(e, r[s.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;
    }
}

dR.RelationMetadata = RelationMetadata;

var ER = {};

Object.defineProperty(ER, "__esModule", {
    value: true
});

ER.EmbeddedMetadata = void 0;

const TR = exports.error;

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 TR.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);
    }
}

ER.EmbeddedMetadata = EmbeddedMetadata;

var gR = {};

Object.defineProperty(gR, "__esModule", {
    value: true
});

gR.RelationIdMetadata = void 0;

const NR = exports.error;

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 NR.TypeORMError(`Cannot find relation ${e}. Wrong relation specified for @RelationId decorator.`);
        this.relation = t;
    }
}

gR.RelationIdMetadata = RelationIdMetadata;

var bR = {};

Object.defineProperty(bR, "__esModule", {
    value: true
});

bR.RelationCountMetadata = void 0;

const AR = exports.error;

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 AR.TypeORMError(`Cannot find relation ${e}. Wrong relation specified for @RelationCount decorator.`);
        this.relation = t;
    }
}

bR.RelationCountMetadata = RelationCountMetadata;

exports.EventListenerTypes = {};

Object.defineProperty(exports.EventListenerTypes, "__esModule", {
    value: true
});

exports.EventListenerTypes.EventListenerTypes = void 0;

class EventListenerTypes {}

exports.EventListenerTypes.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 CR = {};

var RR = {};

Object.defineProperty(RR, "__esModule", {
    value: true
});

RR.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);
    }
}

RR.ForeignKeyMetadata = ForeignKeyMetadata;

Object.defineProperty(CR, "__esModule", {
    value: true
});

CR.JunctionEntityMetadataBuilder = void 0;

const SR = sR;

const wR = ep;

const OR = RR;

const MR = uR;

const vR = exports.error;

const IR = zn;

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 s = new wR.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
            }
        });
        s.build();
        const i = 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 SR.ColumnMetadata({
                connection: this.connection,
                entityMetadata: s,
                referencedColumn: n,
                args: {
                    target: "",
                    mode: "virtual",
                    propertyName: r,
                    options: {
                        name: r,
                        length: !n.length && (IR.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 SR.ColumnMetadata({
                connection: this.connection,
                entityMetadata: s,
                referencedColumn: n,
                args: {
                    target: "",
                    mode: "virtual",
                    propertyName: r,
                    options: {
                        length: !n.length && (IR.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(i, o);
        s.ownerColumns = i;
        s.inverseColumns = o;
        s.ownColumns = [ ...i, ...o ];
        s.ownColumns.forEach(t => t.relationMetadata = e);
        s.foreignKeys = e.createForeignKeyConstraints ? [ new OR.ForeignKeyMetadata({
            entityMetadata: s,
            referencedEntityMetadata: e.entityMetadata,
            columns: i,
            referencedColumns: n,
            name: i[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 OR.ForeignKeyMetadata({
            entityMetadata: s,
            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"
        }) ] : [];
        s.ownIndices = [ new MR.IndexMetadata({
            entityMetadata: s,
            columns: i,
            args: {
                target: s.target,
                synchronize: true
            }
        }), new MR.IndexMetadata({
            entityMetadata: s,
            columns: o,
            args: {
                target: s.target,
                synchronize: true
            }
        }) ];
        return s;
    }
    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 vR.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 vR.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;
                }
            });
        });
    }
}

CR.JunctionEntityMetadataBuilder = JunctionEntityMetadataBuilder;

var PR = {};

Object.defineProperty(PR, "__esModule", {
    value: true
});

PR.ClosureJunctionEntityMetadataBuilder = void 0;

const LR = ep;

const _R = sR;

const DR = RR;

const xR = uR;

class ClosureJunctionEntityMetadataBuilder {
    constructor(e) {
        this.connection = e;
    }
    build(e) {
        const t = new LR.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 _R.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 _R.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 xR.IndexMetadata({
            entityMetadata: t,
            columns: [ t.ownColumns[0] ],
            args: {
                target: t.target,
                synchronize: true
            }
        }), new xR.IndexMetadata({
            entityMetadata: t,
            columns: [ t.ownColumns[1] ],
            args: {
                target: t.target,
                synchronize: true
            }
        }) ];
        if (e.treeLevelColumn) {
            t.ownColumns.push(new _R.ColumnMetadata({
                connection: this.connection,
                entityMetadata: t,
                args: {
                    target: "",
                    mode: "virtual",
                    propertyName: "level",
                    options: {
                        type: this.connection.driver.mappedDataTypes.treeLevel
                    }
                }
            }));
        }
        t.foreignKeys = [ new DR.ForeignKeyMetadata({
            entityMetadata: t,
            referencedEntityMetadata: e,
            columns: [ t.ownColumns[0] ],
            referencedColumns: e.primaryColumns,
            onDelete: this.connection.driver.options.type === "mssql" ? "NO ACTION" : "CASCADE"
        }), new DR.ForeignKeyMetadata({
            entityMetadata: t,
            referencedEntityMetadata: e,
            columns: [ t.ownColumns[1] ],
            referencedColumns: e.primaryColumns,
            onDelete: this.connection.driver.options.type === "mssql" ? "NO ACTION" : "CASCADE"
        }) ];
        return t;
    }
}

PR.ClosureJunctionEntityMetadataBuilder = ClosureJunctionEntityMetadataBuilder;

var $R = {};

var qR = {};

Object.defineProperty(qR, "__esModule", {
    value: true
});

qR.UniqueMetadata = void 0;

const UR = exports.error;

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 UR.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;
    }
}

qR.UniqueMetadata = UniqueMetadata;

Object.defineProperty($R, "__esModule", {
    value: true
});

$R.RelationJoinColumnBuilder = void 0;

const BR = sR;

const jR = qR;

const FR = RR;

const kR = exports.error;

const QR = zn;

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 FR.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 s = new jR.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
            }
        });
        s.build(this.connection.namingStrategy);
        return {
            foreignKey: r,
            columns: a,
            uniqueConstraint: s
        };
    }
    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 kR.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 s = t.embeddedMetadata ? t.embeddedMetadata.columns : t.entityMetadata.ownColumns;
            let i = s.find(e => e.databaseNameWithoutPrefixes === r);
            if (!i) {
                i = new BR.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 && (QR.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(i);
            }
            i.referencedColumn = n;
            i.type = n.type;
            i.relationMetadata = t;
            i.build(this.connection);
            return i;
        });
    }
}

$R.RelationJoinColumnBuilder = RelationJoinColumnBuilder;

var VR = {};

Object.defineProperty(VR, "__esModule", {
    value: true
});

VR.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);
        }
    }
}

VR.EntityListenerMetadata = EntityListenerMetadata;

var KR = {};

Object.defineProperty(KR, "__esModule", {
    value: true
});

KR.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;
    }
}

KR.CheckMetadata = CheckMetadata;

var WR = {};

Object.defineProperty(WR, "__esModule", {
    value: true
});

WR.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;
    }
}

WR.ExclusionMetadata = ExclusionMetadata;

Object.defineProperty(rR, "__esModule", {
    value: true
});

rR.EntityMetadataBuilder = void 0;

const HR = ep;

const GR = sR;

const YR = uR;

const zR = dR;

const JR = ER;

const XR = gR;

const ZR = bR;

const eS = exports.EventListenerTypes;

const tS = dh;

const nS = CR;

const aS = PR;

const rS = $R;

const sS = VR;

const iS = qR;

const oS = KR;

const cS = WR;

const lS = exports.error;

const uS = zn;

const hS = RR;

const dS = exports.InstanceChecker;

class EntityMetadataBuilder {
    constructor(e, t) {
        this.connection = e;
        this.metadataArgsStorage = t;
        this.junctionEntityMetadataBuilder = new nS.JunctionEntityMetadataBuilder(e);
        this.closureJunctionEntityMetadataBuilder = new aS.ClosureJunctionEntityMetadataBuilder(e);
        this.relationJoinColumnBuilder = new rS.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" && tS.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: s} = this.relationJoinColumnBuilder.build(n, t);
                if (a) {
                    t.registerForeignKeys(a);
                    e.foreignKeys.push(a);
                }
                if (r) {
                    t.registerJoinColumns(r);
                }
                if (s) {
                    if (uS.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 YR.IndexMetadata({
                            entityMetadata: s.entityMetadata,
                            columns: s.columns,
                            args: {
                                target: s.target,
                                name: s.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(s);
                        } else {
                            t.entityMetadata.ownUniques.push(s);
                        }
                        this.computeEntityMetadataStep2(e);
                    }
                }
                if (a && this.connection.driver.options.type === "cockroachdb") {
                    const n = new YR.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" ? tS.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 HR.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 GR.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 GR.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 GR.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 GR.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 GR.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 zR.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 XR.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 ZR.RelationCountMetadata({
                entityMetadata: t,
                args: e
            });
        });
        t.ownListeners = this.metadataArgsStorage.filterListeners(t.inheritanceTree).map(e => new sS.EntityListenerMetadata({
            entityMetadata: t,
            args: e
        }));
        t.checks = this.metadataArgsStorage.filterChecks(t.inheritanceTree).map(e => new oS.CheckMetadata({
            entityMetadata: t,
            args: e
        }));
        if (this.connection.driver.options.type === "postgres") {
            t.exclusions = this.metadataArgsStorage.filterExclusions(t.inheritanceTree).map(e => new cS.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 YR.IndexMetadata({
                entityMetadata: t,
                args: e
            }));
            const e = this.metadataArgsStorage.filterIndices(t.inheritanceTree).filter(e => e.unique).map(e => new iS.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 YR.IndexMetadata({
                entityMetadata: t,
                args: e
            }));
        }
        if (uS.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 YR.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 iS.UniqueMetadata({
                entityMetadata: t,
                args: e
            }));
            t.ownUniques.push(...e);
        }
    }
    createEmbeddedsRecursively(e, t) {
        return t.map(t => {
            const n = new JR.EmbeddedMetadata({
                entityMetadata: e,
                args: t
            });
            const a = typeof n.type === "function" ? tS.MetadataUtils.getInheritanceTree(n.type) : [ n.type ];
            n.columns = this.metadataArgsStorage.filterColumns(a).map(t => new GR.ColumnMetadata({
                connection: this.connection,
                entityMetadata: e,
                embeddedMetadata: n,
                args: t
            }));
            n.relations = this.metadataArgsStorage.filterRelations(a).map(t => new zR.RelationMetadata({
                entityMetadata: e,
                embeddedMetadata: n,
                args: t
            }));
            n.listeners = this.metadataArgsStorage.filterListeners(a).map(t => new sS.EntityListenerMetadata({
                entityMetadata: e,
                embeddedMetadata: n,
                args: t
            }));
            n.indices = this.metadataArgsStorage.filterIndices(a).map(t => new YR.IndexMetadata({
                entityMetadata: e,
                embeddedMetadata: n,
                args: t
            }));
            n.uniques = this.metadataArgsStorage.filterUniques(a).map(t => new iS.UniqueMetadata({
                entityMetadata: e,
                embeddedMetadata: n,
                args: t
            }));
            n.relationIds = this.metadataArgsStorage.filterRelationIds(a).map(t => new XR.RelationIdMetadata({
                entityMetadata: e,
                args: t
            }));
            n.relationCounts = this.metadataArgsStorage.filterRelationCounts(a).map(t => new ZR.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 === eS.EventListenerTypes.AFTER_LOAD);
        e.afterInsertListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.AFTER_INSERT);
        e.afterUpdateListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.AFTER_UPDATE);
        e.afterRemoveListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.AFTER_REMOVE);
        e.afterSoftRemoveListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.AFTER_SOFT_REMOVE);
        e.afterRecoverListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.AFTER_RECOVER);
        e.beforeInsertListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.BEFORE_INSERT);
        e.beforeUpdateListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.BEFORE_UPDATE);
        e.beforeRemoveListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.BEFORE_REMOVE);
        e.beforeSoftRemoveListeners = e.listeners.filter(e => e.type === eS.EventListenerTypes.BEFORE_SOFT_REMOVE);
        e.beforeRecoverListeners = e.listeners.filter(e => e.type === eS.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 lS.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 YR.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 : dS.InstanceChecker.isEntitySchema(a) ? e.target === a.options.name || e.target === a.options.target : e.target === a);
            if (!r) {
                throw new lS.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 s = n.columnNames ?? [];
            const i = n.referencedColumnNames ?? [];
            const o = [];
            const c = [];
            if (n.propertyName) {
                s.push(n.propertyName);
                if (n.inverseSide) {
                    if (typeof n.inverseSide === "function") {
                        i.push(n.inverseSide(r.propertiesMap));
                    } else {
                        i.push(n.inverseSide);
                    }
                }
            }
            if (!i.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 s = t.targetName;
                throw new lS.TypeORMError(`Foreign key constraint ${r}contains column that is missing in the entity (${s}): ${e}`);
            };
            o.push(...s.map(t => l(t, e)));
            c.push(...i.map(e => l(e, r)));
            e.foreignKeys.push(new hS.ForeignKeyMetadata({
                entityMetadata: e,
                referencedEntityMetadata: r,
                namingStrategy: this.connection.namingStrategy,
                columns: o,
                referencedColumns: c,
                ...n
            }));
        });
    }
}

rR.EntityMetadataBuilder = EntityMetadataBuilder;

var pS = {};

var mS = {};

Object.defineProperty(mS, "__esModule", {
    value: true
});

mS.EntitySchemaEmbeddedError = void 0;

const fS = exports.error;

class EntitySchemaEmbeddedError extends fS.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);
    }
}

mS.EntitySchemaEmbeddedError = EntitySchemaEmbeddedError;

Object.defineProperty(pS, "__esModule", {
    value: true
});

pS.EntitySchemaTransformer = void 0;

const yS = hh;

const ES = mS;

class EntitySchemaTransformer {
    transform(e) {
        const t = new yS.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: s} = n;
            if (s) {
                t.discriminatorValues.push({
                    target: n.target || n.name,
                    value: s
                });
            }
            this.transformColumnsRecursive(n, t);
        });
        return t;
    }
    transformColumnsRecursive(e, t) {
        Object.keys(e.columns).forEach(n => {
            const a = e.columns[n];
            const r = a;
            let s = "regular";
            if (r.createDate) s = "createDate";
            if (r.updateDate) s = "updateDate";
            if (r.deleteDate) s = "deleteDate";
            if (r.version) s = "version";
            if (r.treeChildrenCount) s = "treeChildrenCount";
            if (r.treeLevel) s = "treeLevel";
            if (r.objectId) s = "objectId";
            const i = {
                target: e.target || e.name,
                mode: s,
                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(i);
            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 s = {
                    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(s);
            }
        });
        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 ES.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);
            });
        }
    }
}

pS.EntitySchemaTransformer = EntitySchemaTransformer;

var TS;

function gS() {
    if (TS) return GA;
    TS = 1;
    Object.defineProperty(GA, "__esModule", {
        value: true
    });
    GA.ConnectionMetadataBuilder = void 0;
    const e = YA;
    const t = Dc;
    const n = Nd;
    const a = Od();
    const r = rR;
    const s = pS;
    const i = exports.InstanceChecker;
    let o = class ConnectionMetadataBuilder {
        constructor(e) {
            this.connection = e;
        }
        async buildMigrations(a) {
            const [r, s] = t.OrmUtils.splitClassesAndStrings(a);
            const i = [ ...r, ...await (0, e.importClassesFromDirectories)(this.connection.logger, s) ];
            return i.map(e => (0, n.getFromContainer)(e));
        }
        async buildSubscribers(r) {
            const [s, i] = t.OrmUtils.splitClassesAndStrings(r || []);
            const o = [ ...s, ...await (0, e.importClassesFromDirectories)(this.connection.logger, i) ];
            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 => !i.InstanceChecker.isEntitySchema(e));
            const u = o.filter(e => i.InstanceChecker.isEntitySchema(e));
            const h = [ ...l, ...await (0, e.importClassesFromDirectories)(this.connection.logger, c) ];
            h.forEach(e => {
                if (i.InstanceChecker.isEntitySchema(e)) {
                    u.push(e);
                }
            });
            const d = new r.EntityMetadataBuilder(this.connection, (0, a.getMetadataArgsStorage)()).build(h);
            const p = (new s.EntitySchemaTransformer).transform(u);
            const m = new r.EntityMetadataBuilder(this.connection, p).build();
            return [ ...d, ...m ];
        }
    };
    GA.ConnectionMetadataBuilder = o;
    return GA;
}

var NS = {};

var bS = {};

var AS = {};

Object.defineProperty(AS, "__esModule", {
    value: true
});

exports.AbstractLogger_2 = AS.AbstractLogger = void 0;

const CS = exports.PlatformTools;

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 = CS.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 = CS.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;
        }
    }
}

exports.AbstractLogger_2 = AS.AbstractLogger = AbstractLogger;

Object.defineProperty(bS, "__esModule", {
    value: true
});

exports.SimpleConsoleLogger_2 = bS.SimpleConsoleLogger = void 0;

const RS = AS;

class SimpleConsoleLogger extends RS.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;
            }
        }
    }
}

exports.SimpleConsoleLogger_2 = bS.SimpleConsoleLogger = SimpleConsoleLogger;

var SS = {};

Object.defineProperty(SS, "__esModule", {
    value: true
});

exports.AdvancedConsoleLogger_2 = SS.AdvancedConsoleLogger = void 0;

const wS = exports.PlatformTools;

const OS = AS;

class AdvancedConsoleLogger extends OS.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":
                wS.PlatformTools.log(String(t.message));
                break;

              case "info":
              case "query":
                if (t.prefix) {
                    wS.PlatformTools.logInfo(t.prefix, t.message);
                } else {
                    wS.PlatformTools.log(String(t.message));
                }
                break;

              case "warn":
              case "query-slow":
                if (t.prefix) {
                    wS.PlatformTools.logWarn(t.prefix, t.message);
                } else {
                    console.warn(wS.PlatformTools.warn(String(t.message)));
                }
                break;

              case "error":
              case "query-error":
                if (t.prefix) {
                    wS.PlatformTools.logError(t.prefix, String(t.message));
                } else {
                    console.error(wS.PlatformTools.error(String(t.message)));
                }
                break;
            }
        }
    }
}

exports.AdvancedConsoleLogger_2 = SS.AdvancedConsoleLogger = AdvancedConsoleLogger;

var MS = {};

Object.defineProperty(MS, "__esModule", {
    value: true
});

exports.FileLogger_2 = MS.FileLogger = void 0;

const vS = e.require$$0;

const IS = vS.__importDefault(Zh());

const PS = exports.PlatformTools;

const LS = AS;

class FileLogger extends LS.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 = IS.default.path + "/";
        let n = "ormlogs.log";
        if (this.fileLoggerOptions && this.fileLoggerOptions.logPath) {
            n = PS.PlatformTools.pathNormalize(this.fileLoggerOptions.logPath);
        }
        e = e.map(e => "[" + (new Date).toISOString() + "]" + e);
        PS.PlatformTools.appendFileSync(t + n, e.join("\r\n") + "\r\n");
    }
}

exports.FileLogger_2 = MS.FileLogger = FileLogger;

var _S = {};

Object.defineProperty(_S, "__esModule", {
    value: true
});

_S.DebugLogger = void 0;

const DS = AS;

const xS = t.srcExports;

class DebugLogger extends DS.AbstractLogger {
    constructor() {
        super(...arguments);
        this.logger = {
            log: (0, xS.debug)("typeorm:log"),
            info: (0, xS.debug)("typeorm:info"),
            warn: (0, xS.debug)("typeorm:warn"),
            error: (0, xS.debug)("typeorm:error"),
            query: (0, xS.debug)("typeorm:query:log"),
            "query-error": (0, xS.debug)("typeorm:query:error"),
            "query-slow": (0, xS.debug)("typeorm:query:slow"),
            "schema-build": (0, xS.debug)("typeorm:schema"),
            migration: (0, xS.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);
                }
            }
        }
    }
}

_S.DebugLogger = DebugLogger;

var $S = {};

Object.defineProperty($S, "__esModule", {
    value: true
});

$S.FormattedConsoleLogger = void 0;

const qS = exports.PlatformTools;

const US = AS;

class FormattedConsoleLogger extends US.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":
                qS.PlatformTools.log(String(t.message));
                break;

              case "info":
              case "query":
                if (t.prefix) {
                    qS.PlatformTools.logInfo(t.prefix, t.message);
                } else {
                    qS.PlatformTools.log(String(t.message));
                }
                break;

              case "warn":
              case "query-slow":
                if (t.prefix) {
                    qS.PlatformTools.logWarn(t.prefix, t.message);
                } else {
                    console.warn(qS.PlatformTools.warn(String(t.message)));
                }
                break;

              case "error":
              case "query-error":
                if (t.prefix) {
                    qS.PlatformTools.logError(t.prefix, String(t.message));
                } else {
                    console.error(qS.PlatformTools.error(String(t.message)));
                }
                break;
            }
        }
    }
}

$S.FormattedConsoleLogger = FormattedConsoleLogger;

Object.defineProperty(NS, "__esModule", {
    value: true
});

NS.LoggerFactory = void 0;

const BS = bS;

const jS = SS;

const FS = MS;

const kS = _S;

const QS = exports.ObjectUtils;

const VS = $S;

class LoggerFactory {
    create(e, t) {
        if (QS.ObjectUtils.isObject(e)) return e;
        if (e) {
            switch (e) {
              case "simple-console":
                return new BS.SimpleConsoleLogger(t);

              case "file":
                return new FS.FileLogger(t);

              case "advanced-console":
                return new jS.AdvancedConsoleLogger(t);

              case "formatted-console":
                return new VS.FormattedConsoleLogger(t);

              case "debug":
                return new kS.DebugLogger;
            }
        }
        return new jS.AdvancedConsoleLogger(t);
    }
}

NS.LoggerFactory = LoggerFactory;

var KS = {};

var WS = {};

Object.defineProperty(WS, "__esModule", {
    value: true
});

WS.RedisQueryResultCache = void 0;

const HS = exports.PlatformTools;

const GS = W;

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 GS.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 HS.PlatformTools.load("ioredis");
            } else {
                return HS.PlatformTools.load(this.clientType);
            }
        } catch (e) {
            throw new GS.TypeORMError(`Cannot use cache because ${this.clientType} is not installed. Please run "npm i ${this.clientType} --save".`);
        }
    }
}

WS.RedisQueryResultCache = RedisQueryResultCache;

var YS = {};

Object.defineProperty(YS, "__esModule", {
    value: true
});

YS.DbQueryResultCache = void 0;

const zS = bu;

const JS = su;

const XS = sc;

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 JS.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 zS.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 zS.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 zS.MssqlParameter(e.identifier, "nvarchar"),
                time: new zS.MssqlParameter(e.time, "bigint"),
                duration: new zS.MssqlParameter(e.duration, "int"),
                query: new zS.MssqlParameter(e.query, "nvarchar"),
                result: new zS.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, XS.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();
    }
}

YS.DbQueryResultCache = DbQueryResultCache;

Object.defineProperty(KS, "__esModule", {
    value: true
});

KS.QueryResultCacheFactory = void 0;

const ZS = WS;

const ew = YS;

const tw = W;

class QueryResultCacheFactory {
    constructor(e) {
        this.connection = e;
    }
    create() {
        if (!this.connection.options.cache) throw new tw.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 ZS.RedisQueryResultCache(this.connection, e.type);
        } else {
            return new ew.DbQueryResultCache(this.connection);
        }
    }
}

KS.QueryResultCacheFactory = QueryResultCacheFactory;

var nw = {};

Object.defineProperty(nw, "__esModule", {
    value: true
});

nw.RelationLoader = void 0;

const aw = 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 s = e.entityMetadata.name;
        const i = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
        const o = i.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 ");
        i.innerJoin(e.entityMetadata.target, s, u);
        if (c.length === 1) {
            i.where(`${s}.${c[0].propertyPath} IN (:...${s + "_" + c[0].propertyName})`);
            i.setParameter(s + "_" + c[0].propertyName, r.map(e => c[0].getEntityValue(e, true)));
        } else {
            const e = r.map((e, t) => c.map((n, a) => {
                const r = s + "_entity_" + t + "_" + a;
                i.setParameter(r, n.getEntityValue(e, true));
                return s + "." + n.propertyPath + " = :" + r;
            }).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
            i.where(e);
        }
        aw.FindOptionsUtils.joinEagerRelations(i, i.alias, i.expressionMap.mainAlias.metadata);
        return i.getMany();
    }
    loadOneToManyOrOneToOneNotOwner(e, t, n, a) {
        const r = Array.isArray(t) ? t : [ t ];
        const s = e.inverseRelation.joinColumns;
        const i = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.inverseRelation.entityMetadata.target, e.propertyName);
        const o = i.expressionMap.mainAlias.name;
        if (s.length === 1) {
            i.where(`${o}.${s[0].propertyPath} IN (:...${o + "_" + s[0].propertyName})`);
            i.setParameter(o + "_" + s[0].propertyName, r.map(e => s[0].referencedColumn.getEntityValue(e, true)));
        } else {
            const e = r.map((e, t) => s.map((n, a) => {
                const r = o + "_entity_" + t + "_" + a;
                i.setParameter(r, n.referencedColumn.getEntityValue(e, true));
                return o + "." + n.propertyPath + " = :" + r;
            }).join(" AND ")).map(e => "(" + e + ")").join(" OR ");
            i.where(e);
        }
        aw.FindOptionsUtils.joinEagerRelations(i, i.alias, i.expressionMap.mainAlias.metadata);
        return i.getMany();
    }
    loadManyToManyOwner(e, t, n, a) {
        const r = Array.isArray(t) ? t : [ t ];
        const s = e.joinColumns.reduce((e, t) => {
            e[t.propertyName] = r.map(e => t.referencedColumn.getEntityValue(e, true));
            return e;
        }, {});
        const i = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
        const o = i.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}`);
        i.innerJoin(c, c, [ ...l, ...u ].join(" AND ")).setParameters(s);
        aw.FindOptionsUtils.joinEagerRelations(i, i.alias, i.expressionMap.mainAlias.metadata);
        return i.getMany();
    }
    loadManyToManyNotOwner(e, t, n, a) {
        const r = Array.isArray(t) ? t : [ t ];
        const s = a ? a : this.connection.createQueryBuilder(n).select(e.propertyName).from(e.type, e.propertyName);
        const i = s.expressionMap.mainAlias.name;
        const o = e.junctionEntityMetadata.tableName;
        const c = e.inverseRelation.joinColumns.map(e => `${o}.${e.propertyName} = ${i}.${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;
        }, {});
        s.innerJoin(o, o, [ ...c, ...l ].join(" AND ")).setParameters(u);
        aw.FindOptionsUtils.joinEagerRelations(s, s.alias, s.expressionMap.mainAlias.metadata);
        return s.getMany();
    }
    enableLazyLoad(e, t, n) {
        const a = this;
        const r = "__" + e.propertyName + "__";
        const s = "__promise_" + e.propertyName + "__";
        const i = "__has_" + e.propertyName + "__";
        const o = (e, t) => {
            e[r] = t;
            e[i] = true;
            delete e[s];
            return t;
        };
        const c = (e, t) => {
            delete e[i];
            delete e[r];
            e[s] = t;
            t.then(n => e[s] === t ? o(e, n) : n);
            return t;
        };
        Object.defineProperty(t, e.propertyName, {
            get: function() {
                if (this[i] === true || this[r] !== undefined) return Promise.resolve(this[r]);
                if (this[s]) return this[s];
                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
        });
    }
}

nw.RelationLoader = RelationLoader;

var rw;

function sw() {
    if (rw) return B;
    rw = 1;
    Object.defineProperty(B, "__esModule", {
        value: true
    });
    B.DataSource = void 0;
    const e = j;
    const t = exports.DefaultNamingStrategy;
    const n = exports.error;
    const a = ru;
    const r = Ou;
    const s = sm();
    const i = im;
    const o = gS();
    const c = Lc;
    const l = NS;
    const u = KS;
    const h = nw;
    const d = exports.ObjectUtils;
    const p = Qc;
    const m = zn;
    const f = exports.InstanceChecker;
    const y = Qu;
    (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 i.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 s.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 s = d.ObjectUtils.mixedListToArray(this.options.entities || []);
            const i = await e.buildEntityMetadatas(s);
            d.ObjectUtils.assign(this, {
                entityMetadatas: i,
                entityMetadatasMap: new Map(i.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 i) {
                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";
        }
    };
    B.DataSource = E;
    return B;
}

exports.requireAbstractRepository = vd;

exports.requireDataSource = sw;

exports.requireEntityManager = zp;

exports.requireGlobals = Od;

exports.requireImportUtils = nd;

exports.requireMongoEntityManager = em;