all files / preprocesors/ MysqlSchemaPreprocessor.js

100% Statements 99/99
88.89% Branches 48/54
100% Functions 26/26
100% Lines 95/95
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289                            21×                           21×                                   13×   13×                                                                     13× 11×                                                                         13× 11×                                                               13×               83×               72×                   14× 54× 40×   14× 14×                     19× 75× 56×   60× 19×                 13× 44× 44×   13×        
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var typeUtil_1 = require("../commons/utils/typeUtil");
var utils_1 = require("../commons/utils/utils");
var schemaUtil_1 = require("../commons/utils/schemaUtil");
var logger_1 = require("../commons/logger");
var config_1 = require("../configs/config");
var CROSS_REFERENCE_COL_LENGTH = 2;
var FIRST_INDEX = 0;
var SECOND_INDEX = 1;
/**
 * MySql schema pre processor.
 *
 * @export
 * @class MysqlSchemaPreprocessor
 */
var MysqlSchemaPreprocessor = (function () {
    function MysqlSchemaPreprocessor() {
    }
    /**
     * Normalize the table schema.
     *
     * @param {*} columnSchema column schema to be normalized
     * @returns {{}} normalized column schema
     */
    MysqlSchemaPreprocessor.prototype.convertToStandardSchema = function (columnSchema) {
        var column = {
            name: columnSchema.COLUMN_NAME ? columnSchema.COLUMN_NAME : '',
            primary: Boolean(columnSchema.COLUMN_KEY && columnSchema.COLUMN_KEY === 'PRI'),
            unique: Boolean(columnSchema.COLUMN_KEY && (columnSchema.COLUMN_KEY === 'PRI' || columnSchema.COLUMN_KEY === 'UNI')),
            foreignKey: Boolean(columnSchema.COLUMN_KEY && columnSchema.COLUMN_KEY === 'MUL'),
            allowNull: Boolean(columnSchema.IS_NULLABLE && columnSchema.IS_NULLABLE === 'YES'),
            dataType: {
                type: typeUtil_1.default.convertSqlType(columnSchema.DATA_TYPE),
                size: columnSchema.CHARACTER_MAXIMUM_LENGTH ?
                    parseInt(columnSchema.CHARACTER_MAXIMUM_LENGTH, config_1.default.NUMERIC_BASE) :
                    undefined,
                rawValues: columnSchema.COLUMN_TYPE,
            },
        };
        return schemaUtil_1.default.convertValues(column);
    };
    /**
     * Normalizes all foreign key relations, by creating the respective columns in the target tables.
     *
     * @param {*} schema db schema
     * @returns {*} normalized db schema
     */
    MysqlSchemaPreprocessor.prototype.normalizeSchemaRelations = function (schema) {
        var normalizedSchema = schema;
        normalizedSchema = this.normalizeOneToOneRelations(normalizedSchema);
        normalizedSchema = this.normalizeOneToManyRelations(normalizedSchema);
        normalizedSchema = this.normalizeManyToManyRelations(normalizedSchema);
        normalizedSchema = this.cleanupUnusedPropertiesFromColumns(normalizedSchema);
        normalizedSchema = this.stripEmptyTables(normalizedSchema);
        logger_1.default.info(JSON.stringify(normalizedSchema));
        return normalizedSchema;
    };
    /**
     * Normalizes one to one relations.
     * Parses the table list and checks for tables
     * which have unique foreign keys, are not CrossReferenceTables(many to many)
     * and adds the foreign column on both sides of the relation.
     *
     * @param {*} schema db schema
     * @returns {*} normalized db schema
     */
    MysqlSchemaPreprocessor.prototype.normalizeOneToOneRelations = function (schema) {
        var _this = this;
        var updatedSchema = schema;
        schema.forEach(function (table) {
            if (!_this.tableHasForeignKeys(table) || _this.tableIsCrossReferenceTable(table)) {
                return table;
            }
            table.columns.forEach(function (column) {
                if (column.foreignKey && column.unique && column.dataType.references) {
                    var targetColumn = {
                        name: schemaUtil_1.default.relationIsAlias(column) ? utils_1.default.toColumnName(column.dataType.references.name) : column.name,
                        primary: column.primary,
                        unique: true,
                        allowNull: false,
                        dataType: {
                            type: column.dataType.type,
                            isArray: false,
                            relationType: '1-1',
                        },
                    };
                    var sourceColumn = {
                        name: utils_1.default.singular(table.name).toLowerCase(),
                        primary: column.primary,
                        unique: true,
                        allowNull: true,
                        dataType: {
                            type: utils_1.default.toTitleCase(table.name),
                            isArray: false,
                            relationType: '1-1',
                            isRelationHolder: true,
                        },
                    };
                    updatedSchema = _this.addColumnToTable(updatedSchema, column.dataType.references.table, sourceColumn);
                    updatedSchema = _this.addColumnToTable(updatedSchema, table.name, targetColumn);
                }
            });
            return table;
        });
        return updatedSchema;
    };
    /**
     * Normalizes one to many relations.
     * Parses the table list and checks for tables
     * which have foreign keys, are not CrossReferenceTables(many to many)
     * and adds the foreign column on the holder.
     *
     * @param {Schema} schema db schema
     * @returns {Schema} normalized db schema
     */
    MysqlSchemaPreprocessor.prototype.normalizeOneToManyRelations = function (schema) {
        var _this = this;
        var updatedSchema = schema;
        schema.forEach(function (table) {
            if (!_this.tableHasForeignKeys(table) || _this.tableIsCrossReferenceTable(table)) {
                return table;
            }
            table.columns.forEach(function (column) {
                if (column.foreignKey && column.dataType.references) {
                    var sourceColumn = {
                        name: schemaUtil_1.default.relationIsAlias(column) ? utils_1.default.toColumnName(column.dataType.references.name) : column.name,
                        primary: column.primary,
                        unique: false,
                        allowNull: false,
                        dataType: {
                            type: utils_1.default.toTitleCase(column.name),
                            isArray: false,
                            relationType: '1-n',
                        },
                    };
                    var targetColumn = {
                        name: schemaUtil_1.default.relationIsAlias(column) ? table.name + "_" + utils_1.default.toColumnName(column.dataType.references.name) : table.name,
                        primary: column.primary,
                        unique: false,
                        allowNull: true,
                        dataType: {
                            type: utils_1.default.toTitleCase(table.name),
                            isArray: true,
                            relationType: '1-n',
                            isRelationHolder: true,
                        },
                    };
                    updatedSchema = _this.addColumnToTable(updatedSchema, column.dataType.references.table, targetColumn);
                    updatedSchema = _this.addColumnToTable(updatedSchema, table.name, sourceColumn);
                    if (schemaUtil_1.default.relationIsAlias(column)) {
                        updatedSchema = _this.removeColumnFromTable(updatedSchema, table.name, column.name);
                    }
                }
            });
            return table;
        });
        return updatedSchema;
    };
    /**
     * Normalizes many to many relations.
     * Parses the table list and checks for tables
     * which are CrossReferenceTables(many to many)
     * and adds the foreign columns to the source and target tables.
     *
     * @param {*} schema db schema
     * @returns {*} normalized db schema
     */
    MysqlSchemaPreprocessor.prototype.normalizeManyToManyRelations = function (schema) {
        var _this = this;
        var updatedSchema = schema;
        schema.forEach(function (table) {
            if (!_this.tableIsCrossReferenceTable(table) || table.columns.length !== CROSS_REFERENCE_COL_LENGTH) {
                return table;
            }
            var source = table.columns[FIRST_INDEX];
            var target = table.columns[SECOND_INDEX];
            var sourceColumn = {
                name: source.dataType.references ? source.dataType.references.table : '',
                primary: source.primary,
                unique: false,
                allowNull: true,
                dataType: {
                    type: utils_1.default.toTitleCase(source.dataType.type),
                    isArray: true,
                    relationType: 'n-n',
                    isRelationHolder: true,
                },
            };
            var targetColumn = {
                name: target.dataType.references ? target.dataType.references.table : '',
                primary: target.primary,
                unique: false,
                allowNull: true,
                dataType: {
                    type: utils_1.default.toTitleCase(target.dataType.type),
                    isArray: true,
                    relationType: 'n-n',
                    isRelationHolder: true,
                },
            };
            updatedSchema = _this.addColumnToTable(updatedSchema, source.dataType.references ? source.dataType.references.table : '', targetColumn);
            updatedSchema = _this.addColumnToTable(updatedSchema, target.dataType.references ? target.dataType.references.table : '', sourceColumn);
            updatedSchema = _this.removeColumnFromTable(updatedSchema, table.name, source.name);
            updatedSchema = _this.removeColumnFromTable(updatedSchema, table.name, target.name);
            return table;
        });
        return updatedSchema;
    };
    /**
     * Strips tables with no columns from schema.
     *
     * @param {*} schema db schema
     * @returns {Array<*>} cleaned up schema
     */
    MysqlSchemaPreprocessor.prototype.stripEmptyTables = function (schema) {
        return schema.filter(function (table) { return Boolean(Object.keys(table.columns).length); });
    };
    /**
     * Checks if the table has any foreign key columns.
     *
     * @param {*} table db table
     * @returns {boolean} checked if it contains foreign keys.
     */
    MysqlSchemaPreprocessor.prototype.tableHasForeignKeys = function (table) {
        return Boolean(table.columns.filter(function (column) { return column.foreignKey; }).length);
    };
    /**
     * Checks if the table is a cross reference map(association table for many to many relations).
     *
     * @param {*} table table schema
     * @returns {boolean} checked if cross reference table.
     */
    MysqlSchemaPreprocessor.prototype.tableIsCrossReferenceTable = function (table) {
        return table.columns.filter(function (column) { return column.foreignKey; }).length === table.columns.length;
    };
    /**
     * Adds a column to a table in the schema.
     *
     * @param {*} schema db schema
     * @param {string} tableName table in which to add column
     * @param {*} column column to be added
     * @returns {Array|*} updated schema
     */
    MysqlSchemaPreprocessor.prototype.addColumnToTable = function (schema, tableName, column) {
        return this.removeColumnFromTable(schema, tableName, column.name).map(function (table) {
            if (table.name !== tableName) {
                return table;
            }
            table.columns.push(column);
            return table;
        });
    };
    /**
     * Removes a column from a table in the schema.
     *
     * @param {*} schema db schema
     * @param {string} tableName table from which we need to remove
     * @param {string} columnName column to be removed
     * @returns {Array|*} schema with removed column
     */
    MysqlSchemaPreprocessor.prototype.removeColumnFromTable = function (schema, tableName, columnName) {
        return schema.map(function (table) {
            if (table.name !== tableName) {
                return table;
            }
            table.columns = table.columns.filter(function (column) { return column.name !== columnName; });
            return table;
        });
    };
    /**
     * Remove unused properties from schema.
     *
     * @param {*} schema db schema
     * @returns {Array|*} cleaned up db schema
     */
    MysqlSchemaPreprocessor.prototype.cleanupUnusedPropertiesFromColumns = function (schema) {
        return schema.map(function (table) {
            table.columns.map(function (column) {
                delete column.foreignKey;
                return column;
            });
            return table;
        });
    };
    return MysqlSchemaPreprocessor;
}());
exports.default = MysqlSchemaPreprocessor;