sedk-mysql
Version:
Simple SQL builder and validator for MySQL
88 lines • 2.77 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AliasedTable = exports.Table = void 0;
const TableAsterisk_1 = require("../TableAsterisk");
const util_1 = require("../util");
class Table {
constructor(data) {
this.data = data;
this.mColumns = data.columns;
const columnArray = [];
Object.values(data.columns).forEach(it => {
columnArray.push(it);
it.table = this;
});
this.columnArray = columnArray;
}
set schema(schema) {
if (this.mSchema === undefined)
this.mSchema = schema;
else
throw new Error('Schema can only be assigned one time');
}
get schema() {
if (this.mSchema === undefined)
throw new Error('Schema is undefined');
return this.mSchema;
}
get name() {
return this.data.name;
}
get fqName() {
return `${this.schema.fqName}.\`${(0, util_1.escapeBackTick)(this.data.name)}\``;
}
as(alias) {
return new AliasedTable(this, alias);
}
get columns() {
return this.mColumns;
}
/** Alias to get columns() */
get c() {
return this.columns;
}
/**
* Returns array of table's columns, this is different from
* columns() property which returns an object with column name as key
*/
getColumns() {
return this.columnArray;
}
get ASTERISK() {
return new TableAsterisk_1.TableAsterisk(this);
}
isColumnExist(column) {
return this.columnArray.includes(column);
}
getStmt(data, artifacts) {
if (this.mSchema === undefined)
throw new Error('Schema is undefined');
const schemaName = (this.mSchema.name !== 'public'
|| data.option.addPublicSchemaName === 'always'
|| (data.option.addPublicSchemaName === 'when other schema mentioned'
&& Array.from(artifacts.tables).some(it => it.schema.name !== 'public')))
? `${this.mSchema.fqName}.`
: '';
return `${schemaName}\`${(0, util_1.escapeBackTick)(this.data.name)}\``;
}
}
exports.Table = Table;
class AliasedTable {
constructor(table, alias) {
this.table = table;
this.alias = alias;
}
getStmt(data, artifacts) {
const escapedAlias = (0, util_1.escapeBackTick)(this.alias);
const asString = (data.option.addAsBeforeTableAlias === 'always') ? ' AS' : '';
return `${this.table.getStmt(data, artifacts)}${asString} \`${escapedAlias}\``;
}
get name() {
return this.table.name;
}
get fqName() {
return this.table.fqName;
}
}
exports.AliasedTable = AliasedTable;
//# sourceMappingURL=Table.js.map