Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#ifndef DBMS_METADATA_COMMON_INTERNAL_HPP
#define DBMS_METADATA_COMMON_INTERNAL_HPP
 
#include <string>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>
#include <map>
#include <unordered_map>
#include <set>
#include <optional>
#include <string_view>
#include <vector>
#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<ObjectType> stringToObjectType(const std::string& str);
 
// Вспомогательная функция для одиночного указателя
template<typename T>
static inline void pfree_if_not_null(T*& ptr) {
    if (ptr != NULL) {
        pfree(ptr);
        ptr = NULL;  // предотвращает случайное повторное освобождение
    }
}
 
// Вариативный шаблон для произвольного числа аргументов (по ссылке)
template<typename... Args>
static void pfree_all(Args&... args) {
    (pfree_if_not_null(args), ...);
}
 
std::optional<OTPName> stringToObjectTypePath(const std::string& str);
std::optional<FilterName> stringToFilterName(const std::string& str);
std::optional<AttrName> stringToAttrName(const std::string& str);
std::optional<TransformParam> 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