Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-06-19 0cfc87bd32822e5ba22d8c2b1a26fa60f63ad7fa
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
#include "dbms_json_schema.hpp"
 
extern "C"
{
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/fmgroids.h"
#include "utils/jsonb.h"
#include "funcapi.h"
} // extern "C"
 
#include "../nlohmann/json-schema.hpp"
 
#include <algorithm>
#include <exception>
#include <memory>
#include <set>
#include <string>
#include <cstring>
#include <vector>
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_json_schema_is_schema_valid);
PG_FUNCTION_INFO_V1(dbms_json_schema_is_schema_valid2);
PG_FUNCTION_INFO_V1(dbms_json_schema_is_valid);
PG_FUNCTION_INFO_V1(dbms_json_schema_validate_report);
PG_FUNCTION_INFO_V1(dbms_json_schema_get_version);
}
 
#define RUDB_DBMS_JSON_SCHEMA_VERSION "1.0.0"
#define DBMS_JSON_SCHEMA_VALID 1
#define DBMS_JSON_SCHEMA_INVALID 0
#define DBMS_JSON_SCHEMA_RAISE_NONE 0
#define DBMS_JSON_SCHEMA_RAISE_ERROR 1
 
namespace DbmsJsonSchema
{
using JsonDocument = nlohmann::json;
using JsonValidator = nlohmann::json_schema::json_validator;
 
struct ValidationIssue
{
    std::string schemaPath_;
    std::string instancePath_;
    std::string code_;
    std::string error_;
};
 
struct ValidationResult
{
    bool schemaValid_{false};
    bool dataValid_{false};
    JsonDocument errorsReport_;
    std::string reportText_;
};
 
class CollectingErrorHandler : public nlohmann::json_schema::error_handler
{
public:
    explicit CollectingErrorHandler(const JsonDocument *schema_document)
        : schemaDocument_(schema_document)
    {
    }
 
    std::vector<ValidationIssue> issues_;
 
    void error(const nlohmann::json::json_pointer &ptr,
               const JsonDocument &instance,
               const std::string &message) override
    {
        issues_.push_back(buildIssue(ptr, schemaDocument_, instance, message));
    }
 
private:
    const JsonDocument *schemaDocument_{nullptr};
 
    static bool
    isnumerictoken(const std::string &token)
    {
        return !token.empty() &&
               std::all_of(token.begin(), token.end(), [](unsigned char ch) { return std::isdigit(ch) != 0; });
    }
 
    static std::vector<std::string>
    splitpointertokens(const nlohmann::json::json_pointer &ptr)
    {
        std::vector<std::string> tokens;
        std::string pointerString = ptr.to_string();
 
        if (pointerString.empty()) {
            return tokens;
        }
 
        std::size_t startPos = 1;
 
        while (startPos <= pointerString.size()) {
            std::size_t slashPos = pointerString.find('/', startPos);
            std::string token = pointerString.substr(startPos, slashPos - startPos);
 
            std::size_t replacePos = 0;
            while ((replacePos = token.find("~1", replacePos)) != std::string::npos) {
                token.replace(replacePos, 2, "/");
                replacePos += 1;
            }
 
            replacePos = 0;
            while ((replacePos = token.find("~0", replacePos)) != std::string::npos) {
                token.replace(replacePos, 2, "~");
                replacePos += 1;
            }
 
            tokens.push_back(token);
 
            if (slashPos == std::string::npos) {
                break;
            }
 
            startPos = slashPos + 1;
        }
 
        return tokens;
    }
 
    static std::string
    buildpropertyschemapath(const std::vector<std::string> &tokens,
                            bool appendType,
                            bool parentOnly)
    {
        std::string schemaPath = "$";
        std::size_t limit = tokens.size();
 
        if (parentOnly && limit > 0) {
            limit -= 1;
        }
 
        for (std::size_t index = 0; index < limit; ++index) {
            if (isnumerictoken(tokens[index])) {
                schemaPath += ".items";
            } else {
                schemaPath += ".properties." + tokens[index];
            }
        }
 
        if (parentOnly) {
            schemaPath += ".properties";
        } else if (appendType) {
            schemaPath += ".type";
        }
 
        return schemaPath;
    }
 
