#include "dbms_json.hpp"
|
|
extern "C"
|
{
|
#include "access/htup_details.h"
|
#include "catalog/namespace.h"
|
#include "executor/spi.h"
|
#include "funcapi.h"
|
#include "nodes/makefuncs.h"
|
#include "nodes/pg_list.h"
|
#include "port.h"
|
#include "parser/scansup.h"
|
#include "utils/builtins.h"
|
#include "utils/elog.h"
|
#include "utils/jsonb.h"
|
#include "utils/lsyscache.h"
|
#include "utils/numeric.h"
|
#include "utils/regproc.h"
|
#include "utils/varlena.h"
|
}
|
|
#include <cctype>
|
#include <cstring>
|
#include <set>
|
#include <string>
|
#include <vector>
|
|
extern "C"
|
{
|
PG_FUNCTION_INFO_V1(dbms_json_build_dataguide);
|
PG_FUNCTION_INFO_V1(dbms_json_get_index_dataguide);
|
PG_FUNCTION_INFO_V1(dbms_json_get_view_sql);
|
PG_FUNCTION_INFO_V1(dbms_json_add_virtual_columns);
|
PG_FUNCTION_INFO_V1(dbms_json_create_view);
|
PG_FUNCTION_INFO_V1(dbms_json_create_view2);
|
PG_FUNCTION_INFO_V1(dbms_json_drop_virtual_columns);
|
PG_FUNCTION_INFO_V1(dbms_json_json_type_convertible_check);
|
PG_FUNCTION_INFO_V1(dbms_json_rename_column);
|
PG_FUNCTION_INFO_V1(dbms_json_create_view_on_path);
|
}
|
|
#define DBMS_JSON_MV_REFRESH_ON_STATEMENT 1
|
#define DBMS_JSON_TYPE_NULL 1
|
#define DBMS_JSON_TYPE_STRING 2
|
#define DBMS_JSON_TYPE_NUMBER 3
|
#define DBMS_JSON_TYPE_BOOLEAN 4
|
#define DBMS_JSON_TYPE_OBJECT 5
|
#define DBMS_JSON_TYPE_ARRAY 6
|
|
namespace DbmsJson
|
{
|
struct ColumnSpec
|
{
|
std::string jsonFieldName_;
|
std::string columnName_;
|
std::string columnType_;
|
};
|
|
struct GuideEntry
|
{
|
std::string path_;
|
std::string jsonType_;
|
std::string columnName_;
|
std::string columnType_;
|
};
|
|
struct MetadataEntry
|
{
|
Oid relationOid_;
|
std::string jsonColumnName_;
|
std::string path_;
|
std::string jsonType_;
|
std::string preferredName_;
|
};
|
|
static std::vector<MetadataEntry> metadataEntries_;
|
|
static JsonbValue *
|
getobjectfield(JsonbContainer *container, const char *field_name, JsonbValue *value_buffer)
|
{
|
if (container == nullptr || !JsonContainerIsObject(container)) {
|
return nullptr;
|
}
|
|
return getKeyJsonValueFromContainer(container,
|
field_name,
|
strlen(field_name),
|
value_buffer);
|
}
|
|
static std::string
|
jsonbvaluetostring(const JsonbValue *json_value)
|
{
|
char *valueCString = nullptr;
|
std::string resultValue;
|
|
if (json_value == nullptr) {
|
return resultValue;
|
}
|
|
switch (json_value->type) {
|
case jbvString:
|
return std::string(json_value->val.string.val, json_value->val.string.len);
|
case jbvBinary:
|
valueCString = JsonbToCString(nullptr,
|
json_value->val.binary.data,
|
json_value->val.binary.len);
|
resultValue = valueCString == nullptr ? "" : std::string(valueCString);
|
if (valueCString != nullptr) {
|
pfree(valueCString);
|
}
|
return resultValue;
|
default:
|
break;
|
}
|
|
return resultValue;
|
}
|
|
static int32
|
jsonbvaluetoint32(const JsonbValue *json_value, int32 default_value)
|
{
|
if (json_value == nullptr) {
|
return default_value;
|
}
|
|
if (json_value->type != jbvNumeric) {
|
return default_value;
|
}
|
|
return numeric_int4_opt_error(json_value->val.numeric, nullptr);
|
}
|
|
static std::string
|
normalizesqlidentifier(const std::string &identifier_value, bool mixed_case_columns)
|
{
|
std::string normalizedValue = identifier_value;
|
|
if (mixed_case_columns) {
|
return normalizedValue;
|
}
|
|
for (char ¤tChar : normalizedValue) {
|
currentChar = static_cast<char>(pg_tolower(static_cast<unsigned char>(currentChar)));
|
}
|
|
return normalizedValue;
|
}
|
|
static std::string
|
normalizepath(const std::string &path_value)
|
{
|
if (path_value.empty() || path_value == "$") {
|
return "$[*]";
|
}
|
|
if (path_value.size() >= 3 &&
|
path_value.compare(path_value.size() - 3, 3, "[*]") == 0) {
|
return path_value;
|
}
|
|
return path_value + "[*]";
|
}
|
|
static std::string
|
trimrootpath(const std::string &path_value)
|
{
|
if (path_value == "$") {
|
return "";
|
}
|
|
if (path_value.rfind("$.", 0) == 0) {
|
return path_value.substr(2);
|
}
|
|
return path_value;
|
}
|
|
static std::string
|
joinpath(const std::string &base_path, const std::string &field_name)
|
{
|
if (base_path.empty()) {
|
return "$." + field_name;
|
}
|
|
return base_path + "." + field_name;
|
}
|
|
static bool
|
ispathunderroot(const std::string &full_path, const std::string &root_path)
|
{
|
if (root_path == "$" || root_path.empty()) {
|
return true;
|
}
|
|
if (full_path == root_path) {
|
return true;
|
}
|
|
return full_path.rfind(root_path + ".", 0) == 0;
|
}
|
|
static std::string
|
makerelativepath(const std::string &full_path, const std::string &root_path)
|
{
|
std::string rootPrefix = trimrootpath(root_path);
|
std::string fullPrefix = trimrootpath(full_path);
|
|
if (rootPrefix.empty()) {
|
return fullPrefix;
|
}
|
|
if (fullPrefix == rootPrefix) {
|
return "";
|
}
|
|
if (fullPrefix.rfind(rootPrefix + ".", 0) == 0) {
|
return fullPrefix.substr(rootPrefix.size() + 1);
|
}
|
|
return fullPrefix;
|
}
|
|
static std::string
|
buildjsonpathfromrelative(const std::string &relative_path)
|
{
|
if (relative_path.empty()) {
|
return "$";
|
}
|
|
return "$." + relative_path;
|
}
|
|
static std::string
|
buildqualifiedname(const std::string &owner_name, const std::string &object_name)
|
{
|
return std::string(quote_identifier(owner_name.c_str())) + "." +
|
quote_identifier(object_name.c_str());
|
}
|
|
static std::string
|
resolveownername()
|
{
|
List *searchPath = fetch_search_path(false);
|
|
if (searchPath != NIL) {
|
Oid schemaOid = linitial_oid(searchPath);
|
char *schemaName = get_namespace_name(schemaOid);
|
|
if (schemaName != nullptr && strcmp(schemaName, "pg_catalog") != 0) {
|
return std::string(schemaName);
|
}
|
}
|
|
return "public";
|
}
|
|
static std::string
|
normalizeidentifierinput(const std::string &identifier_value)
|
{
|
char *normalizedIdentifier = downcase_identifier(identifier_value.c_str(),
|
identifier_value.length(),
|
false,
|
false);
|
std::string normalizedValue = normalizedIdentifier == nullptr
|
? std::string()
|
: std::string(normalizedIdentifier);
|
|
if (normalizedIdentifier != nullptr) {
|
pfree(normalizedIdentifier);
|
}
|
|
return normalizedValue;
|
}
|
|
static Oid
|
resolvetablerelid(const std::string &table_name)
|
{
|
text *tableNameText = cstring_to_text(table_name.c_str());
|
List *nameList = textToQualifiedNameList(tableNameText);
|
Oid relationOid = InvalidOid;
|
|
if (list_length(nameList) == 1) {
|
char *relationName = pstrdup(table_name.c_str());
|
List *searchPath = fetch_search_path(false);
|
ListCell *searchPathCell;
|
|
foreach(searchPathCell, searchPath) {
|
Oid namespaceOid = lfirst_oid(searchPathCell);
|
|
relationOid = get_relname_relid(relationName, namespaceOid);
|
if (relationOid == InvalidOid) {
|
char *normalizedRelationName = downcase_identifier(relationName,
|
strlen(relationName),
|
false,
|
false);
|
relationOid = get_relname_relid(normalizedRelationName, namespaceOid);
|
pfree(normalizedRelationName);
|
}
|
|
if (relationOid != InvalidOid) {
|
break;
|
}
|
}
|
|
list_free(searchPath);
|
pfree(relationName);
|
} else if (list_length(nameList) == 2) {
|
char *schemaName = pstrdup(strVal(linitial(nameList)));
|
char *relationName = pstrdup(strVal(lsecond(nameList)));
|
Oid namespaceOid = get_namespace_oid(schemaName, true);
|
|
if (namespaceOid == InvalidOid) {
|
char *normalizedSchemaName = downcase_identifier(schemaName,
|
strlen(schemaName),
|
false,
|
false);
|
namespaceOid = get_namespace_oid(normalizedSchemaName, true);
|
pfree(normalizedSchemaName);
|
}
|
|
if (namespaceOid != InvalidOid) {
|
relationOid = get_relname_relid(relationName, namespaceOid);
|
|
if (relationOid == InvalidOid) {
|
char *normalizedRelationName = downcase_identifier(relationName,
|
strlen(relationName),
|
false,
|
false);
|
relationOid = get_relname_relid(normalizedRelationName, namespaceOid);
|
pfree(normalizedRelationName);
|
}
|
}
|
|
pfree(schemaName);
|
pfree(relationName);
|
}
|
|
pfree(tableNameText);
|
list_free_deep(nameList);
|
|
if (relationOid == InvalidOid) {
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_TABLE),
|
errmsg("relation does not exist"),
|
errdetail("tablename=%s", table_name.c_str())));
|
}
|
|
return relationOid;
|
}
|
|
static Oid
|
resolvetablerelid(const std::string &owner_name, const std::string &table_name)
|
{
|
std::string qualifiedName = normalizeidentifierinput(owner_name) + "." +
|
normalizeidentifierinput(table_name);
|
|
return resolvetablerelid(qualifiedName);
|
}
|
|
static std::string
|
resolverelationownername(Oid relation_oid)
|
{
|
Oid namespaceOid = get_rel_namespace(relation_oid);
|
char *namespaceName = get_namespace_name(namespaceOid);
|
|
if (namespaceName == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_SCHEMA),
|
errmsg("relation schema does not exist"),
|
errdetail("relation_oid=%u", relation_oid)));
|
}
|
|
return std::string(namespaceName);
|
}
|
|
static std::string
|
resolverelationname(Oid relation_oid)
|
{
|
char *relationName = get_rel_name(relation_oid);
|
|
if (relationName == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_TABLE),
|
errmsg("relation name does not exist"),
|
errdetail("relation_oid=%u", relation_oid)));
|
}
|
|
return std::string(relationName);
|
}
|
|
static std::string
|
resolvecolumnname(Oid relation_oid, const std::string &column_name)
|
{
|
AttrNumber attributeNumber = get_attnum(relation_oid, column_name.c_str());
|
char *resolvedName = nullptr;
|
|
if (attributeNumber == InvalidAttrNumber) {
|
std::string normalizedName = normalizeidentifierinput(column_name);
|
|
if (normalizedName != column_name) {
|
attributeNumber = get_attnum(relation_oid, normalizedName.c_str());
|
}
|
}
|
|
if (attributeNumber == InvalidAttrNumber) {
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_COLUMN),
|
errmsg("column does not exist"),
|
errdetail("column_name=%s", column_name.c_str())));
|
}
|
|
resolvedName = get_attname(relation_oid, attributeNumber, false);
|
if (resolvedName == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_COLUMN),
|
errmsg("column name does not exist"),
|
errdetail("relation_oid=%u, column_name=%s",
|
relation_oid,
|
column_name.c_str())));
|
}
|
|
return std::string(resolvedName);
|
}
|
|
static std::string
|
resolvetableownername(const std::string &table_name)
|
{
|
Oid relationOid = resolvetablerelid(table_name);
|
|
return resolverelationownername(relationOid);
|
}
|
|
static std::string
|
resolvetableownername(const std::string &owner_name, const std::string &table_name)
|
{
|
Oid relationOid = resolvetablerelid(owner_name, table_name);
|
|
return resolverelationownername(relationOid);
|
}
|
|
static std::string
|
resolvetablename(const std::string &table_name)
|
{
|
Oid relationOid = resolvetablerelid(table_name);
|
|
return resolverelationname(relationOid);
|
}
|
|
static std::string
|
resolvetablename(const std::string &owner_name, const std::string &table_name)
|
{
|
Oid relationOid = resolvetablerelid(owner_name, table_name);
|
|
return resolverelationname(relationOid);
|
}
|
|
static std::string
|
resolvejsoncolumnname(const std::string &table_name, const std::string &column_name)
|
{
|
Oid relationOid = resolvetablerelid(table_name);
|
|
return resolvecolumnname(relationOid, column_name);
|
}
|
|
static std::string
|
resolvejsoncolumnname(const std::string &owner_name,
|
const std::string &table_name,
|
const std::string &column_name)
|
{
|
Oid relationOid = resolvetablerelid(owner_name, table_name);
|
|
return resolvecolumnname(relationOid, column_name);
|
}
|
|
static std::string
|
resolvestatusname(const std::string &status_table_name)
|
{
|
return normalizeidentifierinput(status_table_name);
|
}
|
|
static void
|
normalizeexistingtableandcolumn(const std::string &table_name,
|
const std::string &column_name,
|
std::string *owner_name,
|
std::string *normalized_table_name,
|
std::string *normalized_column_name)
|
{
|
Oid relationOid = resolvetablerelid(table_name);
|
|
*owner_name = resolverelationownername(relationOid);
|
*normalized_table_name = resolverelationname(relationOid);
|
*normalized_column_name = resolvecolumnname(relationOid, column_name);
|
}
|
|
static void
|
normalizeexistingtableandcolumn(const std::string &owner_name,
|
const std::string &table_name,
|
const std::string &column_name,
|
std::string *normalized_owner_name,
|
std::string *normalized_table_name,
|
std::string *normalized_column_name)
|
{
|
Oid relationOid = resolvetablerelid(owner_name, table_name);
|
|
*normalized_owner_name = resolverelationownername(relationOid);
|
*normalized_table_name = resolverelationname(relationOid);
|
*normalized_column_name = resolvecolumnname(relationOid, column_name);
|
}
|
|
static std::string
|
resolvecolumntype(JsonbContainer *column_guide)
|
{
|
JsonbValue typeBuffer;
|
JsonbValue lengthBuffer;
|
JsonbValue *typeValue = getobjectfield(column_guide, "type", &typeBuffer);
|
JsonbValue *lengthValue = getobjectfield(column_guide, "o:length", &lengthBuffer);
|
std::string typeName = jsonbvaluetostring(typeValue);
|
int32 columnLength = jsonbvaluetoint32(lengthValue, 0);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON resolve column type"),
|
errdetail("json_type=%s, length=%d",
|
typeName.c_str(),
|
columnLength)));
|
|
if (typeName == "number") {
|
return "number";
|
}
|
|
if (typeName == "string") {
|
if (columnLength > 0) {
|
return "varchar2(" + std::to_string(columnLength) + ")";
|
}
|
|
return "varchar2(4000)";
|
}
|
|
if (typeName == "integer") {
|
return "number";
|
}
|
|
if (typeName == "boolean") {
|
return "varchar2(5)";
|
}
|
|
if (typeName == "null") {
|
return "varchar2(4)";
|
}
|
|
return "";
|
}
|
|
static std::string
|
resolvecolumntypefromname(const std::string &json_type)
|
{
|
if (json_type == "number" || json_type == "integer") {
|
return "numeric";
|
}
|
|
if (json_type == "boolean") {
|
return "boolean";
|
}
|
|
if (json_type == "string" || json_type == "null") {
|
return "text";
|
}
|
|
return "";
|
}
|
|
static bool
|
isscalarjsonbvalue(const JsonbValue *json_value)
|
{
|
if (json_value == nullptr) {
|
return false;
|
}
|
|
switch (json_value->type) {
|
case jbvString:
|
case jbvNumeric:
|
case jbvBool:
|
case jbvNull:
|
return true;
|
default:
|
return false;
|
}
|
}
|
|
static std::string
|
resolvejsontypename(const JsonbValue *json_value)
|
{
|
if (json_value == nullptr) {
|
return "";
|
}
|
|
switch (json_value->type) {
|
case jbvString:
|
return "string";
|
case jbvNumeric:
|
return "number";
|
case jbvBool:
|
return "boolean";
|
case jbvNull:
|
return "null";
|
default:
|
return "";
|
}
|
}
|
|
static std::string
|
resolvejsontypenamefromcode(int32 type_code)
|
{
|
switch (type_code) {
|
case DBMS_JSON_TYPE_NULL:
|
return "null";
|
case DBMS_JSON_TYPE_STRING:
|
return "string";
|
case DBMS_JSON_TYPE_NUMBER:
|
return "number";
|
case DBMS_JSON_TYPE_BOOLEAN:
|
return "boolean";
|
case DBMS_JSON_TYPE_OBJECT:
|
return "object";
|
case DBMS_JSON_TYPE_ARRAY:
|
return "array";
|
default:
|
return "";
|
}
|
}
|
|
static void
|
appendguideentry(JsonbParseState **parse_state,
|
const std::string &path_value,
|
const std::string &json_type,
|
const std::string &column_name)
|
{
|
JsonbValue keyValue;
|
JsonbValue valueValue;
|
|
(void) pushJsonbValue(parse_state, WJB_BEGIN_OBJECT, nullptr);
|
|
keyValue.type = jbvString;
|
keyValue.val.string.val = const_cast<char *>("path");
|
keyValue.val.string.len = 4;
|
valueValue.type = jbvString;
|
valueValue.val.string.val = pstrdup(path_value.c_str());
|
valueValue.val.string.len = path_value.size();
|
(void) pushJsonbValue(parse_state, WJB_KEY, &keyValue);
|
(void) pushJsonbValue(parse_state, WJB_VALUE, &valueValue);
|
|
keyValue.val.string.val = const_cast<char *>("type");
|
keyValue.val.string.len = 4;
|
valueValue.val.string.val = pstrdup(json_type.c_str());
|
valueValue.val.string.len = json_type.size();
|
(void) pushJsonbValue(parse_state, WJB_KEY, &keyValue);
|
(void) pushJsonbValue(parse_state, WJB_VALUE, &valueValue);
|
|
keyValue.val.string.val = const_cast<char *>("column");
|
keyValue.val.string.len = 6;
|
valueValue.val.string.val = pstrdup(column_name.c_str());
|
valueValue.val.string.len = column_name.size();
|
(void) pushJsonbValue(parse_state, WJB_KEY, &keyValue);
|
(void) pushJsonbValue(parse_state, WJB_VALUE, &valueValue);
|
|
(void) pushJsonbValue(parse_state, WJB_END_OBJECT, nullptr);
|
}
|
|
static void
|
collectguideentries(JsonbContainer *container,
|
const std::string &base_path,
|
JsonbParseState **parse_state)
|
{
|
JsonbIterator *iterator = JsonbIteratorInit(container);
|
JsonbValue iteratorValue;
|
JsonbIteratorToken token;
|
std::string currentKey;
|
|
while ((token = JsonbIteratorNext(&iterator, &iteratorValue, true)) != WJB_DONE) {
|
std::string currentPath;
|
std::string currentType;
|
|
if (token == WJB_KEY) {
|
currentKey.assign(iteratorValue.val.string.val, iteratorValue.val.string.len);
|
continue;
|
}
|
|
if (token != WJB_VALUE) {
|
continue;
|
}
|
|
currentPath = joinpath(base_path, currentKey);
|
currentType = resolvejsontypename(&iteratorValue);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.BUILD_DATAGUIDE inspect node"),
|
errdetail("path=%s, type=%s",
|
currentPath.c_str(),
|
currentType.empty() ? "composite" : currentType.c_str())));
|
|
if (isscalarjsonbvalue(&iteratorValue)) {
|
appendguideentry(parse_state,
|
currentPath,
|
currentType,
|
normalizesqlidentifier(currentKey, false));
|
continue;
|
}
|
|
if (iteratorValue.type == jbvBinary &&
|
JsonContainerIsObject(iteratorValue.val.binary.data)) {
|
collectguideentries(iteratorValue.val.binary.data, currentPath, parse_state);
|
}
|
}
|
}
|
|
static Jsonb *
|
builddataguide(Jsonb *json_value)
|
{
|
JsonbValue rootValue;
|
JsonbParseState *parseState = nullptr;
|
JsonbValue *resultValue = nullptr;
|
|
JsonbToJsonbValue(json_value, &rootValue);
|
|
if (rootValue.type != jbvBinary ||
|
!JsonContainerIsObject(rootValue.val.binary.data)) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("DBMS_JSON.BUILD_DATAGUIDE expects root JSON object")));
|
}
|
|
(void) pushJsonbValue(&parseState, WJB_BEGIN_ARRAY, nullptr);
|
collectguideentries(rootValue.val.binary.data, "$", &parseState);
|
resultValue = pushJsonbValue(&parseState, WJB_END_ARRAY, nullptr);
|
|
return JsonbValueToJsonb(resultValue);
|
}
|
|
static void
|
appendguideentryifmissing(JsonbParseState **parse_state,
|
std::set<std::string> *seen_entries,
|
const GuideEntry &entry)
|
{
|
std::string entryKey = entry.path_ + "|" + entry.jsonType_ + "|" + entry.columnName_ + "|" +
|
entry.columnType_;
|
|
if (seen_entries->find(entryKey) != seen_entries->end()) {
|
return;
|
}
|
|
seen_entries->insert(entryKey);
|
appendguideentry(parse_state, entry.path_, entry.jsonType_, entry.columnName_);
|
}
|
|
static Jsonb *
|
buildguidefromentries(const std::vector<GuideEntry> &entries)
|
{
|
JsonbParseState *parseState = nullptr;
|
JsonbValue *resultValue = nullptr;
|
std::set<std::string> seenEntries;
|
|
(void) pushJsonbValue(&parseState, WJB_BEGIN_ARRAY, nullptr);
|
|
for (const GuideEntry &entry : entries) {
|
appendguideentryifmissing(&parseState, &seenEntries, entry);
|
}
|
|
resultValue = pushJsonbValue(&parseState, WJB_END_ARRAY, nullptr);
|
return JsonbValueToJsonb(resultValue);
|
}
|
|
static void
|
applypreferrednames(Oid relation_oid,
|
const std::string &json_column_name,
|
std::vector<GuideEntry> *entries)
|
{
|
if (entries->empty()) {
|
return;
|
}
|
|
for (const MetadataEntry &metadataEntry : metadataEntries_) {
|
if (metadataEntry.relationOid_ != relation_oid ||
|
metadataEntry.jsonColumnName_ != json_column_name) {
|
continue;
|
}
|
for (GuideEntry &entry : *entries) {
|
if (entry.path_ == metadataEntry.path_ &&
|
entry.jsonType_ == metadataEntry.jsonType_) {
|
entry.columnName_ = metadataEntry.preferredName_;
|
}
|
}
|
}
|
}
|
|
static void
|
upsertmetadataentry(Oid relation_oid,
|
const std::string &json_column_name,
|
const std::string &path_value,
|
const std::string &json_type,
|
const std::string &preferred_name)
|
{
|
for (MetadataEntry &metadataEntry : metadataEntries_) {
|
if (metadataEntry.relationOid_ == relation_oid &&
|
metadataEntry.jsonColumnName_ == json_column_name &&
|
metadataEntry.path_ == path_value &&
|
metadataEntry.jsonType_ == json_type) {
|
metadataEntry.preferredName_ = preferred_name;
|
return;
|
}
|
}
|
|
metadataEntries_.push_back({relation_oid,
|
json_column_name,
|
path_value,
|
json_type,
|
preferred_name});
|
}
|
|
static void
|
parseguideentriesfromproperties(JsonbContainer *properties_container,
|
const std::string &base_path,
|
std::vector<GuideEntry> *entries)
|
{
|
JsonbIterator *iterator = JsonbIteratorInit(properties_container);
|
JsonbValue iteratorValue;
|
JsonbIteratorToken token;
|
std::string currentKey;
|
|
while ((token = JsonbIteratorNext(&iterator, &iteratorValue, true)) != WJB_DONE) {
|
if (token == WJB_KEY) {
|
currentKey.assign(iteratorValue.val.string.val, iteratorValue.val.string.len);
|
continue;
|
}
|
|
if (token != WJB_VALUE || iteratorValue.type != jbvBinary ||
|
!JsonContainerIsObject(iteratorValue.val.binary.data)) {
|
continue;
|
}
|
|
{
|
JsonbContainer *childContainer = iteratorValue.val.binary.data;
|
JsonbValue typeBuffer;
|
JsonbValue preferredBuffer;
|
JsonbValue propertiesBuffer;
|
JsonbValue *typeValue = getobjectfield(childContainer, "type", &typeBuffer);
|
JsonbValue *preferredValue =
|
getobjectfield(childContainer, "o:preferred_column_name", &preferredBuffer);
|
JsonbValue *propertiesValue = getobjectfield(childContainer, "properties", &propertiesBuffer);
|
std::string currentPath = joinpath(base_path, currentKey);
|
std::string jsonType = jsonbvaluetostring(typeValue);
|
std::string columnName = preferredValue == nullptr
|
? normalizesqlidentifier(currentKey, true)
|
: jsonbvaluetostring(preferredValue);
|
std::string columnType = resolvecolumntype(childContainer);
|
|
if (!columnType.empty()) {
|
entries->push_back({currentPath, jsonType, columnName, columnType});
|
}
|
|
if (propertiesValue != nullptr &&
|
propertiesValue->type == jbvBinary &&
|
JsonContainerIsObject(propertiesValue->val.binary.data)) {
|
parseguideentriesfromproperties(propertiesValue->val.binary.data, currentPath, entries);
|
}
|
}
|
}
|
}
|
|
static void
|
parseguideentries(Jsonb *guide_jsonb, std::vector<GuideEntry> *entries)
|
{
|
JsonbValue rootValue;
|
JsonbIterator *iterator = JsonbIteratorInit(&guide_jsonb->root);
|
JsonbValue iteratorValue;
|
JsonbIteratorToken token;
|
|
JsonbToJsonbValue(guide_jsonb, &rootValue);
|
|
if (rootValue.type == jbvBinary && JsonContainerIsObject(rootValue.val.binary.data)) {
|
JsonbValue propertiesBuffer;
|
JsonbValue *propertiesValue =
|
getobjectfield(rootValue.val.binary.data, "properties", &propertiesBuffer);
|
|
if (propertiesValue != nullptr &&
|
propertiesValue->type == jbvBinary &&
|
JsonContainerIsObject(propertiesValue->val.binary.data)) {
|
parseguideentriesfromproperties(propertiesValue->val.binary.data, "$", entries);
|
return;
|
}
|
}
|
|
while ((token = JsonbIteratorNext(&iterator, &iteratorValue, true)) != WJB_DONE) {
|
JsonbValue pathBuffer;
|
JsonbValue typeBuffer;
|
JsonbValue columnBuffer;
|
JsonbValue *pathValue = nullptr;
|
JsonbValue *typeValue = nullptr;
|
JsonbValue *columnValue = nullptr;
|
|
if (token != WJB_ELEM || iteratorValue.type != jbvBinary ||
|
!JsonContainerIsObject(iteratorValue.val.binary.data)) {
|
continue;
|
}
|
|
pathValue = getobjectfield(iteratorValue.val.binary.data, "path", &pathBuffer);
|
typeValue = getobjectfield(iteratorValue.val.binary.data, "type", &typeBuffer);
|
columnValue = getobjectfield(iteratorValue.val.binary.data, "column", &columnBuffer);
|
|
if (pathValue == nullptr || typeValue == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid data guide entry"),
|
errdetail("guide entry must contain path and type")));
|
}
|
|
entries->push_back({jsonbvaluetostring(pathValue),
|
jsonbvaluetostring(typeValue),
|
columnValue == nullptr ? "" : jsonbvaluetostring(columnValue),
|
""});
|
}
|
}
|
|
static Jsonb *
|
builddataguidefortable(const std::string &owner_name,
|
const std::string &table_name,
|
const std::string &json_column_name)
|
{
|
Oid argTypes[0];
|
Datum values[0];
|
const char nulls[1] = {' '};
|
int spiStatus = SPI_OK_CONNECT;
|
int executeStatus = SPI_OK_SELECT;
|
std::string selectSql =
|
"SELECT CASE "
|
"WHEN " + std::string(quote_identifier(json_column_name.c_str())) + " IS NULL THEN NULL "
|
"ELSE pg_catalog.dbms_json_build_dataguide(" +
|
std::string(quote_identifier(json_column_name.c_str())) + ") END "
|
"FROM " + buildqualifiedname(owner_name, table_name);
|
std::vector<GuideEntry> allEntries;
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON table guide build"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
executeStatus = SPI_execute_with_args(selectSql.c_str(),
|
0,
|
argTypes,
|
values,
|
nulls,
|
true,
|
0);
|
if (executeStatus != SPI_OK_SELECT) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON failed to build guide from table"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
|
for (uint64 rowIndex = 0; rowIndex < SPI_processed; ++rowIndex) {
|
bool isNull = false;
|
Datum guideDatum = SPI_getbinval(SPI_tuptable->vals[rowIndex],
|
SPI_tuptable->tupdesc,
|
1,
|
&isNull);
|
|
if (!isNull) {
|
Jsonb *rowGuideJsonb = DatumGetJsonbP(guideDatum);
|
parseguideentries(rowGuideJsonb, &allEntries);
|
}
|
}
|
|
SPI_finish();
|
return buildguidefromentries(allEntries);
|
}
|
|
static text *
|
builddataguidetextforformat(Jsonb *guide_jsonb, int32 format_code, int32 pretty_code)
|
{
|
text *guideText = nullptr;
|
|
if (format_code != 1 && format_code != 2 && format_code != 3) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("DBMS_JSON.GET_INDEX_DATAGUIDE invalid format"),
|
errdetail("format=%d", format_code)));
|
}
|
|
if (pretty_code == 1) {
|
guideText = DatumGetTextPP(DirectFunctionCall1(jsonb_pretty, JsonbPGetDatum(guide_jsonb)));
|
} else {
|
guideText = cstring_to_text(JsonbToCString(nullptr, &guide_jsonb->root, VARSIZE(guide_jsonb)));
|
}
|
|
return guideText;
|
}
|
|
static std::string
|
buildjsonpatharrayliteral(const std::string &json_path)
|
{
|
std::string trimmedPath = trimrootpath(json_path);
|
std::string resultValue = "{";
|
std::size_t startPos = 0;
|
|
while (startPos <= trimmedPath.size()) {
|
std::size_t dotPos = trimmedPath.find('.', startPos);
|
std::string token = trimmedPath.substr(startPos, dotPos - startPos);
|
|
if (!token.empty()) {
|
if (resultValue.size() > 1) {
|
resultValue += ",";
|
}
|
|
resultValue += token;
|
}
|
|
if (dotPos == std::string::npos) {
|
break;
|
}
|
|
startPos = dotPos + 1;
|
}
|
|
resultValue += "}";
|
return resultValue;
|
}
|
|
static std::string
|
buildvirtualcolumnexpr(const std::string &json_column_name,
|
const std::string &json_path,
|
const std::string &column_type)
|
{
|
std::string baseExpr =
|
"(" + std::string(quote_identifier(json_column_name.c_str())) + " #>> '" +
|
buildjsonpatharrayliteral(json_path) + "')";
|
|
if (column_type == "numeric") {
|
return "(" + baseExpr + "::numeric)";
|
}
|
|
if (column_type == "boolean") {
|
return "(" + baseExpr + "::boolean)";
|
}
|
|
return baseExpr;
|
}
|
|
static void
|
buildcolumnsfromguide(const std::vector<GuideEntry> &entries,
|
const std::string &root_path,
|
const std::string &prefix_value,
|
bool resolve_name_conflicts,
|
bool mixed_case_columns,
|
bool prefer_declared_types,
|
std::vector<ColumnSpec> *columns)
|
{
|
std::set<std::string> usedNames;
|
|
for (const GuideEntry &entry : entries) {
|
std::string relativePath;
|
std::string leafName;
|
std::string resolvedName;
|
std::string columnType;
|
std::size_t dotPos;
|
|
if (!ispathunderroot(entry.path_, root_path)) {
|
continue;
|
}
|
|
relativePath = makerelativepath(entry.path_, root_path);
|
if (relativePath.empty()) {
|
continue;
|
}
|
|
dotPos = relativePath.rfind('.');
|
leafName = dotPos == std::string::npos ? relativePath : relativePath.substr(dotPos + 1);
|
resolvedName = entry.columnName_.empty() ? leafName : entry.columnName_;
|
resolvedName = normalizesqlidentifier(prefix_value + resolvedName, mixed_case_columns);
|
columnType = prefer_declared_types && !entry.columnType_.empty()
|
? entry.columnType_
|
: resolvecolumntypefromname(entry.jsonType_);
|
|
if (columnType.empty()) {
|
continue;
|
}
|
|
if (usedNames.find(resolvedName) != usedNames.end()) {
|
if (!resolve_name_conflicts) {
|
ereport(ERROR,
|
(errcode(ERRCODE_DUPLICATE_COLUMN),
|
errmsg("invalid data guide: column name conflict"),
|
errdetail("column_name=%s", resolvedName.c_str())));
|
}
|
|
int suffixValue = 1;
|
std::string uniqueName;
|
|
do {
|
uniqueName = resolvedName + std::to_string(suffixValue);
|
suffixValue++;
|
} while (usedNames.find(uniqueName) != usedNames.end());
|
|
resolvedName = uniqueName;
|
}
|
|
usedNames.insert(resolvedName);
|
columns->push_back({relativePath, resolvedName, columnType});
|
}
|
}
|
|
static std::string
|
buildcolumnclause(const std::vector<ColumnSpec> &columns)
|
{
|
std::string resultValue;
|
|
for (std::size_t index = 0; index < columns.size(); ++index) {
|
if (index != 0) {
|
resultValue += ",\n";
|
}
|
|
resultValue += std::string(quote_identifier(columns[index].columnName_.c_str())) + " " +
|
columns[index].columnType_ + " path '" +
|
buildjsonpathfromrelative(columns[index].jsonFieldName_) + "'";
|
}
|
|
return resultValue;
|
}
|
|
static std::string
|
buildselectsql(const std::string &owner_name,
|
const std::string &table_name,
|
const std::string &json_column_name,
|
const std::string &path_value,
|
const std::vector<ColumnSpec> &columns,
|
bool materialize)
|
{
|
std::string selectHead = materialize
|
? "SELECT RT.\"ROWID\" ROW_ID, JT.*\n"
|
: "SELECT JT.*\n";
|
|
return selectHead +
|
"FROM " + buildqualifiedname(owner_name, table_name) + " RT,\n" +
|
"JSON_TABLE(" + std::string(quote_identifier(json_column_name.c_str())) + ", '" +
|
normalizepath(path_value) + "' COLUMNS (\n" +
|
buildcolumnclause(columns) + "))JT";
|
}
|
|
static std::string
|
buildddl(const std::string &owner_name,
|
const std::string &view_name,
|
const std::string &select_sql,
|
bool materialize,
|
int32 mv_refresh_mode)
|
{
|
if (view_name.empty()) {
|
return select_sql;
|
}
|
|
if (materialize) {
|
if (mv_refresh_mode != DBMS_JSON_MV_REFRESH_ON_STATEMENT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported materialized view refresh mode"),
|
errdetail("mvrefreshmode=%d", mv_refresh_mode)));
|
}
|
|
return "CREATE MATERIALIZED VIEW " + buildqualifiedname(owner_name, view_name) +
|
" BUILD IMMEDIATE REFRESH FAST ON STATEMENT WITH ROWID\nAS " + select_sql;
|
}
|
|
return "CREATE OR REPLACE VIEW " + buildqualifiedname(owner_name, view_name) +
|
" AS " + select_sql;
|
}
|
} // namespace DbmsJson
|
|
extern "C" Datum
|
dbms_json_build_dataguide(PG_FUNCTION_ARGS)
|
{
|
Jsonb *_jsonValue = PG_GETARG_JSONB_P(0);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.BUILD_DATAGUIDE call"),
|
errdetail("input_size=%d", VARSIZE(_jsonValue))));
|
|
PG_RETURN_JSONB_P(DbmsJson::builddataguide(_jsonValue));
|
}
|
|
extern "C" Datum
|
dbms_json_get_index_dataguide(PG_FUNCTION_ARGS)
|
{
|
text *_tableNameText = PG_GETARG_TEXT_PP(0);
|
text *_jsonColumnNameText = PG_GETARG_TEXT_PP(1);
|
int32 formatCode = PG_GETARG_INT32(2);
|
int32 prettyCode = PG_NARGS() > 3 && !PG_ARGISNULL(3) ? PG_GETARG_INT32(3) : 0;
|
char *_tableNameCString = text_to_cstring(_tableNameText);
|
char *_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
std::string tableOwnerName;
|
std::string tableName;
|
std::string jsonColumnName;
|
Oid relationOid = InvalidOid;
|
Jsonb *guideJsonb = nullptr;
|
text *guideText = nullptr;
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_INDEX_DATAGUIDE call"),
|
errdetail("tablename=%s, jcolname=%s, format=%d, pretty=%d",
|
_tableNameCString,
|
_jsonColumnNameCString,
|
formatCode,
|
prettyCode)));
|
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&tableOwnerName,
|
&tableName,
|
&jsonColumnName);
|
relationOid = DbmsJson::resolvetablerelid(tableOwnerName, tableName);
|
guideJsonb = DbmsJson::builddataguidefortable(tableOwnerName,
|
tableName,
|
jsonColumnName);
|
|
{
|
std::vector<DbmsJson::GuideEntry> guideEntries;
|
DbmsJson::parseguideentries(guideJsonb, &guideEntries);
|
DbmsJson::applypreferrednames(relationOid,
|
jsonColumnName,
|
&guideEntries);
|
guideJsonb = DbmsJson::buildguidefromentries(guideEntries);
|
}
|
|
guideText = DbmsJson::builddataguidetextforformat(guideJsonb, formatCode, prettyCode);
|
|
pfree(_tableNameCString);
|
pfree(_jsonColumnNameCString);
|
|
PG_RETURN_TEXT_P(guideText);
|
}
|
|
extern "C" Datum
|
dbms_json_get_view_sql(PG_FUNCTION_ARGS)
|
{
|
text *_viewNameText = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0);
|
text *_tableNameText = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1);
|
text *_jsonColumnNameText = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2);
|
Jsonb *_dataGuideJsonb = PG_ARGISNULL(3) ? nullptr : PG_GETARG_JSONB_P(3);
|
bool materialize = PG_ARGISNULL(4) ? false : PG_GETARG_BOOL(4);
|
int32 mvRefreshMode =
|
PG_ARGISNULL(5) ? DBMS_JSON_MV_REFRESH_ON_STATEMENT : PG_GETARG_INT32(5);
|
text *_pathText = PG_ARGISNULL(6) ? nullptr : PG_GETARG_TEXT_PP(6);
|
bool resolveNameConflicts = PG_ARGISNULL(7) ? true : PG_GETARG_BOOL(7);
|
text *_columnPrefixText = PG_ARGISNULL(8) ? nullptr : PG_GETARG_TEXT_PP(8);
|
bool mixedCaseColumns = PG_ARGISNULL(9) ? true : PG_GETARG_BOOL(9);
|
char *_viewNameCString = nullptr;
|
char *_tableNameCString = nullptr;
|
char *_jsonColumnNameCString = nullptr;
|
char *_pathCString = nullptr;
|
char *_columnPrefixCString = nullptr;
|
std::vector<DbmsJson::GuideEntry> guideEntries;
|
std::vector<DbmsJson::ColumnSpec> columns;
|
std::string viewOwnerName;
|
std::string tableOwnerName;
|
std::string viewName;
|
std::string tableName;
|
std::string jsonColumnName;
|
std::string pathValue = "$";
|
std::string columnPrefix;
|
std::string ddlText;
|
bool isViewNameNull = (_viewNameText == nullptr);
|
bool isTableNameNull = (_tableNameText == nullptr);
|
bool isJsonColumnNameNull = (_jsonColumnNameText == nullptr);
|
bool isDataGuideNull = (_dataGuideJsonb == nullptr);
|
bool isPathNull = (_pathText == nullptr);
|
bool isColumnPrefixNull = (_columnPrefixText == nullptr);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_VIEW_SQL call"),
|
errdetail("viewname_is_null=%s, tablename_is_null=%s, jcolname_is_null=%s, dataguide_is_null=%s, materialize=%s, mvrefreshmode=%d, path_is_null=%s, resolvenameconflicts=%s, colnameprefix_is_null=%s, mixedcasecolumns=%s",
|
isViewNameNull ? "true" : "false",
|
isTableNameNull ? "true" : "false",
|
isJsonColumnNameNull ? "true" : "false",
|
isDataGuideNull ? "true" : "false",
|
materialize ? "true" : "false",
|
mvRefreshMode,
|
isPathNull ? "true" : "false",
|
resolveNameConflicts ? "true" : "false",
|
isColumnPrefixNull ? "true" : "false",
|
mixedCaseColumns ? "true" : "false")));
|
|
if (isTableNameNull || isJsonColumnNameNull || isDataGuideNull) {
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("DBMS_JSON.GET_VIEW_SQL does not allow NULL required arguments")));
|
}
|
|
_viewNameCString = isViewNameNull ? nullptr : text_to_cstring(_viewNameText);
|
_tableNameCString = text_to_cstring(_tableNameText);
|
_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
_pathCString = isPathNull ? nullptr : text_to_cstring(_pathText);
|
_columnPrefixCString = isColumnPrefixNull ? nullptr : text_to_cstring(_columnPrefixText);
|
|
viewName = _viewNameCString == nullptr
|
? ""
|
: DbmsJson::normalizeidentifierinput(std::string(_viewNameCString));
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&tableOwnerName,
|
&tableName,
|
&jsonColumnName);
|
pathValue = _pathCString == nullptr ? "$" : std::string(_pathCString);
|
columnPrefix = _columnPrefixCString == nullptr ? "" : std::string(_columnPrefixCString);
|
viewOwnerName = DbmsJson::resolveownername();
|
|
if (!mixedCaseColumns) {
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_VIEW_SQL mixed case disabled"),
|
errdetail("column names will be normalized to lower case")));
|
}
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_VIEW_SQL normalized arguments"),
|
errdetail("view_owner=%s, viewname=%s, tablename=%s, jcolname=%s, path=%s, colnameprefix=%s",
|
viewOwnerName.c_str(),
|
viewName.empty() ? "<NULL>" : viewName.c_str(),
|
tableName.c_str(),
|
jsonColumnName.c_str(),
|
pathValue.c_str(),
|
columnPrefix.empty() ? "<NULL>" : columnPrefix.c_str())));
|
|
DbmsJson::parseguideentries(_dataGuideJsonb, &guideEntries);
|
DbmsJson::buildcolumnsfromguide(guideEntries,
|
pathValue,
|
columnPrefix,
|
resolveNameConflicts,
|
mixedCaseColumns,
|
true,
|
&columns);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_VIEW_SQL columns collected"),
|
errdetail("column_count=%zu", columns.size())));
|
|
if (_viewNameCString != nullptr) {
|
pfree(_viewNameCString);
|
}
|
if (_tableNameCString != nullptr) {
|
pfree(_tableNameCString);
|
}
|
if (_jsonColumnNameCString != nullptr) {
|
pfree(_jsonColumnNameCString);
|
}
|
if (_pathCString != nullptr) {
|
pfree(_pathCString);
|
}
|
if (_columnPrefixCString != nullptr) {
|
pfree(_columnPrefixCString);
|
}
|
|
if (columns.empty()) {
|
PG_RETURN_TEXT_P(cstring_to_text(""));
|
}
|
|
ddlText = DbmsJson::buildddl(viewOwnerName,
|
viewName,
|
DbmsJson::buildselectsql(tableOwnerName,
|
tableName,
|
jsonColumnName,
|
pathValue,
|
columns,
|
materialize),
|
materialize,
|
mvRefreshMode);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.GET_VIEW_SQL result"),
|
errdetail("ddl_length=%zu", ddlText.size())));
|
|
PG_RETURN_TEXT_P(cstring_to_text(ddlText.c_str()));
|
}
|
|
extern "C" Datum
|
dbms_json_add_virtual_columns(PG_FUNCTION_ARGS)
|
{
|
text *_tableNameText = PG_GETARG_TEXT_PP(0);
|
text *_jsonColumnNameText = PG_GETARG_TEXT_PP(1);
|
Jsonb *_dataGuideJsonb = PG_GETARG_JSONB_P(2);
|
bool resolveNameConflicts = PG_NARGS() > 3 && !PG_ARGISNULL(3) ? PG_GETARG_BOOL(3) : true;
|
text *_columnPrefixText = PG_NARGS() > 4 && !PG_ARGISNULL(4) ? PG_GETARG_TEXT_PP(4) : nullptr;
|
bool mixedCaseColumns = PG_NARGS() > 5 && !PG_ARGISNULL(5) ? PG_GETARG_BOOL(5) : false;
|
char *_tableNameCString = text_to_cstring(_tableNameText);
|
char *_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
char *_columnPrefixCString = _columnPrefixText == nullptr ? nullptr : text_to_cstring(_columnPrefixText);
|
std::string ownerName;
|
std::string tableName;
|
std::string jsonColumnName;
|
std::vector<DbmsJson::GuideEntry> guideEntries;
|
std::vector<DbmsJson::ColumnSpec> columns;
|
int spiStatus = SPI_OK_CONNECT;
|
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&ownerName,
|
&tableName,
|
&jsonColumnName);
|
DbmsJson::parseguideentries(_dataGuideJsonb, &guideEntries);
|
DbmsJson::buildcolumnsfromguide(guideEntries,
|
"$",
|
_columnPrefixCString == nullptr ? "" : std::string(_columnPrefixCString),
|
resolveNameConflicts,
|
mixedCaseColumns,
|
false,
|
&columns);
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON.ADD_VIRTUAL_COLUMNS"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
for (const DbmsJson::ColumnSpec &columnSpec : columns) {
|
std::string alterSql =
|
"ALTER TABLE " + DbmsJson::buildqualifiedname(ownerName, tableName) +
|
" ADD COLUMN " + std::string(quote_identifier(columnSpec.columnName_.c_str())) +
|
" " + columnSpec.columnType_ + " GENERATED ALWAYS AS " +
|
DbmsJson::buildvirtualcolumnexpr(jsonColumnName,
|
DbmsJson::buildjsonpathfromrelative(columnSpec.jsonFieldName_),
|
columnSpec.columnType_) +
|
" STORED";
|
|
int executeStatus = SPI_execute(alterSql.c_str(), false, 0);
|
if (executeStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.ADD_VIRTUAL_COLUMNS failed"),
|
errdetail("column_name=%s, spi_status=%d",
|
columnSpec.columnName_.c_str(),
|
executeStatus)));
|
}
|
}
|
|
SPI_finish();
|
|
pfree(_tableNameCString);
|
pfree(_jsonColumnNameCString);
|
if (_columnPrefixCString != nullptr) {
|
pfree(_columnPrefixCString);
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_create_view(PG_FUNCTION_ARGS)
|
{
|
text *_viewNameText = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0);
|
text *_tableNameText = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1);
|
text *_jsonColumnNameText = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2);
|
Jsonb *_dataGuideJsonb = PG_ARGISNULL(3) ? nullptr : PG_GETARG_JSONB_P(3);
|
text *_resourcePathText = PG_ARGISNULL(4) ? nullptr : PG_GETARG_TEXT_PP(4);
|
bool materialize = PG_ARGISNULL(5) ? false : PG_GETARG_BOOL(5);
|
int32 mvRefreshMode =
|
PG_ARGISNULL(6) ? DBMS_JSON_MV_REFRESH_ON_STATEMENT : PG_GETARG_INT32(6);
|
text *_pathText = PG_ARGISNULL(7) ? nullptr : PG_GETARG_TEXT_PP(7);
|
bool resolveNameConflicts = PG_ARGISNULL(8) ? true : PG_GETARG_BOOL(8);
|
text *_columnPrefixText = PG_ARGISNULL(9) ? nullptr : PG_GETARG_TEXT_PP(9);
|
bool mixedCaseColumns = PG_ARGISNULL(10) ? false : PG_GETARG_BOOL(10);
|
char *_viewNameCString = nullptr;
|
char *_tableNameCString = nullptr;
|
char *_jsonColumnNameCString = nullptr;
|
char *_pathCString = nullptr;
|
char *_columnPrefixCString = nullptr;
|
char *_guideCString = nullptr;
|
int spiStatus = SPI_OK_CONNECT;
|
int executeStatus = SPI_OK_UTILITY;
|
std::vector<DbmsJson::GuideEntry> guideEntries;
|
std::vector<DbmsJson::ColumnSpec> columns;
|
std::string viewOwnerName;
|
std::string tableOwnerName;
|
std::string viewName;
|
std::string tableName;
|
std::string jsonColumnName;
|
std::string pathValue = "$";
|
std::string columnPrefix;
|
std::string ddlText;
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.CREATE_VIEW call"),
|
errdetail("viewname_is_null=%s, tablename_is_null=%s, jcolname_is_null=%s, dataguide_is_null=%s, resourcepath_is_null=%s, materialize=%s, mvrefreshmode=%d, path_is_null=%s, resolvenameconflicts=%s, colnameprefix_is_null=%s, mixedcasecolumns=%s",
|
_viewNameText == nullptr ? "true" : "false",
|
_tableNameText == nullptr ? "true" : "false",
|
_jsonColumnNameText == nullptr ? "true" : "false",
|
_dataGuideJsonb == nullptr ? "true" : "false",
|
_resourcePathText == nullptr ? "true" : "false",
|
materialize ? "true" : "false",
|
mvRefreshMode,
|
_pathText == nullptr ? "true" : "false",
|
resolveNameConflicts ? "true" : "false",
|
_columnPrefixText == nullptr ? "true" : "false",
|
mixedCaseColumns ? "true" : "false")));
|
|
if (_viewNameText == nullptr || _tableNameText == nullptr ||
|
_jsonColumnNameText == nullptr || _dataGuideJsonb == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("DBMS_JSON.CREATE_VIEW does not allow NULL required arguments")));
|
}
|
|
if (_resourcePathText != nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("DBMS_JSON.CREATE_VIEW resourcepath is not supported"),
|
errdetail("resourcepath must be NULL")));
|
}
|
|
_viewNameCString = text_to_cstring(_viewNameText);
|
_tableNameCString = text_to_cstring(_tableNameText);
|
_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
_pathCString = _pathText == nullptr ? nullptr : text_to_cstring(_pathText);
|
_columnPrefixCString = _columnPrefixText == nullptr ? nullptr : text_to_cstring(_columnPrefixText);
|
|
viewOwnerName = DbmsJson::resolveownername();
|
viewName = DbmsJson::normalizeidentifierinput(std::string(_viewNameCString));
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&tableOwnerName,
|
&tableName,
|
&jsonColumnName);
|
pathValue = _pathCString == nullptr ? "$" : std::string(_pathCString);
|
columnPrefix = _columnPrefixCString == nullptr ? "" : std::string(_columnPrefixCString);
|
|
DbmsJson::parseguideentries(_dataGuideJsonb, &guideEntries);
|
DbmsJson::buildcolumnsfromguide(guideEntries,
|
pathValue,
|
columnPrefix,
|
resolveNameConflicts,
|
mixedCaseColumns,
|
true,
|
&columns);
|
|
if (columns.empty()) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid data guide: no scalar fields found")));
|
}
|
|
ddlText = DbmsJson::buildddl(viewOwnerName,
|
viewName,
|
DbmsJson::buildselectsql(tableOwnerName,
|
tableName,
|
jsonColumnName,
|
pathValue,
|
columns,
|
materialize),
|
materialize,
|
mvRefreshMode);
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.CREATE_VIEW ddl"),
|
errdetail("ddl=%s", ddlText.c_str())));
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON.CREATE_VIEW"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
executeStatus = SPI_execute(ddlText.c_str(), false, 0);
|
if (executeStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.CREATE_VIEW failed to execute DDL"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
|
SPI_finish();
|
|
if (_viewNameCString != nullptr) {
|
pfree(_viewNameCString);
|
}
|
if (_tableNameCString != nullptr) {
|
pfree(_tableNameCString);
|
}
|
if (_jsonColumnNameCString != nullptr) {
|
pfree(_jsonColumnNameCString);
|
}
|
if (_pathCString != nullptr) {
|
pfree(_pathCString);
|
}
|
if (_columnPrefixCString != nullptr) {
|
pfree(_columnPrefixCString);
|
}
|
if (_guideCString != nullptr) {
|
pfree(_guideCString);
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_create_view2(PG_FUNCTION_ARGS)
|
{
|
int32 serviceArg = 0;
|
|
if (PG_NARGS() != 12) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("DBMS_JSON.CREATE_VIEW2 accepts exactly 12 arguments")));
|
}
|
|
if (!PG_ARGISNULL(11)) {
|
serviceArg = PG_GETARG_INT32(11);
|
}
|
(void) serviceArg;
|
|
{
|
LOCAL_FCINFO(fcinfo2, 11);
|
|
InitFunctionCallInfoData(*fcinfo2, nullptr, 11, InvalidOid, nullptr, nullptr);
|
fcinfo2->args[0].value = PG_GETARG_DATUM(0);
|
fcinfo2->args[0].isnull = PG_ARGISNULL(0);
|
fcinfo2->args[1].value = PG_GETARG_DATUM(1);
|
fcinfo2->args[1].isnull = PG_ARGISNULL(1);
|
fcinfo2->args[2].value = PG_GETARG_DATUM(2);
|
fcinfo2->args[2].isnull = PG_ARGISNULL(2);
|
fcinfo2->args[3].value = PG_GETARG_DATUM(3);
|
fcinfo2->args[3].isnull = PG_ARGISNULL(3);
|
fcinfo2->args[4].value = PG_GETARG_DATUM(4);
|
fcinfo2->args[4].isnull = PG_ARGISNULL(4);
|
fcinfo2->args[5].value = PG_GETARG_DATUM(5);
|
fcinfo2->args[5].isnull = PG_ARGISNULL(5);
|
fcinfo2->args[6].value = PG_GETARG_DATUM(6);
|
fcinfo2->args[6].isnull = PG_ARGISNULL(6);
|
fcinfo2->args[7].value = PG_GETARG_DATUM(7);
|
fcinfo2->args[7].isnull = PG_ARGISNULL(7);
|
fcinfo2->args[8].value = PG_GETARG_DATUM(8);
|
fcinfo2->args[8].isnull = PG_ARGISNULL(8);
|
fcinfo2->args[9].value = PG_GETARG_DATUM(9);
|
fcinfo2->args[9].isnull = PG_ARGISNULL(9);
|
fcinfo2->args[10].value = PG_GETARG_DATUM(10);
|
fcinfo2->args[10].isnull = PG_ARGISNULL(10);
|
|
(void) dbms_json_create_view(fcinfo2);
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_drop_virtual_columns(PG_FUNCTION_ARGS)
|
{
|
text *_tableNameText = PG_GETARG_TEXT_PP(0);
|
text *_jsonColumnNameText = PG_GETARG_TEXT_PP(1);
|
char *_tableNameCString = text_to_cstring(_tableNameText);
|
char *_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
std::string ownerName;
|
std::string tableName;
|
std::string jsonColumnName;
|
int spiStatus = SPI_OK_CONNECT;
|
int executeStatus = SPI_OK_SELECT;
|
std::string selectSql;
|
std::vector<std::string> columnNames;
|
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&ownerName,
|
&tableName,
|
&jsonColumnName);
|
selectSql =
|
"SELECT attname FROM pg_attribute a "
|
"JOIN pg_class c ON c.oid = a.attrelid "
|
"JOIN pg_namespace n ON n.oid = c.relnamespace "
|
"WHERE n.nspname = " + std::string(quote_literal_cstr(ownerName.c_str())) +
|
" AND c.relname = " + std::string(quote_literal_cstr(tableName.c_str())) +
|
" AND a.attnum > 0 AND NOT a.attisdropped "
|
" AND a.attgenerated <> ''";
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON.DROP_VIRTUAL_COLUMNS"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
executeStatus = SPI_execute(selectSql.c_str(), true, 0);
|
if (executeStatus != SPI_OK_SELECT) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.DROP_VIRTUAL_COLUMNS failed to read columns"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
|
for (uint64 rowIndex = 0; rowIndex < SPI_processed; ++rowIndex) {
|
HeapTuple rowTuple = SPI_tuptable->vals[rowIndex];
|
TupleDesc rowDesc = SPI_tuptable->tupdesc;
|
bool isNull = false;
|
Datum columnNameDatum = SPI_getbinval(rowTuple, rowDesc, 1, &isNull);
|
char *columnNameCString = pstrdup(NameStr(*DatumGetName(columnNameDatum)));
|
|
if (strcmp(columnNameCString, jsonColumnName.c_str()) != 0) {
|
columnNames.push_back(std::string(columnNameCString));
|
}
|
|
pfree(columnNameCString);
|
}
|
|
for (const std::string &columnName : columnNames) {
|
std::string dropSql =
|
"ALTER TABLE " + DbmsJson::buildqualifiedname(ownerName, tableName) +
|
" DROP COLUMN IF EXISTS " + std::string(quote_identifier(columnName.c_str()));
|
int dropStatus = SPI_execute(dropSql.c_str(), false, 0);
|
|
if (dropStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.DROP_VIRTUAL_COLUMNS failed"),
|
errdetail("column_name=%s, spi_status=%d",
|
columnName.c_str(),
|
dropStatus)));
|
}
|
}
|
|
SPI_finish();
|
pfree(_tableNameCString);
|
pfree(_jsonColumnNameCString);
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_json_type_convertible_check(PG_FUNCTION_ARGS)
|
{
|
text *_ownerText = PG_GETARG_TEXT_PP(0);
|
text *_tableNameText = PG_GETARG_TEXT_PP(1);
|
text *_columnNameText = PG_GETARG_TEXT_PP(2);
|
text *_statusTableNameText = PG_GETARG_TEXT_PP(3);
|
bool fastCheck = PG_NARGS() > 4 && !PG_ARGISNULL(4) ? PG_GETARG_BOOL(4) : false;
|
bool appendStatus = PG_NARGS() > 5 && !PG_ARGISNULL(5) ? PG_GETARG_BOOL(5) : false;
|
char *_ownerCString = text_to_cstring(_ownerText);
|
char *_tableNameCString = text_to_cstring(_tableNameText);
|
char *_columnNameCString = text_to_cstring(_columnNameText);
|
char *_statusTableNameCString = text_to_cstring(_statusTableNameText);
|
int spiStatus = SPI_OK_CONNECT;
|
int executeStatus = SPI_OK_UTILITY;
|
std::string ownerName;
|
std::string tableName;
|
std::string columnName;
|
std::string statusTableName;
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_ownerCString),
|
std::string(_tableNameCString),
|
std::string(_columnNameCString),
|
&ownerName,
|
&tableName,
|
&columnName);
|
statusTableName = DbmsJson::resolvestatusname(std::string(_statusTableNameCString));
|
std::string statusQualified = DbmsJson::buildqualifiedname(ownerName, statusTableName);
|
std::string createSql =
|
"CREATE TABLE IF NOT EXISTS " + statusQualified +
|
" (row_no bigint, is_convertible boolean, error_text text)";
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON.JSON_TYPE_CONVERTIBLE_CHECK"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
executeStatus = SPI_execute(createSql.c_str(), false, 0);
|
if (executeStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.JSON_TYPE_CONVERTIBLE_CHECK failed to create status table"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
|
if (!appendStatus) {
|
std::string truncateSql = "TRUNCATE TABLE " + statusQualified;
|
executeStatus = SPI_execute(truncateSql.c_str(), false, 0);
|
if (executeStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.JSON_TYPE_CONVERTIBLE_CHECK failed to truncate status table"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
}
|
|
{
|
std::string inputTypeName = fastCheck ? "json" : "jsonb";
|
std::string insertSql =
|
"INSERT INTO " + statusQualified +
|
" SELECT row_number() OVER (), "
|
" pg_input_is_valid((" + std::string(quote_identifier(columnName.c_str())) + ")::text, " +
|
std::string(quote_literal_cstr(inputTypeName.c_str())) + "), "
|
" CASE "
|
" WHEN pg_input_is_valid((" + std::string(quote_identifier(columnName.c_str())) + ")::text, " +
|
std::string(quote_literal_cstr(inputTypeName.c_str())) + ") "
|
" THEN " + std::string(quote_literal_cstr("ok")) +
|
" ELSE (pg_input_error_info((" + std::string(quote_identifier(columnName.c_str())) + ")::text, " +
|
std::string(quote_literal_cstr(inputTypeName.c_str())) + ")).message "
|
" END " +
|
" FROM " + DbmsJson::buildqualifiedname(ownerName, tableName) +
|
" WHERE " + std::string(quote_identifier(columnName.c_str())) + " IS NOT NULL";
|
|
executeStatus = SPI_execute(insertSql.c_str(), false, 0);
|
if (executeStatus != SPI_OK_INSERT) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.JSON_TYPE_CONVERTIBLE_CHECK failed to populate status table"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
}
|
|
SPI_finish();
|
pfree(_ownerCString);
|
pfree(_tableNameCString);
|
pfree(_columnNameCString);
|
pfree(_statusTableNameCString);
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_rename_column(PG_FUNCTION_ARGS)
|
{
|
text *_tableNameText = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0);
|
text *_jsonColumnNameText = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1);
|
text *_pathText = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2);
|
int32 typeCode = PG_ARGISNULL(3) ? 0 : PG_GETARG_INT32(3);
|
text *_preferredNameText = PG_ARGISNULL(4) ? nullptr : PG_GETARG_TEXT_PP(4);
|
char *_tableNameCString = nullptr;
|
char *_jsonColumnNameCString = nullptr;
|
char *_pathCString = nullptr;
|
char *_preferredNameCString = nullptr;
|
std::string tableOwnerName;
|
std::string tableName;
|
std::string jsonColumnName;
|
std::string jsonType;
|
Oid relationOid = InvalidOid;
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.RENAME_COLUMN call"),
|
errdetail("tablename_is_null=%s, jcolname_is_null=%s, path_is_null=%s, type=%d, preferred_name_is_null=%s",
|
_tableNameText == nullptr ? "true" : "false",
|
_jsonColumnNameText == nullptr ? "true" : "false",
|
_pathText == nullptr ? "true" : "false",
|
typeCode,
|
_preferredNameText == nullptr ? "true" : "false")));
|
|
if (_tableNameText == nullptr || _jsonColumnNameText == nullptr ||
|
_pathText == nullptr || _preferredNameText == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("DBMS_JSON.RENAME_COLUMN does not allow NULL arguments")));
|
}
|
|
jsonType = DbmsJson::resolvejsontypenamefromcode(typeCode);
|
if (jsonType.empty()) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("DBMS_JSON.RENAME_COLUMN invalid type code"),
|
errdetail("type=%d", typeCode)));
|
}
|
|
_tableNameCString = text_to_cstring(_tableNameText);
|
_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
_pathCString = text_to_cstring(_pathText);
|
_preferredNameCString = text_to_cstring(_preferredNameText);
|
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&tableOwnerName,
|
&tableName,
|
&jsonColumnName);
|
relationOid = DbmsJson::resolvetablerelid(tableOwnerName, tableName);
|
DbmsJson::upsertmetadataentry(relationOid,
|
jsonColumnName,
|
std::string(_pathCString),
|
jsonType,
|
std::string(_preferredNameCString));
|
|
if (_tableNameCString != nullptr) {
|
pfree(_tableNameCString);
|
}
|
if (_jsonColumnNameCString != nullptr) {
|
pfree(_jsonColumnNameCString);
|
}
|
if (_pathCString != nullptr) {
|
pfree(_pathCString);
|
}
|
if (_preferredNameCString != nullptr) {
|
pfree(_preferredNameCString);
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
extern "C" Datum
|
dbms_json_create_view_on_path(PG_FUNCTION_ARGS)
|
{
|
text *_viewNameText = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0);
|
text *_tableNameText = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1);
|
text *_jsonColumnNameText = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2);
|
text *_pathText = PG_ARGISNULL(3) ? nullptr : PG_GETARG_TEXT_PP(3);
|
int32 frequency = PG_ARGISNULL(4) ? 0 : PG_GETARG_INT32(4);
|
char *_viewNameCString = nullptr;
|
char *_tableNameCString = nullptr;
|
char *_jsonColumnNameCString = nullptr;
|
char *_pathCString = nullptr;
|
std::string viewOwnerName;
|
std::string tableOwnerName;
|
Oid relationOid = InvalidOid;
|
Jsonb *guideJsonb = nullptr;
|
std::vector<DbmsJson::GuideEntry> guideEntries;
|
std::vector<DbmsJson::ColumnSpec> columns;
|
std::string ddlText;
|
int spiStatus = SPI_OK_CONNECT;
|
int executeStatus = SPI_OK_UTILITY;
|
|
ereport(LOG,
|
(errmsg("DBMS_JSON.CREATE_VIEW_ON_PATH call"),
|
errdetail("viewname_is_null=%s, tablename_is_null=%s, jcolname_is_null=%s, path_is_null=%s, frequency=%d",
|
_viewNameText == nullptr ? "true" : "false",
|
_tableNameText == nullptr ? "true" : "false",
|
_jsonColumnNameText == nullptr ? "true" : "false",
|
_pathText == nullptr ? "true" : "false",
|
frequency)));
|
|
if (_viewNameText == nullptr || _tableNameText == nullptr ||
|
_jsonColumnNameText == nullptr || _pathText == nullptr) {
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("DBMS_JSON.CREATE_VIEW_ON_PATH does not allow NULL required arguments")));
|
}
|
|
if (frequency != 0) {
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("DBMS_JSON.CREATE_VIEW_ON_PATH frequency is not supported in simplified mode"),
|
errdetail("frequency=%d", frequency)));
|
}
|
|
_viewNameCString = text_to_cstring(_viewNameText);
|
_tableNameCString = text_to_cstring(_tableNameText);
|
_jsonColumnNameCString = text_to_cstring(_jsonColumnNameText);
|
_pathCString = text_to_cstring(_pathText);
|
|
viewOwnerName = DbmsJson::resolveownername();
|
std::string tableName;
|
std::string jsonColumnName;
|
DbmsJson::normalizeexistingtableandcolumn(std::string(_tableNameCString),
|
std::string(_jsonColumnNameCString),
|
&tableOwnerName,
|
&tableName,
|
&jsonColumnName);
|
relationOid = DbmsJson::resolvetablerelid(tableOwnerName, tableName);
|
guideJsonb = DbmsJson::builddataguidefortable(tableOwnerName,
|
tableName,
|
jsonColumnName);
|
DbmsJson::parseguideentries(guideJsonb, &guideEntries);
|
DbmsJson::applypreferrednames(relationOid,
|
jsonColumnName,
|
&guideEntries);
|
DbmsJson::buildcolumnsfromguide(guideEntries,
|
std::string(_pathCString),
|
"",
|
true,
|
false,
|
true,
|
&columns);
|
|
if (columns.empty()) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("DBMS_JSON.CREATE_VIEW_ON_PATH found no scalar fields"),
|
errdetail("path=%s", _pathCString)));
|
}
|
|
ddlText = DbmsJson::buildddl(viewOwnerName,
|
DbmsJson::normalizeidentifierinput(std::string(_viewNameCString)),
|
DbmsJson::buildselectsql(tableOwnerName,
|
tableName,
|
jsonColumnName,
|
std::string(_pathCString),
|
columns,
|
false),
|
false,
|
DBMS_JSON_MV_REFRESH_ON_STATEMENT);
|
|
spiStatus = SPI_connect();
|
if (spiStatus != SPI_OK_CONNECT) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in DBMS_JSON.CREATE_VIEW_ON_PATH"),
|
errdetail("spi_status=%d", spiStatus)));
|
}
|
|
executeStatus = SPI_execute(ddlText.c_str(), false, 0);
|
if (executeStatus != SPI_OK_UTILITY) {
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DBMS_JSON.CREATE_VIEW_ON_PATH failed"),
|
errdetail("spi_status=%d", executeStatus)));
|
}
|
|
SPI_finish();
|
|
if (_viewNameCString != nullptr) {
|
pfree(_viewNameCString);
|
}
|
if (_tableNameCString != nullptr) {
|
pfree(_tableNameCString);
|
}
|
if (_jsonColumnNameCString != nullptr) {
|
pfree(_jsonColumnNameCString);
|
}
|
if (_pathCString != nullptr) {
|
pfree(_pathCString);
|
}
|
|
PG_RETURN_VOID();
|
}
|