adba
Version:
Any DataBase to API
224 lines (223 loc) • 10.7 kB
JavaScript
;
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.generateMSSQLModels = generateMSSQLModels;
exports.mapMssqlTypeToJsonType = mapMssqlTypeToJsonType;
exports.mapMssqlTypeToJsonFormat = mapMssqlTypeToJsonFormat;
const objection_1 = require("objection");
const dbl_utils_1 = require("dbl-utils");
const model_utilities_1 = require("./model-utilities");
/**
* Generates MSSQL models dynamically based on database structures.
* @param knexInstance - The Knex instance connected to the database.
* @param opts - Options including parse and format functions.
* @returns A promise that resolves to an object containing all generated models.
*/
function generateMSSQLModels(knexInstance_1) {
return __awaiter(this, arguments, void 0, function* (knexInstance, opts = {}) {
const models = {};
const { relationsFunc, squemaFixings, columnsFunc, parseFunc, formatFunc } = opts;
try {
// Query table and view structures from the database
const structures = yield knexInstance.raw(`
SELECT TABLE_NAME as name, TABLE_TYPE as type
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE IN ('BASE TABLE', 'VIEW')
`).then(res => res.recordset);
for (const { name: structureName, type } of structures) {
const columns = yield knexInstance.raw(`
SELECT
c.COLUMN_NAME as column_name,
c.DATA_TYPE as data_type,
c.IS_NULLABLE as is_nullable,
c.COLUMN_DEFAULT as column_default,
COLUMNPROPERTY(object_id(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity') AS is_identity
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = ?
`, [structureName]).then(res => res.recordset);
const foreignKeys = yield knexInstance.raw(`
SELECT
fk.name AS fk_name,
tp.name AS table,
rcp.name AS to,
cp.name AS from
FROM sys.foreign_keys AS fk
INNER JOIN sys.foreign_key_columns AS fkc ON fk.object_id = fkc.constraint_object_id
INNER JOIN sys.tables AS tp ON fkc.parent_object_id = tp.object_id
INNER JOIN sys.columns AS cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
INNER JOIN sys.tables AS tr ON fkc.referenced_object_id = tr.object_id
INNER JOIN sys.columns AS rcp ON fkc.referenced_object_id = rcp.object_id AND fkc.referenced_column_id = rcp.column_id
WHERE tp.name = ?
`, [structureName]).then(res => res.recordset);
// Define a dynamic model class
const DynamicModel = class extends objection_1.Model {
/**
* Returns the table name for the model.
*/
static get tableName() {
return structureName;
}
/**
* Constructs the JSON schema based on the table structure.
* @returns The JSON schema object for the table.
*/
static get jsonSchema() {
const requiredFields = [];
const schemaProperties = {};
for (const column of columns) {
const format = mapMssqlTypeToJsonFormat(column.data_type, column.column_name);
const type = mapMssqlTypeToJsonType(column.data_type);
const property = {
type: type !== 'buffer' ? type : undefined
};
const isNotNullable = column.is_nullable === 'NO';
const isIdentity = column.is_identity === 1;
const hasDefault = column.column_default != null;
if (isNotNullable && !isIdentity && !hasDefault) {
requiredFields.push(column.column_name);
}
property.$comment = [type, format].filter(Boolean).join('.');
const prefix = type === 'buffer' ? 'x-' : '';
schemaProperties[prefix + column.column_name] = property;
}
if (typeof squemaFixings === 'function') {
const r = squemaFixings(structureName, schemaProperties);
if (r)
(0, dbl_utils_1.deepMerge)(schemaProperties, r);
}
return {
type: 'object',
properties: schemaProperties,
required: requiredFields.length ? requiredFields : undefined,
};
}
/**
* Constructs relation mappings for the model.
* @returns An object containing relation mappings.
*/
static get relationMappings() {
const relations = {};
for (const fk of foreignKeys) {
const relatedModel = Object.values(models).find((Model) => Model.tableName === fk.table);
if (!relatedModel) {
throw new Error(`${structureName}: Model for table ${fk.table} not found`);
}
relations[`${fk.table}`] = {
relation: objection_1.Model.BelongsToOneRelation,
modelClass: relatedModel,
join: {
from: `${structureName}.${fk.from}`,
to: `${fk.table}.${fk.to}`,
},
};
}
if (typeof relationsFunc === 'function') {
const r = relationsFunc(structureName, relations);
if (r)
Object.assign(relations, r);
}
return relations;
}
/**
* Columns information derived from the JSON schema.
*/
static get columns() {
const { properties = {}, required = [] } = this.jsonSchema;
const cols = (0, model_utilities_1.jsonSchemaToColumns)(properties, required);
if (typeof columnsFunc === 'function') {
const r = columnsFunc(structureName, cols);
if (r)
(0, dbl_utils_1.deepMerge)(cols, r);
}
return cols;
}
/**
* Parses the database JSON.
* @param json The JSON object from the database.
* @returns The parsed JSON object.
*/
$parseDatabaseJson(json) {
json = super.$parseDatabaseJson(json);
return typeof parseFunc === 'function' ? parseFunc(structureName, json) : json;
}
/**
* Formats the JSON object for the database.
* @param json The JSON object to be formatted.
* @returns The formatted JSON object.
*/
$formatDatabaseJson(json) {
json = super.$formatDatabaseJson(json);
return typeof formatFunc === 'function' ? formatFunc(structureName, json) : json;
}
};
const pascalCaseName = (0, model_utilities_1.className)(structureName);
const suffix = type === 'BASE TABLE' ? 'Table' : 'View';
const modelName = `${pascalCaseName}${suffix}Model`;
Object.defineProperty(DynamicModel, 'name', { value: modelName });
DynamicModel.knex(knexInstance);
models[modelName] = DynamicModel;
}
}
catch (err) {
console.error('Error generating models:', err);
}
return models;
});
}
/**
* Maps MSSQL data types to corresponding JSON Schema types.
* @param mssqlType - The MSSQL data type.
* @returns The JSON Schema type.
*/
function mapMssqlTypeToJsonType(mssqlType) {
const baseType = mssqlType.toUpperCase();
const typeMap = {
BIT: 'boolean',
VARBINARY: 'buffer',
BINARY: 'buffer',
BIGINT: 'integer',
INT: 'integer',
SMALLINT: 'integer',
TINYINT: 'integer',
DECIMAL: 'number',
FLOAT: 'number',
NUMERIC: 'number',
REAL: 'number',
CHAR: 'string',
VARCHAR: 'string',
NVARCHAR: 'string',
TEXT: 'string',
NTEXT: 'string',
DATE: 'string',
DATETIME: 'string',
DATETIME2: 'string',
SMALLDATETIME: 'string',
TIME: 'string',
};
return typeMap[baseType] || 'string';
}
/**
* Maps MSSQL data types to corresponding JSON Schema formats.
* @param mssqlType - The MSSQL data type.
* @param colName - The column name for potential additional format inference.
* @returns The JSON Schema format if applicable.
*/
function mapMssqlTypeToJsonFormat(mssqlType, colName) {
const baseType = mssqlType.toUpperCase();
const typeMap = {
DATE: 'date',
DATETIME: 'datetime',
DATETIME2: 'datetime',
SMALLDATETIME: 'datetime',
TIME: 'time',
};
return typeMap[baseType] || undefined;
}