    static std::string
    jsonpointertostring(const nlohmann::json::json_pointer &ptr)
    {
        std::vector<std::string> tokens = splitpointertokens(ptr);
        std::string pointerString = "$";
 
        for (const std::string &token : tokens) {
            if (isnumerictoken(token)) {
                pointerString += "[" + token + "]";
            } else {
                pointerString += "." + token;
            }
        }
 
        return pointerString;
    }
 
    static std::string
    jsonvaluetypename(const JsonDocument &value)
    {
        switch (value.type()) {
        case JsonDocument::value_t::null:
            return "null";
        case JsonDocument::value_t::object:
            return "object";
        case JsonDocument::value_t::array:
            return "array";
        case JsonDocument::value_t::string:
            return "string";
        case JsonDocument::value_t::boolean:
            return "boolean";
        case JsonDocument::value_t::number_integer:
        case JsonDocument::value_t::number_unsigned:
        case JsonDocument::value_t::number_float:
            return "number";
        case JsonDocument::value_t::binary:
            return "binary";
        case JsonDocument::value_t::discarded:
            return "discarded";
        }
 
        return "unknown";
    }
 
    static std::string
    resolveexpectedtypefromschema(const JsonDocument *schema_document,
                                  const std::vector<std::string> &tokens)
    {
        const JsonDocument *currentNode = schema_document;
 
        if (currentNode == nullptr) {
            return "";
        }
 
        for (const std::string &token : tokens) {
            if (isnumerictoken(token)) {
                if (!currentNode->is_object() || !currentNode->contains("items")) {
                    return "";
                }
 
                currentNode = &(*currentNode)["items"];
            } else {
                if (!currentNode->is_object() || !currentNode->contains("properties")) {
                    return "";
                }
 
                const JsonDocument &propertiesNode = (*currentNode)["properties"];
                if (!propertiesNode.is_object() || !propertiesNode.contains(token)) {
                    return "";
                }
 
                currentNode = &propertiesNode[token];
            }
        }
 
        if (!currentNode->is_object() || !currentNode->contains("type")) {
            return "";
        }
 
        if ((*currentNode)["type"].is_string()) {
            return (*currentNode)["type"].get<std::string>();
        }
 
        return "";
    }
 
    static ValidationIssue
    buildIssue(const nlohmann::json::json_pointer &ptr,
               const JsonDocument *schema_document,
               const JsonDocument &instance,
               const std::string &message)
    {
        ValidationIssue issue;
        std::vector<std::string> tokens = splitpointertokens(ptr);
 
        issue.instancePath_ = jsonpointertostring(ptr);
        issue.schemaPath_ = "$";
 
        if (message.rfind("unexpected instance type", 0) == 0) {
            std::string expectedType = resolveexpectedtypefromschema(schema_document, tokens);
 
            issue.code_ = "JZN-00503";
            issue.schemaPath_ = buildpropertyschemapath(tokens, true, false);
            issue.error_ = "invalid type found, actual: " + jsonvaluetypename(instance) +
                           ", expected: " + (expectedType.empty() ? "unknown" : expectedType);
        } else if (message.rfind("required property '", 0) == 0) {
            issue.code_ = "JZN-00515";
            issue.schemaPath_ = "$.required";
            issue.error_ = message;
        } else if (message.rfind("validation failed for additional property '", 0) == 0) {
            issue.code_ = "JZN-00514";
            issue.error_ = message;
        } else {
            issue.code_ = "JZN-00501";
            issue.error_ = message;
        }
 
        return issue;
    }
};
 
static void
noopFormatCheck(const std::string &format_name, const std::string &format_value)
{
    (void) format_name;
    (void) format_value;
}
 
static void
noopContentCheck(const std::string &content_encoding,
                 const std::string &content_media_type,
                 const JsonDocument &instance_value)
{
    (void) content_encoding;
    (void) content_media_type;
    (void) instance_value;
}
 
static char *
jsonbtocstringcopy(Jsonb *jsonb_value)
{
    char *jsonCString = JsonbToCString(NULL, &jsonb_value->root, VARSIZE(jsonb_value));
 
    if (jsonCString == nullptr)
    {
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID failed to serialize jsonb")));
    }
 
    return jsonCString;
}
 
static JsonDocument
parsejsondocument(const char *json_data)
{
    try {
        return JsonDocument::parse(json_data);
    } catch (const std::exception &ex) {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid JSON input"),
                 errdetail("%s", ex.what())));
    }
 
    return JsonDocument();
}
 
