From 35c92b1e297b1750db80387fd6bfeb6bd7dca0c2 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 29 May 2023 17:24:47 +0300 Subject: [PATCH 01/22] All smaller functions that build DDL return AlterScriptDto instances. alterScriptFromDeltaHelper.js is broken --- forward_engineering/configs/templates.js | 18 + forward_engineering/ddlProvider.js | 115 ++++++ .../helpers/alterScriptFromDeltaHelper.js | 355 +++++++++--------- .../alterContainerHelper.js | 34 +- .../alterScriptHelpers/alterEntityHelper.js | 98 +++-- .../alterScriptHelpers/alterUdtHelper.js | 284 +++++++------- .../alterScriptHelpers/alterViewHelper.js | 32 +- .../columnHelpers/alterTypeHelper.js | 21 +- .../columnHelpers/commentsHelper.js | 28 +- .../columnHelpers/nonNullConstraintHelper.js | 15 +- .../columnHelpers/renameColumnHelper.js | 11 +- .../containerHelpers/commentsHelper.js | 29 +- .../helpers/alterScriptHelpers/ddlHelper.js | 9 + .../entityHelpers/checkConstraintHelper.js | 36 +- .../entityHelpers/commentsHelper.js | 33 +- .../types/AlterScriptDto.js | 67 ++++ .../viewHelpers/commentsHelper.js | 29 +- .../types/coreApplicationDataTypes.js | 215 +++++++++++ .../types/coreApplicationTypes.js | 158 ++++++++ 19 files changed, 1148 insertions(+), 439 deletions(-) create mode 100644 forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js create mode 100644 forward_engineering/types/coreApplicationDataTypes.js create mode 100644 forward_engineering/types/coreApplicationTypes.js diff --git a/forward_engineering/configs/templates.js b/forward_engineering/configs/templates.js index 81be654..c7e8a2c 100644 --- a/forward_engineering/configs/templates.js +++ b/forward_engineering/configs/templates.js @@ -39,6 +39,24 @@ module.exports = { createForeignKey: 'ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};', + dropTable: 'DROP TABLE IF EXISTS ${tableName};', + + addColumn: 'ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};', + + dropColumn: 'ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};', + + dropDomain: 'DROP DOMAIN IF EXISTS ${udtName};', + + dropType: 'DROP TYPE IF EXISTS ${udtName};', + + alterTypeAddAttribute: 'ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};', + + alterTypeDropAttribute: 'ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};', + + alterTypeRenameAttribute: 'ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};', + + alterTypeChangeAttributeType: 'ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};', + updateCommentOnTable: 'COMMENT ON TABLE ${tableName} IS ${comment};', updateCommentOnColumn: 'COMMENT ON COLUMN ${columnName} IS ${comment};', diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index cf19aef..47e177e 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -932,5 +932,120 @@ module.exports = (baseProvider, options, app) => { } return assignTemplates(templates.dropSchema, templateConfig); }, + + /** + * @param tableName {string} + * @return string + * */ + dropTable(tableName) { + const templateConfig = { + tableName, + } + return assignTemplates(templates.dropTable, templateConfig); + }, + + /** + * @param tableName {string} + * @param columnDefinition {string} + * @return string + * */ + addColumn(tableName, columnDefinition) { + const templateConfig = { + tableName, + columnDefinition, + } + return assignTemplates(templates.addColumn, templateConfig); + }, + + /** + * @param tableName {string} + * @param columnName {string} + * @return string + * */ + dropColumn(tableName, columnName) { + const templateConfig = { + tableName, + columnName, + } + return assignTemplates(templates.dropColumn, templateConfig); + }, + + /** + * @param udtName {string} + * @return string + * */ + dropDomain(udtName,) { + const templateConfig = { + udtName, + } + return assignTemplates(templates.dropDomain, templateConfig); + }, + + /** + * @param udtName {string} + * @return string + * */ + dropType(udtName,) { + const templateConfig = { + udtName, + } + return assignTemplates(templates.dropType, templateConfig); + }, + + /** + * @param udtName {string} + * @param columnDefinition {string} + * @return string + * */ + alterTypeAddAttribute(udtName, columnDefinition) { + const templateConfig = { + udtName, + columnDefinition, + } + return assignTemplates(templates.alterTypeAddAttribute, templateConfig); + }, + + /** + * @param udtName {string} + * @param attributeName {string} + * @return string + * */ + alterTypeDropAttribute(udtName, attributeName) { + const templateConfig = { + udtName, + attributeName, + } + return assignTemplates(templates.alterTypeDropAttribute, templateConfig); + }, + + /** + * @param udtName {string} + * @param oldAttributeName {string} + * @param newAttributeName {string} + * @return string + * */ + alterTypeRenameAttribute(udtName, oldAttributeName, newAttributeName) { + const templateConfig = { + udtName, + oldAttributeName, + newAttributeName, + } + return assignTemplates(templates.alterTypeRenameAttribute, templateConfig); + }, + + /** + * @param udtName {string} + * @param attributeName {string} + * @param newDataType {string} + * @return string + * */ + alterTypeChangeAttributeType(udtName, attributeName, newDataType) { + const templateConfig = { + udtName, + attributeName, + newDataType, + } + return assignTemplates(templates.alterTypeChangeAttributeType, templateConfig); + }, }; }; diff --git a/forward_engineering/helpers/alterScriptFromDeltaHelper.js b/forward_engineering/helpers/alterScriptFromDeltaHelper.js index ee5bed7..36a1085 100644 --- a/forward_engineering/helpers/alterScriptFromDeltaHelper.js +++ b/forward_engineering/helpers/alterScriptFromDeltaHelper.js @@ -1,202 +1,211 @@ -const { getAddContainerScript, getDeleteContainerScript, getModifyContainerScript} = require('./alterScriptHelpers/alterContainerHelper'); const { - getAddCollectionScript, - getDeleteCollectionScript, - getAddColumnScript, - getDeleteColumnScript, - getModifyColumnScript, getModifyCollectionScript, + getAddContainerScriptDto, + getDeleteContainerScriptDto, + getModifyContainerScriptDtos +} = require('./alterScriptHelpers/alterContainerHelper'); +const { + getAddCollectionScriptDto, + getDeleteCollectionScriptDto, + getAddColumnScriptDtos, + getDeleteColumnScriptDtos, + getModifyColumnScriptDtos, + getModifyCollectionScriptDtos, } = require('./alterScriptHelpers/alterEntityHelper'); const { - getDeleteUdtScript, - getCreateUdtScript, - getAddColumnToTypeScript, - getDeleteColumnFromTypeScript, - getModifyColumnOfTypeScript, + getDeleteUdtScriptDto, + getCreateUdtScriptDto, + getAddColumnToTypeScriptDtos, + getDeleteColumnFromTypeScriptDtos, + getModifyColumnOfTypeScriptDto, } = require('./alterScriptHelpers/alterUdtHelper'); -const { getAddViewScript, getDeleteViewScript, getModifyViewScript} = require('./alterScriptHelpers/alterViewHelper'); +const { + getAddViewScriptDto, + getDeleteViewScriptDto, + getModifyViewScriptDtos +} = require('./alterScriptHelpers/alterViewHelper'); const getComparisonModelCollection = collections => { - return collections - .map(collection => JSON.parse(collection)) - .find(collection => collection.collectionName === 'comparisonModelCollection'); + return collections + .map(collection => JSON.parse(collection)) + .find(collection => collection.collectionName === 'comparisonModelCollection'); }; -const getAlterContainersScripts = ({ collection, app}) => { - const addedContainers = collection.properties?.containers?.properties?.added?.items; - const deletedContainers = collection.properties?.containers?.properties?.deleted?.items; - const modifiedContainers = collection.properties?.containers?.properties?.modified?.items; +const getAlterContainersScripts = ({collection, app}) => { + const addedContainers = collection.properties?.containers?.properties?.added?.items; + const deletedContainers = collection.properties?.containers?.properties?.deleted?.items; + const modifiedContainers = collection.properties?.containers?.properties?.modified?.items; - const addContainersScripts = [] - .concat(addedContainers) - .filter(Boolean) - .map(container => getAddContainerScript(app)(Object.keys(container.properties)[0])); - const deleteContainersScripts = [] - .concat(deletedContainers) - .filter(Boolean) - .map(container => getDeleteContainerScript(app)(Object.keys(container.properties)[0])); - const modifyContainersScripts = [] - .concat(modifiedContainers) - .filter(Boolean) - .map(containerWrapper => Object.values(containerWrapper.properties)[0]) - .map(container => getModifyContainerScript(app)(container)) + const addContainersScripts = [] + .concat(addedContainers) + .filter(Boolean) + .map(container => getAddContainerScriptDto(app)(Object.keys(container.properties)[0])); + const deleteContainersScripts = [] + .concat(deletedContainers) + .filter(Boolean) + .map(container => getDeleteContainerScriptDto(app)(Object.keys(container.properties)[0])); + const modifyContainersScripts = [] + .concat(modifiedContainers) + .filter(Boolean) + .map(containerWrapper => Object.values(containerWrapper.properties)[0]) + .map(container => getModifyContainerScriptDtos(app)(container)) - return [ - ...addContainersScripts, - ...deleteContainersScripts, - ...modifyContainersScripts, - ]; + return [ + ...addContainersScripts, + ...deleteContainersScripts, + ...modifyContainersScripts, + ]; }; const getAlterCollectionsScripts = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, -}) => { - const createCollectionsScripts = [] - .concat(collection.properties?.entities?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => collection.compMod?.created) - .map(getAddCollectionScript({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions })); - const deleteCollectionScripts = [] - .concat(collection.properties?.entities?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => collection.compMod?.deleted) - .map(getDeleteCollectionScript(app)); - const modifyCollectionScripts = [] - .concat(collection.properties?.entities?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(getModifyCollectionScript(app)) - .flat(); - const addColumnScripts = [] - .concat(collection.properties?.entities?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getAddColumnScript({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions })); - const deleteColumnScripts = [] - .concat(collection.properties?.entities?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getDeleteColumnScript(app)); - const modifyColumnScript = [] - .concat(collection.properties?.entities?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getModifyColumnScript(app)); + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }) => { + const createCollectionsScripts = [] + .concat(collection.properties?.entities?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(collection => collection.compMod?.created) + .map(getAddCollectionScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); + const deleteCollectionScripts = [] + .concat(collection.properties?.entities?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(collection => collection.compMod?.deleted) + .map(getDeleteCollectionScriptDto(app)); + const modifyCollectionScripts = [] + .concat(collection.properties?.entities?.properties?.modified?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .map(getModifyCollectionScriptDtos(app)) + .flat(); + const addColumnScripts = [] + .concat(collection.properties?.entities?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(collection => !collection.compMod) + .flatMap(getAddColumnScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); + const deleteColumnScripts = [] + .concat(collection.properties?.entities?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(collection => !collection.compMod) + .flatMap(getDeleteColumnScriptDtos(app)); + const modifyColumnScript = [] + .concat(collection.properties?.entities?.properties?.modified?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(collection => !collection.compMod) + .flatMap(getModifyColumnScriptDtos(app)); - return [ - ...createCollectionsScripts, - ...deleteCollectionScripts, - ...modifyCollectionScripts, - ...addColumnScripts, - ...deleteColumnScripts, - ...modifyColumnScript, - ].map(script => script.trim()); + return [ + ...createCollectionsScripts, + ...deleteCollectionScripts, + ...modifyCollectionScripts, + ...addColumnScripts, + ...deleteColumnScripts, + ...modifyColumnScript, + ].map(script => script.trim()); }; const getAlterViewScripts = (collection, app) => { - const createViewsScripts = [] - .concat(collection.properties?.views?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(view => ({ ...view, ...(view.role || {}) })) - .filter(view => view.compMod?.created && view.selectStatement) - .map(getAddViewScript(app)); + const createViewsScripts = [] + .concat(collection.properties?.views?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .map(view => ({...view, ...(view.role || {})})) + .filter(view => view.compMod?.created && view.selectStatement) + .map(getAddViewScriptDto(app)); - const deleteViewsScripts = [] - .concat(collection.properties?.views?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(view => ({ ...view, ...(view.role || {}) })) - .map(getDeleteViewScript(app)); + const deleteViewsScripts = [] + .concat(collection.properties?.views?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .map(view => ({...view, ...(view.role || {})})) + .map(getDeleteViewScriptDto(app)); - const modifyViewsScripts = [] - .concat(collection.properties?.views?.properties?.modified?.items) - .filter(Boolean) - .map(viewWrapper => Object.values(viewWrapper.properties)[0]) - .map(view => ({ ...view, ...(view.role || {}) })) - .flatMap(view => getModifyViewScript(app)(view)); + const modifyViewsScripts = [] + .concat(collection.properties?.views?.properties?.modified?.items) + .filter(Boolean) + .map(viewWrapper => Object.values(viewWrapper.properties)[0]) + .map(view => ({...view, ...(view.role || {})})) + .flatMap(view => getModifyViewScriptDtos(app)(view)); - return [ - ...deleteViewsScripts, - ...createViewsScripts, - ...modifyViewsScripts, - ].map(script => script.trim()); + return [ + ...deleteViewsScripts, + ...createViewsScripts, + ...modifyViewsScripts, + ].map(script => script.trim()); }; const getAlterModelDefinitionsScripts = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, -}) => { - const createUdtScripts = [] - .concat(collection.properties?.modelDefinitions?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(item => ({ ...item, ...(app.require('lodash').omit(item.role, 'properties') || {}) })) - .filter(item => item.compMod?.created) - .map(getCreateUdtScript({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions })); - const deleteUdtScripts = [] - .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(item => ({ ...item, ...(app.require('lodash').omit(item.role, 'properties') || {}) })) - .filter(collection => collection.compMod?.deleted) - .map(getDeleteUdtScript(app)); - const addColumnScripts = [] - .concat(collection.properties?.modelDefinitions?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({ ...item, ...(app.require('lodash').omit(item.role, 'properties') || {}) })) - .filter(item => item.childType === 'composite') - .flatMap( - getAddColumnToTypeScript({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions }), - ); - const deleteColumnScripts = [] - .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({ ...item, ...(app.require('lodash').omit(item.role, 'properties') || {}) })) - .filter(item => item.childType === 'composite') - .flatMap(getDeleteColumnFromTypeScript(app)); + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }) => { + const createUdtScripts = [] + .concat(collection.properties?.modelDefinitions?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) + .filter(item => item.compMod?.created) + .map(getCreateUdtScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); + const deleteUdtScripts = [] + .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) + .filter(collection => collection.compMod?.deleted) + .map(getDeleteUdtScriptDto(app)); + const addColumnScripts = [] + .concat(collection.properties?.modelDefinitions?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(item => !item.compMod) + .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) + .filter(item => item.childType === 'composite') + .flatMap( + getAddColumnToTypeScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}), + ); + const deleteColumnScripts = [] + .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(item => !item.compMod) + .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) + .filter(item => item.childType === 'composite') + .flatMap(getDeleteColumnFromTypeScriptDtos(app)); - const modifyColumnScripts = [] - .concat(collection.properties?.modelDefinitions?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({ ...item, ...(app.require('lodash').omit(item.role, 'properties') || {}) })) - .filter(item => item.childType === 'composite') - .flatMap(getModifyColumnOfTypeScript(app)); + const modifyColumnScripts = [] + .concat(collection.properties?.modelDefinitions?.properties?.modified?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(item => !item.compMod) + .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) + .filter(item => item.childType === 'composite') + .flatMap(getModifyColumnOfTypeScriptDto(app)); - return [ - ...deleteUdtScripts, - ...createUdtScripts, - ...addColumnScripts, - ...deleteColumnScripts, - ...modifyColumnScripts, - ] - .filter(Boolean) - .map(script => script.trim()); + return [ + ...deleteUdtScripts, + ...createUdtScripts, + ...addColumnScripts, + ...deleteColumnScripts, + ...modifyColumnScripts, + ] + .filter(Boolean) + .map(script => script.trim()); }; module.exports = { - getComparisonModelCollection, - getAlterContainersScripts, - getAlterCollectionsScripts, - getAlterViewScripts, - getAlterModelDefinitionsScripts, + getComparisonModelCollection, + getAlterContainersScripts, + getAlterCollectionsScripts, + getAlterViewScripts, + getAlterModelDefinitionsScripts, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js index f286044..05e9fd4 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js @@ -1,35 +1,45 @@ -const {getModifySchemaCommentsScripts} = require("./containerHelpers/commentsHelper"); -const getAddContainerScript = (app) => (containerName) => { +const {getModifySchemaCommentsScriptDtos} = require("./containerHelpers/commentsHelper"); +const {AlterScriptDto} = require("./types/AlterScriptDto"); + +/** + * @return {(containerName: string) => AlterScriptDto} + * */ +const getAddContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); const {wrapInQuotes} = require('../general')({_}); - return ddlProvider.createSchemaOnly(wrapInQuotes(containerName)); + const script = ddlProvider.createSchemaOnly(wrapInQuotes(containerName)); + return AlterScriptDto.getInstance([script], true, false); }; -const getDeleteContainerScript = (app) => (containerName) => { +/** + * @return {(containerName: string) => AlterScriptDto} + * */ +const getDeleteContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); const {wrapInQuotes} = require('../general')({_}); - return ddlProvider.dropSchema(wrapInQuotes(containerName)); + const script = ddlProvider.dropSchema(wrapInQuotes(containerName)); + return AlterScriptDto.getInstance([script], true, true); }; /** - * @return (collection: Object) => Array + * @return {(container: Object) => Array} * */ -const getModifyContainerScript = (app) => (container) => { +const getModifyContainerScriptDtos = (app) => (container) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const modifyCommentScripts = getModifySchemaCommentsScripts(_, ddlProvider)(container); + const modifyCommentScriptDtos = getModifySchemaCommentsScriptDtos(_, ddlProvider)(container); return [ - ...modifyCommentScripts + ...modifyCommentScriptDtos ]; } module.exports = { - getAddContainerScript, - getDeleteContainerScript, - getModifyContainerScript + getAddContainerScriptDto, + getDeleteContainerScriptDto, + getModifyContainerScriptDtos }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js index 2d6eb4d..8e3d644 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js @@ -1,12 +1,17 @@ -const {getModifyCheckConstraintScripts} = require("./entityHelpers/checkConstraintHelper"); +const {getModifyCheckConstraintScriptDtos} = require("./entityHelpers/checkConstraintHelper"); const {getFullTableName} = require("./ddlHelper"); -const {getModifyEntityCommentsScripts} = require("./entityHelpers/commentsHelper"); -const {getUpdateTypesScripts} = require("./columnHelpers/alterTypeHelper"); -const {getModifyNonNullColumnsScripts} = require("./columnHelpers/nonNullConstraintHelper"); -const {getModifiedCommentOnColumnScripts} = require("./columnHelpers/commentsHelper"); -const {getRenameColumnScripts} = require("./columnHelpers/renameColumnHelper"); +const {getModifyEntityCommentsScriptDtos} = require("./entityHelpers/commentsHelper"); +const {getUpdateTypesScriptDtos} = require("./columnHelpers/alterTypeHelper"); +const {getModifyNonNullColumnsScriptDtos} = require("./columnHelpers/nonNullConstraintHelper"); +const {getModifiedCommentOnColumnScriptDtos} = require("./columnHelpers/commentsHelper"); +const {getRenameColumnScriptDtos} = require("./columnHelpers/renameColumnHelper"); +const {AlterScriptDto} = require("./types/AlterScriptDto"); -const getAddCollectionScript = + +/** + * @return {(collection: Object) => AlterScriptDto} + * */ +const getAddCollectionScriptDto = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => collection => { const _ = app.require('lodash'); @@ -49,31 +54,40 @@ const getAddCollectionScript = }; const hydratedTable = ddlProvider.hydrateTable({tableData, entityData: [jsonSchema], jsonSchema}); - return ddlProvider.createTable(hydratedTable, jsonSchema.isActivated); + const script = ddlProvider.createTable(hydratedTable, jsonSchema.isActivated); + return AlterScriptDto.getInstance([script], true, false) }; -const getDeleteCollectionScript = app => collection => { +/** + * @return {(collection: Object) => AlterScriptDto} + * */ +const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); + const ddlProvider = require('../../ddlProvider')(null, null, app); const fullName = getFullTableName(_)(collection); - return `DROP TABLE IF EXISTS ${fullName};`; + const script = ddlProvider.dropTable(fullName); + return AlterScriptDto.getInstance([script], true, true); }; /** - * @return (collection: Object) => Array + * @return {(collection: Object) => AlterScriptDto[]} * */ -const getModifyCollectionScript = (app) => (collection) => { +const getModifyCollectionScriptDtos = (app) => (collection) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const modifyCheckConstraintScripts = getModifyCheckConstraintScripts(_, ddlProvider)(collection); - const modifyCommentScripts = getModifyEntityCommentsScripts(_, ddlProvider)(collection); + const modifyCheckConstraintScriptDtos = getModifyCheckConstraintScriptDtos(_, ddlProvider)(collection); + const modifyCommentScriptDtos = getModifyEntityCommentsScriptDtos(_, ddlProvider)(collection); return [ - ...modifyCheckConstraintScripts, - ...modifyCommentScripts + ...modifyCheckConstraintScriptDtos, + ...modifyCommentScriptDtos ]; } -const getAddColumnScript = +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getAddColumnScriptDtos = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => collection => { const _ = app.require('lodash'); @@ -109,46 +123,58 @@ const getAddColumnScript = }); }) .map(ddlProvider.convertColumnDefinition) - .map(script => `ALTER TABLE IF EXISTS ${fullName} ADD COLUMN IF NOT EXISTS ${script};`); + .map(columnDefinition => ddlProvider.addColumn(fullName, columnDefinition)) + .map(addColumnScript => AlterScriptDto.getInstance([addColumnScript], true, false)); }; -const getDeleteColumnScript = app => collection => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getDeleteColumnScriptDtos = app => collection => { const _ = app.require('lodash'); + const ddlProvider = require('../../ddlProvider')(null, null, app); const {getEntityName} = require('../../utils/general')(_); const {getNamePrefixedWithSchemaName, wrapInQuotes} = require('../general')({_}); const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; const tableName = getEntityName(collectionSchema); const schemaName = collectionSchema.compMod?.keyspaceName; - const fullName = getNamePrefixedWithSchemaName(tableName, schemaName); + const fullTableName = getNamePrefixedWithSchemaName(tableName, schemaName); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => !jsonSchema.compMod) - .map(([name]) => `ALTER TABLE IF EXISTS ${fullName} DROP COLUMN IF EXISTS ${wrapInQuotes(name)};`); + .map(([name]) => { + const columnNameForDDL = wrapInQuotes(name); + return ddlProvider.dropColumn(fullTableName, columnNameForDDL) + }) + .map(dropColumnScript => AlterScriptDto.getInstance([dropColumnScript], true, true)); }; -const getModifyColumnScript = app => collection => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getModifyColumnScriptDtos = app => collection => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const renameColumnScripts = getRenameColumnScripts(_, ddlProvider)(collection); - const updateTypeScripts = getUpdateTypesScripts(_, ddlProvider)(collection); - const modifyNotNullScripts = getModifyNonNullColumnsScripts(_, ddlProvider)(collection); - const modifyCommentScripts = getModifiedCommentOnColumnScripts(_, ddlProvider)(collection); + const renameColumnScriptDtos = getRenameColumnScriptDtos(_, ddlProvider)(collection); + const updateTypeScriptDtos = getUpdateTypesScriptDtos(_, ddlProvider)(collection); + const modifyNotNullScriptDtos = getModifyNonNullColumnsScriptDtos(_, ddlProvider)(collection); + const modifyCommentScriptDtos = getModifiedCommentOnColumnScriptDtos(_, ddlProvider)(collection); return [ - ...renameColumnScripts, - ...updateTypeScripts, - ...modifyNotNullScripts, - ...modifyCommentScripts, + ...renameColumnScriptDtos, + ...updateTypeScriptDtos, + ...modifyNotNullScriptDtos, + ...modifyCommentScriptDtos, ]; }; module.exports = { - getAddCollectionScript, - getDeleteCollectionScript, - getModifyCollectionScript, - getAddColumnScript, - getDeleteColumnScript, - getModifyColumnScript, + getAddCollectionScriptDto, + getDeleteCollectionScriptDto, + getModifyCollectionScriptDtos, + getAddColumnScriptDtos, + getDeleteColumnScriptDtos, + getModifyColumnScriptDtos, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js index 67a6450..476c730 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js @@ -1,135 +1,165 @@ -const { checkFieldPropertiesChanged } = require('./common'); - -const getCreateUdtScript = - ({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions }) => - jsonSchema => { - const _ = app.require('lodash'); - const { createColumnDefinitionBySchema } = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider')(null, null, app); - const { getDefinitionByReference } = app.require('@hackolade/ddl-fe-utils'); - - const schemaData = { dbVersion }; - - const columnDefinitions = _.toPairs(jsonSchema.properties || {}).map(([name, column]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: column, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema: column, - parentJsonSchema: jsonSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }); - - const updatedUdt = createColumnDefinitionBySchema({ - name: jsonSchema.code || jsonSchema.name, - jsonSchema: jsonSchema, - parentJsonSchema: { required: [] }, - definitionJsonSchema: {}, - ddlProvider, - schemaData, - }); - - const udt = { ...updatedUdt, properties: columnDefinitions }; - - return ddlProvider.createUdt(udt); - }; - -const getDeleteUdtScript = app => udt => { - const _ = app.require('lodash'); - const { wrapInQuotes } = require('../general')({ _ }); - - if (udt.type === 'domain') { - return `DROP DOMAIN IF EXISTS ${wrapInQuotes(udt.code || udt.name)};`; - } else { - return `DROP TYPE IF EXISTS ${wrapInQuotes(udt.code || udt.name)};`; - } +const {checkFieldPropertiesChanged} = require('./common'); +const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {getUdtName} = require("./ddlHelper"); + +/** + * @return {(jsonSchema: Object) => AlterScriptDto} + * */ +const getCreateUdtScriptDto = + ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => + jsonSchema => { + const _ = app.require('lodash'); + const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); + const ddlProvider = require('../../ddlProvider')(null, null, app); + const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); + + const schemaData = {dbVersion}; + + const columnDefinitions = _.toPairs(jsonSchema.properties || {}).map(([name, column]) => { + const definitionJsonSchema = getDefinitionByReference({ + propertySchema: column, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }); + + return createColumnDefinitionBySchema({ + name, + jsonSchema: column, + parentJsonSchema: jsonSchema, + ddlProvider, + schemaData, + definitionJsonSchema, + }); + }); + + const updatedUdt = createColumnDefinitionBySchema({ + name: jsonSchema.code || jsonSchema.name, + jsonSchema: jsonSchema, + parentJsonSchema: {required: []}, + definitionJsonSchema: {}, + ddlProvider, + schemaData, + }); + + const udt = {...updatedUdt, properties: columnDefinitions}; + + const script = ddlProvider.createUdt(udt); + return AlterScriptDto.getInstance([script], true, false); + }; + + +/** + * @return {(udt: Object) => AlterScriptDto} + * */ +const getDeleteUdtScriptDto = app => udt => { + const _ = app.require('lodash'); + const ddlProvider = require('../../ddlProvider')(null, null, app); + + const {wrapInQuotes} = require('../general')({_}); + + const ddlUdtName = wrapInQuotes(getUdtName(udt)); + if (udt.type === 'domain') { + const script = ddlProvider.dropDomain(ddlUdtName); + return AlterScriptDto.getInstance([script], true, true); + } else { + const script = ddlProvider.dropType(ddlUdtName); + return AlterScriptDto.getInstance([script], true, true); + } }; -const getAddColumnToTypeScript = - ({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions }) => - udt => { - const _ = app.require('lodash'); - const { createColumnDefinitionBySchema } = require('./createColumnDefinition')(app); - const { wrapInQuotes } = require('../general')({ _ }); - const ddlProvider = require('../../ddlProvider')(null, null, app); - const { getDefinitionByReference } = app.require('@hackolade/ddl-fe-utils'); - - const fullName = wrapInQuotes(udt.code || udt.name); - const schemaData = { dbVersion }; - - return _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => !jsonSchema.compMod) - .map(([name, jsonSchema]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: jsonSchema, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema, - parentJsonSchema: { required: [] }, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }) - .map(ddlProvider.convertColumnDefinition) - .map(script => `ALTER TYPE ${fullName} ADD ATTRIBUTE ${script};`); - }; - -const getDeleteColumnFromTypeScript = app => udt => { - const _ = app.require('lodash'); - const { wrapInQuotes } = require('../general')({ _ }); - - const fullName = wrapInQuotes(udt.code || udt.name); - - return _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => !jsonSchema.compMod) - .map(([name]) => `ALTER TYPE ${fullName} DROP ATTRIBUTE IF EXISTS ${wrapInQuotes(name)};`); +/** + * @return {(udt: Object) => AlterScriptDto[]} + * */ +const getAddColumnToTypeScriptDtos = + ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => + udt => { + const _ = app.require('lodash'); + const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); + const {wrapInQuotes} = require('../general')({_}); + const ddlProvider = require('../../ddlProvider')(null, null, app); + const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); + + const fullName = wrapInQuotes(getUdtName(udt)); + const schemaData = {dbVersion}; + + return _.toPairs(udt.properties) + .filter(([name, jsonSchema]) => !jsonSchema.compMod) + .map(([name, jsonSchema]) => { + const definitionJsonSchema = getDefinitionByReference({ + propertySchema: jsonSchema, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }); + + return createColumnDefinitionBySchema({ + name, + jsonSchema, + parentJsonSchema: {required: []}, + ddlProvider, + schemaData, + definitionJsonSchema, + }); + }) + .map(ddlProvider.convertColumnDefinition) + .map(columnDefinition => ddlProvider.alterTypeAddAttribute(fullName, columnDefinition)) + .map(script => AlterScriptDto.getInstance([script], true, false)); + }; + +/** + * @return {(udt: Object) => AlterScriptDto[]} + * */ +const getDeleteColumnFromTypeScriptDtos = app => udt => { + const _ = app.require('lodash'); + const ddlProvider = require('../../ddlProvider')(null, null, app); + + const {wrapInQuotes} = require('../general')({_}); + + const fullName = wrapInQuotes(udt.code || udt.name); + + return _.toPairs(udt.properties) + .filter(([name, jsonSchema]) => !jsonSchema.compMod) + .map(([name]) => ddlProvider.alterTypeDropAttribute(fullName, wrapInQuotes(name))) + .map(script => AlterScriptDto.getInstance([script], true, true)); }; -const getModifyColumnOfTypeScript = app => udt => { - const _ = app.require('lodash'); - const { wrapInQuotes } = require('../general')({ _ }); - - const fullName = wrapInQuotes(udt.code || udt.name); - - const renameColumnScripts = _.values(udt.properties) - .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) - .map( - jsonSchema => - `ALTER TYPE ${fullName} RENAME ATTRIBUTE ${wrapInQuotes( - jsonSchema.compMod.oldField.name, - )} TO ${wrapInQuotes(jsonSchema.compMod.newField.name)};`, - ); - - const changeTypeScripts = _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => checkFieldPropertiesChanged(jsonSchema.compMod, ['type', 'mode'])) - .map( - ([name, jsonSchema]) => - `ALTER TYPE ${fullName} ALTER ATTRIBUTE ${wrapInQuotes(name)} SET DATA TYPE ${ - jsonSchema.compMod.newField.mode || jsonSchema.compMod.newField.type - };`, - ); - - return [...renameColumnScripts, ...changeTypeScripts]; +/** + * @return {(udt: Object) => AlterScriptDto[]} + * */ +const getModifyColumnOfTypeScriptDto = app => udt => { + const _ = app.require('lodash'); + const ddlProvider = require('../../ddlProvider')(null, null, app); + + const {wrapInQuotes} = require('../general')({_}); + + const fullName = wrapInQuotes(udt.code || udt.name); + + const renameColumnScripts = _.values(udt.properties) + .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) + .map((jsonSchema) => { + const oldAttributeDDLName = wrapInQuotes(jsonSchema.compMod.oldField.name); + const newAttributeDDLName = wrapInQuotes(jsonSchema.compMod.newField.name); + return ddlProvider.alterTypeRenameAttribute(fullName, oldAttributeDDLName, newAttributeDDLName); + }) + .map(script => AlterScriptDto.getInstance([script], true, false)); + + const changeTypeScripts = _.toPairs(udt.properties) + .filter(([name, jsonSchema]) => checkFieldPropertiesChanged(jsonSchema.compMod, ['type', 'mode'])) + .map(([name, jsonSchema]) => { + const attributeDDLName = wrapInQuotes(name); + const newDataType = jsonSchema.compMod.newField.mode || jsonSchema.compMod.newField.type; + return ddlProvider.alterTypeChangeAttributeType(fullName, attributeDDLName, newDataType); + }) + .map(script => AlterScriptDto.getInstance([script], true, false)); + + return [...renameColumnScripts, ...changeTypeScripts]; }; module.exports = { - getCreateUdtScript, - getDeleteUdtScript, - getAddColumnToTypeScript, - getDeleteColumnFromTypeScript, - getModifyColumnOfTypeScript, + getCreateUdtScriptDto, + getDeleteUdtScriptDto, + getAddColumnToTypeScriptDtos, + getDeleteColumnFromTypeScriptDtos, + getModifyColumnOfTypeScriptDto, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js index a2379ef..a99cb3c 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js @@ -1,8 +1,10 @@ -const {getModifyViewCommentsScripts} = require("./viewHelpers/commentsHelper"); +const {getModifyViewCommentsScriptDtos} = require("./viewHelpers/commentsHelper"); +const {AlterScriptDto} = require("./types/AlterScriptDto"); + /** - * @return (view: Object) => string + * @return {(view: Object) => AlterScriptDto} * */ -const getAddViewScript = app => view => { +const getAddViewScriptDto = app => view => { const ddlProvider = require('../../ddlProvider')(null, null, app); const viewData = { @@ -12,37 +14,39 @@ const getAddViewScript = app => view => { }; const hydratedView = ddlProvider.hydrateView({ viewData, entityData: [view] }); - return ddlProvider.createView(hydratedView, {}, view.isActivated); + const script = ddlProvider.createView(hydratedView, {}, view.isActivated); + return AlterScriptDto.getInstance([script], true, false); }; /** - * @return (view: Object) => string + * @return {(view: Object) => AlterScriptDto} * */ -const getDeleteViewScript = app => view => { +const getDeleteViewScriptDto = app => view => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); const { wrapInQuotes } = require('../general')({ _ }); const viewName = wrapInQuotes(view.code || view.name); - return ddlProvider.dropView(viewName); + const script = ddlProvider.dropView(viewName); + return AlterScriptDto.getInstance([script], true, true); }; /** - * @return (view: Object) => Array + * @return {(view: Object) => AlterScriptDto[]} * */ -const getModifyViewScript = (app) => (view) => { +const getModifyViewScriptDtos = (app) => (view) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const modifyCommentsScripts = getModifyViewCommentsScripts(_, ddlProvider)(view); + const modifyCommentsScriptDtos = getModifyViewCommentsScriptDtos(_, ddlProvider)(view); return [ - ...modifyCommentsScripts, + ...modifyCommentsScriptDtos, ]; } module.exports = { - getAddViewScript, - getDeleteViewScript, - getModifyViewScript, + getAddViewScriptDto, + getDeleteViewScriptDto, + getModifyViewScriptDtos, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js index 1a382e6..d33bb2c 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -1,7 +1,10 @@ const {getFullTableName} = require("../ddlHelper"); const {checkFieldPropertiesChanged} = require("../common"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); - +/** + * @return {boolean} + * */ const hasLengthChanged = (collection, oldFieldName, currentJsonSchema) => { const oldProperty = collection.role.properties[oldFieldName]; @@ -10,6 +13,9 @@ const hasLengthChanged = (collection, oldFieldName, currentJsonSchema) => { return previousLength !== newLength; } +/** + * @return {boolean} + * */ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) => { const oldProperty = collection.role.properties[oldFieldName]; @@ -21,11 +27,14 @@ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) return previousPrecision !== newPrecision || previousScale !== newScale; } -const getUpdateTypesScripts = (_, ddlProvider) => (collection) => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getUpdateTypesScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const {wrapInQuotes} = require('../../general')({_}); - const changeTypeScripts = _.toPairs(collection.properties) + return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const hasTypeChanged = checkFieldPropertiesChanged(jsonSchema.compMod, ['type', 'mode']); if (!hasTypeChanged) { @@ -43,10 +52,10 @@ const getUpdateTypesScripts = (_, ddlProvider) => (collection) => { const typeConfig = _.pick(jsonSchema, ['length', 'precision', 'scale']); return ddlProvider.alterColumnType(fullTableName, columnName, typeName, typeConfig); } - ); - return [...changeTypeScripts]; + ) + .map(script => AlterScriptDto.getInstance([script], true, false)); } module.exports = { - getUpdateTypesScripts + getUpdateTypesScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js index 2f5cca3..237c8a1 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js @@ -1,6 +1,10 @@ const {getFullColumnName} = require("../ddlHelper"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); -const getUpdatedCommentOnColumnScripts = (_, ddlProvider) => (collection) => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { const {wrapComment} = require('../../general')({_}); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { @@ -14,10 +18,14 @@ const getUpdatedCommentOnColumnScripts = (_, ddlProvider) => (collection) => { const ddlComment = wrapComment(newComment); const columnName = getFullColumnName(_)(collection, name); return ddlProvider.updateColumnComment(columnName, ddlComment); - }); + }) + .map(script => AlterScriptDto.getInstance([script], true, false)); } -const getDeletedCommentOnColumnScripts = (_, ddlProvider) => (collection) => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getDeletedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const newComment = jsonSchema.description; @@ -28,15 +36,19 @@ const getDeletedCommentOnColumnScripts = (_, ddlProvider) => (collection) => { .map(([name, jsonSchema]) => { const columnName = getFullColumnName(_)(collection, name); return ddlProvider.dropColumnComment(columnName); - }); + }) + .map(script => AlterScriptDto.getInstance([script], true, true)); } -const getModifiedCommentOnColumnScripts = (_, ddlProvider) => (collection) => { - const updatedCommentScripts = getUpdatedCommentOnColumnScripts(_, ddlProvider)(collection); - const deletedCommentScripts = getDeletedCommentOnColumnScripts(_, ddlProvider)(collection); +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getModifiedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { + const updatedCommentScripts = getUpdatedCommentOnColumnScriptDtos(_, ddlProvider)(collection); + const deletedCommentScripts = getDeletedCommentOnColumnScriptDtos(_, ddlProvider)(collection); return [...updatedCommentScripts, ...deletedCommentScripts]; } module.exports = { - getModifiedCommentOnColumnScripts + getModifiedCommentOnColumnScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js index 090bfa3..665ffed 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js @@ -1,6 +1,10 @@ const {getFullTableName} = require("../ddlHelper"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); -const getModifyNonNullColumnsScripts = (_, ddlProvider) => (collection) => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getModifyNonNullColumnsScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const {wrapInQuotes} = require('../../general')({_}); @@ -17,7 +21,9 @@ const getModifyNonNullColumnsScripts = (_, ddlProvider) => (collection) => { const shouldAddForNewName = columnNamesToAddNotNullConstraint.includes(name); return shouldAddForNewName && !shouldRemoveForOldName; }) - .map(([columnName]) => ddlProvider.setNotNullConstraint(fullTableName, wrapInQuotes(columnName))); + .map(([columnName]) => ddlProvider.setNotNullConstraint(fullTableName, wrapInQuotes(columnName))) + .map(script => AlterScriptDto.getInstance([script], true, false)); + const removeNotNullConstraint = _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const oldName = jsonSchema.compMod.oldField.name; @@ -25,11 +31,12 @@ const getModifyNonNullColumnsScripts = (_, ddlProvider) => (collection) => { const shouldAddForNewName = columnNamesToAddNotNullConstraint.includes(name); return shouldRemoveForOldName && !shouldAddForNewName; }) - .map(([name]) => ddlProvider.dropNotNullConstraint(fullTableName, wrapInQuotes(name))); + .map(([name]) => ddlProvider.dropNotNullConstraint(fullTableName, wrapInQuotes(name))) + .map(script => AlterScriptDto.getInstance([script], true, true)); return [...addNotNullConstraintsScript, ...removeNotNullConstraint]; } module.exports = { - getModifyNonNullColumnsScripts + getModifyNonNullColumnsScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js index ff2e0e3..b2a567d 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -1,7 +1,11 @@ const {getFullTableName} = require("../ddlHelper"); const {checkFieldPropertiesChanged} = require("../common"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); -const getRenameColumnScripts = (_, ddlProvider) => (collection) => { +/** + * @return {(collection: Object) => AlterScriptDto[]} + * */ +const getRenameColumnScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const {wrapInQuotes} = require('../../general')({_}); @@ -13,9 +17,10 @@ const getRenameColumnScripts = (_, ddlProvider) => (collection) => { const newColumnName = wrapInQuotes(jsonSchema.compMod.newField.name); return ddlProvider.renameColumn(fullTableName, oldColumnName, newColumnName); } - ); + ) + .map(script => AlterScriptDto.getInstance([script], true, false)); } module.exports = { - getRenameColumnScripts + getRenameColumnScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js index 2435c91..82d2970 100644 --- a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js @@ -1,43 +1,46 @@ +const {AlterScriptDto} = require("../types/AlterScriptDto"); const extractDescription = (container) => { return container?.role?.compMod?.description || {}; } /** - * @return (container: Object) => string + * @return {(collection: Object) => AlterScriptDto | undefined} * */ -const getUpsertCommentsScript = (_, ddlProvider) => (container) => { +const getUpsertCommentsScriptDto = (_, ddlProvider) => (container) => { const {wrapComment, wrapInQuotes} = require('../../general')({_}); const description = extractDescription(container); if (description.new && description.new !== description.old) { const wrappedComment = wrapComment(description.new); const wrappedSchemaName = wrapInQuotes(container.role.name); - return ddlProvider.updateSchemaComment(wrappedSchemaName, wrappedComment); + const script = ddlProvider.updateSchemaComment(wrappedSchemaName, wrappedComment); + return AlterScriptDto.getInstance([script], true, false); } - return ''; + return undefined; } /** - * @return (container: Object) => string + * @return {(collection: Object) => AlterScriptDto | undefined} * */ -const getDropCommentsScript = (_, ddlProvider) => (container) => { +const getDropCommentsScriptDto = (_, ddlProvider) => (container) => { const {wrapInQuotes} = require('../../general')({_}); const description = extractDescription(container); if (description.old && !description.new) { const wrappedSchemaName = wrapInQuotes(container.role.name); - return ddlProvider.dropSchemaComment(wrappedSchemaName); + const script = ddlProvider.dropSchemaComment(wrappedSchemaName); + return AlterScriptDto.getInstance([script], true, true); } - return ''; + return undefined; } /** - * @return (container: Object) => Array + * @return {(collection: Object) => AlterScriptDto[]} * */ -const getModifySchemaCommentsScripts = (_, ddlProvider) => (container) => { - const upsertCommentScript = getUpsertCommentsScript(_, ddlProvider)(container); - const dropCommentScript = getDropCommentsScript(_, ddlProvider)(container); +const getModifySchemaCommentsScriptDtos = (_, ddlProvider) => (container) => { + const upsertCommentScript = getUpsertCommentsScriptDto(_, ddlProvider)(container); + const dropCommentScript = getDropCommentsScriptDto(_, ddlProvider)(container); return [ upsertCommentScript, dropCommentScript @@ -45,5 +48,5 @@ const getModifySchemaCommentsScripts = (_, ddlProvider) => (container) => { } module.exports = { - getModifySchemaCommentsScripts + getModifySchemaCommentsScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js b/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js index 9bc59e3..76d29fd 100644 --- a/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js @@ -25,8 +25,17 @@ const getFullViewName = (_) => (view) => { return getNamePrefixedWithSchemaName(viewName, schemaName); } +/** + * @param udt {Object} + * @return {string} + * */ +const getUdtName = (udt) => { + return udt.code || udt.name; +} + module.exports = { getFullTableName, getFullColumnName, getFullViewName, + getUdtName, } diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index 9730c3e..e26d83b 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js @@ -13,6 +13,7 @@ const {getFullTableName} = require("../ddlHelper"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(collection: Object) => Array} @@ -38,9 +39,9 @@ const mapCheckConstraintNamesToChangeHistory = (_) => (collection) => { } /** - * @return {(constraintHistory: Array, fullTableName: string) => Array} + * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ -const getDropCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, fullTableName) => { +const getDropCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { const {wrapInQuotes} = require('../../general')({_}); return constraintHistory @@ -48,13 +49,14 @@ const getDropCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, fu .map(historyEntry => { const wrappedConstraintName = wrapInQuotes(historyEntry.old.chkConstrName); return ddlProvider.dropConstraint(fullTableName, wrappedConstraintName); - }); + }) + .map(script => AlterScriptDto.getInstance([script], true, true)); } /** - * @return {(constraintHistory: Array, fullTableName: string) => Array} + * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ -const getAddCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, fullTableName) => { +const getAddCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { const {wrapInQuotes} = require('../../general')({_}); return constraintHistory @@ -62,13 +64,14 @@ const getAddCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, ful .map(historyEntry => { const { chkConstrName, constrExpression } = historyEntry.new; return ddlProvider.addCheckConstraint(fullTableName, wrapInQuotes(chkConstrName), constrExpression); - }); + }) + .map(script => AlterScriptDto.getInstance([script], true, false)); } /** - * @return {(constraintHistory: Array, fullTableName: string) => Array} + * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ -const getUpdateCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, fullTableName) => { +const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { const {wrapInQuotes} = require('../../general')({_}); return constraintHistory @@ -87,21 +90,24 @@ const getUpdateCheckConstraintScripts = (_, ddlProvider) => (constraintHistory, const { chkConstrName: newConstrainName, constrExpression: newConstraintExpression } = historyEntry.new; const addConstraintScript = ddlProvider.addCheckConstraint(fullTableName, wrapInQuotes(newConstrainName), newConstraintExpression); - return [dropConstraintScript, addConstraintScript]; + return [ + AlterScriptDto.getInstance([dropConstraintScript], true, true), + AlterScriptDto.getInstance([addConstraintScript], true, false), + ]; }) .flat(); } /** - * @return (collection: Object) => Array + * @return {(collection: Object) => Array} * */ -const getModifyCheckConstraintScripts = (_, ddlProvider) => (collection) => { +const getModifyCheckConstraintScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const constraintHistory = mapCheckConstraintNamesToChangeHistory(_)(collection); - const addCheckConstraintScripts = getAddCheckConstraintScripts(_, ddlProvider)(constraintHistory, fullTableName); - const dropCheckConstraintScripts = getDropCheckConstraintScripts(_, ddlProvider)(constraintHistory, fullTableName); - const updateCheckConstraintScripts = getUpdateCheckConstraintScripts(_, ddlProvider)(constraintHistory, fullTableName); + const addCheckConstraintScripts = getAddCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); + const dropCheckConstraintScripts = getDropCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); + const updateCheckConstraintScripts = getUpdateCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); return [ ...addCheckConstraintScripts, @@ -111,5 +117,5 @@ const getModifyCheckConstraintScripts = (_, ddlProvider) => (collection) => { } module.exports = { - getModifyCheckConstraintScripts + getModifyCheckConstraintScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js index d2b067c..97af66d 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -1,52 +1,55 @@ const {getFullTableName} = require("../ddlHelper"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** - * @return (collection: Object) => string + * @return {(collection: Object) => AlterScriptDto} */ -const getUpdatedCommentOnCollectionScript = (_, ddlProvider) => (collection) => { +const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { const {wrapComment} = require('../../general')({_}); const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { - return ''; + return undefined; } const {old: oldComment, new: newComment} = descriptionInfo; if (!newComment || newComment === oldComment) { - return ''; + return undefined; } const tableName = getFullTableName(_)(collection); const comment = wrapComment(newComment); - return ddlProvider.updateTableComment(tableName, comment); + const script = ddlProvider.updateTableComment(tableName, comment); + return AlterScriptDto.getInstance([script], true, false); } /** - * @return (collection: Object) => string + * @return {(collection: Object) => AlterScriptDto} */ -const getDeletedCommentOnCollectionScript = (_, ddlProvider) => (collection) => { +const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { - return ''; + return undefined; } const {old: oldComment, new: newComment} = descriptionInfo; if (!oldComment || newComment) { - return ''; + return undefined; } const tableName = getFullTableName(_)(collection); - return ddlProvider.dropTableComment(tableName); + const script = ddlProvider.dropTableComment(tableName); + return AlterScriptDto.getInstance([script], true, true); } /** - * @return {(collection: Object) => Array} + * @return {(collection: Object) => Array} * */ -const getModifyEntityCommentsScripts = (_, ddlProvider) => collection => { - const updatedCommentScript = getUpdatedCommentOnCollectionScript(_, ddlProvider)(collection); - const deletedCommentScript = getDeletedCommentOnCollectionScript(_, ddlProvider)(collection); +const getModifyEntityCommentsScriptDtos = (_, ddlProvider) => collection => { + const updatedCommentScript = getUpdatedCommentOnCollectionScriptDto(_, ddlProvider)(collection); + const deletedCommentScript = getDeletedCommentOnCollectionScriptDto(_, ddlProvider)(collection); return [ updatedCommentScript, @@ -55,5 +58,5 @@ const getModifyEntityCommentsScripts = (_, ddlProvider) => collection => { }; module.exports = { - getModifyEntityCommentsScripts + getModifyEntityCommentsScriptDtos } diff --git a/forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js b/forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js new file mode 100644 index 0000000..fb0c973 --- /dev/null +++ b/forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js @@ -0,0 +1,67 @@ +class ModificationScript { + /** + * @type string + * */ + script + + /** + * @type boolean + * */ + isDropScript +} + +class AlterScriptDto { + /** + * @type {boolean | undefined} + * */ + isActivated + + /** + * @type {Array} + * */ + scripts + + /** + * @param scripts {Array} + * @param isActivated {boolean} + * @param isDropScripts {boolean} + * @return {Array} + * */ + static getInstances(scripts, isActivated, isDropScripts) { + return (scripts || []) + .filter(Boolean) + .map(script => ({ + isActivated, + scripts: [{ + isDropScript: isDropScripts, + script + }] + })); + } + + /** + * @param scripts {Array} + * @param isActivated {boolean} + * @param isDropScripts {boolean} + * @return {AlterScriptDto | undefined} + * */ + static getInstance(scripts, isActivated, isDropScripts) { + if (!scripts?.filter(Boolean)?.length) { + return undefined; + } + return { + isActivated, + scripts: scripts + .filter(Boolean) + .map(script => ({ + isDropScript: isDropScripts, + script, + })) + } + } +} + +module.exports = { + ModificationScript, + AlterScriptDto, +} diff --git a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js index 6043495..b1118f1 100644 --- a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js @@ -1,42 +1,45 @@ const {getFullViewName} = require("../ddlHelper"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); const extractDescription = (view) => { return view?.role?.compMod?.description || {}; } /** - * @return (view: Object) => string + * @return {(view: Object) => AlterScriptDto | undefined} * */ -const getUpsertCommentsScript = (_, ddlProvider) => (view) => { +const getUpsertCommentsScriptDto = (_, ddlProvider) => (view) => { const {wrapComment} = require('../../general')({_}); const description = extractDescription(view); if (description.new && description.new !== description.old) { const wrappedComment = wrapComment(description.new); const viewName = getFullViewName(_)(view); - return ddlProvider.updateViewComment(viewName, wrappedComment); + const script = ddlProvider.updateViewComment(viewName, wrappedComment); + return AlterScriptDto.getInstance([script], true, false); } - return ''; + return undefined; } /** - * @return (view: Object) => string + * @return {(view: Object) => AlterScriptDto | undefined} * */ -const getDropCommentsScript = (_, ddlProvider) => (view) => { +const getDropCommentsScriptDto = (_, ddlProvider) => (view) => { const description = extractDescription(view); if (description.old && !description.new) { const viewName = getFullViewName(_)(view); - return ddlProvider.dropViewComment(viewName); + const script = ddlProvider.dropViewComment(viewName); + return AlterScriptDto.getInstance([script], true, true); } - return ''; + return undefined; } /** - * @return (view: Object) => Array + * @return {(view: Object) => AlterScriptDto[]} * */ -const getModifyViewCommentsScripts = (_, ddlProvider) => (view) => { - const upsertCommentScript = getUpsertCommentsScript(_, ddlProvider)(view); - const dropCommentScript = getDropCommentsScript(_, ddlProvider)(view); +const getModifyViewCommentsScriptDtos = (_, ddlProvider) => (view) => { + const upsertCommentScript = getUpsertCommentsScriptDto(_, ddlProvider)(view); + const dropCommentScript = getDropCommentsScriptDto(_, ddlProvider)(view); return [ upsertCommentScript, dropCommentScript @@ -44,5 +47,5 @@ const getModifyViewCommentsScripts = (_, ddlProvider) => (view) => { } module.exports = { - getModifyViewCommentsScripts + getModifyViewCommentsScriptDtos } diff --git a/forward_engineering/types/coreApplicationDataTypes.js b/forward_engineering/types/coreApplicationDataTypes.js new file mode 100644 index 0000000..9f248bd --- /dev/null +++ b/forward_engineering/types/coreApplicationDataTypes.js @@ -0,0 +1,215 @@ + +class ContainerJsonSchema { + /** + * @type {string} + */ + name + + /** + * @type {boolean} + */ + isActivated +} + +class ContainerStyles { + /** + * @type {Object} + * */ + backgroundColor +} + +class EntityData { + + /** + * @type {string | undefined} + */ + collectionName + + /** + * @type {boolean | undefined} + */ + isActivated + + /** + * @type {string | undefined} + */ + bucketId + + /** + * @type {any | undefined} + */ + additionalProperties + + /** + * @type {boolean | undefined} + */ + tableIfNotExists +} + +class InternalDefinitions { + + /** + * @type {string} + */ + $schema + + /** + * @type {"definitions"} + */ + type + + /** + * @type {string} + */ + GUID +} + +class ModelDefinitions { + + /** + * @type {string} + */ + $schema + + /** + * @type {"definitions"} + */ + type + + /** + * @type {string} + */ + GUID +} + +class ExternalDefinitions { + + /** + * @type {string} + */ + $schema + + /** + * @type {"externalDefinitions"} + */ + type + + /** + * @type {string} + */ + GUID +} + +class FieldJsonSchema { + + /** + * @type {string} + */ + type + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {string} + */ + mode + + /** + * @type {string} + */ + subtype + + /** + * @type {[ + * "compositePartitionKey", + * "compositeClusteringKey", + * "compositePrimaryKey", + * "compositeUniqueKey", + * ]} + */ + compositeKey + + /** + * @type {boolean} + */ + compositePartitionKey + + /** + * @type {boolean} + */ + compositeClusteringKey + + /** + * @type {boolean} + */ + compositePrimaryKey + + /** + * @type {boolean} + */ + compositeUniqueKey + + /** + * @type {string} + */ + GUID +} + +class EntityJsonSchema { + + /** + * @type {string} + */ + $schema + + /** + * @type {"object"} + */ + type + + /** + * @type {string} + */ + title + + /** + * @type {{ + * [fieldName: string]: FieldJsonSchema + * }} + */ + properties + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {boolean} + */ + additionalProperties + + /** + * @type {boolean} + */ + tableIfNotExists + + /** + * @type {string} + */ + GUID +} + +module.exports = { + ContainerJsonSchema, + ContainerStyles, + EntityData, + InternalDefinitions, + ModelDefinitions, + ExternalDefinitions, + FieldJsonSchema, + EntityJsonSchema, +} diff --git a/forward_engineering/types/coreApplicationTypes.js b/forward_engineering/types/coreApplicationTypes.js new file mode 100644 index 0000000..d5a0b8a --- /dev/null +++ b/forward_engineering/types/coreApplicationTypes.js @@ -0,0 +1,158 @@ +class PluginError { + /** + * @type string + */ + message + + /** + * @type {string | undefined} + */ + stack +} + +class App { + + /** + * @type {(library: string) => any} + * */ + require +} + +class Logger { + + /** + * @type {(level: string, additionalInfoDto: Object, message: string, hiddenKeys?: any) => void} + * */ + log + + /** + * @type {() => void} + * */ + clear +} + +class CoreData { + /** + * @type {string} + */ + jsonSchema + + /** + * @type {string} + */ + modelDefinitions + + /** + * @type {string} + */ + internalDefinitions + + /** + * @type {string} + */ + externalDefinitions + + /** + * @type {any} + */ + containerData + + /** + * @type {any} + */ + entityData + + /** + * @type {any} + */ + entities + + /** + * @type {Array} + */ + views + + /** + * @type {Object | undefined} + */ + viewData + + /** + * @type {Array} + */ + relationships + + /** + * @type {Object | undefined} + */ + collectionRefsDefinitionsMap + + /** + * @type {boolean} + */ + isUpdateScript + + /** + * @type {'container' | 'entity'} + */ + level + + /** + * @type {string | undefined} + */ + host + + /** + * @type {string | undefined} + */ + clusterId + + /** + * @type {string | undefined} + */ + accessToken + + /** + * @type {string | number | undefined} + */ + applyToInstanceQueryRequestTimeout + + /** + * @type {string | undefined} + */ + script + + /** + * @type {any | undefined} + */ + hiddenKeys + + /** + * @type {Array<{ + * id: string, + * value: any, + * }> | {separateBucket: boolean}} + */ + options + + /** + * @type {[ + * { + * modelName: string, + * dbVendor: string, + * dbVersion: string, + * isLineageEnabled: boolean + * }, + * { relationships: [] }, + * { sources: [] } + * ]} + * */ + modelData +} + +module.exports = { + App, + CoreData, + Logger, + PluginError, +} From b91417f144ca9bd2eb3f0b0b7dbdf999fe91af9f Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 29 May 2023 17:37:24 +0300 Subject: [PATCH 02/22] Deleted common.js file --- forward_engineering/ddlProvider.js | 3 +-- forward_engineering/{configs => ddlProvider}/templates.js | 0 .../helpers/alterScriptHelpers/alterUdtHelper.js | 2 +- .../alterScriptHelpers/columnHelpers/alterTypeHelper.js | 2 +- .../alterScriptHelpers/columnHelpers/renameColumnHelper.js | 2 +- forward_engineering/helpers/alterScriptHelpers/common.js | 7 ------- forward_engineering/utils/general.js | 5 +++++ 7 files changed, 9 insertions(+), 12 deletions(-) rename forward_engineering/{configs => ddlProvider}/templates.js (100%) delete mode 100644 forward_engineering/helpers/alterScriptHelpers/common.js diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index 47e177e..c3da851 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -1,7 +1,6 @@ const defaultTypes = require('./configs/defaultTypes'); const types = require('./configs/types'); -const templates = require('./configs/templates'); -const assignTemplates = require("./utils/assignTemplates"); +const templates = require('./ddlProvider/templates'); module.exports = (baseProvider, options, app) => { const _ = app.require('lodash'); diff --git a/forward_engineering/configs/templates.js b/forward_engineering/ddlProvider/templates.js similarity index 100% rename from forward_engineering/configs/templates.js rename to forward_engineering/ddlProvider/templates.js diff --git a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js index 476c730..ecddeb3 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js @@ -1,4 +1,3 @@ -const {checkFieldPropertiesChanged} = require('./common'); const {AlterScriptDto} = require("./types/AlterScriptDto"); const {getUdtName} = require("./ddlHelper"); @@ -132,6 +131,7 @@ const getModifyColumnOfTypeScriptDto = app => udt => { const ddlProvider = require('../../ddlProvider')(null, null, app); const {wrapInQuotes} = require('../general')({_}); + const {checkFieldPropertiesChanged} = require('../../utils/general')(_); const fullName = wrapInQuotes(udt.code || udt.name); diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js index d33bb2c..5c17484 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -1,5 +1,4 @@ const {getFullTableName} = require("../ddlHelper"); -const {checkFieldPropertiesChanged} = require("../common"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -33,6 +32,7 @@ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) const getUpdateTypesScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const {wrapInQuotes} = require('../../general')({_}); + const {checkFieldPropertiesChanged} = require('../../../utils/general')(_); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js index b2a567d..7a11fc9 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -1,5 +1,4 @@ const {getFullTableName} = require("../ddlHelper"); -const {checkFieldPropertiesChanged} = require("../common"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -8,6 +7,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); const getRenameColumnScriptDtos = (_, ddlProvider) => (collection) => { const fullTableName = getFullTableName(_)(collection); const {wrapInQuotes} = require('../../general')({_}); + const {checkFieldPropertiesChanged} = require('../../../utils/general')(_); return _.values(collection.properties) .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) diff --git a/forward_engineering/helpers/alterScriptHelpers/common.js b/forward_engineering/helpers/alterScriptHelpers/common.js deleted file mode 100644 index 64ae513..0000000 --- a/forward_engineering/helpers/alterScriptHelpers/common.js +++ /dev/null @@ -1,7 +0,0 @@ -const checkFieldPropertiesChanged = (compMod, propertiesToCheck) => { - return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); -}; - -module.exports = { - checkFieldPropertiesChanged, -}; diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index 5432b00..d298ef6 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -129,6 +129,10 @@ module.exports = _ => { } }; + const checkFieldPropertiesChanged = (compMod, propertiesToCheck) => { + return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); + }; + return { getDbName, getDbData, @@ -145,5 +149,6 @@ module.exports = _ => { divideIntoActivatedAndDeactivated, commentIfDeactivated, wrap, + checkFieldPropertiesChanged, }; }; From 6465e3ebd1c4b7799501b485064c592cb831308e Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 29 May 2023 18:09:01 +0300 Subject: [PATCH 03/22] Deleted DDL helper --- forward_engineering/enums/reservedWords.js | 103 +++++++++++++++++ .../alterScriptHelpers/alterEntityHelper.js | 5 +- .../alterScriptHelpers/alterUdtHelper.js | 3 +- .../columnHelpers/alterTypeHelper.js | 5 +- .../columnHelpers/commentsHelper.js | 8 +- .../columnHelpers/nonNullConstraintHelper.js | 4 +- .../columnHelpers/renameColumnHelper.js | 5 +- .../helpers/alterScriptHelpers/ddlHelper.js | 41 ------- .../entityHelpers/checkConstraintHelper.js | 4 +- .../entityHelpers/commentsHelper.js | 8 +- .../viewHelpers/commentsHelper.js | 8 +- forward_engineering/helpers/general.js | 105 +----------------- forward_engineering/utils/general.js | 81 ++++++-------- 13 files changed, 172 insertions(+), 208 deletions(-) create mode 100644 forward_engineering/enums/reservedWords.js delete mode 100644 forward_engineering/helpers/alterScriptHelpers/ddlHelper.js diff --git a/forward_engineering/enums/reservedWords.js b/forward_engineering/enums/reservedWords.js new file mode 100644 index 0000000..f1ee24f --- /dev/null +++ b/forward_engineering/enums/reservedWords.js @@ -0,0 +1,103 @@ +const ReservedWords = Object.freeze({ + ALL: 'ALL', + ANALYSE: 'ANALYSE', + ANALYZE: 'ANALYZE', + AND: 'AND', + ANY: 'ANY', + ARRAY: 'ARRAY', + ASC: 'ASC', + ASYMMETRIC: 'ASYMMETRIC', + AUTHORIZATION: 'AUTHORIZATION', + BINARY: 'BINARY', + BOTH: 'BOTH', + CASE: 'CASE', + CAST: 'CAST', + CHECK: 'CHECK', + COLLATE: 'COLLATE', + COLUMN: 'COLUMN', + CONCURRENTLY: 'CONCURRENTLY', + CONSTRAINT: 'CONSTRAINT', + CREATE: 'CREATE', + CROSS: 'CROSS', + CURRENT_CATALOG: 'CURRENT_CATALOG', + CURRENT_DATE: 'CURRENT_DATE', + CURRENT_ROLE: 'CURRENT_ROLE', + CURRENT_SCHEMA: 'CURRENT_SCHEMA', + CURRENT_TIME: 'CURRENT_TIME', + CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP', + CURRENT_USER: 'CURRENT_USER', + DEFAULT: 'DEFAULT', + DEFERRABLE: 'DEFERRABLE', + DESC: 'DESC', + DISTINCT: 'DISTINCT', + DO: 'DO', + ELSE: 'ELSE', + END: 'END', + EXCEPT: 'EXCEPT', + FALSE: 'FALSE', + FOR: 'FOR', + FOREIGN: 'FOREIGN', + FREEZE: 'FREEZE', + FROM: 'FROM', + FULL: 'FULL', + GRANT: 'GRANT', + GROUP: 'GROUP', + HAVING: 'HAVING', + ILIKE: 'ILIKE', + IN: 'IN', + INITIALLY: 'INITIALLY', + INTERSECT: 'INTERSECT', + INTO: 'INTO', + IS: 'IS', + ISNULL: 'ISNULL', + JOIN: 'JOIN', + LATERAL: 'LATERAL', + LEADING: 'LEADING', + LEFT: 'LEFT', + LIKE: 'LIKE', + LIMIT: 'LIMIT', + LOCALTIME: 'LOCALTIME', + LOCALTIMESTAMP: 'LOCALTIMESTAMP', + NATURAL: 'NATURAL', + NOT: 'NOT', + NULL: 'NULL', + OFFSET: 'OFFSET', + ON: 'ON', + ONLY: 'ONLY', + OR: 'OR', + ORDER: 'ORDER', + OUTER: 'OUTER', + OVERLAPS: 'OVERLAPS', + PLACING: 'PLACING', + PRIMARY: 'PRIMARY', + REFERENCES: 'REFERENCES', + RETURNING: 'RETURNING', + RIGHT: 'RIGHT', + SELECT: 'SELECT', + SESSION_USER: 'SESSION_USER', + SIMILAR: 'SIMILAR', + SOME: 'SOME', + SYMMETRIC: 'SYMMETRIC', + TABLE: 'TABLE', + TABLESAMPLE: 'TABLESAMPLE', + THEN: 'THEN', + TO: 'TO', + TRAILING: 'TRAILING', + TRUE: 'TRUE', + UNION: 'UNION', + UNIQUE: 'UNIQUE', + USER: 'USER', + USING: 'USING', + VARIADIC: 'VARIADIC', + VERBOSE: 'VERBOSE', + WHEN: 'WHEN', + WHERE: 'WHERE', + WINDOW: 'WINDOW', + WITH: 'WITH', +}); + +const ReservedWordsAsArray = Object.values(ReservedWords); + +module.exports = { + ReservedWordsAsArray +} diff --git a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js index 8e3d644..1687e9f 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js @@ -1,5 +1,4 @@ const {getModifyCheckConstraintScriptDtos} = require("./entityHelpers/checkConstraintHelper"); -const {getFullTableName} = require("./ddlHelper"); const {getModifyEntityCommentsScriptDtos} = require("./entityHelpers/commentsHelper"); const {getUpdateTypesScriptDtos} = require("./columnHelpers/alterTypeHelper"); const {getModifyNonNullColumnsScriptDtos} = require("./columnHelpers/nonNullConstraintHelper"); @@ -64,7 +63,9 @@ const getAddCollectionScriptDto = const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const fullName = getFullTableName(_)(collection); + const {getFullTableName} = require('../../utils/general')(_); + + const fullName = getFullTableName(collection); const script = ddlProvider.dropTable(fullName); return AlterScriptDto.getInstance([script], true, true); }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js index ecddeb3..28e2bde 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js @@ -1,5 +1,4 @@ const {AlterScriptDto} = require("./types/AlterScriptDto"); -const {getUdtName} = require("./ddlHelper"); /** * @return {(jsonSchema: Object) => AlterScriptDto} @@ -56,6 +55,7 @@ const getDeleteUdtScriptDto = app => udt => { const ddlProvider = require('../../ddlProvider')(null, null, app); const {wrapInQuotes} = require('../general')({_}); + const {getUdtName} = require('../../utils/general')(_); const ddlUdtName = wrapInQuotes(getUdtName(udt)); if (udt.type === 'domain') { @@ -76,6 +76,7 @@ const getAddColumnToTypeScriptDtos = const _ = app.require('lodash'); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); const {wrapInQuotes} = require('../general')({_}); + const {getUdtName} = require('../../utils/general')(_); const ddlProvider = require('../../ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js index 5c17484..585babd 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -1,4 +1,3 @@ -const {getFullTableName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -30,9 +29,9 @@ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) * @return {(collection: Object) => AlterScriptDto[]} * */ const getUpdateTypesScriptDtos = (_, ddlProvider) => (collection) => { - const fullTableName = getFullTableName(_)(collection); + const {checkFieldPropertiesChanged, getFullTableName} = require('../../../utils/general')(_); + const fullTableName = getFullTableName(collection); const {wrapInQuotes} = require('../../general')({_}); - const {checkFieldPropertiesChanged} = require('../../../utils/general')(_); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js index 237c8a1..c7b9e9b 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js @@ -1,4 +1,3 @@ -const {getFullColumnName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -6,6 +5,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); * */ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { const {wrapComment} = require('../../general')({_}); + const {getFullColumnName} = require('../../../utils/general')(_); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const newComment = jsonSchema.description; @@ -16,7 +16,7 @@ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => .map(([name, jsonSchema]) => { const newComment = jsonSchema.description; const ddlComment = wrapComment(newComment); - const columnName = getFullColumnName(_)(collection, name); + const columnName = getFullColumnName(collection, name); return ddlProvider.updateColumnComment(columnName, ddlComment); }) .map(script => AlterScriptDto.getInstance([script], true, false)); @@ -26,6 +26,8 @@ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => * @return {(collection: Object) => AlterScriptDto[]} * */ const getDeletedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { + const {getFullColumnName} = require('../../../utils/general')(_); + return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const newComment = jsonSchema.description; @@ -34,7 +36,7 @@ const getDeletedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => return oldComment && !newComment; }) .map(([name, jsonSchema]) => { - const columnName = getFullColumnName(_)(collection, name); + const columnName = getFullColumnName(collection, name); return ddlProvider.dropColumnComment(columnName); }) .map(script => AlterScriptDto.getInstance([script], true, true)); diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js index 665ffed..b9ae3a7 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js @@ -1,11 +1,11 @@ -const {getFullTableName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto[]} * */ const getModifyNonNullColumnsScriptDtos = (_, ddlProvider) => (collection) => { - const fullTableName = getFullTableName(_)(collection); + const {getFullTableName} = require('../../../utils/general')(_); + const fullTableName = getFullTableName(collection); const {wrapInQuotes} = require('../../general')({_}); const currentRequiredColumnNames = collection.required || []; diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js index 7a11fc9..3ec71ce 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -1,13 +1,12 @@ -const {getFullTableName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto[]} * */ const getRenameColumnScriptDtos = (_, ddlProvider) => (collection) => { - const fullTableName = getFullTableName(_)(collection); + const {checkFieldPropertiesChanged, getFullTableName} = require('../../../utils/general')(_); + const fullTableName = getFullTableName(collection); const {wrapInQuotes} = require('../../general')({_}); - const {checkFieldPropertiesChanged} = require('../../../utils/general')(_); return _.values(collection.properties) .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) diff --git a/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js b/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js deleted file mode 100644 index 76d29fd..0000000 --- a/forward_engineering/helpers/alterScriptHelpers/ddlHelper.js +++ /dev/null @@ -1,41 +0,0 @@ -const getFullTableName = (_) => (collection) => { - const {getEntityName} = require('../../utils/general')(_); - const {getNamePrefixedWithSchemaName} = require('../general')({_}); - - const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - const tableName = getEntityName(collectionSchema); - const schemaName = collectionSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(tableName, schemaName); -} - -const getFullColumnName = (_) => (collection, columnName) => { - const {wrapInQuotes} = require('../general')({_}); - - const fullTableName = getFullTableName(_)(collection); - return `${fullTableName}.${wrapInQuotes(columnName)}`; -} - -const getFullViewName = (_) => (view) => { - const {getViewName} = require('../../utils/general')(_); - const {getNamePrefixedWithSchemaName} = require('../general')({_}); - - const viewSchema = {...view, ...(_.omit(view?.role, 'properties') || {})}; - const viewName = getViewName(viewSchema); - const schemaName = viewSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(viewName, schemaName); -} - -/** - * @param udt {Object} - * @return {string} - * */ -const getUdtName = (udt) => { - return udt.code || udt.name; -} - -module.exports = { - getFullTableName, - getFullColumnName, - getFullViewName, - getUdtName, -} diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index e26d83b..2d1c960 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js @@ -12,7 +12,6 @@ * */ -const {getFullTableName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -102,7 +101,8 @@ const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistor * @return {(collection: Object) => Array} * */ const getModifyCheckConstraintScriptDtos = (_, ddlProvider) => (collection) => { - const fullTableName = getFullTableName(_)(collection); + const {getFullTableName} = require('../../../utils/general')(_); + const fullTableName = getFullTableName(collection); const constraintHistory = mapCheckConstraintNamesToChangeHistory(_)(collection); const addCheckConstraintScripts = getAddCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js index 97af66d..ba65137 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -1,10 +1,10 @@ -const {getFullTableName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto} */ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { + const {getFullTableName} = require('../../../utils/general')(_); const {wrapComment} = require('../../general')({_}); const descriptionInfo = collection?.role.compMod?.description; @@ -17,7 +17,7 @@ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) return undefined; } - const tableName = getFullTableName(_)(collection); + const tableName = getFullTableName(collection); const comment = wrapComment(newComment); const script = ddlProvider.updateTableComment(tableName, comment); @@ -28,6 +28,8 @@ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) * @return {(collection: Object) => AlterScriptDto} */ const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { + const {getFullTableName} = require('../../../utils/general')(_); + const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { return undefined; @@ -38,7 +40,7 @@ const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) return undefined; } - const tableName = getFullTableName(_)(collection); + const tableName = getFullTableName(collection); const script = ddlProvider.dropTableComment(tableName); return AlterScriptDto.getInstance([script], true, true); diff --git a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js index b1118f1..69fd48d 100644 --- a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js @@ -1,4 +1,3 @@ -const {getFullViewName} = require("../ddlHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); const extractDescription = (view) => { @@ -10,11 +9,12 @@ const extractDescription = (view) => { * */ const getUpsertCommentsScriptDto = (_, ddlProvider) => (view) => { const {wrapComment} = require('../../general')({_}); + const {getFullViewName} = require('../../../utils/general')(_); const description = extractDescription(view); if (description.new && description.new !== description.old) { const wrappedComment = wrapComment(description.new); - const viewName = getFullViewName(_)(view); + const viewName = getFullViewName(view); const script = ddlProvider.updateViewComment(viewName, wrappedComment); return AlterScriptDto.getInstance([script], true, false); } @@ -26,8 +26,10 @@ const getUpsertCommentsScriptDto = (_, ddlProvider) => (view) => { * */ const getDropCommentsScriptDto = (_, ddlProvider) => (view) => { const description = extractDescription(view); + const {getFullViewName} = require('../../../utils/general')(_); + if (description.old && !description.new) { - const viewName = getFullViewName(_)(view); + const viewName = getFullViewName(view); const script = ddlProvider.dropViewComment(viewName); return AlterScriptDto.getInstance([script], true, true); } diff --git a/forward_engineering/helpers/general.js b/forward_engineering/helpers/general.js index d110fd1..43b674b 100644 --- a/forward_engineering/helpers/general.js +++ b/forward_engineering/helpers/general.js @@ -1,100 +1,4 @@ -const POSTGRES_RESERVED_WORDS = [ - 'ALL', - 'ANALYSE', - 'ANALYZE', - 'AND', - 'ANY', - 'ARRAY', - 'ASC', - 'ASYMMETRIC', - 'AUTHORIZATION', - 'BINARY', - 'BOTH', - 'CASE', - 'CAST', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONCURRENTLY', - 'CONSTRAINT', - 'CREATE', - 'CROSS', - 'CURRENT_CATALOG', - 'CURRENT_DATE', - 'CURRENT_ROLE', - 'CURRENT_SCHEMA', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'DEFAULT', - 'DEFERRABLE', - 'DESC', - 'DISTINCT', - 'DO', - 'ELSE', - 'END', - 'EXCEPT', - 'FALSE', - 'FOR', - 'FOREIGN', - 'FREEZE', - 'FROM', - 'FULL', - 'GRANT', - 'GROUP', - 'HAVING', - 'ILIKE', - 'IN', - 'INITIALLY', - 'INTERSECT', - 'INTO', - 'IS', - 'ISNULL', - 'JOIN', - 'LATERAL', - 'LEADING', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'NATURAL', - 'NOT', - 'NULL', - 'OFFSET', - 'ON', - 'ONLY', - 'OR', - 'ORDER', - 'OUTER', - 'OVERLAPS', - 'PLACING', - 'PRIMARY', - 'REFERENCES', - 'RETURNING', - 'RIGHT', - 'SELECT', - 'SESSION_USER', - 'SIMILAR', - 'SOME', - 'SYMMETRIC', - 'TABLE', - 'TABLESAMPLE', - 'THEN', - 'TO', - 'TRAILING', - 'TRUE', - 'UNION', - 'UNIQUE', - 'USER', - 'USING', - 'VARIADIC', - 'VERBOSE', - 'WHEN', - 'WHERE', - 'WINDOW', - 'WITH', -]; +const {ReservedWordsAsArray} = require("../enums/reservedWords"); const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; @@ -116,7 +20,7 @@ module.exports = ({ _, divideIntoActivatedAndDeactivated, commentIfDeactivated } }; const wrapInQuotes = name => - /\s|\W/.test(name) || _.includes(POSTGRES_RESERVED_WORDS, _.toUpper(name)) ? `"${name}"` : name; + /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)) ? `"${name}"` : name; const columnMapToString = ({ name }) => wrapInQuotes(name); @@ -179,9 +83,8 @@ module.exports = ({ _, divideIntoActivatedAndDeactivated, commentIfDeactivated } ); }; - const prepareComment = (comment = '') => - comment.replace(MUST_BE_ESCAPED, character => `${'\\'}${character}`); - + const prepareComment = (comment = '') => + comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index d298ef6..43dac1c 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -26,48 +26,6 @@ module.exports = _ => { const getViewOn = viewData => _.get(viewData, '[0].viewOn'); - const rejectRecursiveRelationships = foreignTableToRelationshipData => { - return Object.keys(foreignTableToRelationshipData).reduce((result, foreignTableId) => { - const tables = foreignTableToRelationshipData[foreignTableId].filter(item => { - const tables = foreignTableToRelationshipData[item.primaryTableId]; - - if (!Array.isArray(tables)) { - return true; - } - - return !tables.some( - item => item.primaryTableId === foreignTableId && item.primaryTableId !== item.foreignTableId, - ); - }); - - if (_.isEmpty(tables)) { - return result; - } - - return Object.assign({}, result, { - [foreignTableId]: tables, - }); - }, {}); - }; - - const filterRecursiveRelationships = foreignTableToRelationshipData => { - return Object.keys(foreignTableToRelationshipData).reduce((result, foreignTableId) => { - const tables = foreignTableToRelationshipData[foreignTableId].filter(item => { - const tables = foreignTableToRelationshipData[item.primaryTableId]; - - if (!Array.isArray(tables)) { - return false; - } - - return tables.some( - item => item.primaryTableId === foreignTableId && item.primaryTableId !== item.foreignTableId, - ); - }); - - return result.concat(tables); - }, []); - }; - const tab = (text, tab = '\t') => { return text .split('\n') @@ -133,14 +91,45 @@ module.exports = _ => { return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); }; + const getFullTableName = (collection) => { + const {getNamePrefixedWithSchemaName} = require('../helpers/general')({_}); + + const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; + const tableName = getEntityName(collectionSchema); + const schemaName = collectionSchema.compMod?.keyspaceName; + return getNamePrefixedWithSchemaName(tableName, schemaName); + } + + const getFullColumnName = (collection, columnName) => { + const {wrapInQuotes} = require('../helpers/general')({_}); + + const fullTableName = getFullTableName(collection); + return `${fullTableName}.${wrapInQuotes(columnName)}`; + } + + const getFullViewName = (view) => { + const {getNamePrefixedWithSchemaName} = require('../helpers/general')({_}); + + const viewSchema = {...view, ...(_.omit(view?.role, 'properties') || {})}; + const viewName = getViewName(viewSchema); + const schemaName = viewSchema.compMod?.keyspaceName; + return getNamePrefixedWithSchemaName(viewName, schemaName); + } + + /** + * @param udt {Object} + * @return {string} + * */ + const getUdtName = (udt) => { + return udt.code || udt.name; + } + return { getDbName, getDbData, getEntityName, getViewName, getViewOn, - rejectRecursiveRelationships, - filterRecursiveRelationships, tab, hasType, clean, @@ -150,5 +139,9 @@ module.exports = _ => { commentIfDeactivated, wrap, checkFieldPropertiesChanged, + getFullTableName, + getFullColumnName, + getFullViewName, + getUdtName, }; }; From 53bdfa62e3e60051e9ac3529838563dac0c77f8e Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 12:25:50 +0300 Subject: [PATCH 04/22] Deleted helpers/general --- forward_engineering/ddlProvider.js | 18 ++- .../alterContainerHelper.js | 4 +- .../alterScriptHelpers/alterEntityHelper.js | 6 +- .../alterScriptHelpers/alterUdtHelper.js | 11 +- .../alterScriptHelpers/alterViewHelper.js | 2 +- .../columnHelpers/alterTypeHelper.js | 3 +- .../columnHelpers/commentsHelper.js | 3 +- .../columnHelpers/nonNullConstraintHelper.js | 3 +- .../columnHelpers/renameColumnHelper.js | 3 +- .../containerHelpers/commentsHelper.js | 4 +- .../entityHelpers/checkConstraintHelper.js | 6 +- .../entityHelpers/commentsHelper.js | 3 +- .../viewHelpers/commentsHelper.js | 3 +- forward_engineering/helpers/general.js | 106 ----------------- forward_engineering/utils/general.js | 107 +++++++++++++++++- 15 files changed, 132 insertions(+), 150 deletions(-) delete mode 100644 forward_engineering/helpers/general.js diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index c3da851..7685f40 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -12,21 +12,15 @@ module.exports = (baseProvider, options, app) => { hasType, wrap, clean, - } = require('./utils/general')(_); - const assignTemplates = require('./utils/assignTemplates'); - const { + wrapComment, getFunctionArguments, wrapInQuotes, getNamePrefixedWithSchemaName, getColumnsList, getViewData, - wrapComment, - getDbVersion, - } = require('./helpers/general')({ - _, - divideIntoActivatedAndDeactivated, - commentIfDeactivated, - }); + } = require('./utils/general')(_); + const assignTemplates = require('./utils/assignTemplates'); + const { generateConstraintsString, foreignKeysToString, @@ -287,6 +281,7 @@ module.exports = (baseProvider, options, app) => { const ifNotExist = index.ifNotExist ? ' IF NOT EXISTS' : ''; const only = index.only ? ' ONLY' : ''; const using = index.index_method ? ` USING ${_.toUpper(index.index_method)}` : ''; + const { getDbVersion } = require('utils/general')(_); const dbVersion = getDbVersion(_.get(dbData, 'dbVersion', '')); const nullsDistinct = isUnique && index.nullsDistinct && dbVersion >= 15 ? `\n ${index.nullsDistinct}` : ''; @@ -448,6 +443,7 @@ module.exports = (baseProvider, options, app) => { : ''; const security_barrier = viewData.viewOptions?.security_barrier ? `security_barrier` : ''; const dbVersionWhereSecurityInvokerAppeared = 15; + const { getDbVersion } = require('utils/general')(_); const security_invoker = viewData.viewOptions?.security_invoker && getDbVersion(dbData.dbVersion) >= dbVersionWhereSecurityInvokerAppeared @@ -546,6 +542,7 @@ module.exports = (baseProvider, options, app) => { const timePrecision = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timePrecision : ''; const timezone = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timezone : ''; const intervalOptions = columnDefinition.type === 'interval' ? jsonSchema.intervalOptions : ''; + const { getDbVersion } = require('utils/general')(_); const dbVersion = getDbVersion(schemaData.dbVersion) const primaryKeyOptions = _.omit( keyHelper.hydratePrimaryKeyOptions( @@ -658,6 +655,7 @@ module.exports = (baseProvider, options, app) => { ? getNamePrefixedWithSchemaName(partitionParent.collectionName, partitionParent.bucketName) : ''; const triggers = hydrateTriggers(entityData, tableData.relatedSchemas); + const { getDbVersion } = require('utils/general')(_); const dbVersion = getDbVersion(_.get(tableData, 'dbData.dbVersion', '')); return { diff --git a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js index 05e9fd4..d3f2454 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js @@ -7,7 +7,7 @@ const {AlterScriptDto} = require("./types/AlterScriptDto"); const getAddContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../general')({_}); + const {wrapInQuotes} = require('../../utils/general')(_); const script = ddlProvider.createSchemaOnly(wrapInQuotes(containerName)); return AlterScriptDto.getInstance([script], true, false); }; @@ -18,7 +18,7 @@ const getAddContainerScriptDto = (app) => (containerName) => { const getDeleteContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../general')({_}); + const {wrapInQuotes} = require('../../utils/general')(_); const script = ddlProvider.dropSchema(wrapInQuotes(containerName)); return AlterScriptDto.getInstance([script], true, true); diff --git a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js index 1687e9f..948ae7a 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js @@ -92,8 +92,7 @@ const getAddColumnScriptDtos = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => collection => { const _ = app.require('lodash'); - const {getEntityName} = require('../../utils/general')(_); - const {getNamePrefixedWithSchemaName} = require('../general')({_}); + const {getEntityName, getNamePrefixedWithSchemaName} = require('../../utils/general')(_); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); const ddlProvider = require('../../ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); @@ -134,8 +133,7 @@ const getAddColumnScriptDtos = const getDeleteColumnScriptDtos = app => collection => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {getEntityName} = require('../../utils/general')(_); - const {getNamePrefixedWithSchemaName, wrapInQuotes} = require('../general')({_}); + const {getEntityName, getNamePrefixedWithSchemaName, wrapInQuotes} = require('../../utils/general')(_); const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; const tableName = getEntityName(collectionSchema); diff --git a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js index 28e2bde..dcc6fc1 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js @@ -54,8 +54,7 @@ const getDeleteUdtScriptDto = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../general')({_}); - const {getUdtName} = require('../../utils/general')(_); + const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); const ddlUdtName = wrapInQuotes(getUdtName(udt)); if (udt.type === 'domain') { @@ -75,8 +74,7 @@ const getAddColumnToTypeScriptDtos = udt => { const _ = app.require('lodash'); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const {wrapInQuotes} = require('../general')({_}); - const {getUdtName} = require('../../utils/general')(_); + const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); const ddlProvider = require('../../ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); @@ -114,7 +112,7 @@ const getDeleteColumnFromTypeScriptDtos = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../general')({_}); + const {wrapInQuotes} = require('../../utils/general')(_); const fullName = wrapInQuotes(udt.code || udt.name); @@ -131,8 +129,7 @@ const getModifyColumnOfTypeScriptDto = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../general')({_}); - const {checkFieldPropertiesChanged} = require('../../utils/general')(_); + const {checkFieldPropertiesChanged, wrapInQuotes} = require('../../utils/general')(_); const fullName = wrapInQuotes(udt.code || udt.name); diff --git a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js b/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js index a99cb3c..d02ddf4 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js @@ -24,7 +24,7 @@ const getAddViewScriptDto = app => view => { const getDeleteViewScriptDto = app => view => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../general')({ _ }); + const { wrapInQuotes } = require('../../utils/general')(_); const viewName = wrapInQuotes(view.code || view.name); const script = ddlProvider.dropView(viewName); diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js index 585babd..c8f3592 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -29,9 +29,8 @@ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) * @return {(collection: Object) => AlterScriptDto[]} * */ const getUpdateTypesScriptDtos = (_, ddlProvider) => (collection) => { - const {checkFieldPropertiesChanged, getFullTableName} = require('../../../utils/general')(_); + const {checkFieldPropertiesChanged, getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); const fullTableName = getFullTableName(collection); - const {wrapInQuotes} = require('../../general')({_}); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js index c7b9e9b..dfb8612 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js @@ -4,8 +4,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); * @return {(collection: Object) => AlterScriptDto[]} * */ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { - const {wrapComment} = require('../../general')({_}); - const {getFullColumnName} = require('../../../utils/general')(_); + const {getFullColumnName, wrapComment} = require('../../../utils/general')(_); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const newComment = jsonSchema.description; diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js index b9ae3a7..410c5e7 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js @@ -4,9 +4,8 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); * @return {(collection: Object) => AlterScriptDto[]} * */ const getModifyNonNullColumnsScriptDtos = (_, ddlProvider) => (collection) => { - const {getFullTableName} = require('../../../utils/general')(_); + const {getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); const fullTableName = getFullTableName(collection); - const {wrapInQuotes} = require('../../general')({_}); const currentRequiredColumnNames = collection.required || []; const previousRequiredColumnNames = collection.role.required || []; diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js index 3ec71ce..e64a763 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -4,9 +4,8 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); * @return {(collection: Object) => AlterScriptDto[]} * */ const getRenameColumnScriptDtos = (_, ddlProvider) => (collection) => { - const {checkFieldPropertiesChanged, getFullTableName} = require('../../../utils/general')(_); + const {checkFieldPropertiesChanged, getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); const fullTableName = getFullTableName(collection); - const {wrapInQuotes} = require('../../general')({_}); return _.values(collection.properties) .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) diff --git a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js index 82d2970..9aad2e0 100644 --- a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js @@ -8,7 +8,7 @@ const extractDescription = (container) => { * @return {(collection: Object) => AlterScriptDto | undefined} * */ const getUpsertCommentsScriptDto = (_, ddlProvider) => (container) => { - const {wrapComment, wrapInQuotes} = require('../../general')({_}); + const {wrapComment, wrapInQuotes} = require('../../../utils/general')(_); const description = extractDescription(container); if (description.new && description.new !== description.old) { @@ -24,7 +24,7 @@ const getUpsertCommentsScriptDto = (_, ddlProvider) => (container) => { * @return {(collection: Object) => AlterScriptDto | undefined} * */ const getDropCommentsScriptDto = (_, ddlProvider) => (container) => { - const {wrapInQuotes} = require('../../general')({_}); + const {wrapInQuotes} = require('../../../utils/general')(_); const description = extractDescription(container); if (description.old && !description.new) { diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index 2d1c960..135d02f 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js @@ -41,7 +41,7 @@ const mapCheckConstraintNamesToChangeHistory = (_) => (collection) => { * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ const getDropCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../general')({_}); + const {wrapInQuotes} = require('../../../utils/general')(_); return constraintHistory .filter(historyEntry => historyEntry.old && !historyEntry.new) @@ -56,7 +56,7 @@ const getDropCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ const getAddCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../general')({_}); + const {wrapInQuotes} = require('../../../utils/general')(_); return constraintHistory .filter(historyEntry => historyEntry.new && !historyEntry.old) @@ -71,7 +71,7 @@ const getAddCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, * @return {(constraintHistory: Array, fullTableName: string) => Array} * */ const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../general')({_}); + const {wrapInQuotes} = require('../../../utils/general')(_); return constraintHistory .filter(historyEntry => { diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js index ba65137..b8c8a21 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -4,8 +4,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); * @return {(collection: Object) => AlterScriptDto} */ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { - const {getFullTableName} = require('../../../utils/general')(_); - const {wrapComment} = require('../../general')({_}); + const {getFullTableName, wrapComment} = require('../../../utils/general')(_); const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { diff --git a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js index 69fd48d..9380ce1 100644 --- a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js +++ b/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js @@ -8,8 +8,7 @@ const extractDescription = (view) => { * @return {(view: Object) => AlterScriptDto | undefined} * */ const getUpsertCommentsScriptDto = (_, ddlProvider) => (view) => { - const {wrapComment} = require('../../general')({_}); - const {getFullViewName} = require('../../../utils/general')(_); + const {getFullViewName, wrapComment} = require('../../../utils/general')(_); const description = extractDescription(view); if (description.new && description.new !== description.old) { diff --git a/forward_engineering/helpers/general.js b/forward_engineering/helpers/general.js deleted file mode 100644 index 43b674b..0000000 --- a/forward_engineering/helpers/general.js +++ /dev/null @@ -1,106 +0,0 @@ -const {ReservedWordsAsArray} = require("../enums/reservedWords"); - -const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; - -module.exports = ({ _, divideIntoActivatedAndDeactivated, commentIfDeactivated }) => { - const getFunctionArguments = functionArguments => { - return _.map(functionArguments, arg => { - const defaultExpression = arg.defaultExpression ? `DEFAULT ${arg.defaultExpression}` : ''; - - return _.trim(`${arg.argumentMode} ${arg.argumentName || ''} ${arg.argumentType} ${defaultExpression}`); - }).join(', '); - }; - - const getNamePrefixedWithSchemaName = (name, schemaName) => { - if (schemaName) { - return `${wrapInQuotes(schemaName)}.${wrapInQuotes(name)}`; - } - - return wrapInQuotes(name); - }; - - const wrapInQuotes = name => - /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)) ? `"${name}"` : name; - - const columnMapToString = ({ name }) => wrapInQuotes(name); - - const getColumnsList = (columns, isAllColumnsDeactivated, isParentActivated, mapColumn = columnMapToString) => { - const dividedColumns = divideIntoActivatedAndDeactivated(columns, mapColumn); - const deactivatedColumnsAsString = dividedColumns?.deactivatedItems?.length - ? commentIfDeactivated(dividedColumns.deactivatedItems.join(', '), { - isActivated: false, - isPartOfLine: true, - }) - : ''; - - return !isAllColumnsDeactivated && isParentActivated - ? ' (' + dividedColumns.activatedItems.join(', ') + deactivatedColumnsAsString + ')' - : ' (' + columns.map(mapColumn).join(', ') + ')'; - }; - - const getKeyWithAlias = key => { - if (!key) { - return ''; - } - - if (key.alias) { - return `${wrapInQuotes(key.name)} as ${wrapInQuotes(key.alias)}`; - } else { - return wrapInQuotes(key.name); - } - }; - - const getViewData = keys => { - if (!Array.isArray(keys)) { - return { tables: [], columns: [] }; - } - - return keys.reduce( - (result, key) => { - if (!key.tableName) { - result.columns.push(getKeyWithAlias(key)); - - return result; - } - - let tableName = wrapInQuotes(key.tableName); - - if (!result.tables.includes(tableName)) { - result.tables.push(tableName); - } - - result.columns.push({ - statement: `${tableName}.${getKeyWithAlias(key)}`, - isActivated: key.isActivated, - }); - - return result; - }, - { - tables: [], - columns: [], - }, - ); - }; - - const prepareComment = (comment = '') => - comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); - - const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; - - const getDbVersion = (dbVersion = '') => { - const version = dbVersion.match(/\d+/); - - return Number(_.get(version, [0], 0)); - }; - - return { - getFunctionArguments, - getNamePrefixedWithSchemaName, - wrapInQuotes, - getColumnsList, - getViewData, - wrapComment, - getDbVersion, - }; -}; diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index 43dac1c..b9d32ae 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -7,6 +7,9 @@ * the agreement/contract under which the software has been supplied. */ +const {ReservedWordsAsArray} = require("../enums/reservedWords"); +const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; + module.exports = _ => { const getDbName = containerData => { return _.get(containerData, '[0].code') || _.get(containerData, '[0].name', ''); @@ -92,7 +95,7 @@ module.exports = _ => { }; const getFullTableName = (collection) => { - const {getNamePrefixedWithSchemaName} = require('../helpers/general')({_}); + const {getNamePrefixedWithSchemaName} = require('../utils/general')(_); const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; const tableName = getEntityName(collectionSchema); @@ -101,14 +104,14 @@ module.exports = _ => { } const getFullColumnName = (collection, columnName) => { - const {wrapInQuotes} = require('../helpers/general')({_}); + const {wrapInQuotes} = require('../utils/general')(_); const fullTableName = getFullTableName(collection); return `${fullTableName}.${wrapInQuotes(columnName)}`; } const getFullViewName = (view) => { - const {getNamePrefixedWithSchemaName} = require('../helpers/general')({_}); + const {getNamePrefixedWithSchemaName} = require('../utils/general')(_); const viewSchema = {...view, ...(_.omit(view?.role, 'properties') || {})}; const viewName = getViewName(viewSchema); @@ -124,6 +127,97 @@ module.exports = _ => { return udt.code || udt.name; } + const getDbVersion = (dbVersion = '') => { + const version = dbVersion.match(/\d+/); + + return Number(_.get(version, [0], 0)); + }; + + const prepareComment = (comment = '') => + comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); + + const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; + + const getFunctionArguments = functionArguments => { + return _.map(functionArguments, arg => { + const defaultExpression = arg.defaultExpression ? `DEFAULT ${arg.defaultExpression}` : ''; + + return _.trim(`${arg.argumentMode} ${arg.argumentName || ''} ${arg.argumentType} ${defaultExpression}`); + }).join(', '); + }; + + const getNamePrefixedWithSchemaName = (name, schemaName) => { + if (schemaName) { + return `${wrapInQuotes(schemaName)}.${wrapInQuotes(name)}`; + } + + return wrapInQuotes(name); + }; + + const wrapInQuotes = name => + /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)) ? `"${name}"` : name; + + const columnMapToString = ({ name }) => wrapInQuotes(name); + + const getColumnsList = (columns, isAllColumnsDeactivated, isParentActivated, mapColumn = columnMapToString) => { + const dividedColumns = divideIntoActivatedAndDeactivated(columns, mapColumn); + const deactivatedColumnsAsString = dividedColumns?.deactivatedItems?.length + ? commentIfDeactivated(dividedColumns.deactivatedItems.join(', '), { + isActivated: false, + isPartOfLine: true, + }) + : ''; + + return !isAllColumnsDeactivated && isParentActivated + ? ' (' + dividedColumns.activatedItems.join(', ') + deactivatedColumnsAsString + ')' + : ' (' + columns.map(mapColumn).join(', ') + ')'; + }; + + const getKeyWithAlias = key => { + if (!key) { + return ''; + } + + if (key.alias) { + return `${wrapInQuotes(key.name)} as ${wrapInQuotes(key.alias)}`; + } else { + return wrapInQuotes(key.name); + } + }; + + const getViewData = keys => { + if (!Array.isArray(keys)) { + return { tables: [], columns: [] }; + } + + return keys.reduce( + (result, key) => { + if (!key.tableName) { + result.columns.push(getKeyWithAlias(key)); + + return result; + } + + let tableName = wrapInQuotes(key.tableName); + + if (!result.tables.includes(tableName)) { + result.tables.push(tableName); + } + + result.columns.push({ + statement: `${tableName}.${getKeyWithAlias(key)}`, + isActivated: key.isActivated, + }); + + return result; + }, + { + tables: [], + columns: [], + }, + ); + }; + return { getDbName, getDbData, @@ -143,5 +237,12 @@ module.exports = _ => { getFullColumnName, getFullViewName, getUdtName, + getDbVersion, + wrapComment, + getFunctionArguments, + getNamePrefixedWithSchemaName, + wrapInQuotes, + getColumnsList, + getViewData, }; }; From 9d1810313a70cfb4d341ee6221422b1326000a69 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 14:59:49 +0300 Subject: [PATCH 05/22] Refactoring of alter script functionality --- .../alterScript/alterScriptBuilder.js | 105 +++++++++ .../alterScriptFromDeltaHelper.js | 210 +++++++++++++----- .../alterContainerHelper.js | 8 +- .../alterScriptHelpers/alterEntityHelper.js | 14 +- .../alterScriptHelpers/alterUdtHelper.js | 16 +- .../alterScriptHelpers/alterViewHelper.js | 8 +- .../columnHelpers/alterTypeHelper.js | 2 +- .../columnHelpers/commentsHelper.js | 2 +- .../columnHelpers/nonNullConstraintHelper.js | 2 +- .../columnHelpers/renameColumnHelper.js | 2 +- .../containerHelpers/commentsHelper.js | 2 +- .../createColumnDefinition.js | 0 .../entityHelpers/checkConstraintHelper.js | 2 +- .../entityHelpers/commentsHelper.js | 2 +- .../viewHelpers/commentsHelper.js | 2 +- .../types/AlterScriptDto.js | 0 forward_engineering/api.js | 168 ++++++-------- .../ddlHelpers}/columnDefinitionHelper.js | 2 +- .../ddlHelpers}/constraintsHelper.js | 0 .../ddlHelpers}/databaseHelper.js | 0 .../ddlHelpers}/functionHelper.js | 0 .../ddlHelpers}/indexHelper.js | 0 .../ddlHelpers}/keyHelper.js | 0 .../ddlHelpers}/procedureHelper.js | 0 .../ddlHelpers}/tableHelper.js | 0 .../ddlHelpers}/triggerHelper.js | 0 .../ddlHelpers}/udtHelper.js | 0 .../{ => ddlProvider}/ddlProvider.js | 30 +-- .../helpers/commentDropStatements.js | 50 ----- forward_engineering/helpers/constants.js | 13 -- 30 files changed, 368 insertions(+), 272 deletions(-) create mode 100644 forward_engineering/alterScript/alterScriptBuilder.js rename forward_engineering/{helpers => alterScript}/alterScriptFromDeltaHelper.js (59%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/alterContainerHelper.js (80%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/alterEntityHelper.js (92%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/alterUdtHelper.js (91%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/alterViewHelper.js (80%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/columnHelpers/alterTypeHelper.js (97%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/columnHelpers/commentsHelper.js (97%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js (96%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/columnHelpers/renameColumnHelper.js (93%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/containerHelpers/commentsHelper.js (96%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/createColumnDefinition.js (100%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/entityHelpers/checkConstraintHelper.js (98%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/entityHelpers/commentsHelper.js (96%) rename forward_engineering/{helpers => alterScript}/alterScriptHelpers/viewHelpers/commentsHelper.js (96%) rename forward_engineering/{helpers/alterScriptHelpers => alterScript}/types/AlterScriptDto.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/columnDefinitionHelper.js (97%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/constraintsHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/databaseHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/functionHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/indexHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/keyHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/procedureHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/tableHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/triggerHelper.js (100%) rename forward_engineering/{helpers => ddlProvider/ddlHelpers}/udtHelper.js (100%) rename forward_engineering/{ => ddlProvider}/ddlProvider.js (96%) delete mode 100644 forward_engineering/helpers/commentDropStatements.js delete mode 100644 forward_engineering/helpers/constants.js diff --git a/forward_engineering/alterScript/alterScriptBuilder.js b/forward_engineering/alterScript/alterScriptBuilder.js new file mode 100644 index 0000000..4e9325a --- /dev/null +++ b/forward_engineering/alterScript/alterScriptBuilder.js @@ -0,0 +1,105 @@ +const {getAlterScriptDtos} = require("./alterScriptFromDeltaHelper"); + +const {AlterScriptDto} = require('./types/AlterScriptDto'); + +/** + * @return {(dtos: AlterScriptDto[], shouldApplyDropStatements: boolean) => string} + * */ +const joinAlterScriptDtosIntoScript = (_) => (dtos, shouldApplyDropStatements) => { + const { commentIfDeactivated } = require('../utils/general')(_); + const script = dtos.map((dto) => { + if (dto.isActivated === false) { + return dto.scripts + .map((scriptDto) => commentIfDeactivated(scriptDto.script, { + isActivated: false, + isPartOfLine: false, + })); + } + if (!shouldApplyDropStatements) { + return dto.scripts + .map((scriptDto) => commentIfDeactivated(scriptDto.script, { + isActivated: !scriptDto.isDropScript, + isPartOfLine: false, + })); + } + return dto.scripts.map((scriptDto) => scriptDto.script); + }) + .flat() + .filter(Boolean) + .map((scriptLine) => scriptLine.trim()) + .filter(Boolean) + .join('\n\n'); + + return script + '\n\n'; +} + +/** + * @param data {CoreData} + * @param app {App} + * @return {string} + * */ +const buildEntityLevelAlterScript = (data, app) => { + const _ = app.require('lodash'); + const alterScriptDtos = getAlterScriptDtos(data, app); + const shouldApplyDropStatements = data.options?.additionalOptions?.some( + option => option.id === 'applyDropStatements' && option.value, + ); + + return joinAlterScriptDtosIntoScript(_)(alterScriptDtos, shouldApplyDropStatements); +} + +/** + * @param data {CoreData} + * @param app {App} + * @return { boolean} + * */ +const doesEntityLevelAlterScriptContainDropStatements = (data, app) => { + const alterScriptDtos = getAlterScriptDtos(data, app); + return alterScriptDtos + .some(alterScriptDto => alterScriptDto.isActivated && alterScriptDto + .scripts.some(scriptModificationDto => scriptModificationDto.isDropScript)); +} + +const mapCoreDataForContainerLevelScripts = (data) => { + return { + ...data, + jsonSchema: data.collections[0], + internalDefinitions: Object.values(data.internalDefinitions)[0], + } +} + +/** + * @param data {CoreData} + * @param app {App} + * @return {string} + * */ +const buildContainerLevelAlterScript = (data, app) => { + const preparedData = mapCoreDataForContainerLevelScripts(data); + const _ = app.require('lodash'); + const alterScriptDtos = getAlterScriptDtos(preparedData, app); + const shouldApplyDropStatements = preparedData.options?.additionalOptions?.some( + option => option.id === 'applyDropStatements' && option.value, + ); + + return joinAlterScriptDtosIntoScript(_)(alterScriptDtos, shouldApplyDropStatements); +} + +/** + * @param data {CoreData} + * @param app {App} + * @return { boolean} + * */ +const doesContainerLevelAlterScriptContainDropStatements = (data, app) => { + const preparedData = mapCoreDataForContainerLevelScripts(data); + const alterScriptDtos = getAlterScriptDtos(preparedData, app); + return alterScriptDtos + .some(alterScriptDto => alterScriptDto.isActivated && alterScriptDto + .scripts.some(scriptModificationDto => scriptModificationDto.isDropScript)); +} + +module.exports = { + buildEntityLevelAlterScript, + doesEntityLevelAlterScriptContainDropStatements, + buildContainerLevelAlterScript, + doesContainerLevelAlterScriptContainDropStatements +} diff --git a/forward_engineering/helpers/alterScriptFromDeltaHelper.js b/forward_engineering/alterScript/alterScriptFromDeltaHelper.js similarity index 59% rename from forward_engineering/helpers/alterScriptFromDeltaHelper.js rename to forward_engineering/alterScript/alterScriptFromDeltaHelper.js index 36a1085..1e5e100 100644 --- a/forward_engineering/helpers/alterScriptFromDeltaHelper.js +++ b/forward_engineering/alterScript/alterScriptFromDeltaHelper.js @@ -16,47 +16,63 @@ const { getCreateUdtScriptDto, getAddColumnToTypeScriptDtos, getDeleteColumnFromTypeScriptDtos, - getModifyColumnOfTypeScriptDto, + getModifyColumnOfTypeScriptDtos, } = require('./alterScriptHelpers/alterUdtHelper'); const { getAddViewScriptDto, getDeleteViewScriptDto, getModifyViewScriptDtos } = require('./alterScriptHelpers/alterViewHelper'); +const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {App, CoreData} = require("../types/coreApplicationTypes"); +const {InternalDefinitions, ModelDefinitions, ExternalDefinitions} = require("../types/coreApplicationDataTypes"); -const getComparisonModelCollection = collections => { - return collections - .map(collection => JSON.parse(collection)) - .find(collection => collection.collectionName === 'comparisonModelCollection'); -}; - -const getAlterContainersScripts = ({collection, app}) => { +/** + * @param dto {{ + * collection: Object, + * app: App, + * }} + * @return {AlterScriptDto[]} + * */ +const getAlterContainersScriptDtos = ({collection, app}) => { const addedContainers = collection.properties?.containers?.properties?.added?.items; const deletedContainers = collection.properties?.containers?.properties?.deleted?.items; const modifiedContainers = collection.properties?.containers?.properties?.modified?.items; - const addContainersScripts = [] + const addContainersScriptDtos = [] .concat(addedContainers) .filter(Boolean) .map(container => getAddContainerScriptDto(app)(Object.keys(container.properties)[0])); - const deleteContainersScripts = [] + const deleteContainersScriptDtos = [] .concat(deletedContainers) .filter(Boolean) .map(container => getDeleteContainerScriptDto(app)(Object.keys(container.properties)[0])); - const modifyContainersScripts = [] + const modifyContainersScriptDtos = [] .concat(modifiedContainers) .filter(Boolean) .map(containerWrapper => Object.values(containerWrapper.properties)[0]) - .map(container => getModifyContainerScriptDtos(app)(container)) + .flatMap(container => getModifyContainerScriptDtos(app)(container)) return [ - ...addContainersScripts, - ...deleteContainersScripts, - ...modifyContainersScripts, + ...addContainersScriptDtos, + ...deleteContainersScriptDtos, + ...modifyContainersScriptDtos, ]; }; -const getAlterCollectionsScripts = ({ + +/** + * @param dto {{ + * collection: Object, + * app: App, + * dbVersion: string, + * modelDefinitions: ModelDefinitions, + * internalDefinitions: InternalDefinitions, + * externalDefinitions: ExternalDefinitions, + * }} + * @return {AlterScriptDto[]} + * */ +const getAlterCollectionsScriptDtos = ({ collection, app, dbVersion, @@ -64,37 +80,36 @@ const getAlterCollectionsScripts = ({ internalDefinitions, externalDefinitions, }) => { - const createCollectionsScripts = [] + const createCollectionsScriptDtos = [] .concat(collection.properties?.entities?.properties?.added?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .filter(collection => collection.compMod?.created) .map(getAddCollectionScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteCollectionScripts = [] + const deleteCollectionScriptDtos = [] .concat(collection.properties?.entities?.properties?.deleted?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .filter(collection => collection.compMod?.deleted) .map(getDeleteCollectionScriptDto(app)); - const modifyCollectionScripts = [] + const modifyCollectionScriptDtos = [] .concat(collection.properties?.entities?.properties?.modified?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) - .map(getModifyCollectionScriptDtos(app)) - .flat(); - const addColumnScripts = [] + .flatMap(getModifyCollectionScriptDtos(app)); + const addColumnScriptDtos = [] .concat(collection.properties?.entities?.properties?.added?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .filter(collection => !collection.compMod) .flatMap(getAddColumnScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteColumnScripts = [] + const deleteColumnScriptDtos = [] .concat(collection.properties?.entities?.properties?.deleted?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .filter(collection => !collection.compMod) .flatMap(getDeleteColumnScriptDtos(app)); - const modifyColumnScript = [] + const modifyColumnScriptDtos = [] .concat(collection.properties?.entities?.properties?.modified?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) @@ -102,17 +117,22 @@ const getAlterCollectionsScripts = ({ .flatMap(getModifyColumnScriptDtos(app)); return [ - ...createCollectionsScripts, - ...deleteCollectionScripts, - ...modifyCollectionScripts, - ...addColumnScripts, - ...deleteColumnScripts, - ...modifyColumnScript, - ].map(script => script.trim()); + ...createCollectionsScriptDtos, + ...deleteCollectionScriptDtos, + ...modifyCollectionScriptDtos, + ...addColumnScriptDtos, + ...deleteColumnScriptDtos, + ...modifyColumnScriptDtos, + ]; }; -const getAlterViewScripts = (collection, app) => { - const createViewsScripts = [] +/** + * @param collection {Object} + * @param app {App} + * @return {AlterScriptDto[]} + * */ +const getAlterViewScriptDtos = (collection, app) => { + const createViewsScriptDtos = [] .concat(collection.properties?.views?.properties?.added?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) @@ -120,14 +140,14 @@ const getAlterViewScripts = (collection, app) => { .filter(view => view.compMod?.created && view.selectStatement) .map(getAddViewScriptDto(app)); - const deleteViewsScripts = [] + const deleteViewsScriptDtos = [] .concat(collection.properties?.views?.properties?.deleted?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .map(view => ({...view, ...(view.role || {})})) .map(getDeleteViewScriptDto(app)); - const modifyViewsScripts = [] + const modifyViewsScriptDtos = [] .concat(collection.properties?.views?.properties?.modified?.items) .filter(Boolean) .map(viewWrapper => Object.values(viewWrapper.properties)[0]) @@ -135,13 +155,24 @@ const getAlterViewScripts = (collection, app) => { .flatMap(view => getModifyViewScriptDtos(app)(view)); return [ - ...deleteViewsScripts, - ...createViewsScripts, - ...modifyViewsScripts, - ].map(script => script.trim()); + ...deleteViewsScriptDtos, + ...createViewsScriptDtos, + ...modifyViewsScriptDtos, + ]; }; -const getAlterModelDefinitionsScripts = ({ +/** + * @param dto {{ + * collection: Object, + * app: App, + * dbVersion: string, + * modelDefinitions: ModelDefinitions, + * internalDefinitions: InternalDefinitions, + * externalDefinitions: ExternalDefinitions, + * }} + * @return {AlterScriptDto[]} + * */ +const getAlterModelDefinitionsScriptDtos = ({ collection, app, dbVersion, @@ -149,21 +180,21 @@ const getAlterModelDefinitionsScripts = ({ internalDefinitions, externalDefinitions, }) => { - const createUdtScripts = [] + const createUdtScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.added?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) .filter(item => item.compMod?.created) .map(getCreateUdtScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteUdtScripts = [] + const deleteUdtScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) .filter(collection => collection.compMod?.deleted) .map(getDeleteUdtScriptDto(app)); - const addColumnScripts = [] + const addColumnScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.added?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) @@ -173,7 +204,7 @@ const getAlterModelDefinitionsScripts = ({ .flatMap( getAddColumnToTypeScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}), ); - const deleteColumnScripts = [] + const deleteColumnScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) @@ -182,30 +213,93 @@ const getAlterModelDefinitionsScripts = ({ .filter(item => item.childType === 'composite') .flatMap(getDeleteColumnFromTypeScriptDtos(app)); - const modifyColumnScripts = [] + const modifyColumnScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.modified?.items) .filter(Boolean) .map(item => Object.values(item.properties)[0]) .filter(item => !item.compMod) .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) .filter(item => item.childType === 'composite') - .flatMap(getModifyColumnOfTypeScriptDto(app)); + .flatMap(getModifyColumnOfTypeScriptDtos(app)); + + return [ + ...deleteUdtScriptDtos, + ...createUdtScriptDtos, + ...addColumnScriptDtos, + ...deleteColumnScriptDtos, + ...modifyColumnScriptDtos, + ]; +}; + +/** + * @param dto {AlterScriptDto} + * @return {AlterScriptDto | undefined} + */ +const prettifyAlterScriptDto = (dto) => { + if (!dto) { + return undefined; + } + const nonEmptyScriptModificationDtos = dto.scripts + .map((scriptDto) => ({ + ...scriptDto, + script: (scriptDto.script || '').trim() + })) + .filter((scriptDto) => Boolean(scriptDto.script)); + if (!nonEmptyScriptModificationDtos.length) { + return undefined; + } + return { + ...dto, + scripts: nonEmptyScriptModificationDtos + } +} + +/** + * @param data {CoreData} + * @param app {App} + * @return {Array} + * */ +const getAlterScriptDtos = (data, app) => { + const collection = JSON.parse(data.jsonSchema); + if (!collection) { + throw new Error( + '"comparisonModelCollection" is not found. Alter script can be generated only from Delta model', + ); + } + + const modelDefinitions = JSON.parse(data.modelDefinitions); + const internalDefinitions = JSON.parse(data.internalDefinitions); + const externalDefinitions = JSON.parse(data.externalDefinitions); + const dbVersion = data.modelData[0]?.dbVersion; + const containersScriptDtos = getAlterContainersScriptDtos({collection, app}); + const collectionsScriptDtos = getAlterCollectionsScriptDtos({ + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }); + const viewScriptDtos = getAlterViewScriptDtos(collection, app); + const modelDefinitionsScriptDtos = getAlterModelDefinitionsScriptDtos({ + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }); return [ - ...deleteUdtScripts, - ...createUdtScripts, - ...addColumnScripts, - ...deleteColumnScripts, - ...modifyColumnScripts, + ...containersScriptDtos, + ...modelDefinitionsScriptDtos, + ...collectionsScriptDtos, + ...viewScriptDtos, ] - .filter(Boolean) - .map(script => script.trim()); + .map((dto) => prettifyAlterScriptDto(dto)) + .filter(Boolean); }; module.exports = { - getComparisonModelCollection, - getAlterContainersScripts, - getAlterCollectionsScripts, - getAlterViewScripts, - getAlterModelDefinitionsScripts, + getAlterScriptDtos, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js similarity index 80% rename from forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js index d3f2454..91ca42a 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterContainerHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js @@ -1,12 +1,12 @@ const {getModifySchemaCommentsScriptDtos} = require("./containerHelpers/commentsHelper"); -const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(containerName: string) => AlterScriptDto} * */ const getAddContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {wrapInQuotes} = require('../../utils/general')(_); const script = ddlProvider.createSchemaOnly(wrapInQuotes(containerName)); return AlterScriptDto.getInstance([script], true, false); @@ -17,7 +17,7 @@ const getAddContainerScriptDto = (app) => (containerName) => { * */ const getDeleteContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {wrapInQuotes} = require('../../utils/general')(_); const script = ddlProvider.dropSchema(wrapInQuotes(containerName)); @@ -29,7 +29,7 @@ const getDeleteContainerScriptDto = (app) => (containerName) => { * */ const getModifyContainerScriptDtos = (app) => (container) => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const modifyCommentScriptDtos = getModifySchemaCommentsScriptDtos(_, ddlProvider)(container); diff --git a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js similarity index 92% rename from forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js index 948ae7a..0e19df3 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js @@ -4,7 +4,7 @@ const {getUpdateTypesScriptDtos} = require("./columnHelpers/alterTypeHelper"); const {getModifyNonNullColumnsScriptDtos} = require("./columnHelpers/nonNullConstraintHelper"); const {getModifiedCommentOnColumnScriptDtos} = require("./columnHelpers/commentsHelper"); const {getRenameColumnScriptDtos} = require("./columnHelpers/renameColumnHelper"); -const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** @@ -16,7 +16,7 @@ const getAddCollectionScriptDto = const _ = app.require('lodash'); const {getEntityName} = require('../../utils/general')(_); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); const schemaName = collection.compMod.keyspaceName; @@ -62,7 +62,7 @@ const getAddCollectionScriptDto = * */ const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getFullTableName} = require('../../utils/general')(_); const fullName = getFullTableName(collection); @@ -75,7 +75,7 @@ const getDeleteCollectionScriptDto = app => collection => { * */ const getModifyCollectionScriptDtos = (app) => (collection) => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const modifyCheckConstraintScriptDtos = getModifyCheckConstraintScriptDtos(_, ddlProvider)(collection); const modifyCommentScriptDtos = getModifyEntityCommentsScriptDtos(_, ddlProvider)(collection); @@ -94,7 +94,7 @@ const getAddColumnScriptDtos = const _ = app.require('lodash'); const {getEntityName, getNamePrefixedWithSchemaName} = require('../../utils/general')(_); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; @@ -132,7 +132,7 @@ const getAddColumnScriptDtos = * */ const getDeleteColumnScriptDtos = app => collection => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getEntityName, getNamePrefixedWithSchemaName, wrapInQuotes} = require('../../utils/general')(_); const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; @@ -154,7 +154,7 @@ const getDeleteColumnScriptDtos = app => collection => { * */ const getModifyColumnScriptDtos = app => collection => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const renameColumnScriptDtos = getRenameColumnScriptDtos(_, ddlProvider)(collection); const updateTypeScriptDtos = getUpdateTypesScriptDtos(_, ddlProvider)(collection); diff --git a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js similarity index 91% rename from forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js index dcc6fc1..22b2dea 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(jsonSchema: Object) => AlterScriptDto} @@ -8,7 +8,7 @@ const getCreateUdtScriptDto = jsonSchema => { const _ = app.require('lodash'); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); const schemaData = {dbVersion}; @@ -52,7 +52,7 @@ const getCreateUdtScriptDto = * */ const getDeleteUdtScriptDto = app => udt => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); @@ -75,7 +75,7 @@ const getAddColumnToTypeScriptDtos = const _ = app.require('lodash'); const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); const fullName = wrapInQuotes(getUdtName(udt)); @@ -110,7 +110,7 @@ const getAddColumnToTypeScriptDtos = * */ const getDeleteColumnFromTypeScriptDtos = app => udt => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {wrapInQuotes} = require('../../utils/general')(_); @@ -125,9 +125,9 @@ const getDeleteColumnFromTypeScriptDtos = app => udt => { /** * @return {(udt: Object) => AlterScriptDto[]} * */ -const getModifyColumnOfTypeScriptDto = app => udt => { +const getModifyColumnOfTypeScriptDtos = app => udt => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const {checkFieldPropertiesChanged, wrapInQuotes} = require('../../utils/general')(_); @@ -159,5 +159,5 @@ module.exports = { getDeleteUdtScriptDto, getAddColumnToTypeScriptDtos, getDeleteColumnFromTypeScriptDtos, - getModifyColumnOfTypeScriptDto, + getModifyColumnOfTypeScriptDtos, }; diff --git a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js similarity index 80% rename from forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js index d02ddf4..345403a 100644 --- a/forward_engineering/helpers/alterScriptHelpers/alterViewHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js @@ -1,11 +1,11 @@ const {getModifyViewCommentsScriptDtos} = require("./viewHelpers/commentsHelper"); -const {AlterScriptDto} = require("./types/AlterScriptDto"); +const {AlterScriptDto} = require("../types/AlterScriptDto"); /** * @return {(view: Object) => AlterScriptDto} * */ const getAddViewScriptDto = app => view => { - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const viewData = { name: view.code || view.name, @@ -23,7 +23,7 @@ const getAddViewScriptDto = app => view => { * */ const getDeleteViewScriptDto = app => view => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const { wrapInQuotes } = require('../../utils/general')(_); const viewName = wrapInQuotes(view.code || view.name); @@ -36,7 +36,7 @@ const getDeleteViewScriptDto = app => view => { * */ const getModifyViewScriptDtos = (app) => (view) => { const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider')(null, null, app); + const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const modifyCommentsScriptDtos = getModifyViewCommentsScriptDtos(_, ddlProvider)(view); diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js similarity index 97% rename from forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js index c8f3592..b3446ba 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {boolean} diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js similarity index 97% rename from forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js index dfb8612..1b0cbde 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto[]} diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js similarity index 96% rename from forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js index 410c5e7..456bfaa 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto[]} diff --git a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js similarity index 93% rename from forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js index e64a763..9d423e0 100644 --- a/forward_engineering/helpers/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto[]} diff --git a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js similarity index 96% rename from forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js index 9aad2e0..f6e75c3 100644 --- a/forward_engineering/helpers/alterScriptHelpers/containerHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); const extractDescription = (container) => { return container?.role?.compMod?.description || {}; diff --git a/forward_engineering/helpers/alterScriptHelpers/createColumnDefinition.js b/forward_engineering/alterScript/alterScriptHelpers/createColumnDefinition.js similarity index 100% rename from forward_engineering/helpers/alterScriptHelpers/createColumnDefinition.js rename to forward_engineering/alterScript/alterScriptHelpers/createColumnDefinition.js diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js similarity index 98% rename from forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index 135d02f..7ee641f 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js @@ -12,7 +12,7 @@ * */ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {(collection: Object) => Array} diff --git a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js similarity index 96% rename from forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js index b8c8a21..6d843c6 100644 --- a/forward_engineering/helpers/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); /** * @return {(collection: Object) => AlterScriptDto} diff --git a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js similarity index 96% rename from forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js rename to forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js index 9380ce1..a96f0c1 100644 --- a/forward_engineering/helpers/alterScriptHelpers/viewHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js @@ -1,4 +1,4 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); const extractDescription = (view) => { return view?.role?.compMod?.description || {}; diff --git a/forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js b/forward_engineering/alterScript/types/AlterScriptDto.js similarity index 100% rename from forward_engineering/helpers/alterScriptHelpers/types/AlterScriptDto.js rename to forward_engineering/alterScript/types/AlterScriptDto.js diff --git a/forward_engineering/api.js b/forward_engineering/api.js index 818fd12..971c9d4 100644 --- a/forward_engineering/api.js +++ b/forward_engineering/api.js @@ -1,119 +1,79 @@ const reApi = require('../reverse_engineering/api'); -const { createLogger } = require('../reverse_engineering/helpers/loggerHelper'); +const {createLogger} = require('../reverse_engineering/helpers/loggerHelper'); const applyToInstanceHelper = require('./applyToInstanceHelper'); -const { commentDropStatements, doesScriptContainDropStatements} = require('./helpers/commentDropStatements'); +const { + buildEntityLevelAlterScript, + buildContainerLevelAlterScript, + doesContainerLevelAlterScriptContainDropStatements, + doesEntityLevelAlterScriptContainDropStatements +} = require("./alterScript/alterScriptBuilder"); module.exports = { - generateScript(data, logger, callback, app) { - try { - const { - getAlterContainersScripts, - getAlterCollectionsScripts, - getAlterViewScripts, - getAlterModelDefinitionsScripts, - } = require('./helpers/alterScriptFromDeltaHelper'); + generateScript(data, logger, callback, app) { + try { + const script = buildEntityLevelAlterScript(data, app); + callback(null, script); + } catch (error) { + logger.log('error', {message: error.message, stack: error.stack}, 'PostgreSQL Forward-Engineering Error'); - const collection = JSON.parse(data.jsonSchema); - if (!collection) { - throw new Error( - '"comparisonModelCollection" is not found. Alter script can be generated only from Delta model', - ); - } + callback({message: error.message, stack: error.stack}); + } + }, - const modelDefinitions = JSON.parse(data.modelDefinitions); - const internalDefinitions = JSON.parse(data.internalDefinitions); - const externalDefinitions = JSON.parse(data.externalDefinitions); - const dbVersion = data.modelData[0]?.dbVersion; - const containersScripts = getAlterContainersScripts({collection, app}); - const collectionsScripts = getAlterCollectionsScripts({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - const viewScripts = getAlterViewScripts(collection, app); - const modelDefinitionsScripts = getAlterModelDefinitionsScripts({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - const script = [ - ...containersScripts, - ...modelDefinitionsScripts, - ...collectionsScripts, - ...viewScripts, - ].join('\n\n'); + generateViewScript(data, logger, callback, app) { + callback(new Error('Forward-Engineering of delta model on view level is not supported')); + }, - const applyDropStatements = data.options?.additionalOptions?.some( - option => option.id === 'applyDropStatements' && option.value, - ); + generateContainerScript(data, logger, callback, app) { + try { + const script = buildContainerLevelAlterScript(data, app); + callback(null, script); + } catch (error) { + logger.log('error', {message: error.message, stack: error.stack}, 'PostgreSQL Forward-Engineering Error'); - callback(null, applyDropStatements ? script : commentDropStatements(script)); - } catch (error) { - logger.log('error', { message: error.message, stack: error.stack }, 'PostgreSQL Forward-Engineering Error'); + callback({message: error.message, stack: error.stack}); + } + }, - callback({ message: error.message, stack: error.stack }); - } - }, - generateViewScript(data, logger, callback, app) { - callback(new Error('Forward-Engineering of delta model on view level is not supported')); - }, - generateContainerScript(data, logger, callback, app) { - try { - data.jsonSchema = data.collections[0]; - data.internalDefinitions = Object.values(data.internalDefinitions)[0]; - this.generateScript(data, logger, callback, app); - } catch (error) { - logger.log('error', { message: error.message, stack: error.stack }, 'PostgreSQL Forward-Engineering Error'); + getDatabases(connectionInfo, logger, callback, app) { + logger.progress({message: 'Find all databases'}); - callback({ message: error.message, stack: error.stack }); - } - }, - getDatabases(connectionInfo, logger, callback, app) { - logger.progress({ message: 'Find all databases' }); + reApi.getDatabases(connectionInfo, logger, callback, app); + }, - reApi.getDatabases(connectionInfo, logger, callback, app); - }, - applyToInstance(connectionInfo, logger, callback, app) { - logger.clear(); - logger.log( - 'info', - app.require('lodash').omit(connectionInfo, 'script', 'containerData'), - 'connectionInfo', - connectionInfo.hiddenKeys, - ); + applyToInstance(connectionInfo, logger, callback, app) { + logger.clear(); + logger.log( + 'info', + app.require('lodash').omit(connectionInfo, 'script', 'containerData'), + 'connectionInfo', + connectionInfo.hiddenKeys, + ); - const postgresLogger = createLogger({ - title: 'Apply to instance', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); + const postgresLogger = createLogger({ + title: 'Apply to instance', + hiddenKeys: connectionInfo.hiddenKeys, + logger, + }); - applyToInstanceHelper.applyToInstance(connectionInfo, postgresLogger, app).then(callback, callback); - }, - testConnection(connectionInfo, logger, callback, app) { - reApi.testConnection(connectionInfo, logger, callback, app).then(callback, callback); - }, - isDropInStatements(data, logger, callback, app) { - try { - const cb = (error, script = '') => - callback( - error, - doesScriptContainDropStatements(script), - ); + applyToInstanceHelper.applyToInstance(connectionInfo, postgresLogger, app).then(callback, callback); + }, - if (data.level === 'container') { - this.generateContainerScript(data, logger, cb, app); - } else { - this.generateScript(data, logger, cb, app); - } - } catch (e) { - callback({ message: e.message, stack: e.stack }); - } - }, + testConnection(connectionInfo, logger, callback, app) { + reApi.testConnection(connectionInfo, logger, callback, app).then(callback, callback); + }, + + isDropInStatements(data, logger, callback, app) { + try { + if (data.level === 'container') { + const containsDropStatements = doesContainerLevelAlterScriptContainDropStatements(data, app); + callback(null, containsDropStatements); + } else { + const containsDropStatements = doesEntityLevelAlterScriptContainDropStatements(data, app); + callback(null, containsDropStatements); + } + } catch (e) { + callback({message: e.message, stack: e.stack}); + } + }, }; diff --git a/forward_engineering/helpers/columnDefinitionHelper.js b/forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js similarity index 97% rename from forward_engineering/helpers/columnDefinitionHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js index 63de6d3..0a0326e 100644 --- a/forward_engineering/helpers/columnDefinitionHelper.js +++ b/forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js @@ -1,4 +1,4 @@ -module.exports = ({ _, wrap, assignTemplates, templates, commentIfDeactivated, wrapComment, wrapInQuotes }) => { +module.exports = ({ _, assignTemplates, templates, commentIfDeactivated, wrapComment, wrapInQuotes }) => { const addLength = (type, length) => { return `${type}(${length})`; }; diff --git a/forward_engineering/helpers/constraintsHelper.js b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js similarity index 100% rename from forward_engineering/helpers/constraintsHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js diff --git a/forward_engineering/helpers/databaseHelper.js b/forward_engineering/ddlProvider/ddlHelpers/databaseHelper.js similarity index 100% rename from forward_engineering/helpers/databaseHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/databaseHelper.js diff --git a/forward_engineering/helpers/functionHelper.js b/forward_engineering/ddlProvider/ddlHelpers/functionHelper.js similarity index 100% rename from forward_engineering/helpers/functionHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/functionHelper.js diff --git a/forward_engineering/helpers/indexHelper.js b/forward_engineering/ddlProvider/ddlHelpers/indexHelper.js similarity index 100% rename from forward_engineering/helpers/indexHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/indexHelper.js diff --git a/forward_engineering/helpers/keyHelper.js b/forward_engineering/ddlProvider/ddlHelpers/keyHelper.js similarity index 100% rename from forward_engineering/helpers/keyHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/keyHelper.js diff --git a/forward_engineering/helpers/procedureHelper.js b/forward_engineering/ddlProvider/ddlHelpers/procedureHelper.js similarity index 100% rename from forward_engineering/helpers/procedureHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/procedureHelper.js diff --git a/forward_engineering/helpers/tableHelper.js b/forward_engineering/ddlProvider/ddlHelpers/tableHelper.js similarity index 100% rename from forward_engineering/helpers/tableHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/tableHelper.js diff --git a/forward_engineering/helpers/triggerHelper.js b/forward_engineering/ddlProvider/ddlHelpers/triggerHelper.js similarity index 100% rename from forward_engineering/helpers/triggerHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/triggerHelper.js diff --git a/forward_engineering/helpers/udtHelper.js b/forward_engineering/ddlProvider/ddlHelpers/udtHelper.js similarity index 100% rename from forward_engineering/helpers/udtHelper.js rename to forward_engineering/ddlProvider/ddlHelpers/udtHelper.js diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js similarity index 96% rename from forward_engineering/ddlProvider.js rename to forward_engineering/ddlProvider/ddlProvider.js index 7685f40..91054ee 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -1,6 +1,6 @@ -const defaultTypes = require('./configs/defaultTypes'); -const types = require('./configs/types'); -const templates = require('./ddlProvider/templates'); +const defaultTypes = require('../configs/defaultTypes'); +const types = require('../configs/types'); +const templates = require('./templates'); module.exports = (baseProvider, options, app) => { const _ = app.require('lodash'); @@ -18,8 +18,8 @@ module.exports = (baseProvider, options, app) => { getNamePrefixedWithSchemaName, getColumnsList, getViewData, - } = require('./utils/general')(_); - const assignTemplates = require('./utils/assignTemplates'); + } = require('../utils/general')(_); + const assignTemplates = require('../utils/assignTemplates'); const { generateConstraintsString, @@ -28,7 +28,7 @@ module.exports = (baseProvider, options, app) => { createKeyConstraint, getConstraintsWarnings, additionalPropertiesForForeignKey, - } = require('./helpers/constraintsHelper')({ + } = require('./ddlHelpers/constraintsHelper')({ _, commentIfDeactivated, checkAllKeysDeactivated, @@ -36,9 +36,9 @@ module.exports = (baseProvider, options, app) => { getColumnsList, wrapInQuotes, }); - const keyHelper = require('./helpers/keyHelper')(_, clean); + const keyHelper = require('./ddlHelpers/keyHelper')(_, clean); - const { getFunctionsScript } = require('./helpers/functionHelper')({ + const { getFunctionsScript } = require('./ddlHelpers/functionHelper')({ _, templates, assignTemplates, @@ -46,7 +46,7 @@ module.exports = (baseProvider, options, app) => { getNamePrefixedWithSchemaName, }); - const { getProceduresScript } = require('./helpers/procedureHelper')({ + const { getProceduresScript } = require('./ddlHelpers/procedureHelper')({ _, templates, assignTemplates, @@ -54,13 +54,13 @@ module.exports = (baseProvider, options, app) => { getNamePrefixedWithSchemaName, }); - const { getTableTemporaryValue, getTableOptions } = require('./helpers/tableHelper')({ + const { getTableTemporaryValue, getTableOptions } = require('./ddlHelpers/tableHelper')({ _, checkAllKeysDeactivated, getColumnsList, }); - const { getUserDefinedType, isNotPlainType } = require('./helpers/udtHelper')({ + const { getUserDefinedType, isNotPlainType } = require('./ddlHelpers/udtHelper')({ _, commentIfDeactivated, assignTemplates, @@ -69,7 +69,7 @@ module.exports = (baseProvider, options, app) => { wrapComment, }); - const { getIndexKeys, getIndexOptions } = require('./helpers/indexHelper')({ + const { getIndexKeys, getIndexOptions } = require('./ddlHelpers/indexHelper')({ _, wrapInQuotes, checkAllKeysDeactivated, @@ -77,7 +77,7 @@ module.exports = (baseProvider, options, app) => { }); const { decorateType, decorateDefault, getColumnComments, replaceTypeByVersion } = - require('./helpers/columnDefinitionHelper')({ + require('./ddlHelpers/columnDefinitionHelper')({ _, wrap, assignTemplates, @@ -87,7 +87,7 @@ module.exports = (baseProvider, options, app) => { wrapComment, }); - const { getTriggersScript, hydrateTriggers } = require('./helpers/triggerHelper')({ + const { getTriggersScript, hydrateTriggers } = require('./ddlHelpers/triggerHelper')({ _, wrap, assignTemplates, @@ -96,7 +96,7 @@ module.exports = (baseProvider, options, app) => { commentIfDeactivated, }); - const { getLocaleProperties } = require('./helpers/databaseHelper')(); + const { getLocaleProperties } = require('./ddlHelpers/databaseHelper')(); return { createDatabase(modelData) { diff --git a/forward_engineering/helpers/commentDropStatements.js b/forward_engineering/helpers/commentDropStatements.js deleted file mode 100644 index e37e97d..0000000 --- a/forward_engineering/helpers/commentDropStatements.js +++ /dev/null @@ -1,50 +0,0 @@ -const { DROP_STATEMENTS } = require('./constants'); - -const isDropNotNullStatementRegex = /ALTER TABLE IF EXISTS .+ ALTER COLUMN .+ DROP NOT NULL;/; - -const isDropConstraintStatementRegex = /ALTER TABLE IF EXISTS .+ DROP CONSTRAINT IF EXISTS .+;/; - -const dropCommentRegex = /COMMENT ON (TABLE|SCHEMA|VIEW|COLUMN) .+ IS NULL;/; - -/** - * @param scriptLine {string} - * @return {boolean} - * */ -const shouldStatementBeCommentedOut = (scriptLine) => { - const doesContainDropStatements = DROP_STATEMENTS.some(statement => scriptLine.includes(statement)); - if (doesContainDropStatements) { - return true; - } - - return [ - isDropNotNullStatementRegex, - isDropConstraintStatementRegex, - dropCommentRegex, - ].some(regex => regex.test(scriptLine)); -} - -/** - * @param script {string} - * @return {boolean} - * */ -const doesScriptContainDropStatements = (script) => { - return script.split('\n') - .some(shouldStatementBeCommentedOut); -} - - -const commentDropStatements = (script = '') => - script - .split('\n') - .map(line => { - if (shouldStatementBeCommentedOut(line)) { - return `-- ${line}`; - } - return line; - }) - .join('\n'); - -module.exports = { - commentDropStatements, - doesScriptContainDropStatements, -}; diff --git a/forward_engineering/helpers/constants.js b/forward_engineering/helpers/constants.js deleted file mode 100644 index 5c9cba7..0000000 --- a/forward_engineering/helpers/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -const DROP_STATEMENTS = [ - 'DROP SCHEMA', - 'DROP TABLE', - 'DROP COLUMN', - 'DROP DOMAIN', - 'DROP TYPE', - 'DROP ATTRIBUTE', - 'DROP VIEW', -]; - -module.exports = { - DROP_STATEMENTS, -}; From f4657b5d19e454b21d76253264d2cf62a5614129 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 15:10:57 +0300 Subject: [PATCH 06/22] Require fixes --- forward_engineering/ddlProvider/ddlProvider.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 91054ee..28788ef 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -281,7 +281,7 @@ module.exports = (baseProvider, options, app) => { const ifNotExist = index.ifNotExist ? ' IF NOT EXISTS' : ''; const only = index.only ? ' ONLY' : ''; const using = index.index_method ? ` USING ${_.toUpper(index.index_method)}` : ''; - const { getDbVersion } = require('utils/general')(_); + const { getDbVersion } = require('../utils/general')(_); const dbVersion = getDbVersion(_.get(dbData, 'dbVersion', '')); const nullsDistinct = isUnique && index.nullsDistinct && dbVersion >= 15 ? `\n ${index.nullsDistinct}` : ''; @@ -443,7 +443,7 @@ module.exports = (baseProvider, options, app) => { : ''; const security_barrier = viewData.viewOptions?.security_barrier ? `security_barrier` : ''; const dbVersionWhereSecurityInvokerAppeared = 15; - const { getDbVersion } = require('utils/general')(_); + const { getDbVersion } = require('../utils/general')(_); const security_invoker = viewData.viewOptions?.security_invoker && getDbVersion(dbData.dbVersion) >= dbVersionWhereSecurityInvokerAppeared @@ -542,7 +542,7 @@ module.exports = (baseProvider, options, app) => { const timePrecision = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timePrecision : ''; const timezone = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timezone : ''; const intervalOptions = columnDefinition.type === 'interval' ? jsonSchema.intervalOptions : ''; - const { getDbVersion } = require('utils/general')(_); + const { getDbVersion } = require('../utils/general')(_); const dbVersion = getDbVersion(schemaData.dbVersion) const primaryKeyOptions = _.omit( keyHelper.hydratePrimaryKeyOptions( @@ -655,7 +655,7 @@ module.exports = (baseProvider, options, app) => { ? getNamePrefixedWithSchemaName(partitionParent.collectionName, partitionParent.bucketName) : ''; const triggers = hydrateTriggers(entityData, tableData.relatedSchemas); - const { getDbVersion } = require('utils/general')(_); + const { getDbVersion } = require('../utils/general')(_); const dbVersion = getDbVersion(_.get(tableData, 'dbData.dbVersion', '')); return { From 4624d85d189f879f69f5cfd80f2f12b4a58755b8 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 15:40:02 +0300 Subject: [PATCH 07/22] Fixed unnecessary trailing \n\n --- forward_engineering/alterScript/alterScriptBuilder.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptBuilder.js b/forward_engineering/alterScript/alterScriptBuilder.js index 4e9325a..f2609e1 100644 --- a/forward_engineering/alterScript/alterScriptBuilder.js +++ b/forward_engineering/alterScript/alterScriptBuilder.js @@ -6,8 +6,8 @@ const {AlterScriptDto} = require('./types/AlterScriptDto'); * @return {(dtos: AlterScriptDto[], shouldApplyDropStatements: boolean) => string} * */ const joinAlterScriptDtosIntoScript = (_) => (dtos, shouldApplyDropStatements) => { - const { commentIfDeactivated } = require('../utils/general')(_); - const script = dtos.map((dto) => { + const {commentIfDeactivated} = require('../utils/general')(_); + return dtos.map((dto) => { if (dto.isActivated === false) { return dto.scripts .map((scriptDto) => commentIfDeactivated(scriptDto.script, { @@ -29,8 +29,6 @@ const joinAlterScriptDtosIntoScript = (_) => (dtos, shouldApplyDropStatements) = .map((scriptLine) => scriptLine.trim()) .filter(Boolean) .join('\n\n'); - - return script + '\n\n'; } /** From 436c3a684f9b74e8698d2870cadec0b920c075b5 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 16:38:32 +0300 Subject: [PATCH 08/22] Fixed problem with missing ddlProvider.js file in the forward_engineering folder --- forward_engineering/ddlProvider.js | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 forward_engineering/ddlProvider.js diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js new file mode 100644 index 0000000..f9d33cc --- /dev/null +++ b/forward_engineering/ddlProvider.js @@ -0,0 +1,4 @@ +// This file reexports actual DDL Provider. +// Core application needs this file to ... + +module.exports = require('./ddlProvider/ddlProvider'); From 901a3ff30804dabcc156277237ce920f5127b316 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 30 May 2023 19:45:51 +0300 Subject: [PATCH 09/22] Added commenting out of relationships in FE scripts --- forward_engineering/ddlProvider.js | 2 +- forward_engineering/ddlProvider/ddlProvider.js | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index f9d33cc..a76ecbe 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -1,4 +1,4 @@ // This file reexports actual DDL Provider. -// Core application needs this file to ... +// Core application needs this file to generate FE scripts module.exports = require('./ddlProvider/ddlProvider'); diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 28788ef..56a33c7 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -331,17 +331,19 @@ module.exports = (baseProvider, options, app) => { foreignSchemaName, primarySchemaName, customProperties, + isActivated }, dbData, schemaData, ) { const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const isActivated = + const isRelationshipActivated = !isAllPrimaryKeysDeactivated && !isAllForeignKeysDeactivated && primaryTableActivated && - foreignTableActivated; + foreignTableActivated && + isActivated; const { foreignOnDelete, foreignOnUpdate, foreignMatch } = additionalPropertiesForForeignKey(customProperties); @@ -349,8 +351,8 @@ module.exports = (baseProvider, options, app) => { const foreignKeyStatement = assignTemplates(templates.createForeignKeyConstraint, { primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), name: name ? `CONSTRAINT ${wrapInQuotes(name)}` : '', - foreignKey: isActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: isActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), + foreignKey: isRelationshipActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), + primaryKey: isRelationshipActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', match: foreignMatch ? ` MATCH ${foreignMatch}` : '', @@ -358,7 +360,7 @@ module.exports = (baseProvider, options, app) => { return { statement: _.trim(foreignKeyStatement), - isActivated, + isActivated: isRelationshipActivated, }; }, From da2935be1f901c5b8771f1d44f6986c154e01375 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 31 May 2023 09:24:53 +0300 Subject: [PATCH 10/22] Started to work on adding relationships to alter script --- .../alterScript/alterScriptFromDeltaHelper.js | 87 ++++++++--- .../alterContainerHelper.js | 4 +- .../alterScriptHelpers/alterEntityHelper.js | 14 +- .../alterRelationshipsHelper.js | 138 ++++++++++++++++++ .../alterScriptHelpers/alterUdtHelper.js | 15 +- .../alterScriptHelpers/alterViewHelper.js | 6 +- .../alterScript/types/AlterScriptDto.js | 32 ++++ .../ddlProvider/ddlProvider.js | 13 ++ forward_engineering/ddlProvider/templates.js | 2 + 9 files changed, 276 insertions(+), 35 deletions(-) create mode 100644 forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js diff --git a/forward_engineering/alterScript/alterScriptFromDeltaHelper.js b/forward_engineering/alterScript/alterScriptFromDeltaHelper.js index 1e5e100..7c33454 100644 --- a/forward_engineering/alterScript/alterScriptFromDeltaHelper.js +++ b/forward_engineering/alterScript/alterScriptFromDeltaHelper.js @@ -23,10 +23,16 @@ const { getDeleteViewScriptDto, getModifyViewScriptDtos } = require('./alterScriptHelpers/alterViewHelper'); -const {AlterScriptDto} = require("./types/AlterScriptDto"); +const { + getModifyForeignKeyScriptDtos, + getDeleteForeignKeyScriptDtos, + getAddForeignKeyScriptDtos +} = require("./alterScriptHelpers/alterRelationshipsHelper"); +const {AlterScriptDto, ModificationScript} = require("./types/AlterScriptDto"); const {App, CoreData} = require("../types/coreApplicationTypes"); const {InternalDefinitions, ModelDefinitions, ExternalDefinitions} = require("../types/coreApplicationDataTypes"); + /** * @param dto {{ * collection: Object, @@ -57,7 +63,7 @@ const getAlterContainersScriptDtos = ({collection, app}) => { ...addContainersScriptDtos, ...deleteContainersScriptDtos, ...modifyContainersScriptDtos, - ]; + ].filter(Boolean); }; @@ -73,13 +79,13 @@ const getAlterContainersScriptDtos = ({collection, app}) => { * @return {AlterScriptDto[]} * */ const getAlterCollectionsScriptDtos = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }) => { + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }) => { const createCollectionsScriptDtos = [] .concat(collection.properties?.entities?.properties?.added?.items) .filter(Boolean) @@ -123,7 +129,7 @@ const getAlterCollectionsScriptDtos = ({ ...addColumnScriptDtos, ...deleteColumnScriptDtos, ...modifyColumnScriptDtos, - ]; + ].filter(Boolean); }; /** @@ -158,7 +164,7 @@ const getAlterViewScriptDtos = (collection, app) => { ...deleteViewsScriptDtos, ...createViewsScriptDtos, ...modifyViewsScriptDtos, - ]; + ].filter(Boolean); }; /** @@ -173,13 +179,13 @@ const getAlterViewScriptDtos = (collection, app) => { * @return {AlterScriptDto[]} * */ const getAlterModelDefinitionsScriptDtos = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }) => { + collection, + app, + dbVersion, + modelDefinitions, + internalDefinitions, + externalDefinitions, + }) => { const createUdtScriptDtos = [] .concat(collection.properties?.modelDefinitions?.properties?.added?.items) .filter(Boolean) @@ -228,9 +234,46 @@ const getAlterModelDefinitionsScriptDtos = ({ ...addColumnScriptDtos, ...deleteColumnScriptDtos, ...modifyColumnScriptDtos, - ]; + ].filter(Boolean); }; +/** + * @return Array + * */ +const getAlterRelationshipsScriptDtos = ({ + collection, + app, + }) => { + const _ = app.require('lodash'); + const ddlProvider = require('../ddlProvider/ddlProvider')(null, null, app); + + const addedRelationships = [] + .concat(collection.properties?.relationships?.properties?.added?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(relationship => relationship?.role?.compMod?.created); + const deletedRelationships = [] + .concat(collection.properties?.relationships?.properties?.deleted?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(relationship => relationship?.role?.compMod?.deleted); + const modifiedRelationships = [] + .concat(collection.properties?.relationships?.properties?.modified?.items) + .filter(Boolean) + .map(item => Object.values(item.properties)[0]) + .filter(relationship => relationship?.role?.compMod?.modified); + + const deleteFkScriptDtos = getDeleteForeignKeyScriptDtos(ddlProvider, _)(deletedRelationships); + const addFkScriptDtos = getAddForeignKeyScriptDtos(ddlProvider, _)(addedRelationships); + const modifiedFkScriptDtos = getModifyForeignKeyScriptDtos(ddlProvider, _)(modifiedRelationships); + + return [ + ...deleteFkScriptDtos, + ...addFkScriptDtos, + ...modifiedFkScriptDtos, + ].filter(Boolean); +} + /** * @param dto {AlterScriptDto} * @return {AlterScriptDto | undefined} @@ -239,6 +282,9 @@ const prettifyAlterScriptDto = (dto) => { if (!dto) { return undefined; } + /** + * @type {Array} + * */ const nonEmptyScriptModificationDtos = dto.scripts .map((scriptDto) => ({ ...scriptDto, @@ -289,13 +335,16 @@ const getAlterScriptDtos = (data, app) => { internalDefinitions, externalDefinitions, }); + const relationshipScriptDtos = getAlterRelationshipsScriptDtos({collection, app}); return [ ...containersScriptDtos, ...modelDefinitionsScriptDtos, ...collectionsScriptDtos, ...viewScriptDtos, + ...relationshipScriptDtos, ] + .filter(Boolean) .map((dto) => prettifyAlterScriptDto(dto)) .filter(Boolean); }; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js index 91ca42a..1e11841 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js @@ -2,7 +2,7 @@ const {getModifySchemaCommentsScriptDtos} = require("./containerHelpers/comments const {AlterScriptDto} = require("../types/AlterScriptDto"); /** - * @return {(containerName: string) => AlterScriptDto} + * @return {(containerName: string) => AlterScriptDto | undefined} * */ const getAddContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); @@ -13,7 +13,7 @@ const getAddContainerScriptDto = (app) => (containerName) => { }; /** - * @return {(containerName: string) => AlterScriptDto} + * @return {(containerName: string) => AlterScriptDto | undefined} * */ const getDeleteContainerScriptDto = (app) => (containerName) => { const _ = app.require('lodash'); diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js index 0e19df3..0c86e01 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js @@ -8,7 +8,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); /** - * @return {(collection: Object) => AlterScriptDto} + * @return {(collection: Object) => AlterScriptDto | undefined} * */ const getAddCollectionScriptDto = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => @@ -58,7 +58,7 @@ const getAddCollectionScriptDto = }; /** - * @return {(collection: Object) => AlterScriptDto} + * @return {(collection: Object) => AlterScriptDto | undefined} * */ const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); @@ -82,7 +82,7 @@ const getModifyCollectionScriptDtos = (app) => (collection) => { return [ ...modifyCheckConstraintScriptDtos, ...modifyCommentScriptDtos - ]; + ].filter(Boolean); } /** @@ -124,7 +124,8 @@ const getAddColumnScriptDtos = }) .map(ddlProvider.convertColumnDefinition) .map(columnDefinition => ddlProvider.addColumn(fullName, columnDefinition)) - .map(addColumnScript => AlterScriptDto.getInstance([addColumnScript], true, false)); + .map(addColumnScript => AlterScriptDto.getInstance([addColumnScript], true, false)) + .filter(Boolean); }; /** @@ -146,7 +147,8 @@ const getDeleteColumnScriptDtos = app => collection => { const columnNameForDDL = wrapInQuotes(name); return ddlProvider.dropColumn(fullTableName, columnNameForDDL) }) - .map(dropColumnScript => AlterScriptDto.getInstance([dropColumnScript], true, true)); + .map(dropColumnScript => AlterScriptDto.getInstance([dropColumnScript], true, true)) + .filter(Boolean); }; /** @@ -166,7 +168,7 @@ const getModifyColumnScriptDtos = app => collection => { ...updateTypeScriptDtos, ...modifyNotNullScriptDtos, ...modifyCommentScriptDtos, - ]; + ].filter(Boolean); }; module.exports = { diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js new file mode 100644 index 0000000..e7005cd --- /dev/null +++ b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js @@ -0,0 +1,138 @@ +const {AlterScriptDto} = require("../types/AlterScriptDto"); + + +/** + * @param relationship {Object} + * @return string + * */ +const getRelationshipName = (relationship) => { + return relationship.role.name; +} + +/** + * @return {(relationship: Object) => string} + * */ +const getAddSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { + const compMod = relationship.role.compMod; + + // const parentDBName = replaceSpaceWithUnderscore(compMod.parent.bucketName); + // const parentEntityName = replaceSpaceWithUnderscore(compMod.parent.collectionName); + // const parentTableName = getFullEntityName(parentDBName, parentEntityName); + // + // const childDBName = replaceSpaceWithUnderscore(compMod.child.bucketName); + // const childEntityName = replaceSpaceWithUnderscore(compMod.child.collectionName); + // const childTableName = getFullEntityName(childDBName, childEntityName); + // + // const relationshipName = compMod.name?.new || getRelationshipName(relationship) || ''; + // + // const addFkConstraintDto = { + // childTableName, + // fkConstraintName: prepareName(relationshipName), + // childColumns: compMod.child.fieldNames.map(name => prepareName(name)), + // parentTableName, + // parentColumns: compMod.parent.fieldNames.map(name => prepareName(name)), + // }; + // return ddlProvider.addFkConstraint(addFkConstraintDto); + + return ''; +} + +/** + * @param relationship {Object} + * @return boolean + * */ +const canRelationshipBeAdded = (relationship) => { + const compMod = relationship.role.compMod; + if (!compMod) { + return false; + } + return [ + (compMod.name?.new || getRelationshipName(relationship)), + compMod.parent?.bucketName, + compMod.parent?.collectionName, + compMod.parent?.fieldNames?.length, + compMod.child?.bucketName, + compMod.child?.collectionName, + compMod.child?.fieldNames?.length, + ].every(property => Boolean(property)); +} + +/** + * @return {(addedRelationships: Array) => Array} + * */ +const getAddForeignKeyScriptDtos = (ddlProvider, _) => (addedRelationships) => { + return addedRelationships + .filter((relationship) => canRelationshipBeAdded(relationship)) + .map(relationship => { + const script = getAddSingleForeignKeyScript(ddlProvider, _)(relationship); + const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); + return AlterScriptDto.getInstance([script], isActivated, false); + }) + .filter(Boolean) + .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); +} + +/** + * @return {(relationship: Object) => string} + * */ +const getDeleteSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { + const { getNamePrefixedWithSchemaName, wrapInQuotes } = require('../../utils/general')(_); + const compMod = relationship.role.compMod; + + const childBucketName = compMod.child.bucketName; + const childEntityName = compMod.child.collectionName; + const ddlChildEntityName = getNamePrefixedWithSchemaName(childEntityName, childBucketName); + + const relationshipName = compMod.name?.old || getRelationshipName(relationship) || ''; + const ddlRelationshipName = wrapInQuotes(relationshipName); + return ddlProvider.dropForeignKey(ddlChildEntityName, ddlRelationshipName); +} + +const canRelationshipBeDeleted = (relationship) => { + const compMod = relationship.role.compMod; + if (!compMod) { + return false; + } + return [ + (compMod.name?.old || getRelationshipName(relationship)), + compMod.child?.bucketName, + compMod.child?.collectionName, + ].every(property => Boolean(property)); +} + +/** + * @return {(deletedRelationships: Array) => Array} + * */ +const getDeleteForeignKeyScriptDtos = (ddlProvider, _) => (deletedRelationships) => { + return deletedRelationships + .filter((relationship) => canRelationshipBeDeleted(relationship)) + .map(relationship => { + const script = getDeleteSingleForeignKeyScript(ddlProvider, _)(relationship); + const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); + return AlterScriptDto.getInstance([script], isActivated, true); + }) + .filter(Boolean) + .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); +} + +/** + * @return {(modifiedRelationships: Array) => Array} + * */ +const getModifyForeignKeyScriptDtos = (ddlProvider, _) => (modifiedRelationships) => { + return modifiedRelationships + .filter(relationship => canRelationshipBeAdded(relationship) && canRelationshipBeDeleted(relationship)) + .map(relationship => { + const deleteScript = getDeleteSingleForeignKeyScript(ddlProvider, _)(relationship); + const addScript = getAddSingleForeignKeyScript(ddlProvider, _)(relationship); + const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); + return AlterScriptDto.getDropAndRecreateInstance(deleteScript, addScript, isActivated); + }) + .filter(Boolean) + .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); +} + +module.exports = { + getDeleteForeignKeyScriptDtos, + getModifyForeignKeyScriptDtos, + getAddForeignKeyScriptDtos, +} diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js index 22b2dea..f316599 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js @@ -1,7 +1,7 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); /** - * @return {(jsonSchema: Object) => AlterScriptDto} + * @return {(jsonSchema: Object) => AlterScriptDto | undefined} * */ const getCreateUdtScriptDto = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => @@ -48,7 +48,7 @@ const getCreateUdtScriptDto = /** - * @return {(udt: Object) => AlterScriptDto} + * @return {(udt: Object) => AlterScriptDto | undefined} * */ const getDeleteUdtScriptDto = app => udt => { const _ = app.require('lodash'); @@ -102,7 +102,8 @@ const getAddColumnToTypeScriptDtos = }) .map(ddlProvider.convertColumnDefinition) .map(columnDefinition => ddlProvider.alterTypeAddAttribute(fullName, columnDefinition)) - .map(script => AlterScriptDto.getInstance([script], true, false)); + .map(script => AlterScriptDto.getInstance([script], true, false)) + .filter(Boolean); }; /** @@ -119,7 +120,8 @@ const getDeleteColumnFromTypeScriptDtos = app => udt => { return _.toPairs(udt.properties) .filter(([name, jsonSchema]) => !jsonSchema.compMod) .map(([name]) => ddlProvider.alterTypeDropAttribute(fullName, wrapInQuotes(name))) - .map(script => AlterScriptDto.getInstance([script], true, true)); + .map(script => AlterScriptDto.getInstance([script], true, true)) + .filter(Boolean); }; /** @@ -151,7 +153,10 @@ const getModifyColumnOfTypeScriptDtos = app => udt => { }) .map(script => AlterScriptDto.getInstance([script], true, false)); - return [...renameColumnScripts, ...changeTypeScripts]; + return [ + ...renameColumnScripts, + ...changeTypeScripts + ].filter(Boolean); }; module.exports = { diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js index 345403a..4d69fe4 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js @@ -2,7 +2,7 @@ const {getModifyViewCommentsScriptDtos} = require("./viewHelpers/commentsHelper" const {AlterScriptDto} = require("../types/AlterScriptDto"); /** - * @return {(view: Object) => AlterScriptDto} + * @return {(view: Object) => AlterScriptDto | undefined} * */ const getAddViewScriptDto = app => view => { const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); @@ -19,7 +19,7 @@ const getAddViewScriptDto = app => view => { }; /** - * @return {(view: Object) => AlterScriptDto} + * @return {(view: Object) => AlterScriptDto | undefined} * */ const getDeleteViewScriptDto = app => view => { const _ = app.require('lodash'); @@ -42,7 +42,7 @@ const getModifyViewScriptDtos = (app) => (view) => { return [ ...modifyCommentsScriptDtos, - ]; + ].filter(Boolean); } module.exports = { diff --git a/forward_engineering/alterScript/types/AlterScriptDto.js b/forward_engineering/alterScript/types/AlterScriptDto.js index fb0c973..2cc8551 100644 --- a/forward_engineering/alterScript/types/AlterScriptDto.js +++ b/forward_engineering/alterScript/types/AlterScriptDto.js @@ -59,6 +59,38 @@ class AlterScriptDto { })) } } + + /** + * @param dropScript {string | undefined} + * @param createScript {string | undefined} + * @param isActivated {boolean} + * @return {AlterScriptDto | undefined} + * */ + static getDropAndRecreateInstance(dropScript, createScript, isActivated) { + /** + * @type {ModificationScript[]} + * */ + const scriptModificationDtos = []; + if (Boolean(dropScript)) { + scriptModificationDtos.push({ + isDropScript: true, + script: dropScript, + }) + } + if (Boolean(createScript)) { + scriptModificationDtos.push({ + isDropScript: false, + script: createScript, + }); + } + if (!scriptModificationDtos?.length) { + return undefined; + } + return { + isActivated, + scripts: scriptModificationDtos, + } + } } module.exports = { diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 56a33c7..8c34c89 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -1046,5 +1046,18 @@ module.exports = (baseProvider, options, app) => { } return assignTemplates(templates.alterTypeChangeAttributeType, templateConfig); }, + + /** + * @param tableName {string} + * @param fkConstraintName {string} + * @return string + * */ + dropForeignKey(tableName, fkConstraintName) { + const templateConfig = { + tableName, + fkConstraintName, + } + return assignTemplates(templates.dropForeignKey, templateConfig); + } }; }; diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js index c7e8a2c..4fa0468 100644 --- a/forward_engineering/ddlProvider/templates.js +++ b/forward_engineering/ddlProvider/templates.js @@ -39,6 +39,8 @@ module.exports = { createForeignKey: 'ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};', + dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName}', + dropTable: 'DROP TABLE IF EXISTS ${tableName};', addColumn: 'ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};', From 06f98b51a33ec1400e1982171595f962bde5aa36 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 31 May 2023 09:51:17 +0300 Subject: [PATCH 11/22] Fixed missing semicolon in "drop fk" template --- forward_engineering/ddlProvider/templates.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js index 4fa0468..f932d55 100644 --- a/forward_engineering/ddlProvider/templates.js +++ b/forward_engineering/ddlProvider/templates.js @@ -39,7 +39,7 @@ module.exports = { createForeignKey: 'ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};', - dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName}', + dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};', dropTable: 'DROP TABLE IF EXISTS ${tableName};', From bffd112b44794f80d2caaa314fd32fc6b926de46 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 31 May 2023 13:02:21 +0300 Subject: [PATCH 12/22] Added types for "alter relationships" functionality --- .../alterRelationshipsHelper.js | 91 +++--- .../alterScript/types/AlterRelationshipDto.js | 274 ++++++++++++++++++ .../ddlProvider/ddlProvider.js | 73 ++++- forward_engineering/utils/general.js | 5 + 4 files changed, 398 insertions(+), 45 deletions(-) create mode 100644 forward_engineering/alterScript/types/AlterRelationshipDto.js diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js index e7005cd..83f98d1 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js @@ -1,8 +1,11 @@ const {AlterScriptDto} = require("../types/AlterScriptDto"); +const { + AlterRelationshipDto +} = require('../types/AlterRelationshipDto'); /** - * @param relationship {Object} + * @param relationship {AlterRelationshipDto} * @return string * */ const getRelationshipName = (relationship) => { @@ -10,35 +13,41 @@ const getRelationshipName = (relationship) => { } /** - * @return {(relationship: Object) => string} + * @return {(relationship: AlterRelationshipDto) => string} + * */ +const getFullChildTableName = (_) => (relationship) => { + const {getNamePrefixedWithSchemaName} = require('../../utils/general')(_); + const compMod = relationship.role.compMod; + + const childBucketName = compMod.child.bucket.name; + const childEntityName = compMod.child.collection.name; + return getNamePrefixedWithSchemaName(childEntityName, childBucketName); +} + +/** + * @return {(relationship: AlterRelationshipDto) => string} * */ const getAddSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { const compMod = relationship.role.compMod; - - // const parentDBName = replaceSpaceWithUnderscore(compMod.parent.bucketName); - // const parentEntityName = replaceSpaceWithUnderscore(compMod.parent.collectionName); - // const parentTableName = getFullEntityName(parentDBName, parentEntityName); - // - // const childDBName = replaceSpaceWithUnderscore(compMod.child.bucketName); - // const childEntityName = replaceSpaceWithUnderscore(compMod.child.collectionName); - // const childTableName = getFullEntityName(childDBName, childEntityName); - // - // const relationshipName = compMod.name?.new || getRelationshipName(relationship) || ''; - // - // const addFkConstraintDto = { - // childTableName, - // fkConstraintName: prepareName(relationshipName), - // childColumns: compMod.child.fieldNames.map(name => prepareName(name)), - // parentTableName, - // parentColumns: compMod.parent.fieldNames.map(name => prepareName(name)), - // }; - // return ddlProvider.addFkConstraint(addFkConstraintDto); - - return ''; + + const relationshipName = compMod.name?.new || getRelationshipName(relationship) || ''; + + return ddlProvider.createForeignKey({ + name: relationshipName, + foreignKey: compMod.child.collection.fkFields, + primaryKey: compMod.parent.collection.fkFields, + customProperties: compMod.customProperties?.new, + foreignTable: compMod.child.collection.name, + foreignSchemaName: compMod.child.bucket.name, + foreignTableActivated: compMod.child.collection.isActivated, + primaryTable: compMod.parent.collection.name, + primarySchemaName: compMod.parent.bucket.name, + primaryTableActivated: compMod.parent.collection.isActivated, + }).statement; } /** - * @param relationship {Object} + * @param relationship {AlterRelationshipDto} * @return boolean * */ const canRelationshipBeAdded = (relationship) => { @@ -48,17 +57,17 @@ const canRelationshipBeAdded = (relationship) => { } return [ (compMod.name?.new || getRelationshipName(relationship)), - compMod.parent?.bucketName, - compMod.parent?.collectionName, - compMod.parent?.fieldNames?.length, - compMod.child?.bucketName, - compMod.child?.collectionName, - compMod.child?.fieldNames?.length, + compMod.parent?.bucket, + compMod.parent?.collection, + compMod.parent?.collection?.fkFields?.length, + compMod.child?.bucket, + compMod.child?.collection, + compMod.child?.collection?.fkFields?.length, ].every(property => Boolean(property)); } /** - * @return {(addedRelationships: Array) => Array} + * @return {(addedRelationships: Array) => Array} * */ const getAddForeignKeyScriptDtos = (ddlProvider, _) => (addedRelationships) => { return addedRelationships @@ -73,21 +82,23 @@ const getAddForeignKeyScriptDtos = (ddlProvider, _) => (addedRelationships) => { } /** - * @return {(relationship: Object) => string} + * @return {(relationship: AlterRelationshipDto) => string} * */ const getDeleteSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { - const { getNamePrefixedWithSchemaName, wrapInQuotes } = require('../../utils/general')(_); + const {wrapInQuotes} = require('../../utils/general')(_); const compMod = relationship.role.compMod; - const childBucketName = compMod.child.bucketName; - const childEntityName = compMod.child.collectionName; - const ddlChildEntityName = getNamePrefixedWithSchemaName(childEntityName, childBucketName); + const ddlChildEntityName = getFullChildTableName(_)(relationship); const relationshipName = compMod.name?.old || getRelationshipName(relationship) || ''; const ddlRelationshipName = wrapInQuotes(relationshipName); return ddlProvider.dropForeignKey(ddlChildEntityName, ddlRelationshipName); } +/** + * @param relationship {AlterRelationshipDto} + * @return {boolean} + * */ const canRelationshipBeDeleted = (relationship) => { const compMod = relationship.role.compMod; if (!compMod) { @@ -95,13 +106,13 @@ const canRelationshipBeDeleted = (relationship) => { } return [ (compMod.name?.old || getRelationshipName(relationship)), - compMod.child?.bucketName, - compMod.child?.collectionName, + compMod.child?.bucket, + compMod.child?.collection, ].every(property => Boolean(property)); } /** - * @return {(deletedRelationships: Array) => Array} + * @return {(deletedRelationships: Array) => Array} * */ const getDeleteForeignKeyScriptDtos = (ddlProvider, _) => (deletedRelationships) => { return deletedRelationships @@ -116,7 +127,7 @@ const getDeleteForeignKeyScriptDtos = (ddlProvider, _) => (deletedRelationships) } /** - * @return {(modifiedRelationships: Array) => Array} + * @return {(modifiedRelationships: Array) => Array} * */ const getModifyForeignKeyScriptDtos = (ddlProvider, _) => (modifiedRelationships) => { return modifiedRelationships diff --git a/forward_engineering/alterScript/types/AlterRelationshipDto.js b/forward_engineering/alterScript/types/AlterRelationshipDto.js new file mode 100644 index 0000000..eee563e --- /dev/null +++ b/forward_engineering/alterScript/types/AlterRelationshipDto.js @@ -0,0 +1,274 @@ +class AlterRelationshipFKField { + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {string} + */ + name +} + +class AlterRelationshipParentDto { + + /** + * @type {{ + * name: string, + * isActivated: boolean + * }} + */ + bucket + + /** + * @type {{ + * name: string, + * isActivated: boolean, + * fkFields: Array + * }} + */ + collection +} + +class AlterRelationshipChildDto { + + /** + * @type {{ + * name: string, + * isActivated: boolean + * }} + */ + bucket + + /** + * @type {{ + * name: string, + * isActivated: boolean, + * fkFields: Array + * }} + */ + collection +} + +class AlterRelationshipCustomProperties { + + /** + * @type {string} + */ + relationshipOnDelete + + /** + * @type {string} + */ + relationshipOnUpdate + + /** + * @type {string} + */ + relationshipMatch + +} + +class AlterRelationshipRoleCompModDto { + + /** + * @type {boolean} + */ + created + + /** + * @type {boolean} + */ + deleted + + /** + * @type {boolean | undefined} + */ + modified + + /** + * @type {AlterRelationshipParentDto} + * */ + parent + + /** + * @type {AlterRelationshipChildDto} + * */ + child + + /** + * @type {{ + * new: string, + * old: string, + * } | undefined} + */ + name + + /** + * @type {{ + * new: string, + * old: string, + * } | undefined} + */ + description + + /** + * @type {{ + * old?: AlterRelationshipCustomProperties, + * new?: AlterRelationshipCustomProperties + * } | undefined} + * */ + customProperties + + /** + * @type {{ + * new?: boolean, + * old?: boolean, + * }} + */ + isActivated +} + +class AlterRelationshipRoleDto { + + /** + * @type {string} + */ + id + + /** + * @type {string} + */ + name + + /** + * @type {"Foreign Key"} + */ + relationshipType + + /** + * @type {Array>} + */ + parentField + + /** + * @type {string} + */ + parentCardinality + + /** + * @type {Array>} + */ + childField + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {string} + */ + childCardinality + + /** + * @type {string} + */ + parentCollection + + /** + * @type {string} + */ + childCollection + + /** + * @type {Object} + */ + hackoladeStyles + + /** + * @type {AlterRelationshipRoleCompModDto} + * */ + compMod + + /** + * @type {"relationship"} + */ + roleType +} + +class AlterRelationshipDto { + + /** + * @type {"object"} + */ + type + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {boolean} + */ + unique + + /** + * @type {"object"} + */ + subtype + + /** + * @type {[ + * "compositePartitionKey", + * "compositePrimaryKey", + * "compositeUniqueKey", + * "triggerUpdateColumns", + * ]} + */ + compositeKey + + /** + * @type {boolean} + */ + compositePartitionKey + + /** + * @type {boolean} + */ + compositePrimaryKey + + /** + * @type {boolean} + */ + compositeUniqueKey + + /** + * @type {boolean} + */ + triggerUpdateColumns + + /** + * @type {AlterRelationshipRoleDto} + */ + role + + /** + * @type {string} + */ + GUID + +} + + +module.exports = { + AlterRelationshipRoleCompModDto, + AlterRelationshipRoleDto, + AlterRelationshipDto, + AlterRelationshipFKField, + AlterRelationshipParentDto, + AlterRelationshipChildDto, + AlterRelationshipCustomProperties +} diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 8c34c89..f3c7de8 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -320,6 +320,36 @@ module.exports = (baseProvider, options, app) => { }); }, + /** + * @param name {string} + * @param isActivated {boolean} + * @param customProperties {{ + * relationshipOnDelete?: string, + * relationshipOnUpdate?: string, + * relationshipMatch?: string, + * }} + * @param primaryTableActivated {boolean} + * @param foreignTableActivated {boolean} + * @param foreignSchemaName {string} + * @param primarySchemaName {string} + * @param primaryTable {string} + * @param primaryKey {Array<{ + * isActivated: boolean, + * name: string, + * }>} + * @param foreignKey {Array<{ + * isActivated: boolean, + * name: string, + * }>} + * @param schemaData {{ + * schemaName: string + * }} + * @param dbData {any} + * @return {{ + * statement: string, + * isActivated: boolean, + * }} + * */ createForeignKeyConstraint( { name, @@ -364,6 +394,37 @@ module.exports = (baseProvider, options, app) => { }; }, + /** + * @param name {string} + * @param isActivated {boolean} + * @param customProperties {{ + * relationshipOnDelete?: string, + * relationshipOnUpdate?: string, + * relationshipMatch?: string, + * }} + * @param primaryTableActivated {boolean} + * @param foreignTableActivated {boolean} + * @param foreignSchemaName {string} + * @param foreignTable {string} + * @param primarySchemaName {string} + * @param primaryTable {string} + * @param primaryKey {Array<{ + * isActivated: boolean, + * name: string, + * }>} + * @param foreignKey {Array<{ + * isActivated: boolean, + * name: string, + * }>} + * @param schemaData {{ + * schemaName: string + * }} + * @param dbData {any} + * @return {{ + * statement: string, + * isActivated: boolean, + * }} + * */ createForeignKey( { name, @@ -376,17 +437,19 @@ module.exports = (baseProvider, options, app) => { foreignSchemaName, primarySchemaName, customProperties, + isActivated }, dbData, schemaData, ) { const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const isActivated = + const isRelationshipActivated = !isAllPrimaryKeysDeactivated && !isAllForeignKeysDeactivated && primaryTableActivated && - foreignTableActivated; + foreignTableActivated && + isActivated; const { foreignOnDelete, foreignOnUpdate, foreignMatch } = additionalPropertiesForForeignKey(customProperties); @@ -395,8 +458,8 @@ module.exports = (baseProvider, options, app) => { primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), foreignTable: getNamePrefixedWithSchemaName(foreignTable, foreignSchemaName || schemaData.schemaName), name: name ? wrapInQuotes(name) : '', - foreignKey: isActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: isActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), + foreignKey: isRelationshipActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), + primaryKey: isRelationshipActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', match: foreignMatch ? ` MATCH ${foreignMatch}` : '', @@ -404,7 +467,7 @@ module.exports = (baseProvider, options, app) => { return { statement: _.trim(foreignKeyStatement), - isActivated, + isActivated: isRelationshipActivated, }; }, diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index b9d32ae..255137a 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -55,6 +55,11 @@ module.exports = _ => { return keys.every(key => _.get(key, 'isActivated', true)); }; + /** + * @param keys {Array<{ + * isActivated: boolean, + * }>} + * */ const checkAllKeysDeactivated = keys => { return keys.length ? keys.every(key => !_.get(key, 'isActivated', true)) : false; }; From 40e7f206d178dfe402ee7dbcff90eaa2b8cde4c6 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 1 Jun 2023 09:49:25 +0300 Subject: [PATCH 13/22] Relationships that exist between deactivated entities are now also deactivated. Deactivated columns are now commented out --- .../alterRelationshipsHelper.js | 44 ++++++++++++------- .../ddlProvider/ddlProvider.js | 22 +++++----- 2 files changed, 38 insertions(+), 28 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js index 83f98d1..a86bbc9 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js @@ -25,9 +25,12 @@ const getFullChildTableName = (_) => (relationship) => { } /** - * @return {(relationship: AlterRelationshipDto) => string} + * @return {(relationship: AlterRelationshipDto) => { + * isActivated: boolean, + * statement: string, + * }} * */ -const getAddSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { +const getAddSingleForeignKeyStatementDto = (ddlProvider, _) => (relationship) => { const compMod = relationship.role.compMod; const relationshipName = compMod.name?.new || getRelationshipName(relationship) || ''; @@ -43,7 +46,8 @@ const getAddSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { primaryTable: compMod.parent.collection.name, primarySchemaName: compMod.parent.bucket.name, primaryTableActivated: compMod.parent.collection.isActivated, - }).statement; + isActivated: Boolean(relationship.role?.compMod?.isActivated?.new), + }); } /** @@ -73,18 +77,20 @@ const getAddForeignKeyScriptDtos = (ddlProvider, _) => (addedRelationships) => { return addedRelationships .filter((relationship) => canRelationshipBeAdded(relationship)) .map(relationship => { - const script = getAddSingleForeignKeyScript(ddlProvider, _)(relationship); - const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); - return AlterScriptDto.getInstance([script], isActivated, false); + const scriptDto = getAddSingleForeignKeyStatementDto(ddlProvider, _)(relationship); + return AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, false); }) .filter(Boolean) .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); } /** - * @return {(relationship: AlterRelationshipDto) => string} + * @return {(relationship: AlterRelationshipDto) => { + * isActivated: boolean, + * statement: string, + * }} * */ -const getDeleteSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { +const getDeleteSingleForeignKeyStatementDto = (ddlProvider, _) => (relationship) => { const {wrapInQuotes} = require('../../utils/general')(_); const compMod = relationship.role.compMod; @@ -92,7 +98,14 @@ const getDeleteSingleForeignKeyScript = (ddlProvider, _) => (relationship) => { const relationshipName = compMod.name?.old || getRelationshipName(relationship) || ''; const ddlRelationshipName = wrapInQuotes(relationshipName); - return ddlProvider.dropForeignKey(ddlChildEntityName, ddlRelationshipName); + const statement = ddlProvider.dropForeignKey(ddlChildEntityName, ddlRelationshipName); + + const isRelationshipActivated = Boolean(relationship.role?.compMod?.isActivated?.new); + const isChildTableActivated = compMod.child.collection.isActivated; + return { + statement, + isActivated: isRelationshipActivated && isChildTableActivated, + } } /** @@ -118,9 +131,8 @@ const getDeleteForeignKeyScriptDtos = (ddlProvider, _) => (deletedRelationships) return deletedRelationships .filter((relationship) => canRelationshipBeDeleted(relationship)) .map(relationship => { - const script = getDeleteSingleForeignKeyScript(ddlProvider, _)(relationship); - const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); - return AlterScriptDto.getInstance([script], isActivated, true); + const scriptDto = getDeleteSingleForeignKeyStatementDto(ddlProvider, _)(relationship); + return AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, true); }) .filter(Boolean) .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); @@ -133,10 +145,10 @@ const getModifyForeignKeyScriptDtos = (ddlProvider, _) => (modifiedRelationships return modifiedRelationships .filter(relationship => canRelationshipBeAdded(relationship) && canRelationshipBeDeleted(relationship)) .map(relationship => { - const deleteScript = getDeleteSingleForeignKeyScript(ddlProvider, _)(relationship); - const addScript = getAddSingleForeignKeyScript(ddlProvider, _)(relationship); - const isActivated = Boolean(relationship.role?.compMod?.isActivated?.new); - return AlterScriptDto.getDropAndRecreateInstance(deleteScript, addScript, isActivated); + const deleteScriptDto = getDeleteSingleForeignKeyStatementDto(ddlProvider, _)(relationship); + const addScriptDto = getAddSingleForeignKeyStatementDto(ddlProvider, _)(relationship); + const isActivated = addScriptDto.isActivated && deleteScriptDto.isActivated; + return AlterScriptDto.getDropAndRecreateInstance(deleteScriptDto.statement, addScriptDto.statement, isActivated); }) .filter(Boolean) .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index f3c7de8..6042372 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -368,12 +368,11 @@ module.exports = (baseProvider, options, app) => { ) { const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const isRelationshipActivated = + const areKeysActivated = !isAllPrimaryKeysDeactivated && !isAllForeignKeysDeactivated && primaryTableActivated && - foreignTableActivated && - isActivated; + foreignTableActivated; const { foreignOnDelete, foreignOnUpdate, foreignMatch } = additionalPropertiesForForeignKey(customProperties); @@ -381,8 +380,8 @@ module.exports = (baseProvider, options, app) => { const foreignKeyStatement = assignTemplates(templates.createForeignKeyConstraint, { primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), name: name ? `CONSTRAINT ${wrapInQuotes(name)}` : '', - foreignKey: isRelationshipActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: isRelationshipActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), + foreignKey: areKeysActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), + primaryKey: areKeysActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', match: foreignMatch ? ` MATCH ${foreignMatch}` : '', @@ -390,7 +389,7 @@ module.exports = (baseProvider, options, app) => { return { statement: _.trim(foreignKeyStatement), - isActivated: isRelationshipActivated, + isActivated: areKeysActivated && isActivated, }; }, @@ -444,12 +443,11 @@ module.exports = (baseProvider, options, app) => { ) { const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const isRelationshipActivated = + const areKeysActivated = !isAllPrimaryKeysDeactivated && !isAllForeignKeysDeactivated && primaryTableActivated && - foreignTableActivated && - isActivated; + foreignTableActivated; const { foreignOnDelete, foreignOnUpdate, foreignMatch } = additionalPropertiesForForeignKey(customProperties); @@ -458,8 +456,8 @@ module.exports = (baseProvider, options, app) => { primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), foreignTable: getNamePrefixedWithSchemaName(foreignTable, foreignSchemaName || schemaData.schemaName), name: name ? wrapInQuotes(name) : '', - foreignKey: isRelationshipActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: isRelationshipActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), + foreignKey: areKeysActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), + primaryKey: areKeysActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', match: foreignMatch ? ` MATCH ${foreignMatch}` : '', @@ -467,7 +465,7 @@ module.exports = (baseProvider, options, app) => { return { statement: _.trim(foreignKeyStatement), - isActivated: isRelationshipActivated, + isActivated: areKeysActivated && isActivated, }; }, From fd26c166464822abdab438240891d291786a6f6a Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 1 Jun 2023 20:06:00 +0300 Subject: [PATCH 14/22] Started to work on pk constraints --- .../alterScriptHelpers/alterEntityHelper.js | 9 +- .../entityHelpers/checkConstraintHelper.js | 10 +- .../entityHelpers/commentsHelper.js | 7 +- .../entityHelpers/primaryKeyHelper.js | 182 +++++++++ .../alterScript/types/AlterCollectionDto.js | 379 ++++++++++++++++++ forward_engineering/utils/general.js | 26 +- 6 files changed, 598 insertions(+), 15 deletions(-) create mode 100644 forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js create mode 100644 forward_engineering/alterScript/types/AlterCollectionDto.js diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js index 0c86e01..c67fe2c 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js @@ -5,10 +5,12 @@ const {getModifyNonNullColumnsScriptDtos} = require("./columnHelpers/nonNullCons const {getModifiedCommentOnColumnScriptDtos} = require("./columnHelpers/commentsHelper"); const {getRenameColumnScriptDtos} = require("./columnHelpers/renameColumnHelper"); const {AlterScriptDto} = require("../types/AlterScriptDto"); +const {AlterCollectionDto} = require('../types/AlterCollectionDto'); +const {getModifyPkConstraintsScriptDtos} = require("./entityHelpers/primaryKeyHelper"); /** - * @return {(collection: Object) => AlterScriptDto | undefined} + * @return {(collection: AlterCollectionDto) => AlterScriptDto | undefined} * */ const getAddCollectionScriptDto = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => @@ -58,7 +60,7 @@ const getAddCollectionScriptDto = }; /** - * @return {(collection: Object) => AlterScriptDto | undefined} + * @return {(collection: AlterCollectionDto) => AlterScriptDto | undefined} * */ const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); @@ -71,7 +73,7 @@ const getDeleteCollectionScriptDto = app => collection => { }; /** - * @return {(collection: Object) => AlterScriptDto[]} + * @return {(collection: AlterCollectionDto) => AlterScriptDto[]} * */ const getModifyCollectionScriptDtos = (app) => (collection) => { const _ = app.require('lodash'); @@ -79,6 +81,7 @@ const getModifyCollectionScriptDtos = (app) => (collection) => { const modifyCheckConstraintScriptDtos = getModifyCheckConstraintScriptDtos(_, ddlProvider)(collection); const modifyCommentScriptDtos = getModifyEntityCommentsScriptDtos(_, ddlProvider)(collection); + const modifyPKConstraintDtos = getModifyPkConstraintsScriptDtos(_, ddlProvider)(collection); return [ ...modifyCheckConstraintScriptDtos, ...modifyCommentScriptDtos diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index 7ee641f..cdc0601 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js @@ -1,3 +1,6 @@ +const {AlterCollectionDto} = require('../../types/AlterCollectionDto'); +const {AlterScriptDto} = require("../../types/AlterScriptDto"); + /** * @typedef {{ * id: string, @@ -11,11 +14,8 @@ * }} CheckConstraintHistoryEntry * */ - -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - /** - * @return {(collection: Object) => Array} + * @return {(collection: AlterCollectionDto) => Array} * */ const mapCheckConstraintNamesToChangeHistory = (_) => (collection) => { const checkConstraintHistory = collection?.compMod?.chkConstr; @@ -98,7 +98,7 @@ const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistor } /** - * @return {(collection: Object) => Array} + * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyCheckConstraintScriptDtos = (_, ddlProvider) => (collection) => { const {getFullTableName} = require('../../../utils/general')(_); diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js index 6d843c6..7b9fbd6 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -1,7 +1,8 @@ const {AlterScriptDto} = require("../../types/AlterScriptDto"); +const {AlterCollectionDto} = require('../../types/AlterCollectionDto'); /** - * @return {(collection: Object) => AlterScriptDto} + * @return {(collection: AlterCollectionDto) => AlterScriptDto} */ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { const {getFullTableName, wrapComment} = require('../../../utils/general')(_); @@ -24,7 +25,7 @@ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) } /** - * @return {(collection: Object) => AlterScriptDto} + * @return {(collection: AlterCollectionDto) => AlterScriptDto} */ const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { const {getFullTableName} = require('../../../utils/general')(_); @@ -46,7 +47,7 @@ const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) } /** - * @return {(collection: Object) => Array} + * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyEntityCommentsScriptDtos = (_, ddlProvider) => collection => { const updatedCommentScript = getUpdatedCommentOnCollectionScriptDto(_, ddlProvider)(collection); diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js new file mode 100644 index 0000000..303f929 --- /dev/null +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -0,0 +1,182 @@ +const { AlterScriptDto } = require('../../types/AlterScriptDto'); +const {AlterCollectionDto, AlterCollectionColumnDto,AlterCollectionRoleCompModPKDto} = require('../../types/AlterCollectionDto'); + + +/** + * @return {(collection: AlterCollectionDto, guid: string) => AlterCollectionColumnDto | undefined} + * */ +const getPropertyByGuid = (_) => (collection, guid) => { + const propertyInArray = _.toPairs(collection?.role?.properties) + .filter(([name, jsonSchema]) => jsonSchema.GUID === guid) + .map(([name, jsonSchema]) => jsonSchema); + if (!propertyInArray.length) { + return undefined; + } + return propertyInArray[0]; +} + +/** + * @return {(collection: AlterCollectionDto, guids: string[]) => Array} + * */ +const getPropertiesByGuids = (_) => (collection, guids) => { + return guids + .map(guid => getPropertyByGuid(_)(collection, guid)) + .filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => boolean} + * */ +const didCompositePkChange = (_) => (collection) => { + const pkDto = collection?.role?.compMod?.primaryKey || {}; + const newPrimaryKeys = pkDto.new || []; + const oldPrimaryKeys = pkDto.old || []; + if (newPrimaryKeys.length !== oldPrimaryKeys.length) { + return true; + } + if (newPrimaryKeys.length === 0 && oldPrimaryKeys.length === 0) { + return false; + } + const areKeyArraysEqual = _(oldPrimaryKeys).differenceWith(newPrimaryKeys, _.isEqual).isEmpty(); + return !areKeyArraysEqual; +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getAddCompositePkScripts = (_, ddlProvider) => (collection) => { + const didPkChange = didCompositePkChange(_)(collection); + if (!didPkChange) { + return [] + } + const fullTableName = generateFullEntityName(collection); + const constraintName = getEntityNameFromCollection(collection) + '_pk'; + const pkDto = collection?.role?.compMod?.primaryKey || {}; + const newPrimaryKeys = pkDto.new || []; + + return newPrimaryKeys + .map((newPk) => { + /** + * @type {Array} + * */ + const compositePrimaryKey = newPk.compositePrimaryKey || []; + const guidsOfColumnsInPk = compositePrimaryKey.map((compositePkEntry) => compositePkEntry.keyId); + const columnsInPk = getPropertiesByGuids(_)(collection, guidsOfColumnsInPk); + const columnNamesForDDL = columnsInPk.map(column => prepareName(column.compMod.newField.name)); + if (!columnNamesForDDL.length) { + return undefined; + } + return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); + }) + .filter(Boolean) + .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) + .filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { + const didPkChange = didCompositePkChange(_)(collection); + if (!didPkChange) { + return [] + } + const fullTableName = generateFullEntityName(collection); + const pkDto = collection?.role?.compMod?.primaryKey || {}; + const oldPrimaryKeys = pkDto.old || []; + return oldPrimaryKeys + .map(oldPk => ddlProvider.dropPkConstraint(fullTableName)) + .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) + .filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getModifyCompositePkScripts = (_, ddlProvider) => (collection) => { + const dropCompositePkScripts = getDropCompositePkScripts(_, ddlProvider)(collection); + const addCompositePkScripts = getAddCompositePkScripts(_, ddlProvider)(collection); + + return [ + ...dropCompositePkScripts, + ...addCompositePkScripts, + ].filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getAddPkScripts = (_, ddlProvider) => (collection) => { + const { getFullCollectionName, getSchemaOfAlterCollection } = require('../../../utils/general')(_); + const collectionSchema = getSchemaOfAlterCollection(collection); + + const fullTableName = getFullCollectionName(collectionSchema); + const constraintName = getEntityNameFromCollection(collection) + '_pk'; + + return _.toPairs(collection.properties) + .filter(([name, jsonSchema]) => { + const isRegularPrimaryKey = jsonSchema.primaryKey && !jsonSchema.compositePrimaryKey; + const oldName = jsonSchema.compMod.oldField.name; + const wasTheFieldAPrimaryKey = Boolean(collection.role.properties[oldName]?.primaryKey); + return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; + }) + .map(([name, jsonSchema]) => { + const nameForDDl = prepareName(name); + const columnNamesForDDL = [nameForDDl]; + return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); + }) + .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) + .filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getDropPkScripts = (_, ddlProvider) => (collection) => { + const fullTableName = generateFullEntityName(collection); + + return _.toPairs(collection.properties) + .filter(([name, jsonSchema]) => { + const oldName = jsonSchema.compMod.oldField.name; + const oldJsonSchema = collection.role.properties[oldName]; + const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; + + const isNotAPrimaryKey = !jsonSchema.primaryKey && !jsonSchema.compositePrimaryKey; + return wasTheFieldARegularPrimaryKey && isNotAPrimaryKey; + }) + .map(([name, jsonSchema]) => { + return ddlProvider.dropConstraint(fullTableName, ); + }) + .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) + .filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getModifyPkScripts = (_, ddlProvider) => (collection) => { + const dropPkScripts = getDropPkScripts(_, ddlProvider)(collection); + const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); + + return [ + ...dropPkScripts, + ...addPkScripts, + ].filter(Boolean); +} + +/** + * @return {(collection: AlterCollectionDto) => Array} + * */ +const getModifyPkConstraintsScriptDtos = (_, ddlProvider) => (collection) => { + const modifyCompositePkScripts = getModifyCompositePkScripts(_, ddlProvider)(collection); + const modifyPkScripts = getModifyPkScripts(_, ddlProvider)(collection); + + return [ + ...modifyCompositePkScripts, + ...modifyPkScripts, + ].filter(Boolean); +} + +module.exports = { + getModifyPkConstraintsScriptDtos, +} diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js new file mode 100644 index 0000000..64521ca --- /dev/null +++ b/forward_engineering/alterScript/types/AlterCollectionDto.js @@ -0,0 +1,379 @@ +class ColumnCompModField { + + /** + * @type {string} + */ + type + + /** + * @type {string} + */ + name + + /** + * @type {string} + */ + mode +} + +class AlterCollectionColumnCompModDto { + + /** + * @type {ColumnCompModField} + * */ + oldField + + /** + * @type {ColumnCompModField} + * */ + newField + +} + +class AlterCollectionColumnDto { + /** + * @type {string} + */ + type + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {boolean} + */ + primaryKey + + /** + * @type {boolean} + */ + unique + + /** + * @type {string} + */ + mode + + /** + * @type {number} + */ + length + + /** + * @type {[ + * "compositePartitionKey", + * "compositePrimaryKey", + * "compositeUniqueKey", + * "triggerUpdateColumns", + * ]} + */ + compositeKey + + /** + * @type {boolean} + */ + compositePartitionKey + + /** + * @type {boolean} + */ + compositePrimaryKey + + /** + * @type {boolean} + */ + compositeUniqueKey + + /** + * @type {boolean} + */ + triggerUpdateColumns + + /** + * @type {AlterCollectionColumnCompModDto} + * */ + compMod + + /** + * @type {string} + */ + GUID +} + +class AlterCollectionRoleDefinitionDto { + + /** + * @type {string} + */ + id + + /** + * @type {string} + */ + type + + /** + * @type {Array} + */ + properties +} + +class AlterCollectionRoleCompModPKDto { + + /** + * @type {string} + * */ + keyId +} + +class AlterCollectionRoleCompModDto { + /** + * @type {string} + */ + keyspaceName + + /** + * @type {{ + * name: string, + * isActivated: boolean, + * ifNotExist: boolean, + * }} + */ + bucketProperties + + /** + * @type {{ + * new: string, + * old: string, + * }} + */ + collectionName + + /** + * @type {{ + * new: boolean, + * old: boolean, + * }} + */ + isActivated + + /** + * @type {{ + * new: string, + * old: string, + * }} + */ + bucketId + + /** + * @type {{ + * new: boolean, + * old: boolean, + * }} + */ + ifNotExist + + /** + * @type {{ + * new: string, + * old: string, + * }} + */ + on_commit + + /** + * @type {{ + * new: Array<{ + * compositePrimaryKey: AlterCollectionRoleCompModPKDto[], + * }>, + * old: Array<{ + * compositePrimaryKey: AlterCollectionRoleCompModPKDto[], + * }>, + * }} + */ + primaryKey + + /** + * @type {{ + * new: string, + * old: string, + * }} + */ + table_tablespace_name + + /** + * @type {Array<{ + * [propertyName: string]: AlterCollectionColumnDto + * }>} + */ + newProperties +} + +class AlterCollectionRoleDto { + + /** + * @type {string} + */ + id + + /** + * @type {"object"} + */ + type + + /** + * @type {string} + */ + collectionName + + /** + * @type {{ + * [propertyName: string]: AlterCollectionColumnDto + * }} + */ + properties + + /** + * @type {AlterCollectionRoleDefinitionDto} + * */ + definitions + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {boolean} + */ + additionalProperties + + /** + * @type {boolean} + */ + memory_optimized + + /** + * @type {Array} + */ + collectionUsers + + /** + * @type {boolean} + */ + ifNotExist + + /** + * @type {string} + */ + on_commit + + /** + * @type {string} + */ + table_tablespace_name + + /** + * @type {string} + */ + bucketId + + /** + * @type {AlterCollectionRoleCompModDto} + * */ + compMod + + /** + * @type {string} + */ + name + + /** + * @type {"entity"} + */ + roleType + + /** + * @type {Array} + */ + patternProperties +} + +class AlterCollectionDto { + + /** + * @type {"object"} + */ + type + + /** + * @type {boolean} + */ + isActivated + + /** + * @type {boolean} + */ + unique + + /** + * @type {"object"} + */ + subtype + + /** + * @type {{ + * [preopertyName: string]: AlterCollectionColumnDto + * }} + * */ + properties + + /** + * @type {[ + * "compositePartitionKey", + * "compositePrimaryKey", + * "compositeUniqueKey", + * "triggerUpdateColumns", + * ]} + */ + compositeKey + + /** + * @type {boolean} + */ + compositePartitionKey + + /** + * @type {boolean} + */ + compositePrimaryKey + + /** + * @type {boolean} + */ + compositeUniqueKey + + /** + * @type {boolean} + */ + triggerUpdateColumns + + /** + * @type {AlterCollectionRoleDto} + * */ + role + + /** + * @type {string} + */ + GUID +} + +module.exports = { + AlterCollectionDto, + AlterCollectionRoleDto, + AlterCollectionColumnDto, + AlterCollectionRoleCompModPKDto, +} diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index 255137a..1438f59 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -7,6 +7,8 @@ * the agreement/contract under which the software has been supplied. */ +const {AlterCollectionDto, AlterCollectionRoleDto} = require('../alterScript/types/AlterCollectionDto'); + const {ReservedWordsAsArray} = require("../enums/reservedWords"); const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; @@ -40,6 +42,24 @@ module.exports = _ => { return Object.keys(types).map(_.toLower).includes(_.toLower(type)); }; + /** + * @param collection {AlterCollectionDto} + * @return {AlterCollectionDto & AlterCollectionRoleDto} + * */ + const getSchemaOfAlterCollection = (collection) => { + return {...collection, ...(_.omit(collection?.role, 'properties') || {})}; + } + + /** + * @param collectionSchema {AlterCollectionDto & AlterCollectionRoleDto} + * @return {string} + * */ + const getFullCollectionName = (collectionSchema) => { + const collectionName = getEntityName(collectionSchema); + const bucketName = collectionSchema.compMod?.keyspaceName; + return getNamePrefixedWithSchemaName(collectionName, bucketName); + } + const clean = obj => Object.entries(obj) .filter(([name, value]) => !_.isNil(value)) @@ -100,8 +120,6 @@ module.exports = _ => { }; const getFullTableName = (collection) => { - const {getNamePrefixedWithSchemaName} = require('../utils/general')(_); - const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; const tableName = getEntityName(collectionSchema); const schemaName = collectionSchema.compMod?.keyspaceName; @@ -116,8 +134,6 @@ module.exports = _ => { } const getFullViewName = (view) => { - const {getNamePrefixedWithSchemaName} = require('../utils/general')(_); - const viewSchema = {...view, ...(_.omit(view?.role, 'properties') || {})}; const viewName = getViewName(viewSchema); const schemaName = viewSchema.compMod?.keyspaceName; @@ -249,5 +265,7 @@ module.exports = _ => { wrapInQuotes, getColumnsList, getViewData, + getSchemaOfAlterCollection, + getFullCollectionName }; }; From b8a380bb419297d6bbb84170892d3583fffdd22e Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 2 Jun 2023 12:53:00 +0300 Subject: [PATCH 15/22] Added ability to DROP regular pk constraints (with and without extra options) --- .../entityHelpers/primaryKeyHelper.js | 78 +++++-- .../alterScript/types/AlterCollectionDto.js | 17 ++ .../ddlHelpers/constraintsHelper.js | 206 ++++++++++-------- .../ddlProvider/ddlProvider.js | 43 +++- forward_engineering/ddlProvider/templates.js | 2 + 5 files changed, 240 insertions(+), 106 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 303f929..48eb3f1 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -1,5 +1,10 @@ const { AlterScriptDto } = require('../../types/AlterScriptDto'); -const {AlterCollectionDto, AlterCollectionColumnDto,AlterCollectionRoleCompModPKDto} = require('../../types/AlterCollectionDto'); +const { + AlterCollectionDto, + AlterCollectionColumnDto, + AlterCollectionRoleCompModPKDto, + AlterCollectionColumnPrimaryKeyOptionDto +} = require('../../types/AlterCollectionDto'); /** @@ -41,6 +46,14 @@ const didCompositePkChange = (_) => (collection) => { return !areKeyArraysEqual; } +/** + * @param wrapInQuotes {(s: string) => string} + * @return {(entityName: string) => string} + * */ +const getDefaultConstraintName = (wrapInQuotes) => (entityName) => { + return wrapInQuotes(`${entityName}_pk`); +} + /** * @return {(collection: AlterCollectionDto) => Array} * */ @@ -107,11 +120,17 @@ const getModifyCompositePkScripts = (_, ddlProvider) => (collection) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getAddPkScripts = (_, ddlProvider) => (collection) => { - const { getFullCollectionName, getSchemaOfAlterCollection } = require('../../../utils/general')(_); + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes + } = require('../../../utils/general')(_); const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); - const constraintName = getEntityNameFromCollection(collection) + '_pk'; + const entityName = getEntityName(collectionSchema); + const constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { @@ -121,19 +140,40 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; }) .map(([name, jsonSchema]) => { - const nameForDDl = prepareName(name); - const columnNamesForDDL = [nameForDDl]; - return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); + const pkColumns = [{ + name: wrapInQuotes(name), + isActivated: jsonSchema.isActivated, + }] + + return ddlProvider.createKeyConstraint( + fullTableName, + collection.isActivated, + { + name: constraintName, + columns: pkColumns, + include: [], + storageParameters: '', + tablespace: '', + }); }) - .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) + .map(scriptDto => AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, false)) .filter(Boolean); } /** * @return {(collection: AlterCollectionDto) => Array} * */ -const getDropPkScripts = (_, ddlProvider) => (collection) => { - const fullTableName = generateFullEntityName(collection); +const getDropPkScript = (_, ddlProvider) => (collection) => { + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes + } = require('../../../utils/general')(_); + + const collectionSchema = getSchemaOfAlterCollection(collection); + const fullTableName = getFullCollectionName(collectionSchema); + const entityName = getEntityName(collectionSchema); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { @@ -145,7 +185,19 @@ const getDropPkScripts = (_, ddlProvider) => (collection) => { return wasTheFieldARegularPrimaryKey && isNotAPrimaryKey; }) .map(([name, jsonSchema]) => { - return ddlProvider.dropConstraint(fullTableName, ); + const constraintOptions = jsonSchema.primaryKeyOptions; + let constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); + if (constraintOptions?.length && constraintOptions?.length > 0) { + /** + * @type {AlterCollectionColumnPrimaryKeyOptionDto} + * */ + const constraintOption = constraintOptions[0]; + if (constraintOption.constraintName) { + constraintName = wrapInQuotes(constraintOption.constraintName); + } + } + + return ddlProvider.dropPkConstraint(fullTableName, constraintName); }) .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) .filter(Boolean); @@ -155,7 +207,7 @@ const getDropPkScripts = (_, ddlProvider) => (collection) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyPkScripts = (_, ddlProvider) => (collection) => { - const dropPkScripts = getDropPkScripts(_, ddlProvider)(collection); + const dropPkScripts = getDropPkScript(_, ddlProvider)(collection); const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); return [ @@ -168,11 +220,11 @@ const getModifyPkScripts = (_, ddlProvider) => (collection) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyPkConstraintsScriptDtos = (_, ddlProvider) => (collection) => { - const modifyCompositePkScripts = getModifyCompositePkScripts(_, ddlProvider)(collection); + // const modifyCompositePkScripts = getModifyCompositePkScripts(_, ddlProvider)(collection); const modifyPkScripts = getModifyPkScripts(_, ddlProvider)(collection); return [ - ...modifyCompositePkScripts, + // ...modifyCompositePkScripts, ...modifyPkScripts, ].filter(Boolean); } diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js index 64521ca..586a6b6 100644 --- a/forward_engineering/alterScript/types/AlterCollectionDto.js +++ b/forward_engineering/alterScript/types/AlterCollectionDto.js @@ -30,6 +30,18 @@ class AlterCollectionColumnCompModDto { } +class AlterCollectionColumnPrimaryKeyOptionDto { + /** + * @type {string} + * */ + id + + /** + * @type {string} + * */ + constraintName +} + class AlterCollectionColumnDto { /** * @type {string} @@ -86,6 +98,11 @@ class AlterCollectionColumnDto { */ compositeUniqueKey + /** + * @type {Array | undefined} + * */ + primaryKeyOptions + /** * @type {boolean} */ diff --git a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js index 202e755..98f71cf 100644 --- a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js +++ b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js @@ -1,106 +1,128 @@ module.exports = ({ - _, - commentIfDeactivated, - checkAllKeysDeactivated, - assignTemplates, - wrapInQuotes, - getColumnsList, -}) => { - const generateConstraintsString = (dividedConstraints, isParentActivated) => { - const deactivatedItemsAsString = commentIfDeactivated( - (dividedConstraints?.deactivatedItems || []).join(',\n\t'), - { - isActivated: !isParentActivated, - isPartOfLine: true, - }, - ); - const activatedConstraints = dividedConstraints?.activatedItems?.length - ? ',\n\t' + dividedConstraints.activatedItems.join(',\n\t') - : ''; + _, + commentIfDeactivated, + checkAllKeysDeactivated, + assignTemplates, + wrapInQuotes, + getColumnsList, + }) => { + const generateConstraintsString = (dividedConstraints, isParentActivated) => { + const deactivatedItemsAsString = commentIfDeactivated( + (dividedConstraints?.deactivatedItems || []).join(',\n\t'), + { + isActivated: !isParentActivated, + isPartOfLine: true, + }, + ); + const activatedConstraints = dividedConstraints?.activatedItems?.length + ? ',\n\t' + dividedConstraints.activatedItems.join(',\n\t') + : ''; - const deactivatedConstraints = dividedConstraints?.deactivatedItems?.length - ? '\n\t' + deactivatedItemsAsString - : ''; + const deactivatedConstraints = dividedConstraints?.deactivatedItems?.length + ? '\n\t' + deactivatedItemsAsString + : ''; - return activatedConstraints + deactivatedConstraints; - }; + return activatedConstraints + deactivatedConstraints; + }; - const foreignKeysToString = keys => { - if (Array.isArray(keys)) { - const activatedKeys = keys - .filter(key => _.get(key, 'isActivated', true)) - .map(key => wrapInQuotes(_.trim(key.name))); - const deactivatedKeys = keys - .filter(key => !_.get(key, 'isActivated', true)) - .map(key => wrapInQuotes(_.trim(key.name))); - const deactivatedKeysAsString = deactivatedKeys.length - ? commentIfDeactivated(deactivatedKeys, { isActivated: false, isPartOfLine: true }) - : ''; + const foreignKeysToString = keys => { + if (Array.isArray(keys)) { + const activatedKeys = keys + .filter(key => _.get(key, 'isActivated', true)) + .map(key => wrapInQuotes(_.trim(key.name))); + const deactivatedKeys = keys + .filter(key => !_.get(key, 'isActivated', true)) + .map(key => wrapInQuotes(_.trim(key.name))); + const deactivatedKeysAsString = deactivatedKeys.length + ? commentIfDeactivated(deactivatedKeys, {isActivated: false, isPartOfLine: true}) + : ''; - return activatedKeys.join(', ') + deactivatedKeysAsString; - } - return keys; - }; + return activatedKeys.join(', ') + deactivatedKeysAsString; + } + return keys; + }; - const foreignActiveKeysToString = keys => { - return keys.map(key => _.trim(key.name)).join(', '); - }; + const foreignActiveKeysToString = keys => { + return keys.map(key => _.trim(key.name)).join(', '); + }; - const createKeyConstraint = (templates, isParentActivated) => keyData => { - const constraintName = wrapInQuotes(_.trim(keyData.name)); - const isAllColumnsDeactivated = checkAllKeysDeactivated(keyData.columns || []); - const columns = !_.isEmpty(keyData.columns) - ? getColumnsList(keyData.columns, isAllColumnsDeactivated, isParentActivated) - : ''; - const includeNonKey = keyData.include.length - ? ` INCLUDE${getColumnsList(keyData.include, isAllColumnsDeactivated, isParentActivated)}` - : ''; - const storageParameters = keyData.storageParameters ? ` WITH (${keyData.storageParameters})` : ''; - const tablespace = keyData.tablespace ? ` USING INDEX TABLESPACE ${wrapInQuotes(keyData.tablespace)}` : ''; + /** + * @param templates {Object} + * @param isParentActivated {boolean} + * @return {( + * keyData: { + * name: string, + * columns: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * include: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * storageParameters: string, + * tablespace: string, + * } + * ) => { + * statement: string, + * isActivated: boolean, + * }} + * */ + const createKeyConstraint = (templates, isParentActivated) => keyData => { + const constraintName = wrapInQuotes(_.trim(keyData.name)); + const isAllColumnsDeactivated = checkAllKeysDeactivated(keyData.columns || []); + const columns = !_.isEmpty(keyData.columns) + ? getColumnsList(keyData.columns, isAllColumnsDeactivated, isParentActivated) + : ''; + const includeNonKey = keyData.include.length + ? ` INCLUDE${getColumnsList(keyData.include, isAllColumnsDeactivated, isParentActivated)}` + : ''; + const storageParameters = keyData.storageParameters ? ` WITH (${keyData.storageParameters})` : ''; + const tablespace = keyData.tablespace ? ` USING INDEX TABLESPACE ${wrapInQuotes(keyData.tablespace)}` : ''; - return { - statement: assignTemplates(templates.createKeyConstraint, { - constraintName: keyData.name ? `CONSTRAINT ${wrapInQuotes(constraintName)} ` : '', - keyType: keyData.keyType, - columns, - includeNonKey, - storageParameters, - tablespace, - }), - isActivated: !isAllColumnsDeactivated, - }; - }; + return { + statement: assignTemplates(templates.createKeyConstraint, { + constraintName: keyData.name ? `CONSTRAINT ${wrapInQuotes(constraintName)} ` : '', + keyType: keyData.keyType, + columns, + includeNonKey, + storageParameters, + tablespace, + }), + isActivated: !isAllColumnsDeactivated, + }; + }; - const getConstraintsWarnings = (invalidConstraints = []) => { - if (_.isEmpty(invalidConstraints)) { - return ''; - } + const getConstraintsWarnings = (invalidConstraints = []) => { + if (_.isEmpty(invalidConstraints)) { + return ''; + } - return ( - '\n\t' + - invalidConstraints - .map(keyData => { - const constraintName = keyData.name ? ` [constraint name: ${keyData.name}]` : ''; + return ( + '\n\t' + + invalidConstraints + .map(keyData => { + const constraintName = keyData.name ? ` [constraint name: ${keyData.name}]` : ''; - return `-- ${keyData.errorMessage}${constraintName}`; - }) - .join('\n\t') - ); - }; + return `-- ${keyData.errorMessage}${constraintName}`; + }) + .join('\n\t') + ); + }; - const additionalPropertiesForForeignKey = relationship => { - const foreignOnDelete = _.get(relationship, 'relationshipOnDelete', ''); - const foreignOnUpdate = _.get(relationship, 'relationshipOnUpdate', ''); - const foreignMatch = _.get(relationship, 'relationshipMatch', ''); - return { foreignOnDelete, foreignOnUpdate, foreignMatch }; - }; + const additionalPropertiesForForeignKey = relationship => { + const foreignOnDelete = _.get(relationship, 'relationshipOnDelete', ''); + const foreignOnUpdate = _.get(relationship, 'relationshipOnUpdate', ''); + const foreignMatch = _.get(relationship, 'relationshipMatch', ''); + return {foreignOnDelete, foreignOnUpdate, foreignMatch}; + }; - return { - generateConstraintsString, - foreignKeysToString, - foreignActiveKeysToString, - createKeyConstraint, - getConstraintsWarnings, - additionalPropertiesForForeignKey, - }; + return { + generateConstraintsString, + foreignKeysToString, + foreignActiveKeysToString, + createKeyConstraint, + getConstraintsWarnings, + additionalPropertiesForForeignKey, + }; }; diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 6042372..e34c117 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -1119,6 +1119,47 @@ module.exports = (baseProvider, options, app) => { fkConstraintName, } return assignTemplates(templates.dropForeignKey, templateConfig); - } + }, + + /** + * @param tableName {string} + * @param isParentActivated {boolean} + * @param keyData {{ + * name: string, + * columns: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * include: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * storageParameters: string, + * tablespace: string, + * }} + * @return {{ + * statement: string, + * isActivated: boolean, + * }} + * */ + createKeyConstraint(tableName, isParentActivated, keyData) { + const constraintStatement = createKeyConstraint(templates, isParentActivated)(keyData); + return assignTemplates(templates.addPkConstraint, { + constraintStatement, + tableName, + }) + }, + + /** + * @param tableName {string} + * @param constraintName {string} + * */ + dropPkConstraint(tableName, constraintName) { + const templatesConfig = { + tableName, + constraintName, + } + return assignTemplates(templates.dropConstraint, templatesConfig); + }, }; }; diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js index f932d55..fd75612 100644 --- a/forward_engineering/ddlProvider/templates.js +++ b/forward_engineering/ddlProvider/templates.js @@ -41,6 +41,8 @@ module.exports = { dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};', + addPkConstraint: 'ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintStatement}', + dropTable: 'DROP TABLE IF EXISTS ${tableName};', addColumn: 'ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};', From 70a6304729ccacd4c21d8acc598f754f31628685 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 2 Jun 2023 15:03:44 +0300 Subject: [PATCH 16/22] Added support for dropping composite PK constraints (with and without custom name) --- .../alterScriptHelpers/alterEntityHelper.js | 3 +- .../entityHelpers/primaryKeyHelper.js | 91 ++++++++++++------- .../alterScript/types/AlterCollectionDto.js | 33 +++++-- 3 files changed, 85 insertions(+), 42 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js index c67fe2c..87c3ae8 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js @@ -84,7 +84,8 @@ const getModifyCollectionScriptDtos = (app) => (collection) => { const modifyPKConstraintDtos = getModifyPkConstraintsScriptDtos(_, ddlProvider)(collection); return [ ...modifyCheckConstraintScriptDtos, - ...modifyCommentScriptDtos + ...modifyCommentScriptDtos, + ...modifyPKConstraintDtos ].filter(Boolean); } diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 48eb3f1..229eff6 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -58,47 +58,70 @@ const getDefaultConstraintName = (wrapInQuotes) => (entityName) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getAddCompositePkScripts = (_, ddlProvider) => (collection) => { - const didPkChange = didCompositePkChange(_)(collection); - if (!didPkChange) { - return [] - } - const fullTableName = generateFullEntityName(collection); - const constraintName = getEntityNameFromCollection(collection) + '_pk'; - const pkDto = collection?.role?.compMod?.primaryKey || {}; - const newPrimaryKeys = pkDto.new || []; + // const didPkChange = didCompositePkChange(_)(collection); + // if (!didPkChange) { + // return [] + // } + // const fullTableName = generateFullEntityName(collection); + // const constraintName = getEntityNameFromCollection(collection) + '_pk'; + // const pkDto = collection?.role?.compMod?.primaryKey || {}; + // const newPrimaryKeys = pkDto.new || []; + // + // return newPrimaryKeys + // .map((newPk) => { + // /** + // * @type {Array} + // * */ + // const compositePrimaryKey = newPk.compositePrimaryKey || []; + // const guidsOfColumnsInPk = compositePrimaryKey.map((compositePkEntry) => compositePkEntry.keyId); + // const columnsInPk = getPropertiesByGuids(_)(collection, guidsOfColumnsInPk); + // const columnNamesForDDL = columnsInPk.map(column => prepareName(column.compMod.newField.name)); + // if (!columnNamesForDDL.length) { + // return undefined; + // } + // return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); + // }) + // .filter(Boolean) + // .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) + // .filter(Boolean); - return newPrimaryKeys - .map((newPk) => { - /** - * @type {Array} - * */ - const compositePrimaryKey = newPk.compositePrimaryKey || []; - const guidsOfColumnsInPk = compositePrimaryKey.map((compositePkEntry) => compositePkEntry.keyId); - const columnsInPk = getPropertiesByGuids(_)(collection, guidsOfColumnsInPk); - const columnNamesForDDL = columnsInPk.map(column => prepareName(column.compMod.newField.name)); - if (!columnNamesForDDL.length) { - return undefined; - } - return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); - }) - .filter(Boolean) - .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) - .filter(Boolean); + return []; } /** * @return {(collection: AlterCollectionDto) => Array} * */ const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes + } = require('../../../utils/general')(_); + const didPkChange = didCompositePkChange(_)(collection); if (!didPkChange) { - return [] + return []; } - const fullTableName = generateFullEntityName(collection); + + const collectionSchema = getSchemaOfAlterCollection(collection); + const fullTableName = getFullCollectionName(collectionSchema); + const entityName = getEntityName(collectionSchema); + const pkDto = collection?.role?.compMod?.primaryKey || {}; + /** + * @type {AlterCollectionRoleCompModPKDto[]} + * */ const oldPrimaryKeys = pkDto.old || []; + return oldPrimaryKeys - .map(oldPk => ddlProvider.dropPkConstraint(fullTableName)) + .map((oldPk) => { + let constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); + if (oldPk.constraintName) { + constraintName = wrapInQuotes(oldPk.constraintName); + } + return ddlProvider.dropPkConstraint(fullTableName, constraintName); + }) .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) .filter(Boolean); } @@ -108,11 +131,11 @@ const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { * */ const getModifyCompositePkScripts = (_, ddlProvider) => (collection) => { const dropCompositePkScripts = getDropCompositePkScripts(_, ddlProvider)(collection); - const addCompositePkScripts = getAddCompositePkScripts(_, ddlProvider)(collection); + // const addCompositePkScripts = getAddCompositePkScripts(_, ddlProvider)(collection); return [ ...dropCompositePkScripts, - ...addCompositePkScripts, + // ...addCompositePkScripts, ].filter(Boolean); } @@ -208,11 +231,11 @@ const getDropPkScript = (_, ddlProvider) => (collection) => { * */ const getModifyPkScripts = (_, ddlProvider) => (collection) => { const dropPkScripts = getDropPkScript(_, ddlProvider)(collection); - const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); + // const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); return [ ...dropPkScripts, - ...addPkScripts, + // ...addPkScripts, ].filter(Boolean); } @@ -220,11 +243,11 @@ const getModifyPkScripts = (_, ddlProvider) => (collection) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyPkConstraintsScriptDtos = (_, ddlProvider) => (collection) => { - // const modifyCompositePkScripts = getModifyCompositePkScripts(_, ddlProvider)(collection); + const modifyCompositePkScripts = getModifyCompositePkScripts(_, ddlProvider)(collection); const modifyPkScripts = getModifyPkScripts(_, ddlProvider)(collection); return [ - // ...modifyCompositePkScripts, + ...modifyCompositePkScripts, ...modifyPkScripts, ].filter(Boolean); } diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js index 586a6b6..1379dbb 100644 --- a/forward_engineering/alterScript/types/AlterCollectionDto.js +++ b/forward_engineering/alterScript/types/AlterCollectionDto.js @@ -142,7 +142,30 @@ class AlterCollectionRoleCompModPKDto { /** * @type {string} * */ - keyId + id + + /** + * @type {Array<{ + * type: string, + * keyId: string, + * }>} + * */ + compositePrimaryKey + + /** + * @type {string | undefined} + * */ + constraintName + + /** + * @type {string | undefined} + * */ + indexStorageParameters + + /** + * @type {string | undefined} + * */ + indexTablespace } class AlterCollectionRoleCompModDto { @@ -202,12 +225,8 @@ class AlterCollectionRoleCompModDto { /** * @type {{ - * new: Array<{ - * compositePrimaryKey: AlterCollectionRoleCompModPKDto[], - * }>, - * old: Array<{ - * compositePrimaryKey: AlterCollectionRoleCompModPKDto[], - * }>, + * new: Array, + * old: Array, * }} */ primaryKey From 90750018c0217a116d2ea792c233f020d4ade3e7 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 2 Jun 2023 16:17:57 +0300 Subject: [PATCH 17/22] Added support for adding non-composite PK constraints --- .../entityHelpers/primaryKeyHelper.js | 161 +++++++++++------- .../alterScript/types/AlterCollectionDto.js | 17 ++ .../ddlHelpers/constraintsHelper.js | 1 + .../ddlProvider/ddlProvider.js | 15 +- forward_engineering/ddlProvider/templates.js | 2 +- 5 files changed, 133 insertions(+), 63 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 229eff6..2f64893 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -1,4 +1,4 @@ -const { AlterScriptDto } = require('../../types/AlterScriptDto'); +const {AlterScriptDto} = require('../../types/AlterScriptDto'); const { AlterCollectionDto, AlterCollectionColumnDto, @@ -6,29 +6,6 @@ const { AlterCollectionColumnPrimaryKeyOptionDto } = require('../../types/AlterCollectionDto'); - -/** - * @return {(collection: AlterCollectionDto, guid: string) => AlterCollectionColumnDto | undefined} - * */ -const getPropertyByGuid = (_) => (collection, guid) => { - const propertyInArray = _.toPairs(collection?.role?.properties) - .filter(([name, jsonSchema]) => jsonSchema.GUID === guid) - .map(([name, jsonSchema]) => jsonSchema); - if (!propertyInArray.length) { - return undefined; - } - return propertyInArray[0]; -} - -/** - * @return {(collection: AlterCollectionDto, guids: string[]) => Array} - * */ -const getPropertiesByGuids = (_) => (collection, guids) => { - return guids - .map(guid => getPropertyByGuid(_)(collection, guid)) - .filter(Boolean); -} - /** * @return {(collection: AlterCollectionDto) => boolean} * */ @@ -47,11 +24,11 @@ const didCompositePkChange = (_) => (collection) => { } /** - * @param wrapInQuotes {(s: string) => string} - * @return {(entityName: string) => string} + * @param entityName {string} + * @return {string} * */ -const getDefaultConstraintName = (wrapInQuotes) => (entityName) => { - return wrapInQuotes(`${entityName}_pk`); +const getDefaultConstraintName = (entityName) => { + return `${entityName}_pk`; } /** @@ -116,7 +93,7 @@ const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { return oldPrimaryKeys .map((oldPk) => { - let constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); + let constraintName = getDefaultConstraintName(entityName); if (oldPk.constraintName) { constraintName = wrapInQuotes(oldPk.constraintName); } @@ -139,6 +116,97 @@ const getModifyCompositePkScripts = (_, ddlProvider) => (collection) => { ].filter(Boolean); } +/** + * @param columnJsonSchema {AlterCollectionColumnDto} + * @param entityName {string} + * @return {string} + * */ +const getConstraintNameForRegularPk = (columnJsonSchema, entityName) => { + const constraintOptions = columnJsonSchema.primaryKeyOptions; + if (constraintOptions?.length && constraintOptions?.length > 0) { + /** + * @type {AlterCollectionColumnPrimaryKeyOptionDto} + * */ + const constraintOption = constraintOptions[0]; + if (constraintOption.constraintName) { + return constraintOption.constraintName; + } + } + return getDefaultConstraintName(entityName); +} + +/** + * @param _ + * @param wrapInQuotes {(s: string) => string } + * @return {( + * name: string, + * columnJsonSchema: AlterCollectionColumnDto, + * entityName: string, + * entityJsonSchema: AlterCollectionDto, + * ) => { + * name: string, + * keyType: string, + * columns: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * include: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * storageParameters: string, + * tablespace: string, + * } + * } + * */ +const getCreateRegularPKDDLProviderConfig = (_, wrapInQuotes) => ( + columnName, + columnJsonSchema, + entityName, + entityJsonSchema +) => { + const constraintName = getConstraintNameForRegularPk(columnJsonSchema, entityName); + const pkColumns = [{ + name: wrapInQuotes(columnName), + isActivated: columnJsonSchema.isActivated, + }]; + + let storageParameters = ''; + let indexTablespace = ''; + let includeColumns = []; + const constraintOptions = columnJsonSchema.primaryKeyOptions; + if (constraintOptions?.length && constraintOptions?.length > 0) { + /** + * @type {AlterCollectionColumnPrimaryKeyOptionDto} + * */ + const constraintOption = constraintOptions[0]; + if (constraintOption.indexStorageParameters) { + storageParameters = constraintOption.indexStorageParameters; + } + if (constraintOption.indexTablespace) { + indexTablespace = constraintOption.indexTablespace; + } + if (constraintOption.indexInclude) { + includeColumns = _.toPairs(entityJsonSchema.properties) + .filter(([name, jsonSchema]) => Boolean(constraintOption.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.id))) + .map(([name, jsonSchema]) => ({ + name, + isActivated: jsonSchema.isActivated, + })); + } + } + + return { + name: constraintName, + keyType: 'PRIMARY KEY', + columns: pkColumns, + include: includeColumns, + storageParameters, + tablespace: indexTablespace, + } +} + + /** * @return {(collection: AlterCollectionDto) => Array} * */ @@ -149,11 +217,10 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { getEntityName, wrapInQuotes } = require('../../../utils/general')(_); - const collectionSchema = getSchemaOfAlterCollection(collection); + const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); const entityName = getEntityName(collectionSchema); - const constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { @@ -163,21 +230,12 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; }) .map(([name, jsonSchema]) => { - const pkColumns = [{ - name: wrapInQuotes(name), - isActivated: jsonSchema.isActivated, - }] - + const ddlConfig = getCreateRegularPKDDLProviderConfig(_, wrapInQuotes)(name, jsonSchema, entityName, collection); return ddlProvider.createKeyConstraint( fullTableName, collection.isActivated, - { - name: constraintName, - columns: pkColumns, - include: [], - storageParameters: '', - tablespace: '', - }); + ddlConfig + ); }) .map(scriptDto => AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, false)) .filter(Boolean); @@ -208,18 +266,7 @@ const getDropPkScript = (_, ddlProvider) => (collection) => { return wasTheFieldARegularPrimaryKey && isNotAPrimaryKey; }) .map(([name, jsonSchema]) => { - const constraintOptions = jsonSchema.primaryKeyOptions; - let constraintName = getDefaultConstraintName(wrapInQuotes)(entityName); - if (constraintOptions?.length && constraintOptions?.length > 0) { - /** - * @type {AlterCollectionColumnPrimaryKeyOptionDto} - * */ - const constraintOption = constraintOptions[0]; - if (constraintOption.constraintName) { - constraintName = wrapInQuotes(constraintOption.constraintName); - } - } - + const constraintName = wrapInQuotes(getConstraintNameForRegularPk(jsonSchema, entityName)); return ddlProvider.dropPkConstraint(fullTableName, constraintName); }) .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) @@ -231,11 +278,11 @@ const getDropPkScript = (_, ddlProvider) => (collection) => { * */ const getModifyPkScripts = (_, ddlProvider) => (collection) => { const dropPkScripts = getDropPkScript(_, ddlProvider)(collection); - // const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); + const addPkScripts = getAddPkScripts(_, ddlProvider)(collection); return [ ...dropPkScripts, - // ...addPkScripts, + ...addPkScripts, ].filter(Boolean); } diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js index 1379dbb..4d9a766 100644 --- a/forward_engineering/alterScript/types/AlterCollectionDto.js +++ b/forward_engineering/alterScript/types/AlterCollectionDto.js @@ -40,6 +40,23 @@ class AlterCollectionColumnPrimaryKeyOptionDto { * @type {string} * */ constraintName + + /** + * @type {string} + * */ + indexStorageParameters + + /** + * @type {string} + * */ + indexTablespace + + /** + * @type {Array<{ + * keyId: string + * }>} + * */ + indexInclude } class AlterCollectionColumnDto { diff --git a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js index 98f71cf..a75a62f 100644 --- a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js +++ b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js @@ -52,6 +52,7 @@ module.exports = ({ * @return {( * keyData: { * name: string, + * keyType: string, * columns: Array<{ * isActivated: boolean, * name: string, diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index e34c117..640585c 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -1,6 +1,7 @@ const defaultTypes = require('../configs/defaultTypes'); const types = require('../configs/types'); const templates = require('./templates'); +const assignTemplates = require("../utils/assignTemplates"); module.exports = (baseProvider, options, app) => { const _ = app.require('lodash'); @@ -1126,6 +1127,7 @@ module.exports = (baseProvider, options, app) => { * @param isParentActivated {boolean} * @param keyData {{ * name: string, + * keyType: string, * columns: Array<{ * isActivated: boolean, * name: string, @@ -1143,11 +1145,14 @@ module.exports = (baseProvider, options, app) => { * }} * */ createKeyConstraint(tableName, isParentActivated, keyData) { - const constraintStatement = createKeyConstraint(templates, isParentActivated)(keyData); - return assignTemplates(templates.addPkConstraint, { - constraintStatement, - tableName, - }) + const constraintStatementDto = createKeyConstraint(templates, isParentActivated)(keyData); + return { + statement: assignTemplates(templates.addPkConstraint, { + constraintStatement: (constraintStatementDto.statement || '').trim(), + tableName, + }), + isActivated: constraintStatementDto.isActivated, + } }, /** diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js index fd75612..b7eb3b0 100644 --- a/forward_engineering/ddlProvider/templates.js +++ b/forward_engineering/ddlProvider/templates.js @@ -41,7 +41,7 @@ module.exports = { dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};', - addPkConstraint: 'ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintStatement}', + addPkConstraint: 'ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};', dropTable: 'DROP TABLE IF EXISTS ${tableName};', From bd6942426e465a5c60eb6535694d14b203fe307b Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 2 Jun 2023 18:04:12 +0300 Subject: [PATCH 18/22] Added support for adding composite PK constraints --- .../entityHelpers/primaryKeyHelper.js | 155 +++++++++++++----- .../alterScript/types/AlterCollectionDto.js | 23 +-- 2 files changed, 119 insertions(+), 59 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 2f64893..19623e6 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -31,38 +31,119 @@ const getDefaultConstraintName = (entityName) => { return `${entityName}_pk`; } +/** + * @param primaryKey {AlterCollectionRoleCompModPKDto} + * @param entityName {string} + * @return {string} + * */ +const getConstraintNameForCompositePk = (primaryKey, entityName) => { + if (primaryKey.constraintName) { + return primaryKey.constraintName; + } + return getDefaultConstraintName(entityName); +} + +/** + * @param _ + * @param wrapInQuotes {(s: string) => string } + * @return {( + * primaryKey: AlterCollectionRoleCompModPKDto, + * entityName: string, + * entityJsonSchema: AlterCollectionDto, + * ) => { + * name: string, + * keyType: string, + * columns: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * include: Array<{ + * isActivated: boolean, + * name: string, + * }>, + * storageParameters: string, + * tablespace: string, + * } + * } + * */ +const getCreateCompositePKDDLProviderConfig = (_) => ( + primaryKey, + entityName, + entity +) => { + const constraintName = getConstraintNameForCompositePk(primaryKey, entityName); + const pkColumns = _.toPairs(entity.properties) + .filter(([name, jsonSchema]) => Boolean(primaryKey.compositePrimaryKey.find(keyDto => keyDto.keyId === jsonSchema.GUID))) + .map(([name, jsonSchema]) => ({ + name, + isActivated: jsonSchema.isActivated, + })); + + let storageParameters = ''; + let indexTablespace = ''; + let includeColumns = []; + if (primaryKey.indexStorageParameters) { + storageParameters = primaryKey.indexStorageParameters; + } + if (primaryKey.indexTablespace) { + indexTablespace = primaryKey.indexTablespace; + } + if (primaryKey.indexInclude) { + includeColumns = _.toPairs(entity.role.properties) + .filter(([name, jsonSchema]) => Boolean(primaryKey.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.GUID))) + .map(([name, jsonSchema]) => ({ + name, + isActivated: jsonSchema.isActivated, + })); + } + + return { + name: constraintName, + keyType: 'PRIMARY KEY', + columns: pkColumns, + include: includeColumns, + storageParameters, + tablespace: indexTablespace, + } +} + /** * @return {(collection: AlterCollectionDto) => Array} * */ const getAddCompositePkScripts = (_, ddlProvider) => (collection) => { - // const didPkChange = didCompositePkChange(_)(collection); - // if (!didPkChange) { - // return [] - // } - // const fullTableName = generateFullEntityName(collection); - // const constraintName = getEntityNameFromCollection(collection) + '_pk'; - // const pkDto = collection?.role?.compMod?.primaryKey || {}; - // const newPrimaryKeys = pkDto.new || []; - // - // return newPrimaryKeys - // .map((newPk) => { - // /** - // * @type {Array} - // * */ - // const compositePrimaryKey = newPk.compositePrimaryKey || []; - // const guidsOfColumnsInPk = compositePrimaryKey.map((compositePkEntry) => compositePkEntry.keyId); - // const columnsInPk = getPropertiesByGuids(_)(collection, guidsOfColumnsInPk); - // const columnNamesForDDL = columnsInPk.map(column => prepareName(column.compMod.newField.name)); - // if (!columnNamesForDDL.length) { - // return undefined; - // } - // return ddlProvider.addPkConstraint(fullTableName, constraintName, columnNamesForDDL); - // }) - // .filter(Boolean) - // .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, false)) - // .filter(Boolean); - - return []; + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + } = require('../../../utils/general')(_); + + const didPkChange = didCompositePkChange(_)(collection); + if (!didPkChange) { + return [] + } + + const collectionSchema = getSchemaOfAlterCollection(collection); + const fullTableName = getFullCollectionName(collectionSchema); + const entityName = getEntityName(collectionSchema); + + const pkDto = collection?.role?.compMod?.primaryKey || {}; + /** + * @type {Array} + * */ + const newPrimaryKeys = pkDto.new || []; + + return newPrimaryKeys + .map((newPk) => { + const ddlConfig = getCreateCompositePKDDLProviderConfig(_)(newPk, entityName, collection); + return ddlProvider.createKeyConstraint( + fullTableName, + collection.isActivated, + ddlConfig + ); + }) + .filter(Boolean) + .map(scriptDto => AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, false)) + .filter(Boolean); } /** @@ -108,11 +189,11 @@ const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { * */ const getModifyCompositePkScripts = (_, ddlProvider) => (collection) => { const dropCompositePkScripts = getDropCompositePkScripts(_, ddlProvider)(collection); - // const addCompositePkScripts = getAddCompositePkScripts(_, ddlProvider)(collection); + const addCompositePkScripts = getAddCompositePkScripts(_, ddlProvider)(collection); return [ ...dropCompositePkScripts, - // ...addCompositePkScripts, + ...addCompositePkScripts, ].filter(Boolean); } @@ -137,7 +218,6 @@ const getConstraintNameForRegularPk = (columnJsonSchema, entityName) => { /** * @param _ - * @param wrapInQuotes {(s: string) => string } * @return {( * name: string, * columnJsonSchema: AlterCollectionColumnDto, @@ -159,15 +239,15 @@ const getConstraintNameForRegularPk = (columnJsonSchema, entityName) => { * } * } * */ -const getCreateRegularPKDDLProviderConfig = (_, wrapInQuotes) => ( +const getCreateRegularPKDDLProviderConfig = (_) => ( columnName, columnJsonSchema, entityName, - entityJsonSchema + entity ) => { const constraintName = getConstraintNameForRegularPk(columnJsonSchema, entityName); const pkColumns = [{ - name: wrapInQuotes(columnName), + name: columnName, isActivated: columnJsonSchema.isActivated, }]; @@ -187,8 +267,8 @@ const getCreateRegularPKDDLProviderConfig = (_, wrapInQuotes) => ( indexTablespace = constraintOption.indexTablespace; } if (constraintOption.indexInclude) { - includeColumns = _.toPairs(entityJsonSchema.properties) - .filter(([name, jsonSchema]) => Boolean(constraintOption.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.id))) + includeColumns = _.toPairs(entity.role.properties) + .filter(([name, jsonSchema]) => Boolean(constraintOption.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.GUID))) .map(([name, jsonSchema]) => ({ name, isActivated: jsonSchema.isActivated, @@ -215,7 +295,6 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { getFullCollectionName, getSchemaOfAlterCollection, getEntityName, - wrapInQuotes } = require('../../../utils/general')(_); const collectionSchema = getSchemaOfAlterCollection(collection); @@ -230,7 +309,7 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; }) .map(([name, jsonSchema]) => { - const ddlConfig = getCreateRegularPKDDLProviderConfig(_, wrapInQuotes)(name, jsonSchema, entityName, collection); + const ddlConfig = getCreateRegularPKDDLProviderConfig(_)(name, jsonSchema, entityName, collection); return ddlProvider.createKeyConstraint( fullTableName, collection.isActivated, diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js index 4d9a766..095bff4 100644 --- a/forward_engineering/alterScript/types/AlterCollectionDto.js +++ b/forward_engineering/alterScript/types/AlterCollectionDto.js @@ -154,12 +154,7 @@ class AlterCollectionRoleDefinitionDto { properties } -class AlterCollectionRoleCompModPKDto { - - /** - * @type {string} - * */ - id +class AlterCollectionRoleCompModPKDto extends AlterCollectionColumnPrimaryKeyOptionDto{ /** * @type {Array<{ @@ -169,20 +164,6 @@ class AlterCollectionRoleCompModPKDto { * */ compositePrimaryKey - /** - * @type {string | undefined} - * */ - constraintName - - /** - * @type {string | undefined} - * */ - indexStorageParameters - - /** - * @type {string | undefined} - * */ - indexTablespace } class AlterCollectionRoleCompModDto { @@ -243,7 +224,7 @@ class AlterCollectionRoleCompModDto { /** * @type {{ * new: Array, - * old: Array, + * old: Array, * }} */ primaryKey From b30a84909ab8d45d697d2565d7033e75c75d9385 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 6 Jun 2023 14:17:17 +0300 Subject: [PATCH 19/22] Fixed error with updating composite pk name --- .../alterScriptHelpers/entityHelpers/primaryKeyHelper.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 19623e6..5f4701c 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -45,7 +45,6 @@ const getConstraintNameForCompositePk = (primaryKey, entityName) => { /** * @param _ - * @param wrapInQuotes {(s: string) => string } * @return {( * primaryKey: AlterCollectionRoleCompModPKDto, * entityName: string, @@ -72,7 +71,7 @@ const getCreateCompositePKDDLProviderConfig = (_) => ( entity ) => { const constraintName = getConstraintNameForCompositePk(primaryKey, entityName); - const pkColumns = _.toPairs(entity.properties) + const pkColumns = _.toPairs(entity.role.properties) .filter(([name, jsonSchema]) => Boolean(primaryKey.compositePrimaryKey.find(keyDto => keyDto.keyId === jsonSchema.GUID))) .map(([name, jsonSchema]) => ({ name, From a827c17a770ddd48c61d191e17e6e78d54a6cd99 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 6 Jun 2023 16:48:57 +0300 Subject: [PATCH 20/22] Fixed errors: - Not taking into account dropped pks with custom properties - Using new name of constraint instead of old one when dropping updated constraint --- .../entityHelpers/primaryKeyHelper.js | 59 +++++++++++++++---- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index 5f4701c..fd929bd 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -286,6 +286,49 @@ const getCreateRegularPKDDLProviderConfig = (_) => ( } +/** + * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} + * */ +const wasFieldChangedToBeARegularPk = (_) => (columnJsonSchema, collection) => { + const oldName = columnJsonSchema.compMod.oldField.name; + + const isRegularPrimaryKey = columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; + const wasTheFieldAPrimaryKey = Boolean(collection.role.properties[oldName]?.primaryKey); + return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; +} + +/** + * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} + * */ +const isFieldNoLongerARegularPk = (_) => (columnJsonSchema, collection) => { + const oldName = columnJsonSchema.compMod.oldField.name; + + const oldJsonSchema = collection.role.properties[oldName]; + const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; + + const isNotAPrimaryKey = !columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; + return wasTheFieldARegularPrimaryKey && isNotAPrimaryKey; +} + +/** + * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} + * */ +const wasRegularPkModified = (_) => (columnJsonSchema, collection) => { + const oldName = columnJsonSchema.compMod.oldField.name; + const oldJsonSchema = collection.role.properties[oldName]; + + const isRegularPrimaryKey = columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; + const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; + + if (!(isRegularPrimaryKey && wasTheFieldARegularPrimaryKey)) { + return false; + } + const constraintOptions = columnJsonSchema.primaryKeyOptions; + const oldConstraintOptions = oldJsonSchema?.primaryKeyOptions; + const areOptionsEqual = _(oldConstraintOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); + return !areOptionsEqual; +} + /** * @return {(collection: AlterCollectionDto) => Array} * */ @@ -302,10 +345,7 @@ const getAddPkScripts = (_, ddlProvider) => (collection) => { return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { - const isRegularPrimaryKey = jsonSchema.primaryKey && !jsonSchema.compositePrimaryKey; - const oldName = jsonSchema.compMod.oldField.name; - const wasTheFieldAPrimaryKey = Boolean(collection.role.properties[oldName]?.primaryKey); - return isRegularPrimaryKey && !wasTheFieldAPrimaryKey; + return wasFieldChangedToBeARegularPk(_)(jsonSchema, collection) || wasRegularPkModified(_)(jsonSchema, collection); }) .map(([name, jsonSchema]) => { const ddlConfig = getCreateRegularPKDDLProviderConfig(_)(name, jsonSchema, entityName, collection); @@ -336,15 +376,12 @@ const getDropPkScript = (_, ddlProvider) => (collection) => { return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { - const oldName = jsonSchema.compMod.oldField.name; - const oldJsonSchema = collection.role.properties[oldName]; - const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; - - const isNotAPrimaryKey = !jsonSchema.primaryKey && !jsonSchema.compositePrimaryKey; - return wasTheFieldARegularPrimaryKey && isNotAPrimaryKey; + return isFieldNoLongerARegularPk(_)(jsonSchema, collection) || wasRegularPkModified(_)(jsonSchema, collection); }) .map(([name, jsonSchema]) => { - const constraintName = wrapInQuotes(getConstraintNameForRegularPk(jsonSchema, entityName)); + const oldName = jsonSchema.compMod.oldField.name; + const oldJsonSchema = collection.role.properties[oldName]; + const constraintName = wrapInQuotes(getConstraintNameForRegularPk(oldJsonSchema, entityName)); return ddlProvider.dropPkConstraint(fullTableName, constraintName); }) .map(scriptLine => AlterScriptDto.getInstance([scriptLine], collection.isActivated, true)) From 244e6b03ad6b99710008f38deb3c7664068de2c8 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 13 Jun 2023 13:08:42 +0300 Subject: [PATCH 21/22] Fixed errors with formatting PK name --- .../alterScriptHelpers/entityHelpers/primaryKeyHelper.js | 2 +- forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index fd929bd..bc910b4 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -173,7 +173,7 @@ const getDropCompositePkScripts = (_, ddlProvider) => (collection) => { return oldPrimaryKeys .map((oldPk) => { - let constraintName = getDefaultConstraintName(entityName); + let constraintName = wrapInQuotes(getDefaultConstraintName(entityName)); if (oldPk.constraintName) { constraintName = wrapInQuotes(oldPk.constraintName); } diff --git a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js index a75a62f..86cde7b 100644 --- a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js +++ b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js @@ -83,7 +83,7 @@ module.exports = ({ return { statement: assignTemplates(templates.createKeyConstraint, { - constraintName: keyData.name ? `CONSTRAINT ${wrapInQuotes(constraintName)} ` : '', + constraintName: keyData.name ? `CONSTRAINT ${constraintName} ` : '', keyType: keyData.keyType, columns, includeNonKey, From f9b89ff7fa8cdcca826efbb0ef56990dae38c4e3 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 14 Jun 2023 11:05:27 +0300 Subject: [PATCH 22/22] Renamed types to descriptors.js --- forward_engineering/configs/{types.js => descriptors.js} | 0 forward_engineering/ddlProvider/ddlProvider.js | 8 ++++---- 2 files changed, 4 insertions(+), 4 deletions(-) rename forward_engineering/configs/{types.js => descriptors.js} (100%) diff --git a/forward_engineering/configs/types.js b/forward_engineering/configs/descriptors.js similarity index 100% rename from forward_engineering/configs/types.js rename to forward_engineering/configs/descriptors.js diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 640585c..cfdd133 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -1,7 +1,7 @@ const defaultTypes = require('../configs/defaultTypes'); -const types = require('../configs/types'); +const descriptors = require('../configs/descriptors'); const templates = require('./templates'); -const assignTemplates = require("../utils/assignTemplates"); + module.exports = (baseProvider, options, app) => { const _ = app.require('lodash'); @@ -576,11 +576,11 @@ module.exports = (baseProvider, options, app) => { }, getTypesDescriptors() { - return types; + return descriptors; }, hasType(type) { - return hasType(types, type); + return hasType(descriptors, type); }, hydrateDatabase({ modelData }) {