"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var ConnectionIsNotSetError_1 = require("../error/ConnectionIsNotSetError");
var DriverPackageNotInstalledError_1 = require("../error/DriverPackageNotInstalledError");
var DriverUtils_1 = require("../DriverUtils");
var MysqlQueryRunner_1 = require("./MysqlQueryRunner");
var DriverOptionNotSetError_1 = require("../error/DriverOptionNotSetError");
var DataUtils_1 = require("../../util/DataUtils");
var PlatformTools_1 = require("../../platform/PlatformTools");
var RdbmsSchemaBuilder_1 = require("../../schema-builder/RdbmsSchemaBuilder");
/**
 * Organizes communication with MySQL DBMS.
 */
var MysqlDriver = (function () {
    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------
    function MysqlDriver(connection) {
        // -------------------------------------------------------------------------
        // Public Implemented Properties
        // -------------------------------------------------------------------------
        /**
         * Gets list of supported column data types by a driver.
         *
         * @see https://www.tutorialspoint.com/mysql/mysql-data-types.htm
         * @see https://dev.mysql.com/doc/refman/5.7/en/data-types.html
         */
        this.supportedDataTypes = [
            "int",
            "tinyint",
            "smallint",
            "mediumint",
            "bigint",
            "float",
            "double",
            "decimal",
            "date",
            "datetime",
            "timestamp",
            "time",
            "year",
            "char",
            "varchar",
            "blob",
            "text",
            "tinyblob",
            "tinytext",
            "mediumblob",
            "mediumtext",
            "longblob",
            "longtext",
            "enum"
        ];
        /**
         * ORM has special columns and we need to know what database column types should be for those columns.
         * Column types are driver dependant.
         */
        this.mappedDataTypes = {
            createDate: "datetime",
            createDateDefault: "CURRENT_TIMESTAMP",
            updateDate: "datetime",
            updateDateDefault: "CURRENT_TIMESTAMP",
            version: "int",
            treeLevel: "int",
            migrationName: "varchar",
            migrationTimestamp: "timestamp"
        };
        this.connection = connection;
        this.options = connection.options;
        Object.assign(connection.options, DriverUtils_1.DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
        // validate options to make sure everything is set
        if (!(this.options.host || (this.options.extra && this.options.extra.socketPath)))
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("socketPath and host");
        if (!this.options.username)
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("username");
        if (!this.options.database)
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("database");
        // load mysql package
        this.loadDependencies();
    }
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Performs connection to the database.
     */
    MysqlDriver.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var options;
            return __generator(this, function (_a) {
                options = Object.assign({}, {
                    host: this.options.host,
                    user: this.options.username,
                    password: this.options.password,
                    database: this.options.database,
                    port: this.options.port
                }, this.options.extra || {});
                this.pool = this.mysql.createPool(options);
                return [2 /*return*/];
            });
        });
    };
    /**
     * Closes connection with the database.
     */
    MysqlDriver.prototype.disconnect = function () {
        var _this = this;
        if (!this.pool)
            return Promise.reject(new ConnectionIsNotSetError_1.ConnectionIsNotSetError("mysql"));
        return new Promise(function (ok, fail) {
            var handler = function (err) { return err ? fail(err) : ok(); };
            _this.pool.end(handler);
            _this.pool = undefined;
        });
    };
    /**
     * Creates a schema builder used to build and sync a schema.
     */
    MysqlDriver.prototype.createSchemaBuilder = function () {
        return new RdbmsSchemaBuilder_1.RdbmsSchemaBuilder(this.connection);
    };
    /**
     * Creates a query runner used to execute database queries.
     */
    MysqlDriver.prototype.createQueryRunner = function () {
        return new MysqlQueryRunner_1.MysqlQueryRunner(this);
    };
    /**
     * Replaces parameters in the given sql with special escaping character
     * and an array of parameter names to be passed to a query.
     */
    MysqlDriver.prototype.escapeQueryWithParameters = function (sql, parameters) {
        if (!parameters || !Object.keys(parameters).length)
            return [sql, []];
        var escapedParameters = [];
        var keys = Object.keys(parameters).map(function (parameter) { return "(:" + parameter + "\\b)"; }).join("|");
        sql = sql.replace(new RegExp(keys, "g"), function (key) {
            escapedParameters.push(parameters[key.substr(1)]);
            return "?";
        }); // todo: make replace only in value statements, otherwise problems
        return [sql, escapedParameters];
    };
    /**
     * Escapes a column name.
     */
    MysqlDriver.prototype.escapeColumn = function (columnName) {
        return "`" + columnName + "`";
    };
    /**
     * Escapes an alias.
     */
    MysqlDriver.prototype.escapeAlias = function (aliasName) {
        return "`" + aliasName + "`";
    };
    /**
     * Escapes a table name.
     */
    MysqlDriver.prototype.escapeTable = function (tableName) {
        return "`" + tableName + "`";
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type and metadata.
     */
    MysqlDriver.prototype.preparePersistentValue = function (value, columnMetadata) {
        if (value === null || value === undefined)
            return value;
        if (columnMetadata.type === Boolean) {
            return value === true ? 1 : 0;
        }
        else if (columnMetadata.type === "date") {
            return DataUtils_1.DataUtils.mixedDateToDateString(value);
        }
        else if (columnMetadata.type === "time") {
            return DataUtils_1.DataUtils.mixedDateToTimeString(value);
        }
        else if (columnMetadata.type === "datetime") {
            return DataUtils_1.DataUtils.mixedDateToUtcDatetimeString(value);
        }
        else if (columnMetadata.type === "json") {
            return JSON.stringify(value);
        }
        else if (columnMetadata.type === "simple-array") {
            return DataUtils_1.DataUtils.simpleArrayToString(value);
        }
        return value;
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type or metadata.
     */
    MysqlDriver.prototype.prepareHydratedValue = function (value, columnMetadata) {
        if (columnMetadata.type === Boolean) {
            return value ? true : false;
        }
        else if (columnMetadata.type === "datetime") {
            return DataUtils_1.DataUtils.normalizeHydratedDate(value);
        }
        else if (columnMetadata.type === "date") {
            return DataUtils_1.DataUtils.mixedDateToDateString(value);
        }
        else if (columnMetadata.type === "time") {
            return DataUtils_1.DataUtils.mixedTimeToString(value);
        }
        else if (columnMetadata.type === "json") {
            return JSON.parse(value);
        }
        else if (columnMetadata.type === "simple-array") {
            return DataUtils_1.DataUtils.stringToSimpleArray(value);
        }
        return value;
    };
    /**
     * Creates a database type from a given column metadata.
     */
    MysqlDriver.prototype.normalizeType = function (column) {
        var type = "";
        if (column.type === Number) {
            type += "int";
        }
        else if (column.type === String) {
            type += "varchar";
        }
        else if (column.type === Date) {
            type += "datetime";
        }
        else if (column.type === Boolean) {
            type += "tinyint(1)";
        }
        else if (column.type === Object) {
            type += "text";
        }
        else if (column.type === "simple-array") {
            type += "text";
        }
        else {
            type += column.type;
        }
        // normalize shortcuts
        if (type === "integer")
            type = "int";
        if (column.length) {
            type += "(" + column.length + ")";
        }
        else if (column.precision && column.scale) {
            type += "(" + column.precision + "," + column.scale + ")";
        }
        else if (column.precision) {
            type += "(" + column.precision + ")";
        }
        else if (column.scale) {
            type += "(" + column.scale + ")";
        }
        // set default required length if those were not specified
        if (type === "varchar")
            type += "(255)";
        if (type === "int")
            type += "(11)";
        if (type === "tinyint")
            type += "(4)";
        if (type === "smallint")
            type += "(5)";
        if (type === "mediumint")
            type += "(9)";
        if (type === "bigint")
            type += "(20)";
        if (type === "year")
            type += "(4)";
        return type;
    };
    /**
     * Normalizes "default" value of the column.
     */
    MysqlDriver.prototype.normalizeDefault = function (column) {
        if (typeof column.default === "number") {
            return "" + column.default;
        }
        else if (typeof column.default === "boolean") {
            return column.default === true ? "1" : "0";
        }
        else if (typeof column.default === "function") {
            return column.default();
        }
        else if (typeof column.default === "string") {
            return "'" + column.default + "'";
        }
        else {
            return column.default;
        }
    };
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    /**
     * Loads all driver dependencies.
     */
    MysqlDriver.prototype.loadDependencies = function () {
        try {
            this.mysql = PlatformTools_1.PlatformTools.load("mysql"); // try to load first supported package
        }
        catch (e) {
            try {
                this.mysql = PlatformTools_1.PlatformTools.load("mysql2"); // try to load second supported package
            }
            catch (e) {
                throw new DriverPackageNotInstalledError_1.DriverPackageNotInstalledError("Mysql", "mysql");
            }
        }
    };
    return MysqlDriver;
}());
exports.MysqlDriver = MysqlDriver;

//# sourceMappingURL=MysqlDriver.js.map
