Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed JSON_OBJECT issue #3891

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rel.type.RelDataTypeSystemImpl;
import org.apache.calcite.sql.SqlDataTypeSpec;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlUserDefinedTypeNameSpec;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.*;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calcite does not like * imports.

import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlTypeName;

import org.apache.calcite.sql.util.SqlString;

import org.checkerframework.checker.nullness.qual.Nullable;

/**
Expand Down Expand Up @@ -118,4 +117,27 @@ public RedshiftSqlDialect(Context context) {
@Override public boolean supportsAliasedValues() {
return false;
}
@Override public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
if (call.getOperator() == SqlStdOperatorTable.JSON_OBJECT) {
assert call.operandCount() % 2 == 1;

SqlWriter.Frame frame = writer.startFunCall("");
SqlWriter.Frame listFrame = writer.startList("'{' || ", " || '}'");
for(int i = 1; i < call.operandCount(); i += 2) {
String keyName = call.operand(i).toSqlString(this).toString();
String value = call.operand(i + 1).toSqlString(this).toString();
keyName = keyName.substring(1, keyName.length() - 1);
String jsonFragment = String.format("'\"%s\": ' || COALESCE(CASE WHEN %s::varchar ~'^-?\\\\d*(\\\\.\\\\d+)?$' THEN %s::varchar ELSE quote_ident(%s) END, 'null')", keyName, value, value, value);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this deserves an explanation as a comment

writer.print(jsonFragment);
// List separator
if (i != call.operandCount() - 2) {
writer.print(" || ', ' || ");
}
}
writer.endList(listFrame);
writer.endFunCall(frame);
} else {
super.unparseCall(writer, call, leftPrec, rightPrec);
}
}
}