"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InsertQueryBuilder = void 0;
var tslib_1 = require("tslib");
var CockroachDriver_1 = require("../driver/cockroachdb/CockroachDriver");
var SapDriver_1 = require("../driver/sap/SapDriver");
var QueryBuilder_1 = require("./QueryBuilder");
var SqlServerDriver_1 = require("../driver/sqlserver/SqlServerDriver");
var PostgresDriver_1 = require("../driver/postgres/PostgresDriver");
var MysqlDriver_1 = require("../driver/mysql/MysqlDriver");
var RandomGenerator_1 = require("../util/RandomGenerator");
var InsertResult_1 = require("./result/InsertResult");
var ReturningStatementNotSupportedError_1 = require("../error/ReturningStatementNotSupportedError");
var InsertValuesMissingError_1 = require("../error/InsertValuesMissingError");
var ReturningResultsEntityUpdator_1 = require("./ReturningResultsEntityUpdator");
var AbstractSqliteDriver_1 = require("../driver/sqlite-abstract/AbstractSqliteDriver");
var BroadcasterResult_1 = require("../subscriber/BroadcasterResult");
var EntitySchema_1 = require("../entity-schema/EntitySchema");
var OracleDriver_1 = require("../driver/oracle/OracleDriver");
var AuroraDataApiDriver_1 = require("../driver/aurora-data-api/AuroraDataApiDriver");
/**
 * Allows to build complex sql queries in a fashion way and execute those queries.
 */