static bool
isschemavaliddocument(const JsonDocument &schemaDocument)
{
    JsonValidator metaValidator(nullptr, noopFormatCheck, noopContentCheck);
    nlohmann::json_schema::basic_error_handler metaErrorHandler;
    JsonValidator validator(nullptr, noopFormatCheck, noopContentCheck);
 
    metaValidator.set_root_schema(nlohmann::json_schema::draft7_schema_builtin);
    metaValidator.validate(schemaDocument, metaErrorHandler);
 
    if (metaErrorHandler) {
        ereport(LOG,
                (errmsg("DBMS_JSON_SCHEMA schema meta-validation"),
                 errdetail("status=invalid")));
        return false;
    }
 
    validator.set_root_schema(schemaDocument);
    return true;
}
 
static JsonDocument
builderrorsreport(const CollectingErrorHandler &errorHandler)
{
    JsonDocument reportDocument = JsonDocument::object();
    JsonDocument issuesArray = JsonDocument::array();
    std::set<std::string> invalidProperties;
 
    reportDocument["valid"] = errorHandler.issues_.empty();
 
    if (!errorHandler.issues_.empty()) {
        JsonDocument rootIssue = JsonDocument::object();
        rootIssue["schemaPath"] = "$";
        rootIssue["instancePath"] = "$";
        rootIssue["code"] = "JZN-00501";
        rootIssue["error"] = "JSON schema validation failed";
        issuesArray.push_back(rootIssue);
    }
 
    for (const ValidationIssue &issue : errorHandler.issues_) {
        if (issue.code_ == "JZN-00503" &&
            issue.instancePath_.rfind("$.", 0) == 0) {
            invalidProperties.insert(issue.instancePath_.substr(2));
        }
    }
 
    for (const std::string &invalidProperty : invalidProperties) {
        JsonDocument propertyIssue = JsonDocument::object();
        propertyIssue["schemaPath"] = "$.properties";
        propertyIssue["instancePath"] = "$";
        propertyIssue["code"] = "JZN-00514";
        propertyIssue["error"] = "invalid properties: ''" + invalidProperty + "''";
        issuesArray.push_back(propertyIssue);
    }
 
    for (const ValidationIssue &issue : errorHandler.issues_) {
        JsonDocument issueDocument = JsonDocument::object();
        issueDocument["schemaPath"] = issue.schemaPath_;
        issueDocument["instancePath"] = issue.instancePath_;
        issueDocument["code"] = issue.code_;
        issueDocument["error"] = issue.error_;
        issuesArray.push_back(issueDocument);
    }
 
    reportDocument["errors"] = issuesArray;
 
    return reportDocument;
}
 
static std::string
jsonquotestring(const std::string &value)
{
    return JsonDocument(value).dump();
}
 
