"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ConnectionIsNotSetError_1 = require("../error/ConnectionIsNotSetError");
var DriverPackageNotInstalledError_1 = require("../error/DriverPackageNotInstalledError");
var OracleQueryRunner_1 = require("./OracleQueryRunner");
var DriverOptionNotSetError_1 = require("../error/DriverOptionNotSetError");
var DateUtils_1 = require("../../util/DateUtils");
var PlatformTools_1 = require("../../platform/PlatformTools");
var RdbmsSchemaBuilder_1 = require("../../schema-builder/RdbmsSchemaBuilder");
/**
 * Organizes communication with Oracle RDBMS.
 *
 * todo: this driver is not 100% finished yet, need to fix all issues that are left
 */
var OracleDriver = (function () {
    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------
    function OracleDriver(connection) {
        // -------------------------------------------------------------------------
        // Public Implemented Properties
        // -------------------------------------------------------------------------
        /**
         * Gets list of supported column data types by a driver.
         *
         * @see https://www.techonthenet.com/oracle/datatypes.php
         * @see https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT012
         */
        this.supportedDataTypes = [
            "char",
            "nchar",
            "nvarchar2",
            "varchar2",
            "long",
            "raw",
            "long raw",
            "number",
            "numeric",
            "dec",
            "decimal",
            "integer",
            "int",
            "smallint",
            "real",
            "double precision",
            "date",
            "timestamp",
            "timestamp with time zone",
            "timestamp with local time zone",
            "interval year",
            "interval day",
            "bfile",
            "blob",
            "clob",
            "nclob",
            "rowid",
            "urowid"
        ];
        /**
         * Orm has special columns and we need to know what database column types should be for those types.
         * Column types are driver dependant.
         */
        this.mappedDataTypes = {
            createDate: "datetime",
            createDateDefault: "CURRENT_TIMESTAMP",
            updateDate: "datetime",
            updateDateDefault: "CURRENT_TIMESTAMP",
            version: "number",
            treeLevel: "number",
            migrationName: "varchar",
            migrationTimestamp: "timestamp",
        };
        this.connection = connection;
        // Object.assign(connection.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
        this.options = connection.options;
        // validate options to make sure everything is set
        if (!this.options.host)
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("host");
        if (!this.options.username)
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("username");
        if (!this.options.sid)
            throw new DriverOptionNotSetError_1.DriverOptionNotSetError("sid");
        // load oracle package
        this.loadDependencies();
        // extra oracle setup
        this.oracle.outFormat = this.oracle.OBJECT;
    }
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Performs connection to the database.
     * Based on pooling options, it can either create connection immediately,
     * either create a pool and create connection when needed.
     */
    OracleDriver.prototype.connect = function () {
        var _this = this;
        // build connection options for the driver
        var options = Object.assign({}, {
            user: this.options.username,
            password: this.options.password,
            connectString: this.options.host + ":" + this.options.port + "/" + this.options.sid,
        }, this.options.extra || {});
        // pooling is enabled either when its set explicitly to true,
        // either when its not defined at all (e.g. enabled by default)
        return new Promise(function (ok, fail) {
            _this.oracle.createPool(options, function (err, pool) {
                if (err)
                    return fail(err);
                _this.pool = pool;
                ok();
            });
        });
    };
    /**
     * Closes connection with the database.
     */
    OracleDriver.prototype.disconnect = function () {
        var _this = this;
        if (!this.pool)
            return Promise.reject(new ConnectionIsNotSetError_1.ConnectionIsNotSetError("oracle"));
        return new Promise(function (ok, fail) {
            var handler = function (err) { return err ? fail(err) : ok(); };
            // if pooling is used, then disconnect from it
            _this.pool.close(handler);
            _this.pool = undefined;
        });
    };
    /**
     * Creates a schema builder used to build and sync a schema.
     */
    OracleDriver.prototype.createSchemaBuilder = function () {
        return new RdbmsSchemaBuilder_1.RdbmsSchemaBuilder(this.connection);
    };
    /**
     * Creates a query runner used to execute database queries.
     */
    OracleDriver.prototype.createQueryRunner = function () {
        return new OracleQueryRunner_1.OracleQueryRunner(this);
    };
    /**
     * Replaces parameters in the given sql with special escaping character
     * and an array of parameter names to be passed to a query.
     */
    OracleDriver.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 key;
        }); // todo: make replace only in value statements, otherwise problems
        return [sql, escapedParameters];
    };
    /**
     * Escapes a column name.
     */
    OracleDriver.prototype.escapeColumn = function (columnName) {
        return "\"" + columnName + "\"";
    };
    /**
     * Escapes an alias.
     */
    OracleDriver.prototype.escapeAlias = function (aliasName) {
        return "\"" + aliasName + "\"";
    };
    /**
     * Escapes a table name.
     */
    OracleDriver.prototype.escapeTable = function (tableName) {
        return "\"" + tableName + "\"";
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type and metadata.
     */
    OracleDriver.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 DateUtils_1.DateUtils.mixedDateToDateString(value);
        }
        else if (columnMetadata.type === "time") {
            return DateUtils_1.DateUtils.mixedDateToTimeString(value);
        }
        else if (columnMetadata.type === "datetime") {
            return DateUtils_1.DateUtils.mixedDateToUtcDatetimeString(value);
        }
        else if (columnMetadata.type === "json") {
            return JSON.stringify(value);
        }
        else if (columnMetadata.type === "simple-array") {
            return DateUtils_1.DateUtils.simpleArrayToString(value);
        }
        return value;
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type or metadata.
     */
    OracleDriver.prototype.prepareHydratedValue = function (value, columnMetadata) {
        if (columnMetadata.type === Boolean) {
            return value ? true : false;
        }
        else if (columnMetadata.type === "datetime") {
            return DateUtils_1.DateUtils.normalizeHydratedDate(value);
        }
        else if (columnMetadata.type === "date") {
            return DateUtils_1.DateUtils.mixedDateToDateString(value);
        }
        else if (columnMetadata.type === "time") {
            return DateUtils_1.DateUtils.mixedTimeToString(value);
        }
        else if (columnMetadata.type === "json") {
            return JSON.parse(value);
        }
        else if (columnMetadata.type === "simple-array") {
            return DateUtils_1.DateUtils.stringToSimpleArray(value);
        }
        return value;
    };
    /**
     * Creates a database type from a given column metadata.
     */
    OracleDriver.prototype.normalizeType = function (column) {
        var type = "";
        if (column.type === Number) {
            type += "integer";
        }
        else if (column.type === String) {
            type += "nvarchar2";
        }
        else if (column.type === Date) {
            type += "timestamp(0)";
        }
        else if (column.type === Boolean) {
            type += "number(1)";
        }
        else if (column.type === Object) {
            type += "text";
        }
        else if (column.type === "simple-array") {
            type += "text";
        }
        else {
            type += column.type;
        }
        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 + ")";
        }
        return type;
    };
    /**
     * Normalizes "default" value of the column.
     */
    OracleDriver.prototype.normalizeDefault = function (column) {
        if (typeof column.default === "number") {
            return "" + column.default;
        }
        else if (typeof column.default === "boolean") {
            return column.default === true ? "true" : "false";
        }
        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.
     */
    OracleDriver.prototype.loadDependencies = function () {
        try {
            this.oracle = PlatformTools_1.PlatformTools.load("oracledb");
        }
        catch (e) {
            throw new DriverPackageNotInstalledError_1.DriverPackageNotInstalledError("Oracle", "oracledb");
        }
    };
    return OracleDriver;
}());
exports.OracleDriver = OracleDriver;

//# sourceMappingURL=OracleDriver.js.map
