#ifndef DBMS_METADATA_COMMON_INTERNAL_HPP #define DBMS_METADATA_COMMON_INTERNAL_HPP #include #include #include #include #include #include #include #include #include #include "transformation_object.hpp" extern "C" { #include "postgres.h" #include "fmgr.h" #include "utils/builtins.h" #include "utils/numeric.h" #include "utils/date.h" #include "utils/timestamp.h" #include "utils/array.h" #include "catalog/pg_type.h" #include "executor/spi.h" #include "mb/pg_wchar.h" #include "lib/stringinfo.h" } // extern "C" namespace dbms_metadata{ enum ObjectType { ObjectTypeNull, ObjectTypeAqQueue, ObjectTypeAqQueueTable, ObjectTypeAqTransform, ObjectTypeAssociation, ObjectTypeAudit, ObjectTypeAuditObj, ObjectTypeCluster, ObjectTypeComment, ObjectTypeConstraint, ObjectTypeContext, ObjectTypeDatabaseExport, ObjectTypeDbLink, ObjectTypeDefaultRole, ObjectTypeDimension, ObjectTypeDirectory, ObjectTypeFgaPolicy, ObjectTypeFunction, ObjectTypeIndexStatistics, ObjectTypeIndex, ObjectTypeIndextype, ObjectTypeJavaSource, ObjectTypeJob, ObjectTypeLibrary, ObjectTypeMaterializedView, ObjectTypeMaterializedViewLog, ObjectTypeObjectGrant, ObjectTypeOnUserGrant, ObjectTypeOperator, ObjectTypePackage, ObjectTypePackageSpec, ObjectTypePackageBody, ObjectTypeProcedure, ObjectTypeProfile, ObjectTypeProxy, ObjectTypeRefConstraint, ObjectTypeRefreshGroup, ObjectTypeResourceCost, ObjectTypeRlsContext, ObjectTypeRlsGroup, ObjectTypeRlsPolicy, ObjectTypeRmgrConsumerGroup, ObjectTypeRmgrIntitialConsumerGroup, ObjectTypeRmgrPlan, ObjectTypeRmgrPlanDirective, ObjectTypeRole, ObjectTypeRoleGrant, ObjectTypeRollbackSegment, ObjectTypeSchemaExport, ObjectTypeSequence, ObjectTypeSynonym, ObjectTypeSystemGrant, ObjectTypeTable, ObjectTypeTableData, ObjectTypeTableExport, ObjectTypeTableStatistics, ObjectTypeTablespace, ObjectTypeTablespaceQuota, ObjectTypeTransportableExport, ObjectTypeTrigger, ObjectTypeTrustedDbLink, ObjectTypeType, ObjectTypeTypeSpec, ObjectTypeTypeBody, ObjectTypeUser, ObjectTypeView, ObjectTypeXmlschema, ObjectTypeXsUser, ObjectTypeXsRole, ObjectTypeXsRoleset, ObjectTypeXsRoleGrant, ObjectTypeXsSecurityClass, ObjectTypeXsDataSecurity, ObjectTypeXsAcl, ObjectTypeXsAclParam, ObjectTypeXsNamespace }; // Object Type Path Names enum OTPName { OTPNULL, // default null name OTPAssociation, OTPAudit, OTPAuditObj, OTPCluster, OTPComment, OTPConstraint, OTPContext, OTPDBLink, OTPDefaultRole, OTPDimension, OTPDirectory, OTPFGAPolicy, OTPFunction, OTPGrant, OTPIndex, OTPIndexType, OTPJavaSource, OTPJob, OTPLibrary, OTPMaterializedView, OTPMaterializedViewLog, OTPObjectGrant, OTPOperator, OTPPackage, OTPPackageBody, OTPPackageSpec, OTPPasswordHistory, OTPPasswordVerifyFunction, OTPProcedure, OTPProfile, OTPProxy, OTPRefConstraint, OTPRefreshGroup, OTPResourceCost, OTPRLSContext, OTPRLSGroup, OTPRLSPolicy, OTPRole, OTPRoleGrant, OTPRollbackSegment, OTPSchema, OTPSequence, OTPStatistics, OTPSynonym, OTPSystemGrant, OTPTable, OTPTableData, OTPTablespace, OTPTablespaceQuota, OTPTrigger, OTPTrustedDBLink, OTPType, OTPTypeBody, OTPTypeSpec, OTPUser, OTPView, OTPXsAcl, OTPXsDataSecurity, OTPXsNamespace, OTPXsUser, OTPXsRole, OTPXsSecurityClass }; // Proper filter names enum FilterName { FNNull, // default null name FNBaseObjectName, FNBaseObjectNameExpr, FNBaseObjectSchema, FNBaseObjectSchemaExpr, FNBaseObjectTablespace, FNBaseObjectTablespaceExpr, FNBaseObjectType, FNBaseObjectTypeExpr, FNBeginAfter, FNBeginWith, FNBody, FNCustomFilter, FNEdition, FNEndBefore, FNEndWith, FNExcludeBaseObjectNameExpr, FNExcludeGranteeExpr, FNExcludeNameExpr, FNExcludePathExpr, FNExcludeTables, FNGrantee, FNGranteeExpr, FNGrantor, FNIncludePathExpr, FNIncludeUser, FNLongname, FNLongnameExpr, FNName, FNNameExpr, FNPrimary, FNPrivname, FNSchema, FNSchemaExpr, FNSecondary, FNSpecification, FNSystemGenerated, FNTablespace, FNTablespaceExpr }; // Attribute Names (used in set_parse_item()) enum AttrName { ANNull, ANAlterable, ANBaseObjectName, ANBaseObjectType, ANBaseObjectSchema, ANClauseType, ANColumnAttribute, ANConstraintState, ANConstraintType, ANDelTombstone, ANEnable, ANGrantee, ANGrantor, ANLongname, ANName, ANObjectType, ANSchema, ANSystemGenerated, ANTablespace, ANVerb, ANXPath, }; // transform parameter names enum class TransformParam { 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, }; std::string_view ObjectTypeToStringView(ObjectType obj_type); std::optional stringToObjectType(const std::string& str); // Вспомогательная функция для одиночного указателя template static inline void pfree_if_not_null(T*& ptr) { if (ptr != NULL) { pfree(ptr); ptr = NULL; // предотвращает случайное повторное освобождение } } // Вариативный шаблон для произвольного числа аргументов (по ссылке) template static void pfree_all(Args&... args) { (pfree_if_not_null(args), ...); } std::optional stringToObjectTypePath(const std::string& str); std::optional stringToFilterName(const std::string& str); std::optional stringToAttrName(const std::string& str); std::optional stringToParamName(const std::string& str); std::string_view ParamNameToStringView(TransformParam param_name); bool isOTPConsistentWithHeterOT(const ObjectType heterogen, const OTPName path); bool isOTConsistentWithHeterOT(const ObjectType obj_type, const ObjectType hetero) noexcept; bool isFNConsistentWithOT(const ObjectType obj_type, const FilterName filter) noexcept; bool isAttrNameConsistentWithOT(const ObjectType obj_type, const AttrName attr) noexcept; bool isOTConsistentWithTransform(const TransformType transform_type, const ObjectType obj_type) noexcept; bool isRemapParamNameConsistentWithOT(const TransformType transform_type, const ObjectType obj_type, const TransformParam transform_param) noexcept; typedef struct Filter { FilterName name; // let's define value type by filter name char* value; // Например, "HR" OTPName obj_type_path; Filter *next; } Filter; typedef struct Attribute { AttrName name; ObjectType obj_type; Attribute *next; } Attribute; typedef struct Transform { int32 transform_id; ObjectType obj_type; Transform *next; } Transform; // Supporting structure for fetch_ddl heterogeneous type support: // pairs an OID with its originating simple object type. typedef struct FetchOidEntry { Oid oid; ObjectType type; } FetchOidEntry; // Основная структура контекста typedef struct MetadataContext { // 1. Основные параметры, заданные при OPEN ObjectType object_type; char* version; // Например, "COMPATIBLE" char* model; // Всегда "ORACLE" в оригинале, у нас всегда "POSTGRESQL" char* network_link; // 2. Состояние: динамически добавляемые фильтры и трансформы Filter *filters; Attribute *attributes; Transform *transforms; // 3. Управление выборкой size_t fetch_count = 100; // Количество объектов за один FETCH (SET_COUNT) // 3a. Состояние курсора FETCH_DDL: список объектов-кандидатов материализуется // при первом вызове fetch_ddl, последующие вызовы возвращают следующие порции // (размер порции -- fetch_count). fetch_entries выделяется в TopMemoryContext. FetchOidEntry *fetch_entries; // список (OID, тип)-кандидатов (NULL до первого fetch) size_t fetch_entries_count; // длина списка size_t fetch_pos; // индекс следующего объекта для выдачи // 4. Other OTPName object_type_path; bool been_fetched = false; // needs to be set to TRUE by fetch_xxx funcs TODO } MetadataContext; // single row result of fetch_ddl (Oracle sys.ku$_ddl analogue) typedef struct KuDdlRow { char *ddltext; // DDL text (palloc; use pfree) // parseItems parse_items; char *ddlverb; // DDL verb like "CREATE" char *objtype; // Object type like "TABLE" char *objname; char *objschema; int64 objnum; // object number (using OID/relid) char *is_drop; // "YES"/"NO" } KuDdlRow; Datum open(FunctionCallInfo fcinfo); Datum close(FunctionCallInfo fcinfo); Datum fetch_ddl(FunctionCallInfo fcinfo, const int32 handle); Datum get_ddl(FunctionCallInfo fcinfo); Datum get_ddl_table(char *name, char *schema, char *version, char *model, char *transform); char *build_table_ddl_text(Oid tableOid, char *tableName, char *schemaName); Datum get_ddl_view(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_sequence(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_constraint(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_ref_constraint(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_index(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_trigger(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_type(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_function(char *name, char *schema, char *version, char *model, char *transform, bool is_func = true); Datum get_ddl_rlspolicy(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_comment(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_role(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_user(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_tablespace(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_materialized_view(char *name, char *schema, char *version, char *model, char *transform); Datum get_ddl_operator(char *name, char *schema, char *version, char *model, char *transform); // get_dependent_ddl Datum get_dependent_ddl(FunctionCallInfo fcinfo); Datum get_dependent_ddl_comment(char *name, char *schema, char *version, char *model, char *transform, int object_count); Datum get_dependent_ddl_index(char *name, char *schema, char *version, char *model, char *transform, int object_count); TransformationObject* transformForHandle(int32 hndl); Datum set_transform_param_ovr1(FunctionCallInfo fcinfo); Datum set_transform_param_ovr2(FunctionCallInfo fcinfo); Datum set_transform_param_ovr3(FunctionCallInfo fcinfo); Datum setFilter(Numeric& num_handle, const char* ch_name, const char* filter_value, const char* ch_otp); char * get_string_argument(FunctionCallInfo fcinfo, int argnum); int32 get_numeric_argument_int32(FunctionCallInfo fcinfo, int argnum); int32 AddTransformMapRecord(const TransformType type, const int32_t handle, const char* user_file, const int encoding, const ObjectType obj_type); ObjectType getObjectTypeByHandle(const int32 handle); void setFetchCountByHandle(const int32 handle, const int32 value); void setOTPByHandle(const int32 handle, const OTPName obj_type_path); void addFilter(const int32 handle, const FilterName filter_name, const char* filter_value, const OTPName obj_type_path); void addParseAttribute(const int32 handle, const AttrName attr_name, const ObjectType obj_type); void addTransform(const int32 handle, const int32 transform_handle, const ObjectType obj_type); void destroyFiltersByHandle(const int32 handle); void destroyAttributesByHandle(const int32 handle); void destroyTransformsByHandle(const int32 handle); int32 checkCtxHandle(const Numeric num_handle, const char* func_name); int32 checkTransformHandle(const Numeric num_handle, const char* func_name); void checkFetchStatus(const int32 handle, const char* func_name); bool setObjectType(const char* raw_objtype, ObjectType& obj_type, const char* func_name); bool getObjectTypePath(const char* raw_otp, OTPName& obj_type_path, const ObjectType obj_type, const FilterName filter, const char* func_name); }// namespace dbms_metadata #endif // DBMS_METADATA_COMMON_INTERNAL_HPP