var InsertQueryBuilder = /** @class */ (function (_super) {
    (0, tslib_1.__extends)(InsertQueryBuilder, _super);
    function InsertQueryBuilder() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    // -------------------------------------------------------------------------
    // Public Implemented Methods
    // -------------------------------------------------------------------------
    /**
     * Gets generated sql query without parameters being replaced.
     */
    InsertQueryBuilder.prototype.getQuery = function () {
        var sql = this.createComment();
        sql += this.createInsertExpression();
        return sql.trim();
    };
    /**
     * Executes sql generated by query builder and returns raw database results.
     */
    InsertQueryBuilder.prototype.execute = function () {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var valueSets, queryRunner, transactionStartedByUs, broadcastResult_1, declareSql, selectOutputSql, returningResultsEntityUpdator, returningColumns_1, _a, _b, columnPath, _c, insertSql, parameters, statements, sql, queryResult, insertResult, broadcastResult_2, error_1, rollbackError_1;
            var e_1, _d;
            var _this = this;
            return (0, tslib_1.__generator)(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        valueSets = this.getValueSets();
                        // console.timeEnd(".value sets");
                        // If user passed empty array of entities then we don't need to do
                        // anything.
                        //
                        // Fixes GitHub issues #3111 and #5734. If we were to let this through
                        // we would run into problems downstream, like subscribers getting
                        // invoked with the empty array where they expect an entity, and SQL
                        // queries with an empty VALUES clause.
                        if (valueSets.length === 0)
                            return [2 /*return*/, new InsertResult_1.InsertResult()];
                        queryRunner = this.obtainQueryRunner();
                        transactionStartedByUs = false;
                        _e.label = 1;
                    case 1:
                        _e.trys.push([1, 13, 18, 21]);
                        if (!(this.expressionMap.useTransaction === true && queryRunner.isTransactionActive === false)) return [3 /*break*/, 3];
                        return [4 /*yield*/, queryRunner.startTransaction()];
                    case 2:
                        _e.sent();
                        transactionStartedByUs = true;
                        _e.label = 3;
                    case 3:
                        if (!(this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata)) return [3 /*break*/, 5];
                        broadcastResult_1 = new BroadcasterResult_1.BroadcasterResult();
                        valueSets.forEach(function (valueSet) {
                            queryRunner.broadcaster.broadcastBeforeInsertEvent(broadcastResult_1, _this.expressionMap.mainAlias.metadata, valueSet);
                        });
                        return [4 /*yield*/, broadcastResult_1.wait()];
                    case 4:
                        _e.sent();
                        _e.label = 5;
                    case 5:
                        declareSql = null;
                        selectOutputSql = null;
                        returningResultsEntityUpdator = new ReturningResultsEntityUpdator_1.ReturningResultsEntityUpdator(queryRunner, this.expressionMap);
                        returningColumns_1 = [];
                        if (Array.isArray(this.expressionMap.returning) && this.expressionMap.mainAlias.hasMetadata) {
                            try {
                                for (_a = (0, tslib_1.__values)(this.expressionMap.returning), _b = _a.next(); !_b.done; _b = _a.next()) {
                                    columnPath = _b.value;
                                    returningColumns_1.push.apply(returningColumns_1, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(columnPath)), false));
                                }
                            }
                            catch (e_1_1) { e_1 = { error: e_1_1 }; }
                            finally {
                                try {
                                    if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
                                }
                                finally { if (e_1) throw e_1.error; }
                            }
                        }
                        if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata) {
                            if (!(valueSets.length > 1 && this.connection.driver instanceof OracleDriver_1.OracleDriver)) {
                                this.expressionMap.extraReturningColumns = returningResultsEntityUpdator.getInsertionReturningColumns();
                            }
                            returningColumns_1.push.apply(returningColumns_1, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.expressionMap.extraReturningColumns.filter(function (c) { return !returningColumns_1.includes(c); })), false));
                        }
                        if (returningColumns_1.length > 0 && this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver) {
                            declareSql = this.connection.driver.buildTableVariableDeclaration("@OutputTable", returningColumns_1);
                            selectOutputSql = "SELECT * FROM @OutputTable";
                        }
                        _c = (0, tslib_1.__read)(this.getQueryAndParameters(), 2), insertSql = _c[0], parameters = _c[1];
                        statements = [declareSql, insertSql, selectOutputSql];
                        sql = statements.filter(function (s) { return s != null; }).join(";\n\n");
                        return [4 /*yield*/, queryRunner.query(sql, parameters, true)];
                    case 6:
                        queryResult = _e.sent();
                        insertResult = InsertResult_1.InsertResult.from(queryResult);
                        if (!(this.expressionMap.updateEntity === true && this.expressionMap.mainAlias.hasMetadata)) return [3 /*break*/, 8];
                        // console.time(".updating entity");
                        return [4 /*yield*/, returningResultsEntityUpdator.insert(insertResult, valueSets)];
                    case 7:
                        // console.time(".updating entity");
                        _e.sent();
                        _e.label = 8;
                    case 8:
                        if (!(this.expressionMap.callListeners === true && this.expressionMap.mainAlias.hasMetadata)) return [3 /*break*/, 10];
                        broadcastResult_2 = new BroadcasterResult_1.BroadcasterResult();
                        valueSets.forEach(function (valueSet) {
                            queryRunner.broadcaster.broadcastAfterInsertEvent(broadcastResult_2, _this.expressionMap.mainAlias.metadata, valueSet);
                        });
                        return [4 /*yield*/, broadcastResult_2.wait()];
                    case 9:
                        _e.sent();
                        _e.label = 10;
                    case 10:
                        if (!transactionStartedByUs) return [3 /*break*/, 12];
                        return [4 /*yield*/, queryRunner.commitTransaction()];
                    case 11:
                        _e.sent();
                        _e.label = 12;
                    case 12: 
                    // console.timeEnd(".commit");
                    return [2 /*return*/, insertResult];
                    case 13:
                        error_1 = _e.sent();
                        if (!transactionStartedByUs) return [3 /*break*/, 17];
                        _e.label = 14;
                    case 14:
                        _e.trys.push([14, 16, , 17]);
                        return [4 /*yield*/, queryRunner.rollbackTransaction()];
                    case 15:
                        _e.sent();
                        return [3 /*break*/, 17];
                    case 16:
                        rollbackError_1 = _e.sent();
                        return [3 /*break*/, 17];
                    case 17: throw error_1;
                    case 18:
                        if (!(queryRunner !== this.queryRunner)) return [3 /*break*/, 20];
                        return [4 /*yield*/, queryRunner.release()];
                    case 19:
                        _e.sent();
                        _e.label = 20;
                    case 20: return [7 /*endfinally*/];
                    case 21: return [2 /*return*/];
                }
            });
        });
    };
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Specifies INTO which entity's table insertion will be executed.
     */
    InsertQueryBuilder.prototype.into = function (entityTarget, columns) {
        entityTarget = entityTarget instanceof EntitySchema_1.EntitySchema ? entityTarget.options.name : entityTarget;
        var mainAlias = this.createFromAlias(entityTarget);
        this.expressionMap.setMainAlias(mainAlias);
        this.expressionMap.insertColumns = columns || [];
        return this;
    };
    /**
     * Values needs to be inserted into table.
     */
    InsertQueryBuilder.prototype.values = function (values) {
        this.expressionMap.valuesSet = values;
        return this;
    };
    /**
     * Optional returning/output clause.
     */
    InsertQueryBuilder.prototype.output = function (output) {
        return this.returning(output);
    };
    /**
     * Optional returning/output clause.
     */
    InsertQueryBuilder.prototype.returning = function (returning) {
        // not all databases support returning/output cause
        if (!this.connection.driver.isReturningSqlSupported())
            throw new ReturningStatementNotSupportedError_1.ReturningStatementNotSupportedError();
        this.expressionMap.returning = returning;
        return this;
    };
    /**
     * Indicates if entity must be updated after insertion operations.
     * This may produce extra query or use RETURNING / OUTPUT statement (depend on database).
     * Enabled by default.
     */
    InsertQueryBuilder.prototype.updateEntity = function (enabled) {
        this.expressionMap.updateEntity = enabled;
        return this;
    };
    /**
     * Adds additional ON CONFLICT statement supported in postgres and cockroach.
     *
     * @deprecated Use `orIgnore` or `orUpdate`
     */
    InsertQueryBuilder.prototype.onConflict = function (statement) {
        this.expressionMap.onConflict = statement;
        return this;
    };
    /**
     * Adds additional ignore statement supported in databases.
     */
    InsertQueryBuilder.prototype.orIgnore = function (statement) {
        if (statement === void 0) { statement = true; }
        this.expressionMap.onIgnore = !!statement;
        return this;
    };
    /**
     * Adds additional update statement supported in databases.
     */
    InsertQueryBuilder.prototype.orUpdate = function (statementOrOverwrite, conflictTarget) {
        if (!Array.isArray(statementOrOverwrite)) {
            this.expressionMap.onUpdate = {
                conflict: statementOrOverwrite === null || statementOrOverwrite === void 0 ? void 0 : statementOrOverwrite.conflict_target,
                columns: statementOrOverwrite === null || statementOrOverwrite === void 0 ? void 0 : statementOrOverwrite.columns,
                overwrite: statementOrOverwrite === null || statementOrOverwrite === void 0 ? void 0 : statementOrOverwrite.overwrite,
            };
            return this;
        }
        this.expressionMap.onUpdate = {
            overwrite: statementOrOverwrite,
            conflict: conflictTarget,
        };
        return this;
    };
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    /**
     * Creates INSERT express used to perform insert query.
     */
    InsertQueryBuilder.prototype.createInsertExpression = function () {
        var _this = this;
        var tableName = this.getTableName(this.getMainTableName());
        var valuesExpression = this.createValuesExpression(); // its important to get values before returning expression because oracle rely on native parameters and ordering of them is important
        var returningExpression = (this.connection.driver instanceof OracleDriver_1.OracleDriver && this.getValueSets().length > 1) ? null : this.createReturningExpression(); // oracle doesnt support returning with multi-row insert
        var columnsExpression = this.createColumnNamesExpression();
        var query = "INSERT ";
        if (this.connection.driver instanceof MysqlDriver_1.MysqlDriver || this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver) {
            query += "" + (this.expressionMap.onIgnore ? " IGNORE " : "");
        }
        query += "INTO " + tableName;
        // add columns expression
        if (columnsExpression) {
            query += "(" + columnsExpression + ")";
        }
        else {
            if (!valuesExpression && (this.connection.driver instanceof MysqlDriver_1.MysqlDriver || this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver)) // special syntax for mysql DEFAULT VALUES insertion
                query += "()";
        }
        // add OUTPUT expression
        if (returningExpression && this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver) {
            query += " OUTPUT " + returningExpression;
        }
        // add VALUES expression
        if (valuesExpression) {
            if (this.connection.driver instanceof OracleDriver_1.OracleDriver && this.getValueSets().length > 1) {
                query += " " + valuesExpression;
            }
            else {
                query += " VALUES " + valuesExpression;
            }
        }
        else {
            if (this.connection.driver instanceof MysqlDriver_1.MysqlDriver || this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver) { // special syntax for mysql DEFAULT VALUES insertion
                query += " VALUES ()";
            }
            else {
                query += " DEFAULT VALUES";
            }
        }
        if (this.connection.driver instanceof PostgresDriver_1.PostgresDriver || this.connection.driver instanceof AbstractSqliteDriver_1.AbstractSqliteDriver || this.connection.driver instanceof CockroachDriver_1.CockroachDriver) {
            if (this.expressionMap.onIgnore) {
                query += " ON CONFLICT DO NOTHING ";
            }
            else if (this.expressionMap.onConflict) {
                query += " ON CONFLICT " + this.expressionMap.onConflict + " ";
            }
            else if (this.expressionMap.onUpdate) {
                var _a = this.expressionMap.onUpdate, overwrite = _a.overwrite, columns = _a.columns, conflict = _a.conflict;
                var conflictTarget = "ON CONFLICT";
                if (Array.isArray(conflict)) {
                    conflictTarget += " ( " + conflict.map(function (column) { return _this.escape(column); }).join(", ") + " )";
                }
                else if (conflict) {
                    conflictTarget += " ON CONSTRAINT " + this.escape(conflict);
                }
                if (Array.isArray(overwrite)) {
                    query += " " + conflictTarget + " DO UPDATE SET ";
                    query += overwrite === null || overwrite === void 0 ? void 0 : overwrite.map(function (column) { return _this.escape(column) + " = EXCLUDED." + _this.escape(column); }).join(", ");
                    query += " ";
                }
                else if (columns) {
                    query += " " + conflictTarget + " DO UPDATE SET ";
                    query += columns.map(function (column) { return _this.escape(column) + " = :" + column; }).join(", ");
                    query += " ";
                }
            }
        }
        if (this.connection.driver instanceof MysqlDriver_1.MysqlDriver || this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver) {
            if (this.expressionMap.onUpdate) {
                var _b = this.expressionMap.onUpdate, overwrite = _b.overwrite, columns = _b.columns;
                if (Array.isArray(overwrite)) {
                    query += " ON DUPLICATE KEY UPDATE ";
                    query += overwrite.map(function (column) { return _this.escape(column) + " = VALUES(" + _this.escape(column) + ")"; }).join(", ");
                    query += " ";
                }
                else if (Array.isArray(columns)) {
                    query += " ON DUPLICATE KEY UPDATE ";
                    query += columns.map(function (column) { return _this.escape(column) + " = :" + column; }).join(", ");
                    query += " ";
                }
            }
        }
        // add RETURNING expression
        if (returningExpression && (this.connection.driver instanceof PostgresDriver_1.PostgresDriver || this.connection.driver instanceof OracleDriver_1.OracleDriver || this.connection.driver instanceof CockroachDriver_1.CockroachDriver)) {
            query += " RETURNING " + returningExpression;
        }
        // Inserting a specific value for an auto-increment primary key in mssql requires enabling IDENTITY_INSERT
        // IDENTITY_INSERT can only be enabled for tables where there is an IDENTITY column and only if there is a value to be inserted (i.e. supplying DEFAULT is prohibited if IDENTITY_INSERT is enabled)
        if (this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver
            && this.expressionMap.mainAlias.hasMetadata
            && this.expressionMap.mainAlias.metadata.columns
                .filter(function (column) { return _this.expressionMap.insertColumns.length > 0 ? _this.expressionMap.insertColumns.indexOf(column.propertyPath) !== -1 : column.isInsert; })
                .some(function (column) { return _this.isOverridingAutoIncrementBehavior(column); })) {
            query = "SET IDENTITY_INSERT " + tableName + " ON; " + query + "; SET IDENTITY_INSERT " + tableName + " OFF";
        }
        return query;
    };
    /**
     * Gets list of columns where values must be inserted to.
     */
    InsertQueryBuilder.prototype.getInsertedColumns = function () {
        var _this = this;
        if (!this.expressionMap.mainAlias.hasMetadata)
            return [];
        return this.expressionMap.mainAlias.metadata.columns.filter(function (column) {
            // if user specified list of columns he wants to insert to, then we filter only them
            if (_this.expressionMap.insertColumns.length)
                return _this.expressionMap.insertColumns.indexOf(column.propertyPath) !== -1;
            // skip columns the user doesn't want included by default
            if (!column.isInsert) {
                return false;
            }
            // if user did not specified such list then return all columns except auto-increment one
            // for Oracle we return auto-increment column as well because Oracle does not support DEFAULT VALUES expression
            if (column.isGenerated && column.generationStrategy === "increment"
                && !(_this.connection.driver instanceof OracleDriver_1.OracleDriver)
                && !(_this.connection.driver instanceof AbstractSqliteDriver_1.AbstractSqliteDriver)
                && !(_this.connection.driver instanceof MysqlDriver_1.MysqlDriver)
                && !(_this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver)
                && !(_this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver && _this.isOverridingAutoIncrementBehavior(column)))
                return false;
            return true;
        });
    };
    /**
     * Creates a columns string where values must be inserted to for INSERT INTO expression.
     */
    InsertQueryBuilder.prototype.createColumnNamesExpression = function () {
        var _this = this;
        var columns = this.getInsertedColumns();
        if (columns.length > 0)
            return columns.map(function (column) { return _this.escape(column.databaseName); }).join(", ");
        // in the case if there are no insert columns specified and table without metadata used
        // we get columns from the inserted value map, in the case if only one inserted map is specified
        if (!this.expressionMap.mainAlias.hasMetadata && !this.expressionMap.insertColumns.length) {
            var valueSets = this.getValueSets();
            if (valueSets.length === 1)
                return Object.keys(valueSets[0]).map(function (columnName) { return _this.escape(columnName); }).join(", ");
        }
        // get a table name and all column database names
        return this.expressionMap.insertColumns.map(function (columnName) { return _this.escape(columnName); }).join(", ");
    };
    /**
     * Creates list of values needs to be inserted in the VALUES expression.
     */
    InsertQueryBuilder.prototype.createValuesExpression = function () {
        var _this = this;
        var valueSets = this.getValueSets();
        var columns = this.getInsertedColumns();
        // if column metadatas are given then apply all necessary operations with values
        if (columns.length > 0) {
            var expression_1 = "";
            valueSets.forEach(function (valueSet, valueSetIndex) {
                columns.forEach(function (column, columnIndex) {
                    if (columnIndex === 0) {
                        if (_this.connection.driver instanceof OracleDriver_1.OracleDriver && valueSets.length > 1) {
                            expression_1 += " SELECT ";
                        }
                        else {
                            expression_1 += "(";
                        }
                    }
                    // extract real value from the entity
                    var value = column.getEntityValue(valueSet);
                    // if column is relational and value is an object then get real referenced column value from this object
                    // for example column value is { question: { id: 1 } }, value will be equal to { id: 1 }
                    // and we extract "1" from this object
                    /*if (column.referencedColumn && value instanceof Object && !(value instanceof Function)) { // todo: check if we still need it since getEntityValue already has similar code
                        value = column.referencedColumn.getEntityValue(value);
                    }*/
                    if (!(value instanceof Function)) {
                        // make sure our value is normalized by a driver
                        value = _this.connection.driver.preparePersistentValue(value, column);
                    }
                    // newly inserted entities always have a version equal to 1 (first version)
                    // also, user-specified version must be empty
                    if (column.isVersion && value === undefined) {
                        expression_1 += "1";
                        // } else if (column.isNestedSetLeft) {
                        //     const tableName = this.connection.driver.escape(column.entityMetadata.tablePath);
                        //     const rightColumnName = this.connection.driver.escape(column.entityMetadata.nestedSetRightColumn!.databaseName);
                        //     const subQuery = `(SELECT c.max + 1 FROM (SELECT MAX(${rightColumnName}) as max from ${tableName}) c)`;
                        //     expression += subQuery;
                        //
                        // } else if (column.isNestedSetRight) {
                        //     const tableName = this.connection.driver.escape(column.entityMetadata.tablePath);
                        //     const rightColumnName = this.connection.driver.escape(column.entityMetadata.nestedSetRightColumn!.databaseName);
                        //     const subQuery = `(SELECT c.max + 2 FROM (SELECT MAX(${rightColumnName}) as max from ${tableName}) c)`;
                        //     expression += subQuery;
                    }
                    else if (column.isDiscriminator) {
                        expression_1 += _this.createParameter(_this.expressionMap.mainAlias.metadata.discriminatorValue);
                        // return "1";
                        // for create and update dates we insert current date
                        // no, we don't do it because this constant is already in "default" value of the column
                        // with extended timestamp functionality, like CURRENT_TIMESTAMP(6) for example
                        // } else if (column.isCreateDate || column.isUpdateDate) {
                        //     return "CURRENT_TIMESTAMP";
                        // if column is generated uuid and database does not support its generation and custom generated value was not provided by a user - we generate a new uuid value for insertion
                    }
                    else if (column.isGenerated && column.generationStrategy === "uuid" && !_this.connection.driver.isUUIDGenerationSupported() && value === undefined) {
                        value = RandomGenerator_1.RandomGenerator.uuid4();
                        expression_1 += _this.createParameter(value);
                        if (!(valueSetIndex in _this.expressionMap.locallyGenerated)) {
                            _this.expressionMap.locallyGenerated[valueSetIndex] = {};
                        }
                        column.setEntityValue(_this.expressionMap.locallyGenerated[valueSetIndex], value);
                        // if value for this column was not provided then insert default value
                    }
                    else if (value === undefined) {
                        if ((_this.connection.driver instanceof OracleDriver_1.OracleDriver && valueSets.length > 1) || _this.connection.driver instanceof AbstractSqliteDriver_1.AbstractSqliteDriver || _this.connection.driver instanceof SapDriver_1.SapDriver) { // unfortunately sqlite does not support DEFAULT expression in INSERT queries
                            if (column.default !== undefined && column.default !== null) { // try to use default defined in the column
                                expression_1 += _this.connection.driver.normalizeDefault(column);
                            }
                            else {
                                expression_1 += "NULL"; // otherwise simply use NULL and pray if column is nullable
                            }
                        }
                        else {
                            expression_1 += "DEFAULT";
                        }
                        // support for SQL expressions in queries
                    }
                    else if (value instanceof Function) {
                        expression_1 += value();
                        // just any other regular value
                    }
                    else {
                        if (_this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver)
                            value = _this.connection.driver.parametrizeValue(column, value);
                        // we need to store array values in a special class to make sure parameter replacement will work correctly
                        // if (value instanceof Array)
                        //     value = new ArrayParameter(value);
                        var paramName = _this.createParameter(value);
                        if ((_this.connection.driver instanceof MysqlDriver_1.MysqlDriver || _this.connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver) && _this.connection.driver.spatialTypes.indexOf(column.type) !== -1) {
                            var useLegacy = _this.connection.driver.options.legacySpatialSupport;
                            var geomFromText = useLegacy ? "GeomFromText" : "ST_GeomFromText";
                            if (column.srid != null) {
                                expression_1 += geomFromText + "(" + paramName + ", " + column.srid + ")";
                            }
                            else {
                                expression_1 += geomFromText + "(" + paramName + ")";
                            }
                        }
                        else if (_this.connection.driver instanceof PostgresDriver_1.PostgresDriver && _this.connection.driver.spatialTypes.indexOf(column.type) !== -1) {
                            if (column.srid != null) {
                                expression_1 += "ST_SetSRID(ST_GeomFromGeoJSON(" + paramName + "), " + column.srid + ")::" + column.type;
                            }
                            else {
                                expression_1 += "ST_GeomFromGeoJSON(" + paramName + ")::" + column.type;
                            }
                        }
                        else if (_this.connection.driver instanceof SqlServerDriver_1.SqlServerDriver && _this.connection.driver.spatialTypes.indexOf(column.type) !== -1) {
                            expression_1 += column.type + "::STGeomFromText(" + paramName + ", " + (column.srid || "0") + ")";
                        }
                        else {
                            expression_1 += paramName;
                        }
                    }
                    if (columnIndex === columns.length - 1) {
                        if (valueSetIndex === valueSets.length - 1) {
                            if (_this.connection.driver instanceof OracleDriver_1.OracleDriver && valueSets.length > 1) {
                                expression_1 += " FROM DUAL ";
                            }
                            else {
                                expression_1 += ")";
                            }
                        }
                        else {
                            if (_this.connection.driver instanceof OracleDriver_1.OracleDriver && valueSets.length > 1) {
                                expression_1 += " FROM DUAL UNION ALL ";
                            }
                            else {
                                expression_1 += "), ";
                            }
                        }
                    }
                    else {
                        expression_1 += ", ";
                    }
                });
            });
            if (expression_1 === "()")
                return "";
            return expression_1;
        }
        else { // for tables without metadata
            // get values needs to be inserted
            var expression_2 = "";
            valueSets.forEach(function (valueSet, insertionIndex) {
                var columns = Object.keys(valueSet);
                columns.forEach(function (columnName, columnIndex) {
                    if (columnIndex === 0) {
                        expression_2 += "(";
                    }
                    var value = valueSet[columnName];
                    // support for SQL expressions in queries
                    if (value instanceof Function) {
                        expression_2 += value();
                        // if value for this column was not provided then insert default value
                    }
                    else if (value === undefined) {
                        if (_this.connection.driver instanceof AbstractSqliteDriver_1.AbstractSqliteDriver || _this.connection.driver instanceof SapDriver_1.SapDriver) {
                            expression_2 += "NULL";
                        }
                        else {
                            expression_2 += "DEFAULT";
                        }
                        // just any other regular value
                    }
                    else {
                        expression_2 += _this.createParameter(value);
                    }
                    if (columnIndex === Object.keys(valueSet).length - 1) {
                        if (insertionIndex === valueSets.length - 1) {
                            expression_2 += ")";
                        }
                        else {
                            expression_2 += "), ";
                        }
                    }
                    else {
                        expression_2 += ", ";
                    }
                });
            });
            if (expression_2 === "()")
                return "";
            return expression_2;
        }
    };
    /**
     * Gets array of values need to be inserted into the target table.
     */
    InsertQueryBuilder.prototype.getValueSets = function () {
        if (Array.isArray(this.expressionMap.valuesSet))
            return this.expressionMap.valuesSet;
        if (this.expressionMap.valuesSet instanceof Object)
            return [this.expressionMap.valuesSet];
        throw new InsertValuesMissingError_1.InsertValuesMissingError();
    };
    /**
     * Checks if column is an auto-generated primary key, but the current insertion specifies a value for it.
     *
     * @param column
     */
    InsertQueryBuilder.prototype.isOverridingAutoIncrementBehavior = function (column) {
        return column.isPrimary
            && column.isGenerated
            && column.generationStrategy === "increment"
            && this.getValueSets().some(function (valueSet) {
                return column.getEntityValue(valueSet) !== undefined
                    && column.getEntityValue(valueSet) !== null;
            });
    };
    return InsertQueryBuilder;
}(QueryBuilder_1.QueryBuilder));
exports.InsertQueryBuilder = InsertQueryBuilder;

//# sourceMappingURL=InsertQueryBuilder.js.map
