#include #include #include "dbms_metadata_common.hpp" extern "C" { #include "utils/builtins.h" #include "utils/elog.h" #include "postgres.h" #include "fmgr.h" #include "utils/fmgroids.h" #include "access/table.h" #include "access/genam.h" /* для ScanKeyInit, systable_* */ #include "access/heapam.h" #include "access/htup.h" #include "access/htup_details.h" #include "access/tupdesc.h" #include "access/relation.h" #include "access/sysattr.h" #include "utils/rel.h" #include "catalog/indexing.h" #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "catalog/pg_attribute.h" #include "catalog/pg_attrdef.h" #include "catalog/pg_authid.h" #include "catalog/pg_class.h" #include "catalog/pg_collation.h" #include "catalog/pg_constraint.h" #include "catalog/pg_description.h" #include "catalog/pg_enum.h" #include "catalog/pg_opclass.h" #include "catalog/pg_policy.h" #include "catalog/pg_proc.h" #include "catalog/pg_operator.h" #include "catalog/pg_range.h" #include "catalog/pg_sequence.h" #include "catalog/pg_tablespace.h" #include "catalog/pg_trigger.h" #include "commands/comment.h" #include "commands/tablespace.h" #include "parser/parse_node.h" #include "nodes/makefuncs.h" #include "nodes/pg_list.h" #include "utils/acl.h" #include "utils/formatting.h" #include "utils/syscache.h" #include "utils/catcache.h" #include "utils/lsyscache.h" #include "utils/typcache.h" #include "utils/memutils.h" #include "utils/partcache.h" #include "utils/ruleutils.h" //#include "utils/tqual.h" #include "lib/stringinfo.h" #include "parser/parse_type.h" #include "storage/lmgr.h" #include "miscadmin.h" /* для GUC-переменных */ } namespace dbms_metadata{ static std::map ctxMap; static int32 hndlnext = 0; static int32 hndlTransformNext = 0; static TransformationObject sessionTransform; const int32 sessionTransformHandle = -1; static std::map ctxTransformMap; static const char* SQLTERMINATOR = ";"; int32 genNextHandle() { if(++hndlnext == INT32_MAX){ hndlnext = 1; } return hndlnext; } int32 genNextTransformHandle() { if(++hndlTransformNext == INT32_MAX){ hndlTransformNext = 1; } return hndlTransformNext; } std::optional stringToObjectType(const std::string& str) { static const std::unordered_map map = { {"AQ_QUEUE", ObjectType::ObjectTypeAqQueue}, {"AQ_QUEUE_TABLE", ObjectType::ObjectTypeAqQueueTable}, {"AQ_TRANSFORM", ObjectType::ObjectTypeAqTransform}, {"ASSOCIATION", ObjectType::ObjectTypeAssociation}, {"AUDIT", ObjectType::ObjectTypeAudit}, {"AUDIT_OBJ", ObjectType::ObjectTypeAuditObj}, {"CLUSTER", ObjectType::ObjectTypeCluster}, {"COMMENT", ObjectType::ObjectTypeComment}, {"CONSTRAINT", ObjectType::ObjectTypeConstraint}, {"CONTEXT", ObjectType::ObjectTypeContext}, {"DATABASE_EXPORT", ObjectType::ObjectTypeDatabaseExport}, {"DB_LINK", ObjectType::ObjectTypeDbLink}, {"DEFAULT_ROLE", ObjectType::ObjectTypeDefaultRole}, {"DIMENSION", ObjectType::ObjectTypeDimension}, {"DIRECTORY", ObjectType::ObjectTypeDirectory}, {"FGA_POLICY", ObjectType::ObjectTypeFgaPolicy}, {"FUNCTION", ObjectType::ObjectTypeFunction}, {"INDEX_STATISTICS", ObjectType::ObjectTypeIndexStatistics}, {"INDEX", ObjectType::ObjectTypeIndex}, {"INDEXTYPE", ObjectType::ObjectTypeIndextype}, {"JAVA_SOURCE", ObjectType::ObjectTypeJavaSource}, {"JOB", ObjectType::ObjectTypeJob}, {"LIBRARY", ObjectType::ObjectTypeLibrary}, {"MATERIALIZED_VIEW", ObjectType::ObjectTypeMaterializedView}, {"MATERIALIZED_VIEW_LOG", ObjectType::ObjectTypeMaterializedViewLog}, {"OBJECT_GRANT", ObjectType::ObjectTypeObjectGrant}, {"ON_USER_GRANT", ObjectType::ObjectTypeOnUserGrant}, {"OPERATOR", ObjectType::ObjectTypeOperator}, {"PACKAGE", ObjectType::ObjectTypePackage}, {"PACKAGE_SPEC", ObjectType::ObjectTypePackageSpec}, {"PACKAGE_BODY", ObjectType::ObjectTypePackageBody}, {"PROCEDURE", ObjectType::ObjectTypeProcedure}, {"PROFILE", ObjectType::ObjectTypeProfile}, {"PROXY", ObjectType::ObjectTypeProxy}, {"REF_CONSTRAINT", ObjectType::ObjectTypeRefConstraint}, {"REFRESH_GROUP", ObjectType::ObjectTypeRefreshGroup}, {"RESOURCE_COST", ObjectType::ObjectTypeResourceCost}, {"RLS_CONTEXT", ObjectType::ObjectTypeRlsContext}, {"RLS_GROUP", ObjectType::ObjectTypeRlsGroup}, {"RLS_POLICY", ObjectType::ObjectTypeRlsPolicy}, {"RMGR_CONSUMER_GROUP", ObjectType::ObjectTypeRmgrConsumerGroup}, {"RMGR_INTITIAL_CONSUMER_GROUP", ObjectType::ObjectTypeRmgrIntitialConsumerGroup}, {"RMGR_PLAN", ObjectType::ObjectTypeRmgrPlan}, {"RMGR_PLAN_DIRECTIVE", ObjectType::ObjectTypeRmgrPlanDirective}, {"ROLE", ObjectType::ObjectTypeRole}, {"ROLE_GRANT", ObjectType::ObjectTypeRoleGrant}, {"ROLLBACK_SEGMENT", ObjectType::ObjectTypeRollbackSegment}, {"SCHEMA_EXPORT", ObjectType::ObjectTypeSchemaExport}, {"SEQUENCE", ObjectType::ObjectTypeSequence}, {"SYNONYM", ObjectType::ObjectTypeSynonym}, {"SYSTEM_GRANT", ObjectType::ObjectTypeSystemGrant}, {"TABLE", ObjectType::ObjectTypeTable}, {"TABLE_DATA", ObjectType::ObjectTypeTableData}, {"TABLE_EXPORT", ObjectType::ObjectTypeTableExport}, {"TABLE_STATISTICS", ObjectType::ObjectTypeTableStatistics}, {"TABLESPACE", ObjectType::ObjectTypeTablespace}, {"TABLESPACE_QUOTA", ObjectType::ObjectTypeTablespaceQuota}, {"TRANSPORTABLE_EXPORT", ObjectType::ObjectTypeTransportableExport}, {"TRIGGER", ObjectType::ObjectTypeTrigger}, {"TRUSTED_DB_LINK", ObjectType::ObjectTypeTrustedDbLink}, {"TYPE", ObjectType::ObjectTypeType}, {"TYPE_SPEC", ObjectType::ObjectTypeTypeSpec}, {"TYPE_BODY", ObjectType::ObjectTypeTypeBody}, {"USER", ObjectType::ObjectTypeUser}, {"VIEW", ObjectType::ObjectTypeView}, {"XMLSCHEMA", ObjectType::ObjectTypeXmlschema}, {"XS_USER", ObjectType::ObjectTypeXsUser}, {"XS_ROLE", ObjectType::ObjectTypeXsRole}, {"XS_ROLESET", ObjectType::ObjectTypeXsRoleset}, {"XS_ROLE_GRANT", ObjectType::ObjectTypeXsRoleGrant}, {"XS_SECURITY_CLASS", ObjectType::ObjectTypeXsSecurityClass}, {"XS_DATA_SECURITY", ObjectType::ObjectTypeXsDataSecurity}, {"XS_ACL", ObjectType::ObjectTypeXsAcl}, {"XS_ACL_PARAM", ObjectType::ObjectTypeXsAclParam}, {"XS_NAMESPACE", ObjectType::ObjectTypeXsNamespace} }; std::string upper = str; std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); }); auto it = map.find(upper); if (it != map.end()) { return it->second; } return std::nullopt; } std::string_view ObjectTypeToStringView(ObjectType obj_type){ static constexpr std::string_view names[] = { "NONE", "AQ_QUEUE", "AQ_QUEUE_TABLE", "AQ_TRANSFORM", "ASSOCIATION", "AUDIT", "AUDIT_OBJ", "CLUSTER", "COMMENT", "CONSTRAINT", "CONTEXT", "DATABASE_EXPORT", "DB_LINK", "DEFAULT_ROLE", "DIMENSION", "DIRECTORY", "FGA_POLICY", "FUNCTION", "INDEX_STATISTICS", "INDEX", "INDEXTYPE", "JAVA_SOURCE", "JOB", "LIBRARY", "MATERIALIZED_VIEW", "MATERIALIZED_VIEW_LOG", "OBJECT_GRANT", "ON_USER_GRANT", "OPERATOR", "PACKAGE", "PACKAGE_SPEC", "PACKAGE_BODY", "PROCEDURE", "PROFILE", "PROXY", "REF_CONSTRAINT", "REFRESH_GROUP", "RESOURCE_COST", "RLS_CONTEXT", "RLS_GROUP", "RLS_POLICY", "RMGR_CONSUMER_GROUP", "RMGR_INTITIAL_CONSUMER_GROUP", "RMGR_PLAN", "RMGR_PLAN_DIRECTIVE", "ROLE", "ROLE_GRANT", "ROLLBACK_SEGMENT", "SCHEMA_EXPORT", "SEQUENCE", "SYNONYM", "SYSTEM_GRANT", "TABLE", "TABLE_DATA", "TABLE_EXPORT", "TABLE_STATISTICS", "TABLESPACE", "TABLESPACE_QUOTA", "TRANSPORTABLE_EXPORT", "TRIGGER", "TRUSTED_DB_LINK", "TYPE", "TYPE_SPEC", "TYPE_BODY", "USER", "VIEW", "XMLSCHEMA", "XS_USER", "XS_ROLE", "XS_ROLESET", "XS_ROLE_GRANT", "XS_SECURITY_CLASS", "XS_DATA_SECURITY", "XS_ACL", "XS_ACL_PARAM", "XS_NAMESPACE" }; return names[static_cast(obj_type)]; } std::optional stringToObjectTypePath(const std::string& str) { static const std::unordered_map map = { {"NONE", OTPName::OTPNULL}, {"ASSOCIATION", OTPName::OTPAssociation}, {"AUDIT", OTPName::OTPAudit}, {"AUDIT_OBJ", OTPName::OTPAuditObj}, {"CLUSTER", OTPName::OTPCluster}, {"COMMENT", OTPName::OTPComment}, {"CONSTRAINT", OTPName::OTPConstraint}, {"CONTEXT", OTPName::OTPContext}, {"DB_LINK", OTPName::OTPDBLink}, {"DEFAULT_ROLE", OTPName::OTPDefaultRole}, {"DIMENSION", OTPName::OTPDimension}, {"DIRECTORY", OTPName::OTPDirectory}, {"FGA_POLICY", OTPName::OTPFGAPolicy}, {"FUNCTION", OTPName::OTPFunction}, {"GRANT", OTPName::OTPGrant}, {"INDEX", OTPName::OTPIndex}, {"INDEXTYPE", OTPName::OTPIndexType}, {"JAVA_SOURCE", OTPName::OTPJavaSource}, {"LIBRARY", OTPName::OTPLibrary}, {"MATERIALIZED_VIEW", OTPName::OTPMaterializedView}, {"MATERIALIZED_VIEW_LOG", OTPName::OTPMaterializedViewLog}, {"OBJECT_GRANT", OTPName::OTPObjectGrant}, {"OPERATOR", OTPName::OTPOperator}, {"PACKAGE", OTPName::OTPPackage}, {"PACKAGE_BODY", OTPName::OTPPackageBody}, {"PACKAGE_SPEC", OTPName::OTPPackageSpec}, {"PASSWORD_HISTORY", OTPName::OTPPasswordHistory}, {"PASSWORD_VERIFY_FUNCTION", OTPName::OTPPasswordVerifyFunction}, {"PROCEDURE", OTPName::OTPProcedure}, {"PROFILE", OTPName::OTPProfile}, {"PROXY", OTPName::OTPProxy}, {"REF_CONSTRAINT", OTPName::OTPRefConstraint}, {"REFRESH_GROUP", OTPName::OTPRefreshGroup}, {"RESOURCE_COST", OTPName::OTPResourceCost}, {"RLS_CONTEXT", OTPName::OTPRLSContext}, {"RLS_GROUP", OTPName::OTPRLSGroup}, {"RLS_POLICY", OTPName::OTPRLSPolicy}, {"ROLE", OTPName::OTPRole}, {"ROLE_GRANT", OTPName::OTPRoleGrant}, {"ROLLBACK_SEGMENT", OTPName::OTPRollbackSegment}, {"SCHEMA", OTPName::OTPSchema}, {"SEQUENCE", OTPName::OTPSequence}, {"STATISTICS", OTPName::OTPStatistics}, {"SYNONYM", OTPName::OTPSynonym}, {"SYSTEM_GRANT", OTPName::OTPSystemGrant}, {"TABLE", OTPName::OTPTable}, {"TABLE_DATA", OTPName::OTPTableData}, {"TABLESPACE", OTPName::OTPTablespace}, {"TABLESPACE_QUOTA", OTPName::OTPTablespaceQuota}, {"TRIGGER", OTPName::OTPTrigger}, {"TRUSTED_DB_LINK", OTPName::OTPTrustedDBLink}, {"TYPE", OTPName::OTPType}, {"TYPE_BODY", OTPName::OTPTypeBody}, {"TYPE_SPEC", OTPName::OTPTypeSpec}, {"USER", OTPName::OTPUser}, {"VIEW", OTPName::OTPView}, {"XS_ACL", OTPName::OTPXsAcl}, {"XS_DATA_SECURITY", OTPName::OTPXsDataSecurity}, {"XS_NAMESPACE", OTPName::OTPXsNamespace}, {"XS_USER", OTPName::OTPXsUser}, {"XS_ROLE", OTPName::OTPXsRole}, {"XS_SECURITY_CLASS", OTPName::OTPXsSecurityClass} }; std::string upper = str; std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); }); auto it = map.find(upper); if (it != map.end()) { return it->second; } return std::nullopt; } std::optional stringToFilterName(const std::string& str) { static const std::unordered_map map = { {"NONE", FilterName::FNNull}, {"BASE_OBJECT_NAME", FilterName::FNBaseObjectName}, {"BASE_OBJECT_NAME_EXPR", FilterName::FNBaseObjectNameExpr}, {"BASE_OBJECT_SCHEMA", FilterName::FNBaseObjectSchema}, {"BASE_OBJECT_SCHEMA_EXPR", FilterName::FNBaseObjectSchemaExpr}, {"BASE_OBJECT_TABLESPACE", FilterName::FNBaseObjectTablespace}, {"BASE_OBJECT_TABLESPACE_EXPR", FilterName::FNBaseObjectTablespaceExpr}, {"BASE_OBJECT_TYPE", FilterName::FNBaseObjectType}, {"BASE_OBJECT_TYPE_EXPR", FilterName::FNBaseObjectTypeExpr}, {"BEGIN_AFTER", FilterName::FNBeginAfter}, {"BEGIN_WITH", FilterName::FNBeginWith}, {"BODY", FilterName::FNBody}, {"CUSTOM_FILTER", FilterName::FNCustomFilter}, {"EDITION", FilterName::FNEdition}, {"END_BEFORE", FilterName::FNEndBefore}, {"END_WITH", FilterName::FNEndWith}, {"EXCLUDE_BASE_OBJECT_NAME_EXPR", FilterName::FNExcludeBaseObjectNameExpr}, {"EXCLUDE_GRANTEE_EXPR", FilterName::FNExcludeGranteeExpr}, {"EXCLUDE_NAME_EXPR", FilterName::FNExcludeNameExpr}, {"EXCLUDE_PATH_EXPR", FilterName::FNExcludePathExpr}, {"EXCLUDE_TABLES", FilterName::FNExcludeTables}, {"GRANTEE", FilterName::FNGrantee}, {"GRANTEE_EXPR", FilterName::FNGranteeExpr}, {"GRANTOR", FilterName::FNGrantor}, {"INCLUDE_PATH_EXPR", FilterName::FNIncludePathExpr}, {"INCLUDE_USER", FilterName::FNIncludeUser}, {"LONGNAME", FilterName::FNLongname}, {"LONGNAME_EXPR", FilterName::FNLongnameExpr}, {"NAME", FilterName::FNName}, {"NAME_EXPR", FilterName::FNNameExpr}, {"PRIMARY", FilterName::FNPrimary}, {"PRIVNAME", FilterName::FNPrivname}, {"SCHEMA", FilterName::FNSchema}, {"SCHEMA_EXPR", FilterName::FNSchemaExpr}, {"SECONDARY", FilterName::FNSecondary}, {"SPECIFICATION", FilterName::FNSpecification}, {"SYSTEM_GENERATED", FilterName::FNSystemGenerated}, {"TABLESPACE", FilterName::FNTablespace}, {"TABLESPACE_EXPR", FilterName::FNTablespaceExpr} }; std::string upper = str; std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); }); auto it = map.find(upper); if (it != map.end()) { return it->second; } return std::nullopt; } std::optional stringToAttrName(const std::string& str) { static const std::unordered_map map = { {"NONE", AttrName::ANNull}, {"ALTERABLE", AttrName::ANAlterable}, {"BASE_OBJECT_NAME", AttrName::ANBaseObjectName}, {"BASE_OBJECT_TYPE", AttrName::ANBaseObjectType}, {"BASE_OBJECT_SCHEMA", AttrName::ANBaseObjectSchema}, {"CLAUSE_TYPE", AttrName::ANClauseType}, {"COLUMN_ATTRIBUTE", AttrName::ANColumnAttribute}, {"CONSTRAINT_STATE", AttrName::ANConstraintState}, {"DEL_TOMBSTONE", AttrName::ANDelTombstone}, {"ENABLE", AttrName::ANEnable}, {"GRANTEE", AttrName::ANGrantee}, {"GRANTOR", AttrName::ANGrantor}, {"LONGNAME", AttrName::ANLongname}, {"NAME", AttrName::ANName}, {"OBJECT_TYPE", AttrName::ANObjectType}, {"SCHEMA", AttrName::ANSchema}, {"SYSTEM_GENERATED", AttrName::ANSystemGenerated}, {"TABLESPACE", AttrName::ANTablespace}, {"VERB", AttrName::ANVerb}, {"XPATH", AttrName::ANXPath} }; std::string upper = str; std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); }); auto it = map.find(upper); if (it != map.end()) { return it->second; } return std::nullopt; } std::optional stringToParamName(const std::string& str) { static const std::unordered_map map = { {"BODY", TransformParam::BODY}, {"COLLATION_CLAUSE", TransformParam::COLLATION_CLAUSE}, {"CONSTRAINTS", TransformParam::CONSTRAINTS}, {"CONSTRAINTS_AS_ALTER", TransformParam::CONSTRAINTS_AS_ALTER}, {"CONSTRAINT_NAME_FROM_INDEX", TransformParam::CONSTRAINT_NAME_FROM_INDEX}, {"CONSTRAINT_USE_DEFAULT_INDEX", TransformParam::CONSTRAINT_USE_DEFAULT_INDEX}, {"DEFAULT", TransformParam::DEFAULT}, {"DWCS_CVT_CONSTRAINTS", TransformParam::DWCS_CVT_CONSTRAINTS}, {"DWCS_CVT_IOTS", TransformParam::DWCS_CVT_IOTS}, {"FORCE", TransformParam::FORCE}, {"INHERIT", TransformParam::INHERIT}, {"INSERT", TransformParam::INSERT}, {"LOB_STORAGE", TransformParam::LOB_STORAGE}, {"OBJECT_ROW", TransformParam::OBJECT_ROW}, {"OID", TransformParam::OID}, {"OMIT_ENCRYPTION_CLAUSE", TransformParam::OMIT_ENCRYPTION_CLAUSE}, {"PARTITIONING", TransformParam::PARTITIONING}, {"PCTSPACE", TransformParam::PCTSPACE}, {"PHYSICAL_PROPERTIES", TransformParam::PHYSICAL_PROPERTIES}, {"PRETTY", TransformParam::PRETTY}, {"PRESERVE_LOCAL", TransformParam::PRESERVE_LOCAL}, {"REF_CONSTRAINTS", TransformParam::REF_CONSTRAINTS}, {"REMAP_COLUMN_NAME", TransformParam::REMAP_COLUMN_NAME}, {"REMAP_DATAFILE", TransformParam::REMAP_DATAFILE}, {"REMAP_NAME", TransformParam::REMAP_NAME}, {"REMAP_SCHEMA", TransformParam::REMAP_SCHEMA}, {"REMAP_TABLESPACE", TransformParam::REMAP_TABLESPACE}, {"REVOKE_FROM", TransformParam::REVOKE_FROM}, {"REUSE", TransformParam::REUSE}, {"SEGMENT_ATTRIBUTES", TransformParam::SEGMENT_ATTRIBUTES}, {"SIZE_BYTE_KEYWORD", TransformParam::SIZE_BYTE_KEYWORD}, {"SPECIFICATION", TransformParam::SPECIFICATION}, {"STORAGE", TransformParam::STORAGE}, {"SQLTERMINATOR", TransformParam::SQLTERMINATOR}, {"TABLESPACE", TransformParam::TABLESPACE}, {"TABLE_COMPRESSION_CLAUSE", TransformParam::TABLE_COMPRESSION_CLAUSE} }; std::string upper = str; std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); }); auto it = map.find(upper); if (it != map.end()) { return it->second; } return std::nullopt; } std::string_view ParamNameToStringView(TransformParam param_name){ static constexpr std::string_view names[] = { "BODY", "COLLATION_CLAUSE", "CONSTRAINTS", "CONSTRAINTS_AS_ALTER", "CONSTRAINT_NAME_FROM_INDEX", "CONSTRAINT_USE_DEFAULT_INDEX", "DEFAULT", "DWCS_CVT_CONSTRAINTS", "DWCS_CVT_IOTS", "FORCE", "INHERIT", "INSERT", "LOB_STORAGE", "OBJECT_ROW", "OID", "OMIT_ENCRYPTION_CLAUSE", "PARTITIONING", "PCTSPACE", "PHYSICAL_PROPERTIES", "PRETTY", "PRESERVE_LOCAL", "REF_CONSTRAINTS", "REMAP_COLUMN_NAME", "REMAP_DATAFILE", "REMAP_NAME", "REMAP_SCHEMA", "REMAP_TABLESPACE", "REVOKE_FROM", "REUSE", "SEGMENT_ATTRIBUTES", "SIZE_BYTE_KEYWORD", "SPECIFICATION", "STORAGE", "SQLTERMINATOR", "TABLESPACE", "TABLE_COMPRESSION_CLAUSE" }; return names[static_cast(param_name)]; } bool isValidObjectType(const std::string& str) { static const std::regex pattern( "(^(AQ_QUEUE|AQ_QUEUE_TABLE|AQ_TRANSFORM|ASSOCIATION|AUDIT|" "AUDIT_OBJ|CLUSTER|COMMENT|CONSTRAINT|CONTEXT|DATABASE_EXPORT|" "DB_LINK|DEFAULT_ROLE|DIMENSION|DIRECTORY|FGA_POLICY|FUNCTION|" "INDEX_STATISTICS|INDEX|INDEXTYPE|JAVA_SOURCE|JOB|LIBRARY|" "MATERIALIZED_VIEW|MATERIALIZED_VIEW_LOG|OBJECT_GRANT|ON_USER_GRANT|" "OPERATOR|PACKAGE|PACKAGE_SPEC|PACKAGE_BODY|PROCEDURE|PROFILE|" "PROXY|REF_CONSTRAINT|REFRESH_GROUP|RESOURCE_COST|RLS_CONTEXT|" "RLS_GROUP|RLS_POLICY|RMGR_CONSUMER_GROUP|RMGR_INTITIAL_CONSUMER_GROUP|" "RMGR_PLAN|RMGR_PLAN_DIRECTIVE|ROLE|ROLE_GRANT|ROLLBACK_SEGMENT|" "SCHEMA_EXPORT|SEQUENCE|SYNONYM|SYSTEM_GRANT|TABLE|TABLE_DATA|" "TABLE_EXPORT|TABLE_STATISTICS|TABLESPACE|TABLESPACE_QUOTA|" "TRANSPORTABLE_EXPORT|TRIGGER|TRUSTED_DB_LINK|TYPE|TYPE_SPEC|" "TYPE_BODY|USER|VIEW|XMLSCHEMA|XS_USER|XS_ROLE|XS_ROLESET|" "XS_ROLE_GRANT|XS_SECURITY_CLASS|XS_DATA_SECURITY|XS_ACL|" "XS_ACL_PARAM|XS_NAMESPACE)$)", std::regex::icase ); return std::regex_match(str, pattern); } bool isValidVersion(const std::string& version) { static const std::regex pattern( R"(^(COMPATIBLE|LATEST|\d+(\.\d+)*)$)", std::regex::icase ); return std::regex_match(version, pattern); } bool isValidModel(const std::string& model) { static const std::regex pattern( R"(^POSTGRESQL$)", std::regex::icase ); return std::regex_match(model, pattern); } bool isOTConsistentWithHeterOT(const ObjectType obj_type, const ObjectType hetero) noexcept { switch(hetero) { case ObjectType::ObjectTypeDatabaseExport: { switch(obj_type) { case ObjectType::ObjectTypeAssociation: case ObjectType::ObjectTypeAudit: case ObjectType::ObjectTypeAuditObj: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeComment: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeContext: case ObjectType::ObjectTypeDbLink: case ObjectType::ObjectTypeDefaultRole: case ObjectType::ObjectTypeDimension: case ObjectType::ObjectTypeDirectory: case ObjectType::ObjectTypeFgaPolicy: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeIndexStatistics: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeIndextype: case ObjectType::ObjectTypeJavaSource: case ObjectType::ObjectTypeJob: case ObjectType::ObjectTypeLibrary: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: case ObjectType::ObjectTypeObjectGrant: case ObjectType::ObjectTypeOperator: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypePackageSpec: case ObjectType::ObjectTypePackageBody: //case ObjectType::ObjectTypePasswordHistory: //case ObjectType::ObjectTypePasswordVerifyFunction: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeProfile: case ObjectType::ObjectTypeProxy: case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeRefreshGroup: case ObjectType::ObjectTypeResourceCost: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeRoleGrant: case ObjectType::ObjectTypeRollbackSegment: case ObjectType::ObjectTypeSequence: case ObjectType::ObjectTypeSynonym: case ObjectType::ObjectTypeSystemGrant: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTableData: case ObjectType::ObjectTypeTableStatistics: case ObjectType::ObjectTypeTablespace: case ObjectType::ObjectTypeTablespaceQuota: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeTrustedDbLink: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeTypeBody: case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeXmlschema: return true; default: return false; } break; } case ObjectType::ObjectTypeSchemaExport: { switch(obj_type) { case ObjectType::ObjectTypeAuditObj: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeComment: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeDbLink: case ObjectType::ObjectTypeDefaultRole: // if INCLUDE_USER is set TODO case ObjectType::ObjectTypeDimension: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeIndexStatistics: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeIndextype: case ObjectType::ObjectTypeJavaSource: case ObjectType::ObjectTypeJob: case ObjectType::ObjectTypeLibrary: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: case ObjectType::ObjectTypeObjectGrant: case ObjectType::ObjectTypeOperator: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypePackageSpec: case ObjectType::ObjectTypePackageBody: //case ObjectType::ObjectTypePasswordHistory: // if INCLUDE_USER is set TODO case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeRefreshGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeSequence: case ObjectType::ObjectTypeSynonym: case ObjectType::ObjectTypeSystemGrant: // if INCLUDE_USER is set TODO case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTableData: case ObjectType::ObjectTypeTableStatistics: case ObjectType::ObjectTypeTablespaceQuota: // if INCLUDE_USER is set TODO case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeTypeBody: case ObjectType::ObjectTypeUser: // if INCLUDE_USER is set TODO case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeXmlschema: return true; default: return false; } break; } case ObjectType::ObjectTypeTableExport: { switch(obj_type) { case ObjectType::ObjectTypeAuditObj: case ObjectType::ObjectTypeComment: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeIndexStatistics: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeObjectGrant: case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTableData: case ObjectType::ObjectTypeTableStatistics: case ObjectType::ObjectTypeTrigger: return true; default: return false; } break; } case ObjectType::ObjectTypeTransportableExport: { switch(obj_type) { case ObjectType::ObjectTypeAuditObj: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeComment: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeFgaPolicy: case ObjectType::ObjectTypeIndexStatistics: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeObjectGrant: case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTableData: case ObjectType::ObjectTypeTableStatistics: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeTypeBody: return true; default: return false; } break; } default: return false; } // unreachable return true; } /* Should only check consistency of filter name with initial object type set by dbms_metadata_open(). For checking if object type path is consistent with object type there exists another check */ bool isFNConsistentWithOT(const ObjectType obj_type, const FilterName filter) noexcept { // There are a pair of universal filters if (filter == FilterName::FNCustomFilter || filter == FilterName::FNEdition) { return true; } // Strong correspondence switch(obj_type) { case ObjectType::ObjectTypeTableExport: { switch(filter) { case FilterName::FNExcludeTables: case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: case FilterName::FNSchema: case FilterName::FNSchemaExpr: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: case FilterName::FNBeginWith: case FilterName::FNBeginAfter: case FilterName::FNEndBefore: case FilterName::FNEndWith: return true; default: return false; } break; } case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypeType: { switch(filter) { case FilterName::FNSpecification: case FilterName::FNBody: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeTable: { switch(filter) { case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: case FilterName::FNPrimary: case FilterName::FNSecondary: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: case FilterName::FNSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeCluster: { switch(filter) { case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: { switch(filter) { case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: case FilterName::FNSystemGenerated: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeTableData: { switch(filter) { case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeTransportableExport: { switch(filter) { case FilterName::FNTablespace: case FilterName::FNTablespaceExpr: case FilterName::FNBeginWith: case FilterName::FNBeginAfter: case FilterName::FNEndBefore: case FilterName::FNEndWith: return true; default: return false; } break; } case ObjectType::ObjectTypeTrigger: { switch(filter) { case FilterName::FNSystemGenerated: case FilterName::FNName: case FilterName::FNNameExpr: case FilterName::FNExcludeNameExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeObjectGrant: { switch(filter) { case FilterName::FNGrantor: return true; default: return false; } break; } case ObjectType::ObjectTypeSynonym: case ObjectType::ObjectTypeJavaSource: case ObjectType::ObjectTypeXmlschema: { switch(filter) { case FilterName::FNLongname: case FilterName::FNLongnameExpr: return true; default: return false; } break; } case ObjectType::ObjectTypeSchemaExport: { switch(filter) { case FilterName::FNSchema: case FilterName::FNSchemaExpr: case FilterName::FNIncludeUser: case FilterName::FNBeginWith: case FilterName::FNBeginAfter: case FilterName::FNEndBefore: case FilterName::FNEndWith: return true; default: return false; } break; } case ObjectType::ObjectTypeDatabaseExport: { switch(filter) { case FilterName::FNSchema: case FilterName::FNSchemaExpr: case FilterName::FNIncludeUser: case FilterName::FNBeginWith: case FilterName::FNBeginAfter: case FilterName::FNEndBefore: case FilterName::FNEndWith: return true; default: return false; } break; } // to be continued TO DO // let's consider all other combinations as possible for now default: return true; } // unreachable return true; } /* This one checks if specified object type path is consistent with initial object type set by dbms_metadata_open(). It's only about heterogenous object types. Also multiple nested paths to object types are currently not supported. Only one level of nesting is available for now. */ bool filterObjectTypePathCheck(const ObjectType obj_type, const OTPName obj_type_path, const FilterName filter) noexcept { /* those filters are not consistent with any object type path */ if ((filter == FilterName::FNBeginWith || filter == FilterName::FNBeginAfter || filter == FilterName::FNEndBefore || filter == FilterName::FNEndWith) && obj_type_path != OTPName::OTPNULL) // if we are here then it IS NOT OTPNull but for safety reasons we still check { return false; } switch(obj_type) { case ObjectType::ObjectTypeTableExport: { switch(obj_type_path) { case OTPName::OTPAuditObj: case OTPName::OTPComment: case OTPName::OTPConstraint: case OTPName::OTPIndex: case OTPName::OTPObjectGrant: case OTPName::OTPRefConstraint: case OTPName::OTPStatistics: case OTPName::OTPTable: case OTPName::OTPTableData: case OTPName::OTPTrigger: return true; break; case OTPName::OTPGrant: if (filter == FilterName::FNIncludePathExpr || filter == FilterName::FNExcludePathExpr) { return true; } else { return false; } break; default: return false; } break; } case ObjectType::ObjectTypeSchemaExport: { switch(obj_type_path) { case OTPName::OTPAssociation: case OTPName::OTPAuditObj: case OTPName::OTPCluster: case OTPName::OTPComment: case OTPName::OTPConstraint: case OTPName::OTPDBLink: case OTPName::OTPDefaultRole: case OTPName::OTPDimension: case OTPName::OTPFunction: case OTPName::OTPIndex: case OTPName::OTPIndexType: case OTPName::OTPJavaSource: case OTPName::OTPJob: case OTPName::OTPLibrary: case OTPName::OTPMaterializedView: case OTPName::OTPMaterializedViewLog: case OTPName::OTPObjectGrant: case OTPName::OTPOperator: case OTPName::OTPPackage: case OTPName::OTPPackageBody: case OTPName::OTPPackageSpec: case OTPName::OTPPasswordHistory: case OTPName::OTPProcedure: case OTPName::OTPRefConstraint: case OTPName::OTPRefreshGroup: case OTPName::OTPSequence: case OTPName::OTPStatistics: case OTPName::OTPSynonym: case OTPName::OTPTable: case OTPName::OTPTableData: case OTPName::OTPTablespaceQuota: case OTPName::OTPTrigger: case OTPName::OTPXsSecurityClass: case OTPName::OTPXsDataSecurity: case OTPName::OTPXsAcl: case OTPName::OTPType: case OTPName::OTPTypeBody: case OTPName::OTPTypeSpec: case OTPName::OTPUser: case OTPName::OTPView: return true; break; case OTPName::OTPGrant: if (filter == FilterName::FNIncludePathExpr || filter == FilterName::FNExcludePathExpr) { return true; } else { return false; } break; default: return false; } break; } case ObjectType::ObjectTypeDatabaseExport: { switch(obj_type_path) { case OTPName::OTPAssociation: case OTPName::OTPAudit: case OTPName::OTPAuditObj: case OTPName::OTPCluster: case OTPName::OTPComment: case OTPName::OTPConstraint: case OTPName::OTPContext: case OTPName::OTPDBLink: case OTPName::OTPDefaultRole: case OTPName::OTPDimension: case OTPName::OTPDirectory: case OTPName::OTPFGAPolicy: case OTPName::OTPFunction: case OTPName::OTPIndex: case OTPName::OTPIndexType: case OTPName::OTPJavaSource: case OTPName::OTPJob: case OTPName::OTPLibrary: case OTPName::OTPMaterializedView: case OTPName::OTPMaterializedViewLog: case OTPName::OTPObjectGrant: case OTPName::OTPOperator: case OTPName::OTPPackage: case OTPName::OTPPackageBody: case OTPName::OTPPackageSpec: case OTPName::OTPPasswordHistory: case OTPName::OTPProcedure: case OTPName::OTPProfile: case OTPName::OTPProxy: case OTPName::OTPRefConstraint: case OTPName::OTPRefreshGroup: case OTPName::OTPRLSGroup: case OTPName::OTPRLSContext: case OTPName::OTPRLSPolicy: case OTPName::OTPRole: case OTPName::OTPRoleGrant: case OTPName::OTPRollbackSegment: case OTPName::OTPSequence: case OTPName::OTPStatistics: case OTPName::OTPSynonym: case OTPName::OTPSystemGrant: case OTPName::OTPTable: case OTPName::OTPTableData: case OTPName::OTPTablespace: case OTPName::OTPTablespaceQuota: case OTPName::OTPTrigger: case OTPName::OTPXsUser: case OTPName::OTPXsRole: case OTPName::OTPXsSecurityClass: case OTPName::OTPXsDataSecurity: case OTPName::OTPXsAcl: case OTPName::OTPXsNamespace: case OTPName::OTPTrustedDBLink: case OTPName::OTPType: case OTPName::OTPTypeBody: case OTPName::OTPTypeSpec: case OTPName::OTPUser: case OTPName::OTPView: return true; break; case OTPName::OTPGrant: case OTPName::OTPPasswordVerifyFunction: case OTPName::OTPResourceCost: case OTPName::OTPSchema: if (filter == FilterName::FNIncludePathExpr || filter == FilterName::FNExcludePathExpr) { return true; } else { return false; } break; default: return false; } break; } case ObjectType::ObjectTypeTransportableExport: { switch(obj_type_path) { case OTPName::OTPCluster: case OTPName::OTPComment: case OTPName::OTPConstraint: case OTPName::OTPFGAPolicy: case OTPName::OTPIndex: case OTPName::OTPMaterializedView: case OTPName::OTPMaterializedViewLog: case OTPName::OTPRLSContext: case OTPName::OTPRLSGroup: case OTPName::OTPRLSPolicy: case OTPName::OTPStatistics: case OTPName::OTPTableData: case OTPName::OTPTablespace: case OTPName::OTPTrigger: return true; break; default: return false; } break; } default: return false; } // unreachable return true; } bool isAttrNameConsistentWithOT(const ObjectType obj_type, const AttrName attr) noexcept { // Universal attributes if (attr == AttrName::ANXPath || attr == AttrName::ANConstraintState || attr == AttrName::ANColumnAttribute || attr == AttrName::ANVerb || attr == AttrName::ANAlterable || attr == AttrName::ANClauseType || attr == AttrName::ANConstraintType) { return true; } // heterogeneous object type if (obj_type == ObjectType::ObjectTypeTableExport || obj_type == ObjectType::ObjectTypeSchemaExport || obj_type == ObjectType::ObjectTypeDatabaseExport || obj_type == ObjectType::ObjectTypeTransportableExport) { // should be checked in query parsing stage, so return true for now return true; } // maybe the best way is to query postgresql analogue of DBMS_METADATA_PARSE_ITEMS // Strong correspondence switch(obj_type) { #if 0 case ObjectType::ObjectTypeAlterFunction: case ObjectType::ObjectTypeAlterPackageBody: case ObjectType::ObjectTypeAlterPackageSpec: case ObjectType::ObjectTypeAlterProcedure: case ObjectType::ObjectTypeMaterializedZonemap: case ObjectType::ObjectTypeProcDepObj: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeAnalyticView: case ObjectType::ObjectTypeAttributeDimension: case ObjectType::ObjectTypeHierarchy: case ObjectType::ObjectTypeMLEENV: case ObjectType::ObjectTypeMLEModule: case ObjectType::ObjectTypePropertyGraph: case ObjectType::ObjectTypeSQLDomain: { switch(attr) { case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeAuditContext: case ObjectType::ObjectTypeAuditPolicy: case ObjectType::ObjectTypeAuditPolicyEnable: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANGrantee: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeClustering: case ObjectType::ObjectTypeDomainAssociation: case ObjectType::ObjectTypeLogicalPartitionTracking: case ObjectType::ObjectTypePostTableAction: case ObjectType::ObjectTypePreTableAction: case ObjectType::ObjectTypeProcActInstance: case ObjectType::ObjectTypeProcDepObjAudit: case ObjectType::ObjectTypeProcObjAudit: case ObjectType::ObjectTypeRADMPolicy: case ObjectType::ObjectTypeUserPrefStatistics: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeCodeBaseGrant: case ObjectType::ObjectTypeSchemaGrant: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANGrantor: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeDomainIndexPartition: case ObjectType::ObjectTypeSubpartition: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANTablespace: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeDVPS*: // many of them case ObjectType::ObjectTypeEndPlugTSBLK: case ObjectType::ObjectTypeMarker: case ObjectType::ObjectTypePlugTSBLK: case ObjectType::ObjectTypeProcAudit: case ObjectType::ObjectTypeRADMFPTM: case ObjectType::ObjectTypeRADMPolicyExpr: { switch(attr) { case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeEXPXMLSchema: case ObjectType::ObjectTypeIncType: case ObjectType::ObjectTypeJavaClass: case ObjectType::ObjectTypeJavaResource: case ObjectType::ObjectTypePostDataTable: case ObjectType::ObjectTypeProcObj: { switch(attr) { case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeIdentityColumn: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypePartition: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: case AttrName::ANTablespace: return true; default: return false; } break; } case ObjectType::ObjectTypePasswordHistory: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANGrantee: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypePasswordVerifyFunction: { switch(attr) { case AttrName::ANGrantor: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypePlugTSTablespace: { switch(attr) { case AttrName::ANObjectType: case AttrName::ANObjectTablespace: return true; default: return false; } break; } case ObjectType::ObjectTypeProcactSchema: { switch(attr) { case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeProcactSchemaPKG: case ObjectType::ObjectTypeProcactSysPKG: { switch(attr) { case AttrName::ANName: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeProcactSystem: case ObjectType::ObjectTypeProcSystemGrant: { switch(attr) { case AttrName::ANGrantor: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeProcDepObjGrant: case ObjectType::ObjectTypeProcObjGrant: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANGrantor: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeTablespaceILMPolicy: { switch(attr) { case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeVectorIndex: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: case AttrName::ANSystemGenerated: return true; default: return false; } break; } case ObjectType::ObjectTypeXsGrant: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } #endif case ObjectType::ObjectTypeAqQueue: case ObjectType::ObjectTypeAqQueueTable: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeAqTransform: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeDbLink: case ObjectType::ObjectTypeDimension: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeIndextype: case ObjectType::ObjectTypeJavaSource: case ObjectType::ObjectTypeLibrary: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeOperator: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypePackageSpec: case ObjectType::ObjectTypePackageBody: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeRefreshGroup: case ObjectType::ObjectTypeRmgrConsumerGroup: case ObjectType::ObjectTypeRmgrPlan: case ObjectType::ObjectTypeSequence: case ObjectType::ObjectTypeSynonym: case ObjectType::ObjectTypeTypeBody: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeXmlschema: { switch(attr) { case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeAssociation: case ObjectType::ObjectTypeAuditObj: case ObjectType::ObjectTypeIndexStatistics: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeTableStatistics: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeAudit: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeComment: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANDelTombstone: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeRefConstraint: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: case AttrName::ANSystemGenerated: return true; default: return false; } break; } case ObjectType::ObjectTypeContext: case ObjectType::ObjectTypeDirectory: case ObjectType::ObjectTypeProfile: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeRollbackSegment: case ObjectType::ObjectTypeTablespace: case ObjectType::ObjectTypeTrustedDbLink: { switch(attr) { case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeDefaultRole: case ObjectType::ObjectTypeOnUserGrant: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANGrantor: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeFgaPolicy: case ObjectType::ObjectTypeRmgrPlanDirective: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeTableData: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANDelTombstone: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: case AttrName::ANSystemGenerated: case AttrName::ANTablespace: return true; default: return false; } break; } case ObjectType::ObjectTypeJob: { switch(attr) { case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeMaterializedViewLog: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeObjectGrant: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANGrantee: case AttrName::ANGrantor: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeProxy: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeResourceCost: { switch(attr) { case AttrName::ANGrantor: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeRmgrIntitialConsumerGroup: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeRoleGrant: case ObjectType::ObjectTypeSystemGrant: case ObjectType::ObjectTypeTablespaceQuota: case ObjectType::ObjectTypeXsRoleGrant: { switch(attr) { case AttrName::ANGrantee: case AttrName::ANGrantor: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeTable: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANDelTombstone: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: case AttrName::ANTablespace: return true; default: return false; } break; } case ObjectType::ObjectTypeTrigger: { switch(attr) { case AttrName::ANBaseObjectName: case AttrName::ANBaseObjectSchema: case AttrName::ANBaseObjectType: case AttrName::ANEnable: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeUser: { switch(attr) { case AttrName::ANGrantor: case AttrName::ANLongname: case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeXsAcl: case ObjectType::ObjectTypeXsDataSecurity: case ObjectType::ObjectTypeXsSecurityClass: case ObjectType::ObjectTypeXsUser: { switch(attr) { case AttrName::ANName: case AttrName::ANObjectType: case AttrName::ANSchema: return true; default: return false; } break; } case ObjectType::ObjectTypeXsAclParam: case ObjectType::ObjectTypeXsNamespace: case ObjectType::ObjectTypeXsRole: case ObjectType::ObjectTypeXsRoleset: { switch(attr) { case AttrName::ANName: case AttrName::ANObjectType: return true; default: return false; } break; } case ObjectType::ObjectTypeNull: return false; // let's consider all other combinations as not possible for now default: return false; } // unreachable return true; } bool isOTConsistentWithTransform(const TransformType transform_type, const ObjectType obj_type) noexcept { // There are a pair of universal transformations if (transform_type == TransformType::DDL || transform_type == TransformType::MODIFY) { return true; } // Strong correspondence switch(transform_type) { case TransformType::ALTERDDL: { switch(obj_type) { case ObjectType::ObjectTypeAqQueue: case ObjectType::ObjectTypeAqQueueTable: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeContext: case ObjectType::ObjectTypeDbLink: case ObjectType::ObjectTypeFgaPolicy: //case ObjectType::ObjectTypeDomainIndexPartition: case ObjectType::ObjectTypeIndex: //case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: //case ObjectType::ObjectTypePartition: //case ObjectType::ObjectTypeProcactSysPkg: //case ObjectType::ObjectTypeProcactSchemaPkg: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeSequence: //case ObjectType::ObjectTypeSubpartition: case ObjectType::ObjectTypeSynonym: //case ObjectType::ObjectTypeSynonymObjnum: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTablespace: //case ObjectType::ObjectTypeTablespaceSet: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: return true; default: return false; } break; } case TransformType::ALTERXML: { switch(obj_type) { case ObjectType::ObjectTypeAqQueue: case ObjectType::ObjectTypeAqQueueTable: case ObjectType::ObjectTypeCluster: //case ObjectType::ObjectTypeDomainIndexPartition: case ObjectType::ObjectTypeIndex: //case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: //case ObjectType::ObjectTypePartition: //case ObjectType::ObjectTypeProcactSysPkg: //case ObjectType::ObjectTypeProcactSchemaPkg: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeSequence: //case ObjectType::ObjectTypeSubpartition: case ObjectType::ObjectTypeSynonym: //case ObjectType::ObjectTypeSynonymObjnum: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTablespace: //case ObjectType::ObjectTypeTablespaceSet: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: return true; default: return false; } break; } case TransformType::SXML: { switch(obj_type) { case ObjectType::ObjectTypeAqQueue: case ObjectType::ObjectTypeAqQueueTable: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeContext: case ObjectType::ObjectTypeDbLink: //case ObjectType::ObjectTypeDomainIndexPartition: //case ObjectType::ObjectTypeDpstreamTable: case ObjectType::ObjectTypeFgaPolicy: case ObjectType::ObjectTypeIndex: //case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: //case ObjectType::ObjectTypePartition: //case ObjectType::ObjectTypeProcactSysPkg: //case ObjectType::ObjectTypeProcactSchemaPkg: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeSequence: //case ObjectType::ObjectTypeSqlDomain: //case ObjectType::ObjectTypeSubpartition: case ObjectType::ObjectTypeSynonym: //case ObjectType::ObjectTypeSynonymObjnum: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTablespace: //case ObjectType::ObjectTypeTablespaceSet: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeTypeBody: case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: return true; default: return false; } break; } case TransformType::SXMLDDL: { switch(obj_type) { case ObjectType::ObjectTypeAqQueue: case ObjectType::ObjectTypeAqQueueTable: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeContext: case ObjectType::ObjectTypeDbLink: //case ObjectType::ObjectTypeDomainIndexPartition: case ObjectType::ObjectTypeFgaPolicy: case ObjectType::ObjectTypeIndex: //case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: //case ObjectType::ObjectTypePartition: //case ObjectType::ObjectTypeProcactSysPkg: //case ObjectType::ObjectTypeProcactSchemaPkg: case ObjectType::ObjectTypeRlsContext: case ObjectType::ObjectTypeRlsGroup: case ObjectType::ObjectTypeRlsPolicy: case ObjectType::ObjectTypeRole: case ObjectType::ObjectTypeSequence: //case ObjectType::ObjectTypeSqlDomain: //case ObjectType::ObjectTypeSubpartition: case ObjectType::ObjectTypeSynonym: //case ObjectType::ObjectTypeSynonymObjnum: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeTablespace: //case ObjectType::ObjectTypeTablespaceSet: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTypeSpec: case ObjectType::ObjectTypeTypeBody: case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: return true; default: return false; } break; } case TransformType::MODIFYSXML: { switch(obj_type) { //case ObjectType::ObjectTypeDomainIndexPartition: case ObjectType::ObjectTypeIndex: //case ObjectType::ObjectTypeIndexPartition: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: //case ObjectType::ObjectTypePartition: //case ObjectType::ObjectTypeProcactSysPkg: //case ObjectType::ObjectTypeProcactSchemaPkg: //case ObjectType::ObjectTypeSubpartition: case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeView: return true; default: return false; } break; } // let's consider all other combinations as possible for now default: return true; } // unreachable return true; } bool isParamNameConsistentWithOT(const TransformType transform_type, const ObjectType obj_type, const TransformParam transform_param) noexcept { if (transform_type == TransformType::DDL) { if (transform_param == TransformParam::PRETTY || transform_param == TransformParam::SQLTERMINATOR || transform_param == TransformParam::DEFAULT || transform_param == TransformParam::INHERIT) { return true; } switch(obj_type) { case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeTrigger: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: return true; default: return false; } break; } case ObjectType::ObjectTypeTable: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::OMIT_ENCRYPTION_CLAUSE: case TransformParam::DWCS_CVT_IOTS: case TransformParam::DWCS_CVT_CONSTRAINTS: case TransformParam::CONSTRAINT_USE_DEFAULT_INDEX: case TransformParam::CONSTRAINT_NAME_FROM_INDEX: case TransformParam::CONSTRAINTS: case TransformParam::REF_CONSTRAINTS: case TransformParam::CONSTRAINTS_AS_ALTER: case TransformParam::OID: case TransformParam::SIZE_BYTE_KEYWORD: case TransformParam::PARTITIONING: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PCTSPACE: case TransformParam::LOB_STORAGE: case TransformParam::TABLE_COMPRESSION_CLAUSE: return true; default: return false; } break; } case ObjectType::ObjectTypeConstraint: { switch(transform_param) { case TransformParam::DWCS_CVT_CONSTRAINTS: case TransformParam::CONSTRAINT_USE_DEFAULT_INDEX: case TransformParam::CONSTRAINT_NAME_FROM_INDEX: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeCluster: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PCTSPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeView: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::FORCE: return true; default: return false; } break; } case ObjectType::ObjectTypePackage: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::SPECIFICATION: case TransformParam::BODY: return true; default: return false; } break; } case ObjectType::ObjectTypeType: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::OID: case TransformParam::SPECIFICATION: case TransformParam::BODY: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: { switch(transform_param) { case TransformParam::PARTITIONING: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PCTSPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeRollbackSegment: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PCTSPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeTablespace: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::REUSE: case TransformParam::PCTSPACE: return true; default: return false; } break; } /* case ObjectType::ObjectTypeOutline: { switch(transform_type) { case TransformParam::INSERT: return true; default: return false; } break; } */ case ObjectType::ObjectTypeRole: { switch(transform_param) { case TransformParam::REVOKE_FROM: return true; default: return false; } break; } default: return false; } } else if (transform_type == TransformType::MODIFY) { if (transform_param == TransformParam::OBJECT_ROW) { return true; } else { return false; } } else if (transform_type == TransformType::SXML) { switch(obj_type) { case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypeTrigger: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: return true; default: return false; } break; } case ObjectType::ObjectTypeTable: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::CONSTRAINTS: case TransformParam::REF_CONSTRAINTS: case TransformParam::OID: case TransformParam::PARTITIONING: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PHYSICAL_PROPERTIES: return true; default: return false; } break; } case ObjectType::ObjectTypeCluster: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeMaterializedView: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PHYSICAL_PROPERTIES: return true; default: return false; } break; } case ObjectType::ObjectTypeType: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: case TransformParam::OID: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: { switch(transform_param) { case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PHYSICAL_PROPERTIES: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::PARTITIONING: return true; default: return false; } break; } case ObjectType::ObjectTypeMaterializedViewLog: { switch(transform_param) { case TransformParam::STORAGE: case TransformParam::TABLESPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeRollbackSegment: case ObjectType::ObjectTypeTablespace: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: return true; default: return false; } break; } default: return false; } } else if (transform_type == TransformType::MODIFYSXML) { switch(obj_type) { case ObjectType::ObjectTypeTable: { switch(transform_param) { case TransformParam::CONSTRAINTS: case TransformParam::REF_CONSTRAINTS: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::REMAP_NAME: case TransformParam::REMAP_SCHEMA: case TransformParam::REMAP_COLUMN_NAME: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeMaterializedView: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::REMAP_NAME: case TransformParam::REMAP_SCHEMA: case TransformParam::REMAP_COLUMN_NAME: return true; default: return false; } break; } case ObjectType::ObjectTypeMaterializedViewLog: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::REMAP_NAME: case TransformParam::REMAP_SCHEMA: return true; default: return false; } break; } case ObjectType::ObjectTypeView: { switch(transform_param) { case TransformParam::REMAP_NAME: case TransformParam::REMAP_SCHEMA: case TransformParam::REMAP_COLUMN_NAME: return true; default: return false; } break; } default: return false; } } else if (transform_type == TransformType::SXMLDDL) { switch(obj_type) { case ObjectType::ObjectTypeTable: { switch(transform_param) { case TransformParam::CONSTRAINTS: case TransformParam::REF_CONSTRAINTS: case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PARTITIONING: case TransformParam::COLLATION_CLAUSE: case TransformParam::OID: return true; default: return false; } break; } case ObjectType::ObjectTypeUser: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypeType: case ObjectType::ObjectTypeTrigger: { switch(transform_param) { case TransformParam::COLLATION_CLAUSE: return true; default: return false; } break; } case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeMaterializedView: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::COLLATION_CLAUSE: return true; default: return false; } break; } case ObjectType::ObjectTypeIndex: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: case TransformParam::PARTITIONING: case TransformParam::PRESERVE_LOCAL: return true; default: return false; } break; } case ObjectType::ObjectTypeMaterializedViewLog: { switch(transform_param) { case TransformParam::SEGMENT_ATTRIBUTES: case TransformParam::STORAGE: case TransformParam::TABLESPACE: return true; default: return false; } break; } case ObjectType::ObjectTypeTablespace: { switch(transform_param) { case TransformParam::REUSE: return true; default: return false; } break; } default: return false; } } else { return false; } // unreachable return true; } bool isRemapParamNameConsistentWithOT(const TransformType transform_type, const ObjectType obj_type, const TransformParam transform_param) noexcept { if (transform_type == TransformType::MODIFY) { switch(transform_param) { case TransformParam::REMAP_DATAFILE: { switch(obj_type) { case ObjectType::ObjectTypeLibrary: case ObjectType::ObjectTypeTablespace: case ObjectType::ObjectTypeDirectory: return true; default: return false; } break; } case TransformParam::REMAP_NAME: { switch(obj_type) { case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeSequence: case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeProcedure: case ObjectType::ObjectTypePackage: case ObjectType::ObjectTypePackageBody: case ObjectType::ObjectTypeTrigger: case ObjectType::ObjectTypeType: // and more of them named objects TODO return true; default: return false; } break; } case TransformParam::REMAP_SCHEMA: { switch(obj_type) { case ObjectType::ObjectTypeUser: // add schema and granted and dependent objects TODO return true; default: return false; } break; } case TransformParam::REMAP_TABLESPACE: { switch(obj_type) { case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeCluster: case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeRollbackSegment: case ObjectType::ObjectTypeMaterializedView: case ObjectType::ObjectTypeMaterializedViewLog: case ObjectType::ObjectTypeTablespaceQuota: return true; default: return false; } break; } default: return false; } } // probably ALTERXML TODO return false; } bool isValidDDLTransform(const std::string& str) { static const std::regex pattern( "(^(PRETTY|SQLTERMINATOR|CONSTRAINTS|REF_CONSTRAINTS|" "CONSTRAINTS_AS_ALTER|OID|SIZE_BYTE_KEYWORD|PARTITIONING|" "SEGMENT_ATTRIBUTES|STORAGE|TABLESPACE|SPECIFICATION|BODY|FORCE|" "REUSE|OMIT_ENCRYPTION_CLAUSE|DWCS_CVT_IOTS|DWCS_CVT_CONSTRAINTS|" "CONSTRAINT_USE_DEFAULT_INDEX|CONSTRAINT_NAME_FROM_INDEX|DEFAULT|" "INHERIT|COLLATION_CLAUSE|REVOKE_FROM|LOB_STORAGE|PCTSPACE|" "TABLE_COMPRESSION_CLAUSE)$)", std::regex::icase ); return std::regex_match(str, pattern); } bool OT_to_OTP_correspondence(const ObjectType obj_type, const OTPName obj_type_path) { static const std::unordered_map umap = { {ObjectType::ObjectTypeAssociation, OTPName::OTPAssociation}, {ObjectType::ObjectTypeAudit, OTPName::OTPAudit}, {ObjectType::ObjectTypeAuditObj, OTPName::OTPAuditObj}, {ObjectType::ObjectTypeCluster, OTPName::OTPCluster}, {ObjectType::ObjectTypeComment, OTPName::OTPComment}, {ObjectType::ObjectTypeConstraint, OTPName::OTPConstraint}, {ObjectType::ObjectTypeContext, OTPName::OTPContext}, {ObjectType::ObjectTypeDbLink, OTPName::OTPDBLink}, {ObjectType::ObjectTypeDefaultRole, OTPName::OTPDefaultRole}, {ObjectType::ObjectTypeDimension, OTPName::OTPDimension}, {ObjectType::ObjectTypeDirectory, OTPName::OTPDirectory}, {ObjectType::ObjectTypeFgaPolicy, OTPName::OTPFGAPolicy}, {ObjectType::ObjectTypeFunction, OTPName::OTPFunction}, {ObjectType::ObjectTypeIndex, OTPName::OTPIndex}, {ObjectType::ObjectTypeIndextype, OTPName::OTPIndexType}, {ObjectType::ObjectTypeJavaSource, OTPName::OTPJavaSource}, {ObjectType::ObjectTypeJob, OTPName::OTPJob}, {ObjectType::ObjectTypeLibrary, OTPName::OTPLibrary}, {ObjectType::ObjectTypeMaterializedView, OTPName::OTPMaterializedView}, {ObjectType::ObjectTypeMaterializedViewLog, OTPName::OTPMaterializedViewLog}, {ObjectType::ObjectTypeObjectGrant, OTPName::OTPObjectGrant}, {ObjectType::ObjectTypeOperator, OTPName::OTPOperator}, {ObjectType::ObjectTypePackage, OTPName::OTPPackage}, {ObjectType::ObjectTypePackageSpec, OTPName::OTPPackageSpec}, {ObjectType::ObjectTypePackageBody, OTPName::OTPPackageBody}, {ObjectType::ObjectTypeProcedure, OTPName::OTPProcedure}, {ObjectType::ObjectTypeProfile, OTPName::OTPProfile}, {ObjectType::ObjectTypeProxy, OTPName::OTPProxy}, {ObjectType::ObjectTypeRefConstraint, OTPName::OTPRefConstraint}, {ObjectType::ObjectTypeRefreshGroup, OTPName::OTPRefreshGroup}, {ObjectType::ObjectTypeResourceCost, OTPName::OTPResourceCost}, {ObjectType::ObjectTypeRlsContext, OTPName::OTPRLSContext}, {ObjectType::ObjectTypeRlsGroup, OTPName::OTPRLSGroup}, {ObjectType::ObjectTypeRlsPolicy, OTPName::OTPRLSPolicy}, {ObjectType::ObjectTypeRole, OTPName::OTPRole}, {ObjectType::ObjectTypeRoleGrant, OTPName::OTPRoleGrant}, {ObjectType::ObjectTypeRollbackSegment, OTPName::OTPRollbackSegment}, {ObjectType::ObjectTypeSequence, OTPName::OTPSequence}, {ObjectType::ObjectTypeSynonym, OTPName::OTPSynonym}, {ObjectType::ObjectTypeSystemGrant, OTPName::OTPSystemGrant}, {ObjectType::ObjectTypeTable, OTPName::OTPTable}, {ObjectType::ObjectTypeTableData, OTPName::OTPTableData}, {ObjectType::ObjectTypeTablespace, OTPName::OTPTablespace}, {ObjectType::ObjectTypeTablespaceQuota, OTPName::OTPTablespaceQuota}, {ObjectType::ObjectTypeTrigger, OTPName::OTPTrigger}, {ObjectType::ObjectTypeTrustedDbLink, OTPName::OTPTrustedDBLink}, {ObjectType::ObjectTypeType, OTPName::OTPType}, {ObjectType::ObjectTypeTypeSpec, OTPName::OTPTypeSpec}, {ObjectType::ObjectTypeTypeBody, OTPName::OTPTypeBody}, {ObjectType::ObjectTypeUser, OTPName::OTPUser}, {ObjectType::ObjectTypeView, OTPName::OTPView}, {ObjectType::ObjectTypeXsUser, OTPName::OTPXsUser}, {ObjectType::ObjectTypeXsRole, OTPName::OTPXsRole} }; auto it = umap.find(obj_type); if (it != umap.end()) { if (it->second == obj_type_path) { return true; } } return false; } // filter function typedef struct filter_diapason { OTPName start; OTPName stop; bool start_include; // включая старт bool stop_include; // включая стоп } filter_diapason_t; void init_filter_diapason(filter_diapason_t *diap){ if(diap){ diap->start = OTPUser; diap->start_include = true; diap->stop = OTPXsSecurityClass; diap->stop_include = true; } } void get_filter_diapason(Filter *fl, filter_diapason_t *diap){ init_filter_diapason(diap); for (Filter *f = fl; f != NULL; f = f->next) { if(f->name == FNBeginWith){ auto otp = dbms_metadata::stringToObjectTypePath(std::string(f->value)); if(otp != std::nullopt){ diap->start = otp.value(); diap->start_include = true; } } else if (f->name == FNBeginAfter){ auto otp = dbms_metadata::stringToObjectTypePath(std::string(f->value)); if(otp != std::nullopt){ diap->start = otp.value(); diap->start_include = false; } } else if(f->name == FNEndWith){ auto otp = dbms_metadata::stringToObjectTypePath(std::string(f->value)); if(otp != std::nullopt){ diap->stop = otp.value(); diap->stop_include = true; } } else if(f->name == FNEndBefore){ auto otp = dbms_metadata::stringToObjectTypePath(std::string(f->value)); if(otp != std::nullopt){ diap->stop = otp.value(); diap->stop_include = false; } } } } /* checks if type is in range defined by filters */ bool type_in_filter_diapason(OTPName type, filter_diapason_t *diap) { if (diap == nullptr) return false; // Порядок извлечения типов объектов (как в Oracle SCHEMA_EXPORT). // OTPNULL исключён. Порядок можно менять здесь. static const std::vector kOrder = { // Безопасность и учётные записи OTPUser, OTPSystemGrant, OTPDefaultRole, OTPRoleGrant, OTPTablespaceQuota, OTPPasswordHistory, OTPPasswordVerifyFunction, OTPProfile, OTPProxy, OTPObjectGrant, // Схема и табличные пространства OTPSchema, OTPTablespace, // Типы OTPTypeSpec, OTPTypeBody, OTPType, OTPJavaSource, OTPLibrary, // Последовательности OTPSequence, // Таблицы и данные OTPTable, OTPTableData, // Комментарии, ограничения, индексы, статистика OTPComment, OTPConstraint, OTPRefConstraint, OTPIndex, OTPStatistics, // Триггеры OTPTrigger, // Материализованные представления OTPMaterializedViewLog, OTPMaterializedView, // Представления и синонимы OTPView, OTPSynonym, // Программный код OTPProcedure, OTPFunction, OTPPackageSpec, OTPPackageBody, OTPPackage, // Расширения типов OTPOperator, OTPIndexType, // Кластеры OTPCluster, // Ссылки на удалённые БД OTPDBLink, OTPTrustedDBLink, // Прочие объекты схемы OTPJob, OTPDimension, OTPRefreshGroup, OTPRollbackSegment, OTPResourceCost, OTPDirectory, // RLS, аудит, контексты OTPContext, OTPRLSContext, OTPRLSGroup, OTPRLSPolicy, OTPFGAPolicy, OTPAudit, OTPAuditObj, OTPAssociation, // Real Application Security OTPXsUser, OTPXsRole, OTPXsAcl, OTPXsNamespace, OTPXsDataSecurity, OTPXsSecurityClass }; // Размер массива = максимальное значение enum + 1 static constexpr int kEnumSize = static_cast(OTPXsSecurityClass) + 1; // O(1)-таблица: enum → позиция в kOrder. Инициализируется один раз. static const std::array kPos = []{ std::array arr; arr.fill(-1); for (int i = 0; i < static_cast(kOrder.size()); ++i) arr[static_cast(kOrder[i])] = i; return arr; }(); auto pos = [](OTPName t) -> int { const int idx = static_cast(t); if (idx < 0 || idx >= kEnumSize) return -1; return kPos[idx]; }; const int typePos = pos(type); if (typePos < 0) return false; const int startPos = pos(diap->start); const int stopPos = pos(diap->stop); const int n = static_cast(kOrder.size()); const int lo = (startPos < 0) ? 0 : startPos; const int hi = (stopPos < 0) ? n - 1 : stopPos; // Как в Oracle: если границы заданы в обратном порядке — диапазон пуст. if (lo > hi) return false; const bool afterStart = diap->start_include ? (typePos >= lo) : (typePos > lo); const bool beforeStop = diap->stop_include ? (typePos <= hi) : (typePos < hi); return afterStart && beforeStop; } // общая функция фильтра, не для явного использования, рассчитывает что format только 2 %s содержит из подставляемого char *common_filter_condition(Filter *fl, const char *name, FilterName fn, const char *format, ObjectType object_type = ObjectTypeNull) { StringInfoData buf; bool first = true; if (name == NULL) return NULL; initStringInfo(&buf); for (Filter *f = fl; f != NULL; f = f->next) { // это нужный фильтр? if (f->name != fn) continue; /* If filter is set for any object type path then it will pass. If filter is set with specific object type path then it should match object type of entity for which we are collecting OIDs in this moment (subtype of heterogenous object type) */ if (f->obj_type_path != OTPNULL && !OT_to_OTP_correspondence(object_type, f->obj_type_path)) { continue; } if (f->value == NULL) continue; if (!first) appendStringInfoString(&buf, " AND "); appendStringInfo(&buf, format, name, f->value); first = false; } if (first) { pfree(buf.data); return NULL; } return buf.data; } char *common_boolean_filter_condition(Filter *fl, bool default_val, FilterName fn, const char *format, ObjectType object_type = ObjectTypeNull) { StringInfoData buf; bool first = true; initStringInfo(&buf); for (Filter *f = fl; f != NULL; f = f->next) { // это нужный фильтр? if (f->name != fn) continue; /* If filter is set for any object type path then it will pass. If filter is set with specific object type path then it should match object type of entity for which we are collecting OIDs in this moment (subtype of heterogenous object type) */ if (f->obj_type_path != OTPNULL && !OT_to_OTP_correspondence(object_type, f->obj_type_path)) { continue; } if (f->value == NULL) continue; if (!first) appendStringInfoString(&buf, " AND "); char *valupper = str_toupper(f->value, strlen(f->value), DEFAULT_COLLATION_OID); appendStringInfo(&buf, format, strcmp(valupper, "TRUE")==0 ? "TRUE" : "FALSE"); pfree(valupper); first = false; } if (first) { appendStringInfo(&buf, format, default_val ? "TRUE" : "FALSE"); } return buf.data; } // FILTER NAME char *filter_condition_name(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNName, "(%s = '%s')", object_type); } // FILTER NAME_EXPR char *filter_condition_name_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { StringInfoData buf; bool first = true; if (name == NULL) return NULL; initStringInfo(&buf); for (Filter *f = fl; f != NULL; f = f->next) { if (f->name != FNNameExpr) continue; /* If filter is set for any object type path then it will pass. If filter is set with specific object type path then it should match object type of entity for which we are collecting OIDs in this moment (subtype of heterogenous object type) */ if (f->obj_type_path != OTPNULL && !OT_to_OTP_correspondence(object_type, f->obj_type_path)) { continue; } if (f->value == NULL) continue; if (!first) appendStringInfoString(&buf, " AND "); appendStringInfo(&buf, "(%s %s)", name, f->value); first = false; } if (first) { pfree(buf.data); return NULL; } return buf.data; } // FILTER EXCLUDE_NAME_EXPR char *filter_condition_exclude_name_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNExcludeNameExpr, "(NOT (%s %s))", object_type); } // FILTER SCHEMA char *filter_condition_schema(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNSchema, "(%s = '%s')", object_type); } // FILTER SCHEMA_EXPR char *filter_condition_schema_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNSchemaExpr, "(%s %s)", object_type); } // FILTER TABLESPACE char *filter_condition_tablespace(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNTablespace, "(%s = '%s')", object_type); } // FILTER TABLESPACE_EXPR char *filter_condition_tablespace_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNTablespaceExpr, "(%s %s)", object_type); } // FILTER BASE_OBJECT_NAME char *filter_condition_base_object_name(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNBaseObjectName, "(%s = '%s')", object_type); } // FILTER BASE_OBJECT_SCHEMA char *filter_condition_base_object_schema(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNBaseObjectSchema, "(%s = '%s')", object_type); } // FILTER BASE_OBJECT_NAME_EXPR char *filter_condition_base_object_name_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNBaseObjectNameExpr, "(%s %s)", object_type); } // FILTER EXCLUDE_BASE_OBJECT_NAME_EXPR char *filter_condition_exclude_base_object_name_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNExcludeBaseObjectNameExpr, "(NOT (%s %s))", object_type); } // FILTER BASE_OBJECT_SCHEMA_EXPR char *filter_condition_base_object_schema_expr(Filter *fl, const char *name, ObjectType object_type = ObjectTypeNull) { return common_filter_condition(fl, name, FNBaseObjectSchemaExpr, "(%s %s)", object_type); } // FILTER EXCLUDE_TABLES char *filter_condition_exclude_tables(Filter *fl, const char *format, ObjectType object_type = ObjectTypeNull) { return common_boolean_filter_condition(fl, false, FNExcludeTables, format, object_type); } // FILTER PRIMARY char *filter_condition_primary(Filter *fl, const char *format, ObjectType object_type = ObjectTypeNull) { return common_boolean_filter_condition(fl, true, FNPrimary, format, object_type); } // FILTER SECONDARY char *filter_condition_secondary(Filter *fl, const char *format, ObjectType object_type = ObjectTypeNull) { return common_boolean_filter_condition(fl, true, FNSecondary, format, object_type); } // FILTER SYSTEM_GENERATED char *filter_condition_system_generated(Filter *fl, const char *format, ObjectType object_type = ObjectTypeNull) { return common_boolean_filter_condition(fl, true, FNSystemGenerated, format, object_type); } // FILTER INCLUDE_USER char *filter_condition_include_user(Filter *fl, const char *format, ObjectType object_type = ObjectTypeNull) { return common_boolean_filter_condition(fl, false, FNIncludeUser, format, object_type); } // defines char *build_view_ddl_text(Oid viewOid, char *viewName, char *schemaName, const int32 transform_handler); char* build_index_ddl_text(Oid indexOid, char *indexName, char *schemaName, const int32 transform_handler); char *build_seq_ddl_text(Oid seqOid, char *seqName, char *schemaName, const int32 transform_handler); char* build_trigger_ddl_text(Oid trigOid, char *trigName, char *schemaName, const int32 transform_handler); char* build_constraint_ddl(Oid constrOid, char *schema, char *constrName, const int32 transform_handler, ObjectType obj_type); char* build_function_ddl(Oid funcOid, char *schema, char *funcName, const int32 transform_handler, ObjectType obj_type); bool build_type_statement(Oid typeOid, Oid table_oid, const char typetype, char** ddl, const int32 transform_handler); void get_view_names_by_oid(Oid relOid, char **schemaName, char **viewName); void get_sequence_names_by_oid(Oid relOid, char **schemaName, char **viewName); bool get_trigger_names_by_oid(Oid relOid, char **schemaName, char **trigName); char* make_constraint_statement(Oid objectOid, char *schema, char *name, const int32 transform_handler); char *make_type_statement(Oid typeOid, const int32 transform_handler); TransformationObject::ParamValue get_ddl_transform_param(const int32 transform_handler, const char* transform_param, const int obj_type = ObjectType::ObjectTypeNull); char * get_string_argument(FunctionCallInfo fcinfo, int argnum) { if (PG_ARGISNULL(argnum)) return NULL; text *arg_txt = PG_GETARG_TEXT_PP(argnum); char *result = NULL; if (VARSIZE_ANY_EXHDR(arg_txt) == 0) return NULL; result = text_to_cstring(arg_txt); return result; } int32 get_numeric_argument_int32(FunctionCallInfo fcinfo, int argnum) { if(PG_ARGISNULL(argnum)) return 0; Numeric arg_num = PG_GETARG_NUMERIC(argnum); int32 res = DatumGetInt32(DirectFunctionCall1(numeric_int4, NumericGetDatum(arg_num))); return res; } int32 create_context(ObjectType type, const char* version, const char* model) { if (version == nullptr || model == nullptr) { return -1; } // Проверка, не заполнена ли карта целиком const size_t maxIds = static_cast(INT32_MAX); // от 1 до INT32_MAX включительно if (ctxMap.size() >= maxIds) { return -1; // все возможные идентификаторы заняты } int32 id = 0; // Поиск свободного идентификатора while (true) { id = genNextHandle(); if (ctxMap.find(id) == ctxMap.end()) { break; // нашли свободный } // Если карта заполнена, повторный поиск бессмыслен if (ctxMap.size() >= maxIds) { return -1; } // Иначе продолжаем цикл, genNextHandle() выдаст следующий } // Выделение памяти под структуру в TopMemoryContext MetadataContext* ctx = (MetadataContext*) MemoryContextAlloc( TopMemoryContext, sizeof(MetadataContext) ); if (ctx == nullptr) { return -1; } // Заполнение полей ctx->object_type = type; ctx->version = MemoryContextStrdup(TopMemoryContext, version); ctx->model = MemoryContextStrdup(TopMemoryContext, model); ctx->network_link = nullptr; ctx->filters = nullptr; ctx->attributes = nullptr; ctx->transforms = nullptr; ctx->fetch_count = 100; ctx->object_type_path = OTPName::OTPNULL; ctx->been_fetched = false; ctx->fetch_entries = nullptr; ctx->fetch_entries_count = 0; ctx->fetch_pos = 0; // Сохранение в карте ctxMap[id] = ctx; return id; } int32 AddTransformMapRecord(const TransformType type, const int32_t handle, const char* user_file, const int encoding, const ObjectType obj_type) { int32 id = 0; int obj_type_i = static_cast(obj_type); // checking if we have possible IDs left const size_t maxIds = static_cast(INT32_MAX); // 1 to INT32_MAX if (ctxTransformMap.size() >= maxIds) { return -1; } /* We can have two (or more) identical transforms added to the same open handle. Oracle seems to be allowing it but it reports error in fetch_xxx function(). Maybe the best way is to count a hash from (handle, transform_type) instead of plain id and check if map already has such key? TODO */ // searching for the free ID while (true) { id = genNextTransformHandle(); if (ctxTransformMap.find(id) == ctxTransformMap.end()) { break; } } /* As we have a C++ map of C++ objects here, I think that trying to allocate memory in the PG context for a C++ object with internal STL objects inside of it is a pointless and merciless way to do the things. For now it's placed in the heap. So it rather should be heavily refactored or left as is (TODO?) */ ctxTransformMap.try_emplace(id, type, handle, user_file, encoding, obj_type_i); return id; } Datum open(FunctionCallInfo fcinfo) { char *object_type = get_string_argument(fcinfo, 0); char *version = get_string_argument(fcinfo, 1); char *model = get_string_argument(fcinfo, 2); // netlink not support if(!PG_ARGISNULL(3)){ ereport(ERROR, (errmsg("Параметр network_link не поддерживается."))); } if(object_type == NULL){ ereport(ERROR, (errmsg("Параметр object_type не задан."))); } if(version == NULL){ ereport(ERROR, (errmsg("Параметр version не задан."))); } if(model == NULL){ ereport(ERROR, (errmsg("Параметр model не задан."))); } if(!isValidObjectType(std::string(object_type))){ ereport(ERROR, (errmsg("invalid input value %s for parameter OBJECT_TYPE in function OPEN", object_type))); } if(!isValidVersion(std::string(version))){ ereport(ERROR, (errmsg("invalid input value %s for parameter VERSION in function OPEN", version))); } if(!isValidModel(std::string(model))){ ereport(ERROR, (errmsg("invalid input value %s for parameter MODEL in function OPEN", model))); } auto type = stringToObjectType(std::string(object_type)); if(!type){ ereport(ERROR, (errmsg("invalid input value %s for parameter OBJECT_TYPE in function OPEN", object_type))); } int32 result = create_context(type.value(), version, model); if(result<0){ ereport(ERROR, (errmsg("Error create context"))); } pfree_all(object_type, version, model); return DirectFunctionCall1(int4_numeric, Int32GetDatum(result)); } Datum close(FunctionCallInfo fcinfo) { /* 1. Извлекаем аргумент как numeric */ Numeric num = PG_GETARG_NUMERIC(0); /* 2. Преобразуем numeric в int32 через встроенную функцию */ int32 ctxId; ctxId = DatumGetInt32(DirectFunctionCall1(numeric_int4, PointerGetDatum(num))); /* 3. Ищем контекст в глобальной карте */ auto it = ctxMap.find(ctxId); if (it == ctxMap.end()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value %d for parameter HANDLE in function CLOSE", ctxId))); /* 4. Удаляем запись и освобождаем память */ destroyFiltersByHandle(ctxId); // at this point we are sure that ctxId is valid destroyAttributesByHandle(ctxId); destroyTransformsByHandle(ctxId); MetadataContext *ctx = it->second; if (ctx->fetch_entries != nullptr) { pfree(ctx->fetch_entries); ctx->fetch_entries = nullptr; } ctxMap.erase(it); pfree_all(ctx); PG_RETURN_VOID(); } // ------------------------------------------------ Datum get_ddl(FunctionCallInfo fcinfo){ char *ch_object_type = get_string_argument(fcinfo, 0); char *name = get_string_argument(fcinfo, 1); char *schema = get_string_argument(fcinfo, 2); char *version = get_string_argument(fcinfo, 3); char *model = get_string_argument(fcinfo, 4); char *transform = get_string_argument(fcinfo, 5); ObjectType object_type = ObjectType::ObjectTypeNull; const char* func_name = "DBMS_METADATA_GET_DDL"; // object type check if (setObjectType(ch_object_type, object_type, func_name)) { // it cannot be a heterogeneous object type if (object_type == ObjectType::ObjectTypeTableExport || object_type == ObjectType::ObjectTypeSchemaExport || object_type == ObjectType::ObjectTypeDatabaseExport || object_type == ObjectType::ObjectTypeTransportableExport) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value \"%s\" for parameter OBJECT_TYPE" " in function %s", ch_object_type, func_name))); } } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value NULL for parameter OBJECT_TYPE in " "function %s", func_name))); } auto transform_name = TransformationObject::stringToTransformType(std::string(transform)); if (transform_name == std::nullopt) { auto obj_type_name = ObjectTypeToStringView(object_type); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid transform NAME parameter \"%s\" for object type " "\"%s\" in function %s", transform, obj_type_name.data(), func_name))); } else { if(transform_name.value() != TransformType::DDL) { ereport(ERROR, (errmsg("Transform type %s is not supported", transform))); } } switch(object_type){ case ObjectTypeTable: return get_ddl_table(name, schema, version, model, transform); case ObjectTypeView: return get_ddl_view(name, schema, version, model, transform); break; case ObjectTypeSequence: return get_ddl_sequence(name, schema, version, model, transform); break; case ObjectTypeConstraint: return get_ddl_constraint(name, schema, version, model, transform); break; case ObjectTypeRefConstraint: return get_ddl_ref_constraint(name, schema, version, model, transform); break; case ObjectTypeIndex: return get_ddl_index(name, schema, version, model, transform); break; case ObjectTypeTrigger: return get_ddl_trigger(name, schema, version, model, transform); break; case ObjectTypeType: return get_ddl_type(name, schema, version, model, transform); break; case ObjectTypeFunction: return get_ddl_function(name, schema, version, model, transform); break; case ObjectTypeProcedure: return get_ddl_function(name, schema, version, model, transform, false); break; case ObjectTypeRlsPolicy: return get_ddl_rlspolicy(name, schema, version, model, transform); break; case ObjectTypeComment: return get_ddl_comment(name, schema, version, model, transform); break; case ObjectTypeRole: return get_ddl_role(name, schema, version, model, transform); break; case ObjectTypeUser: return get_ddl_user(name, schema, version, model, transform); break; case ObjectTypeTablespace: return get_ddl_tablespace(name, schema, version, model, transform); break; case ObjectTypeMaterializedView: return get_ddl_materialized_view(name, schema, version, model, transform); break; case ObjectTypeOperator: return get_ddl_operator(name, schema, version, model, transform); break; default: ereport(ERROR, (errmsg("Поддержка %s не реализована", ch_object_type))); } } /* ----------------------------------------------- get_ddl support functions */ // oid по имени таблицы и схемы Oid getRelationOid(char *name, char *schema, bool missing_ok = false){ Oid tableOid; RangeVar *rv; /* 1. Создаём и заполняем структуру RangeVar */ rv = makeRangeVar(schema, /* имя схемы или NULL для поиска по путям */ name, /* имя таблицы */ -1); /* местоположение в исходном коде (неважно) */ /* 2. Получаем OID. Второй аргумент - режим блокировки (AccessShareLock - безопасно для чтения) , третий аргумент - missing_ok - не вызывает ошибку если не найдено */ tableOid = RangeVarGetRelid(rv, AccessShareLock, missing_ok); pfree(rv); return tableOid; } void get_object_names_by_oid(Oid relOid, char **schemaName, char **viewName) { HeapTuple tp; Form_pg_class classForm; Oid schemaOid; char *nspname; char *relname; /* 1. Получаем кортеж из системного кеша по OID отношения */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relOid))); classForm = (Form_pg_class) GETSTRUCT(tp); /* 2. Получаем OID схемы и извлекаем её имя */ schemaOid = classForm->relnamespace; nspname = get_namespace_name(schemaOid); if (!nspname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema with OID %u does not exist", schemaOid))); } /* 3. Копируем имя объекта */ relname = pstrdup(NameStr(classForm->relname)); ReleaseSysCache(tp); /* 4. Возвращаем результаты (память выделена через palloc, освобождать вызывающему) */ *schemaName = nspname; *viewName = relname; } // имя схемы и таблицы по её oid void get_table_names_by_oid(Oid relOid, char **schemaName, char **tableName) { HeapTuple tp; Form_pg_class classForm; Oid schemaOid; char relkind; char *nspname; char *relname; /* 1. Получаем кортеж из системного кеша по OID отношения */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relOid))); classForm = (Form_pg_class) GETSTRUCT(tp); /* 2. Проверяем тип отношения: допустимы только 'r' и 'p' */ relkind = classForm->relkind; if (relkind != RELKIND_RELATION && relkind != RELKIND_PARTITIONED_TABLE) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a table or partitioned table", NameStr(classForm->relname)))); } /* 3. Получаем OID схемы и извлекаем её имя */ schemaOid = classForm->relnamespace; nspname = get_namespace_name(schemaOid); if (!nspname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema with OID %u does not exist", schemaOid))); } /* 4. Копируем имя таблицы (безопасно, т.к. оно хранится в формате NameData) */ relname = pstrdup(NameStr(classForm->relname)); ReleaseSysCache(tp); /* 5. Возвращаем результаты */ *schemaName = nspname; *tableName = relname; } char * get_table_definition(Oid relid, char &relpersistence, bool segment_attributes) { Relation rel; TupleDesc tupdesc; int natts; StringInfoData buf; bool first = true; char *result; rel = relation_open(relid, AccessShareLock); tupdesc = RelationGetDescr(rel); natts = tupdesc->natts; initStringInfo(&buf); for (int i = 0; i < natts; i++) { Form_pg_attribute att = TupleDescAttr(tupdesc, i); char *attname = NameStr(att->attname); if (att->attnum <= 0 || att->attisdropped) continue; if (strcmp(attname, "tableoid") == 0 || strcmp(attname, "cmax") == 0 || strcmp(attname, "xmax") == 0 || strcmp(attname, "cmin") == 0 || strcmp(attname, "xmin") == 0 || strcmp(attname, "ctid") == 0) continue; if (!first) appendStringInfoChar(&buf, ','); first = false; const char *quoted = quote_identifier(attname); char *typname = format_type_with_typemod(att->atttypid, att->atttypmod); appendStringInfo(&buf, "%s %s", quoted, typname); if(attname != quoted) pfree((void *) quoted); pfree(typname); /* DEFAULT – безопасное извлечение через heap_getattr */ if (att->atthasdef) { Relation adrel; ScanKeyData skey[2]; SysScanDesc scan; HeapTuple adtup; adrel = table_open(AttrDefaultRelationId, AccessShareLock); ScanKeyInit(&skey[0], Anum_pg_attrdef_adrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relid)); ScanKeyInit(&skey[1], Anum_pg_attrdef_adnum, BTEqualStrategyNumber, F_INT2EQ, Int16GetDatum(att->attnum)); scan = systable_beginscan(adrel, AttrDefaultIndexId, true, NULL, 2, skey); adtup = systable_getnext(scan); if (HeapTupleIsValid(adtup)) { Datum adbin_datum; bool isnull; adbin_datum = heap_getattr(adtup, Anum_pg_attrdef_adbin, RelationGetDescr(adrel), &isnull); if (!isnull) { Datum expr_datum; char *expr_str; char *substr; expr_datum = DirectFunctionCall2(pg_get_expr, adbin_datum, ObjectIdGetDatum(relid)); expr_str = TextDatumGetCString(expr_datum); substr = pnstrdup(expr_str, 128); appendStringInfo(&buf, " DEFAULT %s", substr); pfree(substr); pfree(expr_str); } } systable_endscan(scan); table_close(adrel, AccessShareLock); } /* NOT NULL */ if (att->attnotnull) appendStringInfoString(&buf, " NOT NULL"); } /* Получаем relpersistence (оставляем для последующей доработки) */ if(segment_attributes) { relpersistence = rel->rd_rel->relpersistence; } relation_close(rel, AccessShareLock); result = pstrdup(buf.data); pfree(buf.data); return result; } char *make_create_table_statement(const char *schema_name, const char *table_name, char relpersistence, const char *table_def) { StringInfoData buf; char *quoted_schema = NULL; char *quoted_table = NULL; /* Экранируем имя таблицы */ quoted_table = (char *) quote_identifier(table_name); /* Экранируем схему */ quoted_schema = (char *) quote_identifier(schema_name); initStringInfo(&buf); appendStringInfoString(&buf, "-- Table definition\nCREATE "); if (relpersistence == 'u') appendStringInfoString(&buf, "UNLOGGED "); appendStringInfoString(&buf, "TABLE "); appendStringInfo(&buf, "%s.", quoted_schema); appendStringInfo(&buf, "%s (%s)", quoted_table, table_def); /* Освобождаем экранированные строки */ if(quoted_schema != schema_name) pfree(quoted_schema); if(quoted_table != table_name) pfree(quoted_table); return buf.data; } void make_table_partition_statement(Oid tableOid, char **ddl) { Relation rel; PartitionKey partKey; StringInfo new_ddl; List *deparse_ctx = NIL; int exprstate = 0; const char *strategy_str; int i; if (ddl == NULL || *ddl == NULL) return; /* нет DDL для дополнения */ /* Открываем таблицу с блокировкой ACCESS SHARE (достаточно для чтения) */ rel = table_open(tableOid, AccessShareLock); /* Проверяем, является ли таблица секционированной (relkind = 'p') */ if (rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) { table_close(rel, AccessShareLock); return; /* не секционирована — ничего не делаем */ } /* Получаем ключ секционирования (он уже загружен в relcache) */ partKey = RelationGetPartitionKey(rel); if (partKey == NULL) { table_close(rel, AccessShareLock); return; /* аномалия: relkind='p' но ключа нет */ } /* Определяем строковое представление стратегии */ switch (partKey->strategy) { case PARTITION_STRATEGY_RANGE: strategy_str = "RANGE"; break; case PARTITION_STRATEGY_LIST: strategy_str = "LIST"; break; case PARTITION_STRATEGY_HASH: strategy_str = "HASH"; break; default: table_close(rel, AccessShareLock); return; /* неизвестная стратегия */ } /* Формируем строку " PARTITION BY (col1, col2, ...)" */ new_ddl = makeStringInfo(); appendStringInfo(new_ddl, " PARTITION BY %s (", strategy_str); for (i = 0; i < partKey->partnatts; i++) { AttrNumber attnum = partKey->partattrs[i]; char *attname; if (i > 0) appendStringInfoChar(new_ddl, ','); if (attnum == 0) { /* The partition key is specified by an expression (partattrs[i] == 0). This means that an expression is specified instead of the column by which partitioning occurs. The expression itself is stored in partKey->partexprs in the same order as the zero-valued partattrs. get_attname() cannot be called with attnum == 0—it will fail with an attribute lookup error. */ Node *expr; char *exprstr; if (deparse_ctx == NIL) deparse_ctx = deparse_context_for(get_rel_name(rel->rd_id), rel->rd_id); expr = (Node *) list_nth(partKey->partexprs, exprstate); exprstr = deparse_expression(expr, deparse_ctx, false, false); appendStringInfo(new_ddl, "(%s)", exprstr); exprstate++; continue; } /* Получаем имя атрибута по его номеру в таблице */ attname = get_attname(rel->rd_id, attnum, false); if (attname == NULL) { /* если что-то пошло не так — прерываем формирование */ pfree(new_ddl->data); pfree(new_ddl); table_close(rel, AccessShareLock); return; } /* Экранируем имя (если оно зарезервированное или содержит спецсимволы) */ appendStringInfo(new_ddl, "%s", quote_identifier(attname)); } appendStringInfoChar(new_ddl, ')'); /* Конкатенируем с существующим DDL */ *ddl = (char*)repalloc(*ddl, strlen(*ddl) + new_ddl->len + 1); strcat(*ddl, new_ddl->data); /* Очистка */ pfree(new_ddl->data); pfree(new_ddl); table_close(rel, AccessShareLock); } void make_table_storage_parameters(Oid tableOid, char **ddl) { HeapTuple tuple; Datum relopts_datum; bool isnull; ArrayType *relopts_array; char *opts_str = NULL; int nelems; Datum *elem_values; bool *elem_nulls; int i; if (ddl == NULL || *ddl == NULL) return; tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(tableOid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for relation %u", tableOid); relopts_datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull); if (!isnull) { relopts_array = DatumGetArrayTypeP(relopts_datum); nelems = ArrayGetNItems(ARR_NDIM(relopts_array), ARR_DIMS(relopts_array)); if (nelems > 0) { StringInfoData buf; initStringInfo(&buf); /* Разбираем массив на элементы (тип text[]) */ deconstruct_array(relopts_array, TEXTOID, -1, false, 'i', &elem_values, &elem_nulls, &nelems); for (i = 0; i < nelems; i++) { if (i > 0) appendStringInfoChar(&buf, ','); if (!elem_nulls[i]) { char *str = text_to_cstring(DatumGetTextPP(elem_values[i])); appendStringInfoString(&buf, str); pfree(str); } else { appendStringInfoString(&buf, "NULL"); /* на случай NULL-элементов */ } } opts_str = buf.data; /* строка уже в памяти palloc */ if (opts_str && *opts_str) { size_t new_len = strlen(*ddl) + strlen(" WITH (") + strlen(opts_str) + strlen(")") + 1; *ddl = (char*)repalloc(*ddl, new_len); strcat(*ddl, " WITH ("); strcat(*ddl, opts_str); strcat(*ddl, ")"); } /* Очистка */ pfree(elem_values); pfree(elem_nulls); if (opts_str) pfree(opts_str); /* pfree(buf.data) */ } } ReleaseSysCache(tuple); } void make_add_string(const char *str, char **ddl){ size_t new_len = strlen(*ddl) + strlen(str) + 1; *ddl = (char*)repalloc(*ddl, new_len); strcat(*ddl, str); } void make_table_comments(Oid tableOid, bool sqlterminator, char **ddl) { if (ddl == NULL || *ddl == NULL) return; char *schemaname = get_namespace_name(get_rel_namespace(tableOid)); char *relname = get_rel_name(tableOid); if (!schemaname || !relname) elog(ERROR, "could not find relation %u", tableOid); StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); /* 1. Комментарий к таблице (objsubid = 0) */ char *tabcomment = GetComment(tableOid, RelationRelationId, 0); if (tabcomment) { appendStringInfo(&result, "\n\n-- Table comments\n"); appendStringInfo(&result, "COMMENT ON TABLE %s IS %s", full_qualified, quote_literal_cstr(tabcomment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(tabcomment); } /* 2. Комментарии к колонкам */ Relation rel = relation_open(tableOid, AccessShareLock); TupleDesc tupdesc = RelationGetDescr(rel); int natts = tupdesc->natts; bool first_col_comment = true; for (int i = 0; i < natts; i++) { Form_pg_attribute att = TupleDescAttr(tupdesc, i); if (att->attisdropped || att->attnum <= 0) continue; char *attname = NameStr(att->attname); /* Пропускаем системные скрытые колонки */ if (strcmp(attname, "tableoid") == 0 || strcmp(attname, "cmax") == 0 || strcmp(attname, "xmax") == 0 || strcmp(attname, "cmin") == 0 || strcmp(attname, "xmin") == 0 || strcmp(attname, "ctid") == 0) continue; /* Получаем комментарий к колонке (objsubid = номер колонки) */ char *colcomment = GetComment(tableOid, RelationRelationId, att->attnum); if (colcomment) { if (first_col_comment) { appendStringInfo(&result, "\n\n-- Column comments\n"); first_col_comment = false; } char *col_full = psprintf("%s.%s", full_qualified, quote_identifier(attname)); appendStringInfo(&result, "COMMENT ON COLUMN %s IS %s", col_full, quote_literal_cstr(colcomment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(colcomment); pfree(col_full); } } relation_close(rel, AccessShareLock); /* Добавляем в конец DDL с явным приведением типа */ size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char*) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree(full_qualified); pfree(schemaname); pfree(relname); pfree(result.data); } char *get_constraints_ddl_of_table(Oid tableOid, bool sqlterminator) { HeapTuple tp; Relation conRel; ScanKeyData skey; SysScanDesc scan; StringInfoData buf; char *schema_name; char *rel_name; const char *quoted_schema; const char *quoted_rel; bool found = false; AttrNumber oid_attnum; /* Получаем схему и имя таблицы */ HeapTuple relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(tableOid)); if (!HeapTupleIsValid(relTup)) elog(ERROR, "relation with OID %u does not exist", tableOid); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(relTup); Oid namespaceOid = relForm->relnamespace; rel_name = pstrdup(NameStr(relForm->relname)); ReleaseSysCache(relTup); schema_name = get_namespace_name(namespaceOid); if (!schema_name) elog(ERROR, "could not find schema for relation %u", tableOid); quoted_schema = quote_identifier(schema_name); quoted_rel = quote_identifier(rel_name); initStringInfo(&buf); /* Открываем pg_constraint и получаем номер атрибута oid */ conRel = table_open(ConstraintRelationId, AccessShareLock); oid_attnum = get_attnum(RelationGetRelid(conRel), "oid"); if (oid_attnum == InvalidAttrNumber) elog(ERROR, "could not find oid attribute in pg_constraint"); ScanKeyInit(&skey, Anum_pg_constraint_conrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(tableOid)); scan = systable_beginscan(conRel, ConstraintRelidTypidNameIndexId, true, NULL, 1, &skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tp); char contype = conForm->contype; char *conname = NameStr(conForm->conname); Datum defDatum; char *def; Datum oidDatum; bool isnull; if (conForm->conrelid != tableOid) continue; if (contype != CONSTRAINT_PRIMARY && contype != CONSTRAINT_UNIQUE && //contype != CONSTRAINT_FOREIGN && // oracle не добавляет его, надо отдельно включать contype != CONSTRAINT_CHECK) continue; /* Получаем OID ограничения через столбец oid */ oidDatum = heap_getattr(tp, oid_attnum, RelationGetDescr(conRel), &isnull); if (isnull) elog(ERROR, "could not get OID of constraint"); Oid conOid = DatumGetObjectId(oidDatum); defDatum = DirectFunctionCall2(pg_get_constraintdef_ext, ObjectIdGetDatum(conOid), BoolGetDatum(true)); def = TextDatumGetCString(defDatum); if (contype == CONSTRAINT_CHECK) { appendStringInfo(&buf, "ALTER TABLE %s.%s ADD %s", quoted_schema, quoted_rel, def); } else { appendStringInfo(&buf, "ALTER TABLE %s.%s ADD CONSTRAINT %s %s", quoted_schema, quoted_rel, quote_identifier(conname), def); } if (sqlterminator) appendStringInfoChar(&buf, ';'); appendStringInfoChar(&buf, '\n'); pfree(def); found = true; } systable_endscan(scan); table_close(conRel, AccessShareLock); if(schema_name != quoted_schema) pfree((void*)quoted_schema); if(rel_name != quoted_rel) pfree((void*)quoted_rel); pfree(schema_name); pfree(rel_name); if (!found) { pfree(buf.data); return pstrdup(""); } return buf.data; } void make_table_constraints(Oid tableOid, bool sqlterminator, char **ddl){ char *constraints = get_constraints_ddl_of_table(tableOid, sqlterminator); if(strlen(constraints)>0){ make_add_string("\n\n--Constraints\n", ddl); make_add_string(constraints, ddl); } } char *get_ref_constraints_ddl_of_table(Oid tableOid, bool sqlterminator) { HeapTuple tp; Relation conRel; ScanKeyData skey; SysScanDesc scan; StringInfoData buf; char *schema_name; char *rel_name; const char *quoted_schema; const char *quoted_rel; AttrNumber oid_attnum; //bool found = false; /* Получаем схему и имя таблицы */ HeapTuple relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(tableOid)); if (!HeapTupleIsValid(relTup)) elog(ERROR, "relation with OID %u does not exist", tableOid); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(relTup); Oid namespaceOid = relForm->relnamespace; rel_name = pstrdup(NameStr(relForm->relname)); ReleaseSysCache(relTup); schema_name = get_namespace_name(namespaceOid); if (!schema_name) elog(ERROR, "could not find schema for relation %u", tableOid); quoted_schema = quote_identifier(schema_name); quoted_rel = quote_identifier(rel_name); initStringInfo(&buf); /* Открываем pg_constraint */ conRel = table_open(ConstraintRelationId, AccessShareLock); /* Получаем номер атрибута oid (явный столбец) */ oid_attnum = get_attnum(RelationGetRelid(conRel), "oid"); if (oid_attnum == InvalidAttrNumber) elog(ERROR, "could not find oid attribute in pg_constraint"); ScanKeyInit(&skey, Anum_pg_constraint_conrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(tableOid)); scan = systable_beginscan(conRel, ConstraintRelidTypidNameIndexId, true, NULL, 1, &skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tp); char contype = conForm->contype; char *conname = NameStr(conForm->conname); Datum defDatum; char *def; Datum oidDatum; bool isnull; if (conForm->conrelid != tableOid) continue; /* Нас интересуют только внешние ключи */ if (contype != CONSTRAINT_FOREIGN) continue; /* Получаем OID ограничения */ oidDatum = heap_getattr(tp, oid_attnum, RelationGetDescr(conRel), &isnull); if (isnull) elog(ERROR, "could not get OID of constraint"); Oid conOid = DatumGetObjectId(oidDatum); /* Получаем определение ограничения (pretty=true) */ defDatum = DirectFunctionCall2(pg_get_constraintdef_ext, ObjectIdGetDatum(conOid), BoolGetDatum(true)); def = TextDatumGetCString(defDatum); /* Формируем ALTER TABLE ADD CONSTRAINT */ appendStringInfo(&buf, "ALTER TABLE %s.%s ADD CONSTRAINT %s %s", quoted_schema, quoted_rel, quote_identifier(conname), def); if (sqlterminator) appendStringInfoChar(&buf, ';'); appendStringInfoChar(&buf, '\n'); pfree(def); //found = true; } systable_endscan(scan); table_close(conRel, AccessShareLock); if(schema_name != quoted_schema) pfree((void*)quoted_schema); if(rel_name != quoted_rel) pfree((void*)quoted_rel); pfree(schema_name); pfree(rel_name); /* Пока закомментировал, в оракле вроде нет ошибки если не нашлось ограничение Если внешних ключей нет, генерируем исключение (как в PL/pgSQL) if (!found) { pfree(buf.data); elog(ERROR, "specified object of type REF_CONSTRAINT not found"); } */ return buf.data; } void make_table_ref_constraints(Oid tableOid, bool sqlterminator, char **ddl){ char *constraints = get_ref_constraints_ddl_of_table(tableOid, sqlterminator); if(strlen(constraints)>0){ make_add_string("\n\n-- Referential constraints\n", ddl); make_add_string(constraints, ddl); } } // This function generates full DDL table text by table OID (same logic for // get_ddl_table and fetch_ddl). sessionTransform keeps the transform data. char *build_table_ddl_text(Oid tableOid, char *tableName, char *schemaName, const int32 transform_handler) { char *columns; char relpersistence = ' '; char *ddl; bool segment_attributes = std::get(get_ddl_transform_param(transform_handler, "SEGMENT_ATTRIBUTES", ObjectTypeTable)); bool storage = std::get(get_ddl_transform_param(transform_handler, "STORAGE", ObjectTypeTable)); bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeTable)); bool sqlterminator_constraint = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeConstraint)); bool sqlterminator_ref_constraint = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeRefConstraint)); bool sqlterminator_comment = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeComment)); columns = get_table_definition(tableOid, relpersistence, segment_attributes); ddl = make_create_table_statement(schemaName, tableName, relpersistence, columns); pfree(columns); if (std::get(get_ddl_transform_param(transform_handler, "PARTITIONING", ObjectTypeTable))) make_table_partition_statement(tableOid, &ddl); if(segment_attributes && storage) make_table_storage_parameters(tableOid, &ddl); if(sqlterminator) make_add_string(SQLTERMINATOR, &ddl); make_table_comments(tableOid, sqlterminator_comment, &ddl); if(std::get(get_ddl_transform_param(transform_handler, "CONSTRAINTS", ObjectTypeTable))) make_table_constraints(tableOid, sqlterminator_constraint, &ddl); if(std::get(get_ddl_transform_param(transform_handler, "REF_CONSTRAINTS", ObjectTypeTable))) make_table_ref_constraints(tableOid, sqlterminator_ref_constraint, &ddl); return ddl; } Datum get_ddl_table(char *name, char *schema, char *version, char *model, char *transform) { char *tableName = nullptr; char *schemaName = nullptr; Oid tableOid = getRelationOid(name, schema); get_table_names_by_oid(tableOid, &schemaName, &tableName); char *ddl = build_table_ddl_text(tableOid, tableName, schemaName, -1); text *result = cstring_to_text(ddl); pfree_all(ddl, tableName, schemaName); PG_RETURN_TEXT_P(result); } /* ============================================= fetch_ddl support functions */ /* This function lists OIDs of all standart relation objects within not system schemas. Object type should be specified by caller as function can be used not only with homogenous types but with heterogenous types too. In such case ctx->obj_type will be a heterogenous object type and obj_type will be it's subtype. */ std::vector enumerate_relation_obj_oids(const MetadataContext *ctx, const ObjectType obj_type) { std::vector result; std::string query_str; char* filter_by_name = nullptr; char* filter_by_name_expr = nullptr; char* filter_by_exc_name_expr = nullptr; query_str.append("SELECT c.oid " "FROM pg_catalog.pg_class c " "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "); if (obj_type == ObjectType::ObjectTypeTable) { query_str.append("WHERE c.relkind IN ('r', 'p') "); } else if (obj_type == ObjectType::ObjectTypeView) { query_str.append("WHERE c.relkind = 'v' "); } else if (obj_type == ObjectType::ObjectTypeIndex) { query_str.append("WHERE c.relkind = 'i' "); } else if (obj_type == ObjectType::ObjectTypeSequence) { query_str.append("WHERE c.relkind = 'S' "); } filter_by_name = filter_condition_name(ctx->filters, "c.relname", obj_type); filter_by_name_expr = filter_condition_name_expr(ctx->filters, "c.relname", obj_type); filter_by_exc_name_expr = filter_condition_exclude_name_expr(ctx->filters, "c.relname", obj_type); if (filter_by_name) { query_str.append(" AND "); query_str.append(filter_by_name); } if (filter_by_name_expr) { query_str.append(" AND "); query_str.append(filter_by_name_expr); } if (filter_by_exc_name_expr) { query_str.append(" AND "); query_str.append(filter_by_exc_name_expr); } query_str.append(" AND n.nspname NOT LIKE 'pg\\_%' " " AND n.nspname <> 'information_schema' " "ORDER BY n.nspname, c.relname"); //ereport(WARNING, errmsg("final string is: %s", query_str.data())); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function " "DBMS_METADATA_FETCH_DDL"))); int ret = SPI_execute(query_str.data(), true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function DBMS_METADATA_FETCH_DDL"))); } //ereport(WARNING, errmsg("Number of OIDS: %d", SPI_processed)); for (uint64 i = 0; i < SPI_processed; i++) { bool isnull; Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result.push_back(DatumGetObjectId(d)); } SPI_finish(); pfree_all(filter_by_name, filter_by_name_expr, filter_by_exc_name_expr); return result; } /* This function lists OIDs of all triggers within not system schemas. */ std::vector enumerate_trigger_oids(const MetadataContext *ctx) { std::vector result; std::string query_str; char* filter_by_name = nullptr; char* filter_by_name_expr = nullptr; char* filter_by_exc_name_expr = nullptr; query_str.append("SELECT t.oid " "FROM pg_trigger t " "JOIN pg_class c ON c.oid = t.tgrelid " "JOIN pg_namespace n ON n.oid = c.relnamespace " "WHERE n.nspname NOT LIKE 'pg\\_%' " "AND n.nspname <> 'information_schema' "); filter_by_name = filter_condition_name(ctx->filters, "t.tgname", ObjectType::ObjectTypeTrigger); if (filter_by_name) { query_str.append(" AND "); query_str.append(filter_by_name); } filter_by_name_expr = filter_condition_name_expr(ctx->filters, "t.tgname", ObjectType::ObjectTypeTrigger); if (filter_by_name_expr) { query_str.append(" AND "); query_str.append(filter_by_name_expr); } filter_by_exc_name_expr = filter_condition_exclude_name_expr(ctx->filters, "t.tgname", ObjectType::ObjectTypeTrigger); if (filter_by_exc_name_expr) { query_str.append(" AND "); query_str.append(filter_by_exc_name_expr); } query_str.append(" ORDER BY n.nspname, c.relname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function " "DBMS_METADATA_FETCH_DDL"))); int ret = SPI_execute(query_str.data(), true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function DBMS_METADATA_FETCH_DDL"))); } //ereport(WARNING, errmsg("Number of OIDS: %d", SPI_processed)); for (uint64 i = 0; i < SPI_processed; i++) { bool isnull; Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result.push_back(DatumGetObjectId(d)); } SPI_finish(); pfree_all(filter_by_name, filter_by_name_expr, filter_by_exc_name_expr); return result; } /* This function lists OIDs of all constraints within not system schemas. Object type should be specified by caller as function can be used not only with homogenous types but with heterogenous types too. In such case ctx->obj_type will be a heterogenous object type and obj_type will be it's subtype. */ std::vector enumerate_constraint_oids(const MetadataContext *ctx, const ObjectType obj_type) { std::vector result; std::string query_str; char* filter_by_name = nullptr; char* filter_by_name_expr = nullptr; char* filter_by_exc_name_expr = nullptr; query_str.append("SELECT c.oid " "FROM pg_constraint c " "JOIN pg_namespace n ON n.oid = c.connamespace "); if (obj_type == ObjectType::ObjectTypeConstraint) { query_str.append("WHERE c.contype != 'f' "); } else if (obj_type == ObjectType::ObjectTypeRefConstraint) { query_str.append("WHERE c.contype = 'f' "); } filter_by_name = filter_condition_name(ctx->filters, "c.conname", obj_type); if (filter_by_name) { query_str.append(" AND "); query_str.append(filter_by_name); } filter_by_name_expr = filter_condition_name_expr(ctx->filters, "c.conname", obj_type); if (filter_by_name_expr) { query_str.append(" AND "); query_str.append(filter_by_name_expr); } filter_by_exc_name_expr = filter_condition_exclude_name_expr(ctx->filters, "c.conname", obj_type); if (filter_by_exc_name_expr) { query_str.append(" AND "); query_str.append(filter_by_exc_name_expr); } query_str.append(" AND c.conrelid != 0 " // skip non-table constraint " AND n.nspname NOT LIKE 'pg\\_%' " " AND n.nspname <> 'information_schema' " "ORDER BY n.nspname, c.conname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function " "DBMS_METADATA_FETCH_DDL"))); int ret = SPI_execute(query_str.data(), true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function " "DBMS_METADATA_FETCH_DDL"))); } for (uint64 i = 0; i < SPI_processed; i++) { bool isnull; Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result.push_back(DatumGetObjectId(d)); } SPI_finish(); pfree_all(filter_by_name, filter_by_name_expr, filter_by_exc_name_expr); return result; } /* This function lists OIDs of all functions / procedures within not system schemas. Object type should be specified by caller as function can be used not only with homogenous types but with heterogenous types too. In such case ctx->obj_type will be a heterogenous object type and obj_type will be it's subtype. */ std::vector enumerate_function_oids(const MetadataContext *ctx, const ObjectType obj_type) { std::vector result; std::string query_str; char* filter_by_name = nullptr; char* filter_by_name_expr = nullptr; char* filter_by_exc_name_expr = nullptr; query_str.append("SELECT p.oid " "FROM pg_proc p " "JOIN pg_namespace n ON n.oid = p.pronamespace "); if (obj_type == ObjectType::ObjectTypeFunction) { query_str.append("WHERE p.prokind = 'f' "); } else if (obj_type == ObjectType::ObjectTypeProcedure) { query_str.append("WHERE p.prokind = 'p' "); } filter_by_name = filter_condition_name(ctx->filters, "p.proname", obj_type); if (filter_by_name) { query_str.append(" AND "); query_str.append(filter_by_name); } filter_by_name_expr = filter_condition_name_expr(ctx->filters, "p.proname", obj_type); if (filter_by_name_expr) { query_str.append(" AND "); query_str.append(filter_by_name_expr); } filter_by_exc_name_expr = filter_condition_exclude_name_expr(ctx->filters, "p.proname", obj_type); if (filter_by_exc_name_expr) { query_str.append(" AND "); query_str.append(filter_by_exc_name_expr); } query_str.append(" AND n.nspname NOT LIKE 'pg\\_%' " " AND n.nspname <> 'information_schema' " "ORDER BY n.nspname, p.proname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function DBMS_METADATA_FETCH_DDL"))); int ret = SPI_execute(query_str.data(), true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function DBMS_METADATA_FETCH_DDL"))); } for (uint64 i = 0; i < SPI_processed; i++) { bool isnull; Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result.push_back(DatumGetObjectId(d)); } SPI_finish(); pfree_all(filter_by_name, filter_by_name_expr, filter_by_exc_name_expr); return result; } /* This function lists OIDs of all types within not system schemas. */ std::vector enumerate_type_oids(const MetadataContext *ctx) { std::vector result; std::string query_str; char* filter_by_name = nullptr; char* filter_by_name_expr = nullptr; char* filter_by_exc_name_expr = nullptr; query_str.append("SELECT t.oid " "FROM pg_catalog.pg_type t " "JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace "); query_str.append("WHERE t.typtype NOT IN ('b', 'm') "); filter_by_name = filter_condition_name(ctx->filters, "t.typname", ObjectType::ObjectTypeType); if (filter_by_name) { query_str.append(" AND "); query_str.append(filter_by_name); } filter_by_name_expr = filter_condition_name_expr(ctx->filters, "t.typname", ObjectType::ObjectTypeType); if (filter_by_name_expr) { query_str.append(" AND "); query_str.append(filter_by_name_expr); } filter_by_exc_name_expr = filter_condition_exclude_name_expr(ctx->filters, "t.typname", ObjectType::ObjectTypeType); if (filter_by_exc_name_expr) { query_str.append(" AND "); query_str.append(filter_by_exc_name_expr); } query_str.append(" AND n.nspname NOT LIKE 'pg\\_%' " " AND n.nspname <> 'information_schema' " "ORDER BY n.nspname, t.typname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function " "DBMS_METADATA_FETCH_DDL"))); int ret = SPI_execute(query_str.data(), true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function DBMS_METADATA_FETCH_DDL"))); } for (uint64 i = 0; i < SPI_processed; i++) { bool isnull; Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result.push_back(DatumGetObjectId(d)); } SPI_finish(); pfree_all(filter_by_name, filter_by_name_expr, filter_by_exc_name_expr); return result; } /* This function gets name and namespace name for constraint by it's Oid */ bool get_constraint_names_by_oid(const Oid constrOid, char** schemaName, char** constrName, Oid* owner_table) { HeapTuple tuple; tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid)); if (HeapTupleIsValid(tuple)) { Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple); *constrName = pstrdup(NameStr(conForm->conname)); char *rawNspName = get_namespace_name(conForm->connamespace); if (rawNspName != NULL) { *schemaName = pstrdup(rawNspName); pfree(rawNspName); } *owner_table = conForm->conrelid; ReleaseSysCache(tuple); } else { // as we are unable to get data then it has become corrupted obviously return false; } return true; } /* This function gets name and namespace name for function by it's Oid */ void get_function_names_by_oid(const Oid funcOid, char** schemaName, char** funcName) { HeapTuple tuple; tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid)); if (HeapTupleIsValid(tuple)) { Form_pg_proc procForm = (Form_pg_proc) GETSTRUCT(tuple); *funcName = pstrdup(NameStr(procForm->proname)); char *rawNspName = get_namespace_name(procForm->pronamespace); if (rawNspName != NULL) { *schemaName = pstrdup(rawNspName); pfree(rawNspName); } ReleaseSysCache(tuple); } } /* This function gets name and namespace name for type by it's Oid */ void get_type_data_by_oid(const Oid typeOid, char** schemaName, char** typeName, Oid* table_oid, char* typetype) { HeapTuple tuple; tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid)); if (HeapTupleIsValid(tuple)) { Form_pg_type typeForm = (Form_pg_type) GETSTRUCT(tuple); *typeName = pstrdup(NameStr(typeForm->typname)); char *rawNspName = get_namespace_name(typeForm->typnamespace); if (rawNspName != NULL) { *schemaName = pstrdup(rawNspName); pfree(rawNspName); } *table_oid = typeForm->typrelid; *typetype = typeForm->typtype; ReleaseSysCache(tuple); } } /* This function builds a row for ku$_ddl table */ KuDdlRow build_ku_ddl_row_for_table(Oid tableOid, const int32 transform_handler) { char *schemaName = nullptr; char *tableName = nullptr; char *ddl = nullptr; get_table_names_by_oid(tableOid, &schemaName, &tableName); //ereport(WARNING, errmsg("OID: %u, schema %s, table %s", tableOid, schemaName, tableName)); ddl = build_table_ddl_text(tableOid, tableName, schemaName, transform_handler); //ereport(WARNING, errmsg("OID: %u, ddl is: %s", tableOid, ddl)); // possible parseItem filling in here TODO KuDdlRow row; row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("TABLE"); row.objname = tableName; row.objschema = schemaName; row.objnum = (int64) tableOid; row.is_drop = pstrdup("NO"); return row; } /* This function builds a row for ku$_ddl view */ KuDdlRow build_ku_ddl_row_for_view(Oid viewOid, const int32 transform_handler) { char *schemaName = nullptr; char *viewName = nullptr; char *ddl = nullptr; get_view_names_by_oid(viewOid, &schemaName, &viewName); ddl = build_view_ddl_text(viewOid, viewName, schemaName, transform_handler); // possible parseItem filling in here TODO KuDdlRow row; row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("VIEW"); row.objname = viewName; row.objschema = schemaName; row.objnum = (int64) viewOid; row.is_drop = pstrdup("NO"); return row; } /* This function builds a row for ku$_ddl view */ KuDdlRow build_ku_ddl_row_for_index(Oid indexOid, const int32 transform_handler) { char *schemaName = nullptr; char *indexName = nullptr; char *ddl = nullptr; get_object_names_by_oid(indexOid, &schemaName, &indexName); ddl = build_index_ddl_text(indexOid, indexName, schemaName, transform_handler); // possible parseItem filling in here TODO KuDdlRow row; row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("INDEX"); row.objname = indexName; row.objschema = schemaName; row.objnum = (int64) indexOid; row.is_drop = pstrdup("NO"); return row; } /* This function builds a row for ku$_ddl sequence */ KuDdlRow build_ku_ddl_row_for_seq(Oid seqOid, const int32 transform_handler) { char *schemaName = nullptr; char *seqName = nullptr; char *ddl = nullptr; get_sequence_names_by_oid(seqOid, &schemaName, &seqName); ddl = build_seq_ddl_text(seqOid, seqName, schemaName, transform_handler); //ereport(WARNING, errmsg("DDL is: %s", ddl)); // possible parseItem filling in here TODO KuDdlRow row; row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("SEQUENCE"); row.objname = seqName; row.objschema = schemaName; row.objnum = (int64) seqOid; row.is_drop = pstrdup("NO"); return row; } /* This function builds a row for ku$_ddl trigger */ KuDdlRow build_ku_ddl_row_for_trigger(Oid trigOid, const int32 transform_handler) { char *schemaName = nullptr; char *trigName = nullptr; char *ddl = nullptr; KuDdlRow row = {0}; if (get_trigger_names_by_oid(trigOid, &schemaName, &trigName)) { //ereport(WARNING, errmsg("oid %u %s.%s", trigOid, schemaName, trigName)); ddl = build_trigger_ddl_text(trigOid, trigName, schemaName, transform_handler); //ereport(WARNING, errmsg("DDL is: %s", ddl)); // possible parseItem filling in here TODO row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("TRIGGER"); row.objname = pstrdup(trigName); row.objschema = pstrdup(schemaName); row.objnum = (int64) trigOid; row.is_drop = pstrdup("NO"); } return row; } /* This function builds a row for ku$_ddl constraint / ref_constraint */ KuDdlRow build_ku_ddl_row_for_constr(Oid constrOid, ObjectType obj_type, const int32 transform_handler) { char *schemaName = nullptr; char *constrName = nullptr; char *ddl = nullptr; Oid related_table = InvalidOid; KuDdlRow row; if (get_constraint_names_by_oid(constrOid, &schemaName, &constrName, &related_table)) { LockRelationOid(related_table, AccessShareLock); if (OidIsValid(related_table)) { ddl = build_constraint_ddl(constrOid, schemaName, constrName, transform_handler, obj_type); //ereport(WARNING, errmsg("DDL is: %s", ddl)); // possible parseItem filling in here TODO row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("CONSTRAINT"); row.objname = constrName; row.objschema = schemaName; row.objnum = (int64) constrOid; row.is_drop = pstrdup("NO"); } UnlockRelationOid(related_table, AccessShareLock); } return row; } /* This function builds a row for ku$_ddl function */ KuDdlRow build_ku_ddl_row_for_func(Oid funcOid, ObjectType obj_type, const int32 transform_handler) { char *schemaName = nullptr; char *funcName = nullptr; char *ddl = nullptr; KuDdlRow row; get_function_names_by_oid(funcOid, &schemaName, &funcName); ddl = build_function_ddl(funcOid, schemaName, funcName, transform_handler, obj_type); //ereport(WARNING, errmsg("DDL is: %s", ddl)); // possible parseItem filling in here TODO row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); if (obj_type == ObjectType::ObjectTypeFunction) { row.objtype = pstrdup("FUNCTION"); } else { row.objtype = pstrdup("PROCEDURE"); } row.objname = funcName; row.objschema = schemaName; row.objnum = (int64) funcOid; row.is_drop = pstrdup("NO"); return row; } /* This function builds a row for ku$_ddl type */ KuDdlRow build_ku_ddl_row_for_type(Oid typeOid, const int32 transform_handler) { char *schemaName = nullptr; char *typeName = nullptr; char *ddl = nullptr; Oid table_oid = InvalidOid; char typetype; KuDdlRow row = {0}; get_type_data_by_oid(typeOid, &schemaName, &typeName, &table_oid, &typetype); if (schemaName && typeName && build_type_statement(typeOid, table_oid, typetype, &ddl, transform_handler)) { //ereport(WARNING, errmsg("DDL is: %s", ddl)); // possible parseItem filling in here TODO row.ddltext = ddl; row.ddlverb = pstrdup("CREATE"); row.objtype = pstrdup("TYPE"); row.objname = typeName; row.objschema = schemaName; row.objnum = (int64) typeOid; row.is_drop = pstrdup("NO"); } return row; } /* This function checks if relation with such Oid is alive. It is called only after LockRelationOid(relid, AccessShareLock) is acquired, so the result cannot go stale: while the lock is held, a concurrent DROP command (which needs ACCESS EXCLUSIVE) will wait, and a DROP that already committed is invisible to us after AcceptInvalidationMessages() done by LockRelationOid. */ static bool relation_exists(Oid relid, ObjectType obj_type) { HeapTuple tp; if (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint) { tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(relid)); } else if (obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure) { tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(relid)); } else if (obj_type == ObjectType::ObjectTypeType) { tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(relid)); } else { tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); } if (!HeapTupleIsValid(tp)) return false; ReleaseSysCache(tp); return true; } // This function transforms set of ku$_ddl rows into the composite type array // "SYS".ku$_ddl[]. Datum ku_ddl_rows_to_array(std::vector& rows, FunctionCallInfo fcinfo) { // OID of element of "SYS".ku$_ddl type array got from return value Oid resultType = get_fn_expr_rettype(fcinfo->flinfo); Oid elemType = InvalidOid; TupleDesc tupdesc = nullptr; // this one will keep datums of heap tuples std::vector elems; int16 elmlen; bool elmbyval; char elmalign; if (OidIsValid(resultType)) { elemType = get_element_type(resultType); } if (!OidIsValid(elemType)) { // last chance: search by type name in SYS Oid nsp = get_namespace_oid("SYS", false); elemType = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid, CStringGetDatum("ku$_ddl"), ObjectIdGetDatum(nsp)); if (!OidIsValid(elemType)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"SYS.ku$_ddl\" does not exist"))); } } if (rows.empty()) { return PointerGetDatum(construct_empty_array(elemType)); } tupdesc = lookup_rowtype_tupdesc(elemType, -1); elems.reserve(rows.size()); // repacking for (KuDdlRow& row : rows) { Datum values[8]; bool isnull[8] = {false, false, false, false, false, false, false, false}; values[0] = PointerGetDatum(cstring_to_text(row.ddltext)); values[1] = PointerGetDatum(construct_empty_array(TEXTOID)); values[2] = PointerGetDatum(cstring_to_text(row.ddlverb)); values[3] = PointerGetDatum(cstring_to_text(row.objtype)); values[4] = PointerGetDatum(cstring_to_text(row.objname)); values[5] = PointerGetDatum(cstring_to_text(row.objschema)); values[6] = DirectFunctionCall1(int8_numeric, Int64GetDatum(row.objnum)); values[7] = PointerGetDatum(cstring_to_text(row.is_drop)); HeapTuple tup = heap_form_tuple(tupdesc, values, isnull); elems.push_back(heap_copy_tuple_as_datum(tup, tupdesc)); heap_freetuple(tup); pfree_all(row.ddltext, row.ddlverb, row.objtype, row.objname, row.objschema); } ReleaseTupleDesc(tupdesc); get_typlenbyvalalign(elemType, &elmlen, &elmbyval, &elmalign); ArrayType *arr = construct_array(elems.data(), (int) elems.size(), elemType, elmlen, elmbyval, elmalign); return PointerGetDatum(arr); } /* ====================================== end of fetch_ddl support functions */ /* PostgreSQL version of Oracle DBMS_METADATA.FETCH_DDL. Before the call, dbms_metadata_open() is executed; the handle is passed here. Repeated calls return subsequent chunks of objects (size -- SET_COUNT); after exhaustion, an empty array is returned. */ Datum fetch_ddl(FunctionCallInfo fcinfo, const int32 handle) { std::vector rows; size_t end = 0; MetadataContext *ctx = ctxMap.at(handle); int32 transform_handler = -1; /* No transform objects are attached to this handler? too bad We can't let it fetch -- that's what Oracle does */ if (ctx->transforms == nullptr) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Function DBMS_METADATA_FETCH_DDL is " "inconsistent with transform."))); } else { /* number of transforms can be more than one per handler BUT if we are fetching then multiple transforms should throw an error */ if (ctx->transforms->next != nullptr) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Too few transformations added for " "DBMS_METADATA_FETCH_DDL"))); } else { transform_handler = ctx->transforms->transform_id; } } /* First call: Get list of Oids and save them into Metadata Context structure. Memory for list of Oids is allocated in TopMemoryContext so list will still be alive after we exit the function. */ if (!ctx->been_fetched) { std::vector entries; // The only object types supported for now switch (ctx->object_type) { case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeSequence: { auto oids = enumerate_relation_obj_oids(ctx, ctx->object_type); entries.reserve(oids.size()); for (auto oid : oids) entries.push_back({oid, ctx->object_type}); break; } case ObjectType::ObjectTypeTrigger: { auto oids = enumerate_trigger_oids(ctx); entries.reserve(oids.size()); for (auto oid : oids) entries.push_back({oid, ObjectType::ObjectTypeTrigger}); break; } case ObjectType::ObjectTypeConstraint: case ObjectType::ObjectTypeRefConstraint: { auto oids = enumerate_constraint_oids(ctx, ctx->object_type); entries.reserve(oids.size()); for (auto oid : oids) entries.push_back({oid, ctx->object_type}); break; } case ObjectType::ObjectTypeFunction: case ObjectType::ObjectTypeProcedure: { auto oids = enumerate_function_oids(ctx, ctx->object_type); entries.reserve(oids.size()); for (auto oid : oids) entries.push_back({oid, ctx->object_type}); break; } case ObjectType::ObjectTypeType: { auto oids = enumerate_type_oids(ctx); entries.reserve(oids.size()); for (auto oid : oids) entries.push_back({oid, ObjectType::ObjectTypeType}); break; } // Heterogeneous types: enumerate sub-types and tag each OID case ObjectType::ObjectTypeDatabaseExport: // needs to be separated in future TODO case ObjectType::ObjectTypeSchemaExport: { auto add_tagged = [&](ObjectType sub_type) { std::vector oids; switch (sub_type) { case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeView: case ObjectType::ObjectTypeIndex: case ObjectType::ObjectTypeSequence: oids = enumerate_relation_obj_oids(ctx, sub_type); break; case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeConstraint: oids = enumerate_constraint_oids(ctx, sub_type); break; default: break; } for (auto oid : oids) entries.push_back({oid, sub_type}); }; // BEGIN_WITH, BEGIN_AFTER, END_BEFORE, END_WITH filters processing filter_diapason_t otp_range; // get current range if set get_filter_diapason(ctx->filters, &otp_range); if (type_in_filter_diapason(OTPName::OTPSequence, &otp_range)) { add_tagged(ObjectType::ObjectTypeSequence); } if (type_in_filter_diapason(OTPName::OTPTable, &otp_range)) { add_tagged(ObjectType::ObjectTypeTable); } if (type_in_filter_diapason(OTPName::OTPConstraint, &otp_range)) { add_tagged(ObjectType::ObjectTypeConstraint); } if (type_in_filter_diapason(OTPName::OTPRefConstraint, &otp_range)) { add_tagged(ObjectType::ObjectTypeRefConstraint); } if (type_in_filter_diapason(OTPName::OTPIndex, &otp_range)) { add_tagged(ObjectType::ObjectTypeIndex); } if (type_in_filter_diapason(OTPName::OTPView, &otp_range)) { add_tagged(ObjectType::ObjectTypeView); } break; } case ObjectType::ObjectTypeTableExport: case ObjectType::ObjectTypeTransportableExport: { auto add_tagged = [&](ObjectType sub_type) { std::vector oids; switch (sub_type) { case ObjectType::ObjectTypeTable: case ObjectType::ObjectTypeIndex: oids = enumerate_relation_obj_oids(ctx, sub_type); break; case ObjectType::ObjectTypeRefConstraint: case ObjectType::ObjectTypeConstraint: oids = enumerate_constraint_oids(ctx, sub_type); break; default: break; } for (auto oid : oids) entries.push_back({oid, sub_type}); }; // BEGIN_WITH, BEGIN_AFTER, END_BEFORE, END_WITH filters processing filter_diapason_t otp_range; // get current range if set get_filter_diapason(ctx->filters, &otp_range); if (type_in_filter_diapason(OTPName::OTPTable, &otp_range)) { add_tagged(ObjectType::ObjectTypeTable); } if (type_in_filter_diapason(OTPName::OTPConstraint, &otp_range)) { add_tagged(ObjectType::ObjectTypeConstraint); } if (type_in_filter_diapason(OTPName::OTPRefConstraint, &otp_range)) { add_tagged(ObjectType::ObjectTypeRefConstraint); } if (type_in_filter_diapason(OTPName::OTPIndex, &otp_range)) { add_tagged(ObjectType::ObjectTypeIndex); } break; } default: { auto obj_type_name = ObjectTypeToStringView(ctx->object_type); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Object type %s is not yet supported in " "function DBMS_METADATA_FETCH_DDL", obj_type_name.data()))); } } ctx->fetch_entries = (FetchOidEntry*) MemoryContextAlloc( TopMemoryContext, entries.size() * sizeof(FetchOidEntry)); if (entries.size() > 0) { memcpy(ctx->fetch_entries, entries.data(), entries.size() * sizeof(FetchOidEntry)); } ctx->fetch_entries_count = entries.size(); ctx->fetch_pos = 0; ctx->been_fetched = true; } // define number of rows to be fetched NOW end = ctx->fetch_pos + ctx->fetch_count; if (end > ctx->fetch_entries_count) { end = ctx->fetch_entries_count; } // fill in and return another set (size of fetch_count) rows.reserve(end - ctx->fetch_pos); for (size_t i = ctx->fetch_pos; i < end; i++) { FetchOidEntry entry = ctx->fetch_entries[i]; Oid relid = entry.oid; ObjectType obj_type = entry.type; //ereport(WARNING, errmsg("OID: %u", relid)); // Acquire lock only for pg_class-based OIDs (TABLE, VIEW, INDEX, // SEQUENCE, TRIGGER). For constraint/function/type OIDs we use // LockDatabaseObject to protect against concurrent DROP. bool is_rel_oid = (obj_type == ObjectType::ObjectTypeTable || obj_type == ObjectType::ObjectTypeView || obj_type == ObjectType::ObjectTypeIndex || obj_type == ObjectType::ObjectTypeSequence || obj_type == ObjectType::ObjectTypeTrigger); bool is_db_obj = (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint || obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure || obj_type == ObjectType::ObjectTypeType); if (is_rel_oid) LockRelationOid(relid, AccessShareLock); else if (is_db_obj) { Oid classid = InvalidOid; if (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint) classid = ConstraintRelationId; else if (obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure) classid = ProcedureRelationId; else if (obj_type == ObjectType::ObjectTypeType) classid = TypeRelationId; LockDatabaseObject(classid, relid, 0, AccessShareLock); } // for everything except trigger we check relation existence if (obj_type != ObjectType::ObjectTypeTrigger) { if (!relation_exists(relid, obj_type)) { /* skip this relation: unlock, shift end, continue*/ if (is_rel_oid) UnlockRelationOid(relid, AccessShareLock); else if (is_db_obj) { Oid classid = InvalidOid; if (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint) classid = ConstraintRelationId; else if (obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure) classid = ProcedureRelationId; else if (obj_type == ObjectType::ObjectTypeType) classid = TypeRelationId; UnlockDatabaseObject(classid, relid, 0, AccessShareLock); } // we also need to increase end as we are skipping one row if (end < ctx->fetch_entries_count) { end++; } continue; } } // producing rows if (obj_type == ObjectType::ObjectTypeTable) { rows.push_back(build_ku_ddl_row_for_table(relid, transform_handler)); } else if (obj_type == ObjectType::ObjectTypeView) { rows.push_back(build_ku_ddl_row_for_view(relid, transform_handler)); } else if (obj_type == ObjectType::ObjectTypeIndex) { rows.push_back(build_ku_ddl_row_for_index(relid, transform_handler)); } else if (obj_type == ObjectType::ObjectTypeSequence) { rows.push_back(build_ku_ddl_row_for_seq(relid, transform_handler)); } else if (obj_type == ObjectType::ObjectTypeTrigger) { KuDdlRow row; row = build_ku_ddl_row_for_trigger(relid, transform_handler); if (row.objnum == InvalidOid) { /* skip this relation: unlock, shift end, continue */ if (is_rel_oid) UnlockRelationOid(relid, AccessShareLock); // we also need to increase end as we are skipping one row if (end < ctx->fetch_entries_count) { end++; } continue; } else { rows.push_back(row); } } else if (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint) { KuDdlRow row; row = build_ku_ddl_row_for_constr(relid, obj_type, transform_handler); if (row.objnum == InvalidOid) { /* unlock and skip */ if (is_rel_oid) UnlockRelationOid(relid, AccessShareLock); else if (is_db_obj) UnlockDatabaseObject(ConstraintRelationId, relid, 0, AccessShareLock); if (end < ctx->fetch_entries_count) { end++; } continue; } else { rows.push_back(row); } } else if (obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure) { rows.push_back(build_ku_ddl_row_for_func(relid, obj_type, transform_handler)); } else if (obj_type == ObjectType::ObjectTypeType) { KuDdlRow row; row = build_ku_ddl_row_for_type(relid, transform_handler); if (row.objnum == InvalidOid) { /* skip this relation: unlock, shift end, continue*/ if (is_rel_oid) UnlockRelationOid(relid, AccessShareLock); else if (is_db_obj) UnlockDatabaseObject(TypeRelationId, relid, 0, AccessShareLock); // we also need to increase end as we are skipping one row if (end < ctx->fetch_entries_count) { end++; } continue; } else { rows.push_back(row); } } if (is_rel_oid) UnlockRelationOid(relid, AccessShareLock); else if (is_db_obj) { Oid classid = InvalidOid; if (obj_type == ObjectType::ObjectTypeConstraint || obj_type == ObjectType::ObjectTypeRefConstraint) { classid = ConstraintRelationId; } else if (obj_type == ObjectType::ObjectTypeFunction || obj_type == ObjectType::ObjectTypeProcedure) { classid = ProcedureRelationId; } else if (obj_type == ObjectType::ObjectTypeType) { classid = TypeRelationId; } UnlockDatabaseObject(classid, relid, 0, AccessShareLock); } } ctx->fetch_pos = end; return ku_ddl_rows_to_array(rows, fcinfo); } TransformationObject* transformForHandle(int32 hndl) { if (hndl == sessionTransformHandle) return &sessionTransform; // указатель на глобальный объект auto it = ctxTransformMap.find(hndl); if (it != ctxTransformMap.end()) return &it->second; // указатель на элемент в map return nullptr; // не найдено } Datum set_transform_param_ovr1(FunctionCallInfo fcinfo) { if(PG_ARGISNULL(0)){ ereport(ERROR, (errmsg("Параметр transform_handle не задан."))); } int32 transformHndl = get_numeric_argument_int32(fcinfo, 0); TransformationObject *transformObj = transformForHandle(transformHndl); char *param_name = get_string_argument(fcinfo, 1); char *value = get_string_argument(fcinfo, 2); char *ch_obj_type = get_string_argument(fcinfo, 3); const char* func_name = "DBMS_METADATA_SET_TRANSFORM_PARAM"; ObjectType transform_param_OT = ObjectType::ObjectTypeNull; if (ch_obj_type && transformHndl != -1) { setObjectType(ch_obj_type, transform_param_OT, func_name); } if(transformObj){ transformObj->setString(std::string(param_name), std::string(value), static_cast(transform_param_OT)); } else ereport(ERROR, (errmsg("invalid input value %d for parameter TRANSFORM_HANDLE in function SET_TRANSFORM_PARAM", transformHndl))); //ereport(NOTICE, (errmsg("SET %s to %s", param_name, std::get(transformObj->getParam(param_name)).c_str() ))); PG_RETURN_VOID(); } Datum set_transform_param_ovr2(FunctionCallInfo fcinfo) { if(PG_ARGISNULL(0)){ ereport(ERROR, (errmsg("Параметр transform_handle не задан."))); } int32 transformHndl = get_numeric_argument_int32(fcinfo, 0); TransformationObject *transformObj = transformForHandle(transformHndl); char *param_name = get_string_argument(fcinfo, 1); bool value = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2); char *ch_obj_type = get_string_argument(fcinfo, 3); const char* func_name = "DBMS_METADATA_SET_TRANSFORM_PARAM"; ObjectType transform_param_OT = ObjectType::ObjectTypeNull; if (ch_obj_type && transformHndl != -1) { setObjectType(ch_obj_type, transform_param_OT, func_name); } if(transformObj){ transformObj->setBool(std::string(param_name), value, static_cast(transform_param_OT)); } else ereport(ERROR, (errmsg("invalid input value %d for parameter TRANSFORM_HANDLE in function SET_TRANSFORM_PARAM", transformHndl))); //ereport(NOTICE, (errmsg("SET %s to %s", param_name, std::get(transformObj->getParam(param_name)) ? "true" : "false"))); PG_RETURN_VOID(); } Datum set_transform_param_ovr3(FunctionCallInfo fcinfo) { if(PG_ARGISNULL(0)){ ereport(ERROR, (errmsg("Параметр transform_handle не задан."))); } int32 transformHndl = get_numeric_argument_int32(fcinfo, 0); TransformationObject *transformObj = transformForHandle(transformHndl); char *param_name = get_string_argument(fcinfo, 1); int32 value = PG_ARGISNULL(2) ? false : PG_GETARG_INT32(2); char *ch_obj_type = get_string_argument(fcinfo, 3); const char* func_name = "DBMS_METADATA_SET_TRANSFORM_PARAM"; ObjectType transform_param_OT = ObjectType::ObjectTypeNull; if (ch_obj_type && transformHndl != -1) { setObjectType(ch_obj_type, transform_param_OT, func_name); } if(transformObj){ transformObj->setInt(std::string(param_name), value, static_cast(transform_param_OT)); } else ereport(ERROR, (errmsg("invalid input value %d for parameter TRANSFORM_HANDLE in function SET_TRANSFORM_PARAM", transformHndl))); //ereport(NOTICE, (errmsg("SET %s to %d", param_name, std::get(transformObj->getParam(param_name))))); PG_RETURN_VOID(); } Datum setFilter(Numeric& num_handle, const char* ch_name, const char* filter_value, const char* ch_otp) { int32 handle = 0; FilterName filter_name = FilterName::FNNull; OTPName obj_type_path = OTPName::OTPNULL; ObjectType init_obj_type = ObjectType::ObjectTypeNull; const char* func_name = "DBMS_METADATA_SET_FILTER"; /* -------------------------------- checks */ handle = checkCtxHandle(num_handle, func_name); // check if fetch has been called before checkFetchStatus(handle, func_name); // let's get initial object type init_obj_type = getObjectTypeByHandle(handle); if (ch_name) { // check if this is a valid filter name auto name = stringToFilterName(std::string(ch_name)); if (name == std::nullopt) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid input value %s for parameter NAME in function" " DBMS_METADATA_SET_FILTER", ch_name))); } else { filter_name = name.value(); // check if filter name is consistent with current object type // (which has been set during dbms_metadata_open()) in case object // type path is not set if (!ch_otp && !isFNConsistentWithOT(init_obj_type, filter_name)) { auto obj_type_name = ObjectTypeToStringView(init_obj_type); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid NAME parameter \"%s\" for object type %s" " in function DBMS_METADATA_SET_FILTER", ch_name, obj_type_name.data()))); } } } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Missing NAME value in function " "DBMS_METADATA_SET_FILTER"))); } /* there should also be a filter <-> object type path correspondence check */ // TODO ! if (!filter_value) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Missing VALUE value in function " "DBMS_METADATA_SET_FILTER"))); } /* apart from getting object type path here we are checking it's consistence with filter */ getObjectTypePath(ch_otp, obj_type_path, init_obj_type, filter_name, func_name); /* --------------------- end of the checks */ addFilter(handle, filter_name, filter_value, obj_type_path); PG_RETURN_VOID(); } ObjectType getObjectTypeByHandle(const int32 handle) { // no check for handle here, so exception is possible return ctxMap.at(handle)->object_type; } void setFetchCountByHandle(const int32 handle, const int32 value) { // no check for handle here, so exception is possible ctxMap.at(handle)->fetch_count = static_cast(value); } void setOTPByHandle(const int32 handle, const OTPName obj_type_path) { // no check for handle here, so exception is possible ctxMap.at(handle)->object_type_path = obj_type_path; } // VIEW // Получить имя схемы и имя представления по OID представления. void get_view_names_by_oid(Oid relOid, char **schemaName, char **viewName) { HeapTuple tp; Form_pg_class classForm; Oid schemaOid; char relkind; char *nspname; char *relname; /* 1. Получаем кортеж из системного кеша по OID отношения */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relOid))); classForm = (Form_pg_class) GETSTRUCT(tp); /* 2. Проверяем тип отношения: допустимо только 'v' (обычное представление) */ relkind = classForm->relkind; if (relkind != RELKIND_VIEW) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a view", NameStr(classForm->relname)))); } /* 3. Получаем OID схемы и извлекаем её имя */ schemaOid = classForm->relnamespace; nspname = get_namespace_name(schemaOid); if (!nspname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema with OID %u does not exist", schemaOid))); } /* 4. Копируем имя представления (безопасно, т.к. оно хранится в формате NameData) */ relname = pstrdup(NameStr(classForm->relname)); ReleaseSysCache(tp); /* 5. Возвращаем результаты (память выделена через palloc, освобождать вызывающему) */ *schemaName = nspname; *viewName = relname; } char *get_view_definition(Oid relid) { Datum result; char *viewdef; /* * Вызываем SQL-функцию pg_get_viewdef(oid). * Она возвращает текст с определением представления. * DirectFunctionCall1 гарантирует, что будет вызвана версия с одним аргументом. */ result = DirectFunctionCall1(pg_get_viewdef, ObjectIdGetDatum(relid)); viewdef = TextDatumGetCString(result); return viewdef; } char *make_create_view_statement(const char *schema_name, const char *view_name, const char *view_def) { StringInfoData buf; char *quoted_schema = NULL; char *quoted_table = NULL; /* Экранируем имя представления */ quoted_table = (char *) quote_identifier(view_name); /* Экранируем схему */ quoted_schema = (char *) quote_identifier(schema_name); initStringInfo(&buf); appendStringInfoString(&buf, "--VIEW\nCREATE VIEW "); appendStringInfo(&buf, "%s.", quoted_schema); appendStringInfo(&buf, "%s AS %s", quoted_table, view_def); // pg_get_viewdef добавляет ';' - удаляем if(buf.data[strlen(buf.data)-1] == ';') buf.data[strlen(buf.data)-1] = 0; /* Освобождаем экранированные строки */ if(quoted_schema != schema_name) pfree(quoted_schema); if(quoted_table != view_name) pfree(quoted_table); return buf.data; } void make_view_comments(Oid viewOid, const char *schemaname, const char *relname, bool sqlterminator, char **ddl){ // 1. Комментарий к представлению StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); char *viewComment = GetComment(viewOid, RelationRelationId, 0); if (viewComment) { appendStringInfo(&result, "\n\n-- View comments\n"); appendStringInfo(&result, "COMMENT ON VIEW %s IS %s", full_qualified, quote_literal_cstr(viewComment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(viewComment); } /* 2. Комментарии к колонкам */ Relation rel = relation_open(viewOid, AccessShareLock); TupleDesc tupdesc = RelationGetDescr(rel); int natts = tupdesc->natts; bool first_col_comment = true; for (int i = 0; i < natts; i++) { Form_pg_attribute att = TupleDescAttr(tupdesc, i); if (att->attisdropped || att->attnum <= 0) continue; char *attname = NameStr(att->attname); /* Получаем комментарий к колонке (objsubid = номер колонки) */ char *colcomment = GetComment(viewOid, RelationRelationId, att->attnum); if (colcomment) { if (first_col_comment) { appendStringInfo(&result, "\n\n-- Column comments\n"); first_col_comment = false; } char *col_full = psprintf("%s.%s", full_qualified, quote_identifier(attname)); appendStringInfo(&result, "COMMENT ON COLUMN %s IS %s", col_full, quote_literal_cstr(colcomment)); if (sqlterminator) appendStringInfoChar(&result, ';'); appendStringInfoChar(&result, '\n'); pfree(colcomment); pfree(col_full); } } relation_close(rel, AccessShareLock); /* Добавляем в конец DDL с явным приведением типа */ size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char*) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree_all(full_qualified, result.data); } // This function generates full DDL view text by view OID (same logic for // get_ddl_view and fetch_ddl). sessionTransform keeps the transform data. char *build_view_ddl_text(Oid viewOid, char *viewName, char *schemaName, const int32 transform_handler) { char *ddl = nullptr; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeView)); bool sqlterminator_comment = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeComment)); char *viewDef = get_view_definition(viewOid); ddl = make_create_view_statement(schemaName, viewName, viewDef); if(sqlterminator) make_add_string(";", &ddl); make_view_comments(viewOid, schemaName, viewName, sqlterminator_comment, &ddl); if (viewDef) { pfree(viewDef); } return ddl; } Datum get_ddl_view(char *name, char *schema, char *version, char *model, char *transform){ text *result; char *viewName = nullptr; char *schemaName = nullptr; Oid viewOid = getRelationOid(name, schema); get_view_names_by_oid(viewOid, &viewName, &schemaName); char *ddl = build_view_ddl_text(viewOid, viewName, schemaName, -1); result = cstring_to_text(ddl); pfree_all(ddl, viewName, schemaName); PG_RETURN_TEXT_P(result); } // SEQUENCE void get_sequence_names_by_oid(Oid relOid, char **schemaName, char **viewName) { HeapTuple tp; Form_pg_class classForm; Oid schemaOid; char relkind; char *nspname; char *relname; /* 1. Получаем кортеж из системного кеша по OID отношения */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relOid))); classForm = (Form_pg_class) GETSTRUCT(tp); /* 2. Проверяем тип отношения: только sequence */ relkind = classForm->relkind; if (relkind != RELKIND_SEQUENCE) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a sequence", NameStr(classForm->relname)))); } /* 3. Получаем OID схемы и извлекаем её имя */ schemaOid = classForm->relnamespace; nspname = get_namespace_name(schemaOid); if (!nspname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema with OID %u does not exist", schemaOid))); } /* 4. Копируем имя представления */ relname = pstrdup(NameStr(classForm->relname)); ReleaseSysCache(tp); /* 5. Возвращаем результаты (память выделена через palloc, освобождать вызывающему) */ *schemaName = nspname; *viewName = relname; } char *make_sequence_statement(Oid seqOid, const char *schemaname, const char *relname, bool sqlterminator) { StringInfoData buf; HeapTuple tp; Relation rel; ScanKeyData skey; SysScanDesc scan; Form_pg_sequence seqForm; int64 start_value, increment_by, min_value, max_value, cache_size; bool cycle; /* ----- Проверка, что это действительно последовательность ----- */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(seqOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", seqOid))); Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tp); if (classForm->relkind != RELKIND_SEQUENCE) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a sequence", NameStr(classForm->relname)))); } ReleaseSysCache(tp); /* ----- Получаем параметры последовательности из pg_sequence ----- */ rel = table_open(SequenceRelationId, AccessShareLock); ScanKeyInit(&skey, Anum_pg_sequence_seqrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(seqOid)); scan = systable_beginscan(rel, SequenceRelidIndexId, true, NULL, 1, &skey); tp = systable_getnext(scan); if (!HeapTupleIsValid(tp)) { systable_endscan(scan); table_close(rel, AccessShareLock); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("no pg_sequence entry for OID %u", seqOid))); } seqForm = (Form_pg_sequence) GETSTRUCT(tp); start_value = seqForm->seqstart; increment_by = seqForm->seqincrement; min_value = seqForm->seqmin; max_value = seqForm->seqmax; cache_size = seqForm->seqcache; cycle = seqForm->seqcycle; systable_endscan(scan); table_close(rel, AccessShareLock); /* ----- Формируем SQL-строку ----- */ initStringInfo(&buf); const char *esc_schema = quote_identifier(schemaname); const char *esc_rel = quote_identifier(relname); appendStringInfo(&buf, "--SEQUENCE\nCREATE SEQUENCE %s.%s START WITH " INT64_FORMAT " INCREMENT BY " INT64_FORMAT " MINVALUE " INT64_FORMAT " MAXVALUE " INT64_FORMAT " CACHE " INT64_FORMAT " %s", esc_schema, esc_rel, start_value, increment_by, min_value, max_value, cache_size, cycle ? "CYCLE" : "NO CYCLE"); if(esc_schema != schemaname) pfree((void*)esc_schema); if(esc_rel != relname) pfree((void*)esc_rel); if (sqlterminator) appendStringInfoChar(&buf, ';'); char *result = pstrdup(buf.data); pfree(buf.data); return result; } void make_sequence_comments(Oid seqOid, const char *schemaname, const char *relname, bool sqlterminator, char **ddl){ StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); char *seqComment = GetComment(seqOid, RelationRelationId, 0); if (seqComment) { appendStringInfo(&result, "\n\n-- Sequence comment\n"); appendStringInfo(&result, "COMMENT ON SEQUENCE %s IS %s", full_qualified, quote_literal_cstr(seqComment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(seqComment); } /* Добавляем в конец DDL с явным приведением типа */ size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char*) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree_all(full_qualified, result.data); } // This function generates full DDL sequence text by sequence OID (same logic // for get_ddl_sequence and fetch_ddl). sessionTransform keeps the transform // data. char *build_seq_ddl_text(Oid seqOid, char *seqName, char *schemaName, const int32 transform_handler) { char *ddl = nullptr; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeSequence)); bool sqlterminator_comment = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeComment)); ddl = make_sequence_statement(seqOid, schemaName, seqName, sqlterminator); make_sequence_comments(seqOid, schemaName, seqName, sqlterminator_comment, &ddl); return ddl; } Datum get_ddl_sequence(char *name, char *schema, char *version, char *model, char *transform){ text *result; char *sequenceName; char *schemaName; Oid sequenceOid = getRelationOid(name, schema); get_sequence_names_by_oid(sequenceOid, &schemaName, &sequenceName); char *ddl = build_seq_ddl_text(sequenceOid, sequenceName, schemaName, -1); result = cstring_to_text(ddl); pfree_all(ddl, sequenceName, schemaName); PG_RETURN_TEXT_P(result); } static char * get_constraint_def_via_spi(Oid constraintOid) { char *def = NULL; int ret; StringInfoData query; bool isnull; SPITupleTable *tuptable; Datum datum; MemoryContext target_context = CurrentMemoryContext; initStringInfo(&query); appendStringInfo(&query, "SELECT pg_get_constraintdef(%u, true)", constraintOid); SPI_connect(); ret = SPI_execute(query.data, true, 1); if (ret == SPI_OK_SELECT && SPI_processed == 1) { tuptable = SPI_tuptable; datum = SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &isnull); if (!isnull){ char *res = TextDatumGetCString(datum); def = MemoryContextStrdup(target_context, res); pfree(res); } } SPI_finish(); pfree(query.data); if (def == NULL || strlen(def) == 0) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not get constraint definition for OID %u", constraintOid))); return def; } char * make_constraint_statement(Oid objectOid, char *schema, char *name, const int32 transform_handler) { HeapTuple tp = NULL; Form_pg_constraint conForm; Oid relid; Oid constraintOid = InvalidOid; char *relname, *nspname, *conname, *def; const char *q_nsp, *q_rel, *q_con; StringInfoData buf; char *result; bool found = false; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeConstraint)); if (OidIsValid(objectOid)) { /* -------- objectOid задан – считаем, что это индекс --------- */ tp = SearchSysCache1(RELOID, ObjectIdGetDatum(objectOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("relation with OID %u does not exist", objectOid))); Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tp); if (classForm->relkind != RELKIND_INDEX) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("object %u is not an index", objectOid))); } Oid namespaceOid = classForm->relnamespace; char *indexName = pstrdup(NameStr(classForm->relname)); ReleaseSysCache(tp); /* больше не нужен */ /* Ищем ограничение по имени индекса и namespace */ Relation conRel = table_open(ConstraintRelationId, AccessShareLock); ScanKeyData skey[2]; SysScanDesc scan; ScanKeyInit(&skey[0], Anum_pg_constraint_conname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(indexName)); ScanKeyInit(&skey[1], Anum_pg_constraint_connamespace, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(namespaceOid)); scan = systable_beginscan(conRel, ConstraintNameNspIndexId, true, NULL, 2, skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { conForm = (Form_pg_constraint) GETSTRUCT(tp); if (conForm->contype == CONSTRAINT_FOREIGN) continue; constraintOid = conForm->oid; found = true; break; } systable_endscan(scan); table_close(conRel, AccessShareLock); pfree(indexName); if (!found) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("no table constraint found for index %u", objectOid))); /* Получаем кортеж ограничения по его OID */ tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("constraint %u not found", constraintOid))); conForm = (Form_pg_constraint) GETSTRUCT(tp); } else { /* -------- objectOid не задан – ищем по имени и схеме --------- */ if (name == NULL || name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("constraint name must be provided when object OID is invalid"))); List *schemalist; ListCell *lc; Oid nspOid; if (schema != NULL) { nspOid = get_namespace_oid(schema, false); schemalist = list_make1_oid(nspOid); } else { schemalist = fetch_search_path(true); } Relation conRel = table_open(ConstraintRelationId, AccessShareLock); ScanKeyData skey[2]; SysScanDesc scan; foreach(lc, schemalist) { nspOid = lfirst_oid(lc); ScanKeyInit(&skey[0], Anum_pg_constraint_conname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(name)); ScanKeyInit(&skey[1], Anum_pg_constraint_connamespace, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(nspOid)); scan = systable_beginscan(conRel, ConstraintNameNspIndexId, true, NULL, 2, skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { conForm = (Form_pg_constraint) GETSTRUCT(tp); if (OidIsValid(conForm->conrelid) && conForm->contype != CONSTRAINT_FOREIGN) { constraintOid = conForm->oid; found = true; break; } } systable_endscan(scan); if (found) break; } table_close(conRel, AccessShareLock); list_free(schemalist); if (!found) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("constraint \"%s\" does not exist", name))); /* Теперь, когда ограничение найдено, получаем его кортеж через системный кеш */ tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid)); if (!HeapTupleIsValid(tp)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("constraint %u not found", constraintOid))); conForm = (Form_pg_constraint) GETSTRUCT(tp); } /* -------- Общая часть: проверка, что это табличное ограничение --------- */ relid = conForm->conrelid; if (!OidIsValid(relid)) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("constraint %u is not a table constraint", constraintOid))); } if (conForm->contype == CONSTRAINT_FOREIGN) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("foreign key constraints are not supported"))); } /* -------- Получение имён и построение ALTER TABLE ... --------- */ conname = pstrdup(NameStr(conForm->conname)); relname = get_rel_name(relid); if (!relname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("table with OID %u does not exist", relid))); } nspname = get_namespace_name(get_rel_namespace(relid)); if (!nspname) { ReleaseSysCache(tp); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema for table OID %u does not exist", relid))); } def = get_constraint_def_via_spi(constraintOid); q_nsp = quote_identifier(nspname); q_rel = quote_identifier(relname); q_con = quote_identifier(conname); initStringInfo(&buf); appendStringInfo(&buf, "ALTER TABLE %s.%s ADD CONSTRAINT %s %s", q_nsp, q_rel, q_con, def); if (sqlterminator) appendStringInfoChar(&buf, ';'); result = pstrdup(buf.data); pfree_all(buf.data, def, conname, relname, nspname); ReleaseSysCache(tp); return result; } /* separate function for fetch_ddl: it's more optimized for multiple row fetching */ char* build_constraint_ddl(Oid constrOid, char *schema, char *constrName, const int32 transform_handler, ObjectType obj_type) { HeapTuple tp = NULL; Form_pg_constraint conForm; Oid table_id; char *relname = nullptr; char *def = nullptr; const char *q_nsp, *q_rel, *q_con; char *result; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", static_cast(obj_type))); /* Get constraint tuple by it's OID */ tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid)); if (!HeapTupleIsValid(tp)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("constraint %u not found", constrOid))); } conForm = (Form_pg_constraint) GETSTRUCT(tp); table_id = conForm->conrelid; relname = get_rel_name(table_id); def = get_constraint_def_via_spi(constrOid); q_nsp = quote_identifier(schema); q_rel = quote_identifier(relname); q_con = quote_identifier(constrName); StringInfo buf = makeStringInfo(); appendStringInfo(buf, "ALTER TABLE %s.%s ADD CONSTRAINT %s %s", q_nsp, q_rel, q_con, def); if (sqlterminator) appendStringInfoChar(buf, ';'); result = pstrdup(buf->data); pfree_all(def, relname); ReleaseSysCache(tp); destroyStringInfo(buf); return result; } Datum get_ddl_constraint(char *name, char *schema, char *version, char *model, char *transform) { text *result; Oid constraintOid = getRelationOid(name, schema, true); char *ddl = make_constraint_statement(constraintOid, schema, name, -1); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } static void find_ref_constraint(char *name, char *schema, Oid *conOid_out, Oid *tableOid_out, char **conName_out) { Relation conRel; HeapTuple tp; Form_pg_constraint conForm; List *schemas = NIL; ListCell *lc; int found = 0; Oid conOid = InvalidOid; Oid tableOid = InvalidOid; char *conName = NULL; conRel = table_open(ConstraintRelationId, AccessShareLock); if (schema != NULL && schema[0] != '\0') { Oid schemaOid = get_namespace_oid(schema, false); ScanKeyData skey[2]; SysScanDesc scan; ScanKeyInit(&skey[0], Anum_pg_constraint_conname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(name)); ScanKeyInit(&skey[1], Anum_pg_constraint_connamespace, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(schemaOid)); scan = systable_beginscan(conRel, ConstraintNameNspIndexId, true, NULL, 2, skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { conForm = (Form_pg_constraint) GETSTRUCT(tp); if (conForm->contype != CONSTRAINT_FOREIGN || !OidIsValid(conForm->conrelid)) continue; found++; if (found > 1) break; conOid = conForm->oid; tableOid = conForm->conrelid; conName = pstrdup(NameStr(conForm->conname)); } systable_endscan(scan); } else { schemas = fetch_search_path(false); foreach(lc, schemas) { Oid namespaceOid = lfirst_oid(lc); ScanKeyData skey[2]; SysScanDesc scan; ScanKeyInit(&skey[0], Anum_pg_constraint_conname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(name)); ScanKeyInit(&skey[1], Anum_pg_constraint_connamespace, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(namespaceOid)); scan = systable_beginscan(conRel, ConstraintNameNspIndexId, true, NULL, 2, skey); while (HeapTupleIsValid(tp = systable_getnext(scan))) { conForm = (Form_pg_constraint) GETSTRUCT(tp); if (conForm->contype != CONSTRAINT_FOREIGN || !OidIsValid(conForm->conrelid)) continue; found++; if (found > 1) break; conOid = conForm->oid; tableOid = conForm->conrelid; conName = pstrdup(NameStr(conForm->conname)); } systable_endscan(scan); if (found > 0) break; } list_free(schemas); } table_close(conRel, AccessShareLock); if (found == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("Referential constraint with name \"%s\" not found%s%s", name, (schema && schema[0]) ? " in schema \"" : "", (schema && schema[0]) ? schema : ""))); if (found > 1) ereport(ERROR, (errcode(ERRCODE_CARDINALITY_VIOLATION), errmsg("Duplicate ref constraints found with name \"%s\"%s%s", name, (schema && schema[0]) ? " in schema \"" : "", (schema && schema[0]) ? schema : ""))); *conOid_out = conOid; *tableOid_out = tableOid; *conName_out = conName; } char *make_ref_constraint_statement(char *name, char *schema, const int32 transform_handler) { Oid conOid, tableOid; char *conName; char *tableName, *tableNsp, *def; const char *q_table_nsp, *q_table, *q_con; StringInfoData buf; char *result; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeRefConstraint)); /* Проверка имени */ if (name == NULL || name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("constraint name cannot be null or empty"))); /* Находим ограничение (учитывая search_path, если schema NULL) */ find_ref_constraint(name, schema, &conOid, &tableOid, &conName); /* Получаем имя таблицы и её схему */ tableName = get_rel_name(tableOid); if (!tableName) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("table with OID %u does not exist", tableOid))); tableNsp = get_namespace_name(get_rel_namespace(tableOid)); if (!tableNsp) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), errmsg("schema for table OID %u does not exist", tableOid))); /* Получаем определение ограничения */ def = get_constraint_def_via_spi(conOid); /* Экранируем идентификаторы */ q_table_nsp = quote_identifier(tableNsp); q_table = quote_identifier(tableName); q_con = quote_identifier(conName); /* Собираем команду */ initStringInfo(&buf); appendStringInfo(&buf, "ALTER TABLE %s.%s ADD CONSTRAINT %s %s", q_table_nsp, q_table, q_con, def); if (sqlterminator) appendStringInfoChar(&buf, ';'); result = pstrdup(buf.data); /* Очистка */ pfree(buf.data); pfree(def); pfree(tableNsp); pfree(tableName); pfree(conName); return result; } Datum get_ddl_ref_constraint(char *name, char *schema, char *version, char *model, char *transform) { text *result; char *ddl = make_ref_constraint_statement(name, schema, -1); result = cstring_to_text(ddl); pfree(ddl); PG_RETURN_TEXT_P(result); } char *make_index_statement(Oid indexOid, bool sqlterminator){ char *indexdef; StringInfoData result; initStringInfo(&result); /* Получить полное определение индекса (без завершающей ';') */ indexdef = pg_get_indexdef_string(indexOid); if(indexdef) { appendStringInfo(&result, "-- Index\n"); appendStringInfo(&result, "%s%s", indexdef, sqlterminator ? ";" : ""); } else{ ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unable get definition for index with OID %u", indexOid))); } return result.data; } void make_index_comment(Oid indexOid, char *relname, char *schemaname, bool sqlterminator, char **ddl){ StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); char *seqComment = GetComment(indexOid, RelationRelationId, 0); if (seqComment) { appendStringInfo(&result, "\n\n-- Index comment\n"); appendStringInfo(&result, "COMMENT ON INDEX %s IS %s", full_qualified, quote_literal_cstr(seqComment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(seqComment); } /* Добавляем в конец DDL с явным приведением типа */ size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char*) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree_all(full_qualified, result.data); } char* build_index_ddl_text(Oid indexOid, char *indexName, char *schemaName, const int32 transform_handler) { char *ddl = nullptr; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeIndex)); bool sqlterminator_comment = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeComment)); ddl = make_index_statement(indexOid, sqlterminator); make_index_comment(indexOid, indexName, schemaName, sqlterminator_comment, &ddl); return ddl; } /* gets DDL for index creation */ Datum get_ddl_index(char *name, char *schema, char *version, char *model, char *transform) { text *result; Oid indexOid = getRelationOid(name, schema); char *ddl = NULL; char *schemaName, *indexName; if(get_rel_relkind(indexOid) != RELKIND_INDEX){ ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("index with OID %u does not exist", indexOid))); } get_object_names_by_oid(indexOid, &schemaName, &indexName); ddl = build_index_ddl_text(indexOid, indexName, schemaName, -1); result = cstring_to_text(ddl); pfree_all(ddl, indexName, schemaName); PG_RETURN_TEXT_P(result); } // TRIGGER bool get_trigger_names_by_oid(Oid relOid, char **schemaName, char **trigName) { char query[256] = {0}; int ret = 0; if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function DBMS_METADATA_FETCH_DDL"))); snprintf(query, sizeof(query), "SELECT t.tgname, n.nspname " "FROM pg_trigger t " "JOIN pg_class c ON c.oid = t.tgrelid " "JOIN pg_namespace n ON n.oid = c.relnamespace " "WHERE t.oid = %u", relOid); ret = SPI_execute(query, true, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_execute failed in function DBMS_METADATA_FETCH_DDL"))); } // first row is enough if (SPI_processed > 0) { Datum values[2]; bool nulls[2]; values[0] = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &nulls[0]); values[1] = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &nulls[1]); if (!nulls[0]) { const char *name = NameStr(*DatumGetName(values[0])); *trigName = (char *) SPI_palloc(strlen(name) + 1); strcpy(*trigName, name); } if (!nulls[1]) { const char *name = NameStr(*DatumGetName(values[1])); *schemaName = (char *) SPI_palloc(strlen(name) + 1); strcpy(*schemaName, name); } } else // <= 0 { /* The trigger might have been deleted in the period between the moment we've got it's Oid and the moment we've locked it */ SPI_finish(); return false; } SPI_finish(); return true; } char *make_trigger_statement(Oid triggerOid, bool sqlterminator) { char *triggerdef; text *triggerdef_t; StringInfoData result; initStringInfo(&result); // getting and converting trigger creation script triggerdef_t = DatumGetTextPP(DirectFunctionCall1(pg_get_triggerdef, ObjectIdGetDatum(triggerOid))); triggerdef = text_to_cstring(triggerdef_t); if(triggerdef) { appendStringInfo(&result, "-- Trigger\n"); appendStringInfo(&result, "%s%s", triggerdef, sqlterminator ? ";" : ""); pfree(triggerdef); } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Unable get definition for trigger with OID %u", triggerOid))); } return result.data; } void make_trigger_comment(Oid triggerOid, char *relname, char *schemaname, bool sqlterminator, char **ddl) { StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); char *triggerComment = GetComment(triggerOid, TriggerRelationId, 0); if (triggerComment) { appendStringInfo(&result, "\n\n-- Trigger comment\n"); appendStringInfo(&result, "COMMENT ON TRIGGER %s IS %s", full_qualified, quote_literal_cstr(triggerComment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(triggerComment); } // append to the ddl size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char*) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree_all(full_qualified, result.data); } char* build_trigger_ddl_text(Oid trigOid, char *trigName, char *schemaName, const int32 transform_handler) { char *ddl = nullptr; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeTrigger)); bool sqlterminator_comment = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeComment)); ddl = make_trigger_statement(trigOid, sqlterminator); make_trigger_comment(trigOid, trigName, schemaName, sqlterminator_comment, &ddl); return ddl; } Datum get_ddl_trigger(char *name, char *schema, char *version, char *model, char *transform) { text *result; text *name_text; char *ddl = NULL; char *schemaName; char query[256] = {0}; Oid schema_oid = InvalidOid; Oid trigger_oid = InvalidOid; Oid argtypes[] = { TEXTOID, OIDOID }; Datum argvals[2]; SPIPlanPtr plan = nullptr; int spi_ret = 0; // schema check if (!schema) { schemaName = MemoryContextStrdup(TopMemoryContext, "public"); } else { schemaName = MemoryContextStrdup(TopMemoryContext, schema); } // ----------------------------------------------------- getting schema OID schema_oid = get_namespace_oid(schemaName, false); // ---------------------------------------------------- getting trigger OID // preparing a query to SPI snprintf(query, sizeof(query), //"SELECT t.oid, t.tgrelid " "SELECT t.oid " "FROM pg_trigger t " "JOIN pg_class c ON c.oid = t.tgrelid " "WHERE t.tgname = $1 AND c.relnamespace = $2"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in function DBMS_METADATA_GET_DDL"))); // prepare plan with arguments name_text = cstring_to_text(name); argvals[0] = PointerGetDatum(name_text); argvals[1] = ObjectIdGetDatum(schema_oid); plan = SPI_prepare(query, 2, argtypes); if (plan == nullptr) { SPI_finish(); ereport(ERROR, (errmsg("SPI prepare failed"))); } spi_ret = SPI_execute_plan(plan, argvals, NULL, true, 0); if (spi_ret == SPI_OK_SELECT && SPI_processed > 0) { if (SPI_processed == 1) { bool isnull; // good! We've found only one Datum d_trig = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); trigger_oid = DatumGetObjectId(d_trig); /* elog(INFO, "Trigger '%s' found in schema '%s' on table OID %u", trigger_name, schema_name, table_oid); */ } else { // There are few tables with such trigger name... ereport(ERROR, (errcode(ERRCODE_CARDINALITY_VIOLATION), errmsg("Trigger name \"%s\" is not unique within " "schema \"%s\".", name, schemaName))); } } else { ereport(ERROR, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("Trigger '%s' not found in schema '%s'", name, schemaName))); } SPI_finish(); // ------------------------------------------------------------------------ ddl = build_trigger_ddl_text(trigger_oid, name, schemaName, -1); result = cstring_to_text(ddl); pfree_all(ddl, schemaName); PG_RETURN_TEXT_P(result); } // TYPE object Oid getTypeOid(const char *typeName, const char *schemaName, bool missing_ok = false) { List *names = NIL; if (schemaName != NULL) names = list_make2(makeString((char *)schemaName), makeString((char *)typeName)); else names = list_make1(makeString((char *)typeName)); TypeName *tn = makeTypeNameFromNameList(names); Oid result = LookupTypeNameOid(NULL, tn, missing_ok); pfree(tn); /* освобождаем узел TypeName */ list_free_deep(names); /* освобождаем список и все строки внутри */ return result; } /* Генерация DDL для составного (композитного) типа по OID отношения (relid) */ static char * make_composite_type(Oid relid, bool sqlterminator) { HeapTuple relTup; HeapTuple attTup; Form_pg_class relForm; Form_pg_attribute attForm; ScanKeyData skey[2]; SysScanDesc scan; Relation attRel; StringInfoData ddl; StringInfoData attrList; char *schemaName; char *typeName; bool first = true; /* Получаем информацию о составном типе из pg_class */ relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); if (!HeapTupleIsValid(relTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("cache lookup failed for relation %u", relid))); relForm = (Form_pg_class) GETSTRUCT(relTup); if (relForm->relkind != RELKIND_COMPOSITE_TYPE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation %u is not a composite type", relid))); schemaName = get_namespace_name(relForm->relnamespace); typeName = pstrdup(NameStr(relForm->relname)); ReleaseSysCache(relTup); /* Открываем pg_attribute для сканирования атрибутов (attnum > 0) */ attRel = table_open(AttributeRelationId, AccessShareLock); initStringInfo(&attrList); ScanKeyInit(&skey[0], Anum_pg_attribute_attrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relid)); ScanKeyInit(&skey[1], Anum_pg_attribute_attnum, BTGreaterStrategyNumber, F_INT2GT, Int16GetDatum(0)); scan = systable_beginscan(attRel, AttributeRelidNumIndexId, true, /* indexOK */ NULL, /* snapshot */ 2, skey); while (HeapTupleIsValid(attTup = systable_getnext(scan))) { const char *attname_c; char *attname; char *atttype; Oid atttypid; int32 atttypmod; attForm = (Form_pg_attribute) GETSTRUCT(attTup); atttypid = attForm->atttypid; atttypmod = attForm->atttypmod; attname_c = quote_identifier(NameStr(attForm->attname)); attname = pstrdup(attname_c); atttype = format_type_with_typemod(atttypid, atttypmod); if (!first) appendStringInfoString(&attrList, ", "); appendStringInfo(&attrList, "%s %s", attname, atttype); first = false; pfree(attname); pfree(atttype); } systable_endscan(scan); table_close(attRel, AccessShareLock); /* Формируем финальный CREATE TYPE */ initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE TYPE %s.%s AS (%s)", quote_identifier(schemaName), quote_identifier(typeName), attrList.data); if (sqlterminator) appendStringInfoChar(&ddl, ';'); pfree(attrList.data); pfree(typeName); if (schemaName) pfree(schemaName); return ddl.data; } /* fetch_ddl version of make_composite_type() */ static bool make_composite_type_fetch(Oid relid, bool sqlterminator, char** ddl) { HeapTuple relTup; HeapTuple attTup; Form_pg_class relForm; Form_pg_attribute attForm; ScanKeyData skey[2]; SysScanDesc scan; Relation attRel; StringInfoData si_ddl; StringInfoData attrList; char *schemaName; char *typeName; bool first = true; // lock table LockRelationOid(relid, AccessShareLock); relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); if (!HeapTupleIsValid(relTup)) { /* Something bad happened. Most probably the relation has been dropped while we were fetching data. Skip it */ UnlockRelationOid(relid, AccessShareLock); ReleaseSysCache(relTup); return false; } relForm = (Form_pg_class) GETSTRUCT(relTup); schemaName = get_namespace_name(relForm->relnamespace); typeName = pstrdup(NameStr(relForm->relname)); ReleaseSysCache(relTup); attRel = table_open(AttributeRelationId, AccessShareLock); initStringInfo(&attrList); ScanKeyInit(&skey[0], Anum_pg_attribute_attrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relid)); ScanKeyInit(&skey[1], Anum_pg_attribute_attnum, BTGreaterStrategyNumber, F_INT2GT, Int16GetDatum(0)); scan = systable_beginscan(attRel, AttributeRelidNumIndexId, true, /* indexOK */ NULL, /* snapshot */ 2, skey); while (HeapTupleIsValid(attTup = systable_getnext(scan))) { const char *attname_c; char *attname; char *atttype; Oid atttypid; int32 atttypmod; attForm = (Form_pg_attribute) GETSTRUCT(attTup); atttypid = attForm->atttypid; atttypmod = attForm->atttypmod; /* This can happen if attributes are dropped right now in parallel session. Skip it then */ if (atttypid == 0) { systable_endscan(scan); table_close(attRel, AccessShareLock); UnlockRelationOid(relid, AccessShareLock); pfree_all(schemaName, typeName); return false; } attname_c = quote_identifier(NameStr(attForm->attname)); attname = pstrdup(attname_c); //ereport(WARNING, errmsg("MCT cycle mid: atttypid %u atttypmod %d", atttypid, atttypmod)); atttype = format_type_with_typemod(atttypid, atttypmod); if (!first) appendStringInfoString(&attrList, ", "); appendStringInfo(&attrList, "%s %s", attname, atttype); first = false; pfree(attname); pfree(atttype); } systable_endscan(scan); table_close(attRel, AccessShareLock); UnlockRelationOid(relid, AccessShareLock); /* Формируем финальный CREATE TYPE */ initStringInfo(&si_ddl); appendStringInfo(&si_ddl, "CREATE TYPE %s.%s AS (%s)", quote_identifier(schemaName), quote_identifier(typeName), attrList.data); if (sqlterminator) appendStringInfoChar(&si_ddl, ';'); pfree(attrList.data); pfree(typeName); if (schemaName) pfree(schemaName); *ddl = si_ddl.data; return true; } /* Генерирует DDL для перечислимого (enum) типа по OID типа (pg_type.oid) */ static char * make_enum_type(Oid enumtypid, bool sqlterminator) { HeapTuple typTup; Form_pg_type typForm; char *schemaName; char *typeName; StringInfoData ddl; StringInfoData values; bool first = true; Relation enumRel; ScanKeyData skey[1]; SysScanDesc scan; HeapTuple enumTup; typTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enumtypid)); if (!HeapTupleIsValid(typTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("cache lookup failed for type %u", enumtypid))); typForm = (Form_pg_type) GETSTRUCT(typTup); if (typForm->typtype != TYPTYPE_ENUM) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("type %u is not an enum", enumtypid))); schemaName = get_namespace_name(typForm->typnamespace); typeName = pstrdup(NameStr(typForm->typname)); ReleaseSysCache(typTup); /* Открываем pg_enum для получения значений */ enumRel = table_open(EnumRelationId, AccessShareLock); initStringInfo(&values); ScanKeyInit(&skey[0], Anum_pg_enum_enumtypid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(enumtypid)); scan = systable_beginscan(enumRel, EnumTypIdLabelIndexId, true, NULL, 1, skey); while (HeapTupleIsValid(enumTup = systable_getnext(scan))) { Form_pg_enum enumForm = (Form_pg_enum) GETSTRUCT(enumTup); char *label = pstrdup(NameStr(enumForm->enumlabel)); char *quoted = quote_literal_cstr(label); if (!first) appendStringInfoString(&values, ", "); appendStringInfoString(&values, quoted); first = false; pfree(label); pfree(quoted); } systable_endscan(scan); table_close(enumRel, AccessShareLock); /* Формируем финальный CREATE TYPE AS ENUM */ initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE TYPE %s.%s AS ENUM (%s)", quote_identifier(schemaName), quote_identifier(typeName), values.data); if (sqlterminator) appendStringInfoChar(&ddl, ';'); pfree(values.data); pfree(typeName); if (schemaName) pfree(schemaName); return ddl.data; } //range static char * get_opclass_name_oid(Oid opcid) { char *result = NULL; Relation rel; ScanKeyData skey; SysScanDesc scan; HeapTuple tup; rel = table_open(OperatorClassRelationId, AccessShareLock); ScanKeyInit(&skey, Anum_pg_opclass_oid, /* вместо ObjectIdAttributeNumber */ BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(opcid)); scan = systable_beginscan(rel, OpclassOidIndexId, true, NULL, 1, &skey); tup = systable_getnext(scan); if (HeapTupleIsValid(tup)) { Form_pg_opclass opcForm = (Form_pg_opclass) GETSTRUCT(tup); char *opcName = pstrdup(NameStr(opcForm->opcname)); Oid nspid = opcForm->opcnamespace; char *nspName = get_namespace_name(nspid); result = psprintf("%s.%s", nspName, opcName); pfree(opcName); if (nspName) pfree(nspName); } systable_endscan(scan); table_close(rel, AccessShareLock); return result; } //range static char *make_range_type(Oid rangetypid, bool sqlterminator) { HeapTuple typTup; Form_pg_type typForm; HeapTuple rangeTup; Form_pg_range rangeForm; char *schemaName; char *typeName; StringInfoData ddl; Oid rngsubtype; Oid rngcollation = InvalidOid; Oid rngsubopc = InvalidOid; Oid rngcanonical = InvalidOid; Oid rngsubdiff = InvalidOid; char *subtypeName = NULL; char *collationName = NULL; char *opclassName = NULL; char *canonicalName = NULL; char *subdiffName = NULL; bool first = true; Relation rangeRel; ScanKeyData skey; SysScanDesc scan; typTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rangetypid)); if (!HeapTupleIsValid(typTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("cache lookup failed for type %u", rangetypid))); typForm = (Form_pg_type) GETSTRUCT(typTup); if (typForm->typtype != TYPTYPE_RANGE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("type %u is not a range type", rangetypid))); schemaName = get_namespace_name(typForm->typnamespace); typeName = pstrdup(NameStr(typForm->typname)); ReleaseSysCache(typTup); /* Получаем запись pg_range */ rangeRel = table_open(RangeRelationId, AccessShareLock); ScanKeyInit(&skey, Anum_pg_range_rngtypid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(rangetypid)); scan = systable_beginscan(rangeRel, RangeTypidIndexId, true, NULL, 1, &skey); rangeTup = systable_getnext(scan); if (!HeapTupleIsValid(rangeTup)) { systable_endscan(scan); table_close(rangeRel, AccessShareLock); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("range type %u not found in pg_range", rangetypid))); } rangeForm = (Form_pg_range) GETSTRUCT(rangeTup); rngsubtype = rangeForm->rngsubtype; rngcollation = rangeForm->rngcollation; rngsubopc = rangeForm->rngsubopc; rngcanonical = rangeForm->rngcanonical; rngsubdiff = rangeForm->rngsubdiff; systable_endscan(scan); table_close(rangeRel, AccessShareLock); /* Формируем имена объектов */ subtypeName = format_type_with_typemod(rngsubtype, -1); if (OidIsValid(rngcollation)) collationName = get_collation_name(rngcollation); if (OidIsValid(rngsubopc)) opclassName = get_opclass_name_oid(rngsubopc); if (OidIsValid(rngcanonical)) canonicalName = get_func_name(rngcanonical); if (OidIsValid(rngsubdiff)) subdiffName = get_func_name(rngsubdiff); /* Формируем DDL */ initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE TYPE %s.%s AS RANGE (", quote_identifier(schemaName), quote_identifier(typeName)); if (subtypeName) { appendStringInfo(&ddl, "%s SUBTYPE = %s", first ? "" : ", ", subtypeName); first = false; pfree(subtypeName); } if (opclassName) { appendStringInfo(&ddl, ", SUBTYPE_OPCLASS = %s", opclassName); pfree(opclassName); } if (collationName) { const char *quoted_coll = quote_identifier(collationName); appendStringInfo(&ddl, ", COLLATION = %s", quoted_coll); if(quoted_coll != collationName) pfree((void*)quoted_coll); pfree(collationName); } if (canonicalName) { appendStringInfo(&ddl, ", CANONICAL = %s", canonicalName); pfree(canonicalName); } if (subdiffName) { appendStringInfo(&ddl, ", SUBTYPE_DIFF = %s", subdiffName); pfree(subdiffName); } appendStringInfoString(&ddl, ")"); if (sqlterminator) appendStringInfoChar(&ddl, ';'); pfree(typeName); if (schemaName) pfree(schemaName); return ddl.data; } // тип пустышка static char *make_pseudo_type(Oid pseudotypid, bool sqlterminator) { HeapTuple typTup; Form_pg_type typForm; char *schemaName; char *typeName; StringInfoData ddl; typTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(pseudotypid)); if (!HeapTupleIsValid(typTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("cache lookup failed for type %u", pseudotypid))); typForm = (Form_pg_type) GETSTRUCT(typTup); if (typForm->typtype != TYPTYPE_PSEUDO) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("type %u is not a shell type", pseudotypid))); schemaName = get_namespace_name(typForm->typnamespace); typeName = pstrdup(NameStr(typForm->typname)); ReleaseSysCache(typTup); initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE TYPE %s.%s", quote_identifier(schemaName), quote_identifier(typeName)); if (sqlterminator) appendStringInfoChar(&ddl, ';'); pfree(typeName); if (schemaName) pfree(schemaName); return ddl.data; } static char * make_domain_type(Oid domaintypid, bool sqlterminator) { MemoryContext oldcontext = CurrentMemoryContext; StringInfoData ddl; int ret; SPITupleTable *tuptable; TupleDesc tupdesc; HeapTuple tuple; char *schemaName = NULL; char *typeName = NULL; char *baseType = NULL; char *collationName = NULL; char *defaultStr = NULL; bool notNull = false; Oid argtypes[1]; Datum values[1]; char *tmp = NULL; int nchecks = 0; char **checkNames = NULL; char **checkDefs = NULL; ret = SPI_connect(); if (ret != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", ret))); const char *mainQuery = "SELECT " " n.nspname AS schemaname, " " t.typname AS typename, " " format_type(t.typbasetype, t.typtypmod) AS basetype, " " (SELECT collname FROM pg_collation WHERE oid = t.typcollation) AS collname, " " t.typdefault AS default_expr, " " t.typnotnull " "FROM pg_type t " "JOIN pg_namespace n ON t.typnamespace = n.oid " "WHERE t.oid = $1 AND t.typtype = 'd'"; argtypes[0] = OIDOID; values[0] = ObjectIdGetDatum(domaintypid); ret = SPI_execute_with_args(mainQuery, 1, argtypes, values, NULL, false, 1); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("SPI_execute_with_args failed: %d", ret))); } if (SPI_processed == 0) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("domain type %u not found in pg_type", domaintypid))); } tuptable = SPI_tuptable; tupdesc = tuptable->tupdesc; tuple = tuptable->vals[0]; MemoryContextSwitchTo(oldcontext); tmp = SPI_getvalue(tuple, tupdesc, 1); if (tmp) { schemaName = pstrdup(tmp); pfree(tmp); } tmp = SPI_getvalue(tuple, tupdesc, 2); if (tmp) { typeName = pstrdup(tmp); pfree(tmp); } tmp = SPI_getvalue(tuple, tupdesc, 3); if (tmp) { baseType = pstrdup(tmp); pfree(tmp); } tmp = SPI_getvalue(tuple, tupdesc, 4); if (tmp) { collationName = pstrdup(tmp); pfree(tmp); } tmp = SPI_getvalue(tuple, tupdesc, 5); if (tmp) { defaultStr = pstrdup(tmp); pfree(tmp); } tmp = SPI_getvalue(tuple, tupdesc, 6); if (tmp) { notNull = (strcmp(tmp, "t") == 0); pfree(tmp); } if (!schemaName || !typeName || !baseType) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("incomplete data for domain type %u", domaintypid))); } const char *checkQuery = "SELECT conname, pg_get_constraintdef(oid) " "FROM pg_constraint " "WHERE contypid = $1 AND contype = 'c' " "ORDER BY conname"; argtypes[0] = OIDOID; values[0] = ObjectIdGetDatum(domaintypid); ret = SPI_execute_with_args(checkQuery, 1, argtypes, values, NULL, false, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("SPI_execute_with_args failed for check constraints: %d", ret))); } MemoryContextSwitchTo(oldcontext); nchecks = SPI_processed; if (nchecks > 0) { checkNames = (char **) palloc(nchecks * sizeof(char *)); checkDefs = (char **) palloc(nchecks * sizeof(char *)); tuptable = SPI_tuptable; tupdesc = tuptable->tupdesc; for (int i = 0; i < nchecks; i++) { tuple = tuptable->vals[i]; tmp = SPI_getvalue(tuple, tupdesc, 1); checkNames[i] = tmp ? pstrdup(tmp) : NULL; if (tmp) pfree(tmp); tmp = SPI_getvalue(tuple, tupdesc, 2); checkDefs[i] = tmp ? pstrdup(tmp) : NULL; if (tmp) pfree(tmp); } } SPI_finish(); initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE DOMAIN %s.%s AS %s", quote_identifier(schemaName), quote_identifier(typeName), baseType); if (collationName) { const char *quoted_coll = quote_identifier(collationName); appendStringInfo(&ddl, " COLLATE %s", quoted_coll); if(quoted_coll != collationName) pfree((void*)quoted_coll); } if (defaultStr) appendStringInfo(&ddl, " DEFAULT %s", defaultStr); if (notNull) appendStringInfoString(&ddl, " NOT NULL"); for (int i = 0; i < nchecks; i++) { char *conname = checkNames[i]; char *condef = checkDefs[i]; if (!conname || !condef) { if (conname) pfree(conname); if (condef) pfree(condef); continue; } if (strncmp(condef, "CHECK (", 7) == 0) { size_t len = strlen(condef); if (len > 8 && condef[len - 1] == ')') { char *expr = (char *) palloc(len - 7); memcpy(expr, condef + 7, len - 8); expr[len - 8] = '\0'; appendStringInfo(&ddl, " CONSTRAINT %s CHECK (%s)", quote_identifier(conname), expr); pfree(expr); } else { appendStringInfo(&ddl, " CONSTRAINT %s %s", quote_identifier(conname), condef); } } else { appendStringInfo(&ddl, " CONSTRAINT %s %s", quote_identifier(conname), condef); } pfree(conname); pfree(condef); } if (checkNames) pfree(checkNames); if (checkDefs) pfree(checkDefs); if (sqlterminator) appendStringInfoChar(&ddl, ';'); if (schemaName) pfree(schemaName); if (typeName) pfree(typeName); if (baseType) pfree(baseType); if (collationName) pfree(collationName); if (defaultStr) pfree(defaultStr); return ddl.data; } /* fetch_ddl version of make_type_statement() */ bool build_type_statement(Oid typeOid, Oid table_oid, const char typetype, char** ddl, const int32 transform_handler) { bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeType)); switch (typetype) { case TYPTYPE_COMPOSITE: /* 'c' */ return make_composite_type_fetch(table_oid, sqlterminator, ddl); break; // the ones under this comment may cause ereport case TYPTYPE_ENUM: /* 'e' */ *ddl = make_enum_type(typeOid, sqlterminator); break; case TYPTYPE_RANGE: /* 'r' */ *ddl = make_range_type(typeOid, sqlterminator); break; case TYPTYPE_PSEUDO: /* 'p' */ *ddl = make_pseudo_type(typeOid, sqlterminator); break; case TYPTYPE_DOMAIN: /* 'd' */ *ddl = make_domain_type(typeOid, sqlterminator); break; default: /* unexpectef type type, skip */ return false; break; } return true; } // основная функция генерации типа char *make_type_statement(Oid typeOid, const int32 transform_handler) { HeapTuple typTup; Form_pg_type typForm; char typtype; Oid relid; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeType)); typTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid)); if (!HeapTupleIsValid(typTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("cache lookup failed for type %u", typeOid))); typForm = (Form_pg_type) GETSTRUCT(typTup); typtype = typForm->typtype; relid = typForm->typrelid; /* для составного типа — OID отношения */ ReleaseSysCache(typTup); switch (typtype) { case TYPTYPE_COMPOSITE: /* 'c' */ if (!OidIsValid(relid)) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("composite type %u has no associated relation", typeOid))); return make_composite_type(relid, sqlterminator); case TYPTYPE_ENUM: /* 'e' */ return make_enum_type(typeOid, sqlterminator); case TYPTYPE_RANGE: /* 'r' */ return make_range_type(typeOid, sqlterminator); case TYPTYPE_PSEUDO: /* 'p' */ return make_pseudo_type(typeOid, sqlterminator); case TYPTYPE_DOMAIN: /* 'd' */ return make_domain_type(typeOid, sqlterminator); default: ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("unsupported type category '%c' for DDL generation", typtype))); } } Datum get_ddl_type(char *name, char *schema, char *version, char *model, char *transform) { text *result; Oid typeOid = getTypeOid(name, schema); char *ddl = make_type_statement(typeOid, -1); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } // FUNCTION List *getRoutineOids(char *schema, char *name, bool is_func) { List *names; FuncCandidateList candidates; int fgc_flags; List *oidlist = NIL; FuncCandidateList cur; char expected_kind = is_func ? PROKIND_FUNCTION : PROKIND_PROCEDURE; if (name == NULL) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("routine name must not be NULL"))); /* Формируем список имён для FuncnameGetCandidates */ if (schema != NULL) names = list_make2(makeString(schema), makeString(name)); else names = list_make1(makeString(name)); /* * Получаем всех кандидатов (без ограничения по числу аргументов). * Параметры: * nargs = -1 любое число аргументов * argnames = NIL * expand_variadic = false * expand_defaults = false * missing_ok = false если ни одного кандидата, возвращает NULL * force_parallel = false */ candidates = FuncnameGetCandidates(names, -1, NIL, false, false, false, false, &fgc_flags); if (candidates == NULL) { if (schema != NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("routine \"%s.%s\" does not exist", schema, name))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("routine \"%s\" does not exist", name))); } /* Фильтруем кандидатов по prokind */ for (cur = candidates; cur != NULL; cur = cur->next) { HeapTuple proTup; Form_pg_proc proForm; proTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(cur->oid)); if (!HeapTupleIsValid(proTup)) continue; /* на всякий случай */ proForm = (Form_pg_proc) GETSTRUCT(proTup); if (proForm->prokind == expected_kind) oidlist = lappend_oid(oidlist, cur->oid); ReleaseSysCache(proTup); } /* Если после фильтрации ничего не осталось — ошибка */ if (oidlist == NIL) { const char *objtype = is_func ? "function" : "procedure"; if (schema != NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("%s \"%s.%s\" does not exist", objtype, schema, name))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("%s \"%s\" does not exist", objtype, name))); } return oidlist; } char *make_function_statement(Oid funcOid, bool is_func, const int32 transform_handler) { HeapTuple proTup; Form_pg_proc proForm; char expected_kind; Datum defDatum; text *defText; char *defCString; StringInfoData ddl; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", is_func ? ObjectTypeFunction : ObjectTypeProcedure)); /* 1. Проверка существования и типа объекта */ proTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid)); if (!HeapTupleIsValid(proTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("function with OID %u does not exist", funcOid))); proForm = (Form_pg_proc) GETSTRUCT(proTup); expected_kind = is_func ? PROKIND_FUNCTION : PROKIND_PROCEDURE; if (proForm->prokind != expected_kind) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("OID %u is not a %s", funcOid, is_func ? "function" : "procedure"))); ReleaseSysCache(proTup); /* 2. Получение DDL через pg_get_functiondef */ defDatum = DirectFunctionCall1(pg_get_functiondef, ObjectIdGetDatum(funcOid)); defText = DatumGetTextP(defDatum); defCString = text_to_cstring(defText); /* 3. Формирование результата с помощью StringInfo */ initStringInfo(&ddl); appendStringInfoString(&ddl, defCString); /* 4. Добавление терминатора, если требуется */ if (sqlterminator && ddl.len > 0 && ddl.data[ddl.len - 1] != ';' && ddl.data[ddl.len - 1] != '/') { appendStringInfoChar(&ddl, ';'); } pfree(defCString); /* освобождаем временную строку */ /* 5. Возвращаем строку из StringInfo (она уже в palloc-памяти) */ return ddl.data; } char* build_function_ddl(Oid funcOid, char *schema, char *funcName, const int32 transform_handler, ObjectType obj_type) { Datum defDatum; text *defText; char *defCString; StringInfoData ddl; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", obj_type)); defDatum = DirectFunctionCall1(pg_get_functiondef, ObjectIdGetDatum(funcOid)); defText = DatumGetTextP(defDatum); defCString = text_to_cstring(defText); initStringInfo(&ddl); appendStringInfoString(&ddl, defCString); // terminatoring if (sqlterminator && ddl.len > 0 && ddl.data[ddl.len - 1] != ';' && ddl.data[ddl.len - 1] != '/') { appendStringInfoChar(&ddl, ';'); } pfree(defCString); return ddl.data; } Datum get_ddl_function(char *name, char *schema, char *version, char *model, char *transform, bool is_func) { text *result; List *oids = getRoutineOids(schema, name, is_func); ListCell *lc; StringInfoData resultDdl; initStringInfo(&resultDdl); foreach(lc, oids) { Oid funcOid = lfirst_oid(lc); char *ddl = make_function_statement(funcOid, is_func, -1); appendStringInfoString(&resultDdl, ddl); appendStringInfoChar(&resultDdl, '\n'); pfree(ddl); } result = cstring_to_text(resultDdl.data); pfree_all(resultDdl.data); list_free(oids); PG_RETURN_TEXT_P(result); } List * getRlsPolicyOids(char *schema, char *name) { MemoryContext oldcontext = CurrentMemoryContext; List *oidlist = NIL; int ret; SPITupleTable *tuptable; TupleDesc tupdesc; Oid argtypes[2]; Datum values[2]; int nargs = 0; if (name == NULL) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("policy name must not be NULL"))); ret = SPI_connect(); if (ret != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", ret))); const char *query; if (schema != NULL) { query = "SELECT p.oid " "FROM pg_policy p " "JOIN pg_class c ON p.polrelid = c.oid " "JOIN pg_namespace n ON c.relnamespace = n.oid " "WHERE p.polname = $1 AND n.nspname = $2"; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; values[0] = CStringGetTextDatum(name); values[1] = CStringGetTextDatum(schema); nargs = 2; } else { query = "SELECT p.oid " "FROM pg_policy p " "JOIN pg_class c ON p.polrelid = c.oid " "WHERE p.polname = $1"; argtypes[0] = TEXTOID; values[0] = CStringGetTextDatum(name); nargs = 1; } ret = SPI_execute_with_args(query, nargs, argtypes, values, NULL, false, 0); if (ret != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("SPI_execute_with_args failed: %d", ret))); } tuptable = SPI_tuptable; tupdesc = tuptable->tupdesc; /* Переключаемся в контекст вызова, чтобы список выделялся в нём */ MemoryContextSwitchTo(oldcontext); for (uint64 i = 0; i < SPI_processed; i++) { HeapTuple tuple = tuptable->vals[i]; bool isnull; Oid polOid = DatumGetObjectId(SPI_getbinval(tuple, tupdesc, 1, &isnull)); oidlist = lappend_oid(oidlist, polOid); } SPI_finish(); if (oidlist == NIL) { if (schema != NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("policy \"%s\" on schema \"%s\" does not exist", name, schema))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("policy \"%s\" does not exist in any schema", name))); } return oidlist; } char *make_rlspolicy_statement(Oid rlspolicyOid, const int32 transform_handler) { Relation policyRel; ScanKeyData skey; SysScanDesc scan; HeapTuple polTuple; Form_pg_policy polForm; HeapTuple relTuple; Form_pg_class relForm; char *polName; char *relName; char *schemaName; char polcmd; bool permissive; Oid relid; char *usingText = NULL; char *withcheckText = NULL; StringInfoData ddl; StringInfoData rolesStr; bool isnull; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeRlsPolicy)); policyRel = table_open(PolicyRelationId, AccessShareLock); ScanKeyInit(&skey, Anum_pg_policy_oid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(rlspolicyOid)); scan = systable_beginscan(policyRel, PolicyOidIndexId, true, NULL, 1, &skey); polTuple = systable_getnext(scan); if (!HeapTupleIsValid(polTuple)) { systable_endscan(scan); table_close(policyRel, AccessShareLock); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("RLS policy with OID %u does not exist", rlspolicyOid))); } polForm = (Form_pg_policy) GETSTRUCT(polTuple); polName = pstrdup(NameStr(polForm->polname)); polcmd = polForm->polcmd; permissive = polForm->polpermissive; relid = polForm->polrelid; /* Получение USING-выражения */ Datum polqualDatum = heap_getattr(polTuple, Anum_pg_policy_polqual, RelationGetDescr(policyRel), &isnull); if (!isnull) { Datum result = DirectFunctionCall2(pg_get_expr, polqualDatum, ObjectIdGetDatum(relid)); usingText = text_to_cstring(DatumGetTextP(result)); } /* Получение WITH CHECK-выражения */ Datum polwithcheckDatum = heap_getattr(polTuple, Anum_pg_policy_polwithcheck, RelationGetDescr(policyRel), &isnull); if (!isnull) { Datum result = DirectFunctionCall2(pg_get_expr, polwithcheckDatum, ObjectIdGetDatum(relid)); withcheckText = text_to_cstring(DatumGetTextP(result)); } /* ===== ОБРАБОТКА РОЛЕЙ ===== */ initStringInfo(&rolesStr); Datum rolesDatum = heap_getattr(polTuple, Anum_pg_policy_polroles, RelationGetDescr(policyRel), &isnull); if (!isnull) { ArrayType *rolesArr = DatumGetArrayTypeP(rolesDatum); Datum *roleDatums; bool *roleNulls; int nroles; deconstruct_array(rolesArr, OIDOID, sizeof(Oid), true, 'i', &roleDatums, &roleNulls, &nroles); if (nroles == 0) { /* Пустой массив → PUBLIC */ appendStringInfoString(&rolesStr, "PUBLIC"); } else { bool first = true; for (int i = 0; i < nroles; i++) { if (roleNulls[i]) continue; Oid roleOid = DatumGetObjectId(roleDatums[i]); /* Пропускаем InvalidOid*/ if (roleOid == InvalidOid) continue; char *roleName = GetUserNameFromId(roleOid, false); if (roleName && roleName[0] != '\0') { if (!first) appendStringInfoString(&rolesStr, ", "); appendStringInfoString(&rolesStr, quote_identifier(roleName)); first = false; } pfree(roleName); } /* Если после фильтрации не осталось ролей – считаем как PUBLIC */ if (first) appendStringInfoString(&rolesStr, "PUBLIC"); } pfree(roleDatums); pfree(roleNulls); } else { /* Если поле NULL (не должно быть, но на всякий случай) – PUBLIC */ appendStringInfoString(&rolesStr, "PUBLIC"); } systable_endscan(scan); table_close(policyRel, AccessShareLock); /* Получение информации о таблице и схеме */ relTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); if (!HeapTupleIsValid(relTuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation with OID %u does not exist", relid))); relForm = (Form_pg_class) GETSTRUCT(relTuple); relName = pstrdup(NameStr(relForm->relname)); schemaName = get_namespace_name(relForm->relnamespace); ReleaseSysCache(relTuple); /* Формирование DDL */ initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE POLICY %s ON %s.%s", quote_identifier(polName), quote_identifier(schemaName), quote_identifier(relName)); if (!permissive) appendStringInfoString(&ddl, " AS RESTRICTIVE"); else appendStringInfoString(&ddl, " AS PERMISSIVE"); if (polcmd != '*') { const char *cmd_str; switch (polcmd) { case 'r': cmd_str = "SELECT"; break; case 'a': cmd_str = "INSERT"; break; case 'w': cmd_str = "UPDATE"; break; case 'd': cmd_str = "DELETE"; break; default: cmd_str = "ALL"; break; } appendStringInfo(&ddl, " FOR %s", cmd_str); } /* всегда добавляем TO */ if (rolesStr.len > 0) appendStringInfo(&ddl, " TO %s", rolesStr.data); else appendStringInfoString(&ddl, " TO PUBLIC"); if (usingText && usingText[0] != '\0') appendStringInfo(&ddl, " USING (%s)", usingText); if (withcheckText && withcheckText[0] != '\0') appendStringInfo(&ddl, " WITH CHECK (%s)", withcheckText); if (sqlterminator) appendStringInfoChar(&ddl, ';'); /* Очистка */ pfree(polName); pfree(relName); if (schemaName) pfree(schemaName); if (usingText) pfree(usingText); if (withcheckText) pfree(withcheckText); pfree(rolesStr.data); return ddl.data; } Datum get_ddl_rlspolicy(char *name, char *schema, char *version, char *model, char *transform) { text *result; List *oids = getRlsPolicyOids(schema, name); ListCell *lc; StringInfoData resultDdl; initStringInfo(&resultDdl); foreach(lc, oids) { Oid funcOid = lfirst_oid(lc); char *ddl = make_rlspolicy_statement(funcOid, -1); appendStringInfoString(&resultDdl, ddl); appendStringInfoChar(&resultDdl, '\n'); pfree(ddl); } result = cstring_to_text(resultDdl.data); pfree_all(resultDdl.data); list_free(oids); PG_RETURN_TEXT_P(result); } Datum get_ddl_comment(char *name, char *schema, char *version, char *model, char *transform) { const char* func_name = "DBMS_METADATA_GET_DDL"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value \"%s\" for parameter NAME" " in function %s", name, func_name))); return Datum(); } // ROLE char *make_role_statement(Oid roleOid, const int32 transform_handler, bool on_user = false) { HeapTuple roleTup; Form_pg_authid roleForm; StringInfoData ddl; char *rolename; const char *quoted_rolename; Datum validuntil_datum; bool isnull; bool first_option = true; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", on_user ? ObjectTypeUser : ObjectTypeRole)); roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleOid)); if (!HeapTupleIsValid(roleTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("role with OID %u does not exist", roleOid))); roleForm = (Form_pg_authid) GETSTRUCT(roleTup); /* Если запрошен пользователь (on_user), проверяем наличие LOGIN */ if (on_user && !roleForm->rolcanlogin) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("role \"%s\" does not have LOGIN privilege", NameStr(roleForm->rolname)))); rolename = pstrdup(NameStr(roleForm->rolname)); quoted_rolename = quote_identifier(rolename); initStringInfo(&ddl); /* Используем CREATE USER или CREATE ROLE в зависимости от on_user */ if (on_user) appendStringInfo(&ddl, "CREATE USER %s", quoted_rolename); else appendStringInfo(&ddl, "CREATE ROLE %s", quoted_rolename); #define APPEND_OPTION(optname, value) \ do { \ appendStringInfo(&ddl, "%s %s%s", \ first_option ? " WITH" : "", \ (value) ? "" : "NO", \ optname); \ first_option = false; \ } while (0) APPEND_OPTION("SUPERUSER", roleForm->rolsuper); APPEND_OPTION("INHERIT", roleForm->rolinherit); APPEND_OPTION("CREATEROLE", roleForm->rolcreaterole); APPEND_OPTION("CREATEDB", roleForm->rolcreatedb); if(!on_user) // для create user LOGIN включен по умолчанию, не прописываем явно APPEND_OPTION("LOGIN", roleForm->rolcanlogin); APPEND_OPTION("REPLICATION", roleForm->rolreplication); APPEND_OPTION("BYPASSRLS", roleForm->rolbypassrls); #undef APPEND_OPTION if (roleForm->rolconnlimit != -1) { appendStringInfo(&ddl, "%s CONNECTION LIMIT %d", first_option ? " WITH" : "", roleForm->rolconnlimit); first_option = false; } validuntil_datum = SysCacheGetAttr(AUTHOID, roleTup, Anum_pg_authid_rolvaliduntil, &isnull); if (!isnull) { char *validuntil_str = DatumGetCString( DirectFunctionCall1(timestamptz_out, validuntil_datum) ); appendStringInfo(&ddl, "%s VALID UNTIL '%s'", first_option ? " WITH" : "", validuntil_str); pfree(validuntil_str); first_option = false; } if (sqlterminator) appendStringInfoChar(&ddl, ';'); /* Освобождаем память */ if(rolename != quoted_rolename) pfree((void*)quoted_rolename); pfree(rolename); ReleaseSysCache(roleTup); return ddl.data; } Datum get_ddl_role(char *name, char *schema, char *version, char *model, char *transform) { text * result; Oid roleOid = get_role_oid(name, false); char *ddl = make_role_statement(roleOid, -1); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } Datum get_ddl_user(char *name, char *schema, char *version, char *model, char *transform) { text * result; Oid roleOid = get_role_oid(name, false); char *ddl = make_role_statement(roleOid, -1, true); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } // TABLESPACE char * make_tablespace_statement(Oid tablespaceOid, const int32 transform_handler) { HeapTuple spcTup; Form_pg_tablespace spcForm; StringInfoData ddl; const char *spcname; const char *quoted_spcname; char *owner_name; char *location; Datum options_datum; bool isnull; ArrayType *options_array; Datum *option_datums; bool *option_nulls; int noptions; int i; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeTablespace)); spcTup = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(tablespaceOid)); if (!HeapTupleIsValid(spcTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("tablespace with OID %u does not exist", tablespaceOid))); spcForm = (Form_pg_tablespace) GETSTRUCT(spcTup); spcname = NameStr(spcForm->spcname); quoted_spcname = quote_identifier(spcname); owner_name = GetUserNameFromId(spcForm->spcowner, false); /* Проверяем, является ли табличное пространство системным */ if (tablespaceOid == DEFAULTTABLESPACE_OID || tablespaceOid == GLOBALTABLESPACE_OID) { ReleaseSysCache(spcTup); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot generate DDL for system tablespace \"%s\"", spcname))); } /* Получаем путь */ Datum location_datum = DirectFunctionCall1(pg_tablespace_location, ObjectIdGetDatum(tablespaceOid)); location = text_to_cstring(DatumGetTextP(location_datum)); /* Проверяем, что путь не пустой */ if (location == NULL || location[0] == '\0') ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("tablespace \"%s\" has no valid location", spcname))); options_datum = SysCacheGetAttr(TABLESPACEOID, spcTup, Anum_pg_tablespace_spcoptions, &isnull); initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE TABLESPACE %s", quoted_spcname); if (owner_name) { const char *quoted_owner = quote_identifier(owner_name); appendStringInfo(&ddl, " OWNER %s", quoted_owner); if(quoted_owner != owner_name) pfree((void*)quoted_owner); } appendStringInfo(&ddl, " LOCATION '%s'", location); if (!isnull) { options_array = DatumGetArrayTypeP(options_datum); deconstruct_array(options_array, TEXTOID, -1, false, 'i', &option_datums, &option_nulls, &noptions); if (noptions > 0) { StringInfoData options_str; initStringInfo(&options_str); for (i = 0; i < noptions; i++) { if (option_nulls[i]) continue; char *opt = text_to_cstring(DatumGetTextP(option_datums[i])); if (i > 0) appendStringInfoString(&options_str, ", "); appendStringInfoString(&options_str, opt); pfree(opt); } if (options_str.len > 0) { appendStringInfo(&ddl, " WITH (%s)", options_str.data); pfree(options_str.data); } } pfree(option_datums); pfree(option_nulls); } if (sqlterminator) appendStringInfoChar(&ddl, ';'); if(quoted_spcname != spcname) pfree((void*)quoted_spcname); if (owner_name) pfree(owner_name); pfree(location); ReleaseSysCache(spcTup); return ddl.data; } Datum get_ddl_tablespace(char *name, char *schema, char *version, char *model, char *transform) { text *result; Oid tablespaceOid = get_tablespace_oid(name, false); char *ddl = make_tablespace_statement(tablespaceOid, -1); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } // MATERIALIZED VIEW char * make_materialized_view_statement(Oid mvOid, const int32 transform_handler) { HeapTuple relTup; Form_pg_class relForm; HeapTuple tsTup; Form_pg_tablespace tsForm; char *schemaName; char *relName; char *viewdef = NULL; char *tablespaceName = NULL; Datum viewdef_datum; Datum relopts_datum; bool isnull; Datum *option_datums = NULL; bool *option_nulls = NULL; int noptions = 0; StringInfoData ddl; int i; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeMaterializedView)); /* 1. Получаем кортеж pg_class через RELOID */ relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(mvOid)); if (!HeapTupleIsValid(relTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("relation with OID %u does not exist", mvOid))); relForm = (Form_pg_class) GETSTRUCT(relTup); if (relForm->relkind != RELKIND_MATVIEW) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a materialized view", NameStr(relForm->relname)))); schemaName = get_namespace_name(relForm->relnamespace); relName = pstrdup(NameStr(relForm->relname)); /* 2. Получаем определение запроса */ viewdef_datum = DirectFunctionCall1(pg_get_viewdef, ObjectIdGetDatum(mvOid)); viewdef = text_to_cstring(DatumGetTextP(viewdef_datum)); /* --- УДАЛЕНИЕ ЗАВЕРШАЮЩЕЙ ';' (ЕСЛИ ЕСТЬ) --- */ if (viewdef != NULL) { int len = strlen(viewdef); if (len > 0 && viewdef[len - 1] == ';') viewdef[len - 1] = '\0'; } /* 3. Опции (reloptions) */ relopts_datum = SysCacheGetAttr(RELOID, relTup, Anum_pg_class_reloptions, &isnull); if (!isnull) { ArrayType *relopts_arr = DatumGetArrayTypeP(relopts_datum); deconstruct_array(relopts_arr, TEXTOID, -1, false, 'i', &option_datums, &option_nulls, &noptions); } /* 4. Табличное пространство */ if (OidIsValid(relForm->reltablespace)) { tsTup = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(relForm->reltablespace)); if (HeapTupleIsValid(tsTup)) { tsForm = (Form_pg_tablespace) GETSTRUCT(tsTup); tablespaceName = pstrdup(NameStr(tsForm->spcname)); ReleaseSysCache(tsTup); } } ReleaseSysCache(relTup); /* 5. Формируем DDL */ initStringInfo(&ddl); appendStringInfo(&ddl, "CREATE MATERIALIZED VIEW %s.%s", quote_identifier(schemaName), quote_identifier(relName)); if (noptions > 0) { StringInfoData opt_str; initStringInfo(&opt_str); for (i = 0; i < noptions; i++) { if (option_nulls[i]) continue; char *opt = text_to_cstring(DatumGetTextP(option_datums[i])); if (i > 0) appendStringInfoString(&opt_str, ", "); appendStringInfoString(&opt_str, opt); pfree(opt); } if (opt_str.len > 0) { appendStringInfo(&ddl, " WITH (%s)", opt_str.data); pfree(opt_str.data); } pfree(option_datums); pfree(option_nulls); } if (tablespaceName) { const char *quoted_ts = quote_identifier(tablespaceName); appendStringInfo(&ddl, " TABLESPACE %s", quoted_ts); if (quoted_ts != tablespaceName) pfree((void *)quoted_ts); pfree(tablespaceName); } appendStringInfo(&ddl, " AS %s", viewdef); if (relForm->relispopulated) appendStringInfoString(&ddl, " WITH DATA"); else appendStringInfoString(&ddl, " WITH NO DATA"); if (sqlterminator) appendStringInfoChar(&ddl, ';'); /* Очистка */ if (schemaName) pfree(schemaName); if (relName) pfree(relName); if (viewdef) pfree(viewdef); return ddl.data; } Datum get_ddl_materialized_view(char *name, char *schema, char *version, char *model, char *transform) { Oid mvOid = getRelationOid(name, schema); char *ddl = make_materialized_view_statement(mvOid, -1); text *result = cstring_to_text(ddl); elog(NOTICE, "%s", ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } // OPERATOR List * getOperatorOids(char *name, char *schema) { List *oidlist = NIL; CatCList *catlist; int i; Oid namespaceId = InvalidOid; MemoryContext oldcontext = CurrentMemoryContext; if (name == NULL) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("operator name must not be NULL"))); /* Если схема задана, получаем её OID */ if (schema != NULL) { namespaceId = get_namespace_oid(schema, false); } /* Поиск операторов по имени через SysCache */ catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(name)); if (catlist->n_members == 0) { ReleaseSysCacheList(catlist); if (schema != NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator \"%s\" in schema \"%s\" does not exist", name, schema))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator \"%s\" does not exist", name))); } /* Переключаемся в контекст вызова, чтобы список выделялся в нём */ MemoryContextSwitchTo(oldcontext); /* Перебираем найденные операторы */ for (i = 0; i < catlist->n_members; i++) { HeapTuple opertup = &catlist->members[i]->tuple; Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup); Oid operOid = operform->oid; Oid operNamespace = operform->oprnamespace; /* Если схема задана, проверяем соответствие namespace */ if (OidIsValid(namespaceId) && operNamespace != namespaceId) continue; /* Если схема не задана, фильтруем только пользовательские схемы */ if (!OidIsValid(namespaceId)) { /* Исключаем системные схемы: pg_catalog (11), pg_toast (99) */ if (operNamespace == 11 || operNamespace == 99) continue; } oidlist = lappend_oid(oidlist, operOid); } ReleaseSysCacheList(catlist); /* Если ничего не найдено — ошибка */ if (oidlist == NIL) { if (schema != NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator \"%s\" in schema \"%s\" does not exist", name, schema))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator \"%s\" does not exist", name))); } return oidlist; } char *make_operator_statement(Oid operatorOid, const int32 transform_handler) { HeapTuple opTup; Form_pg_operator opForm; StringInfoData ddl; char *opname; char *schemaName; const char *quoted_schema; char *procName = NULL; char *procSchema = NULL; char *leftTypeName = NULL; char *rightTypeName = NULL; char *commutatorName = NULL; char *commutatorSchema = NULL; char *negatorName = NULL; char *negatorSchema = NULL; char *restrictName = NULL; char *restrictSchema = NULL; char *joinName = NULL; char *joinSchema = NULL; bool hashes; bool merges; Oid leftArg; Oid rightArg; Oid procOid; Oid commOid; Oid negOid; Oid restOid; Oid joinOid; bool first = true; bool sqlterminator = std::get(get_ddl_transform_param(transform_handler, "SQLTERMINATOR", ObjectTypeOperator)); opTup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operatorOid)); if (!HeapTupleIsValid(opTup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator with OID %u does not exist", operatorOid))); opForm = (Form_pg_operator) GETSTRUCT(opTup); opname = pstrdup(NameStr(opForm->oprname)); schemaName = get_namespace_name(opForm->oprnamespace); leftArg = opForm->oprleft; rightArg = opForm->oprright; procOid = opForm->oprcode; commOid = opForm->oprcom; negOid = opForm->oprnegate; restOid = opForm->oprrest; joinOid = opForm->oprjoin; hashes = opForm->oprcanhash; merges = opForm->oprcanmerge; quoted_schema = quote_identifier(schemaName); /* PROCEDURE – полное имя функции */ if (OidIsValid(procOid)) { procName = get_func_name(procOid); Oid procNs = get_func_namespace(procOid); if (OidIsValid(procNs)) procSchema = get_namespace_name(procNs); } if (!procName || !procSchema) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("procedure function for operator %u not found", operatorOid))); if (OidIsValid(leftArg)) leftTypeName = format_type_be(leftArg); if (OidIsValid(rightArg)) rightTypeName = format_type_be(rightArg); /* COMMUTATOR */ if (OidIsValid(commOid)) { HeapTuple commTup = SearchSysCache1(OPEROID, ObjectIdGetDatum(commOid)); if (HeapTupleIsValid(commTup)) { Form_pg_operator commForm = (Form_pg_operator) GETSTRUCT(commTup); commutatorName = pstrdup(NameStr(commForm->oprname)); commutatorSchema = get_namespace_name(commForm->oprnamespace); ReleaseSysCache(commTup); } } /* NEGATOR */ if (OidIsValid(negOid)) { HeapTuple negTup = SearchSysCache1(OPEROID, ObjectIdGetDatum(negOid)); if (HeapTupleIsValid(negTup)) { Form_pg_operator negForm = (Form_pg_operator) GETSTRUCT(negTup); negatorName = pstrdup(NameStr(negForm->oprname)); negatorSchema = get_namespace_name(negForm->oprnamespace); ReleaseSysCache(negTup); } } /* RESTRICT */ if (OidIsValid(restOid)) { restrictName = get_func_name(restOid); Oid restNs = get_func_namespace(restOid); if (OidIsValid(restNs)) restrictSchema = get_namespace_name(restNs); } /* JOIN */ if (OidIsValid(joinOid)) { joinName = get_func_name(joinOid); Oid joinNs = get_func_namespace(joinOid); if (OidIsValid(joinNs)) joinSchema = get_namespace_name(joinNs); } ReleaseSysCache(opTup); /* Формируем DDL */ initStringInfo(&ddl); /* Имя оператора выводим без кавычек (синтаксис CREATE OPERATOR не требует экранирования) */ appendStringInfo(&ddl, "CREATE OPERATOR %s.%s (", quoted_schema, opname); appendStringInfo(&ddl, " PROCEDURE = %s.%s", quote_identifier(procSchema), quote_identifier(procName)); first = false; if (leftTypeName) { appendStringInfo(&ddl, "%s LEFTARG = %s", first ? "" : ",", leftTypeName); first = false; } if (rightTypeName) { appendStringInfo(&ddl, "%s RIGHTARG = %s", first ? "" : ",", rightTypeName); first = false; } if (commutatorName && commutatorSchema) { /* Имя оператора-коммутатора также без кавычек */ appendStringInfo(&ddl, "%s COMMUTATOR = %s.%s", first ? "" : ",", quote_identifier(commutatorSchema), commutatorName); first = false; } if (negatorName && negatorSchema) { appendStringInfo(&ddl, "%s NEGATOR = %s.%s", first ? "" : ",", quote_identifier(negatorSchema), negatorName); first = false; } if (restrictName && restrictSchema) { appendStringInfo(&ddl, "%s RESTRICT = %s.%s", first ? "" : ",", quote_identifier(restrictSchema), quote_identifier(restrictName)); first = false; } if (joinName && joinSchema) { appendStringInfo(&ddl, "%s JOIN = %s.%s", first ? "" : ",", quote_identifier(joinSchema), quote_identifier(joinName)); first = false; } if (hashes) { appendStringInfo(&ddl, "%s HASHES", first ? "" : ","); first = false; } if (merges) { appendStringInfo(&ddl, "%s MERGES", first ? "" : ","); first = false; } appendStringInfoChar(&ddl, ')'); if (sqlterminator) appendStringInfoChar(&ddl, ';'); /* Освобождение */ if (schemaName != quoted_schema) pfree((void*)quoted_schema); pfree(opname); pfree(schemaName); if (procName) pfree(procName); if (procSchema) pfree(procSchema); if (leftTypeName) pfree(leftTypeName); if (rightTypeName) pfree(rightTypeName); if (commutatorName) pfree(commutatorName); if (commutatorSchema) pfree(commutatorSchema); if (negatorName) pfree(negatorName); if (negatorSchema) pfree(negatorSchema); if (restrictName) pfree(restrictName); if (restrictSchema) pfree(restrictSchema); if (joinName) pfree(joinName); if (joinSchema) pfree(joinSchema); return ddl.data; } Datum get_ddl_operator(char *name, char *schema, char *version, char *model, char *transform) { text *result; List *oids = getOperatorOids(name, schema); ListCell *lc; StringInfoData resultDdl; initStringInfo(&resultDdl); foreach(lc, oids) { Oid operatorOid = lfirst_oid(lc); char *ddl = make_operator_statement(operatorOid, -1); appendStringInfoString(&resultDdl, ddl); appendStringInfoChar(&resultDdl, '\n'); pfree(ddl); } result = cstring_to_text(resultDdl.data); pfree_all(resultDdl.data); list_free(oids); PG_RETURN_TEXT_P(result); } Datum get_dependent_ddl(FunctionCallInfo fcinfo) { char *ch_object_type = get_string_argument(fcinfo, 0); char *name = get_string_argument(fcinfo, 1); char *schema = get_string_argument(fcinfo, 2); char *version = get_string_argument(fcinfo, 3); char *model = get_string_argument(fcinfo, 4); char *transform = get_string_argument(fcinfo, 5); int object_count = get_numeric_argument_int32(fcinfo, 6); ObjectType object_type = ObjectType::ObjectTypeNull; const char* func_name = "DBMS_METADATA_GET_DEPENDENT_DDL"; // object type check if (setObjectType(ch_object_type, object_type, func_name)) { // it cannot be a heterogeneous object type if (object_type == dbms_metadata::ObjectType::ObjectTypeTableExport || object_type == dbms_metadata::ObjectType::ObjectTypeSchemaExport || object_type == dbms_metadata::ObjectType::ObjectTypeDatabaseExport || object_type == ObjectType::ObjectTypeTransportableExport) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value \"%s\" for parameter OBJECT_TYPE" " in function %s", ch_object_type, func_name))); } } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid input value NULL for parameter OBJECT_TYPE in " "function %s", func_name))); } auto transform_name = TransformationObject::stringToTransformType(std::string(transform)); if (transform_name == std::nullopt) { auto obj_type_name = ObjectTypeToStringView(object_type); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid transform NAME parameter \"%s\" for object type " "\"%s\" in function %s", transform, obj_type_name.data(), func_name))); } else { if(transform_name.value() != TransformType::DDL) { ereport(ERROR, (errmsg("Transform %s not support", transform))); } } switch(object_type){ case ObjectTypeComment: return get_dependent_ddl_comment(name, schema, version, model, transform, object_count); case ObjectTypeIndex: return get_dependent_ddl_index(name, schema, version, model, transform, object_count); default: ereport(ERROR, (errmsg("Поддержка %s не реализована", ch_object_type))); } } // DEPENDENT COMMENT // можно ли для relid создавать комментарий в get_dependet_ddl bool relation_is_dependent_comment(Oid relOid){ /* Получаем информацию о relation из pg_class */ HeapTuple relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(relTup)) elog(ERROR, "cache lookup failed for relation %u", relOid); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(relTup); char relkind = relForm->relkind; ReleaseSysCache(relTup); switch(relkind){ case RELKIND_RELATION: /* обычная таблица */ case RELKIND_PARTITIONED_TABLE: /* секционированная таблица */ case RELKIND_VIEW: case RELKIND_MATVIEW: case RELKIND_INDEX: case RELKIND_PARTITIONED_INDEX: return true; } return false; } void make_relation_comments(Oid tableOid, bool sqlterminator, char **ddl) { if (ddl == NULL || *ddl == NULL) return; char *schemaname = get_namespace_name(get_rel_namespace(tableOid)); char *relname = get_rel_name(tableOid); if (!schemaname || !relname) elog(ERROR, "could not find relation %u", tableOid); /* Получаем информацию о relation из pg_class */ HeapTuple relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(tableOid)); if (!HeapTupleIsValid(relTup)) elog(ERROR, "cache lookup failed for relation %u", tableOid); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(relTup); char relkind = relForm->relkind; Oid reltype = relForm->reltype; ReleaseSysCache(relTup); /* Определяем ключевое слово для COMMENT ON и OID/classoid для комментария relation */ const char *comment_keyword = NULL; Oid comment_oid = tableOid; Oid comment_classoid = RelationRelationId; switch (relkind) { case RELKIND_RELATION: /* обычная таблица */ case RELKIND_PARTITIONED_TABLE: /* секционированная таблица */ comment_keyword = "TABLE"; break; case RELKIND_VIEW: comment_keyword = "VIEW"; break; case RELKIND_MATVIEW: comment_keyword = "MATERIALIZED VIEW"; break; case RELKIND_FOREIGN_TABLE: comment_keyword = "FOREIGN TABLE"; break; case RELKIND_SEQUENCE: comment_keyword = "SEQUENCE"; break; case RELKIND_INDEX: case RELKIND_PARTITIONED_INDEX: comment_keyword = "INDEX"; break; case RELKIND_COMPOSITE_TYPE: comment_keyword = "TYPE"; comment_oid = reltype; comment_classoid = TypeRelationId; break; default: /* Для прочих типов relation комментарии не поддерживаются */ pfree(schemaname); pfree(relname); return; } StringInfoData result; initStringInfo(&result); char *full_qualified = quote_qualified_identifier(schemaname, relname); /* 1. Комментарий к relation */ char *relcomment = GetComment(comment_oid, comment_classoid, 0); if (relcomment) { appendStringInfo(&result, "-- %s comments\n", comment_keyword); appendStringInfo(&result, "COMMENT ON %s %s IS %s", comment_keyword, full_qualified, quote_literal_cstr(relcomment)); if (sqlterminator) appendStringInfoChar(&result, ';'); pfree(relcomment); } /* 2. Комментарии к колонкам — только для relation, у которых могут быть колонки */ bool has_columns = (relkind == RELKIND_RELATION || relkind == RELKIND_PARTITIONED_TABLE || relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW || relkind == RELKIND_FOREIGN_TABLE || relkind == RELKIND_COMPOSITE_TYPE); if (has_columns) { Relation rel = relation_open(tableOid, AccessShareLock); TupleDesc tupdesc = RelationGetDescr(rel); int natts = tupdesc->natts; bool first_col_comment = true; for (int i = 0; i < natts; i++) { Form_pg_attribute att = TupleDescAttr(tupdesc, i); if (att->attisdropped || att->attnum <= 0) continue; char *attname = NameStr(att->attname); /* Пропускаем системные скрытые колонки */ if (strcmp(attname, "tableoid") == 0 || strcmp(attname, "cmax") == 0 || strcmp(attname, "xmax") == 0 || strcmp(attname, "cmin") == 0 || strcmp(attname, "xmin") == 0 || strcmp(attname, "ctid") == 0) continue; char *colcomment = GetComment(tableOid, RelationRelationId, att->attnum); if (colcomment) { if (first_col_comment) { appendStringInfo(&result, "\n\n-- Column comments\n"); first_col_comment = false; } char *col_full = psprintf("%s.%s", full_qualified, quote_identifier(attname)); appendStringInfo(&result, "COMMENT ON COLUMN %s IS %s", col_full, quote_literal_cstr(colcomment)); if (sqlterminator) appendStringInfoChar(&result, ';'); appendStringInfoChar(&result, '\n'); pfree(colcomment); pfree(col_full); } } relation_close(rel, AccessShareLock); } /* Добавляем в конец DDL */ size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char *) repalloc(*ddl, new_len); strcat(*ddl, result.data); pfree(full_qualified); pfree(schemaname); pfree(relname); pfree(result.data); } Datum get_dependent_ddl_comment(char *name, char *schema, char *version, char *model, char *transform, int object_count) { text *result; Oid relOid = getRelationOid(name, schema); bool sqlterminator = std::get(get_ddl_transform_param(-1, "SQLTERMINATOR")); if(!relation_is_dependent_comment(relOid)){ elog(ERROR, "no make dependent comment for relation %u", relOid); } char *ddl = (char*)palloc0(1); // empty string make_relation_comments(relOid, sqlterminator, &ddl); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } // DEPENDENT INDEX // можно ли для relid создавать index в get_dependet_ddl bool relation_is_dependent_index(Oid relOid){ /* Получаем информацию о relation из pg_class */ HeapTuple relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(relTup)) elog(ERROR, "cache lookup failed for relation %u", relOid); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(relTup); char relkind = relForm->relkind; ReleaseSysCache(relTup); switch(relkind){ case RELKIND_RELATION: /* обычная таблица */ case RELKIND_PARTITIONED_TABLE: /* секционированная таблица */ case RELKIND_MATVIEW: return true; } return false; } void make_relation_index(Oid relOid, bool sqlterminator, char **ddl) { Relation indexRel; ScanKeyData skey; SysScanDesc scan; HeapTuple indexTuple; StringInfoData result; if (ddl == NULL || *ddl == NULL) return; initStringInfo(&result); /* Открываем pg_index и сканируем по indrelid через индекс */ indexRel = table_open(IndexRelationId, AccessShareLock); ScanKeyInit(&skey, Anum_pg_index_indrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relOid)); scan = systable_beginscan(indexRel, IndexIndrelidIndexId, true, NULL, 1, &skey); while (HeapTupleIsValid(indexTuple = systable_getnext(scan))) { Form_pg_index indexForm = (Form_pg_index) GETSTRUCT(indexTuple); Oid indexOid = indexForm->indexrelid; Datum ddlDatum; char *indexDdl; size_t len; /* Получаем текст CREATE INDEX через системную функцию */ ddlDatum = DirectFunctionCall1(pg_get_indexdef, ObjectIdGetDatum(indexOid)); indexDdl = text_to_cstring(DatumGetTextP(ddlDatum)); len = strlen(indexDdl); if (len > 0) { appendStringInfoString(&result, indexDdl); if (sqlterminator && indexDdl[len - 1] != ';') appendStringInfoChar(&result, ';'); appendStringInfoChar(&result, '\n'); } pfree(indexDdl); } systable_endscan(scan); table_close(indexRel, AccessShareLock); /* Если что-то сгенерировали — дописываем в *ddl */ if (result.len > 0) { size_t new_len = strlen(*ddl) + result.len + 1; *ddl = (char *) repalloc(*ddl, new_len); strcat(*ddl, result.data); } pfree(result.data); } Datum get_dependent_ddl_index(char *name, char *schema, char *version, char *model, char *transform, int object_count) { text *result; Oid relOid = getRelationOid(name, schema); bool sqlterminator = std::get(get_ddl_transform_param(-1, "SQLTERMINATOR")); if(!relation_is_dependent_index(relOid)){ elog(ERROR, "no make dependent index for relation %u", relOid); } char *ddl = (char*)palloc0(1); // empty string make_relation_index(relOid, sqlterminator, &ddl); result = cstring_to_text(ddl); pfree_all(ddl); PG_RETURN_TEXT_P(result); } /* ----------------------------------------------- get_ddl support functions */ /* adding new filter node to filter list in ctxMap structure */ void addFilter(const int32 handle, const FilterName filter_name, const char* filter_value, const OTPName obj_type_path) { Filter* fnode = ctxMap.at(handle)->filters; Filter* new_fnode = nullptr; // search for the end of the list and check if such filter isn't // existing already if (fnode != nullptr) { while (fnode->next != nullptr) { if (fnode->name == filter_name && strcmp(fnode->value, filter_value) == 0) { // skip adding duplicate filter return; } else { fnode = fnode->next; } } // check last one if (fnode->name == filter_name && strcmp(fnode->value, filter_value) == 0) { return; } } // let's allocate new Filter node new_fnode = (Filter*)MemoryContextAlloc(TopMemoryContext, sizeof(Filter)); new_fnode->name = filter_name; new_fnode->value = MemoryContextStrdup(TopMemoryContext, filter_value); new_fnode->obj_type_path = obj_type_path; new_fnode->next = nullptr; // add new filter node to the end of the current filters list if (fnode == nullptr) { ctxMap.at(handle)->filters = new_fnode; } else { fnode->next = new_fnode; } // char *form_text = filter_condition_name(ctxMap.at(handle)->filters, "d.name", OTPTable); // elog(NOTICE, "FILTER NAME: %s", form_text ? form_text : "NULL"); // if(form_text) // pfree(form_text); // form_text = filter_condition_name_expr(ctxMap.at(handle)->filters, "d.name", OTPTable); // elog(NOTICE, "FILTER NAME_EXPR: %s", form_text ? form_text : "NULL"); // if(form_text) // pfree(form_text); // form_text = filter_condition_exclude_name_expr(ctxMap.at(handle)->filters, "d.name", OTPTable); // elog(NOTICE, "FILTER EXCLUDE_NAME_EXPR: %s", form_text ? form_text : "NULL"); // if(form_text) // pfree(form_text); // filter_diapason_t diap; // get_filter_diapason(ctxMap.at(handle)->filters, &diap); // elog(NOTICE, "TABLE %s", type_in_filter_diapason(OTPTable, &diap) ? "in DIAPASON" : "before diappason"); } /* adding new attribute (or "parse item") node to attribute list in ctxMap structure */ void addParseAttribute(const int32 handle, const AttrName attr_name, const ObjectType obj_type) { Attribute* anode = ctxMap.at(handle)->attributes; Attribute* new_anode = nullptr; // search for the end of the list and check if such attribute isn't // existing already if (anode != nullptr) { while (anode->next != nullptr) { if (anode->name == attr_name && anode->obj_type == obj_type) { // skip adding duplicate attribute return; } else { anode = anode->next; } } // check last one if (anode->name == attr_name && anode->obj_type == obj_type) { return; } } // let's allocate new Attribute node new_anode = (Attribute*)MemoryContextAlloc(TopMemoryContext, sizeof(Attribute)); new_anode->name = attr_name; new_anode->obj_type = obj_type; new_anode->next = nullptr; // add new attribute node to the end of the current attribute list if (anode == nullptr) { ctxMap.at(handle)->attributes = new_anode; } else { anode->next = new_anode; } } // adding new transform node to transform list in ctxMap structure void addTransform(const int32 handle, const int32 transform_handle, const ObjectType obj_type) { Transform* tnode = ctxMap.at(handle)->transforms; Transform* new_tnode = nullptr; // search for the end of the list if (tnode != nullptr) { while (tnode->next != nullptr) { tnode = tnode->next; } } // let's allocate new Filter node new_tnode = (Transform*)MemoryContextAlloc(TopMemoryContext, sizeof(Transform)); new_tnode->transform_id = transform_handle; new_tnode->obj_type = obj_type; new_tnode->next = nullptr; // add new filter node to the end of the current filters list if (tnode == nullptr) { ctxMap.at(handle)->transforms = new_tnode; } else { tnode->next = new_tnode; } } // free all memory from Filter list void destroyFiltersByHandle(const int32 handle) { Filter* current_filter = ctxMap.at(handle)->filters; if (current_filter != nullptr) { Filter* next_filter = nullptr; do { next_filter = current_filter->next; pfree(current_filter->value); pfree(current_filter); current_filter = next_filter; } while (next_filter != nullptr); ctxMap.at(handle)->filters = nullptr; } } // free all memory from Attributes list void destroyAttributesByHandle(const int32 handle) { Attribute* current_attr = ctxMap.at(handle)->attributes; if (current_attr != nullptr) { Attribute* next_attr = nullptr; do { next_attr = current_attr->next; pfree(current_attr); current_attr = next_attr; } while (next_attr != nullptr); ctxMap.at(handle)->attributes = nullptr; } } // free all memory from Transform list (including ctxTransformMap elements) void destroyTransformsByHandle(const int32 handle) { Transform* current_transform = ctxMap.at(handle)->transforms; if (current_transform != nullptr) { Transform* next_transform = nullptr; do { // erase element by this ID from ctxTransformMap auto it = ctxTransformMap.find(current_transform->transform_id); ctxTransformMap.erase(it); next_transform = current_transform->next; pfree(current_transform); current_transform = next_transform; } while (next_transform != nullptr); ctxMap.at(handle)->filters = nullptr; } } int32 checkCtxHandle(const Numeric num_handle, const char* func_name) { int32 handle = 0; bool inv_handle = false; if(num_handle) { handle = DatumGetInt32(DirectFunctionCall1(numeric_int4, NumericGetDatum(num_handle))); } else { inv_handle = true; } // checking if handle is valid and corresponds to existing slot if (inv_handle || handle < 0 || ctxMap.count(handle) == 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid input value %d for parameter HANDLE in " "function %s", handle, func_name))); } return handle; } int32 checkTransformHandle(const Numeric num_handle, const char* func_name) { int32 handle = 0; bool inv_handle = false; if(num_handle) { handle = DatumGetInt32(DirectFunctionCall1(numeric_int4, NumericGetDatum(num_handle))); } else { inv_handle = true; } // checking if handle is valid and corresponds to existing slot if (inv_handle || ctxTransformMap.count(handle) == 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid input value %d for parameter HANDLE in " "function %s", handle, func_name))); } return handle; } void checkFetchStatus(const int32 handle, const char* func_name) { // handle should be a real valid value if (ctxMap.at(handle)->been_fetched) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("After the first call to FETCH_xxx is made, no " "further calls to %s for the current OPEN context are " "permitted", func_name))); } } bool setObjectType(const char* raw_objtype, ObjectType& obj_type, const char* func_name) { if (raw_objtype) { // check if this is a valid object type auto opt_obj_type = stringToObjectType(std::string(raw_objtype)); if (opt_obj_type == std::nullopt) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid input value %s for parameter OBJECT_TYPE in " "function %s", raw_objtype, func_name))); } else { obj_type = opt_obj_type.value(); return true; } } else { return false; } } bool getObjectTypePath(const char* raw_otp, OTPName& obj_type_path, const ObjectType obj_type, const FilterName filter, const char* func_name) { if (raw_otp) { // check if this is a valid object type path auto otp = dbms_metadata::stringToObjectTypePath(std::string(raw_otp)); if (otp == std::nullopt) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid input value %s for parameter OBJECT_TYPE_PATH" " in function %s", raw_otp, func_name))); } else { obj_type_path = otp.value(); // check if object type path is consistent with handle object type if (!filterObjectTypePathCheck(obj_type, obj_type_path, filter)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("parameter OBJECT_TYPE_PATH value \"%s\" in " "function %s is inconsistent with HANDLE", raw_otp, func_name))); } return true; } } else { return false; } } TransformationObject::ParamValue get_ddl_transform_param(const int32 transform_handler, const char* transform_param, const int obj_type) { std::string transformation(transform_param); // internal error if transform_param is something else if (!isValidDDLTransform(transformation)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Impossible transform parameter has been used"))); } if (transform_handler != -1) { auto it_transform_obj = ctxTransformMap.find(transform_handler); if (it_transform_obj == ctxTransformMap.end()) { // bad bad bad internal error ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Can't find attached transform object"))); } // search for specific value auto tp = it_transform_obj->second.getParam(transformation, obj_type); if (tp.has_value()) { return tp.value(); } /* if we have a transformation with heterogenous object type and object type passed to this function is consistent with that heterogenous object then let's return transform value */ ObjectType transform_OT = static_cast(it_transform_obj->second.getObjType()); if (transform_OT == ObjectType::ObjectTypeDatabaseExport || transform_OT == ObjectType::ObjectTypeSchemaExport || transform_OT == ObjectType::ObjectTypeTableExport || transform_OT == ObjectType::ObjectTypeTransportableExport) { // parameter can be set with heterogenous object type tp = it_transform_obj->second.getParam(transformation, transform_OT); if (tp.has_value() && isOTConsistentWithHeterOT(static_cast(obj_type), transform_OT)) { return tp.value(); } } } /* If no specific transformations has been set then we go after session/default value. If session_transform hasn't been modified (by user) it still keeps all default values */ auto tp = sessionTransform.getParam(transformation, obj_type); if (!tp.has_value()) { // we shouldn't be here throw std::invalid_argument("Error: no default value for specified " "transformation " + transformation + " and object type"); } return tp.value(); } } // namespace dbms_metadata extern "C" { } // extern "C"