61 lines
2.8 KiB
JavaScript
61 lines
2.8 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var example_def_1 = __importDefault(require("./example-def"));
|
|
function createDatabase(storageDef) {
|
|
var tableCreationQueries = [];
|
|
for (var i in storageDef.tables) {
|
|
tableCreationQueries.push(getTableCreationString(storageDef.tables[i]));
|
|
}
|
|
for (var i in storageDef.relations) {
|
|
tableCreationQueries.push(getTableRelationsCreationString(storageDef.relations[i]));
|
|
}
|
|
tableCreationQueries.map(function (query) {
|
|
console.log(query);
|
|
});
|
|
}
|
|
function getTableCreationString(tableDef) {
|
|
var primaryKeyString = tableDef.name + "_id VARCHAR(36) PRIMARY KEY";
|
|
var columnString = "" + primaryKeyString;
|
|
var defaultColumns = "created DATETIME NOT NULL DEFAULT NOW(), modified DATETIME NOT NULL DEFAULT NOW()";
|
|
var indexString = "";
|
|
// columns
|
|
for (var i in tableDef.columns) {
|
|
var column = tableDef.columns[i];
|
|
columnString = columnString + ", " + createColumnString(column);
|
|
}
|
|
// relations
|
|
for (var i in tableDef.relations) {
|
|
var relation = tableDef.relations[i];
|
|
columnString = columnString + ", " + relation.table + "_id VARCHAR(36)";
|
|
}
|
|
// default created & modified
|
|
columnString = columnString + ", " + defaultColumns;
|
|
return "CREATE TABLE IF NOT EXISTS " + tableDef.name + " (" + columnString + (indexString !== '' ? ', ' + indexString : '') + ");";
|
|
}
|
|
function createColumnString(column) {
|
|
var typeMap = {
|
|
"blob": "BLOB",
|
|
"boolean": "BOOLEAN",
|
|
"date": "DATE",
|
|
"dateTIME": "DATETIME",
|
|
"number": "INT",
|
|
"string": "VARCHAR(255)",
|
|
};
|
|
return column.name + " " + typeMap[column.type] + (column.nullable ? '' : ' NOT NULL') + (column.default ? ' DEFAULT ' + column.default : '') + (column.autoIncrement ? ' AUTO_INCREMENT' : '') + (column.unique ? ' UNIQUE' : '');
|
|
}
|
|
function getTableRelationsCreationString(relationsDef) {
|
|
var columnString = relationsDef.left + "_id VARCHAR(36) NOT NULL, " + relationsDef.right + "_id VARCHAR(36) NOT NULL";
|
|
var indexString = "INDEX " + relationsDef.left + "_id_index (" + relationsDef.left + "_id), INDEX " + relationsDef.right + "_id_index (" + relationsDef.right + "_id)";
|
|
if (relationsDef.columns && relationsDef.columns.length) {
|
|
for (var i in relationsDef.columns) {
|
|
var column = relationsDef.columns[i];
|
|
columnString = columnString + ", " + createColumnString(column);
|
|
}
|
|
}
|
|
return "CREATE TABLE IF NOT EXISTS " + relationsDef.left + "_" + relationsDef.right + " (" + columnString + (indexString !== '' ? ', ' + indexString : '') + ");";
|
|
}
|
|
createDatabase(example_def_1.default.storage);
|