static std::string
serializereporttext(const CollectingErrorHandler &errorHandler)
{
    std::string reportText = "{\"valid\":";
    std::set<std::string> invalidProperties;
 
    reportText += errorHandler.issues_.empty() ? "true" : "false";
    reportText += ",\"errors\":[";
 
    if (!errorHandler.issues_.empty()) {
        reportText += "{\"schemaPath\":\"$\",\"instancePath\":\"$\",\"code\":\"JZN-00501\",\"error\":\"JSON schema validation failed\"}";
    }
 
    for (const ValidationIssue &issue : errorHandler.issues_) {
        if (issue.code_ == "JZN-00503" &&
            issue.instancePath_.rfind("$.", 0) == 0) {
            invalidProperties.insert(issue.instancePath_.substr(2));
        }
    }
 
    for (const std::string &invalidProperty : invalidProperties) {
        if (reportText.back() != '[') {
            reportText += ",";
        }
 
        reportText += "{\"schemaPath\":\"$.properties\",\"instancePath\":\"$\",\"code\":\"JZN-00514\",\"error\":";
        reportText += jsonquotestring("invalid properties:\n'" + invalidProperty + "'");
        reportText += "}";
    }
 
    for (const ValidationIssue &issue : errorHandler.issues_) {
        if (reportText.back() != '[') {
            reportText += ",";
        }
 
        reportText += "{\"schemaPath\":";
        reportText += jsonquotestring(issue.schemaPath_);
        reportText += ",\"instancePath\":";
        reportText += jsonquotestring(issue.instancePath_);
        reportText += ",\"code\":";
        reportText += jsonquotestring(issue.code_);
        reportText += ",\"error\":";
        reportText += jsonquotestring(issue.error_);
        reportText += "}";
    }
 
    reportText += "]}";
    return reportText;
}
 
static ValidationResult
validatejsondocument(const JsonDocument &dataDocument,
                     const JsonDocument &schemaDocument)
{
    ValidationResult result;
    JsonValidator validator(nullptr, noopFormatCheck, noopContentCheck);
    CollectingErrorHandler errorHandler(&schemaDocument);
 
    result.schemaValid_ = isschemavaliddocument(schemaDocument);
 
    if (!result.schemaValid_) {
        result.dataValid_ = false;
        result.errorsReport_ = JsonDocument::object({
            {"valid", false},
            {"errors", JsonDocument::array()}
        });
        return result;
    }
 
    validator.set_root_schema(schemaDocument);
    validator.validate(dataDocument, errorHandler);
 
    result.dataValid_ = errorHandler.issues_.empty();
    result.errorsReport_ = builderrorsreport(errorHandler);
    result.reportText_ = serializereporttext(errorHandler);
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA validation result"),
             errdetail("schema_valid=%s, data_valid=%s, issues=%zu",
                       result.schemaValid_ ? "true" : "false",
                       result.dataValid_ ? "true" : "false",
                       errorHandler.issues_.size())));
 
    return result;
}
 
static ValidationResult
validatecstringinput(const char *json_data,
                     const char *json_schema)
{
    JsonDocument dataDocument = parsejsondocument(json_data);
    JsonDocument schemaDocument = parsejsondocument(json_schema);
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA validation text input"),
             errdetail("json_length=%zu, schema_length=%zu",
                       strlen(json_data),
                       strlen(json_schema))));
 
    return validatejsondocument(dataDocument, schemaDocument);
}
 
static Jsonb *
jsondocumenttojsonb(const JsonDocument &document)
{
    std::string jsonText = document.dump();
    Datum jsonbDatum = DirectFunctionCall1(jsonb_in, CStringGetDatum(jsonText.c_str()));
 
    return DatumGetJsonbP(jsonbDatum);
}
 
static text *
jsondocumenttotext(const JsonDocument &document)
{
    return cstring_to_text(document.dump(-1, ' ', false, JsonDocument::error_handler_t::strict).c_str());
}
 
static bool
isschemavalidinternal(Jsonb *json_schema)
{
    char *jsonCString = jsonbtocstringcopy(json_schema);
    JsonDocument schemaDocument;
    bool resultValue = false;
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID input"),
             errdetail("schema_length=%zu", strlen(jsonCString))));
 
    schemaDocument = parsejsondocument(jsonCString);
    resultValue = isschemavaliddocument(schemaDocument);
 
    if (!resultValue) {
        ereport(LOG,
                (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID meta-schema check"),
                 errdetail("status=invalid")));
    } else {
        ereport(LOG,
                (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID result"),
                 errdetail("status=valid")));
    }
 
    if (jsonCString != nullptr) {
        pfree(jsonCString);
    }
 
    return resultValue;
}
 
