From 4a60513fcf596a0c468cf2a87262d11866999e4c Mon Sep 17 00:00:00 2001 From: chulanovskyi-bs <56116665+chulanovskyi-bs@users.noreply.github.com> Date: Tue, 13 Aug 2024 20:47:35 +0300 Subject: [PATCH] HCK-7614: column DEFAULT (#113) * feat: added column DEFAULT prop handler * fix: drop DEFAULT statement params * fix: bump pg version * fix: adjusted statements with fail-safe check IF EXISTS * fix: handle _fasly_ values properly * fix: handle drop statement for empty values * fix: appropriately generate drop statement * chore: simplify --- .../alterScript/alterScriptBuilder.js | 2 +- .../alterContainerHelper.js | 4 +- .../alterScriptHelpers/alterEntityHelper.js | 14 +- .../alterRelationshipsHelper.js | 4 +- .../alterScriptHelpers/alterUdtHelper.js | 8 +- .../alterScriptHelpers/alterViewHelper.js | 2 +- .../columnHelpers/alterTypeHelper.js | 2 +- .../columnHelpers/commentsHelper.js | 4 +- .../columnHelpers/defaultValueHelper.js | 65 +++ .../columnHelpers/nonNullConstraintHelper.js | 2 +- .../columnHelpers/renameColumnHelper.js | 2 +- .../containerHelpers/commentsHelper.js | 4 +- .../containerHelpers/sequencesHelper.js | 6 +- .../entityHelpers/checkConstraintHelper.js | 8 +- .../entityHelpers/commentsHelper.js | 4 +- .../entityHelpers/indexesHelper.js | 6 +- .../entityHelpers/primaryKeyHelper.js | 20 +- .../entityHelpers/uniqueKeyHelper.js | 24 +- .../viewHelpers/commentsHelper.js | 4 +- .../ddlProvider/ddlProvider.js | 35 +- forward_engineering/ddlProvider/templates.js | 5 + forward_engineering/utils/general.js | 479 +++++++++--------- package-lock.json | 146 ++---- package.json | 11 +- 24 files changed, 460 insertions(+), 401 deletions(-) create mode 100644 forward_engineering/alterScript/alterScriptHelpers/columnHelpers/defaultValueHelper.js diff --git a/forward_engineering/alterScript/alterScriptBuilder.js b/forward_engineering/alterScript/alterScriptBuilder.js index 8127826..3ccbf8c 100644 --- a/forward_engineering/alterScript/alterScriptBuilder.js +++ b/forward_engineering/alterScript/alterScriptBuilder.js @@ -6,7 +6,7 @@ const { AlterScriptDto } = require('./types/AlterScriptDto'); * @return {(dtos: AlterScriptDto[], shouldApplyDropStatements: boolean) => string} * */ const joinAlterScriptDtosIntoScript = _ => (dtos, shouldApplyDropStatements) => { - const { commentIfDeactivated } = require('../utils/general')(_); + const { commentIfDeactivated } = require('../utils/general'); return dtos .map(dto => { if (dto.isActivated === false) { diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js index c43757e..5260168 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js @@ -7,7 +7,7 @@ const { AlterScriptDto } = require('../types/AlterScriptDto'); const getAddContainerScriptDto = app => containerName => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../../utils/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/ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../../utils/general')(_); + const { wrapInQuotes } = require('../../utils/general'); const script = ddlProvider.dropSchema(wrapInQuotes(containerName)); return AlterScriptDto.getInstance([script], true, true); diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js index ae71a94..677cf64 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js @@ -13,6 +13,7 @@ const { getAddedIndexesScriptDtos, getAdditionalDataForDdlProvider, } = require('./entityHelpers/indexesHelper'); +const { getModifiedDefaultColumnValueScriptDtos } = require('./columnHelpers/defaultValueHelper'); /** * @return {(collection: AlterCollectionDto) => AlterScriptDto | undefined} @@ -21,7 +22,7 @@ const getAddCollectionScriptDto = ({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions }) => collection => { const _ = app.require('lodash'); - const { getEntityName } = require('../../utils/general')(_); + const { getEntityName } = require('../../utils/general'); const { createColumnDefinitionBySchema } = require('./createColumnDefinition')(app); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const { getDefinitionByReference } = app.require('@hackolade/ddl-fe-utils'); @@ -76,7 +77,7 @@ const getAddCollectionScriptDto = const getDeleteCollectionScriptDto = app => collection => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { getFullTableName } = require('../../utils/general')(_); + const { getFullTableName } = require('../../utils/general'); const fullName = getFullTableName(collection); const script = ddlProvider.dropTable(fullName); @@ -116,7 +117,7 @@ const getAddColumnsByConditionScriptDtos = ({ app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions }) => (collection, predicate) => { const _ = app.require('lodash'); - const { getEntityName, getNamePrefixedWithSchemaName } = require('../../utils/general')(_); + const { getEntityName, getNamePrefixedWithSchemaName } = require('../../utils/general'); const { createColumnDefinitionBySchema } = require('./createColumnDefinition')(app); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const { getDefinitionByReference } = app.require('@hackolade/ddl-fe-utils'); @@ -204,7 +205,7 @@ const getAddColumnScriptDtos = const getDeleteColumnsByConditionScriptDtos = app => (collection, predicate) => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { getEntityName, getNamePrefixedWithSchemaName, wrapInQuotes } = require('../../utils/general')(_); + const { getEntityName, getNamePrefixedWithSchemaName, wrapInQuotes } = require('../../utils/general'); const collectionSchema = { ...collection, ...(_.omit(collection?.role, 'properties') || {}) }; const tableName = getEntityName(collectionSchema); @@ -294,12 +295,17 @@ const getModifyColumnScriptDtos = const updateTypeScriptDtos = getUpdateTypesScriptDtos(_, ddlProvider)(collection); const modifyNotNullScriptDtos = getModifyNonNullColumnsScriptDtos(_, ddlProvider)(collection); const modifyCommentScriptDtos = getModifiedCommentOnColumnScriptDtos(_, ddlProvider)(collection); + const modifyDefaultColumnValueScriptDtos = getModifiedDefaultColumnValueScriptDtos({ + ddlProvider, + collection, + }); return [ ...renameColumnScriptDtos, ...updateTypeScriptDtos, ...modifyNotNullScriptDtos, ...modifyCommentScriptDtos, + ...modifyDefaultColumnValueScriptDtos, ].filter(Boolean); }; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js index 5991fd5..d75e3e1 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js @@ -13,7 +13,7 @@ const getRelationshipName = relationship => { * @return {(relationship: AlterRelationshipDto) => string} * */ const getFullChildTableName = _ => relationship => { - const { getNamePrefixedWithSchemaName } = require('../../utils/general')(_); + const { getNamePrefixedWithSchemaName } = require('../../utils/general'); const compMod = relationship.role.compMod; const childBucketName = compMod.child.bucket.name; @@ -88,7 +88,7 @@ const getAddForeignKeyScriptDtos = (ddlProvider, _) => addedRelationships => { * }} * */ const getDeleteSingleForeignKeyStatementDto = (ddlProvider, _) => relationship => { - const { wrapInQuotes } = require('../../utils/general')(_); + const { wrapInQuotes } = require('../../utils/general'); const compMod = relationship.role.compMod; const ddlChildEntityName = getFullChildTableName(_)(relationship); diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js index 704425c..a834257 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js @@ -53,7 +53,7 @@ const getDeleteUdtScriptDto = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { getUdtName, wrapInQuotes } = require('../../utils/general')(_); + const { getUdtName, wrapInQuotes } = require('../../utils/general'); const ddlUdtName = wrapInQuotes(getUdtName(udt)); if (udt.type === 'domain') { @@ -73,7 +73,7 @@ const getAddColumnToTypeScriptDtos = udt => { const _ = app.require('lodash'); const { createColumnDefinitionBySchema } = require('./createColumnDefinition')(app); - const { getUdtName, wrapInQuotes } = require('../../utils/general')(_); + const { getUdtName, wrapInQuotes } = require('../../utils/general'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); const { getDefinitionByReference } = app.require('@hackolade/ddl-fe-utils'); @@ -112,7 +112,7 @@ const getDeleteColumnFromTypeScriptDtos = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../../utils/general')(_); + const { wrapInQuotes } = require('../../utils/general'); const fullName = wrapInQuotes(udt.code || udt.name); @@ -130,7 +130,7 @@ const getModifyColumnOfTypeScriptDtos = app => udt => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { checkFieldPropertiesChanged, wrapInQuotes } = require('../../utils/general')(_); + const { checkFieldPropertiesChanged, wrapInQuotes } = require('../../utils/general'); const fullName = wrapInQuotes(udt.code || udt.name); diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js index 16f890d..6d34a42 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js @@ -24,7 +24,7 @@ const getAddViewScriptDto = app => view => { const getDeleteViewScriptDto = app => view => { const _ = app.require('lodash'); const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../../utils/general')(_); + const { wrapInQuotes } = require('../../utils/general'); const viewName = wrapInQuotes(view.code || view.name); const script = ddlProvider.dropView(viewName); diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js index 543b8ac..09d6af9 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js @@ -29,7 +29,7 @@ const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) * @return {(collection: Object) => AlterScriptDto[]} * */ const getUpdateTypesScriptDtos = (_, ddlProvider) => collection => { - const { checkFieldPropertiesChanged, getFullTableName, wrapInQuotes } = require('../../../utils/general')(_); + const { checkFieldPropertiesChanged, getFullTableName, wrapInQuotes } = require('../../../utils/general'); const fullTableName = getFullTableName(collection); return _.toPairs(collection.properties) diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js index 794a408..4fb04d3 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js @@ -4,7 +4,7 @@ const { AlterScriptDto } = require('../../types/AlterScriptDto'); * @return {(collection: Object) => AlterScriptDto[]} * */ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => collection => { - const { getFullColumnName, wrapComment } = require('../../../utils/general')(_); + const { getFullColumnName, wrapComment } = require('../../../utils/general'); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { const newComment = jsonSchema.description; @@ -25,7 +25,7 @@ const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => collection => { * @return {(collection: Object) => AlterScriptDto[]} * */ const getDeletedCommentOnColumnScriptDtos = (_, ddlProvider) => collection => { - const { getFullColumnName } = require('../../../utils/general')(_); + const { getFullColumnName } = require('../../../utils/general'); return _.toPairs(collection.properties) .filter(([name, jsonSchema]) => { diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/defaultValueHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/defaultValueHelper.js new file mode 100644 index 0000000..a548656 --- /dev/null +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/defaultValueHelper.js @@ -0,0 +1,65 @@ +const { toPairs } = require('lodash'); +const { AlterScriptDto } = require('../../types/AlterScriptDto'); +const { getFullTableName, wrapInQuotes, wrapInSingleQuotes } = require('../../../utils/general'); + +/** + * @param { ({ ddlProvider: Object, collection: Object }) } + * @returns { Array } + * */ +const getUpdatedDefaultColumnValueScriptDtos = ({ ddlProvider, collection }) => + toPairs(collection.properties) + .filter(([_name, jsonSchema]) => { + const newDefault = jsonSchema.default; + const oldName = jsonSchema.compMod.oldField.name; + const oldDefault = collection.role.properties[oldName]?.default; + return newDefault !== undefined && (!oldDefault || newDefault !== oldDefault); + }) + .map(([columnName, jsonSchema]) => { + const newDefaultValue = jsonSchema.default; + const scriptGenerationConfig = { + tableName: getFullTableName(collection), + columnName: wrapInQuotes(columnName), + defaultValue: wrapInSingleQuotes({ name: newDefaultValue }), + }; + return ddlProvider.updateColumnDefaultValue(scriptGenerationConfig); + }) + .map(script => AlterScriptDto.getInstance([script], true, false)) + .filter(Boolean); + +/** + * @param { ({ ddlProvider: Object, collection: Object }) } + * @returns { Array } + * */ +const getDeletedDefaultColumnValueScriptDtos = ({ ddlProvider, collection }) => + toPairs(collection.properties) + .filter(([_name, jsonSchema]) => { + const newDefault = jsonSchema.default; + const oldName = jsonSchema.compMod.oldField.name; + const oldDefault = collection.role.properties[oldName]?.default; + const hasPrevValue = oldDefault !== undefined; + const hasNewValue = newDefault !== undefined; + return hasPrevValue && !hasNewValue; + }) + .map(([columnName]) => { + const scriptGenerationConfig = { + tableName: getFullTableName(collection), + columnName: wrapInQuotes(columnName), + }; + return ddlProvider.dropColumnDefaultValue(scriptGenerationConfig); + }) + .map(script => AlterScriptDto.getInstance([script], true, true)) + .filter(Boolean); + +/** + * @param { ({ ddlProvider: Object, collection: Object }) } + * @returns { Array } + * */ +const getModifiedDefaultColumnValueScriptDtos = ({ ddlProvider, collection }) => { + const updatedDefaultValuesScriptDtos = getUpdatedDefaultColumnValueScriptDtos({ ddlProvider, collection }); + const dropDefaultValuesScriptDtos = getDeletedDefaultColumnValueScriptDtos({ ddlProvider, collection }); + return [...updatedDefaultValuesScriptDtos, ...dropDefaultValuesScriptDtos]; +}; + +module.exports = { + getModifiedDefaultColumnValueScriptDtos, +}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js index f4ca3f4..ee51c8d 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js @@ -4,7 +4,7 @@ const { AlterScriptDto } = require('../../types/AlterScriptDto'); * @return {(collection: Object) => AlterScriptDto[]} * */ const getModifyNonNullColumnsScriptDtos = (_, ddlProvider) => collection => { - const { getFullTableName, wrapInQuotes } = require('../../../utils/general')(_); + const { getFullTableName, wrapInQuotes } = require('../../../utils/general'); const fullTableName = getFullTableName(collection); const currentRequiredColumnNames = collection.required || []; diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js index 1d1d0d3..42515bf 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js @@ -4,7 +4,7 @@ const { AlterScriptDto } = require('../../types/AlterScriptDto'); * @return {(collection: Object) => AlterScriptDto[]} * */ const getRenameColumnScriptDtos = (_, ddlProvider) => collection => { - const { checkFieldPropertiesChanged, getFullTableName, wrapInQuotes } = require('../../../utils/general')(_); + const { checkFieldPropertiesChanged, getFullTableName, wrapInQuotes } = require('../../../utils/general'); const fullTableName = getFullTableName(collection); return _.values(collection.properties) diff --git a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js index c374e42..7e5d800 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js @@ -8,7 +8,7 @@ const extractDescription = container => { * @return {(collection: Object) => AlterScriptDto | undefined} * */ const getUpsertCommentsScriptDto = (_, ddlProvider) => container => { - const { wrapComment, wrapInQuotes } = require('../../../utils/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('../../../utils/general')(_); + const { wrapInQuotes } = require('../../../utils/general'); const description = extractDescription(container); if (description.old && !description.new) { diff --git a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/sequencesHelper.js b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/sequencesHelper.js index b717cc3..5100a74 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/sequencesHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/sequencesHelper.js @@ -11,7 +11,7 @@ const getAddContainerSequencesScriptDtos = ({ container }) => { const _ = app.require('lodash'); const ddlProvider = require('../../../ddlProvider')(null, null, app); - const { getDbName } = require('../../../utils/general')(_); + const { getDbName } = require('../../../utils/general'); const schemaName = getDbName([container.role]); return (container.role?.sequences || []) @@ -29,7 +29,7 @@ const getModifyContainerSequencesScriptDtos = ({ container }) => { const _ = app.require('lodash'); const ddlProvider = require('../../../ddlProvider')(null, null, app); - const { getDbName, getGroupItemsByCompMode } = require('../../../utils/general')(_); + const { getDbName, getGroupItemsByCompMode } = require('../../../utils/general'); const schemaName = getDbName([container.role]); const sequencesCompMod = container.role?.compMod?.[sequencesCompModKey] || {}; @@ -72,7 +72,7 @@ const getDeleteContainerSequencesScriptDtos = ({ container }) => { const _ = app.require('lodash'); const ddlProvider = require('../../../ddlProvider')(null, null, app); - const { getDbName } = require('../../../utils/general')(_); + const { getDbName } = require('../../../utils/general'); const schemaName = getDbName([container.role]); return (container.role?.sequences || []) diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js index 7dae3c4..4240b4d 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ b/forward_engineering/alterScript/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('../../../utils/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('../../../utils/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('../../../utils/general')(_); + const { wrapInQuotes } = require('../../../utils/general'); return constraintHistory .filter(historyEntry => { @@ -105,7 +105,7 @@ const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistor * @return {(collection: AlterCollectionDto) => Array} * */ const getModifyCheckConstraintScriptDtos = (_, ddlProvider) => collection => { - const { getFullTableName } = require('../../../utils/general')(_); + const { getFullTableName } = require('../../../utils/general'); const fullTableName = getFullTableName(collection); const constraintHistory = mapCheckConstraintNamesToChangeHistory(_)(collection); diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js index 110a8cf..3589d9a 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js @@ -5,7 +5,7 @@ const { AlterCollectionDto } = require('../../types/AlterCollectionDto'); * @return {(collection: AlterCollectionDto) => AlterScriptDto} */ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => collection => { - const { getFullTableName, wrapComment } = require('../../../utils/general')(_); + const { getFullTableName, wrapComment } = require('../../../utils/general'); const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { @@ -28,7 +28,7 @@ const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => collection => * @return {(collection: AlterCollectionDto) => AlterScriptDto} */ const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => collection => { - const { getFullTableName } = require('../../../utils/general')(_); + const { getFullTableName } = require('../../../utils/general'); const descriptionInfo = collection?.role.compMod?.description; if (!descriptionInfo) { diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/indexesHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/indexesHelper.js index 988371c..99f56b4 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/indexesHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/indexesHelper.js @@ -57,7 +57,7 @@ const setNamesToColumns = const mapIndexToFeIndexDto = ({ _ }) => ({ index, collection }) => { - const { getSchemaNameFromCollection } = require('../../../utils/general')(_); + const { getSchemaNameFromCollection } = require('../../../utils/general'); const schemaName = getSchemaNameFromCollection({ collection }); @@ -183,7 +183,7 @@ const getAddedIndexesScriptDtos = const getDeleteIndexScriptDto = ({ _, ddlProvider }) => ({ index, additionalDataForDdlProvider }) => { - const { getNamePrefixedWithSchemaName } = require('../../../utils/general')(_); + const { getNamePrefixedWithSchemaName } = require('../../../utils/general'); const { isParentActivated, schemaName } = additionalDataForDdlProvider; @@ -369,7 +369,7 @@ const getModifyIndexesScriptDtos = }; const getAdditionalDataForDdlProvider = ({ _, dbVersion, collection }) => { - const { getSchemaNameFromCollection } = require('../../../utils/general')(_); + const { getSchemaNameFromCollection } = require('../../../utils/general'); return { dbData: { dbVersion }, diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js index d8c7ed9..3b0a819 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js @@ -215,7 +215,7 @@ const getCreateCompositePKDDLProviderConfig = _ => (primaryKey, entityName, enti * @return {(collection: AlterCollectionDto) => Array} * */ const getAddCompositePkScriptDtos = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general')(_); + const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general'); /** * @type {AlterCollectionRoleCompModPrimaryKey} @@ -254,8 +254,12 @@ const getAddCompositePkScriptDtos = (_, ddlProvider) => collection => { * @return {(collection: AlterCollectionDto) => Array} * */ const getDropCompositePkScriptDtos = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName, wrapInQuotes } = - require('../../../utils/general')(_); + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes, + } = require('../../../utils/general'); const pkDto = collection?.role?.compMod?.primaryKey || {}; const newPrimaryKeys = pkDto.new || []; @@ -540,7 +544,7 @@ const wasRegularPkModified = _ => (columnJsonSchema, collection) => { * @return {(collection: AlterCollectionDto) => Array} * */ const getAddPkScriptDtos = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general')(_); + const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general'); const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); @@ -572,8 +576,12 @@ const getAddPkScriptDtos = (_, ddlProvider) => collection => { * @return {(collection: AlterCollectionDto) => Array} * */ const getDropPkScriptDto = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName, wrapInQuotes } = - require('../../../utils/general')(_); + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes, + } = require('../../../utils/general'); const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/uniqueKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/uniqueKeyHelper.js index b710c37..2f49ad7 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/uniqueKeyHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/uniqueKeyHelper.js @@ -174,7 +174,7 @@ const getConstraintNameForCompositeUniqueKey = (uniqueKey, entityName) => { * } * */ const getCreateCompositeUniqueKeyDDLProviderConfig = _ => (uniqueKey, entityName, entity, dbVersion) => { - const { clean, getDbVersion } = require('../../../utils/general')(_); + const { clean, getDbVersion } = require('../../../utils/general'); const keyHelper = require('../../../ddlProvider/ddlHelpers/keyHelper')(_, clean); const constraintName = getConstraintNameForCompositeUniqueKey(uniqueKey, entityName); @@ -228,7 +228,7 @@ const getCreateCompositeUniqueKeyDDLProviderConfig = _ => (uniqueKey, entityName * @return {(collection: AlterCollectionDto, dbVersion: string) => Array} * */ const getAddCompositeUniqueKeyScriptDtos = (_, ddlProvider) => (collection, dbVersion) => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general')(_); + const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general'); /** * @type {AlterCollectionRoleCompModUniqueKey} @@ -272,8 +272,12 @@ const getAddCompositeUniqueKeyScriptDtos = (_, ddlProvider) => (collection, dbVe * @return {(collection: AlterCollectionDto) => Array} * */ const getDropCompositeUniqueKeyScriptDtos = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName, wrapInQuotes } = - require('../../../utils/general')(_); + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes, + } = require('../../../utils/general'); const uniqueDto = collection?.role?.compMod?.uniqueKey || {}; const newUniqueKeys = uniqueDto.new || []; @@ -364,7 +368,7 @@ const getConstraintNameForRegularUniqueKey = (columnJsonSchema, entityName) => { * */ const getCreateRegularUniqueKeyDDLProviderConfig = _ => (columnName, columnJsonSchema, entityName, entity, dbVersion) => { - const { clean, getDbVersion } = require('../../../utils/general')(_); + const { clean, getDbVersion } = require('../../../utils/general'); const keyHelper = require('../../../ddlProvider/ddlHelpers/keyHelper')(_, clean); const constraintName = getConstraintNameForRegularUniqueKey(columnJsonSchema, entityName); const uniqueColumns = [ @@ -582,7 +586,7 @@ const wasRegularUniqueKeyModified = _ => (columnJsonSchema, collection) => { * @return {(collection: AlterCollectionDto, dbVersion: string) => Array} * */ const getAddUniqueKeyScriptDtos = (_, ddlProvider) => (collection, dbVersion) => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general')(_); + const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName } = require('../../../utils/general'); const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); @@ -620,8 +624,12 @@ const getAddUniqueKeyScriptDtos = (_, ddlProvider) => (collection, dbVersion) => * @return {(collection: AlterCollectionDto) => Array} * */ const getDropUniqueKeyScriptDto = (_, ddlProvider) => collection => { - const { getFullCollectionName, getSchemaOfAlterCollection, getEntityName, wrapInQuotes } = - require('../../../utils/general')(_); + const { + getFullCollectionName, + getSchemaOfAlterCollection, + getEntityName, + wrapInQuotes, + } = require('../../../utils/general'); const collectionSchema = getSchemaOfAlterCollection(collection); const fullTableName = getFullCollectionName(collectionSchema); diff --git a/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js index 09e776a..ed9f8ee 100644 --- a/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js +++ b/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js @@ -8,7 +8,7 @@ const extractDescription = view => { * @return {(view: Object) => AlterScriptDto | undefined} * */ const getUpsertCommentsScriptDto = (_, ddlProvider) => view => { - const { getFullViewName, wrapComment } = require('../../../utils/general')(_); + const { getFullViewName, wrapComment } = require('../../../utils/general'); const description = extractDescription(view); if (description.new && description.new !== description.old) { @@ -25,7 +25,7 @@ const getUpsertCommentsScriptDto = (_, ddlProvider) => view => { * */ const getDropCommentsScriptDto = (_, ddlProvider) => view => { const description = extractDescription(view); - const { getFullViewName } = require('../../../utils/general')(_); + const { getFullViewName } = require('../../../utils/general'); if (description.old && !description.new) { const viewName = getFullViewName(view); diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js index 74ae793..4d11a5c 100644 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ b/forward_engineering/ddlProvider/ddlProvider.js @@ -19,7 +19,7 @@ module.exports = (baseProvider, options, app) => { getNamePrefixedWithSchemaName, getColumnsList, getViewData, - } = require('../utils/general')(_); + } = require('../utils/general'); const assignTemplates = require('../utils/assignTemplates'); const { @@ -330,7 +330,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}` : ''; @@ -567,7 +567,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 @@ -666,7 +666,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( @@ -782,7 +782,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 { @@ -1341,5 +1341,30 @@ module.exports = (baseProvider, options, app) => { }; return assignTemplates(templates.reindexIndex, templatesConfig); }, + + /** + * @param {{ tableName: string, columnName: string, defaultValue: string }} + * @return string + * */ + updateColumnDefaultValue({ tableName, columnName, defaultValue }) { + const templateConfig = { + tableName, + columnName, + defaultValue, + }; + return assignTemplates(templates.updateColumnDefaultValue, templateConfig); + }, + + /** + * @param {{ tableName: string, columnName: string }} + * @return string + * */ + dropColumnDefaultValue({ tableName, columnName }) { + const templateConfig = { + tableName, + columnName, + }; + return assignTemplates(templates.dropColumnDefaultValue, templateConfig); + }, }; }; diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js index bfd34ae..becf1ea 100644 --- a/forward_engineering/ddlProvider/templates.js +++ b/forward_engineering/ddlProvider/templates.js @@ -134,4 +134,9 @@ module.exports = { setSequenceType: 'ALTER SEQUENCE IF EXISTS ${name} SET ${sequenceType};\n', alterSequence: 'ALTER SEQUENCE IF EXISTS ${name}' + '${options}' + ';\n', + + updateColumnDefaultValue: + 'ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DEFAULT ${defaultValue};', + + dropColumnDefaultValue: 'ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP DEFAULT;', }; diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js index e881375..62b2353 100644 --- a/forward_engineering/utils/general.js +++ b/forward_engineering/utils/general.js @@ -7,294 +7,297 @@ * the agreement/contract under which the software has been supplied. */ +const _ = require('lodash'); const { AlterCollectionDto, AlterCollectionRoleDto } = require('../alterScript/types/AlterCollectionDto'); - 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', ''); - }; +const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; - const getEntityName = entityData => { - return (entityData && (entityData.code || entityData.collectionName)) || ''; - }; +const getDbName = containerData => { + return _.get(containerData, '[0].code') || _.get(containerData, '[0].name', ''); +}; - const getViewName = view => { - return (view && (view.code || view.name)) || ''; - }; +const getEntityName = entityData => { + return (entityData && (entityData.code || entityData.collectionName)) || ''; +}; - const getDbData = containerData => { - return Object.assign({}, _.get(containerData, '[0]', {}), { name: getDbName(containerData) }); - }; +const getViewName = view => { + return (view && (view.code || view.name)) || ''; +}; - const getViewOn = viewData => _.get(viewData, '[0].viewOn'); +const getDbData = containerData => { + return Object.assign({}, _.get(containerData, '[0]', {}), { name: getDbName(containerData) }); +}; - const tab = (text, tab = '\t') => { - return text - .split('\n') - .map(line => tab + line) - .join('\n'); - }; +const getViewOn = viewData => _.get(viewData, '[0].viewOn'); - const hasType = (types, type) => { - return Object.keys(types).map(_.toLower).includes(_.toLower(type)); - }; +const tab = (text, tab = '\t') => { + return text + .split('\n') + .map(line => tab + line) + .join('\n'); +}; - /** - * @param collection {AlterCollectionDto} - * @return {AlterCollectionDto & AlterCollectionRoleDto} - * */ - const getSchemaOfAlterCollection = collection => { - return { ...collection, ...(_.omit(collection?.role, 'properties') || {}) }; - }; +const hasType = (types, type) => { + return Object.keys(types).map(_.toLower).includes(_.toLower(type)); +}; - /** - * @param collectionSchema {AlterCollectionDto & AlterCollectionRoleDto} - * @return {string} - * */ - const getFullCollectionName = collectionSchema => { - const collectionName = getEntityName(collectionSchema); - const bucketName = collectionSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(collectionName, bucketName); - }; +/** + * @param collection {AlterCollectionDto} + * @return {AlterCollectionDto & AlterCollectionRoleDto} + * */ +const getSchemaOfAlterCollection = collection => { + return { ...collection, ...(_.omit(collection?.role, 'properties') || {}) }; +}; - const clean = obj => - Object.entries(obj) - .filter(([name, value]) => !_.isNil(value)) - .reduce( - (result, [name, value]) => ({ - ...result, - [name]: value, - }), - {}, - ); - - const checkAllKeysActivated = keys => { - return keys.every(key => _.get(key, 'isActivated', true)); - }; +/** + * @param collectionSchema {AlterCollectionDto & AlterCollectionRoleDto} + * @return {string} + * */ +const getFullCollectionName = collectionSchema => { + const collectionName = getEntityName(collectionSchema); + const bucketName = collectionSchema.compMod?.keyspaceName; + return getNamePrefixedWithSchemaName(collectionName, bucketName); +}; - /** - * @param keys {Array<{ - * isActivated: boolean, - * }>} - * */ - const checkAllKeysDeactivated = keys => { - return keys.length ? keys.every(key => !_.get(key, 'isActivated', true)) : false; - }; +const clean = obj => + Object.entries(obj) + .filter(([name, value]) => !_.isNil(value)) + .reduce( + (result, [name, value]) => ({ + ...result, + [name]: value, + }), + {}, + ); - const divideIntoActivatedAndDeactivated = (items, mapFunction) => { - const activatedItems = items.filter(item => _.get(item, 'isActivated', true)).map(mapFunction); - const deactivatedItems = items.filter(item => !_.get(item, 'isActivated', true)).map(mapFunction); +const checkAllKeysActivated = keys => { + return keys.every(key => _.get(key, 'isActivated', true)); +}; - return { activatedItems, deactivatedItems }; - }; +/** + * @param keys {Array<{ + * isActivated: boolean, + * }>} + * */ +const checkAllKeysDeactivated = keys => { + return keys.length ? keys.every(key => !_.get(key, 'isActivated', true)) : false; +}; - const commentIfDeactivated = (statement, { isActivated, isPartOfLine, inlineComment = '--' }) => { - if (!statement) { - return ''; - } - if (isActivated !== false) { - return statement; - } - if (isPartOfLine) { - return '/* ' + statement + ' */'; - } else if (statement.includes('\n')) { - return '/*\n' + statement + ' */\n'; - } else { - return inlineComment + ' ' + statement; - } - }; +const divideIntoActivatedAndDeactivated = (items, mapFunction) => { + const activatedItems = items.filter(item => _.get(item, 'isActivated', true)).map(mapFunction); + const deactivatedItems = items.filter(item => !_.get(item, 'isActivated', true)).map(mapFunction); - const wrap = (str, start = "'", end = "'") => { - const firstChar = str[0]; - const lastChar = str[str.length - 1]; + return { activatedItems, deactivatedItems }; +}; - if (lastChar === start && firstChar === end) { - return str; - } else { - return `${start}${str}${end}`; - } - }; +const commentIfDeactivated = (statement, { isActivated, isPartOfLine, inlineComment = '--' }) => { + if (!statement) { + return ''; + } + if (isActivated !== false) { + return statement; + } + if (isPartOfLine) { + return '/* ' + statement + ' */'; + } else if (statement.includes('\n')) { + return '/*\n' + statement + ' */\n'; + } else { + return inlineComment + ' ' + statement; + } +}; - const checkFieldPropertiesChanged = (compMod, propertiesToCheck) => { - return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); - }; +const wrap = (str, start = "'", end = "'") => { + const firstChar = str[0]; + const lastChar = str[str.length - 1]; - const getFullTableName = collection => { - const collectionSchema = { ...collection, ...(_.omit(collection?.role, 'properties') || {}) }; - const tableName = getEntityName(collectionSchema); - const schemaName = getSchemaNameFromCollection({ collection: collectionSchema }); - return getNamePrefixedWithSchemaName(tableName, schemaName); - }; + if (lastChar === start && firstChar === end) { + return str; + } else { + return `${start}${str}${end}`; + } +}; - const getSchemaNameFromCollection = ({ collection }) => { - return collection.compMod?.keyspaceName; - }; +const checkFieldPropertiesChanged = (compMod, propertiesToCheck) => { + return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); +}; - const getFullColumnName = (collection, columnName) => { - const fullTableName = getFullTableName(collection); - return `${fullTableName}.${wrapInQuotes(columnName)}`; - }; +const getFullTableName = collection => { + const collectionSchema = { ...collection, ...(_.omit(collection?.role, 'properties') || {}) }; + const tableName = getEntityName(collectionSchema); + const schemaName = getSchemaNameFromCollection({ collection: collectionSchema }); + return getNamePrefixedWithSchemaName(tableName, schemaName); +}; - const getFullViewName = view => { - const viewSchema = { ...view, ...(_.omit(view?.role, 'properties') || {}) }; - const viewName = getViewName(viewSchema); - const schemaName = viewSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(viewName, schemaName); - }; +const getSchemaNameFromCollection = ({ collection }) => { + return collection.compMod?.keyspaceName; +}; - /** - * @param udt {Object} - * @return {string} - * */ - const getUdtName = udt => { - return udt.code || udt.name; - }; +const getFullColumnName = (collection, columnName) => { + const fullTableName = getFullTableName(collection); + return `${fullTableName}.${wrapInQuotes(columnName)}`; +}; - const getDbVersion = (dbVersion = '') => { - const version = dbVersion.match(/\d+/); +const getFullViewName = view => { + const viewSchema = { ...view, ...(_.omit(view?.role, 'properties') || {}) }; + const viewName = getViewName(viewSchema); + const schemaName = viewSchema.compMod?.keyspaceName; + return getNamePrefixedWithSchemaName(viewName, schemaName); +}; - return Number(_.get(version, [0], 0)); - }; +/** + * @param udt {Object} + * @return {string} + * */ +const getUdtName = udt => { + return udt.code || udt.name; +}; - const prepareComment = (comment = '') => comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); +const getDbVersion = (dbVersion = '') => { + const version = dbVersion.match(/\d+/); - const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; + return Number(_.get(version, [0], 0)); +}; - const getFunctionArguments = functionArguments => { - return _.map(functionArguments, arg => { - const defaultExpression = arg.defaultExpression ? `DEFAULT ${arg.defaultExpression}` : ''; +const prepareComment = (comment = '') => comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); - return _.trim(`${arg.argumentMode} ${arg.argumentName || ''} ${arg.argumentType} ${defaultExpression}`); - }).join(', '); - }; +const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; - const getNamePrefixedWithSchemaName = (name, schemaName) => { - if (schemaName) { - return `${wrapInQuotes(schemaName)}.${wrapInQuotes(name)}`; - } +const getFunctionArguments = functionArguments => { + return _.map(functionArguments, arg => { + const defaultExpression = arg.defaultExpression ? `DEFAULT ${arg.defaultExpression}` : ''; - return wrapInQuotes(name); - }; + return _.trim(`${arg.argumentMode} ${arg.argumentName || ''} ${arg.argumentType} ${defaultExpression}`); + }).join(', '); +}; - const wrapInQuotes = name => - /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)) ? `"${name}"` : name; +const getNamePrefixedWithSchemaName = (name, schemaName) => { + if (schemaName) { + return `${wrapInQuotes(schemaName)}.${wrapInQuotes(name)}`; + } - const columnMapToString = ({ name }) => wrapInQuotes(name); + return 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, - }) - : ''; +const shouldNameBeEscaped = ({ name }) => /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)); - return !isAllColumnsDeactivated && isParentActivated - ? ' (' + dividedColumns.activatedItems.join(', ') + deactivatedColumnsAsString + ')' - : ' (' + columns.map(mapColumn).join(', ') + ')'; - }; +const wrapInQuotes = name => (shouldNameBeEscaped({ name }) ? `"${name}"` : name); - const getKeyWithAlias = key => { - if (!key) { - return ''; - } +const wrapInSingleQuotes = ({ name }) => (shouldNameBeEscaped({ name }) ? `'${name}'` : name); - if (key.alias) { - return `${wrapInQuotes(key.name)} as ${wrapInQuotes(key.alias)}`; - } else { - return wrapInQuotes(key.name); - } - }; +const columnMapToString = ({ name }) => wrapInQuotes(name); - const getViewData = keys => { - if (!Array.isArray(keys)) { - return { tables: [], columns: [] }; - } +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 keys.reduce( - (result, key) => { - if (!key.tableName) { - result.columns.push(getKeyWithAlias(key)); + return !isAllColumnsDeactivated && isParentActivated + ? ' (' + dividedColumns.activatedItems.join(', ') + deactivatedColumnsAsString + ')' + : ' (' + columns.map(mapColumn).join(', ') + ')'; +}; - return result; - } +const getKeyWithAlias = key => { + if (!key) { + return ''; + } - const tableName = `${wrapInQuotes(key.dbName)}.${wrapInQuotes(key.tableName)}`; + if (key.alias) { + return `${wrapInQuotes(key.name)} as ${wrapInQuotes(key.alias)}`; + } else { + return wrapInQuotes(key.name); + } +}; - if (!result.tables.includes(tableName)) { - result.tables.push(tableName); - } +const getViewData = keys => { + if (!Array.isArray(keys)) { + return { tables: [], columns: [] }; + } - result.columns.push({ - statement: `${tableName}.${getKeyWithAlias(key)}`, - isActivated: key.isActivated, - }); + return keys.reduce( + (result, key) => { + if (!key.tableName) { + result.columns.push(getKeyWithAlias(key)); return result; - }, - { - tables: [], - columns: [], - }, - ); - }; + } + + const tableName = `${wrapInQuotes(key.dbName)}.${wrapInQuotes(key.tableName)}`; - const getGroupItemsByCompMode = ({ newItems = [], oldItems = [] }) => { - const addedItems = newItems.filter(newItem => !oldItems.some(item => item.id === newItem.id)); - const removedItems = []; - const modifiedItems = []; - - oldItems.forEach(oldItem => { - const newItem = newItems.find(item => item.id === oldItem.id); - if (!newItem) { - removedItems.push(oldItem); - } else { - if (!_.isEqual(newItem, oldItem)) { - modifiedItems.push(newItem); - } + if (!result.tables.includes(tableName)) { + result.tables.push(tableName); } - }); - return { - added: addedItems, - removed: removedItems, - modified: modifiedItems, - }; - }; + result.columns.push({ + statement: `${tableName}.${getKeyWithAlias(key)}`, + isActivated: key.isActivated, + }); + + return result; + }, + { + tables: [], + columns: [], + }, + ); +}; + +const getGroupItemsByCompMode = ({ newItems = [], oldItems = [] }) => { + const addedItems = newItems.filter(newItem => !oldItems.some(item => item.id === newItem.id)); + const removedItems = []; + const modifiedItems = []; + + oldItems.forEach(oldItem => { + const newItem = newItems.find(item => item.id === oldItem.id); + if (!newItem) { + removedItems.push(oldItem); + } else { + if (!_.isEqual(newItem, oldItem)) { + modifiedItems.push(newItem); + } + } + }); return { - getDbName, - getDbData, - getEntityName, - getViewName, - getViewOn, - tab, - hasType, - clean, - checkAllKeysActivated, - checkAllKeysDeactivated, - divideIntoActivatedAndDeactivated, - commentIfDeactivated, - wrap, - checkFieldPropertiesChanged, - getFullTableName, - getFullColumnName, - getFullViewName, - getUdtName, - getDbVersion, - wrapComment, - getFunctionArguments, - getNamePrefixedWithSchemaName, - wrapInQuotes, - getColumnsList, - getViewData, - getSchemaOfAlterCollection, - getFullCollectionName, - getSchemaNameFromCollection, - getGroupItemsByCompMode, + added: addedItems, + removed: removedItems, + modified: modifiedItems, }; }; + +module.exports = { + getDbName, + getDbData, + getEntityName, + getViewName, + getViewOn, + tab, + hasType, + clean, + checkAllKeysActivated, + checkAllKeysDeactivated, + divideIntoActivatedAndDeactivated, + commentIfDeactivated, + wrap, + checkFieldPropertiesChanged, + getFullTableName, + getFullColumnName, + getFullViewName, + getUdtName, + getDbVersion, + wrapComment, + getFunctionArguments, + getNamePrefixedWithSchemaName, + wrapInQuotes, + getColumnsList, + getViewData, + getSchemaOfAlterCollection, + getFullCollectionName, + getSchemaNameFromCollection, + getGroupItemsByCompMode, + wrapInSingleQuotes, +}; diff --git a/package-lock.json b/package-lock.json index 41627dc..9aaaa5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,14 +1,15 @@ { "name": "PostgreSQL", - "version": "0.2.2", + "version": "0.2.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "PostgreSQL", - "version": "0.2.2", + "version": "0.2.7", "dependencies": { - "pg": "^8.7.1" + "lodash": "4.17.21", + "pg": "8.12.0" }, "devDependencies": { "@hackolade/hck-esbuild-plugins-pack": "0.0.1", @@ -18,8 +19,8 @@ "esbuild-plugin-clean": "1.0.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", - "eslint-formatter-teamcity": "^1.0.0", - "eslint-plugin-import": "^2.26.0", + "eslint-formatter-teamcity": "1.0.0", + "eslint-plugin-import": "2.26.0", "eslint-plugin-prettier": "5.1.3", "eslint-plugin-unused-imports": "3.2.0", "lint-staged": "14.0.1", @@ -942,26 +943,6 @@ "node": ">=8" } }, - "node_modules/array.prototype.findlastindex": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", - "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "es-shim-unscopables": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/array.prototype.flat": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", @@ -980,24 +961,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array.prototype.flatmap": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", - "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.2.0", - "es-abstract": "^1.22.1", - "es-shim-unscopables": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/arraybuffer.prototype.slice": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", @@ -1698,28 +1661,24 @@ } }, "node_modules/eslint-plugin-import": { - "version": "2.29.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz", - "integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==", + "version": "2.26.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", + "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", "dev": true, "dependencies": { - "array-includes": "^3.1.7", - "array.prototype.findlastindex": "^1.2.3", - "array.prototype.flat": "^1.3.2", - "array.prototype.flatmap": "^1.3.2", - "debug": "^3.2.7", + "array-includes": "^3.1.4", + "array.prototype.flat": "^1.2.5", + "debug": "^2.6.9", "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.9", - "eslint-module-utils": "^2.8.0", - "hasown": "^2.0.0", - "is-core-module": "^2.13.1", + "eslint-import-resolver-node": "^0.3.6", + "eslint-module-utils": "^2.7.3", + "has": "^1.0.3", + "is-core-module": "^2.8.1", "is-glob": "^4.0.3", "minimatch": "^3.1.2", - "object.fromentries": "^2.0.7", - "object.groupby": "^1.0.1", - "object.values": "^1.1.7", - "semver": "^6.3.1", - "tsconfig-paths": "^3.15.0" + "object.values": "^1.1.5", + "resolve": "^1.22.0", + "tsconfig-paths": "^3.14.1" }, "engines": { "node": ">=4" @@ -1739,12 +1698,12 @@ } }, "node_modules/eslint-plugin-import/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "dependencies": { - "ms": "^2.1.1" + "ms": "2.0.0" } }, "node_modules/eslint-plugin-import/node_modules/doctrine": { @@ -1771,14 +1730,11 @@ "node": "*" } }, - "node_modules/eslint-plugin-import/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } + "node_modules/eslint-plugin-import/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true }, "node_modules/eslint-plugin-prettier": { "version": "5.1.3", @@ -2342,6 +2298,15 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, + "node_modules/has": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/has-bigints": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", @@ -2967,6 +2932,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -3158,38 +3128,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/object.fromentries": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", - "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object.groupby": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", - "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/object.values": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", diff --git a/package.json b/package.json index e20e76b..e686261 100644 --- a/package.json +++ b/package.json @@ -61,14 +61,14 @@ }, "devDependencies": { "@hackolade/hck-esbuild-plugins-pack": "0.0.1", - "@typescript-eslint/parser": "7.11.0", "@typescript-eslint/eslint-plugin": "7.11.0", + "@typescript-eslint/parser": "7.11.0", "esbuild": "0.20.2", "esbuild-plugin-clean": "1.0.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", - "eslint-formatter-teamcity": "^1.0.0", - "eslint-plugin-import": "^2.26.0", + "eslint-formatter-teamcity": "1.0.0", + "eslint-plugin-import": "2.26.0", "eslint-plugin-prettier": "5.1.3", "eslint-plugin-unused-imports": "3.2.0", "lint-staged": "14.0.1", @@ -76,6 +76,7 @@ "simple-git-hooks": "2.11.1" }, "dependencies": { - "pg": "^8.7.1" + "lodash": "4.17.21", + "pg": "8.12.0" } -} \ No newline at end of file +}