ts-sql-codegen
Version:
Generates ts-sql-query table mappings from tbls schema output
702 lines • 33.3 kB
JavaScript
"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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Generator = void 0;
const promises_1 = __importDefault(require("fs/promises"));
const handlebars_1 = __importDefault(require("handlebars"));
const hbs_dedent_helper_1 = require("hbs-dedent-helper");
const js_yaml_1 = __importDefault(require("js-yaml"));
const lodash_1 = require("lodash");
const posix_1 = __importDefault(require("path/posix"));
const ts_pattern_1 = require("ts-pattern");
const field_mappings_1 = require("./field-mappings");
const file_remover_1 = require("./file-remover");
const generator_options_1 = require("./generator-options");
const matcher_1 = require("./matcher");
const tbls_types_1 = require("./tbls-types");
(0, hbs_dedent_helper_1.register)();
/**
* Generator class for programmatic codegen.
*
* Most common usage involves creating an instance and calling generate function:
*
* ```ts
* const options = {
* schemaPath: './schema.yaml',
* connectionSourcePath: './connection-source.ts'
* }
* const generator = new Generator(options);
* await generator.generate();
* ```
*
* See [GeneratorOpts](../interfaces/GeneratorOpts.md) for configuration options.
*
* For advanced use-cases, you can extend this class.
* This enables you to use custom templates, pre/post processing of generated code
* and custom logic for table/column/field mapping.
*/
class Generator {
constructor(opts) {
this.writtenFiles = new Set();
this.logger = console;
this.getFieldMappings = (0, lodash_1.memoize)(() => {
var _a;
return ((_a = this.opts.fieldMappings) !== null && _a !== void 0 ? _a : []).concat(field_mappings_1.fieldMappings);
});
this.getTemplatePath = (0, lodash_1.memoize)(() => {
return posix_1.default.join(__dirname, "template.ts.hbs");
});
this.getCompiledTemplate = (0, lodash_1.memoize)(() => __awaiter(this, void 0, void 0, function* () {
const rawTemplate = yield promises_1.default.readFile(this.getTemplatePath(), "utf8");
return handlebars_1.default.compile(rawTemplate, {
noEscape: true
});
}));
this.opts = generator_options_1.GeneratorOptsSchema.parse(opts);
this.naming = generator_options_1.NamingOptionsSchema.parse(this.opts.naming || {});
}
resolvePath(relPath) {
if (this.opts.moduleRoot) {
return posix_1.default.resolve(this.opts.moduleRoot, relPath);
}
return posix_1.default.resolve(relPath);
}
generate() {
return __awaiter(this, void 0, void 0, function* () {
const rawSchema = yield promises_1.default.readFile(this.resolvePath(this.opts.schemaPath), "utf8");
const schema = tbls_types_1.TblsSchema.parse(js_yaml_1.default.load(rawSchema));
yield Promise.all(schema.tables.map((table) => __awaiter(this, void 0, void 0, function* () {
if (this.shouldProcess(table)) {
yield this.generateTableMapper(table);
}
})));
yield new file_remover_1.FileRemover(this.opts, this.writtenFiles, this.logger).removeExtraneousFiles();
});
}
shouldProcess(table) {
const filter = this.opts.tables;
if ((filter === null || filter === void 0 ? void 0 : filter.include) &&
filter.include.findIndex((it) => (0, matcher_1.doesMatchNameOrPatternNamespaced)(it, table.name)) < 0) {
return false;
}
if ((filter === null || filter === void 0 ? void 0 : filter.exclude) &&
filter.exclude.findIndex((it) => (0, matcher_1.doesMatchNameOrPatternNamespaced)(it, table.name)) >= 0) {
return false;
}
return true;
}
getTableKind(table) {
return (0, ts_pattern_1.match)(table.type.toLowerCase())
.with("base table", () => "Table")
.with("table", () => "Table")
.with("view", () => "View")
.with("materialized view", () => "View")
.otherwise(() => null);
}
getTableTemplateInput(table, tableKind, filePath) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
// Qualified table name with schema prefix
const tableName = this.extractTableName(table.name);
const pkCol = this.findPrimaryKey(table);
const fields = this.getFieldsInput(table, pkCol);
const dbConnectionSource = this.getConnectionSourceImportPath(filePath);
const exportTableClass = (_b = (_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.tableClasses) !== null && _b !== void 0 ? _b : true;
const wrapperTypeImports = [];
const className = this.getTableMapperClassName(table.name, tableKind);
const rowTypes = this.getRowTypeInputs(tableName, tableKind, className, wrapperTypeImports);
const valuesTypes = this.getValuesTypeInputs(tableName, tableKind, className, wrapperTypeImports);
const pkField = fields.find(it => it.isPK);
const repo = this.getRepoInput(tableName, tableKind, pkField);
const colMapping = this.getColMappingInput(tableName, !!repo);
const colSetName = this.getColSetName(tableName, tableKind);
const instName = this.getTableMapperInstName(tableName, tableKind);
const idPrefix = this.getIdPrefix(table);
const rowTypePrefix = this.getRowTypePrefix(tableName);
const adapterImports = this.getAdapterImports(filePath, fields);
const typeImports = this.getTypeImports(filePath, fields, !!repo);
const utilImports = this.getUtilImports(colSetName, !!repo);
return this.preProcessTemplateInput({
table: {
name: ((_c = this.opts.tableMapping) === null || _c === void 0 ? void 0 : _c.useQualifiedTableName)
? table.name
: tableName,
kind: tableKind,
comment: this.formatComment([table.comment]),
idPrefix,
},
output: this.opts.output,
imports: [
...utilImports,
...adapterImports,
...typeImports,
...wrapperTypeImports,
],
dbConnectionSource,
className,
instName,
fields,
adapterImports,
exportTableClass,
rowTypes,
valuesTypes,
importExtraTypes: rowTypes || valuesTypes,
rowTypePrefix,
colSetName,
colMapping,
pkField,
repo
});
});
}
getFieldsInput(table, pkCol) {
return table.columns
.filter((col) => {
return !this.isColumnOmitted(table.name, col);
})
.map((col) => this.getFieldInput(col, table, pkCol));
}
getFieldInput(col, table, pkCol) {
var _a, _b, _c, _d;
const isOptional = this.isColumnOptional(table.name, col);
const hasDefault = this.doesColumnHaveDefault(table.name, col);
const isComputed = this.isColumnComputed(table.name, col);
const comment = this.getColComment(table.name, col);
let isPK = false;
let columnMethod;
if (col === pkCol) {
const isAutoGenerated = (_d = (_a = col.default) !== null && _a !== void 0 ? _a : (_c = (_b = this.opts.common) === null || _b === void 0 ? void 0 : _b.primaryKey) === null || _c === void 0 ? void 0 : _c.isAutoGenerated) !== null && _d !== void 0 ? _d : false;
columnMethod = isAutoGenerated
? "autogeneratedPrimaryKey"
: "primaryKey";
isPK = true;
}
else if (isComputed) {
if (isOptional) {
columnMethod = "optionalComputedColumn";
}
else {
columnMethod = "computedColumn";
}
}
else if (!isOptional && !hasDefault) {
columnMethod = "column";
}
else if (isOptional && !hasDefault) {
columnMethod = "optionalColumn";
}
else if (isOptional && hasDefault) {
columnMethod = "optionalColumnWithDefaultValue";
}
else if (!isOptional && hasDefault) {
columnMethod = "columnWithDefaultValue";
}
return {
name: this.getFieldNameForColumn(table.name, col),
columnName: col.name,
comment: this.formatComment([col.comment, comment]),
isOptional,
hasDefault,
columnMethod,
fieldType: this.getFieldType(table.name, col),
includeDBTypeWhenIsOptional: this.opts.includeDBTypeWhenIsOptional || false,
isPK,
};
}
getRepoInput(tableName, tableKind, pkField) {
var _a;
if (!pkField)
return null;
if (!((_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.crudRepository))
return null;
const pkFSuffix = (0, lodash_1.upperFirst)(pkField.name);
const methods = {};
methods.select = `select`;
methods.selectWhere = `selectWhere`;
methods.findAll = `findAll`;
methods.findOne = `findOneBy${pkFSuffix}`;
methods.findMany = `findManyBy${pkFSuffix}`;
if (tableKind === 'Table') {
methods.insert = `select`;
methods.insertOne = `insertOne`;
methods.insertMany = `insertMany`;
methods.update = `update`;
methods.updateOne = `updateOneBy${pkFSuffix}`;
methods.updateMany = `updateManyBy${pkFSuffix}`;
methods.delete = 'delete';
methods.deleteOne = `deleteOneBy${pkFSuffix}`;
methods.deleteMany = `deleteManyBy${pkFSuffix}`;
}
return {
className: this.getCrudRepoName(tableName),
methods,
};
}
generateTableMapper(table) {
return __awaiter(this, void 0, void 0, function* () {
const tableKind = this.getTableKind(table);
if (!tableKind) {
this.logger.warn(`Unknown table type ${table.type} for table ${table.name}: SKIPPING`);
return;
}
const filePath = this.getOutputFilePath(table, tableKind);
const templateInput = yield this.getTableTemplateInput(table, tableKind, filePath);
const template = yield this.getCompiledTemplate();
const output = yield this.postProcessOutput(template(templateInput), table);
yield promises_1.default.mkdir(posix_1.default.dirname(filePath), {
recursive: true
});
if (this.opts.dryRun) {
this.logger.info(`Will populate ${filePath} with:`);
this.logger.info(output);
this.logger.info("---");
}
else {
this.logger.info(`Writing ${filePath}`);
this.writtenFiles.add(posix_1.default.relative(this.opts.outputDirPath, filePath));
yield promises_1.default.writeFile(filePath, output);
}
});
}
getIdPrefix(table) {
var _a, _b;
let idPrefix = (_a = this.opts.tableMapping) === null || _a === void 0 ? void 0 : _a.idPrefix;
if (!idPrefix && ((_b = this.opts.tableMapping) === null || _b === void 0 ? void 0 : _b.useQualifiedTableName)) {
idPrefix = table.name
.split(".")
.slice(0, -1)
.map((it) => (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(it)))
.join("");
}
return idPrefix;
}
formatComment(comments) {
const neComments = comments.filter(Boolean);
if ((0, lodash_1.isEmpty)(neComments))
return null;
const commentLines = neComments
.flatMap(c => c.split("\n"))
.map(c => ` * ${c}`);
commentLines.unshift('/**');
commentLines.push(' */');
return commentLines;
}
getConnectionSourceImportPath(outputFilePath) {
var _a, _b, _c;
const csPath = (_b = (_a = this.opts.connectionSource) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : this.opts.connectionSourcePath;
if (((_c = this.opts.connectionSource) === null || _c === void 0 ? void 0 : _c.resolveRelative) === false) {
return csPath;
}
const relPath = posix_1.default.relative(posix_1.default.dirname(outputFilePath), this.resolvePath(csPath));
return posix_1.default.join(posix_1.default.dirname(relPath), posix_1.default.basename(relPath));
}
getAdapterImports(outputFilePath, fields) {
var _a, _b;
const imports = new Map();
const defaultImports = new Map();
for (const field of fields) {
const adapter = (_a = field.fieldType) === null || _a === void 0 ? void 0 : _a.adapter;
if (!adapter)
continue;
const importPath = this.getAdapterImportPath(adapter, outputFilePath);
let adapterImports;
const map = adapter.isDefault ? defaultImports : imports;
adapterImports = (_b = map.get(importPath)) !== null && _b !== void 0 ? _b : new Set();
map.set(importPath, adapterImports);
adapterImports.add(adapter.name);
}
return this.accumulateImports(imports, defaultImports);
}
accumulateImports(imports, defaultImports) {
const inputs = [];
for (const [entries, isDefault] of [
[imports.entries(), false],
[defaultImports.entries(), true],
]) {
for (const [importPath, importedSet] of entries) {
inputs.push({
importPath,
imported: [...importedSet],
isDefault,
});
}
}
return inputs;
}
getTypeImports(outputFilePath, fields, generateRepo) {
var _a;
const imports = new Map();
const defaultImports = new Map();
for (const field of fields) {
const tsType = field.fieldType.tsType;
if (!tsType)
continue;
const importPath = tsType.importPath;
const name = tsType.name;
if (!importPath || !name) {
continue;
}
const nImportPath = this.getImportPathForOutputPath(outputFilePath, importPath, tsType);
const map = tsType.isDefault ? defaultImports : imports;
const typeImports = (_a = map.get(nImportPath)) !== null && _a !== void 0 ? _a : new Set();
map.set(nImportPath, typeImports);
typeImports.add(name);
}
const importList = this.accumulateImports(imports, defaultImports);
if (generateRepo) {
importList.push({
importPath: "ts-sql-query/expressions/dynamicConditionUsingFilters",
imported: ["DynamicCondition"],
isDefault: false,
});
}
return importList;
}
getUtilImports(colSetName, generateRepo) {
const imports = [];
if (colSetName || generateRepo) {
imports.push({
importPath: "ts-sql-query/extras/utils",
imported: ["extractColumnsFrom"],
isDefault: false
});
}
return imports;
}
getImportPathForOutputPath(filePath, importPath, importedItem) {
if (importedItem.isRelative === false)
return importPath;
const result = posix_1.default.relative(posix_1.default.dirname(filePath), this.resolvePath(importPath));
if (result.startsWith(".")) {
return result;
}
else {
return "./" + result;
}
}
getAdapterImportPath(adapter, outputFilePath) {
var _a, _b, _c;
const relImportPath = (_a = adapter.importPath) !== null && _a !== void 0 ? _a : (_c = (_b = this.opts.common) === null || _b === void 0 ? void 0 : _b.typeAdapter) === null || _c === void 0 ? void 0 : _c.importPath;
if (!relImportPath) {
throw new Error(`Unable to resolve import path for type adapter: ${JSON.stringify(adapter)}`);
}
return this.getImportPathForOutputPath(outputFilePath, relImportPath, adapter);
}
preProcessTemplateInput(input) {
return __awaiter(this, void 0, void 0, function* () {
return input;
});
}
postProcessOutput(output, _table) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const sections = [output];
if ((_a = this.opts.rawContent) === null || _a === void 0 ? void 0 : _a.before) {
sections.unshift(this.opts.rawContent.before);
}
if ((_b = this.opts.rawContent) === null || _b === void 0 ? void 0 : _b.after) {
sections.push(this.opts.rawContent.after);
}
return sections.join('\n');
});
}
getCrudRepoName(tableName) {
return this.naming.crudRepositoryClassNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.crudRepositoryClassNameSuffix;
}
getTableMapperClassName(tableName, tableKind) {
if (tableKind === 'Table') {
return this.naming.tableClassNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.tableClassNameSuffix;
}
else {
return this.naming.viewClassNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.viewClassNameSuffix;
}
}
getRowTypePrefix(tableName) {
return this.getPascalCasedTableName(tableName);
}
getTableMapperInstanceName(tableName, tableKind) {
if (tableKind === 'Table') {
return this.naming.tableInstanceNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.tableInstanceNameSuffix;
}
else {
return this.naming.viewInstanceNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.viewInstanceNameSuffix;
}
}
getColumnsObjectName(tableName, tableKind) {
if (tableKind === 'Table') {
if (this.naming.tableColumnsNamePrefix) {
return this.naming.tableColumnsNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.tableColumnsNameSuffix;
}
else {
return this.getCamelCasedTableName(tableName) +
this.naming.tableColumnsNameSuffix;
}
}
else {
if (this.naming.viewColumnsNamePrefix) {
return this.naming.viewColumnsNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.viewColumnsNameSuffix;
}
else {
return this.getCamelCasedTableName(tableName) +
this.naming.viewColumnsNameSuffix;
}
}
}
getPascalCasedTableName(tableName) {
return (0, lodash_1.upperFirst)((0, lodash_1.camelCase)((0, lodash_1.last)(tableName.split("."))));
}
getCamelCasedTableName(tableName) {
return (0, lodash_1.camelCase)((0, lodash_1.last)(tableName.split(".")));
}
isColumnOmitted(tableName, col) {
const mapping = this.getFieldMappings().find((it) => it.generatedField === false &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type));
return !!mapping;
}
isColumnOptional(tableName, col) {
const mapping = this.getFieldMappings().find((it) => it.generatedField &&
it.generatedField.isOptional != null &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type));
if (mapping === null || mapping === void 0 ? void 0 : mapping.generatedField) {
return mapping.generatedField.isOptional === true;
}
else {
return col.nullable === true;
}
}
doesColumnHaveDefault(tableName, col) {
const mapping = this.getFieldMappings().find((it) => it.generatedField &&
it.generatedField.hasDefault != null &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type));
if (mapping === null || mapping === void 0 ? void 0 : mapping.generatedField) {
return mapping.generatedField.hasDefault === true;
}
else {
return col.default != null;
}
}
isColumnComputed(tableName, col) {
const mapping = this.getFieldMappings().find((it) => it.generatedField &&
it.generatedField.isComputed != null &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type));
if (mapping === null || mapping === void 0 ? void 0 : mapping.generatedField) {
return mapping.generatedField.isComputed === true;
}
return false;
}
getColComment(tableName, col) {
var _a;
const mapping = this.getFieldMappings().find((it) => it.comment &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type));
return (_a = mapping === null || mapping === void 0 ? void 0 : mapping.comment) !== null && _a !== void 0 ? _a : undefined;
}
getFieldNameForColumn(tableName, col) {
var _a, _b;
const mapping = this.getFieldMappings().find((it) => {
var _a;
return it.generatedField &&
((_a = it.generatedField) === null || _a === void 0 ? void 0 : _a.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type);
});
return ((_b = (_a = mapping === null || mapping === void 0 ? void 0 : mapping.generatedField) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (0, lodash_1.camelCase)(col.name));
}
getFieldType(tableName, col) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const mapping = this.getFieldMappings().find((it) => {
var _a;
return it.generatedField &&
((_a = it.generatedField) === null || _a === void 0 ? void 0 : _a.type) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnName, col.name) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.tableName, tableName) &&
(0, matcher_1.doesMatchNameOrPatternNamespaced)(it.columnType, col.type);
});
if (!mapping) {
throw new Error(`Failed to infer field type for ${tableName}.${col.name}`);
}
const generatedField = mapping.generatedField;
const dbTypeName = (_c = (_b = (_a = generatedField.type) === null || _a === void 0 ? void 0 : _a.dbType) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : col.type;
let tsTypeName = (_e = (_d = generatedField.type) === null || _d === void 0 ? void 0 : _d.tsType) === null || _e === void 0 ? void 0 : _e.name;
if (((_f = generatedField === null || generatedField === void 0 ? void 0 : generatedField.type) === null || _f === void 0 ? void 0 : _f.adapter) && !tsTypeName) {
tsTypeName = (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(dbTypeName));
}
return Object.assign(Object.assign({}, generatedField.type), { dbType: Object.assign(Object.assign({}, (_g = generatedField.type) === null || _g === void 0 ? void 0 : _g.dbType), { name: dbTypeName }), tsType: Object.assign(Object.assign({}, (_h = generatedField.type) === null || _h === void 0 ? void 0 : _h.tsType), { name: tsTypeName !== null && tsTypeName !== void 0 ? tsTypeName : "unknown" }) });
}
getOutputFilePath(table, tableKind) {
const fileName = this.getOutputFileName(table, tableKind);
return posix_1.default.join(this.opts.outputDirPath, fileName);
}
getOutputFileName(table, tableKind) {
return this.getTableMapperClassName(table.name, tableKind) + ".ts";
}
findPrimaryKey(table) {
var _a, _b, _c, _d, _e;
let col = null;
const commonPKColName = (_b = (_a = this.opts.common) === null || _a === void 0 ? void 0 : _a.primaryKey) === null || _b === void 0 ? void 0 : _b.name;
if (commonPKColName) {
col = (_c = table.columns.find((it) => it.name === commonPKColName)) !== null && _c !== void 0 ? _c : null;
}
if (!col) {
const pkConstraint = (_d = table.constraints) === null || _d === void 0 ? void 0 : _d.find((it) => it.type === "PRIMARY KEY");
if (pkConstraint && pkConstraint.columns.length === 1) {
return (_e = table.columns.find((it) => it.name === pkConstraint.columns[0])) !== null && _e !== void 0 ? _e : null;
}
}
return null;
}
wrapType(typeExpr, wrapper) {
if (!wrapper)
return typeExpr;
return `${wrapper}<${typeExpr}>`;
}
getTypeWrapper(typeName) {
var _a, _b;
return (_b = (_a = this.opts.typeWrappers) === null || _a === void 0 ? void 0 : _a.find(it => {
return (0, matcher_1.doesMatchNameOrPattern)(it.typeName, typeName);
})) === null || _b === void 0 ? void 0 : _b.wrapper;
}
extractTableName(configTableName) {
return (0, lodash_1.last)(configTableName.split("."));
}
getSelectedRowTypeName(tableName) {
return this.naming.selectedRowTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.selectedRowTypeNameSuffix;
}
getInsertableRowTypeName(tableName) {
return this.naming.insertableRowTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.insertableRowTypeNameSuffix;
}
getUpdatableRowTypeName(tableName) {
return this.naming.updatableRowTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.updatableRowTypeNameSuffix;
}
getSelectedValuesTypeName(tableName) {
return this.naming.selectedValuesTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.selectedValuesTypeNameSuffix;
}
getInsertableValuesTypeName(tableName) {
return this.naming.insertableValuesTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.insertableValuesTypeNameSuffix;
}
getUpdatableValuesTypeName(tableName) {
return this.naming.updatableValuesTypeNamePrefix +
this.getPascalCasedTableName(tableName) +
this.naming.updatableValuesTypeNameSuffix;
}
getColMappingObjName(tableName) {
return this.getPascalCasedTableName(tableName) + this.naming.columnTypeMappingInterfaceNameSuffix;
}
getWrappedTypeInput(name, baseExpr, imports, isInterface = false) {
const selectedWrapper = this.getTypeWrapper(name);
if (selectedWrapper === null || selectedWrapper === void 0 ? void 0 : selectedWrapper.importPath)
imports.push({
importPath: selectedWrapper.importPath,
imported: [selectedWrapper.name],
isDefault: !!selectedWrapper.isDefault
});
return {
name,
isInterface,
expr: this.wrapType(baseExpr, selectedWrapper === null || selectedWrapper === void 0 ? void 0 : selectedWrapper.name)
};
}
getRowTypeInputs(tableName, tableKind, mapperClassName, imports) {
var _a, _b;
const isExported = (_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.rowTypes;
const hasRepo = (_b = this.opts.export) === null || _b === void 0 ? void 0 : _b.crudRepository;
const isInterface = (0, lodash_1.isObject)(isExported) && isExported.asInterface;
const rowTypes = (isExported || hasRepo)
? {}
: false;
if (rowTypes !== false) {
rowTypes.selected = this.getWrappedTypeInput(this.getSelectedRowTypeName(tableName), `SelectedRow<${mapperClassName}>`, imports, isInterface);
rowTypes.selected.isExported = isExported;
if (tableKind !== "View") {
rowTypes.insertable = this.getWrappedTypeInput(this.getInsertableRowTypeName(tableName), `InsertableRow<${mapperClassName}>`, imports, isInterface);
rowTypes.insertable.isExported = isExported;
rowTypes.updatable = this.getWrappedTypeInput(this.getUpdatableRowTypeName(tableName), `UpdatableRow<${mapperClassName}>`, imports, isInterface);
rowTypes.updatable.isExported = isExported;
}
}
return rowTypes;
}
getValuesTypeInputs(tableName, tableKind, mapperClassName, imports) {
var _a;
const isExported = (_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.valuesTypes;
const isInterface = (0, lodash_1.isObject)(isExported) && isExported.asInterface;
const valuesTypes = isExported ? {} : false;
if (valuesTypes !== false) {
valuesTypes.selected = this.getWrappedTypeInput(this.getSelectedValuesTypeName(tableName), `SelectedValues<${mapperClassName}>`, imports, isInterface);
if (tableKind !== "View") {
valuesTypes.insertable = this.getWrappedTypeInput(this.getInsertableValuesTypeName(tableName), `InsertableValues<${mapperClassName}>`, imports, isInterface);
valuesTypes.updatable = this.getWrappedTypeInput(this.getUpdatableValuesTypeName(tableName), `UpdatableValues<${mapperClassName}>`, imports, isInterface);
}
}
return valuesTypes;
}
getColSetName(tableName, tableKind) {
var _a;
return ((_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.extractedColumns)
? this.getColumnsObjectName(tableName, tableKind)
: null;
}
getTableMapperInstName(tableName, tableKind) {
var _a, _b;
return ((_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.tableInstances) || ((_b = this.opts.export) === null || _b === void 0 ? void 0 : _b.extractedColumns)
? this.getTableMapperInstanceName(tableName, tableKind)
: null;
}
getColMappingInput(tableName, didGenerateRepo) {
var _a;
const exportColMapping = (((_a = this.opts.export) === null || _a === void 0 ? void 0 : _a.columnTypeMappingInterface) || didGenerateRepo)
? {}
: false;
if (exportColMapping !== false) {
exportColMapping.name = this.getColMappingObjName(tableName);
}
return exportColMapping;
}
}
exports.Generator = Generator;
//# sourceMappingURL=generator.js.map