static ValidationResult
isvalidinternal(Jsonb *json_data,
                Jsonb *json_schema)
{
    char *dataCString = jsonbtocstringcopy(json_data);
    char *schemaCString = jsonbtocstringcopy(json_schema);
    JsonDocument dataDocument;
    JsonDocument schemaDocument;
    ValidationResult validationResult;
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.IS_VALID input"),
             errdetail("json_length=%zu, schema_length=%zu",
                       strlen(dataCString),
                       strlen(schemaCString))));
 
    dataDocument = parsejsondocument(dataCString);
    schemaDocument = parsejsondocument(schemaCString);
    validationResult = validatejsondocument(dataDocument, schemaDocument);
 
    if (dataCString != nullptr) {
        pfree(dataCString);
    }
 
    if (schemaCString != nullptr) {
        pfree(schemaCString);
    }
 
    return validationResult;
}
} // namespace DbmsJsonSchema
 
/*
 * @qdb_func: dbms_json_schema_is_schema_valid(jsonb)
 * @ora_func: DBMS_JSON_SCHEMA.IS_SCHEMA_VALID(JSON)
 */
Datum
dbms_json_schema_is_schema_valid(PG_FUNCTION_ARGS)
{
    Jsonb *jsonSchema = nullptr;
    bool isValid = false;
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID call"),
             errdetail("nargs=%d, arg0_is_null=%s",
                       PG_NARGS(),
                       PG_ARGISNULL(0) ? "true" : "false")));
 
    if (PG_ARGISNULL(0)) {
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                 errmsg("ORA-64403: input cannot be NULL")));
    }
 
    jsonSchema = PG_GETARG_JSONB_P_COPY(0);
    isValid = DbmsJsonSchema::isschemavalidinternal(jsonSchema);
 
    if (jsonSchema != nullptr) {
        pfree(jsonSchema);
    }
 
    PG_RETURN_INT32(isValid ? DBMS_JSON_SCHEMA_VALID : DBMS_JSON_SCHEMA_INVALID);
}
 
Datum
dbms_json_schema_is_schema_valid2(PG_FUNCTION_ARGS)
{
    int32 serviceArg = 0;
 
    if (PG_NARGS() != 2) {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID2 accepts exactly 2 arguments")));
    }
 
    if (!PG_ARGISNULL(1)) {
        serviceArg = PG_GETARG_INT32(1);
    }
    (void) serviceArg;
 
    {
        LOCAL_FCINFO(fcinfo2, 1);
 
        InitFunctionCallInfoData(*fcinfo2, nullptr, 1, InvalidOid, nullptr, nullptr);
        fcinfo2->args[0].value = PG_GETARG_DATUM(0);
        fcinfo2->args[0].isnull = PG_ARGISNULL(0);
 
        return dbms_json_schema_is_schema_valid(fcinfo2);
    }
}
 
