UNPKG

@microtica/database

Version:

Database tools

75 lines 3.17 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DBSchema = void 0; const _ = require("lodash"); const url = require("url"); /** * * * @export * @class DBSchema */ class DBSchema { constructor(databaseURL) { this.databaseURL = databaseURL; } /** * Gets the name of the database for the current configuration. * @return {String} the name of the database for the current configuration. */ getDatabaseName() { return _.last(this.databaseURL.split("/")); } /** Gets the database dialect. */ extractDialect() { let dialect = url.parse(this.databaseURL).protocol; dialect = dialect.substr(0, dialect.length - 1); if (dialect === "sqlite3") { dialect = "sqlite"; } return dialect; } /** * Checks if a column exists in a table in the current database. * @param tx the transaction to use to make the check query. * @param tableName the name of the table. * @param columnName the name of the column. * @return {Promise<boolean>} resolves to a value indicating whether the specified column exists. */ columnExistsByName(tx, tableName, columnName) { return __awaiter(this, void 0, void 0, function* () { if (this.extractDialect() === "sqlite") { // SQLite const queryResult = yield tx.queryAsync(`PRAGMA table_info(${tableName});`); return _.some(queryResult.rows, row => row.name === columnName); } else { // MySQL const res = yield tx.queryAsync("SELECT * " + "FROM information_schema.COLUMNS " + `WHERE TABLE_SCHEMA = '${this.getDatabaseName()}' AND ` + `TABLE_NAME = '${tableName}' AND ` + `COLUMN_NAME = '${columnName}'`); return res.rowCount > 0; } }); } /** * Checks if a column exists in the current database. * @param tx the transaction to use to make the check query. * @param column the column to check. * @return {Promise<boolean>} resolves to a value indicating whether the specified column exists. */ columnExists(tx, column) { return __awaiter(this, void 0, void 0, function* () { return this.columnExistsByName(tx, column.table._name, column.name); }); } } exports.DBSchema = DBSchema; //# sourceMappingURL=db-schema.js.map