Datum
dbms_json_schema_is_valid(PG_FUNCTION_ARGS)
{
    Jsonb *jsonData = nullptr;
    Jsonb *jsonSchema = nullptr;
    int32 raiseErr = DBMS_JSON_SCHEMA_RAISE_NONE;
    DbmsJsonSchema::ValidationResult validationResult;
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.IS_VALID function call"),
             errdetail("nargs=%d, arg0_is_null=%s, arg1_is_null=%s, arg2_is_null=%s",
                       PG_NARGS(),
                       PG_ARGISNULL(0) ? "true" : "false",
                       PG_ARGISNULL(1) ? "true" : "false",
                       (PG_NARGS() > 2 && PG_ARGISNULL(2)) ? "true" : "false")));
 
    if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) {
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                 errmsg("ORA-64403: input cannot be NULL")));
    }
 
    if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) {
        raiseErr = PG_GETARG_INT32(2);
    }
 
    if (raiseErr != DBMS_JSON_SCHEMA_RAISE_NONE &&
        raiseErr != DBMS_JSON_SCHEMA_RAISE_ERROR) {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("DBMS_JSON_SCHEMA.IS_VALID invalid raise_err"),
                 errdetail("raise_err=%d", raiseErr)));
    }
 
    jsonData = PG_GETARG_JSONB_P_COPY(0);
    jsonSchema = PG_GETARG_JSONB_P_COPY(1);
 
    validationResult = DbmsJsonSchema::isvalidinternal(jsonData, jsonSchema);
 
    if (jsonData != nullptr) {
        pfree(jsonData);
    }
 
    if (jsonSchema != nullptr) {
        pfree(jsonSchema);
    }
 
    if (!validationResult.schemaValid_ &&
        raiseErr == DBMS_JSON_SCHEMA_RAISE_ERROR) {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("JSON schema validation failed"),
                 errdetail("raise_err=RAISE_ERROR requested exception for invalid schema")));
    }
 
    PG_RETURN_INT32(validationResult.dataValid_ ? DBMS_JSON_SCHEMA_VALID
                                                : DBMS_JSON_SCHEMA_INVALID);
}
 
Datum
dbms_json_schema_validate_report(PG_FUNCTION_ARGS)
{
    char *jsonSchemaCString = nullptr;
    Jsonb *jsonDataJsonb = nullptr;
    Jsonb *jsonSchemaJsonb = nullptr;
    char *jsonDataCString = nullptr;
    DbmsJsonSchema::ValidationResult validationResult;
    bool useJsonbInput = false;
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.VALIDATE_REPORT call"),
             errdetail("nargs=%d, arg0_is_null=%s, arg1_is_null=%s",
                       PG_NARGS(),
                       PG_ARGISNULL(0) ? "true" : "false",
                       PG_ARGISNULL(1) ? "true" : "false")));
 
    if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) {
        PG_RETURN_NULL();
    }
 
    useJsonbInput =
        get_fn_expr_argtype(fcinfo->flinfo, 0) == JSONBOID &&
        get_fn_expr_argtype(fcinfo->flinfo, 1) == JSONBOID;
 
    if (useJsonbInput) {
        jsonDataJsonb = PG_GETARG_JSONB_P_COPY(0);
        jsonSchemaJsonb = PG_GETARG_JSONB_P_COPY(1);
        jsonDataCString = DbmsJsonSchema::jsonbtocstringcopy(jsonDataJsonb);
        jsonSchemaCString = DbmsJsonSchema::jsonbtocstringcopy(jsonSchemaJsonb);
    } else {
        text *jsonDataText = PG_GETARG_TEXT_PP(0);
        text *jsonSchemaText = PG_GETARG_TEXT_PP(1);
        jsonDataCString = text_to_cstring(jsonDataText);
        jsonSchemaCString = text_to_cstring(jsonSchemaText);
    }
 
    validationResult = DbmsJsonSchema::validatecstringinput(jsonDataCString, jsonSchemaCString);
 
    ereport(LOG,
            (errmsg("DBMS_JSON_SCHEMA.VALIDATE_REPORT result"),
             errdetail("valid=%s",
                       validationResult.dataValid_ ? "true" : "false")));
 
    if (jsonDataCString != nullptr) {
        pfree(jsonDataCString);
    }
 
    if (jsonSchemaCString != nullptr) {
        pfree(jsonSchemaCString);
    }
 
    if (jsonDataJsonb != nullptr) {
        pfree(jsonDataJsonb);
    }
 
    if (jsonSchemaJsonb != nullptr) {
        pfree(jsonSchemaJsonb);
    }
 
    PG_RETURN_TEXT_P(cstring_to_text(validationResult.reportText_.c_str()));
}
 
Datum
dbms_json_schema_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_JSON_SCHEMA_VERSION));
}