From 79a336611422cbbae9de43da09ef5805387938c7 Mon Sep 17 00:00:00 2001 From: Viraj Jasani Date: Wed, 7 Oct 2026 13:04:45 -0700 Subject: [PATCH 1/3] PHOENIX-8036 Protobuf Data type --- bin/phoenix_utils.py | 8 +- phoenix-core-client/pom.xml | 9 + .../src/main/antlr3/PhoenixSQL.g | 109 +- .../ipc/controller/MetadataRpcController.java | 8 + .../ipc/controller/ServerRpcController.java | 8 + .../apache/phoenix/compile/FromCompiler.java | 10 +- .../apache/phoenix/compile/JoinCompiler.java | 4 +- .../apache/phoenix/compile/QueryCompiler.java | 10 +- .../apache/phoenix/compile/UnionCompiler.java | 30 +- .../coprocessorclient/MetaDataProtocol.java | 4 +- .../phoenix/exception/SQLExceptionCode.java | 92 + .../phoenix/expression/ExpressionType.java | 7 +- .../function/ProtoArrayLengthFunction.java | 134 ++ .../function/ProtoExistsFunction.java | 137 ++ .../function/ProtoFieldTypeFunction.java | 64 + .../function/ProtoFunctionsUtil.java | 271 +++ .../function/ProtoValueAtTagFunction.java | 265 +++ .../function/ProtoValueFunction.java | 296 +++ .../expression/util/proto/PathPlan.java | 143 ++ .../util/proto/ProtoPathParser.java | 125 ++ .../util/proto/ProtoPathResolver.java | 438 ++++ .../util/proto/ProtoPathWalker.java | 466 ++++ .../util/proto/ProtoTagPathParser.java | 125 ++ .../util/proto/ProtoTagPathWalker.java | 234 ++ .../expression/util/proto/TagPathPlan.java | 47 + .../expression/util/proto/package-info.java | 22 + .../phoenix/jdbc/PhoenixConnection.java | 46 + .../phoenix/jdbc/PhoenixDatabaseMetaData.java | 19 + .../apache/phoenix/jdbc/PhoenixStatement.java | 115 + .../AlterProtobufDescriptorStatement.java | 73 + .../org/apache/phoenix/parse/ColumnDef.java | 63 + .../parse/CreateProtobufBundleStatement.java | 95 + .../CreateProtobufDescriptorStatement.java | 70 + .../DropProtobufDescriptorStatement.java | 69 + .../apache/phoenix/parse/ParseContext.java | 4 + .../phoenix/parse/ParseNodeFactory.java | 53 + .../parse/ProtoArrayLengthParseNode.java | 49 + .../phoenix/parse/ProtoExistsParseNode.java | 48 + .../parse/ProtoFieldTypeParseNode.java | 61 + .../parse/ProtoValueAtTagParseNode.java | 66 + .../phoenix/parse/ProtoValueParseNode.java | 161 ++ .../org/apache/phoenix/parse/SQLParser.java | 8 + .../descriptor/ProtoDescriptorRegistry.java | 288 +++ .../ProtoDescriptorRegistryHolder.java | 140 ++ .../descriptor/ProtoDescriptorResolver.java | 169 ++ .../descriptor/ProtoEvolutionValidator.java | 388 ++++ .../descriptor/ProtobufDescriptorFetcher.java | 201 ++ .../SystemProtoDescriptorsJdbcLoader.java | 84 + .../protobuf/descriptor/package-info.java | 22 + .../query/ConnectionQueryServicesImpl.java | 86 +- .../ConnectionlessQueryServicesImpl.java | 14 + .../apache/phoenix/query/QueryConstants.java | 36 +- .../phoenix/schema/ColumnMetaDataOps.java | 20 +- .../schema/ConditionalTTLExpression.java | 10 +- .../apache/phoenix/schema/DelegateColumn.java | 5 + .../apache/phoenix/schema/MetaDataClient.java | 244 ++- .../org/apache/phoenix/schema/PColumn.java | 4 + .../apache/phoenix/schema/PColumnImpl.java | 37 +- .../apache/phoenix/schema/PMetaDataImpl.java | 13 +- .../tool/SchemaExtractionProcessor.java | 3 + .../phoenix/schema/types/PDataType.java | 1 + .../schema/types/PDataTypeFactory.java | 1 + .../phoenix/schema/types/PProtobuf.java | 76 + .../org/apache/phoenix/util/MetaDataUtil.java | 10 + .../org/apache/phoenix/util/SchemaUtil.java | 15 + .../src/main/protobuf/MetaDataService.proto | 2 + .../src/main/protobuf/PTable.proto | 1 + .../protobuf/ProtobufDescriptorService.proto | 146 ++ phoenix-core-server/pom.xml | 4 + .../coprocessor/MetaDataEndpointImpl.java | 118 +- .../coprocessor/MetaDataEndpointObserver.java | 13 + .../coprocessor/PhoenixAccessController.java | 121 +- .../PhoenixMetaDataCoprocessorHost.java | 27 + .../PhoenixRegionServerEndpoint.java | 40 + .../ProtoDescriptorLinkMutations.java | 112 + .../ProtobufDescriptorEndpointImpl.java | 552 +++++ .../SystemProtoDescriptorsSplitPolicy.java | 36 + .../phoenix/schema/transform/Transform.java | 14 +- phoenix-core/pom.xml | 32 + .../phoenix/end2end/AcmeWidgetsBundleIT.java | 1223 +++++++++++ .../phoenix/end2end/AcmeWidgetsProto2IT.java | 360 ++++ .../phoenix/end2end/BasePermissionsIT.java | 104 + .../phoenix/end2end/CoalesceFunctionIT.java | 21 + ...igrateSystemTablesToSystemNamespaceIT.java | 18 +- .../ProtoValueEventualConsistencyIndexIT.java | 73 + .../phoenix/end2end/ProtoValueIndexIT.java | 1876 +++++++++++++++++ .../end2end/ProtoValuePackedRepeatedIT.java | 593 ++++++ .../end2end/ProtoValueTypeCoverageIT.java | 1503 +++++++++++++ .../phoenix/end2end/ProtobufColumnDDLIT.java | 972 +++++++++ .../end2end/ProtobufDescriptorDDLIT.java | 1187 +++++++++++ .../end2end/QueryDatabaseMetaDataIT.java | 14 +- .../SkipSystemTablesExistenceCheckIT.java | 3 +- .../SystemTablesCreationOnConnectionIT.java | 6 +- .../end2end/TenantSpecificTablesDDLIT.java | 6 + .../transform/ProtobufColumnTransformIT.java | 225 ++ .../jdbc/FailoverPhoenixConnectionIT.java | 128 ++ .../schema/tool/SchemaToolExtractionIT.java | 18 + .../apache/phoenix/parse/QueryParserTest.java | 363 ++++ .../ProtoDescriptorResolverTest.java | 572 +++++ .../ProtoEvolutionValidatorTest.java | 584 +++++ .../ProtobufDescriptorFetcherTest.java | 252 +++ .../SystemProtoDescriptorsJdbcLoaderTest.java | 149 ++ .../protobuf/text/AcmeWidgetsFixtures.java | 342 +++ .../ProtobufDescriptorServiceWireTest.java | 283 +++ .../phoenix/schema/types/PDataTypeTest.java | 2 +- .../protobuf/acmewidgets/account_sync.proto | 28 + .../protobuf/acmewidgets/acmewidgets_v1.desc | Bin 0 -> 15612 bytes .../acmewidgets/api_credential_sync.proto | 23 + .../acmewidgets/delivery_window_sync.proto | 26 + .../acmewidgets/entitlement_sync.proto | 86 + .../acmewidgets/storefront_sync.proto | 24 + .../acmewidgets/voucher_revocation_sync.proto | 41 + .../protobuf/acmewidgets/widget_common.proto | 26 + .../acmewidgets/widget_endpoint_types.proto | 49 + .../acmewidgets/widget_governance.proto | 93 + .../acmewidgets/widget_order_graph.proto | 115 + pom.xml | 30 +- src/main/config/spotbugs/spotbugs-exclude.xml | 61 + 118 files changed, 18525 insertions(+), 105 deletions(-) create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFieldTypeFunction.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFunctionsUtil.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/PathPlan.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathParser.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathWalker.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathParser.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/TagPathPlan.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/package-info.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/AlterProtobufDescriptorStatement.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufBundleStatement.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufDescriptorStatement.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/DropProtobufDescriptorStatement.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoArrayLengthParseNode.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoExistsParseNode.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoFieldTypeParseNode.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueAtTagParseNode.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueParseNode.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistry.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistryHolder.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolver.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidator.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcher.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoader.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/package-info.java create mode 100644 phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PProtobuf.java create mode 100644 phoenix-core-client/src/main/protobuf/ProtobufDescriptorService.proto create mode 100644 phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtoDescriptorLinkMutations.java create mode 100644 phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtobufDescriptorEndpointImpl.java create mode 100644 phoenix-core-server/src/main/java/org/apache/phoenix/schema/SystemProtoDescriptorsSplitPolicy.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsBundleIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsProto2IT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueEventualConsistencyIndexIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValuePackedRepeatedIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufColumnDDLIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufDescriptorDDLIT.java create mode 100644 phoenix-core/src/it/java/org/apache/phoenix/end2end/transform/ProtobufColumnTransformIT.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolverTest.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidatorTest.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcherTest.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoaderTest.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/AcmeWidgetsFixtures.java create mode 100644 phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/ProtobufDescriptorServiceWireTest.java create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/account_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/acmewidgets_v1.desc create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/api_credential_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/delivery_window_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/entitlement_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/storefront_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/voucher_revocation_sync.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/widget_common.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/widget_endpoint_types.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/widget_governance.proto create mode 100644 phoenix-core/src/test/resources/protobuf/acmewidgets/widget_order_graph.proto diff --git a/bin/phoenix_utils.py b/bin/phoenix_utils.py index 323e7ed538f..ffa1ddca9c0 100755 --- a/bin/phoenix_utils.py +++ b/bin/phoenix_utils.py @@ -97,7 +97,7 @@ def findClasspath(command_name): command = "%s%s" %(command_path, ' classpath') return tryDecode(subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()) -def setPath(): +def setPath(): # pylint: disable=too-many-statements,too-many-branches PHOENIX_CLIENT_EMBEDDED_JAR_PATTERN = "phoenix-client-embedded-hbase-*[!s].jar" PHOENIX_CLIENT_LITE_JAR_PATTERN = "phoenix-client-lite-hbase-*[!s].jar" PHOENIX_TRACESERVER_JAR_PATTERN = "phoenix-tracing-webapp-*-runnable.jar" @@ -140,7 +140,11 @@ def setPath(): hbase_site_file = os.path.join(hbase_conf_dir, "hbase-site.xml") try: global zk_tls_args - root = ET.parse(hbase_site_file).getroot() + # hbase-site.xml is optional; without it there are no ZK TLS properties to apply + if os.path.isfile(hbase_site_file): + root = ET.parse(hbase_site_file).getroot() + else: + root = ET.Element("configuration") zk_hbase_prefix = "hbase.zookeeper.property." zkcfg = { prop.find("name").text[len(zk_hbase_prefix):]: prop.find("value").text diff --git a/phoenix-core-client/pom.xml b/phoenix-core-client/pom.xml index 722487caa33..3267e51119b 100644 --- a/phoenix-core-client/pom.xml +++ b/phoenix-core-client/pom.xml @@ -216,6 +216,15 @@ org.apache.phoenix.thirdparty phoenix-shaded-commons-cli + + + org.apache.phoenix.thirdparty + phoenix-shaded-protobuf + commons-codec commons-codec diff --git a/phoenix-core-client/src/main/antlr3/PhoenixSQL.g b/phoenix-core-client/src/main/antlr3/PhoenixSQL.g index 297a50d5e9a..36cd2dea453 100644 --- a/phoenix-core-client/src/main/antlr3/PhoenixSQL.g +++ b/phoenix-core-client/src/main/antlr3/PhoenixSQL.g @@ -278,6 +278,11 @@ package org.apache.phoenix.parse; public void setParseNodeFactory(ParseNodeFactory factory) { this.factory = factory; } + + /** Test-only: number of ParseContext frames currently on the stack. */ + int getContextStackDepth() { + return contextStack.size(); + } public boolean isCountFunction(String field) { return CountAggregateFunction.NORMALIZED_NAME.equals(SchemaUtil.normalizeIdentifier(field)); @@ -299,6 +304,17 @@ package org.apache.phoenix.parse; e.input = input; throw e; } + + // PROTOBUF / DESCRIPTOR / BUNDLE are matched as NAME, not tokens, so they stay valid identifiers. + private boolean isKw(Token t, String word) { + return word.equalsIgnoreCase(t.getText()); + } + + private void matchKw(Token t, String word) throws RecognitionException { + if (!isKw(t, word)) { + throwRecognitionException(t); + } + } public int getBindCount() { return anonBindNum; @@ -536,9 +552,25 @@ oneStatement returns [BindableStatement ret] | s=use_schema_node | s=update_statistics_node | s=execute_upgrade_node + | s=protobuf_descriptor_node | s=explain_node) { $ret = s; } ; finally{ contextStack.pop(); } + +// Sub-rule so PROTOBUF DDL alternatives do not push oneStatement past javac's 64KB method limit. +protobuf_descriptor_node returns [BindableStatement ret] + : ( cp=create_protobuf_node { $ret = cp; } + | a=alter_protobuf_descriptor_node { $ret = a; } + | d=drop_protobuf_descriptor_node { $ret = d; } + ) + ; + +// Disambiguates `CREATE PROTOBUF DESCRIPTOR ...` vs `CREATE PROTOBUF BUNDLE ...` by the third token. +create_protobuf_node returns [BindableStatement ret] + : ( {isKw(input.LT(3), "bundle")}?=> b=create_protobuf_bundle_node { $ret = b; } + | c=create_protobuf_descriptor_node { $ret = c; } + ) + ; explain_node returns [BindableStatement ret] @init { ExplainOptsAcc opts = new ExplainOptsAcc(); } @@ -781,6 +813,50 @@ drop_schema_node returns [DropSchemaStatement ret] {ret = factory.dropSchema(s, ex!=null, c!=null); } ; +// No inline .proto text; FROM is a pre-compiled FileDescriptorSet URL. +create_protobuf_descriptor_node returns [CreateProtobufDescriptorStatement ret] + : CREATE p=NAME k=NAME { matchKw(p, "protobuf"); matchKw(k, "descriptor"); } (IF NOT ex=EXISTS)? pn=proto_message_name + FROM url=STRING_LITERAL + { + $ret = factory.createProtobufDescriptor(pn, ex != null, url.getText()); + } + ; + +// IF EXISTS is a silent no-op; IF NOT EXISTS is not valid on ALTER. +alter_protobuf_descriptor_node returns [AlterProtobufDescriptorStatement ret] + : ALTER p=NAME k=NAME { matchKw(p, "protobuf"); matchKw(k, "descriptor"); } (IF ex=EXISTS)? pn=proto_message_name + FROM url=STRING_LITERAL + { + $ret = factory.alterProtobufDescriptor(pn, ex != null, url.getText()); + } + ; + +// In-use check is a PROTO_DESC_LINK prefix scan, never SYSTEM.CATALOG. +drop_protobuf_descriptor_node returns [DropProtobufDescriptorStatement ret] + : DROP p=NAME k=NAME { matchKw(p, "protobuf"); matchKw(k, "descriptor"); } (IF ex=EXISTS)? pn=proto_message_name + { $ret = factory.dropProtobufDescriptor(pn, ex != null); } + ; + +// Registers every listed name from one FileDescriptorSet, atomically. +create_protobuf_bundle_node returns [CreateProtobufBundleStatement ret] + : CREATE p=NAME k=NAME { matchKw(p, "protobuf"); matchKw(k, "bundle"); } (IF NOT ex=EXISTS)? + LPAREN nl=proto_message_name_list RPAREN + FROM url=STRING_LITERAL + { + $ret = factory.createProtobufBundle(nl, ex != null, url.getText()); + } + ; + +// Comma-separated list of qualified proto message names. List order matches source-text +// order (used for deterministic error messages); registration semantics are order- +// independent. The list must be non-empty (the LPAREN/RPAREN around it makes the grammar +// require at least one name). +proto_message_name_list returns [java.util.List ret] +@init { $ret = new java.util.ArrayList(); } + : first=proto_message_name { $ret.add($first.ret); } + (COMMA next=proto_message_name { $ret.add($next.ret); })* + ; + // Parse a drop index statement drop_index_node returns [DropIndexStatement ret] @@ -887,10 +963,11 @@ indexes returns [List ret] ; column_def returns [ColumnDef ret] - : c=column_name dt=identifier (LPAREN l=NUMBER (COMMA s=NUMBER)? RPAREN)? ar=ARRAY? (lsq=LSQUARE (a=NUMBER)? RSQUARE)? (nn=NOT? n=NULL)? (DEFAULT df=expression)? ((pk=PRIMARY KEY (order=ASC|order=DESC)? rr=ROW_TIMESTAMP?)|(ENCODED_QUALIFIER eq=NUMBER))? + : c=column_name dt=identifier (LT pn=proto_message_name GT)? (LPAREN l=NUMBER (COMMA s=NUMBER)? RPAREN)? ar=ARRAY? (lsq=LSQUARE (a=NUMBER)? RSQUARE)? (nn=NOT? n=NULL)? (DEFAULT df=expression)? ((pk=PRIMARY KEY (order=ASC|order=DESC)? rr=ROW_TIMESTAMP?)|(ENCODED_QUALIFIER eq=NUMBER))? { $ret = factory.columnDef( c, dt, + pn, ar != null || lsq != null, a == null ? null : Integer.parseInt( a.getText() ), nn!=null ? Boolean.FALSE : n!=null ? Boolean.TRUE : null, @@ -903,6 +980,36 @@ column_def returns [ColumnDef ret] rr != null); } ; +// Case-preserving parts so reserved words like Order stay valid in PROTOBUF<...>. +proto_message_name returns [String ret] +@init{StringBuilder buf = new StringBuilder();} + : first=proto_message_name_part {buf.append(first);} + (DOT next=proto_message_name_part {buf.append('.').append(next);})* + {$ret = buf.toString();} + ; + +proto_message_name_part returns [String ret] + : any=~(EOF) { + // STRING_LITERAL text has quotes stripped; reject literals so PROTOBUF<'x'> + // cannot parse as PROTOBUF. Accept NAME or reserved-word tokens only. + int tt = $any.getType(); + if (tt == STRING_LITERAL || tt == NUMBER || tt == DECIMAL || tt == DOUBLE + || tt == HEX_LITERAL || tt == BIN_LITERAL || tt == BIND_NAME) { + throw new RuntimeException( + "Invalid PROTOBUF message-name part: literals (" + $any.getText() + + ") are not allowed. Each dot-separated part must be an unquoted " + + "identifier matching [A-Za-z_][A-Za-z0-9_]*."); + } + String text = $any.getText(); + if (text == null || !text.matches("[A-Za-z_][A-Za-z0-9_]*")) { + throw new RuntimeException( + "Invalid PROTOBUF message-name part: '" + text + + "'. Each dot-separated part must match [A-Za-z_][A-Za-z0-9_]*."); + } + $ret = text; + } + ; + dyn_column_defs returns [List ret] @init{ret = new ArrayList(); } : v = dyn_column_def {$ret.add(v);} (COMMA v = dyn_column_def {$ret.add(v);} )* diff --git a/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/MetadataRpcController.java b/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/MetadataRpcController.java index 617584bb6f7..c86552d40ea 100644 --- a/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/MetadataRpcController.java +++ b/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/MetadataRpcController.java @@ -42,6 +42,8 @@ class MetadataRpcController extends DelegatingHBaseRpcController { .add(PhoenixDatabaseMetaData.SYSTEM_SEQUENCE_NAME) .add(PhoenixDatabaseMetaData.SYSTEM_FUNCTION_NAME) .add(PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_NAME) + .add(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME) + .add(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES, true) .getNameAsString()) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_STATS_NAME_BYTES, true) @@ -52,6 +54,12 @@ class MetadataRpcController extends DelegatingHBaseRpcController { .getNameAsString()) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_NAME_BYTES, true) .getNameAsString()) + .add(SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, true) + .getNameAsString()) + .add(SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES, true) + .getNameAsString()) .build(); public MetadataRpcController(HBaseRpcController delegate, Configuration conf) { diff --git a/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/ServerRpcController.java b/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/ServerRpcController.java index 737aa8ee06e..d43ff5f76be 100644 --- a/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/ServerRpcController.java +++ b/phoenix-core-client/src/main/java/org/apache/hadoop/hbase/ipc/controller/ServerRpcController.java @@ -42,6 +42,8 @@ class ServerRpcController extends DelegatingHBaseRpcController { .add(PhoenixDatabaseMetaData.SYSTEM_SEQUENCE_NAME) .add(PhoenixDatabaseMetaData.SYSTEM_FUNCTION_NAME) .add(PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_NAME) + .add(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME) + .add(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES, true) .getNameAsString()) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_STATS_NAME_BYTES, true) @@ -52,6 +54,12 @@ class ServerRpcController extends DelegatingHBaseRpcController { .getNameAsString()) .add(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_NAME_BYTES, true) .getNameAsString()) + .add(SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, true) + .getNameAsString()) + .add(SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES, true) + .getNameAsString()) .build(); ServerRpcController(HBaseRpcController delegate, Configuration conf) { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/FromCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/FromCompiler.java index 6ffaf9eb002..561722ca9e8 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/FromCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/FromCompiler.java @@ -49,6 +49,7 @@ import org.apache.phoenix.parse.PSchema; import org.apache.phoenix.parse.ParseNode; import org.apache.phoenix.parse.ParseNodeFactory; +import org.apache.phoenix.parse.ProtoValueParseNode; import org.apache.phoenix.parse.SelectStatement; import org.apache.phoenix.parse.SingleTableStatement; import org.apache.phoenix.parse.TableName; @@ -306,18 +307,23 @@ public static ColumnResolver getResolverForCreateIndex(SingleTableStatement stat } public static ColumnResolver getResolverForCompiledDerivedTable(PhoenixConnection connection, - TableRef tableRef, RowProjector projector) throws SQLException { + TableRef tableRef, QueryPlan innerPlan) throws SQLException { + RowProjector projector = innerPlan.getProjector(); + ColumnResolver innerResolver = innerPlan.getContext().getResolver(); List projectedColumns = new ArrayList(); PTable table = tableRef.getTable(); for (PColumn column : table.getColumns()) { Expression sourceExpression = projector.getColumnProjector(column.getPosition()).getExpression(); + // Derived-table columns are untyped placeholders; the descriptor binding lives on the source. + PColumn source = ProtoValueParseNode.resolveSourceColumn(innerResolver, sourceExpression); PColumnImpl projectedColumn = new PColumnImpl(column.getName(), column.getFamilyName(), sourceExpression.getDataType(), sourceExpression.getMaxLength(), sourceExpression.getScale(), sourceExpression.isNullable(), column.getPosition(), sourceExpression.getSortOrder(), column.getArraySize(), column.getViewConstant(), column.isViewReferenced(), column.getExpressionStr(), column.isRowTimestamp(), - column.isDynamic(), column.getColumnQualifierBytes(), column.getTimestamp()); + column.isDynamic(), column.getColumnQualifierBytes(), column.getTimestamp(), false, + source == null ? null : source.getProtoMessageName()); projectedColumns.add(projectedColumn); } PTable t = PTableImpl.builderWithColumns(table, projectedColumns).build(); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/JoinCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/JoinCompiler.java index 9c6f71f0fd7..876f135d262 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/JoinCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/JoinCompiler.java @@ -1154,11 +1154,11 @@ public PTable createProjectedTable(boolean retainPKColumns, StatementContext con return TupleProjectionCompiler.createProjectedTable(tableRef, sourceColumns, retainPKColumns); } - public PTable createProjectedTable(RowProjector rowProjector) throws SQLException { + public PTable createProjectedTable(QueryPlan subqueryPlan) throws SQLException { assert (isSubselect()); TableRef tableRef = FromCompiler.getResolverForCompiledDerivedTable(phoenixStatement.getConnection(), - this.tableRef, rowProjector).getTables().get(0); + this.tableRef, subqueryPlan).getTables().get(0); List sourceColumns = new ArrayList(); PTable table = tableRef.getTable(); for (PColumn column : table.getColumns()) { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/QueryCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/QueryCompiler.java index f501ece90cb..a019dda7c4e 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/QueryCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/QueryCompiler.java @@ -378,7 +378,7 @@ protected QueryPlan compileJoinQuery(StatementContext context, JoinTable joinTab false); } QueryPlan plan = compileSubquery(subquery, false); - PTable projectedTable = table.createProjectedTable(plan.getProjector()); + PTable projectedTable = table.createProjectedTable(plan); context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), subquery.getUdfParseNodes())); return new TupleProjectionPlan(plan, new TupleProjector(plan.getProjector()), context, null); @@ -436,7 +436,7 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo } else { SelectStatement subquery = table.getAsSubquery(orderBy); QueryPlan plan = compileSubquery(subquery, false); - initialProjectedTable = table.createProjectedTable(plan.getProjector()); + initialProjectedTable = table.createProjectedTable(plan); tableRef = plan.getTableRef(); context.getScan().setFamilyMap(plan.getContext().getScan().getFamilyMap()); query = joinTable.getAsSingleSubquery((SelectStatement) plan.getStatement(), asSubquery); @@ -541,7 +541,7 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo } else { SelectStatement subquery = rhsTable.getAsSubquery(orderBy); QueryPlan plan = compileSubquery(subquery, false); - rhsProjTable = rhsTable.createProjectedTable(plan.getProjector()); + rhsProjTable = rhsTable.createProjectedTable(plan); rhsTableRef = plan.getTableRef(); context.getScan().setFamilyMap(plan.getContext().getScan().getFamilyMap()); rhs = rhsJoinTable.getAsSingleSubquery((SelectStatement) plan.getStatement(), asSubquery); @@ -771,8 +771,8 @@ protected QueryPlan compileSingleQuery(StatementContext context, SelectStatement // Replace the original resolver and table with those having compiled type info. TableRef tableRef = context.getResolver().getTables().get(0); - ColumnResolver resolver = FromCompiler.getResolverForCompiledDerivedTable( - statement.getConnection(), tableRef, innerQueryPlanRowProjector); + ColumnResolver resolver = FromCompiler + .getResolverForCompiledDerivedTable(statement.getConnection(), tableRef, innerPlan); context.setResolver(resolver); tableRef = resolver.getTables().get(0); context.setCurrentTable(tableRef); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/UnionCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/UnionCompiler.java index 646d1cd5873..c4256cf6c80 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/UnionCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/UnionCompiler.java @@ -37,6 +37,7 @@ import org.apache.phoenix.jdbc.PhoenixStatement; import org.apache.phoenix.parse.AliasedNode; import org.apache.phoenix.parse.OrderByNode; +import org.apache.phoenix.parse.ProtoValueParseNode; import org.apache.phoenix.parse.SelectStatement; import org.apache.phoenix.schema.PColumn; import org.apache.phoenix.schema.PColumnImpl; @@ -92,11 +93,12 @@ public static TableRef contructSchemaTable(PhoenixStatement statement, List plans, int i) { + String common = null; + for (QueryPlan plan : plans) { + PColumn source = ProtoValueParseNode.resolveSourceColumn(plan.getContext().getResolver(), + plan.getProjector().getColumnProjector(i).getExpression()); + String name = source == null ? null : source.getProtoMessageName(); + if (name == null || common != null && !common.equals(name)) { + return null; + } + common = name; + } + return common; + } + @SuppressWarnings("rawtypes") private static void compareExperssions(int i, Expression expression, List targetTypes) throws SQLException { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/MetaDataProtocol.java b/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/MetaDataProtocol.java index 08cac7cbe9a..144ca3ce911 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/MetaDataProtocol.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/MetaDataProtocol.java @@ -92,7 +92,7 @@ public abstract class MetaDataProtocol extends MetaDataService { public static final long MIN_SYSTEM_TABLE_TIMESTAMP_5_1_0 = MIN_SYSTEM_TABLE_TIMESTAMP_4_16_0; public static final long MIN_SYSTEM_TABLE_TIMESTAMP_5_2_0 = MIN_TABLE_TIMESTAMP + 38; public static final long MIN_SYSTEM_TABLE_TIMESTAMP_5_3_0 = MIN_TABLE_TIMESTAMP + 44; - public static final long MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 = MIN_TABLE_TIMESTAMP + 45; + public static final long MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 = MIN_TABLE_TIMESTAMP + 46; // MIN_SYSTEM_TABLE_TIMESTAMP needs to be set to the max of all the MIN_SYSTEM_TABLE_TIMESTAMP_* // constants public static final long MIN_SYSTEM_TABLE_TIMESTAMP = MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0; @@ -193,6 +193,8 @@ public enum MutationCode { UNABLE_TO_DELETE_CHILD_LINK, UNABLE_TO_UPSERT_TASK, ERROR_WRITING_TO_SCHEMA_REGISTRY, + UNABLE_TO_WRITE_PROTO_DESC_LINK, + PROTO_DESCRIPTOR_NOT_FOUND, NO_OP, } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java index 3eddf2278fe..a2e47bc0948 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java @@ -483,6 +483,98 @@ public SQLException newException(SQLExceptionInfo info) { "CDC on this table is either enabled or is in the process of being enabled."), CANNOT_SET_OR_ALTER_MAX_LOOKBACK_FOR_INDEX(10964, "44A46", "Cannot set or alter " + PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY + " on an index"), + PROTOBUF_NOT_ALLOWED_AS_PRIMARY_KEY(10965, "44A47", + "PROTOBUF columns cannot be used as primary key columns at any position."), + PROTOBUF_DESCRIPTOR_NOT_FOUND(10966, "44A48", + "The referenced PROTOBUF descriptor is not registered."), + PROTOBUF_FROM_STRING_NOT_ALLOWED(10967, "44A49", + "PROTOBUF columns cannot be set from a String value."), + PROTOBUF_MESSAGE_NAME_REQUIRED(10968, "44A4A", + "PROTOBUF columns require a fully-qualified message name between angle brackets."), + PROTOBUF_NOT_ALLOWED_IN_ARRAY(10969, "44A4B", "PROTOBUF columns cannot be declared as arrays."), + PROTOBUF_DESCRIPTOR_FETCH_FAILED(10970, "44A4C", + "Failed to fetch the FileDescriptorSet bytes from the URL."), + PROTOBUF_DESCRIPTOR_PARSE_FAILED(10971, "44A4D", + "Failed to parse the FROM URL bytes as a google.protobuf.FileDescriptorSet."), + PROTOBUF_DESCRIPTOR_ALREADY_EXISTS(10972, "44A4E", + "A PROTOBUF descriptor with this name is already registered."), + PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE(10973, "44A4F", + "No matching top-level message in the loaded FileDescriptorSet for the declared " + + "PROTOBUF descriptor name(s)."), + PROTOBUF_DESCRIPTOR_IN_USE(10974, "44A4G", + "Cannot DROP this PROTOBUF descriptor because it is still referenced by at least one column."), + PROTOBUF_DESCRIPTOR_INCOMPATIBLE_EVOLUTION(10975, "44A4H", + "ALTER PROTOBUF DESCRIPTOR was rejected by the evolution validator."), + PROTOBUF_DESCRIPTOR_INTERNAL_ERROR(10976, "44A4I", + "An unexpected server-side error occurred while handling a PROTOBUF descriptor DDL " + + "operation."), + PROTOBUF_REMOVAL_NOT_SUPPORTED(10977, "44A4J", + "PROTOBUF evolution rejected: a field, message, enum, or enum value present in the " + + "old descriptor is absent from the new descriptor."), + PROTOBUF_FIELD_RENAMED(10978, "44A4K", + "PROTOBUF evolution rejected: a field's tag number is unchanged but its name changed."), + PROTOBUF_TAG_RENAMED(10979, "44A4L", + "PROTOBUF evolution rejected: a field's name is unchanged but its tag number changed."), + PROTOBUF_INCOMPATIBLE_TYPE_CHANGE(10980, "44A4M", + "PROTOBUF evolution rejected: a field's type changed."), + PROTOBUF_INCOMPATIBLE_CARDINALITY_CHANGE(10981, "44A4N", + "PROTOBUF evolution rejected: a field's cardinality changed."), + PROTOBUF_ONEOF_MEMBERSHIP_CHANGE(10982, "44A4O", + "PROTOBUF evolution rejected: an existing field moved into or out of an existing oneof."), + PROTOBUF_PACKED_ENCODING_CHANGE(10983, "44A4P", + "PROTOBUF evolution rejected: a repeated field's [packed] annotation was added or " + + "removed."), + // 10984 unused so later PROTOBUF evolution codes keep their assigned numbers. + PROTOBUF_PACKAGE_CHANGED(10985, "44A4R", + "PROTOBUF evolution rejected: the descriptor's containing-file 'package' declaration " + + "changed."), + // 10986 unused so later PROTOBUF evolution codes keep their assigned numbers. + PROTOBUF_ENUM_VALUE_RENAMED(10987, "44A4T", + "PROTOBUF evolution rejected: an enum value's tag is unchanged but its name changed."), + PROTOBUF_ENUM_VALUE_RENUMBERED(10988, "44A4U", + "PROTOBUF evolution rejected: an enum value's name is unchanged but its tag changed."), + PROTOBUF_ENUM_TAG_REUSE(10989, "44A4V", + "PROTOBUF evolution rejected: a new enum value uses a tag number already in use by a " + + "different value name in the same enum."), + // 10990 unused so later PROTOBUF evolution codes keep their assigned numbers. + PROTOBUF_TAG_RESERVED(10991, "44A4X", + "PROTOBUF evolution rejected: a new field's tag number falls in a 'reserved' range."), + PROTOBUF_NAME_RESERVED(10992, "44A4Y", + "PROTOBUF evolution rejected: a new field's name appears in a 'reserved' name list."), + PROTOBUF_RESERVE_OF_LIVE_TAG(10993, "44A4Z", + "PROTOBUF evolution rejected: a new 'reserved' clause covers a tag number currently " + + "used by a live field."), + PROTOBUF_RESERVE_OF_LIVE_NAME(10994, "44A50", + "PROTOBUF evolution rejected: a new 'reserved' clause covers a name currently used " + + "by a live field."), + PROTOBUF_SYNTAX_CHANGED(10995, "44A51", + "PROTOBUF evolution rejected: the descriptor's 'syntax' or 'edition' declaration " + + "changed."), + UNABLE_TO_WRITE_PROTO_DESC_LINK(10996, "44A52", + "Error writing SYSTEM.PROTO_DESC_LINK rows for the PROTOBUF columns; retry the DDL."), + PROTOBUF_PATH_SYNTAX_ERROR(10997, "44A53", "PROTO_VALUE path literal has invalid syntax."), + PROTOBUF_PATH_FIELD_NOT_FOUND(10998, "44A54", + "PROTO_VALUE path segment does not name any field in the descriptor."), + PROTOBUF_PATH_CARDINALITY_MISMATCH(10999, "44A55", + "PROTO_VALUE path segment applies bracket-index or dot-navigation to a field of " + + "incompatible cardinality."), + PROTOBUF_VALUE_TYPE_MISMATCH(11000, "44A56", + "PROTO_VALUE cannot coerce the leaf field's type to the requested SQL type."), + PROTOBUF_PATH_UNSUPPORTED_FEATURE(11002, "44A58", + "PROTO_VALUE path uses a protobuf feature that is not supported."), + PROTOBUF_VALUE_TYPE_NARROWING_NOT_PERMITTED(11003, "44A59", + "PROTO_VALUE requested SQL type is narrower than the field's default; only " + + "widening casts are allowed."), + PROTOBUF_TAG_PATH_INVALID_SYNTAX(11004, "44A5A", + "PROTO_VALUE_AT_TAG tag-path literal has invalid syntax."), + PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED(11005, "44A5B", + "Protobuf descriptor FROM URL must be a local file:/// URL."), + PROTOBUF_BUNDLE_TOO_LARGE(11006, "44A5C", + "CREATE PROTOBUF BUNDLE exceeds the total size cap; split it or use fewer names."), + PROTOBUF_MESSAGE_NAME_NOT_ALLOWED(11007, "44A5D", + "A message name between angle brackets is only allowed on PROTOBUF columns."), + PROTOBUF_DEFAULT_VALUE_CHANGE(11008, "44A5E", + "PROTOBUF evolution rejected: a field's default value changed."), /** Sequence related */ SEQUENCE_ALREADY_EXIST(1200, "42Z00", "Sequence already exists.", new Factory() { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/ExpressionType.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/ExpressionType.java index 6b280cf9de4..77fd97285ac 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/ExpressionType.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/ExpressionType.java @@ -211,7 +211,12 @@ public enum ExpressionType { RawRowSizeFunction(RawRowSizeFunction.class), RegexpLikeFunction(RegexpLikeFunction.class), ByteBasedRegexpLikeFunction(ByteBasedRegexpLikeFunction.class), - StringBasedRegexpLikeFunction(StringBasedRegexpLikeFunction.class); + StringBasedRegexpLikeFunction(StringBasedRegexpLikeFunction.class), + ProtoValueFunction(ProtoValueFunction.class), + ProtoExistsFunction(ProtoExistsFunction.class), + ProtoArrayLengthFunction(ProtoArrayLengthFunction.class), + ProtoFieldTypeFunction(ProtoFieldTypeFunction.class), + ProtoValueAtTagFunction(ProtoValueAtTagFunction.class); ExpressionType(Class clazz) { this.clazz = clazz; diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java new file mode 100644 index 00000000000..20efe3cb7e0 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java @@ -0,0 +1,134 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.io.DataInput; +import java.io.IOException; +import java.sql.SQLException; +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.expression.util.proto.ProtoPathResolver; +import org.apache.phoenix.expression.util.proto.ProtoPathWalker; +import org.apache.phoenix.parse.FunctionParseNode; +import org.apache.phoenix.parse.ProtoArrayLengthParseNode; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarchar; + +/** + * {@code PROTO_ARRAY_LENGTH(payload, path)} — returns the count of elements in a repeated field or + * entries in a map at the given path. Returns 0 when the ancestor container is not present + * (child-of-unset-parent) or the target field has zero occurrences. + */ +@FunctionParseNode.BuiltInFunction(name = ProtoArrayLengthFunction.NAME, + nodeClass = ProtoArrayLengthParseNode.class, + args = { @FunctionParseNode.Argument(allowedTypes = { PProtobuf.class, PVarbinary.class }), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), }) +public class ProtoArrayLengthFunction extends ScalarFunction { + + public static final String NAME = "PROTO_ARRAY_LENGTH"; + + private volatile PathPlan cachedPlan; + private final ProtoDescriptorRegistry registry; + + public ProtoArrayLengthFunction() { + this.registry = null; + } + + public ProtoArrayLengthFunction(List children) { + this(children, null); + } + + /** @param registry the compiling connection's; {@code null} falls back to the per-JVM one */ + public ProtoArrayLengthFunction(List children, ProtoDescriptorRegistry registry) { + super(children); + this.registry = registry; + } + + @Override + public ProtoArrayLengthFunction clone(List children) { + return new ProtoArrayLengthFunction(children, registry); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public PDataType getDataType() { + return PInteger.INSTANCE; + } + + @Override + public void readFields(DataInput input) throws IOException { + super.readFields(input); + this.cachedPlan = null; + } + + @Override + public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { + if (!ProtoFunctionsUtil.evaluatePayload(getChildren().get(0), tuple, ptr)) { + return false; + } + byte[] buf = ptr.get(); + int offset = ptr.getOffset(); + int length = ptr.getLength(); + + PathPlan plan; + try { + plan = ensurePlan(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + + int count; + try { + count = ProtoPathWalker.walkForCount(buf, offset, length, plan); + } catch (IOException e) { + ptr.set(PInteger.INSTANCE.toBytes(0)); + return true; + } + ptr.set(PInteger.INSTANCE.toBytes(count)); + return true; + } + + public PathPlan ensurePlan() throws SQLException { + PathPlan snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + synchronized (this) { + snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + PathPlan plan = ProtoFunctionsUtil.compilePathPlan(getChildren(), NAME, registry, + ProtoDescriptorRegistry.PlanKind.ARRAY_LENGTH, null, + ProtoPathResolver::resolveForArrayLength); + cachedPlan = plan; + return plan; + } + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java new file mode 100644 index 00000000000..d4394326921 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.io.DataInput; +import java.io.IOException; +import java.sql.SQLException; +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.expression.util.proto.ProtoPathResolver; +import org.apache.phoenix.expression.util.proto.ProtoPathWalker; +import org.apache.phoenix.parse.FunctionParseNode; +import org.apache.phoenix.parse.ProtoExistsParseNode; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarchar; + +/** + * {@code PROTO_EXISTS(payload, path)} — returns TRUE if the leaf at the given path is set on the + * wire; FALSE for absent leaves (proto3 implicit defaults, unset optional / proto2, missing map + * keys, past-end indices, child-of-unset-parent, malformed payloads); SQL NULL only when the + * payload column value itself is SQL NULL. + */ +@FunctionParseNode.BuiltInFunction(name = ProtoExistsFunction.NAME, + nodeClass = ProtoExistsParseNode.class, + args = { @FunctionParseNode.Argument(allowedTypes = { PProtobuf.class, PVarbinary.class }), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), }) +public class ProtoExistsFunction extends ScalarFunction { + + public static final String NAME = "PROTO_EXISTS"; + + private volatile PathPlan cachedPlan; + private final ProtoDescriptorRegistry registry; + + public ProtoExistsFunction() { + this.registry = null; + } + + public ProtoExistsFunction(List children) { + this(children, null); + } + + /** @param registry the compiling connection's; {@code null} falls back to the per-JVM one */ + public ProtoExistsFunction(List children, ProtoDescriptorRegistry registry) { + super(children); + this.registry = registry; + } + + @Override + public ProtoExistsFunction clone(List children) { + return new ProtoExistsFunction(children, registry); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public PDataType getDataType() { + return PBoolean.INSTANCE; + } + + @Override + public void readFields(DataInput input) throws IOException { + super.readFields(input); + this.cachedPlan = null; + } + + @Override + public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { + if (!ProtoFunctionsUtil.evaluatePayload(getChildren().get(0), tuple, ptr)) { + return false; + } + // Walk the payload in place; ptr is overwritten only after the walk returns. + byte[] buf = ptr.get(); + int offset = ptr.getOffset(); + int length = ptr.getLength(); + + PathPlan plan; + try { + plan = ensurePlan(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + + Object leaf; + try { + leaf = ProtoPathWalker.walk(buf, offset, length, plan); + } catch (IOException e) { + // Malformed payload (incl. index-compile dummy-UPSERT probe) → FALSE. + ptr.set(PBoolean.INSTANCE.toBytes(false)); + return true; + } + boolean present = leaf != null && leaf != ProtoPathWalker.LEAF_ABSENT; + ptr.set(PBoolean.INSTANCE.toBytes(present)); + return true; + } + + public PathPlan ensurePlan() throws SQLException { + PathPlan snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + synchronized (this) { + snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + PathPlan plan = ProtoFunctionsUtil.compilePathPlan(getChildren(), NAME, registry, + ProtoDescriptorRegistry.PlanKind.PRESENCE, null, ProtoPathResolver::resolveForExistence); + cachedPlan = plan; + return plan; + } + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFieldTypeFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFieldTypeFunction.java new file mode 100644 index 00000000000..868b3fff5ec --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFieldTypeFunction.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.parse.FunctionParseNode; +import org.apache.phoenix.parse.ProtoFieldTypeParseNode; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarchar; + +/** + * {@code PROTO_FIELD_TYPE(payload, path)} — returns the Phoenix SQL type name for the leaf at the + * given path. + */ +@FunctionParseNode.BuiltInFunction(name = ProtoFieldTypeFunction.NAME, + nodeClass = ProtoFieldTypeParseNode.class, + args = { @FunctionParseNode.Argument(allowedTypes = { PProtobuf.class, PVarbinary.class }), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), }) +public class ProtoFieldTypeFunction extends ScalarFunction { + + public static final String NAME = "PROTO_FIELD_TYPE"; + + public ProtoFieldTypeFunction() { + } + + public ProtoFieldTypeFunction(List children) { + super(children); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public PDataType getDataType() { + return PVarchar.INSTANCE; + } + + @Override + public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { + return getChildren().get(getChildren().size() - 1).evaluate(tuple, ptr); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFunctionsUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFunctionsUtil.java new file mode 100644 index 00000000000..8d1e8404585 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoFunctionsUtil.java @@ -0,0 +1,271 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.LiteralExpression; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.expression.util.proto.ProtoPathParser; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PDouble; +import org.apache.phoenix.schema.types.PFloat; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PUnsignedInt; +import org.apache.phoenix.schema.types.PUnsignedLong; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarbinaryEncoded; +import org.apache.phoenix.schema.types.PVarchar; +import org.apache.phoenix.util.ByteUtil; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +/** + * Shared helpers for the PROTO_* SQL functions and their parse nodes. + */ +public final class ProtoFunctionsUtil { + + private ProtoFunctionsUtil() { + } + + /** Resolves a parsed name path against a descriptor into a {@link PathPlan}. */ + @FunctionalInterface + interface PathResolver { + PathPlan resolve(List parsed, Descriptors.Descriptor descriptor, + String pathLiteral) throws SQLException; + } + + /** + * Returns the value of {@code child} as a string, or throws if it is not a non-null literal. + * {@code label} names the argument in the error message. + */ + public static String requiredStringLiteral(Expression child, String functionName, String label) + throws SQLException { + if (!(child instanceof LiteralExpression)) { + throw typeMismatch(functionName + " " + label + " must be a string literal"); + } + Object value = ((LiteralExpression) child).getValue(); + if (value == null) { + throw typeMismatch(functionName + " " + label + " must be non-null"); + } + return value.toString(); + } + + /** Looks up a registered descriptor, or throws if it is not registered. */ + public static ProtoDescriptorRegistry.CachedDescriptor + lookupDescriptor(ProtoDescriptorRegistry registry, String descriptorName, String functionName) + throws SQLException { + ProtoDescriptorRegistry.CachedDescriptor cached = registry.lookup(descriptorName); + if (cached == null) { + throw new SQLExceptionInfo.Builder( + SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE) + .setMessage(functionName + ": descriptor '" + descriptorName + + "' not registered in SYSTEM.PROTO_DESCRIPTORS") + .build().buildException(); + } + return cached; + } + + /** Returns {@code children} with the descriptor name appended as a VARCHAR literal. */ + public static List withDescriptorName(List children, + String descriptorName) throws SQLException { + List augmented = new ArrayList<>(children.size() + 1); + augmented.addAll(children); + augmented.add(LiteralExpression.newConstant(descriptorName, PVarchar.INSTANCE)); + return augmented; + } + + /** + * Compiles (or fetches from the registry's plan cache) the name-path plan for a function whose + * children are {@code (payload, path, ..., descriptorName)}. + */ + static PathPlan compilePathPlan(List children, String functionName, + ProtoDescriptorRegistry registry, ProtoDescriptorRegistry.PlanKind kind, + PDataType requestedType, PathResolver resolver) throws SQLException { + String descriptorName = + requiredStringLiteral(children.get(children.size() - 1), functionName, "descriptor name"); + String pathLiteral = requiredStringLiteral(children.get(1), functionName, "path"); + return withDescriptorRefreshOnMiss( + registry != null ? registry : ProtoDescriptorRegistryHolder.get(), descriptorName, + functionName, + cached -> cached.getOrCompilePathPlan(pathLiteral, kind, requestedType, descriptor -> resolver + .resolve(ProtoPathParser.parse(pathLiteral), descriptor, pathLiteral))); + } + + /** + * Work done against a looked-up descriptor; see {@link #withDescriptorRefreshOnMiss}. + * @param the result type of the action + */ + @FunctionalInterface + public interface DescriptorAction { + T apply(ProtoDescriptorRegistry.CachedDescriptor cached) throws SQLException; + } + + /** + * Looks up {@code descriptorName} and runs {@code action} against it. If that fails in a way a + * newer descriptor could fix (see {@link #isPossiblyStaleDescriptorError}), forces one reload + * from {@code SYSTEM.PROTO_DESCRIPTORS} and retries once. + *

+ * The cached descriptor may predate a CREATE/ALTER run by another client and not have reached its + * TTL yet. Protobuf Descriptor Evolution is add-only, so one reload resolves any legitimately new + * field. The registry rate-limits forced reloads per name, so a genuinely bad path does not + * reload the descriptor on every attempt. + */ + public static T withDescriptorRefreshOnMiss(ProtoDescriptorRegistry registry, + String descriptorName, String functionName, DescriptorAction action) throws SQLException { + try { + return action.apply(lookupDescriptor(registry, descriptorName, functionName)); + } catch (SQLException e) { + if (!isPossiblyStaleDescriptorError(e) || !registry.tryForceRefresh(descriptorName)) { + throw e; + } + return action.apply(lookupDescriptor(registry, descriptorName, functionName)); + } + } + + static boolean isPossiblyStaleDescriptorError(SQLException e) { + int code = e.getErrorCode(); + return code == SQLExceptionCode.PROTOBUF_PATH_FIELD_NOT_FOUND.getErrorCode() + || code == SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE.getErrorCode(); + } + + /** + * Evaluates the payload argument into {@code ptr}. Returns false when it cannot be evaluated yet + * or is empty (the function then returns false). On true, the caller walks the payload in place + * via {@code ptr.get()/getOffset()/getLength()} and must read those before writing its own result + * into {@code ptr}. + */ + static boolean evaluatePayload(Expression payloadArg, Tuple tuple, ImmutableBytesWritable ptr) { + return payloadArg.evaluate(tuple, ptr) && ptr != null && ptr.getLength() != 0; + } + + /** + * Writes the user-supplied default (argument 3) into {@code ptr}, converted to the requested type + * at compile time by {@link #withCompiledDefault}, or SQL NULL when there is no default. + */ + static boolean returnDefaultOrNull(List children, boolean hasDefaultArg, + ImmutableBytesWritable ptr) { + if (!hasDefaultArg) { + return setNull(ptr); + } + children.get(3).evaluate(null, ptr); + return true; + } + + static boolean setNull(ImmutableBytesWritable ptr) { + ptr.set(ByteUtil.EMPTY_BYTE_ARRAY); + return true; + } + + /** Resolves a requested SQL type name, or throws if it is unknown. */ + public static PDataType resolveSqlType(String typeName, String functionName) + throws SQLException { + PDataType type; + try { + type = PDataType.fromSqlTypeName(typeName); + } catch (RuntimeException e) { + type = null; + } + if (type == null) { + throw typeMismatch(functionName + ": unknown SQL type '" + typeName + "'"); + } + return type; + } + + /** + * Returns the first three of {@code children} plus, when {@code userSuppliedDefault} is true, the + * default (argument 3) converted to the requested SQL type (argument 2). A {@code null} or + * {@code 'null'} default becomes a typed null literal. + * @throws SQLException if the default is not a literal or cannot be read as the requested type + */ + public static List withCompiledDefault(List children, + boolean userSuppliedDefault, String functionName) throws SQLException { + List compiled = new ArrayList<>(children.subList(0, 3)); + if (!userSuppliedDefault) { + return compiled; + } + PDataType requestedType = resolveSqlType( + requiredStringLiteral(children.get(2), functionName, "SQL type"), functionName); + Expression defaultChild = children.get(3); + if (!(defaultChild instanceof LiteralExpression)) { + throw typeMismatch(functionName + " default must be a string literal"); + } + Object value = ((LiteralExpression) defaultChild).getValue(); + String s = value == null ? null : value.toString(); + Object converted = + s == null || "null".equalsIgnoreCase(s) ? null : parseDefault(s, requestedType, functionName); + compiled.add(LiteralExpression.newConstant(converted, requestedType)); + return compiled; + } + + private static Object parseDefault(String s, PDataType requestedType, String functionName) + throws SQLException { + if (requestedType == PVarchar.INSTANCE) { + return s; + } + if (requestedType == PVarbinary.INSTANCE || requestedType == PVarbinaryEncoded.INSTANCE) { + return s.getBytes(StandardCharsets.UTF_8); + } + if (requestedType == PBoolean.INSTANCE) { + if ("true".equalsIgnoreCase(s)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(s)) { + return Boolean.FALSE; + } + throw badDefault(s, requestedType, functionName); + } + if ( + requestedType == PInteger.INSTANCE || requestedType == PLong.INSTANCE + || requestedType == PUnsignedInt.INSTANCE || requestedType == PUnsignedLong.INSTANCE + || requestedType == PFloat.INSTANCE || requestedType == PDouble.INSTANCE + || requestedType == PDecimal.INSTANCE + ) { + try { + return requestedType.toObject(s); + } catch (RuntimeException e) { + throw badDefault(s, requestedType, functionName); + } + } + throw typeMismatch( + functionName + " does not support a default for SQL type " + requestedType.getSqlTypeName()); + } + + private static SQLException badDefault(String s, PDataType requestedType, + String functionName) { + return typeMismatch(functionName + " default '" + s + "' is not a valid " + + requestedType.getSqlTypeName() + " value"); + } + + private static SQLException typeMismatch(String message) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage(message).build().buildException(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java new file mode 100644 index 00000000000..f83011a8fa7 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.io.DataInput; +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.LiteralExpression; +import org.apache.phoenix.expression.util.proto.ProtoTagPathParser; +import org.apache.phoenix.expression.util.proto.ProtoTagPathWalker; +import org.apache.phoenix.expression.util.proto.TagPathPlan; +import org.apache.phoenix.parse.FunctionParseNode; +import org.apache.phoenix.parse.ProtoValueAtTagParseNode; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PDouble; +import org.apache.phoenix.schema.types.PFloat; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PUnsignedInt; +import org.apache.phoenix.schema.types.PUnsignedLong; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarbinaryEncoded; +import org.apache.phoenix.schema.types.PVarchar; + +/** + * {@code PROTO_VALUE_AT_TAG(payload, tagPath, sqlType[, default])} — extracts a leaf value from raw + * protobuf wire bytes at the given tag-number path, decoded as the requested SQL type. Schema-less: + * no descriptor registration required. + */ +@FunctionParseNode.BuiltInFunction(name = ProtoValueAtTagFunction.NAME, + nodeClass = ProtoValueAtTagParseNode.class, + args = { @FunctionParseNode.Argument(allowedTypes = { PProtobuf.class, PVarbinary.class }), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true, + defaultValue = ProtoValueAtTagFunction.DEFAULT_VALUE), }) +public class ProtoValueAtTagFunction extends ScalarFunction { + + public static final String NAME = "PROTO_VALUE_AT_TAG"; + + static final String DEFAULT_VALUE = "null"; + + private volatile TagPathPlan cachedPlan; + + public ProtoValueAtTagFunction() { + } + + public ProtoValueAtTagFunction(List children) { + super(children); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public PDataType getDataType() { + String dataType = (String) ((LiteralExpression) getChildren().get(2)).getValue(); + return PDataType.fromSqlTypeName(dataType); + } + + @Override + public void readFields(DataInput input) throws IOException { + super.readFields(input); + this.cachedPlan = null; + } + + @Override + public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { + if (!ProtoFunctionsUtil.evaluatePayload(getChildren().get(0), tuple, ptr)) { + return false; + } + // Walk the payload in place; ptr is overwritten only after the walk returns. + byte[] buf = ptr.get(); + int offset = ptr.getOffset(); + int length = ptr.getLength(); + + TagPathPlan plan; + try { + plan = ensurePlan(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + + Object leaf; + try { + leaf = ProtoTagPathWalker.walk(buf, offset, length, plan); + } catch (IOException e) { + return returnDefaultOrNull(ptr); + } + + if (leaf == null) { + return returnDefaultOrNull(ptr); + } + byte[] out = coerceLeaf(leaf, plan.getRequestedType()); + if (out == null) { + // The value is present but does not fit the requested type, so the default must not apply. + return ProtoFunctionsUtil.setNull(ptr); + } + ptr.set(out); + return true; + } + + private TagPathPlan ensurePlan() throws SQLException { + TagPathPlan snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + synchronized (this) { + snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + String pathLiteral = + ProtoFunctionsUtil.requiredStringLiteral(getChildren().get(1), NAME, "tag-path"); + String typeName = + ProtoFunctionsUtil.requiredStringLiteral(getChildren().get(2), NAME, "SQL type"); + PDataType reqType = ProtoFunctionsUtil.resolveSqlType(typeName, NAME); + int wireType = ProtoTagPathWalker.wireTypeForSqlType(reqType); + if (wireType < 0) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage("PROTO_VALUE_AT_TAG: unsupported SQL type '" + typeName + "'").build() + .buildException(); + } + List segments = ProtoTagPathParser.parse(pathLiteral); + TagPathPlan plan = new TagPathPlan(Collections.unmodifiableList(segments), reqType, wireType); + cachedPlan = plan; + return plan; + } + } + + private boolean returnDefaultOrNull(ImmutableBytesWritable ptr) { + return ProtoFunctionsUtil.returnDefaultOrNull(getChildren(), getChildren().size() > 3, ptr); + } + + private static byte[] coerceLeaf(Object leaf, PDataType requestedType) { + if (leaf == null) { + return null; + } + if (requestedType == PVarchar.INSTANCE) { + if (leaf instanceof String) { + return PVarchar.INSTANCE.toBytes(leaf); + } + if (leaf instanceof byte[]) { + return PVarchar.INSTANCE.toBytes(Bytes.toString((byte[]) leaf)); + } + return PVarchar.INSTANCE.toBytes(leaf.toString()); + } + if (requestedType == PBoolean.INSTANCE && leaf instanceof Boolean) { + return PBoolean.INSTANCE.toBytes(leaf); + } + if (requestedType == PInteger.INSTANCE) { + if (leaf instanceof Integer) { + return PInteger.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Long) { + long v = (Long) leaf; + if (v > Integer.MAX_VALUE || v < Integer.MIN_VALUE) { + return null; + } + return PInteger.INSTANCE.toBytes((int) v); + } + } + if (requestedType == PLong.INSTANCE) { + if (leaf instanceof Long) { + return PLong.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Integer) { + return PLong.INSTANCE.toBytes(((Integer) leaf).longValue()); + } + } + if (requestedType == PUnsignedInt.INSTANCE) { + if (leaf instanceof Integer) { + return PUnsignedInt.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Long) { + long v = (Long) leaf; + if (v < 0 || v > Integer.MAX_VALUE) { + return null; + } + return PUnsignedInt.INSTANCE.toBytes((int) v); + } + } + if (requestedType == PUnsignedLong.INSTANCE) { + if (leaf instanceof Long) { + long v = (Long) leaf; + if (v < 0) { + return null; + } + return PUnsignedLong.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Integer) { + return PUnsignedLong.INSTANCE.toBytes(((Integer) leaf).longValue()); + } + } + if (requestedType == PFloat.INSTANCE && leaf instanceof Float) { + return PFloat.INSTANCE.toBytes(leaf); + } + if (requestedType == PDouble.INSTANCE) { + if (leaf instanceof Double) { + return PDouble.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Float) { + return PDouble.INSTANCE.toBytes(((Float) leaf).doubleValue()); + } + } + if (requestedType == PDecimal.INSTANCE) { + if (leaf instanceof BigDecimal) { + return PDecimal.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Long) { + return PDecimal.INSTANCE.toBytes(new BigDecimal((Long) leaf)); + } + if (leaf instanceof Integer) { + return PDecimal.INSTANCE.toBytes(new BigDecimal((Integer) leaf)); + } + } + if (requestedType == PVarbinary.INSTANCE) { + if (leaf instanceof byte[]) { + return (byte[]) leaf; + } + if (leaf instanceof String) { + return PVarchar.INSTANCE.toBytes(leaf); + } + } + if (requestedType == PVarbinaryEncoded.INSTANCE) { + if (leaf instanceof byte[]) { + return PVarbinaryEncoded.INSTANCE.toBytes(leaf); + } + if (leaf instanceof String) { + return PVarbinaryEncoded.INSTANCE.toBytes(((String) leaf).getBytes(StandardCharsets.UTF_8)); + } + } + return null; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java new file mode 100644 index 00000000000..e2404022235 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java @@ -0,0 +1,296 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.function; + +import java.io.DataInput; +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.LiteralExpression; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.expression.util.proto.ProtoPathResolver; +import org.apache.phoenix.expression.util.proto.ProtoPathWalker; +import org.apache.phoenix.parse.FunctionParseNode; +import org.apache.phoenix.parse.ProtoValueParseNode; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.schema.tuple.Tuple; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PDouble; +import org.apache.phoenix.schema.types.PFloat; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PUnsignedInt; +import org.apache.phoenix.schema.types.PUnsignedLong; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarbinaryEncoded; +import org.apache.phoenix.schema.types.PVarchar; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; + +/** + * {@code PROTO_VALUE(payload, path, type[, default])} — extracts a leaf value from a PROTOBUF-typed + * column at the given path, coerced to the requested SQL type. + */ +@FunctionParseNode.BuiltInFunction(name = ProtoValueFunction.NAME, + nodeClass = ProtoValueParseNode.class, + args = { @FunctionParseNode.Argument(allowedTypes = { PProtobuf.class, PVarbinary.class }), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true), + @FunctionParseNode.Argument(allowedTypes = { PVarchar.class }, isConstant = true, + defaultValue = ProtoValueFunction.DEFAULT_VALUE), }) +public class ProtoValueFunction extends ScalarFunction { + + public static final String NAME = "PROTO_VALUE"; + + static final String DEFAULT_VALUE = "null"; + + private volatile PathPlan cachedPlan; + private final ProtoDescriptorRegistry registry; + + public ProtoValueFunction() { + this.registry = null; + } + + public ProtoValueFunction(List children) { + this(children, null); + } + + /** @param registry the compiling connection's; {@code null} falls back to the per-JVM one */ + public ProtoValueFunction(List children, ProtoDescriptorRegistry registry) { + super(children); + this.registry = registry; + } + + @Override + public ProtoValueFunction clone(List children) { + return new ProtoValueFunction(children, registry); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public PDataType getDataType() { + return getPDataType(); + } + + private PDataType getPDataType() { + String dataType = (String) ((LiteralExpression) getChildren().get(2)).getValue(); + return PDataType.fromSqlTypeName(dataType); + } + + @Override + public void readFields(DataInput input) throws IOException { + super.readFields(input); + this.cachedPlan = null; + } + + @Override + public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { + if (!ProtoFunctionsUtil.evaluatePayload(getChildren().get(0), tuple, ptr)) { + return false; + } + // Walk the payload in place; ptr is overwritten only after the walk returns. + byte[] buf = ptr.get(); + int offset = ptr.getOffset(); + int length = ptr.getLength(); + + PathPlan plan; + try { + plan = ensurePlan(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + + Object leaf; + try { + leaf = ProtoPathWalker.walk(buf, offset, length, plan); + } catch (IOException e) { + // Malformed wire (including index dummy-UPSERT probes) → SQL NULL, not abort. + return returnDefaultOrNull(ptr); + } + if (leaf == ProtoPathWalker.LEAF_ABSENT) { + // Parent present, leaf unset: the user default wins, else the field's own default. + if (hasDefaultArg() || plan.getLeafDefault() == null) { + return returnDefaultOrNull(ptr); + } + leaf = plan.getLeafDefault(); + } + // A null leaf means the parent, message, map key or index is missing. + if (leaf == null) { + return returnDefaultOrNull(ptr); + } + byte[] out = coerceLeaf(leaf, plan); + if (out == null) { + // The value is present but does not fit the requested type, so the default must not apply. + return ProtoFunctionsUtil.setNull(ptr); + } + ptr.set(out); + return true; + } + + public PathPlan ensurePlan() throws SQLException { + PathPlan snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + synchronized (this) { + snapshot = cachedPlan; + if (snapshot != null) { + return snapshot; + } + String requestedTypeName = + ProtoFunctionsUtil.requiredStringLiteral(getChildren().get(2), NAME, "requested SQL type"); + PDataType requestedType = ProtoFunctionsUtil.resolveSqlType(requestedTypeName, NAME); + PathPlan plan = ProtoFunctionsUtil.compilePathPlan(getChildren(), NAME, registry, + ProtoDescriptorRegistry.PlanKind.VALUE, requestedType, (parsed, descriptor, + path) -> ProtoPathResolver.resolve(parsed, descriptor, requestedType, path)); + cachedPlan = plan; + return plan; + } + } + + /** Children are (payload, path, type[, default], descriptorName). */ + private boolean hasDefaultArg() { + return getChildren().size() > 4; + } + + private boolean returnDefaultOrNull(ImmutableBytesWritable ptr) { + return ProtoFunctionsUtil.returnDefaultOrNull(getChildren(), hasDefaultArg(), ptr); + } + + private static boolean isUnsigned64(FieldDescriptor.Type leafType) { + return leafType == FieldDescriptor.Type.UINT64 || leafType == FieldDescriptor.Type.FIXED64; + } + + private static byte[] coerceLeaf(Object leaf, PathPlan plan) { + PDataType requestedType = plan.getRequestedType(); + FieldDescriptor.Type leafType = plan.getLeafProtoFieldType(); + if (requestedType == PVarchar.INSTANCE) { + if (leaf instanceof String) { + return PVarchar.INSTANCE.toBytes(leaf); + } + if (leaf instanceof byte[]) { + return (byte[]) leaf; + } + return PVarchar.INSTANCE.toBytes(leaf.toString()); + } + if (requestedType == PBoolean.INSTANCE && leaf instanceof Boolean) { + return PBoolean.INSTANCE.toBytes(leaf); + } + if (requestedType == PInteger.INSTANCE && leaf instanceof Integer) { + return PInteger.INSTANCE.toBytes(leaf); + } + if (requestedType == PInteger.INSTANCE && leaf instanceof Long) { + long v = (Long) leaf; + if (v > Integer.MAX_VALUE || v < Integer.MIN_VALUE) { + return null; + } + return PInteger.INSTANCE.toBytes((int) v); + } + if (requestedType == PLong.INSTANCE) { + if (leaf instanceof Long) { + // An unsigned 64-bit value of 2^63 or more does not fit in BIGINT. + if ((Long) leaf < 0 && isUnsigned64(leafType)) { + return null; + } + return PLong.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Integer) { + return PLong.INSTANCE.toBytes(((Integer) leaf).longValue()); + } + } + if (requestedType == PUnsignedInt.INSTANCE) { + if (leaf instanceof Integer) { + return PUnsignedInt.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Long) { + long v = (Long) leaf; + if (v < 0 || v > Integer.MAX_VALUE) { + return null; + } + return PUnsignedInt.INSTANCE.toBytes((int) v); + } + } + if (requestedType == PUnsignedLong.INSTANCE && leaf instanceof Long) { + long v = (Long) leaf; + if (v < 0) { + return null; + } + return PUnsignedLong.INSTANCE.toBytes(leaf); + } + if (requestedType == PFloat.INSTANCE && leaf instanceof Float) { + return PFloat.INSTANCE.toBytes(leaf); + } + if (requestedType == PDouble.INSTANCE) { + if (leaf instanceof Double) { + return PDouble.INSTANCE.toBytes(leaf); + } + if (leaf instanceof Float) { + return PDouble.INSTANCE.toBytes(((Float) leaf).doubleValue()); + } + } + if (requestedType == PDecimal.INSTANCE) { + if (leaf instanceof Integer) { + return PDecimal.INSTANCE.toBytes(new BigDecimal((Integer) leaf)); + } + if (leaf instanceof Long) { + long v = (Long) leaf; + return PDecimal.INSTANCE.toBytes(isUnsigned64(leafType) + ? new BigDecimal(Long.toUnsignedString(v)) + : BigDecimal.valueOf(v)); + } + if (leaf instanceof Float) { + float v = (Float) leaf; + return Float.isFinite(v) + ? PDecimal.INSTANCE.toBytes(new BigDecimal(Float.toString(v))) + : null; + } + if (leaf instanceof Double) { + double v = (Double) leaf; + return Double.isFinite(v) ? PDecimal.INSTANCE.toBytes(BigDecimal.valueOf(v)) : null; + } + } + if (requestedType == PVarbinary.INSTANCE) { + if (leaf instanceof byte[]) { + return (byte[]) leaf; + } + if (leaf instanceof String) { + return PVarchar.INSTANCE.toBytes(leaf); + } + } + if (requestedType == PVarbinaryEncoded.INSTANCE) { + if (leaf instanceof byte[]) { + return PVarbinaryEncoded.INSTANCE.toBytes(leaf); + } + if (leaf instanceof String) { + return PVarbinaryEncoded.INSTANCE.toBytes(((String) leaf).getBytes(StandardCharsets.UTF_8)); + } + } + return null; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/PathPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/PathPlan.java new file mode 100644 index 00000000000..1b53b39e02d --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/PathPlan.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.util.Collections; +import java.util.List; +import org.apache.phoenix.schema.types.PDataType; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; + +/** + * Immutable compiled walk plan produced by {@link ProtoPathResolver} and consumed by + * {@link ProtoPathWalker}. One plan corresponds to one resolved {@code PROTO_VALUE(...)} function + * instance. Cached on the function instance so a single scan pays the resolve cost once and reuses + * it for every row. + */ +public final class PathPlan { + + /** Distinguishes how a walker consumes a segment against the encoded payload. */ + public enum SegmentKind { + /** Scalar leaf — the segment field is a primitive protobuf type. */ + SCALAR, + /** Nested message — recurse into the length-delimited inner payload. */ + MESSAGE, + /** N-th element of a repeated field (unpacked). */ + REPEATED_INDEX, + /** String key of a {@code map} entry. */ + MAP_KEY_STRING, + /** Integer key of a {@code map} entry. */ + MAP_KEY_INT, + /** Count of elements in a repeated field or entries in a map (used by PROTO_ARRAY_LENGTH). */ + COUNT_ARRAY + } + + /** One step in the compiled walk. Field is public for allocation-free hot-path read. */ + public static final class PlanSegment { + public final int tagNumber; + public final int wireType; + public final SegmentKind kind; + public final int repeatedIndex; + public final String mapKeyString; + public final long mapKeyInt; + public final int mapValueWireType; + public final boolean scalarRepeated; + + public PlanSegment(int tagNumber, int wireType, SegmentKind kind, int repeatedIndex, + String mapKeyString, long mapKeyInt, int mapValueWireType, boolean scalarRepeated) { + this.tagNumber = tagNumber; + this.wireType = wireType; + this.kind = kind; + this.repeatedIndex = repeatedIndex; + this.mapKeyString = mapKeyString; + this.mapKeyInt = mapKeyInt; + this.mapValueWireType = mapValueWireType; + this.scalarRepeated = scalarRepeated; + } + + public static PlanSegment scalar(int tagNumber, int wireType) { + return new PlanSegment(tagNumber, wireType, SegmentKind.SCALAR, 0, null, 0L, 0, false); + } + + public static PlanSegment message(int tagNumber) { + return new PlanSegment(tagNumber, 2, SegmentKind.MESSAGE, 0, null, 0L, 0, false); + } + + public static PlanSegment repeatedIndex(int tagNumber, int elementWireType, int index) { + return new PlanSegment(tagNumber, elementWireType, SegmentKind.REPEATED_INDEX, index, null, + 0L, 0, false); + } + + public static PlanSegment mapKeyString(int tagNumber, String key, int valueWireType) { + return new PlanSegment(tagNumber, 2, SegmentKind.MAP_KEY_STRING, 0, key, 0L, valueWireType, + false); + } + + public static PlanSegment mapKeyInt(int tagNumber, long key, int valueWireType) { + return new PlanSegment(tagNumber, 2, SegmentKind.MAP_KEY_INT, 0, null, key, valueWireType, + false); + } + + public static PlanSegment countArray(int tagNumber, boolean scalarRepeated, + int elementWireType) { + return new PlanSegment(tagNumber, elementWireType, SegmentKind.COUNT_ARRAY, 0, null, 0L, 0, + scalarRepeated); + } + } + + private final List segments; + private final FieldDescriptor.Type leafProtoFieldType; + private final PDataType requestedType; + private final Object leafDefault; + + public PathPlan(List segments, FieldDescriptor.Type leafProtoFieldType, + PDataType requestedType, Object leafDefault) { + if (segments == null || segments.isEmpty()) { + throw new IllegalArgumentException("segments must be non-empty"); + } + this.segments = Collections.unmodifiableList(segments); + this.leafProtoFieldType = leafProtoFieldType; + this.requestedType = requestedType; + this.leafDefault = leafDefault; + } + + public List getSegments() { + return segments; + } + + /** + * @return the leaf field's protobuf type so the walker can dispatch to the correct scalar decoder + * without holding a live {@code FieldDescriptor} reference on the hot path + */ + public FieldDescriptor.Type getLeafProtoFieldType() { + return leafProtoFieldType; + } + + public PDataType getRequestedType() { + return requestedType; + } + + /** + * @return the value of an unset leaf whose parent is present: the declared + * {@code [default = ...]} if any, else the type's zero value; null if such a leaf reads + * as SQL NULL + */ + public Object getLeafDefault() { + return leafDefault; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathParser.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathParser.java new file mode 100644 index 00000000000..e842ace0993 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathParser.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; + +/** + * Recursive-descent parser for path literals. + */ +public final class ProtoPathParser { + + /** One parsed segment: an identifier plus an optional integer subscript. */ + public static final class ParsedSegment { + public final String identifier; + /** {@code null} when no {@code [N]} subscript is present. */ + public final Long intSubscript; + + ParsedSegment(String identifier, Long intSubscript) { + this.identifier = identifier; + this.intSubscript = intSubscript; + } + } + + private ProtoPathParser() { + } + + public static List parse(String path) throws SQLException { + if (path == null || path.isEmpty()) { + throw syntaxError("path literal must not be empty", path); + } + List segments = new ArrayList<>(); + int i = 0; + int len = path.length(); + while (i < len) { + int identStart = i; + char c = path.charAt(i); + if (!isIdentifierStart(c)) { + throw syntaxError("expected identifier at position " + i, path); + } + i++; + while (i < len && isIdentifierPart(path.charAt(i))) { + i++; + } + String identifier = path.substring(identStart, i); + Long subscript = null; + if (i < len && path.charAt(i) == '[') { + int bracketStart = i; + i++; + int numStart = i; + if (i < len && path.charAt(i) == '-') { + i++; + } + int digitsStart = i; + while (i < len && isDigit(path.charAt(i))) { + i++; + } + if (i == digitsStart) { + throw syntaxError("expected integer inside '[...]' at position " + bracketStart, path); + } + if (i >= len || path.charAt(i) != ']') { + throw syntaxError("expected ']' at position " + i, path); + } + String numText = path.substring(numStart, i); + try { + subscript = Long.parseLong(numText); + } catch (NumberFormatException e) { + throw syntaxError("integer subscript out of range: " + numText, path); + } + i++; + } + segments.add(new ParsedSegment(identifier, subscript)); + if (i < len) { + if (path.charAt(i) == '[') { + throw syntaxError("chained subscripts like 'name[i][j]' are not supported " + + "at position " + i + "; protobuf has no multi-dimensional arrays. " + + "Use an explicit wrapper-message field between the two subscripts.", path); + } + if (path.charAt(i) != '.') { + throw syntaxError("expected '.' between path segments at position " + i, path); + } + i++; + if (i == len) { + throw syntaxError("trailing '.' at end of path", path); + } + } + } + return segments; + } + + private static boolean isIdentifierStart(char c) { + return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c == '_'; + } + + private static boolean isIdentifierPart(char c) { + return isIdentifierStart(c) || c >= '0' && c <= '9' || c == '-'; + } + + private static boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + private static SQLException syntaxError(String detail, String path) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_SYNTAX_ERROR) + .setMessage("Invalid PROTO_VALUE path '" + path + "': " + detail).build().buildException(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java new file mode 100644 index 00000000000..9a9b02d60c8 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java @@ -0,0 +1,438 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.expression.util.proto.PathPlan.PlanSegment; +import org.apache.phoenix.expression.util.proto.ProtoPathParser.ParsedSegment; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PDouble; +import org.apache.phoenix.schema.types.PFloat; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.schema.types.PUnsignedInt; +import org.apache.phoenix.schema.types.PUnsignedLong; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarbinaryEncoded; +import org.apache.phoenix.schema.types.PVarchar; + +import org.apache.phoenix.thirdparty.com.google.protobuf.ByteString; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.EnumValueDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.WireFormat; + +/** + * Resolves a {@link ProtoPathParser}-parsed path against a protobuf {@link Descriptor} to produce a + * compiled {@link PathPlan}. + *

+ * Segment classification: + *

    + *
  • Dot-notation on a scalar/message field → SCALAR / MESSAGE.
  • + *
  • Bracket-notation on a {@code repeated T} field → REPEATED_INDEX.
  • + *
  • Dot-notation on {@code map} + next-segment identifier as key → MAP_KEY_STRING + * (consumes two parsed segments to produce one plan segment).
  • + *
  • Bracket-notation on {@code map} with regular-varint key type → MAP_KEY_INT.
  • + *
+ */ +public final class ProtoPathResolver { + + private ProtoPathResolver() { + } + + public static PathPlan resolve(List parsedSegments, Descriptor root, + PDataType requestedType, String originalPath) throws SQLException { + return resolveInternal(parsedSegments, root, requestedType, originalPath, false); + } + + public static PathPlan resolveForExistence(List parsedSegments, + Descriptor root, String originalPath) throws SQLException { + return resolveInternal(parsedSegments, root, null, originalPath, false); + } + + public static PathPlan resolveForArrayLength(List parsedSegments, + Descriptor root, String originalPath) throws SQLException { + return resolveInternal(parsedSegments, root, null, originalPath, true); + } + + public static String canonicalSqlTypeName(FieldDescriptor.Type protoType) { + switch (protoType) { + case INT32: + case SINT32: + case SFIXED32: + case ENUM: + return PInteger.INSTANCE.getSqlTypeName(); + case INT64: + case SINT64: + case SFIXED64: + return PLong.INSTANCE.getSqlTypeName(); + case UINT32: + case FIXED32: + return PUnsignedInt.INSTANCE.getSqlTypeName(); + case UINT64: + case FIXED64: + return PUnsignedLong.INSTANCE.getSqlTypeName(); + case BOOL: + return PBoolean.INSTANCE.getSqlTypeName(); + case FLOAT: + return PFloat.INSTANCE.getSqlTypeName(); + case DOUBLE: + return PDouble.INSTANCE.getSqlTypeName(); + case STRING: + return PVarchar.INSTANCE.getSqlTypeName(); + case BYTES: + return PVarbinary.INSTANCE.getSqlTypeName(); + case MESSAGE: + return PVarbinary.INSTANCE.getSqlTypeName(); + case GROUP: + default: + throw new IllegalStateException("proto type " + protoType + " not supported"); + } + } + + private static PathPlan resolveInternal(List parsedSegments, Descriptor root, + PDataType requestedType, String originalPath, boolean arrayLengthMode) throws SQLException { + if (parsedSegments == null || parsedSegments.isEmpty()) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_SYNTAX_ERROR) + .setMessage("PROTO_VALUE path must contain at least one segment").build().buildException(); + } + if (root == null) { + throw new IllegalArgumentException("root descriptor must not be null"); + } + + int totalSegments = parsedSegments.size(); + List plan = new ArrayList<>(totalSegments); + Descriptor currentDescriptor = root; + FieldDescriptor leafField = null; + int i = 0; + + while (i < totalSegments) { + ParsedSegment parsed = parsedSegments.get(i); + boolean isLastParsedSegment = i == totalSegments - 1; + if (currentDescriptor == null) { + throw cardinality( + "cannot navigate past a scalar or bytes leaf at segment '" + parsed.identifier + "'", + originalPath); + } + FieldDescriptor field = currentDescriptor.findFieldByName(parsed.identifier); + if (field == null) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_FIELD_NOT_FOUND) + .setMessage("PROTO_VALUE path '" + originalPath + "': field '" + parsed.identifier + + "' not found in message '" + currentDescriptor.getFullName() + "'") + .build().buildException(); + } + if (field.getType() == FieldDescriptor.Type.GROUP) { + throw unsupported("proto2 groups are not supported (segment '" + parsed.identifier + + "'); this is a permanent design decision", originalPath); + } + if ( + arrayLengthMode && isLastParsedSegment && parsed.intSubscript == null + && (field.isRepeated() || field.isMapField()) + ) { + plan.add(buildCountArraySegment(field)); + leafField = field; + i++; + continue; + } + if (field.isMapField()) { + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + if (parsed.intSubscript != null) { + FieldDescriptor.Type keyType = keyField.getType(); + if (!isSupportedIntMapKey(keyType)) { + throw unsupported("map<" + keyType.name().toLowerCase() + ", V> keys are " + + "not supported (segment '" + parsed.identifier + "'); use int32, " + + "int64, uint32, or uint64 map keys instead", originalPath); + } + plan.add(PlanSegment.mapKeyInt(field.getNumber(), parsed.intSubscript, + wireTypeFor(valueField.getType()))); + currentDescriptor = valueField.getType() == FieldDescriptor.Type.MESSAGE + ? valueField.getMessageType() + : null; + leafField = valueField; + i++; + } else { + if (keyField.getType() != FieldDescriptor.Type.STRING) { + throw cardinality("map<" + keyField.getType().name().toLowerCase() + + ", V> access requires bracket-index '[N]', not dot-notation " + "(segment '" + + parsed.identifier + "')", originalPath); + } + if (i + 1 >= parsedSegments.size()) { + throw cardinality("map field '" + parsed.identifier + "' requires a key " + + "segment (e.g. '" + parsed.identifier + ".key.value')", originalPath); + } + ParsedSegment keySegment = parsedSegments.get(i + 1); + if (keySegment.intSubscript != null) { + throw cardinality( + "map key segment '" + keySegment.identifier + + "' cannot carry a bracket-index; use the key as an identifier only", + originalPath); + } + plan.add(PlanSegment.mapKeyString(field.getNumber(), keySegment.identifier, + wireTypeFor(valueField.getType()))); + currentDescriptor = valueField.getType() == FieldDescriptor.Type.MESSAGE + ? valueField.getMessageType() + : null; + leafField = valueField; + i += 2; + } + } else if (field.isRepeated()) { + if (parsed.intSubscript == null) { + throw cardinality( + "repeated field '" + parsed.identifier + "' requires a bracket-index '[N]'", + originalPath); + } + long idx = parsed.intSubscript; + if (idx < 0 || idx > Integer.MAX_VALUE) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_SYNTAX_ERROR) + .setMessage( + "PROTO_VALUE path '" + originalPath + "': repeated index out of range: " + idx) + .build().buildException(); + } + plan.add( + PlanSegment.repeatedIndex(field.getNumber(), wireTypeFor(field.getType()), (int) idx)); + currentDescriptor = + field.getType() == FieldDescriptor.Type.MESSAGE ? field.getMessageType() : null; + leafField = field; + i++; + } else { + if (parsed.intSubscript != null) { + throw cardinality( + "cannot apply bracket-index to non-repeated non-map field '" + parsed.identifier + "'", + originalPath); + } + if (field.getType() == FieldDescriptor.Type.MESSAGE) { + plan.add(PlanSegment.message(field.getNumber())); + currentDescriptor = field.getMessageType(); + } else { + plan.add(PlanSegment.scalar(field.getNumber(), wireTypeFor(field.getType()))); + currentDescriptor = null; + } + leafField = field; + i++; + } + } + + if (leafField == null) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_SYNTAX_ERROR) + .setMessage("PROTO_VALUE path '" + originalPath + "' resolved no leaf field").build() + .buildException(); + } + + if (arrayLengthMode && plan.get(plan.size() - 1).kind != PathPlan.SegmentKind.COUNT_ARRAY) { + throw cardinality("PROTO_ARRAY_LENGTH path '" + originalPath + "' must end at a " + + "repeated field or a map (received a scalar or specific element)", originalPath); + } + if (requestedType != null) { + validateLeafCoercion(leafField, requestedType, originalPath); + } + + return new PathPlan(plan, leafField.getType(), requestedType, leafDefault(leafField)); + } + + /** + * Returns the value of {@code field} when it is unset but its parent is present, in the + * {@link ProtoPathWalker} leaf conventions. Null for message and repeated fields and for an arm + * of a real oneof, which read as SQL NULL when unset. + */ + static Object leafDefault(FieldDescriptor field) { + if ( + field.isRepeated() || field.getType() == FieldDescriptor.Type.MESSAGE + || field.getRealContainingOneof() != null + ) { + return null; + } + Object value = field.getDefaultValue(); + switch (field.getType()) { + case UINT32: + case FIXED32: + return ((Integer) value) & 0xFFFFFFFFL; + case ENUM: + return ((EnumValueDescriptor) value).getNumber(); + case BYTES: + return ((ByteString) value).toByteArray(); + default: + return value; + } + } + + private static PlanSegment buildCountArraySegment(FieldDescriptor field) { + boolean scalarRepeated = + field.isRepeated() && !field.isMapField() && field.getType() != FieldDescriptor.Type.MESSAGE + && field.getType() != FieldDescriptor.Type.STRING + && field.getType() != FieldDescriptor.Type.BYTES; + int elementWireType = scalarRepeated ? wireTypeFor(field.getType()) : 0; + return PlanSegment.countArray(field.getNumber(), scalarRepeated, elementWireType); + } + + private static boolean isSupportedIntMapKey(FieldDescriptor.Type keyType) { + return keyType == FieldDescriptor.Type.INT32 || keyType == FieldDescriptor.Type.INT64 + || keyType == FieldDescriptor.Type.UINT32 || keyType == FieldDescriptor.Type.UINT64; + } + + /** + * Maps a protobuf {@link FieldDescriptor.Type} to its on-wire type per the protobuf encoding spec + * (https://protobuf.dev/programming-guides/encoding/). + * @throws IllegalStateException for GROUP. + */ + static int wireTypeFor(FieldDescriptor.Type type) { + if (type == FieldDescriptor.Type.GROUP) { + throw new IllegalStateException("wireTypeFor called with unsupported protobuf type " + type + + "; upstream GROUP rejection and leaf-type validation should have " + "prevented this"); + } + // Descriptors.FieldDescriptor.Type and WireFormat.FieldType share constant names. + return WireFormat.FieldType.valueOf(type.name()).getWireType(); + } + + private static void validateLeafCoercion(FieldDescriptor leafField, PDataType requestedType, + String path) throws SQLException { + FieldDescriptor.Type protoType = leafField.getType(); + switch (protoType) { + case STRING: + if (requestedType == PVarchar.INSTANCE || requestedType == PVarbinary.INSTANCE) { + return; + } + break; + case BOOL: + if (requestedType == PBoolean.INSTANCE) { + return; + } + break; + case INT32: + case SINT32: + case SFIXED32: + if ( + requestedType == PInteger.INSTANCE || requestedType == PLong.INSTANCE + || requestedType == PDecimal.INSTANCE + ) { + return; + } + if (requestedType == PBoolean.INSTANCE || requestedType == PVarchar.INSTANCE) { + break; + } + break; + case INT64: + case SINT64: + case SFIXED64: + if (requestedType == PLong.INSTANCE || requestedType == PDecimal.INSTANCE) { + return; + } + if (requestedType == PInteger.INSTANCE) { + throw narrowing(protoType, requestedType, path); + } + break; + case UINT32: + case FIXED32: + if ( + requestedType == PLong.INSTANCE || requestedType == PUnsignedInt.INSTANCE + || requestedType == PUnsignedLong.INSTANCE || requestedType == PDecimal.INSTANCE + ) { + return; + } + if (requestedType == PInteger.INSTANCE) { + throw narrowing(protoType, requestedType, path); + } + break; + case UINT64: + case FIXED64: + if ( + requestedType == PUnsignedLong.INSTANCE || requestedType == PLong.INSTANCE + || requestedType == PDecimal.INSTANCE + ) { + return; + } + if (requestedType == PInteger.INSTANCE || requestedType == PUnsignedInt.INSTANCE) { + throw narrowing(protoType, requestedType, path); + } + break; + case FLOAT: + if ( + requestedType == PFloat.INSTANCE || requestedType == PDouble.INSTANCE + || requestedType == PDecimal.INSTANCE + ) { + return; + } + break; + case DOUBLE: + if (requestedType == PDouble.INSTANCE || requestedType == PDecimal.INSTANCE) { + return; + } + if (requestedType == PFloat.INSTANCE) { + throw narrowing(protoType, requestedType, path); + } + break; + case BYTES: + if (requestedType == PVarbinary.INSTANCE || requestedType == PVarbinaryEncoded.INSTANCE) { + return; + } + break; + case MESSAGE: + if (requestedType == PVarbinary.INSTANCE || requestedType == PVarbinaryEncoded.INSTANCE) { + return; + } + if (requestedType == PProtobuf.INSTANCE) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage("PROTO_VALUE path '" + path + "': a nested message has no " + + "descriptor binding and cannot be returned as PROTOBUF; request VARBINARY") + .build().buildException(); + } + break; + case ENUM: + if (requestedType == PInteger.INSTANCE || requestedType == PLong.INSTANCE) { + return; + } + if (requestedType == PVarchar.INSTANCE) { + throw unsupported("enum-leaf-as-VARCHAR (symbolic name) is not yet supported", path); + } + break; + default: + break; + } + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage("PROTO_VALUE path '" + path + "': cannot coerce protobuf type " + protoType.name() + + " to requested SQL type " + requestedType.getSqlTypeName()) + .build().buildException(); + } + + private static SQLException narrowing(FieldDescriptor.Type protoType, PDataType requestedType, + String path) { + return new SQLExceptionInfo.Builder( + SQLExceptionCode.PROTOBUF_VALUE_TYPE_NARROWING_NOT_PERMITTED) + .setMessage("PROTO_VALUE path '" + path + "': cannot narrow protobuf type " + + protoType.name() + " to requested SQL type " + requestedType.getSqlTypeName() + + "; use a wider type or cast at the caller") + .build().buildException(); + } + + private static SQLException cardinality(String detail, String path) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_CARDINALITY_MISMATCH) + .setMessage("PROTO_VALUE path '" + path + "': " + detail).build().buildException(); + } + + private static SQLException unsupported(String detail, String path) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_PATH_UNSUPPORTED_FEATURE) + .setMessage("PROTO_VALUE path '" + path + "': " + detail).build().buildException(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathWalker.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathWalker.java new file mode 100644 index 00000000000..5488f6d593e --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathWalker.java @@ -0,0 +1,466 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.io.IOException; +import java.util.List; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.expression.util.proto.PathPlan.PlanSegment; +import org.apache.phoenix.expression.util.proto.PathPlan.SegmentKind; + +import org.apache.phoenix.thirdparty.com.google.protobuf.CodedInputStream; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.WireFormat; + +/** + * Walks raw protobuf payload bytes with a compiled {@link PathPlan} and returns the leaf value as a + * Java {@link Object} (or {@code null} for missing paths). Runs on the hot path — one call per row + * per {@code PROTO_VALUE} function instance. + *

+ * Uses {@link CodedInputStream} directly (no {@code DynamicMessage} allocation). For + * length-delimited children (MESSAGE, MAP_ENTRY, repeated-of-message), the walker slices the child + * bytes via {@code readByteArray()} and recurses on the remaining plan tail. + *

+ * Leaf return conventions: + *

    + *
  • STRING → {@link String}
  • + *
  • BOOL → {@link Boolean}
  • + *
  • INT32 / SINT32 / SFIXED32 / ENUM → {@link Integer}
  • + *
  • INT64 / SINT64 / SFIXED64 / UINT32 / FIXED32 → {@link Long}
  • + *
  • UINT64 / FIXED64 → {@link Long} (raw bits; values of 2^63 and above are negative, and the + * caller reads them as unsigned)
  • + *
  • FLOAT → {@link Float}
  • + *
  • DOUBLE → {@link Double}
  • + *
  • BYTES / MESSAGE → {@code byte[]}
  • + *
+ * A caller-visible {@code null} means "path not present" (missing message, out-of-range repeated + * index, missing map key, child-of-unset-parent). {@link #LEAF_ABSENT} means the scalar leaf is + * unset but its parent is present; the caller then uses {@link PathPlan#getLeafDefault()}. + *

+ * Non-conformance trade-off for duplicate tags. The protobuf wire-format spec requires + * parsers to keep the last value of a non-repeated scalar that appears more than once, to + * merge multiple encoded instances of the same MESSAGE field via {@code MergeFrom} (equivalent to + * concatenating the LEN-delimited slices), and to keep the last map entry for a repeated key. This + * walker instead returns the first occurrence and short-circuits, so a lookup stops as soon + * as it finds the tag. The difference is only observable if a non-repeated field or map key appears + * more than once in the same parent's bytes, which no canonical serializer (Google Java / C++ / + * Python / Go / Rust generated code) ever produces. Concatenated or handcrafted byte streams CAN + * produce duplicates; those fall outside the supported input contract. + */ +public final class ProtoPathWalker { + + public static final Object LEAF_ABSENT = new Object(); + + private static final byte[] EMPTY_BYTES = new byte[0]; + private static final Object MAP_VALUE_OMITTED = new Object(); + + private ProtoPathWalker() { + } + + /** + * Walks {@code length} payload bytes starting at {@code offset} in place. The buffer is only + * read, and every returned byte[] or String is a copy. + */ + public static Object walk(byte[] buf, int offset, int length, PathPlan plan) throws IOException { + if (buf == null || length == 0) { + return null; + } + return walkSegments(buf, offset, length, plan.getSegments(), 0, plan); + } + + public static int walkForCount(byte[] buf, int offset, int length, PathPlan plan) + throws IOException { + Object result = walk(buf, offset, length, plan); + if (result == null || result == LEAF_ABSENT) { + return 0; + } + if (result instanceof Integer) { + return (Integer) result; + } + throw new IOException( + "walkForCount expected Integer count, got " + result.getClass().getName()); + } + + private static Object walkSegments(byte[] buf, int offset, int length, List segments, + int segIdx, PathPlan plan) throws IOException { + if (segIdx >= segments.size()) { + return null; + } + PlanSegment seg = segments.get(segIdx); + boolean isLast = segIdx == segments.size() - 1; + switch (seg.kind) { + case SCALAR: + return findFirstScalar(buf, offset, length, seg.tagNumber, seg.wireType, + plan.getLeafProtoFieldType()); + case MESSAGE: + return handleMessage(buf, offset, length, segments, segIdx, plan, isLast); + case REPEATED_INDEX: + return handleRepeatedIndex(buf, offset, length, segments, segIdx, plan, isLast); + case MAP_KEY_STRING: + case MAP_KEY_INT: + return handleMapEntry(buf, offset, length, segments, segIdx, plan, isLast); + case COUNT_ARRAY: + return countAtTag(buf, offset, length, seg.tagNumber, seg.scalarRepeated, seg.wireType); + default: + return null; + } + } + + private static int countAtTag(byte[] buf, int offset, int length, int tagNumber, + boolean scalarRepeated, int elementWireType) throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + int count = 0; + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum != tagNumber) { + cis.skipField(tag); + continue; + } + if (scalarRepeated && wt == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + int chunkLen = cis.readRawVarint32(); + int oldLimit = cis.pushLimit(chunkLen); + while (!cis.isAtEnd()) { + skipOneScalarElement(cis, elementWireType); + count++; + } + cis.popLimit(oldLimit); + } else { + cis.skipField(tag); + count++; + } + } + return count; + } + + static void skipOneScalarElement(CodedInputStream cis, int elementWireType) throws IOException { + switch (elementWireType) { + case WireFormat.WIRETYPE_VARINT: + cis.readRawVarint64(); + return; + case WireFormat.WIRETYPE_FIXED32: + cis.readRawLittleEndian32(); + return; + case WireFormat.WIRETYPE_FIXED64: + cis.readRawLittleEndian64(); + return; + default: + throw new IOException("packed chunk with unexpected element wire type " + elementWireType); + } + } + + private static Object handleMessage(byte[] buf, int offset, int length, + List segments, int segIdx, PathPlan plan, boolean isLast) throws IOException { + // First-occurrence fast path — see the class Javadoc for the trade-off. + byte[] inner = findNthLenBytes(buf, offset, length, segments.get(segIdx).tagNumber, 0); + if (inner == null) { + return null; + } + if (isLast) { + return inner; + } + return walkSegments(inner, 0, inner.length, segments, segIdx + 1, plan); + } + + private static Object handleRepeatedIndex(byte[] buf, int offset, int length, + List segments, int segIdx, PathPlan plan, boolean isLast) throws IOException { + PlanSegment seg = segments.get(segIdx); + if (seg.wireType == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + byte[] elem = findNthLenBytes(buf, offset, length, seg.tagNumber, seg.repeatedIndex); + if (elem == null) { + return null; + } + if (isLast) { + if (plan.getLeafProtoFieldType() == FieldDescriptor.Type.STRING) { + return Bytes.toString(elem); + } + return elem; + } + return walkSegments(elem, 0, elem.length, segments, segIdx + 1, plan); + } + // Scalar element — per protobuf spec, parsers accept both packed and + // unpacked encodings on the same tag regardless of what the schema + // declares. Proto3 defaults to packed; proto2 to unpacked; both may + // appear intermixed on the wire during schema evolution. + Object value = findNthScalarAcceptingPacked(buf, offset, length, seg.tagNumber, seg.wireType, + seg.repeatedIndex, plan.getLeafProtoFieldType()); + if (value == null) { + return null; + } + return isLast ? value : null; + } + + private static Object handleMapEntry(byte[] buf, int offset, int length, + List segments, int segIdx, PathPlan plan, boolean isLast) throws IOException { + PlanSegment seg = segments.get(segIdx); + FieldDescriptor.Type leafType = plan.getLeafProtoFieldType(); + Object rawValue = findMapEntryValue(buf, offset, length, seg, leafType); + if (rawValue == null) { + return null; + } + boolean valueOmitted = rawValue == MAP_VALUE_OMITTED; + if (seg.mapValueWireType != WireFormat.WIRETYPE_LENGTH_DELIMITED) { + // Scalar value, already decoded by matchAndExtractValue; it cannot be walked into. + if (!isLast) { + return null; + } + return valueOmitted ? scalarDefault(seg.mapValueWireType, leafType) : rawValue; + } + // Omitted value tag → EMPTY_BYTES, which decodes to the type default. + byte[] valueBytes = valueOmitted ? EMPTY_BYTES : (byte[]) rawValue; + if (isLast) { + if (leafType == FieldDescriptor.Type.STRING) { + return Bytes.toString(valueBytes); + } + return valueBytes; + } + return walkSegments(valueBytes, 0, valueBytes.length, segments, segIdx + 1, plan); + } + + private static Object scalarDefault(int wireType, FieldDescriptor.Type leafType) { + switch (wireType) { + case WireFormat.WIRETYPE_VARINT: + if (leafType == FieldDescriptor.Type.BOOL) { + return Boolean.FALSE; + } + if ( + leafType == FieldDescriptor.Type.INT32 || leafType == FieldDescriptor.Type.SINT32 + || leafType == FieldDescriptor.Type.ENUM + ) { + return Integer.valueOf(0); + } + return Long.valueOf(0L); + case WireFormat.WIRETYPE_FIXED64: + if (leafType == FieldDescriptor.Type.DOUBLE) { + return Double.valueOf(0.0d); + } + return Long.valueOf(0L); + case WireFormat.WIRETYPE_FIXED32: + if (leafType == FieldDescriptor.Type.FLOAT) { + return Float.valueOf(0.0f); + } + if (leafType == FieldDescriptor.Type.SFIXED32) { + return Integer.valueOf(0); + } + return Long.valueOf(0L); + default: + return null; + } + } + + private static Object findFirstScalar(byte[] buf, int offset, int length, int tagNumber, + int wireType, FieldDescriptor.Type leafProtoFieldType) throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum == tagNumber && wt == wireType) { + return readScalarByWireType(cis, wireType, leafProtoFieldType); + } + cis.skipField(tag); + } + return LEAF_ABSENT; + } + + /** Returns the n-th (0-based) LEN-delimited occurrence of tagNumber, or null. */ + static byte[] findNthLenBytes(byte[] buf, int offset, int length, int tagNumber, int n) + throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + int count = 0; + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum == tagNumber && wt == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + if (count == n) { + return cis.readByteArray(); + } + cis.skipField(tag); + count++; + } else { + cis.skipField(tag); + } + } + return null; + } + + private static Object findNthScalarAcceptingPacked(byte[] buf, int offset, int length, + int tagNumber, int elementWireType, int n, FieldDescriptor.Type leafProtoFieldType) + throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + int count = 0; + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum != tagNumber) { + cis.skipField(tag); + continue; + } + if (wt == elementWireType) { + Object value = readScalarByWireType(cis, elementWireType, leafProtoFieldType); + if (count == n) { + return value; + } + count++; + } else if (wt == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + byte[] packed = cis.readByteArray(); + CodedInputStream chunk = CodedInputStream.newInstance(packed); + while (!chunk.isAtEnd()) { + Object value = readScalarByWireType(chunk, elementWireType, leafProtoFieldType); + if (count == n) { + return value; + } + count++; + } + } else { + cis.skipField(tag); + } + } + return null; + } + + private static Object findMapEntryValue(byte[] buf, int offset, int length, PlanSegment seg, + FieldDescriptor.Type leafType) throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum == seg.tagNumber && wt == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + byte[] entryBytes = cis.readByteArray(); + Object result = matchAndExtractValue(entryBytes, seg, leafType); + if (result != null) { + return result; + } + } else { + cis.skipField(tag); + } + } + return null; + } + + /** + * Returns the entry's value if its key matches: raw bytes for a LEN-delimited value, the decoded + * Java value for a scalar value, {@link #MAP_VALUE_OMITTED} if the value tag is absent; or null + * if the key does not match. + */ + private static Object matchAndExtractValue(byte[] entryBytes, PlanSegment seg, + FieldDescriptor.Type leafType) throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(entryBytes); + boolean keyMatched = false; + boolean valueSeen = false; + Object value = null; + boolean valueIsLenDelimited = seg.mapValueWireType == WireFormat.WIRETYPE_LENGTH_DELIMITED; + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + if (fieldNum == 1) { + if (seg.kind == SegmentKind.MAP_KEY_STRING) { + String key = cis.readString(); + if (seg.mapKeyString.equals(key)) { + keyMatched = true; + } + } else { + long key = cis.readInt64(); + if (key == seg.mapKeyInt) { + keyMatched = true; + } + } + } else if (fieldNum == 2) { + valueSeen = true; + value = valueIsLenDelimited + ? cis.readByteArray() + : readScalarByWireType(cis, seg.mapValueWireType, leafType); + } else { + cis.skipField(tag); + } + } + if (!keyMatched) { + return null; + } + // Key matched. Value tag may have been omitted (proto3 defaulted value) — + // signal that to the caller via MAP_VALUE_OMITTED so it can synthesize the + // value type's implicit-presence default rather than treating the entry as + // absent. + return valueSeen ? value : MAP_VALUE_OMITTED; + } + + private static Object readScalarByWireType(CodedInputStream cis, int wireType, + FieldDescriptor.Type leafProtoFieldType) throws IOException { + switch (wireType) { + case WireFormat.WIRETYPE_VARINT: + return readVarintByLeafType(cis, leafProtoFieldType); + case WireFormat.WIRETYPE_FIXED64: + return readFixed64ByLeafType(cis, leafProtoFieldType); + case WireFormat.WIRETYPE_FIXED32: + return readFixed32ByLeafType(cis, leafProtoFieldType); + case WireFormat.WIRETYPE_LENGTH_DELIMITED: + if (leafProtoFieldType == FieldDescriptor.Type.STRING) { + return cis.readString(); + } + return cis.readByteArray(); + default: + return null; + } + } + + private static Object readVarintByLeafType(CodedInputStream cis, FieldDescriptor.Type leafType) + throws IOException { + if (leafType == FieldDescriptor.Type.BOOL) { + return cis.readBool(); + } + if (leafType == FieldDescriptor.Type.INT32 || leafType == FieldDescriptor.Type.ENUM) { + return cis.readInt32(); + } + if (leafType == FieldDescriptor.Type.SINT32) { + return cis.readSInt32(); + } + if (leafType == FieldDescriptor.Type.SINT64) { + return cis.readSInt64(); + } + if (leafType == FieldDescriptor.Type.UINT32) { + // Widen to Long so unsigned semantics are preserved for values above + // Integer.MAX_VALUE without accidental sign flip. + return cis.readInt64() & 0xFFFFFFFFL; + } + // INT64, UINT64 and any other varint leaf type: raw value as Long. + return cis.readInt64(); + } + + private static Object readFixed64ByLeafType(CodedInputStream cis, FieldDescriptor.Type leafType) + throws IOException { + if (leafType == FieldDescriptor.Type.DOUBLE) { + return cis.readDouble(); + } + return cis.readFixed64(); + } + + private static Object readFixed32ByLeafType(CodedInputStream cis, FieldDescriptor.Type leafType) + throws IOException { + if (leafType == FieldDescriptor.Type.FLOAT) { + return cis.readFloat(); + } + if (leafType == FieldDescriptor.Type.SFIXED32) { + return cis.readSFixed32(); + } + return cis.readFixed32() & 0xFFFFFFFFL; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathParser.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathParser.java new file mode 100644 index 00000000000..96a135890b9 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathParser.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; + +/** + * Parser for the schema-less tag-number path grammar used by {@code PROTO_VALUE_AT_TAG}. Produces a + * list of {@link TagSegment} from a string like {@code "1.2[0].5"}. + *

+ * Grammar: + * + *

+ *   tag_path    ::= tag_segment ( '.' tag_segment )*
+ *   tag_segment ::= unsigned_integer [ '[' unsigned_integer ']' ]
+ * 
+ */ +public final class ProtoTagPathParser { + + /** One parsed segment: a tag number plus an optional repeated-element index. */ + public static final class TagSegment { + public final int tagNumber; + /** -1 when no {@code [N]} subscript is present. */ + public final int index; + + TagSegment(int tagNumber, int index) { + this.tagNumber = tagNumber; + this.index = index; + } + + public boolean hasIndex() { + return index >= 0; + } + } + + private ProtoTagPathParser() { + } + + public static List parse(String path) throws SQLException { + if (path == null || path.isEmpty()) { + throw syntaxError("tag-path must not be empty", path); + } + List segments = new ArrayList<>(); + int i = 0; + int len = path.length(); + while (i < len) { + int numStart = i; + if (!isDigit(path.charAt(i))) { + throw syntaxError("expected unsigned integer at position " + i, path); + } + while (i < len && isDigit(path.charAt(i))) { + i++; + } + int tagNumber; + try { + tagNumber = Integer.parseInt(path.substring(numStart, i)); + } catch (NumberFormatException e) { + throw syntaxError("tag number out of range at position " + numStart, path); + } + if (tagNumber <= 0) { + throw syntaxError("tag number must be positive at position " + numStart, path); + } + int subscript = -1; + if (i < len && path.charAt(i) == '[') { + i++; + int subStart = i; + if (i >= len || !isDigit(path.charAt(i))) { + throw syntaxError("expected unsigned integer inside '[...]' at position " + subStart, + path); + } + while (i < len && isDigit(path.charAt(i))) { + i++; + } + if (i >= len || path.charAt(i) != ']') { + throw syntaxError("expected ']' at position " + i, path); + } + try { + subscript = Integer.parseInt(path.substring(subStart, i)); + } catch (NumberFormatException e) { + throw syntaxError("subscript out of range at position " + subStart, path); + } + i++; + } + segments.add(new TagSegment(tagNumber, subscript)); + if (i < len) { + if (path.charAt(i) != '.') { + throw syntaxError("expected '.' between segments at position " + i, path); + } + i++; + if (i == len) { + throw syntaxError("trailing '.' at end of path", path); + } + } + } + return segments; + } + + private static boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + private static SQLException syntaxError(String detail, String path) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_TAG_PATH_INVALID_SYNTAX) + .setMessage("Invalid tag-path '" + path + "': " + detail).build().buildException(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java new file mode 100644 index 00000000000..aca0b83268b --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java @@ -0,0 +1,234 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.List; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.expression.util.proto.ProtoTagPathParser.TagSegment; +import org.apache.phoenix.schema.types.PBoolean; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PDouble; +import org.apache.phoenix.schema.types.PFloat; +import org.apache.phoenix.schema.types.PInteger; +import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PUnsignedInt; +import org.apache.phoenix.schema.types.PUnsignedLong; +import org.apache.phoenix.schema.types.PVarbinary; +import org.apache.phoenix.schema.types.PVarbinaryEncoded; +import org.apache.phoenix.schema.types.PVarchar; + +import org.apache.phoenix.thirdparty.com.google.protobuf.CodedInputStream; +import org.apache.phoenix.thirdparty.com.google.protobuf.WireFormat; + +/** + * Walks raw protobuf payload bytes using a {@link TagPathPlan} compiled from a schema-less + * tag-number path. Uses {@link CodedInputStream} directly without any descriptor. Returns a decoded + * Java object for the leaf value, or {@code null} when the tag is not found or the wire type + * mismatches. + */ +public final class ProtoTagPathWalker { + + private ProtoTagPathWalker() { + } + + /** + * Maps a Phoenix SQL type to its expected protobuf wire type for schema-less access. Returns -1 + * for unsupported types. + */ + public static int wireTypeForSqlType(PDataType sqlType) { + if ( + sqlType == PVarchar.INSTANCE || sqlType == PVarbinary.INSTANCE + || sqlType == PVarbinaryEncoded.INSTANCE + ) { + return WireFormat.WIRETYPE_LENGTH_DELIMITED; + } + if ( + sqlType == PBoolean.INSTANCE || sqlType == PInteger.INSTANCE || sqlType == PLong.INSTANCE + || sqlType == PUnsignedInt.INSTANCE || sqlType == PUnsignedLong.INSTANCE + || sqlType == PDecimal.INSTANCE + ) { + return WireFormat.WIRETYPE_VARINT; + } + if (sqlType == PFloat.INSTANCE) { + return WireFormat.WIRETYPE_FIXED32; + } + if (sqlType == PDouble.INSTANCE) { + return WireFormat.WIRETYPE_FIXED64; + } + return -1; + } + + /** + * Walks the payload bytes according to the plan. Returns the decoded leaf value as a Java object, + * or {@code null} if the tag is absent or there is a wire-type mismatch. + */ + /** + * Walks {@code length} payload bytes starting at {@code offset} in place. The buffer is only + * read, and every returned byte[] or String is a copy. + */ + public static Object walk(byte[] buf, int offset, int length, TagPathPlan plan) + throws IOException { + if (buf == null || length == 0) { + return null; + } + return walkSegments(buf, offset, length, plan.getSegments(), 0, plan); + } + + private static Object walkSegments(byte[] buf, int offset, int length, List segments, + int segIdx, TagPathPlan plan) throws IOException { + if (segIdx >= segments.size()) { + return null; + } + TagSegment seg = segments.get(segIdx); + boolean isLast = segIdx == segments.size() - 1; + + if (isLast) { + return readLeaf(buf, offset, length, seg, plan); + } + byte[] inner = ProtoPathWalker.findNthLenBytes(buf, offset, length, seg.tagNumber, + seg.hasIndex() ? seg.index : 0); + if (inner == null) { + return null; + } + return walkSegments(inner, 0, inner.length, segments, segIdx + 1, plan); + } + + private static Object readLeaf(byte[] buf, int offset, int length, TagSegment seg, + TagPathPlan plan) throws IOException { + int expectedWire = plan.getLeafWireType(); + PDataType reqType = plan.getRequestedType(); + + if (seg.hasIndex()) { + return findNthElement(buf, offset, length, seg.tagNumber, expectedWire, seg.index, reqType); + } + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum == seg.tagNumber) { + return wt == expectedWire ? decodeLeaf(cis, expectedWire, reqType) : null; + } + cis.skipField(tag); + } + return null; + } + + private static Object findNthElement(byte[] buf, int offset, int length, int tagNumber, + int expectedWire, int n, PDataType reqType) throws IOException { + CodedInputStream cis = CodedInputStream.newInstance(buf, offset, length); + int count = 0; + while (!cis.isAtEnd()) { + int tag = cis.readTag(); + int fieldNum = WireFormat.getTagFieldNumber(tag); + int wt = WireFormat.getTagWireType(tag); + if (fieldNum != tagNumber) { + cis.skipField(tag); + continue; + } + if (wt == expectedWire) { + if (count == n) { + return decodeLeaf(cis, expectedWire, reqType); + } + cis.skipField(tag); + count++; + } else if (wt == WireFormat.WIRETYPE_LENGTH_DELIMITED && isScalarWire(expectedWire)) { + // Packed encoding: LEN-delimited chunk of scalars. + byte[] packed = cis.readByteArray(); + CodedInputStream chunk = CodedInputStream.newInstance(packed); + while (!chunk.isAtEnd()) { + if (count == n) { + return decodeLeaf(chunk, expectedWire, reqType); + } + ProtoPathWalker.skipOneScalarElement(chunk, expectedWire); + count++; + } + } else { + return null; + } + } + return null; + } + + private static Object decodeLeaf(CodedInputStream cis, int wireType, PDataType reqType) + throws IOException { + switch (wireType) { + case WireFormat.WIRETYPE_VARINT: + return decodeVarint(cis, reqType); + case WireFormat.WIRETYPE_FIXED64: + return decodeFixed64(cis, reqType); + case WireFormat.WIRETYPE_FIXED32: + return decodeFixed32(cis, reqType); + case WireFormat.WIRETYPE_LENGTH_DELIMITED: + return decodeLenDelimited(cis, reqType); + default: + return null; + } + } + + private static Object decodeVarint(CodedInputStream cis, PDataType reqType) + throws IOException { + long raw = cis.readRawVarint64(); + if (reqType == PBoolean.INSTANCE) { + return raw != 0; + } + if (reqType == PLong.INSTANCE) { + return raw; + } + if (reqType == PUnsignedLong.INSTANCE) { + return raw; + } + if (reqType == PDecimal.INSTANCE) { + return BigDecimal.valueOf(raw); + } + return raw; + } + + private static Object decodeFixed64(CodedInputStream cis, PDataType reqType) + throws IOException { + if (reqType == PDouble.INSTANCE) { + return cis.readDouble(); + } + return cis.readFixed64(); + } + + private static Object decodeFixed32(CodedInputStream cis, PDataType reqType) + throws IOException { + if (reqType == PFloat.INSTANCE) { + return cis.readFloat(); + } + return cis.readFixed32(); + } + + private static Object decodeLenDelimited(CodedInputStream cis, PDataType reqType) + throws IOException { + byte[] bytes = cis.readByteArray(); + if (reqType == PVarchar.INSTANCE) { + return Bytes.toString(bytes); + } + return bytes; + } + + private static boolean isScalarWire(int wireType) { + return wireType == WireFormat.WIRETYPE_VARINT || wireType == WireFormat.WIRETYPE_FIXED32 + || wireType == WireFormat.WIRETYPE_FIXED64; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/TagPathPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/TagPathPlan.java new file mode 100644 index 00000000000..44a993e0bbf --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/TagPathPlan.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.expression.util.proto; + +import java.util.List; +import org.apache.phoenix.expression.util.proto.ProtoTagPathParser.TagSegment; +import org.apache.phoenix.schema.types.PDataType; + +public final class TagPathPlan { + + private final List segments; + private final PDataType requestedType; + private final int leafWireType; + + public TagPathPlan(List segments, PDataType requestedType, int leafWireType) { + this.segments = segments; + this.requestedType = requestedType; + this.leafWireType = leafWireType; + } + + public List getSegments() { + return segments; + } + + public PDataType getRequestedType() { + return requestedType; + } + + public int getLeafWireType() { + return leafWireType; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/package-info.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/package-info.java new file mode 100644 index 00000000000..5d89e2781ce --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Path parsing, resolution and walking utilities for PROTOBUF column value functions. + */ +package org.apache.phoenix.expression.util.proto; diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixConnection.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixConnection.java index bfc2380c0c9..044731869ac 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixConnection.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixConnection.java @@ -88,6 +88,9 @@ import org.apache.phoenix.monitoring.connectionqueryservice.ConnectionQueryServicesMetricsManager; import org.apache.phoenix.parse.PFunction; import org.apache.phoenix.parse.PSchema; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.protobuf.descriptor.SystemProtoDescriptorsJdbcLoader; import org.apache.phoenix.query.ConnectionQueryServices; import org.apache.phoenix.query.DelegateConnectionQueryServices; import org.apache.phoenix.query.MetaDataMutated; @@ -152,6 +155,7 @@ public class PhoenixConnection private String schema; private final ConnectionQueryServices services; private final Properties info; + private volatile ProtoDescriptorRegistry protoDescriptorRegistry; private final Map, Format> formatters = new HashMap<>(); private final int mutateBatchSize; private final long mutateBatchSizeBytes; @@ -185,6 +189,9 @@ public class PhoenixConnection private String sourceOfOperation; private volatile SQLException reasonForClose; private static final String[] CONNECTION_PROPERTIES; + private static final String[] PROTO_DESCRIPTOR_LOADER_EXCLUDED_PROPS = + { PhoenixRuntime.TENANT_ID_ATTRIB, PhoenixRuntime.CURRENT_SCN_ATTRIB, + PhoenixRuntime.BUILD_INDEX_AT_ATTRIB, PhoenixRuntime.CONSISTENCY_ATTRIB }; private final int slowestScanMetricsCount; private final boolean isScanMetricsByRegionEnabled; @@ -755,6 +762,45 @@ public ConnectionQueryServices getQueryServices() { return services; } + /** + * Returns a view of the JVM-wide descriptor cache that loads misses through this connection's + * query services, without its tenant, SCN or consistency, since the latest descriptor decodes + * data written under any earlier one. + *

+ * The cache is keyed by descriptor name only, not by cluster. This keeps it simple for HA, where + * replication peers are expected to hold the same descriptors. If clusters have different schemas + * for the same name, a JVM can read with a stale one after an HA failover, until the cache TTL + * expires. + */ + public ProtoDescriptorRegistry getProtoDescriptorRegistry() { + ProtoDescriptorRegistry registry = protoDescriptorRegistry; + if (registry != null) { + return registry; + } + String loaderUrl = url; + Properties loaderProps = PropertiesUtil.deepCopy(info); + for (String prop : PROTO_DESCRIPTOR_LOADER_EXCLUDED_PROPS) { + loaderUrl = JDBCUtil.removeProperty(loaderUrl, prop); + loaderProps.remove(prop); + } + ConnectionQueryServices cqs = services; + String jdbcUrl = loaderUrl; + ProtoDescriptorRegistry.Loader loader = new SystemProtoDescriptorsJdbcLoader(() -> { + try { + return cqs.connect(jdbcUrl, loaderProps); + } catch (SQLException e) { + throw new RuntimeException(e); + } + }); + registry = ProtoDescriptorRegistryHolder + .getOrInstall(() -> new ProtoDescriptorRegistry(cqs.getConfiguration(), name -> { + throw new IOException( + ProtoDescriptorRegistryHolder.ENDPOINT_NOT_REGISTERED + ", cannot load " + name); + })).withLoader(loader); + protoDescriptorRegistry = registry; + return registry; + } + @Override public void clearWarnings() throws SQLException { } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixDatabaseMetaData.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixDatabaseMetaData.java index ed63485440f..29c1d09524e 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixDatabaseMetaData.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixDatabaseMetaData.java @@ -503,6 +503,25 @@ public class PhoenixDatabaseMetaData implements DatabaseMetaData { public static final String SYSTEM_IDX_CDC_TRACKER_TABLE = "IDX_CDC_TRACKER"; public static final String SYSTEM_IDX_CDC_TRACKER_NAME = SchemaUtil.getTableName(SYSTEM_CATALOG_SCHEMA, SYSTEM_IDX_CDC_TRACKER_TABLE); + + public static final String SYSTEM_PROTO_DESCRIPTORS_TABLE = "PROTO_DESCRIPTORS"; + public static final String SYSTEM_PROTO_DESCRIPTORS_NAME = + SchemaUtil.getTableName(SYSTEM_CATALOG_SCHEMA, SYSTEM_PROTO_DESCRIPTORS_TABLE); + public static final byte[] SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES = + Bytes.toBytes(SYSTEM_PROTO_DESCRIPTORS_NAME); + public static final String PROTOBUF_NAME = "PROTOBUF_NAME"; + public static final byte[] PROTOBUF_NAME_BYTES = Bytes.toBytes(PROTOBUF_NAME); + public static final String FILE_DESCRIPTOR_SET = "FILE_DESCRIPTOR_SET"; + public static final byte[] FILE_DESCRIPTOR_SET_BYTES = Bytes.toBytes(FILE_DESCRIPTOR_SET); + + public static final String SYSTEM_PROTO_DESC_LINK_TABLE = "PROTO_DESC_LINK"; + public static final String SYSTEM_PROTO_DESC_LINK_NAME = + SchemaUtil.getTableName(SYSTEM_CATALOG_SCHEMA, SYSTEM_PROTO_DESC_LINK_TABLE); + public static final byte[] SYSTEM_PROTO_DESC_LINK_NAME_BYTES = + Bytes.toBytes(SYSTEM_PROTO_DESC_LINK_NAME); + public static final String PROTOBUF_DESCRIPTOR_NAME = "PROTOBUF_DESCRIPTOR_NAME"; + public static final byte[] PROTOBUF_DESCRIPTOR_NAME_BYTES = + Bytes.toBytes(PROTOBUF_DESCRIPTOR_NAME); public static final String LAST_TIMESTAMP = "LAST_TIMESTAMP"; public static final String OWNER_PARTITION_ID = "OWNER_PARTITION_ID"; public static final String TRACKER_STATUS = "STATUS"; diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixStatement.java index 3243c6e63d7..f53023fcf94 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixStatement.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixStatement.java @@ -136,6 +136,7 @@ import org.apache.phoenix.parse.AddJarsStatement; import org.apache.phoenix.parse.AliasedNode; import org.apache.phoenix.parse.AlterIndexStatement; +import org.apache.phoenix.parse.AlterProtobufDescriptorStatement; import org.apache.phoenix.parse.AlterSessionStatement; import org.apache.phoenix.parse.BindableStatement; import org.apache.phoenix.parse.ChangePermsStatement; @@ -145,6 +146,8 @@ import org.apache.phoenix.parse.CreateCDCStatement; import org.apache.phoenix.parse.CreateFunctionStatement; import org.apache.phoenix.parse.CreateIndexStatement; +import org.apache.phoenix.parse.CreateProtobufBundleStatement; +import org.apache.phoenix.parse.CreateProtobufDescriptorStatement; import org.apache.phoenix.parse.CreateSchemaStatement; import org.apache.phoenix.parse.CreateSequenceStatement; import org.apache.phoenix.parse.CreateTableStatement; @@ -157,6 +160,7 @@ import org.apache.phoenix.parse.DropColumnStatement; import org.apache.phoenix.parse.DropFunctionStatement; import org.apache.phoenix.parse.DropIndexStatement; +import org.apache.phoenix.parse.DropProtobufDescriptorStatement; import org.apache.phoenix.parse.DropSchemaStatement; import org.apache.phoenix.parse.DropSequenceStatement; import org.apache.phoenix.parse.DropTableStatement; @@ -1793,6 +1797,92 @@ public MutationState execute() throws SQLException { } } + private interface ProtobufDdlAction { + MutationState run(MetaDataClient client) throws SQLException; + } + + private static MutationPlan protobufDdlPlan(PhoenixStatement stmt, Operation operation, + String explain, ProtobufDdlAction action) { + return new BaseMutationPlan(new StatementContext(stmt), operation) { + @Override + public ExplainPlan getExplainPlan() { + return new ExplainPlan(Collections.singletonList(explain)); + } + + @Override + public MutationState execute() throws SQLException { + return action.run(new MetaDataClient(getContext().getConnection())); + } + }; + } + + private static class ExecutableCreateProtobufDescriptorStatement + extends CreateProtobufDescriptorStatement implements CompilableStatement { + + ExecutableCreateProtobufDescriptorStatement(String protoMessageName, boolean ifNotExists, + String sourceUrl) { + super(protoMessageName, ifNotExists, sourceUrl); + } + + @SuppressWarnings("unchecked") + @Override + public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) + throws SQLException { + return protobufDdlPlan(stmt, getOperation(), "CREATE PROTOBUF DESCRIPTOR", + client -> client.createProtobufDescriptor(this)); + } + } + + private static class ExecutableAlterProtobufDescriptorStatement + extends AlterProtobufDescriptorStatement implements CompilableStatement { + + ExecutableAlterProtobufDescriptorStatement(String protoMessageName, boolean ifExists, + String sourceUrl) { + super(protoMessageName, ifExists, sourceUrl); + } + + @SuppressWarnings("unchecked") + @Override + public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) + throws SQLException { + return protobufDdlPlan(stmt, getOperation(), "ALTER PROTOBUF DESCRIPTOR", + client -> client.alterProtobufDescriptor(this)); + } + } + + private static class ExecutableDropProtobufDescriptorStatement + extends DropProtobufDescriptorStatement implements CompilableStatement { + + ExecutableDropProtobufDescriptorStatement(String protoMessageName, boolean ifExists) { + super(protoMessageName, ifExists); + } + + @SuppressWarnings("unchecked") + @Override + public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) + throws SQLException { + return protobufDdlPlan(stmt, getOperation(), "DROP PROTOBUF DESCRIPTOR", + client -> client.dropProtobufDescriptor(this)); + } + } + + private static class ExecutableCreateProtobufBundleStatement extends CreateProtobufBundleStatement + implements CompilableStatement { + + ExecutableCreateProtobufBundleStatement(List protoMessageNames, boolean ifNotExists, + String sourceUrl) { + super(protoMessageNames, ifNotExists, sourceUrl); + } + + @SuppressWarnings("unchecked") + @Override + public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) + throws SQLException { + return protobufDdlPlan(stmt, getOperation(), "CREATE PROTOBUF BUNDLE", + client -> client.createProtobufBundle(this)); + } + } + private static class ExecutableDropSchemaStatement extends DropSchemaStatement implements CompilableStatement { @@ -2374,6 +2464,31 @@ public DropTableStatement dropTable(TableName tableName, PTableType tableType, b return new ExecutableDropTableStatement(tableName, tableType, ifExists, cascade); } + @Override + public CreateProtobufDescriptorStatement createProtobufDescriptor(String protoMessageName, + boolean ifNotExists, String sourceUrl) { + return new ExecutableCreateProtobufDescriptorStatement(protoMessageName, ifNotExists, + sourceUrl); + } + + @Override + public AlterProtobufDescriptorStatement alterProtobufDescriptor(String protoMessageName, + boolean ifExists, String sourceUrl) { + return new ExecutableAlterProtobufDescriptorStatement(protoMessageName, ifExists, sourceUrl); + } + + @Override + public DropProtobufDescriptorStatement dropProtobufDescriptor(String protoMessageName, + boolean ifExists) { + return new ExecutableDropProtobufDescriptorStatement(protoMessageName, ifExists); + } + + @Override + public CreateProtobufBundleStatement createProtobufBundle(List protoMessageNames, + boolean ifNotExists, String sourceUrl) { + return new ExecutableCreateProtobufBundleStatement(protoMessageNames, ifNotExists, sourceUrl); + } + @Override public DropSchemaStatement dropSchema(String schemaName, boolean ifExists, boolean cascade) { return new ExecutableDropSchemaStatement(schemaName, ifExists, cascade); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/AlterProtobufDescriptorStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/AlterProtobufDescriptorStatement.java new file mode 100644 index 00000000000..77c1e5f0f69 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/AlterProtobufDescriptorStatement.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +/** + * Parsed form of: + * + *

+ * ALTER PROTOBUF DESCRIPTOR [ IF EXISTS ] qualified_proto_name
+ *   FROM url_string_literal       -- URL of a serialized FileDescriptorSet
+ * 
+ *

+ * {@code IF EXISTS} matches the convention of {@code ALTER INDEX (IF EXISTS)?} — when present, the + * statement silently no-ops if the descriptor does not exist (useful for idempotent migration + * scripts that may run on databases where prior versions weren't installed). When absent, a missing + * descriptor raises {@code PROTOBUF_DESCRIPTOR_NOT_FOUND}. + *

+ * {@code IF NOT EXISTS} is deliberately NOT supported on ALTER (it would mean "alter something that + * doesn't exist"). Use {@code CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS} for the create-if-missing + * pattern. + *

+ * Unlike {@code CREATE}, the new descriptor must pass the evolution-envelope check against the + * previously-registered version before it replaces it. Validation is descriptor-local: no + * {@code SYSTEM.CATALOG} scan. Evolution rule enforcement happens downstream in + * {@code ProtoEvolutionValidator}. + */ +public class AlterProtobufDescriptorStatement extends MutableStatement { + + private final String protoMessageName; + private final boolean ifExists; + /** URL of a serialized {@code FileDescriptorSet}. Always non-null in a parsed statement. */ + private final String sourceUrl; + + public AlterProtobufDescriptorStatement(String protoMessageName, boolean ifExists, + String sourceUrl) { + this.protoMessageName = protoMessageName; + this.ifExists = ifExists; + this.sourceUrl = sourceUrl; + } + + @Override + public int getBindCount() { + return 0; + } + + public String getProtoMessageName() { + return protoMessageName; + } + + public boolean isIfExists() { + return ifExists; + } + + /** Returns the source URL of the serialized {@code FileDescriptorSet}. */ + public String getSourceUrl() { + return sourceUrl; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ColumnDef.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ColumnDef.java index 1bfe53b3b97..521cdef44e4 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ColumnDef.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ColumnDef.java @@ -32,6 +32,7 @@ import org.apache.phoenix.schema.SortOrder; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PDecimal; +import org.apache.phoenix.schema.types.PProtobuf; import org.apache.phoenix.schema.types.PVarbinary; import org.apache.phoenix.util.ExpressionUtil; import org.apache.phoenix.util.SchemaUtil; @@ -56,6 +57,11 @@ public class ColumnDef { private final String expressionStr; private final Integer encodedQualifier; private final boolean isRowTimestamp; + /** + * For PROTOBUF columns: the fully-qualified protobuf message name as written between the angle + * brackets of {@code PROTOBUF}. {@code null} for every other type. + */ + private final String protoMessageName; public ColumnDef(ColumnDef def, String expressionStr) { this.columnDefName = def.columnDefName; @@ -70,11 +76,20 @@ public ColumnDef(ColumnDef def, String expressionStr) { this.encodedQualifier = def.encodedQualifier; this.isRowTimestamp = def.isRowTimestamp; this.expressionStr = expressionStr; + this.protoMessageName = def.protoMessageName; } ColumnDef(ColumnName columnDefName, String sqlTypeName, boolean isArray, Integer arrSize, Boolean isNull, Integer maxLength, Integer scale, boolean isPK, SortOrder sortOrder, String expressionStr, Integer encodedQualifier, boolean isRowTimestamp) { + this(columnDefName, sqlTypeName, isArray, arrSize, isNull, maxLength, scale, isPK, sortOrder, + expressionStr, encodedQualifier, isRowTimestamp, null); + } + + ColumnDef(ColumnName columnDefName, String sqlTypeName, boolean isArray, Integer arrSize, + Boolean isNull, Integer maxLength, Integer scale, boolean isPK, SortOrder sortOrder, + String expressionStr, Integer encodedQualifier, boolean isRowTimestamp, + String protoMessageName) { try { Preconditions.checkNotNull(sortOrder); PDataType baseType; @@ -85,6 +100,19 @@ public ColumnDef(ColumnDef def, String expressionStr) { // fixed size or like postgres allow infinite. May be the data types max limit can // be used for the array size (May be too big) if (isArray) { + // Catch PROTOBUF arrays *before* PDataType.sqlArrayType(...) calls fromTypeId on the + // synthetic PROTOBUF-array slot (which would surface as a generic "Unsupported sql + // type: 12500" IllegalDataException). PROTOBUF wire format has no canonical + // inter-element separator, so array encoding is not safe. Compare against the + // canonical type-name on PProtobuf.INSTANCE rather than a hardcoded "PROTOBUF" literal + // so this stays in sync if the singleton's getSqlTypeName() ever moves. + if ( + sqlTypeName != null && PProtobuf.INSTANCE.getSqlTypeName() + .equals(SchemaUtil.normalizeIdentifier(sqlTypeName)) + ) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_NOT_ALLOWED_IN_ARRAY) + .setColumnName(columnDefName.getColumnName()).build().buildException(); + } this.isArray = true; dataType = sqlTypeName == null ? null @@ -149,12 +177,33 @@ public ColumnDef(ColumnDef def, String expressionStr) { } } } + if (dataType == PProtobuf.INSTANCE && isPK) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_NOT_ALLOWED_AS_PRIMARY_KEY) + .setColumnName(columnDefName.getColumnName()).build().buildException(); + } if (dataType != null && !dataType.canBePrimaryKey() && isPK) { throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_PRIMARY_KEY_CONSTRAINT) .setColumnName(columnDefName.getColumnName()) .setMessage("," + dataType.toString() + " is not supported as primary key,").build() .buildException(); } + // PROTOBUF — syntax-only check here: the angle-bracketed name must be present + // (PROTOBUF on its own — or PROTOBUF<> which the lexer collapses to NOEQ2 — leaves + // protoMessageName null/empty). Descriptor-existence validation happens later in + // MetaDataClient (which has the connection needed to look up the per-connection + // ProtoDescriptorRegistry against SYSTEM.PROTO_DESCRIPTORS). + if (dataType == PProtobuf.INSTANCE) { + if (protoMessageName == null || protoMessageName.isEmpty()) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_MESSAGE_NAME_REQUIRED) + .setColumnName(columnDefName.getColumnName()).build().buildException(); + } + } + if ( + dataType != PProtobuf.INSTANCE && protoMessageName != null && !protoMessageName.isEmpty() + ) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_MESSAGE_NAME_NOT_ALLOWED) + .setColumnName(columnDefName.getColumnName()).build().buildException(); + } this.maxLength = maxLength; this.scale = scale; this.isPK = isPK; @@ -163,6 +212,7 @@ public ColumnDef(ColumnDef def, String expressionStr) { this.expressionStr = expressionStr; this.encodedQualifier = encodedQualifier; this.isRowTimestamp = isRowTimestamp; + this.protoMessageName = protoMessageName; } catch (SQLException e) { throw new ParseException(e); } @@ -229,6 +279,14 @@ public boolean isRowTimestamp() { return isRowTimestamp; } + /** + * For PROTOBUF columns, the fully-qualified protobuf message name as written between the angle + * brackets of {@code PROTOBUF}. Returns {@code null} for every other type. + */ + public String getProtoMessageName() { + return protoMessageName; + } + public void setIsPK(boolean isPK) { this.isPK = isPK; } @@ -245,6 +303,11 @@ public String toString() { StringBuilder buf = new StringBuilder(columnDefName.getColumnNode().toString()); buf.append(' '); buf.append(dataType.getSqlTypeName()); + if (protoMessageName != null) { + buf.append('<'); + buf.append(protoMessageName); + buf.append('>'); + } if (maxLength != null) { buf.append('('); buf.append(maxLength); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufBundleStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufBundleStatement.java new file mode 100644 index 00000000000..9db1f2a1f3c --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufBundleStatement.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.util.Collections; +import java.util.List; + +/** + * Parsed form of: + * + *

+ * CREATE PROTOBUF BUNDLE [ IF NOT EXISTS ] (
+ *   qualified_proto_name [, qualified_proto_name ]*
+ * )
+ *   FROM url_string_literal
+ * ;
+ * 
+ *

+ * Multi-message registration in a single DDL statement — a syntactic convenience over N individual + * {@code CREATE PROTOBUF DESCRIPTOR} statements that all share the same source URL. The URL points + * at a single {@code FileDescriptorSet} (typically a + * {@code protoc --include_imports --descriptor_set_out=...} output containing many `.proto` files); + * the statement registers one Phoenix descriptor per name in the parenthesized list, all sharing + * that source. + *

+ * Semantics: + *

    + *
  • Every name in the list must resolve to a top-level message in the loaded + * {@code FileDescriptorSet}. If any name fails resolution the whole bundle is rejected with + * {@code PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE} naming the offending entry; no partial + * registration occurs.
  • + *
  • {@code IF NOT EXISTS} is per-name: existing descriptors with the same name are skipped + * without overwrite; new names are registered. The statement is therefore idempotent over the union + * of (already-registered, newly-registered) names.
  • + *
  • Duplicate names within the list are a parse error (caught by the grammar's unique-list + * check).
  • + *
+ * Validation (descriptor compilation, name-resolution, {@code FileDescriptorSet} sanity) happens + * downstream in {@code MetaDataClient.createProtobufBundle}; this class is a pure parse-time data + * carrier. + */ +public class CreateProtobufBundleStatement extends MutableStatement { + + private final List protoMessageNames; + private final boolean ifNotExists; + /** URL of a serialized {@code FileDescriptorSet}. Always non-null in a parsed statement. */ + private final String sourceUrl; + + public CreateProtobufBundleStatement(List protoMessageNames, boolean ifNotExists, + String sourceUrl) { + this.protoMessageNames = protoMessageNames == null + ? Collections.emptyList() + : Collections.unmodifiableList(protoMessageNames); + this.ifNotExists = ifNotExists; + this.sourceUrl = sourceUrl; + } + + @Override + public int getBindCount() { + return 0; + } + + /** + * Returns the immutable list of fully-qualified proto message names being registered. List order + * matches the source-text order in the DDL (used for deterministic error messages and audit + * logging); registration is not order-sensitive. + */ + public List getProtoMessageNames() { + return protoMessageNames; + } + + public boolean isIfNotExists() { + return ifNotExists; + } + + /** Returns the source URL of the serialized {@code FileDescriptorSet}. */ + public String getSourceUrl() { + return sourceUrl; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufDescriptorStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufDescriptorStatement.java new file mode 100644 index 00000000000..5e6663d0ee3 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/CreateProtobufDescriptorStatement.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +/** + * Parsed form of: + * + *
+ * CREATE PROTOBUF DESCRIPTOR [ IF NOT EXISTS ] qualified_proto_name
+ *   FROM url_string_literal       -- URL of a serialized FileDescriptorSet
+ * 
+ *

+ * The URL points at a {@code FileDescriptorSet} binary produced by + * {@code protoc --include_imports --descriptor_set_out=...}. There is no inline {@code .proto} text + * form — the binary-only design avoids the maintenance cost of carrying a proto grammar in Phoenix. + * Validation (descriptor compilation, name-resolution, {@code FileDescriptorSet} sanity) happens + * downstream in {@code MetaDataClient.createProtobufDescriptor}; this class is a pure parse-time + * data carrier. + *

+ * The proto message name preserves the source case (proto identifiers are case-sensitive) via the + * {@code proto_message_name_part} grammar rule's wildcard capture — see PhoenixSQL.g for the + * case-preservation mechanism. + */ +public class CreateProtobufDescriptorStatement extends MutableStatement { + + private final String protoMessageName; + private final boolean ifNotExists; + /** URL of a serialized {@code FileDescriptorSet}. Always non-null in a parsed statement. */ + private final String sourceUrl; + + public CreateProtobufDescriptorStatement(String protoMessageName, boolean ifNotExists, + String sourceUrl) { + this.protoMessageName = protoMessageName; + this.ifNotExists = ifNotExists; + this.sourceUrl = sourceUrl; + } + + @Override + public int getBindCount() { + return 0; + } + + public String getProtoMessageName() { + return protoMessageName; + } + + public boolean isIfNotExists() { + return ifNotExists; + } + + /** Returns the source URL of the serialized {@code FileDescriptorSet}. */ + public String getSourceUrl() { + return sourceUrl; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/DropProtobufDescriptorStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/DropProtobufDescriptorStatement.java new file mode 100644 index 00000000000..1b1e7ca144c --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/DropProtobufDescriptorStatement.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import org.apache.phoenix.jdbc.PhoenixStatement.Operation; + +/** + * Parsed form of: + * + *

+ * DROP PROTOBUF DESCRIPTOR [ IF EXISTS ] qualified_proto_name
+ * 
+ *

+ * The in-use check at execution time queries {@code SYSTEM.PROTO_DESC_LINK} via a single-region + * prefix scan keyed by the descriptor name; {@code SYSTEM.CATALOG} is never scanned (the + * multi-minute cost of full {@code SYSTEM.CATALOG} scans at production scale is what motivated the + * auxiliary link table). + */ +public class DropProtobufDescriptorStatement extends MutableStatement { + + private final String protoMessageName; + private final boolean ifExists; + + public DropProtobufDescriptorStatement(String protoMessageName, boolean ifExists) { + this.protoMessageName = protoMessageName; + this.ifExists = ifExists; + } + + @Override + public int getBindCount() { + return 0; + } + + /** + * Overrides {@link MutableStatement}'s default {@code Operation.UPSERT} to match the convention + * every other Phoenix {@code DROP *} statement uses ({@code DropTableStatement}, + * {@code DropSchemaStatement}, {@code DropIndexStatement}, {@code DropSequenceStatement} all + * return {@code Operation.DELETE}). The DROP-as-delete classification matters for Phoenix's + * mutation routing and metrics; without this override the statement would be mis-bucketed as an + * UPSERT-class mutation. + */ + @Override + public Operation getOperation() { + return Operation.DELETE; + } + + public String getProtoMessageName() { + return protoMessageName; + } + + public boolean isIfExists() { + return ifExists; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseContext.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseContext.java index 9a67bcbd0b2..1d585512005 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseContext.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseContext.java @@ -62,6 +62,10 @@ public ParseContext peek() { public boolean isEmpty() { return stack.isEmpty(); } + + public int size() { + return stack.size(); + } } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseNodeFactory.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseNodeFactory.java index 7c3450bb665..c1ba6eaa3b1 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseNodeFactory.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ParseNodeFactory.java @@ -326,6 +326,18 @@ public ColumnDef columnDef(ColumnName columnDefName, String sqlTypeName, boolean isPK, sortOrder, expressionStr, encodedQualifier, isRowTimestamp); } + /** + * Overload that carries the PROTOBUF message name (the text inside the angle brackets of + * {@code PROTOBUF}). Pass {@code null} for non-PROTOBUF columns. + */ + public ColumnDef columnDef(ColumnName columnDefName, String sqlTypeName, String protoMessageName, + boolean isArray, Integer arrSize, Boolean isNull, Integer maxLength, Integer scale, + boolean isPK, SortOrder sortOrder, String expressionStr, Integer encodedQualifier, + boolean isRowTimestamp) { + return new ColumnDef(columnDefName, sqlTypeName, isArray, arrSize, isNull, maxLength, scale, + isPK, sortOrder, expressionStr, encodedQualifier, isRowTimestamp, protoMessageName); + } + public ColumnDef columnDef(ColumnName columnDefName, String sqlTypeName, boolean isArray, Integer arrSize, Boolean isNull, Integer maxLength, Integer scale, boolean isPK, SortOrder sortOrder, String expressionStr, boolean isRowTimestamp) { @@ -398,6 +410,47 @@ public CreateSchemaStatement createSchema(String schemaName, boolean ifNotExists return new CreateSchemaStatement(schemaName, ifNotExists); } + /** + * Parses {@code CREATE PROTOBUF DESCRIPTOR [IF NOT EXISTS] name FROM 'url'}. The URL points at a + * serialized {@code FileDescriptorSet} produced by + * {@code protoc --include_imports --descriptor_set_out=...}. + */ + public CreateProtobufDescriptorStatement createProtobufDescriptor(String protoMessageName, + boolean ifNotExists, String sourceUrl) { + return new CreateProtobufDescriptorStatement(protoMessageName, ifNotExists, sourceUrl); + } + + /** + * Parses {@code ALTER PROTOBUF DESCRIPTOR [IF EXISTS] name FROM 'url'}. With {@code IF EXISTS} + * the statement silently no-ops if the descriptor does not exist (matches the + * {@code ALTER INDEX (IF EXISTS)?} convention). {@code IF NOT EXISTS} is deliberately not + * supported. + */ + public AlterProtobufDescriptorStatement alterProtobufDescriptor(String protoMessageName, + boolean ifExists, String sourceUrl) { + return new AlterProtobufDescriptorStatement(protoMessageName, ifExists, sourceUrl); + } + + /** + * Parses {@code DROP PROTOBUF DESCRIPTOR [IF EXISTS] name}. + */ + public DropProtobufDescriptorStatement dropProtobufDescriptor(String protoMessageName, + boolean ifExists) { + return new DropProtobufDescriptorStatement(protoMessageName, ifExists); + } + + /** + * Parses {@code CREATE PROTOBUF BUNDLE [IF NOT EXISTS] (name1, name2, ...) FROM 'url'}. The URL + * points at a single {@code FileDescriptorSet} (typically produced by + * {@code protoc --include_imports --descriptor_set_out=...}) and the statement registers one + * Phoenix descriptor per name in the list, all sharing that source. Multi-message convenience + * over N individual {@code CREATE PROTOBUF DESCRIPTOR} statements. + */ + public CreateProtobufBundleStatement createProtobufBundle(List protoMessageNames, + boolean ifNotExists, String sourceUrl) { + return new CreateProtobufBundleStatement(protoMessageNames, ifNotExists, sourceUrl); + } + public CreateIndexStatement createIndex(NamedNode indexName, NamedTableNode dataTable, IndexKeyConstraint ikConstraint, List includeColumns, List splits, ListMultimap> props, boolean ifNotExists, IndexType indexType, diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoArrayLengthParseNode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoArrayLengthParseNode.java new file mode 100644 index 00000000000..0c5340a0b4e --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoArrayLengthParseNode.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.sql.SQLException; +import java.util.List; +import org.apache.phoenix.compile.StatementContext; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.function.FunctionExpression; +import org.apache.phoenix.expression.function.ProtoArrayLengthFunction; +import org.apache.phoenix.expression.function.ProtoFunctionsUtil; + +/** + * Parse node for {@code PROTO_ARRAY_LENGTH(payload, path)}. + */ +public class ProtoArrayLengthParseNode extends FunctionParseNode { + + public ProtoArrayLengthParseNode(String name, List children, + BuiltInFunctionInfo info) { + super(name, children, info); + } + + @Override + public FunctionExpression create(List children, StatementContext context) + throws SQLException { + String descriptorName = ProtoValueParseNode.resolveDescriptorNameForPayload(children.get(0), + context, "PROTO_ARRAY_LENGTH"); + ProtoArrayLengthFunction function = + new ProtoArrayLengthFunction(ProtoFunctionsUtil.withDescriptorName(children, descriptorName), + context.getConnection().getProtoDescriptorRegistry()); + function.ensurePlan(); + return function; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoExistsParseNode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoExistsParseNode.java new file mode 100644 index 00000000000..233bdea843f --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoExistsParseNode.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.sql.SQLException; +import java.util.List; +import org.apache.phoenix.compile.StatementContext; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.function.FunctionExpression; +import org.apache.phoenix.expression.function.ProtoExistsFunction; +import org.apache.phoenix.expression.function.ProtoFunctionsUtil; + +/** + * Parse node for the {@code PROTO_EXISTS(payload, path)} function. + */ +public class ProtoExistsParseNode extends FunctionParseNode { + + public ProtoExistsParseNode(String name, List children, BuiltInFunctionInfo info) { + super(name, children, info); + } + + @Override + public FunctionExpression create(List children, StatementContext context) + throws SQLException { + String descriptorName = + ProtoValueParseNode.resolveDescriptorNameForPayload(children.get(0), context, "PROTO_EXISTS"); + ProtoExistsFunction function = + new ProtoExistsFunction(ProtoFunctionsUtil.withDescriptorName(children, descriptorName), + context.getConnection().getProtoDescriptorRegistry()); + function.ensurePlan(); + return function; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoFieldTypeParseNode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoFieldTypeParseNode.java new file mode 100644 index 00000000000..c1404c7dacf --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoFieldTypeParseNode.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.sql.SQLException; +import java.util.List; +import org.apache.phoenix.compile.StatementContext; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.function.FunctionExpression; +import org.apache.phoenix.expression.function.ProtoFieldTypeFunction; +import org.apache.phoenix.expression.function.ProtoFunctionsUtil; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.expression.util.proto.ProtoPathParser; +import org.apache.phoenix.expression.util.proto.ProtoPathResolver; + +/** + * Parse node for {@code PROTO_FIELD_TYPE(payload, path)}. + */ +public class ProtoFieldTypeParseNode extends FunctionParseNode { + + public ProtoFieldTypeParseNode(String name, List children, BuiltInFunctionInfo info) { + super(name, children, info); + } + + @Override + public FunctionExpression create(List children, StatementContext context) + throws SQLException { + String descriptorName = ProtoValueParseNode.resolveDescriptorNameForPayload(children.get(0), + context, "PROTO_FIELD_TYPE"); + String pathLiteral = ProtoFunctionsUtil.requiredStringLiteral(children.get(1), + ProtoFieldTypeFunction.NAME, "path"); + String resolvedTypeName = resolveTypeName(context, descriptorName, pathLiteral); + return new ProtoFieldTypeFunction( + ProtoFunctionsUtil.withDescriptorName(children, resolvedTypeName)); + } + + private static String resolveTypeName(StatementContext context, String descriptorName, + String pathLiteral) throws SQLException { + List parsed = ProtoPathParser.parse(pathLiteral); + PathPlan plan = ProtoFunctionsUtil.withDescriptorRefreshOnMiss( + context.getConnection().getProtoDescriptorRegistry(), descriptorName, + ProtoFieldTypeFunction.NAME, + cached -> ProtoPathResolver.resolveForExistence(parsed, cached.getDescriptor(), pathLiteral)); + return ProtoPathResolver.canonicalSqlTypeName(plan.getLeafProtoFieldType()); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueAtTagParseNode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueAtTagParseNode.java new file mode 100644 index 00000000000..fe84735e477 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueAtTagParseNode.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.sql.SQLException; +import java.util.List; +import org.apache.phoenix.compile.StatementContext; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.function.FunctionExpression; +import org.apache.phoenix.expression.function.ProtoFunctionsUtil; +import org.apache.phoenix.expression.function.ProtoValueAtTagFunction; +import org.apache.phoenix.expression.util.proto.ProtoTagPathParser; +import org.apache.phoenix.expression.util.proto.ProtoTagPathWalker; +import org.apache.phoenix.schema.types.PDataType; + +/** + * Parse node for {@code PROTO_VALUE_AT_TAG(payload, tagPath, sqlType[, default])}. Validates the + * tag-path grammar and SQL type at compile time. Does not require a descriptor — works on both + * {@code PROTOBUF<...>} and plain {@code VARBINARY} columns. + */ +public class ProtoValueAtTagParseNode extends FunctionParseNode { + + public ProtoValueAtTagParseNode(String name, List children, BuiltInFunctionInfo info) { + super(name, children, info); + } + + @Override + public FunctionExpression create(List children, StatementContext context) + throws SQLException { + String pathLiteral = ProtoFunctionsUtil.requiredStringLiteral(children.get(1), + ProtoValueAtTagFunction.NAME, "tag-path"); + String typeName = ProtoFunctionsUtil.requiredStringLiteral(children.get(2), + ProtoValueAtTagFunction.NAME, "SQL type"); + + ProtoTagPathParser.parse(pathLiteral); + PDataType sqlType = + ProtoFunctionsUtil.resolveSqlType(typeName, ProtoValueAtTagFunction.NAME); + int wireType = ProtoTagPathWalker.wireTypeForSqlType(sqlType); + if (wireType < 0) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage("PROTO_VALUE_AT_TAG: unsupported SQL type '" + typeName + "'").build() + .buildException(); + } + + // validate() pads an omitted default; keep it only if the query supplied one. + return new ProtoValueAtTagFunction(ProtoFunctionsUtil.withCompiledDefault(children, + getChildren().size() > 3, ProtoValueAtTagFunction.NAME)); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueParseNode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueParseNode.java new file mode 100644 index 00000000000..82141f027d6 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ProtoValueParseNode.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.parse; + +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.compile.ColumnResolver; +import org.apache.phoenix.compile.StatementContext; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.expression.CoerceExpression; +import org.apache.phoenix.expression.ColumnExpression; +import org.apache.phoenix.expression.Expression; +import org.apache.phoenix.expression.KeyValueColumnExpression; +import org.apache.phoenix.expression.ProjectedColumnExpression; +import org.apache.phoenix.expression.SingleCellColumnExpression; +import org.apache.phoenix.expression.function.FunctionExpression; +import org.apache.phoenix.expression.function.ProtoFunctionsUtil; +import org.apache.phoenix.expression.function.ProtoValueFunction; +import org.apache.phoenix.schema.PColumn; +import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.TableRef; +import org.apache.phoenix.schema.types.PProtobuf; + +/** + * Parse node for the {@code PROTO_VALUE(payload, path, type[, default])} function. + */ +public class ProtoValueParseNode extends FunctionParseNode { + + public ProtoValueParseNode(String name, List children, BuiltInFunctionInfo info) { + super(name, children, info); + } + + @Override + public FunctionExpression create(List children, StatementContext context) + throws SQLException { + String descriptorName = + resolveDescriptorNameForPayload(children.get(0), context, "PROTO_VALUE"); + // validate() pads an omitted default; keep it only if the query supplied one. + List compiled = ProtoFunctionsUtil.withCompiledDefault(children, + getChildren().size() > 3, ProtoValueFunction.NAME); + ProtoValueFunction function = + new ProtoValueFunction(ProtoFunctionsUtil.withDescriptorName(compiled, descriptorName), + context.getConnection().getProtoDescriptorRegistry()); + function.ensurePlan(); + return function; + } + + public static String resolveDescriptorNameForPayload(Expression payload, StatementContext context, + String functionName) throws SQLException { + Expression unwrapped = payload; + while (unwrapped instanceof CoerceExpression) { + unwrapped = ((CoerceExpression) unwrapped).getChild(); + } + if (!(unwrapped instanceof ColumnExpression)) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage(functionName + " requires the first argument to be a direct " + + "reference to a PROTOBUF<...>-typed column; expression-typed payloads " + + "and cast chains are not yet supported.") + .build().buildException(); + } + PColumn payloadColumn = resolveColumn(context.getResolver(), unwrapped); + if (payloadColumn == null) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage(functionName + " could not resolve the payload column '" + unwrapped + + "' against any table in scope") + .build().buildException(); + } + if ( + !(payloadColumn.getDataType() instanceof PProtobuf) + && payloadColumn.getProtoMessageName() == null + ) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage(functionName + " requires the payload column to be typed " + + "PROTOBUF<...>; column '" + payloadColumn.getName().getString() + "' is typed " + + payloadColumn.getDataType().getSqlTypeName()) + .build().buildException(); + } + String descriptorName = payloadColumn.getProtoMessageName(); + if (descriptorName == null || descriptorName.isEmpty()) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH) + .setMessage(functionName + " payload column '" + payloadColumn.getName().getString() + + "' has no attached PROTOBUF descriptor name — the SYSTEM.CATALOG entry " + + "may be corrupt or missing PROTOBUF_DESCRIPTOR_NAME") + .build().buildException(); + } + return descriptorName; + } + + /** + * Returns the source {@link PColumn} a projected expression reads from, looking through + * coercions, or null if the expression is not a direct column reference. + */ + public static PColumn resolveSourceColumn(ColumnResolver resolver, Expression expression) { + Expression unwrapped = expression; + while (unwrapped instanceof CoerceExpression) { + unwrapped = ((CoerceExpression) unwrapped).getChild(); + } + if (unwrapped.getDataType() != PProtobuf.INSTANCE) { + return null; + } + return resolveColumn(resolver, unwrapped); + } + + private static PColumn resolveColumn(ColumnResolver resolver, Expression unwrapped) { + if (unwrapped instanceof ProjectedColumnExpression) { + return ((ProjectedColumnExpression) unwrapped).getColumn(); + } + if (unwrapped instanceof KeyValueColumnExpression) { + return findColumn(resolver, (KeyValueColumnExpression) unwrapped); + } + return null; + } + + private static PColumn findColumn(ColumnResolver resolver, KeyValueColumnExpression kv) { + if (resolver == null) { + return null; + } + byte[] cf = kv.getColumnFamily(); + // Single-cell storage shares one HBase qualifier across columns; the column's own qualifier is + // its position in the cell. + byte[] cq = kv instanceof SingleCellColumnExpression + ? ((SingleCellColumnExpression) kv).getPositionInArray() + : kv.getColumnQualifier(); + for (TableRef tableRef : resolver.getTables()) { + PTable table = tableRef.getTable(); + for (PColumn column : table.getColumns()) { + if (column.getFamilyName() == null) { + continue; + } + if (!Bytes.equals(column.getFamilyName().getBytes(), cf)) { + continue; + } + byte[] columnQualifier = column.getColumnQualifierBytes() != null + ? column.getColumnQualifierBytes() + : column.getName().getBytes(); + if (Arrays.equals(columnQualifier, cq)) { + return column; + } + } + } + return null; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/SQLParser.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/SQLParser.java index 8df20d59582..4f4fa4b1ced 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/SQLParser.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/SQLParser.java @@ -94,6 +94,14 @@ public BindableStatement nextStatement(ParseNodeFactory factory) throws SQLExcep } } + /** + * Test-only: depth of the underlying parser's ParseContext stack. Must be zero between + * statements; a non-zero value means a grammar rule pushed a frame it never popped. + */ + int getContextStackDepth() { + return parser.getContextStackDepth(); + } + /** * Parses the input as a SQL select or upsert statement. */ diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistry.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistry.java new file mode 100644 index 00000000000..7cc1856e21d --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistry.java @@ -0,0 +1,288 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import org.apache.hadoop.conf.Configuration; +import org.apache.phoenix.exception.PhoenixIOException; +import org.apache.phoenix.expression.util.proto.PathPlan; +import org.apache.phoenix.schema.types.PDataType; + +import org.apache.phoenix.thirdparty.com.google.common.base.Ticker; +import org.apache.phoenix.thirdparty.com.google.common.cache.Cache; +import org.apache.phoenix.thirdparty.com.google.common.cache.CacheBuilder; +import org.apache.phoenix.thirdparty.com.google.common.util.concurrent.UncheckedExecutionException; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +/** + * Per-JVM cache mapping fully-qualified PROTOBUF message names to resolved protobuf + * {@code Descriptor} instances. {@link #withLoader} gives a caller its own loader over the same + * cache. + */ +public final class ProtoDescriptorRegistry { + + @FunctionalInterface + public interface Loader { + /** + * Returns the raw {@code FileDescriptorSet} bytes registered under + * {@code fullyQualifiedMessageName} in {@code SYSTEM.PROTO_DESCRIPTORS}, or {@code null} if the + * name is not registered. + */ + byte[] load(String fullyQualifiedMessageName) throws IOException; + } + + /** + * Cache entry: the resolved message Descriptor. Also owns a per-descriptor PathPlan cache keyed + * by {@code (pathLiteral, PlanKind, requestedType)}. + */ + public static final class CachedDescriptor { + private final Descriptors.Descriptor descriptor; + private final int sizeBytes; + private final Cache pathPlans; + + CachedDescriptor(Descriptors.Descriptor descriptor, int sizeBytes, long planCacheMaxSize, + long planCacheTtlSeconds, Ticker ticker) { + this.descriptor = descriptor; + this.sizeBytes = sizeBytes; + this.pathPlans = CacheBuilder.newBuilder().maximumSize(planCacheMaxSize) + .expireAfterWrite(planCacheTtlSeconds, TimeUnit.SECONDS).ticker(ticker).build(); + } + + public Descriptors.Descriptor getDescriptor() { + return descriptor; + } + + public PathPlan getOrCompilePathPlan(String pathLiteral, PlanKind kind, + PDataType requestedType, PathPlanCompiler compiler) throws SQLException { + // PlanKind partitions the cache so PROTO_VALUE / PROTO_EXISTS / + // PROTO_ARRAY_LENGTH plans for the same path never share a cache entry. + String key = pathLiteral + '|' + kind.name() + '|' + + (requestedType == null ? "" : requestedType.getSqlTypeName()); + try { + return pathPlans.get(key, () -> compiler.compile(descriptor)); + } catch (ExecutionException | UncheckedExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof SQLException) { + throw (SQLException) cause; + } + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new SQLException(cause != null ? cause : e); + } + } + } + + @FunctionalInterface + public interface PathPlanCompiler { + PathPlan compile(Descriptors.Descriptor descriptor) throws SQLException; + } + + public enum PlanKind { + VALUE, + PRESENCE, + ARRAY_LENGTH + } + + /** + * Bounds the per-descriptor plan cache and the forced-refresh table, not the descriptor cache. + */ + public static final String CACHE_MAX_SIZE_ATTRIB = "phoenix.protobuf.descriptor.cache.max.size"; + public static final long DEFAULT_CACHE_MAX_SIZE = 1024L; + + public static final String CACHE_MAX_HEAP_PERCENT_ATTRIB = + "phoenix.protobuf.descriptor.cache.max.heap.percent"; + public static final int DEFAULT_CACHE_MAX_HEAP_PERCENT = 5; + + public static final String CACHE_TTL_SECONDS_ATTRIB = + "phoenix.protobuf.descriptor.cache.ttl.seconds"; + public static final long DEFAULT_CACHE_TTL_SECONDS = 3600L; + + /** + * Minimum interval between two forced refreshes of the same descriptor name (see + * {@link #tryForceRefresh(String)}). Bounds the reload rate when a path is genuinely wrong rather + * than stale. + */ + public static final String MIN_FORCED_REFRESH_INTERVAL_MS_ATTRIB = + "phoenix.protobuf.descriptor.cache.min.forced.refresh.interval.ms"; + public static final long DEFAULT_MIN_FORCED_REFRESH_INTERVAL_MS = 10000L; + + private final Cache> byName; + private final Cache recentForcedRefreshes; + private final Loader loader; + private final ProtoDescriptorResolver resolver; + private final Ticker ticker; + private final long planCacheMaxSize; + private final long planCacheTtlSeconds; + + public ProtoDescriptorRegistry(Configuration conf, Loader loader) { + this(conf, loader, new ProtoDescriptorResolver(), Ticker.systemTicker()); + } + + ProtoDescriptorRegistry(Configuration conf, Loader loader, ProtoDescriptorResolver resolver, + Ticker ticker) { + if (loader == null) { + throw new IllegalArgumentException("Loader must not be null"); + } + if (resolver == null) { + throw new IllegalArgumentException("Resolver must not be null"); + } + if (ticker == null) { + throw new IllegalArgumentException("Ticker must not be null"); + } + this.loader = loader; + this.resolver = resolver; + this.ticker = ticker; + long maxSize = readPositiveLong(conf, CACHE_MAX_SIZE_ATTRIB, DEFAULT_CACHE_MAX_SIZE); + long ttlSeconds = readPositiveLong(conf, CACHE_TTL_SECONDS_ATTRIB, DEFAULT_CACHE_TTL_SECONDS); + this.planCacheMaxSize = maxSize; + this.planCacheTtlSeconds = ttlSeconds; + // A load on first use or expiry runs on the calling thread, bounded only by the query timeout. + // Stale entries are not served during a reload, to keep the cache simple. + // Up to 10% shorter per JVM so RegionServers don't all reload against the one region together. + long ttlMs = TimeUnit.SECONDS.toMillis(ttlSeconds); + ttlMs -= ThreadLocalRandom.current().nextLong(ttlMs / 10 + 1); + this.byName = CacheBuilder.newBuilder().maximumWeight(cacheMaxBytes(conf)) + .weigher((String k, Optional v) -> v + .map(cachedDescriptor -> cachedDescriptor.sizeBytes).orElse(0)) + .concurrencyLevel(1).expireAfterWrite(ttlMs, TimeUnit.MILLISECONDS).ticker(ticker).build(); + long minRefreshMs = readPositiveLong(conf, MIN_FORCED_REFRESH_INTERVAL_MS_ATTRIB, + DEFAULT_MIN_FORCED_REFRESH_INTERVAL_MS); + this.recentForcedRefreshes = CacheBuilder.newBuilder().maximumSize(maxSize) + .expireAfterWrite(minRefreshMs, TimeUnit.MILLISECONDS).ticker(ticker).build(); + } + + private ProtoDescriptorRegistry(ProtoDescriptorRegistry shared, Loader loader) { + this.byName = shared.byName; + this.recentForcedRefreshes = shared.recentForcedRefreshes; + this.loader = loader; + this.resolver = shared.resolver; + this.ticker = shared.ticker; + this.planCacheMaxSize = shared.planCacheMaxSize; + this.planCacheTtlSeconds = shared.planCacheTtlSeconds; + } + + /** + * Returns a view that shares this registry's caches but loads misses with {@code loader}, so + * every caller in the JVM sees one cache entry per name however it reaches the catalog. + */ + public ProtoDescriptorRegistry withLoader(Loader loader) { + if (loader == null) { + throw new IllegalArgumentException("Loader must not be null"); + } + return new ProtoDescriptorRegistry(this, loader); + } + + /** + * Evicts the cached entry for {@code fullyQualifiedMessageName} so the next {@link #lookup} + * reloads it from {@code SYSTEM.PROTO_DESCRIPTORS}, unless the same name was already + * force-refreshed within the configured minimum interval. + *

+ * Used when path resolution fails against a possibly stale descriptor (another client ran + * {@code CREATE}/{@code ALTER PROTOBUF DESCRIPTOR} and this JVM's entry has not reached its TTL + * yet). Evolution is add-only, so one reload is enough to pick up any field the caller could + * legitimately reference. + * @return {@code true} if the caller won the refresh and should retry once; {@code false} if a + * refresh happened recently (the failure is then not caused by staleness of more than the + * interval) or the name is empty + */ + public boolean tryForceRefresh(String fullyQualifiedMessageName) { + if (fullyQualifiedMessageName == null || fullyQualifiedMessageName.isEmpty()) { + return false; + } + if ( + recentForcedRefreshes.asMap().putIfAbsent(fullyQualifiedMessageName, Boolean.TRUE) != null + ) { + return false; + } + byName.invalidate(fullyQualifiedMessageName); + return true; + } + + /** + * Resolves {@code fullyQualifiedMessageName} to a {@link CachedDescriptor}, hitting the cache + * first and falling back to the {@link Loader} on miss. Returns {@code null} if the descriptor is + * not registered (Loader returned null) or if the registered bytes do not contain a top-level + * message matching the requested name (resolver filtered). Misses are not cached, so a descriptor + * registered after a failed lookup is visible on the next one. + *

+ * Single-flight per key — Guava's {@code Cache.get(K, Callable)} guarantees only one concurrent + * loader call for the same key; other callers block until the load completes and then share the + * cached result. + * @throws PhoenixIOException if the Loader throws {@link IOException} (e.g. catalog unreachable) + * or if the resolver fails to parse the bytes (e.g. corrupt descriptor + * cell) + */ + public CachedDescriptor lookup(String fullyQualifiedMessageName) throws PhoenixIOException { + if (fullyQualifiedMessageName == null || fullyQualifiedMessageName.isEmpty()) { + return null; + } + Optional result; + try { + result = byName.get(fullyQualifiedMessageName, () -> { + byte[] bytes = loader.load(fullyQualifiedMessageName); + if (bytes == null) { + return Optional.empty(); + } + Descriptors.Descriptor descriptor = resolver.resolve(bytes, fullyQualifiedMessageName); + if (descriptor == null) { + return Optional.empty(); + } + return Optional.of(new CachedDescriptor(descriptor, bytes.length, planCacheMaxSize, + planCacheTtlSeconds, ticker)); + }); + } catch (ExecutionException | UncheckedExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof IOException) { + throw new PhoenixIOException(cause); + } + throw new PhoenixIOException(cause != null ? new IOException(cause) : new IOException(e)); + } + if (!result.isPresent()) { + byName.asMap().remove(fullyQualifiedMessageName, result); + return null; + } + return result.get(); + } + + public void invalidate(String fullyQualifiedMessageName) { + if (fullyQualifiedMessageName == null || fullyQualifiedMessageName.isEmpty()) { + return; + } + byName.invalidate(fullyQualifiedMessageName); + } + + public static long cacheMaxBytes(Configuration conf) { + long percent = + readPositiveLong(conf, CACHE_MAX_HEAP_PERCENT_ATTRIB, DEFAULT_CACHE_MAX_HEAP_PERCENT); + return Runtime.getRuntime().maxMemory() / 100 * Math.min(percent, 100); + } + + private static long readPositiveLong(Configuration conf, String key, long defaultValue) { + if (conf == null) { + return defaultValue; + } + long value = conf.getLong(key, defaultValue); + return value > 0 ? value : defaultValue; + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistryHolder.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistryHolder.java new file mode 100644 index 00000000000..2a1b74bf845 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorRegistryHolder.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +/** + * Per-JVM static holder for a shared {@link ProtoDescriptorRegistry} instance. + */ +public final class ProtoDescriptorRegistryHolder { + + /** + * Lazy-construction hook used by server-side. Registered via {@link #setFactory}, and invoked at + * most once by the first {@link #get()} that observes {@code registryInstance == null}. + */ + @FunctionalInterface + public interface RegistryFactory { + ProtoDescriptorRegistry create(); + } + + public static final String ENDPOINT_NOT_REGISTERED = + "PROTOBUF functions need PhoenixRegionServerEndpoint installed on every region server"; + + private static volatile ProtoDescriptorRegistry registryInstance; + private static volatile RegistryFactory registryFactory; + + private ProtoDescriptorRegistryHolder() { + } + + /** + * Installs {@code registry} as the per-JVM shared instance if none is installed yet. Used by the + * client-side eager path; server-side callers should prefer {@link #setFactory} so nothing is + * built until the first function evaluate needs it. + * @param registry the registry to install + * @return {@code true} if this call installed the registry, {@code false} if another caller had + * already installed one + */ + public static boolean install(ProtoDescriptorRegistry registry) { + if (registry == null) { + throw new IllegalArgumentException("registry must not be null"); + } + if (registryInstance != null) { + return false; + } + synchronized (ProtoDescriptorRegistryHolder.class) { + if (registryInstance != null) { + return false; + } + registryInstance = registry; + return true; + } + } + + /** + * Registers a lazy {@link RegistryFactory}. Used by server-side. + * @param factory factory to register + * @return {@code true} if this call registered the factory, {@code false} if another caller had + * already registered one + */ + public static boolean setFactory(RegistryFactory factory) { + if (factory == null) { + throw new IllegalArgumentException("factory must not be null"); + } + if (registryFactory != null) { + return false; + } + synchronized (ProtoDescriptorRegistryHolder.class) { + if (registryFactory != null) { + return false; + } + registryFactory = factory; + return true; + } + } + + /** + * @return the installed per-JVM registry; if none is installed but a {@link RegistryFactory} has + * been registered via {@link #setFactory}, the factory is invoked exactly once (under the + * holder lock) to build and install one on demand + * @throws IllegalStateException if neither a registry nor a factory has been registered in this + * JVM + */ + public static ProtoDescriptorRegistry get() { + ProtoDescriptorRegistry snapshot = registryInstance; + if (snapshot != null) { + return snapshot; + } + RegistryFactory factory = registryFactory; + if (factory != null) { + synchronized (ProtoDescriptorRegistryHolder.class) { + snapshot = registryInstance; + if (snapshot != null) { + return snapshot; + } + snapshot = factory.create(); + if (snapshot == null) { + throw new IllegalStateException("ProtoDescriptorRegistryHolder factory returned null"); + } + registryInstance = snapshot; + return snapshot; + } + } + throw new IllegalStateException(ENDPOINT_NOT_REGISTERED); + } + + /** + * Like {@link #get()}, but installs {@code fallback}'s registry when neither a registry nor a + * factory is registered. + */ + public static ProtoDescriptorRegistry getOrInstall(RegistryFactory fallback) { + if (registryInstance == null && registryFactory == null) { + install(fallback.create()); + } + return get(); + } + + public static ProtoDescriptorRegistry getIfInstalled() { + return registryInstance; + } + + public static void uninstall() { + synchronized (ProtoDescriptorRegistryHolder.class) { + registryInstance = null; + registryFactory = null; + } + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolver.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolver.java new file mode 100644 index 00000000000..961c948bc95 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolver.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.DescriptorValidationException; +import org.apache.phoenix.thirdparty.com.google.protobuf.InvalidProtocolBufferException; + +/** + * Resolves FileDescriptorSet bytes plus a fully-qualified message name into a {@code Descriptor}. + * Topologically builds imported files, then finds the top-level message. Stateless and thread-safe. + */ +public final class ProtoDescriptorResolver { + + /** + * Resolves the given raw {@link FileDescriptorSet} bytes against + * {@code fullyQualifiedMessageName}, returning the matching {@code Descriptor} (top-level or + * nested; its containing file is available via {@code Descriptor#getFile()}) or {@code null} if + * the name does not correspond to any message in the set. + * @throws IOException if the bytes don't parse as a valid {@code FileDescriptorSet} + * ({@link InvalidProtocolBufferException}) or if the descriptor set's + * internal cross-file references are inconsistent + * ({@link DescriptorValidationException} — missing imports, type-name + * collisions, etc.) + */ + public Descriptors.Descriptor resolve(byte[] fileDescriptorSetBytes, + String fullyQualifiedMessageName) throws IOException { + if (fileDescriptorSetBytes == null) { + throw new IllegalArgumentException("fileDescriptorSetBytes must not be null"); + } + if (fullyQualifiedMessageName == null || fullyQualifiedMessageName.isEmpty()) { + throw new IllegalArgumentException("fullyQualifiedMessageName must not be null or empty"); + } + + FileDescriptorSet set; + try { + set = FileDescriptorSet.parseFrom(fileDescriptorSetBytes); + } catch (InvalidProtocolBufferException e) { + throw new IOException("FileDescriptorSet bytes do not parse (expected " + + fileDescriptorSetBytes.length + " bytes of valid google.protobuf.FileDescriptorSet)", e); + } + + Map resolvedFiles = resolveAllFiles(set); + + for (Descriptors.FileDescriptor file : resolvedFiles.values()) { + for (Descriptors.Descriptor topLevel : file.getMessageTypes()) { + Descriptors.Descriptor matched = findMessageByFullName(topLevel, fullyQualifiedMessageName); + if (matched != null) { + return matched; + } + } + } + // Name not in this set — caller (registry) maps this to a not-found result. + return null; + } + + /** + * Depth-first walk of a message + its nested types looking for one whose + * {@code Descriptor#getFullName()} equals {@code fullyQualifiedMessageName}. Returns {@code null} + * if not found in this subtree. + *

+ * Short-circuits on the first match. Bounded by the file's static nested-type depth (no cycles + * possible — protobuf nested types form a tree by construction). + */ + private static Descriptors.Descriptor findMessageByFullName(Descriptors.Descriptor message, + String fullyQualifiedMessageName) { + if (fullyQualifiedMessageName.equals(message.getFullName())) { + return message; + } + // Fast prefix check: a nested type's FQ name starts with the outer's FQ name + + // '.'; if the target isn't under this subtree, skip recursion entirely. + String outerPrefix = message.getFullName() + "."; + if (!fullyQualifiedMessageName.startsWith(outerPrefix)) { + return null; + } + for (Descriptors.Descriptor nested : message.getNestedTypes()) { + Descriptors.Descriptor found = findMessageByFullName(nested, fullyQualifiedMessageName); + if (found != null) { + return found; + } + } + return null; + } + + /** + * Walks the {@link FileDescriptorSet}'s files in dependency order and builds each one via + * {@code FileDescriptor.buildFrom}. Returns the resulting map keyed by file name so the caller + * can look up dependents. + *

+ * The order matters: {@code FileDescriptor.buildFrom(proto, deps[])} requires the dependencies + * passed in {@code deps} to already be built. We use a depth-first traversal with cycle-detection + * (proto schemas shouldn't have import cycles, but we guard against malformed input). + */ + private static Map resolveAllFiles(FileDescriptorSet set) + throws IOException { + Map protosByName = new HashMap<>(); + for (FileDescriptorProto proto : set.getFileList()) { + protosByName.put(proto.getName(), proto); + } + Map resolved = new HashMap<>(); + Set resolving = new LinkedHashSet<>(); // for cycle detection + for (FileDescriptorProto proto : set.getFileList()) { + buildFileRecursive(proto, protosByName, resolved, resolving); + } + return resolved; + } + + private static Descriptors.FileDescriptor buildFileRecursive(FileDescriptorProto proto, + Map protosByName, Map resolved, + Set resolving) throws IOException { + String name = proto.getName(); + Descriptors.FileDescriptor existing = resolved.get(name); + if (existing != null) { + return existing; + } + if (!resolving.add(name)) { + // Already on the resolution stack — proto import cycle. + throw new IOException( + "Import cycle detected involving '" + name + "' (resolution stack: " + resolving + ")"); + } + try { + Descriptors.FileDescriptor[] deps = + new Descriptors.FileDescriptor[proto.getDependencyCount()]; + for (int i = 0; i < proto.getDependencyCount(); i++) { + String depName = proto.getDependency(i); + FileDescriptorProto depProto = protosByName.get(depName); + if (depProto == null) { + throw new IOException("FileDescriptorSet for '" + name + "' references '" + depName + + "' but that file is not included in the set. Regenerate the " + + ".desc with `protoc --include_imports` to inline transitive dependencies."); + } + deps[i] = buildFileRecursive(depProto, protosByName, resolved, resolving); + } + try { + Descriptors.FileDescriptor fd = Descriptors.FileDescriptor.buildFrom(proto, deps); + resolved.put(name, fd); + return fd; + } catch (DescriptorValidationException e) { + throw new IOException( + "FileDescriptor validation failed for '" + name + "': " + e.getMessage(), e); + } + } finally { + resolving.remove(name); + } + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidator.java new file mode 100644 index 00000000000..24c0dec9d00 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidator.java @@ -0,0 +1,388 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldOptions; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +/** + * Validates that a candidate PROTOBUF descriptor is a wire-compatible evolution of the + * currently-registered one. Permitted: add unused fields/messages/enums/enum values. Everything + * else, including any change to a field's type, is rejected with a specific + * {@link SQLExceptionCode}. Walks nested types and every message or enum a field references, in the + * same file or an imported one. + */ +public final class ProtoEvolutionValidator { + + private ProtoEvolutionValidator() { + // Utility class + } + + /** Throws on the first evolution violation; returns if {@code newDesc} is compatible. */ + public static void validate(Descriptors.Descriptor oldDesc, Descriptors.Descriptor newDesc) + throws SQLException { + if (oldDesc == null || newDesc == null) { + throw new IllegalArgumentException( + "Both oldDesc and newDesc must be non-null (old=" + oldDesc + ", new=" + newDesc + ")"); + } + checkPackageUnchanged(oldDesc, newDesc); + checkSyntaxUnchanged(oldDesc, newDesc); + checkMessage(oldDesc, newDesc, oldDesc.getFullName(), new HashSet<>()); + } + + private static void checkPackageUnchanged(Descriptors.Descriptor oldDesc, + Descriptors.Descriptor newDesc) throws SQLException { + String oldPkg = oldDesc.getFile().getPackage(); + String newPkg = newDesc.getFile().getPackage(); + if (!Objects.equals(oldPkg, newPkg)) { + throw sqlException(SQLExceptionCode.PROTOBUF_PACKAGE_CHANGED, oldDesc.getFullName(), + "package '" + oldPkg + "' → '" + newPkg + "'"); + } + } + + private static void checkSyntaxUnchanged(Descriptors.Descriptor oldDesc, + Descriptors.Descriptor newDesc) throws SQLException { + String oldSyntax = fileSyntaxDisplay(oldDesc.getFile()); + String newSyntax = fileSyntaxDisplay(newDesc.getFile()); + if (!oldSyntax.equals(newSyntax)) { + throw sqlException(SQLExceptionCode.PROTOBUF_SYNTAX_CHANGED, oldDesc.getFullName(), + "syntax '" + oldSyntax + "' → '" + newSyntax + "'"); + } + } + + /** proto2 files omit {@code syntax}; treat unset as {@code "proto2"}. */ + private static String fileSyntaxDisplay(Descriptors.FileDescriptor file) { + return file.toProto().hasSyntax() ? file.toProto().getSyntax() : "proto2"; + } + + private static void checkMessage(Descriptors.Descriptor oldMsg, Descriptors.Descriptor newMsg, + String path, Set visited) throws SQLException { + if (!visited.add(oldMsg.getFullName())) { + return; + } + checkFields(oldMsg, newMsg, path, visited); + checkReservedRanges(oldMsg, newMsg, path); + checkReservedNames(oldMsg, newMsg, path); + checkEnums(oldMsg, newMsg, path, visited); + checkNestedMessages(oldMsg, newMsg, path, visited); + } + + private static void checkFields(Descriptors.Descriptor oldMsg, Descriptors.Descriptor newMsg, + String path, Set visited) throws SQLException { + Map oldByTag = new HashMap<>(); + Map oldByName = new HashMap<>(); + for (Descriptors.FieldDescriptor f : oldMsg.getFields()) { + oldByTag.put(f.getNumber(), f); + oldByName.put(f.getName(), f); + } + + Map newByTag = new HashMap<>(); + Map newByName = new HashMap<>(); + for (Descriptors.FieldDescriptor f : newMsg.getFields()) { + newByTag.put(f.getNumber(), f); + newByName.put(f.getName(), f); + } + for (Descriptors.FieldDescriptor oldField : oldMsg.getFields()) { + Descriptors.FieldDescriptor newFieldSameTag = newByTag.get(oldField.getNumber()); + if (newFieldSameTag == null) { + // Same name at a different tag is a renumber, not a removal. + Descriptors.FieldDescriptor sameName = newByName.get(oldField.getName()); + if (sameName != null && sameName.getNumber() != oldField.getNumber()) { + throw sqlException(SQLExceptionCode.PROTOBUF_TAG_RENAMED, path, "field '" + + oldField.getName() + "' tag " + oldField.getNumber() + " → " + sameName.getNumber()); + } + throw sqlException(SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, path, + "field '" + oldField.getName() + "' (tag " + oldField.getNumber() + + ") is missing from the new descriptor"); + } + checkFieldSameTag(oldField, newFieldSameTag, path); + checkReferencedType(oldField, newFieldSameTag, visited); + } + for (Descriptors.FieldDescriptor newField : newMsg.getFields()) { + if (oldByTag.containsKey(newField.getNumber())) { + continue; + } + DescriptorProto oldProto = oldMsg.toProto(); + for (DescriptorProto.ReservedRange range : oldProto.getReservedRangeList()) { + // ReservedRange is [start, end). + if (newField.getNumber() >= range.getStart() && newField.getNumber() < range.getEnd()) { + throw sqlException(SQLExceptionCode.PROTOBUF_TAG_RESERVED, path, + "field '" + newField.getName() + "' tag " + newField.getNumber() + + " falls in a reserved range [" + range.getStart() + ", " + range.getEnd() + ")"); + } + } + for (String reservedName : oldProto.getReservedNameList()) { + if (reservedName.equals(newField.getName())) { + throw sqlException(SQLExceptionCode.PROTOBUF_NAME_RESERVED, path, + "field name '" + newField.getName() + "' is reserved by the current descriptor"); + } + } + // New field into an existing oneof is forbidden; a brand-new oneof is fine. + if (newField.getContainingOneof() != null) { + String oneofName = newField.getContainingOneof().getName(); + boolean oneofExistedInOld = false; + for (Descriptors.OneofDescriptor oldOneof : oldMsg.getOneofs()) { + if (oldOneof.getName().equals(oneofName)) { + oneofExistedInOld = true; + break; + } + } + if (oneofExistedInOld) { + throw sqlException(SQLExceptionCode.PROTOBUF_ONEOF_MEMBERSHIP_CHANGE, path, + "new field '" + newField.getName() + "' added into existing oneof '" + oneofName + "'"); + } + } + } + } + + /** Same-tag field must keep name, type, cardinality, oneof, packed annotation, and default. */ + private static void checkFieldSameTag(Descriptors.FieldDescriptor oldField, + Descriptors.FieldDescriptor newField, String path) throws SQLException { + if (!oldField.getName().equals(newField.getName())) { + throw sqlException(SQLExceptionCode.PROTOBUF_FIELD_RENAMED, path, + "field at tag " + oldField.getNumber() + " renamed '" + oldField.getName() + "' → '" + + newField.getName() + "'"); + } + if (oldField.toProto().getLabel() != newField.toProto().getLabel()) { + throw sqlException(SQLExceptionCode.PROTOBUF_INCOMPATIBLE_CARDINALITY_CHANGE, path, + "field '" + oldField.getName() + "' label " + oldField.toProto().getLabel().name() + " → " + + newField.toProto().getLabel().name()); + } + String oldOneof = + oldField.getContainingOneof() == null ? null : oldField.getContainingOneof().getName(); + String newOneof = + newField.getContainingOneof() == null ? null : newField.getContainingOneof().getName(); + if (!Objects.equals(oldOneof, newOneof)) { + throw sqlException(SQLExceptionCode.PROTOBUF_ONEOF_MEMBERSHIP_CHANGE, path, + "field '" + oldField.getName() + "' oneof " + + (oldOneof == null ? "(none)" : "'" + oldOneof + "'") + " → " + + (newOneof == null ? "(none)" : "'" + newOneof + "'")); + } + if (oldField.toProto().getType() != newField.toProto().getType()) { + throw sqlException(SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, path, + "field '" + oldField.getName() + "' type " + oldField.toProto().getType().name() + " → " + + newField.toProto().getType().name()); + } + if ( + oldField.toProto().hasTypeName() + && !oldField.toProto().getTypeName().equals(newField.toProto().getTypeName()) + ) { + throw sqlException(SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, path, + "field '" + oldField.getName() + "' target type " + oldField.toProto().getTypeName() + " → " + + newField.toProto().getTypeName()); + } + if ( + isPackedExplicit(oldField.toProto().getOptions()) + != isPackedExplicit(newField.toProto().getOptions()) + ) { + throw sqlException(SQLExceptionCode.PROTOBUF_PACKED_ENCODING_CHANGE, path, + "field '" + oldField.getName() + "' [packed] annotation " + + (isPackedExplicit(oldField.toProto().getOptions()) ? "removed" : "added")); + } + if ( + !oldField.isRepeated() + && oldField.getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE + ) { + Object oldDefault = effectiveDefault(oldField); + Object newDefault = effectiveDefault(newField); + if (!oldDefault.equals(newDefault)) { + throw sqlException(SQLExceptionCode.PROTOBUF_DEFAULT_VALUE_CHANGE, path, + "field '" + oldField.getName() + "' default " + oldDefault + " → " + newDefault); + } + } + } + + private static Object effectiveDefault(Descriptors.FieldDescriptor field) { + Object value = field.getDefaultValue(); + return value instanceof Descriptors.EnumValueDescriptor + ? ((Descriptors.EnumValueDescriptor) value).getNumber() + : value; + } + + /** Old bytes stay readable only if the referenced type evolved compatibly too. */ + private static void checkReferencedType(Descriptors.FieldDescriptor oldField, + Descriptors.FieldDescriptor newField, Set visited) throws SQLException { + if (oldField.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + Descriptors.Descriptor oldType = oldField.getMessageType(); + checkMessage(oldType, newField.getMessageType(), oldType.getFullName(), visited); + } else if (oldField.getJavaType() == Descriptors.FieldDescriptor.JavaType.ENUM) { + Descriptors.EnumDescriptor oldType = oldField.getEnumType(); + if (visited.add(oldType.getFullName())) { + checkEnum(oldType, newField.getEnumType(), oldType.getFullName()); + } + } + } + + private static boolean isPackedExplicit(FieldOptions options) { + return options.hasPacked() && options.getPacked(); + } + + private static void checkReservedRanges(Descriptors.Descriptor oldMsg, + Descriptors.Descriptor newMsg, String path) throws SQLException { + DescriptorProto oldProto = oldMsg.toProto(); + DescriptorProto newProto = newMsg.toProto(); + Set oldRangeKeys = new HashSet<>(); + for (DescriptorProto.ReservedRange oldRange : oldProto.getReservedRangeList()) { + oldRangeKeys.add(oldRange.getStart() + "-" + oldRange.getEnd()); + } + for (DescriptorProto.ReservedRange newRange : newProto.getReservedRangeList()) { + if (oldRangeKeys.contains(newRange.getStart() + "-" + newRange.getEnd())) { + continue; + } + for (Descriptors.FieldDescriptor oldField : oldMsg.getFields()) { + int tag = oldField.getNumber(); + if (tag >= newRange.getStart() && tag < newRange.getEnd()) { + throw sqlException(SQLExceptionCode.PROTOBUF_RESERVE_OF_LIVE_TAG, path, + "new reserved range [" + newRange.getStart() + ", " + newRange.getEnd() + + ") covers live field '" + oldField.getName() + "' at tag " + tag); + } + } + } + } + + private static void checkReservedNames(Descriptors.Descriptor oldMsg, + Descriptors.Descriptor newMsg, String path) throws SQLException { + Set oldReservedNames = new HashSet<>(oldMsg.toProto().getReservedNameList()); + for (String newReservedName : newMsg.toProto().getReservedNameList()) { + if (oldReservedNames.contains(newReservedName)) { + continue; // already reserved in old — no change + } + for (Descriptors.FieldDescriptor oldField : oldMsg.getFields()) { + if (oldField.getName().equals(newReservedName)) { + throw sqlException(SQLExceptionCode.PROTOBUF_RESERVE_OF_LIVE_NAME, path, + "new reserved name '" + newReservedName + "' collides with live field of the " + + "same name"); + } + } + } + } + + private static void checkEnums(Descriptors.Descriptor oldMsg, Descriptors.Descriptor newMsg, + String path, Set visited) throws SQLException { + Map oldEnumsByName = new HashMap<>(); + for (Descriptors.EnumDescriptor oldEnum : oldMsg.getEnumTypes()) { + oldEnumsByName.put(oldEnum.getName(), oldEnum); + } + Map newEnumsByName = new HashMap<>(); + for (Descriptors.EnumDescriptor newEnum : newMsg.getEnumTypes()) { + newEnumsByName.put(newEnum.getName(), newEnum); + } + for (Map.Entry entry : oldEnumsByName.entrySet()) { + Descriptors.EnumDescriptor newEnum = newEnumsByName.get(entry.getKey()); + if (newEnum == null) { + throw sqlException(SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, path, + "enum '" + entry.getKey() + "' is missing from the new descriptor"); + } + if (visited.add(entry.getValue().getFullName())) { + checkEnum(entry.getValue(), newEnum, path + "." + entry.getKey()); + } + } + } + + private static void checkEnum(Descriptors.EnumDescriptor oldEnum, + Descriptors.EnumDescriptor newEnum, String path) throws SQLException { + // Index by name; tag maps are unsafe under allow_alias. + Map oldByName = new HashMap<>(); + Map newByName = new HashMap<>(); + for (EnumValueDescriptorProto v : oldEnum.toProto().getValueList()) { + oldByName.put(v.getName(), v); + } + for (EnumValueDescriptorProto v : newEnum.toProto().getValueList()) { + newByName.put(v.getName(), v); + } + for (EnumValueDescriptorProto oldValue : oldEnum.toProto().getValueList()) { + EnumValueDescriptorProto sameName = newByName.get(oldValue.getName()); + if (sameName != null) { + if (sameName.getNumber() != oldValue.getNumber()) { + throw sqlException(SQLExceptionCode.PROTOBUF_ENUM_VALUE_RENUMBERED, path, "enum value '" + + oldValue.getName() + "' tag " + oldValue.getNumber() + " → " + sameName.getNumber()); + } + continue; // pre-existing value, unchanged + } + EnumValueDescriptorProto renameTarget = null; + for (EnumValueDescriptorProto candidate : newEnum.toProto().getValueList()) { + if ( + candidate.getNumber() == oldValue.getNumber() + && !oldByName.containsKey(candidate.getName()) + ) { + renameTarget = candidate; + break; + } + } + if (renameTarget != null) { + throw sqlException(SQLExceptionCode.PROTOBUF_ENUM_VALUE_RENAMED, path, + "enum value at tag " + oldValue.getNumber() + " renamed '" + oldValue.getName() + "' → '" + + renameTarget.getName() + "'"); + } + throw sqlException(SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, path, "enum value '" + + oldValue.getName() + "' (tag " + oldValue.getNumber() + ") is missing from the new enum"); + } + for (EnumValueDescriptorProto newValue : newEnum.toProto().getValueList()) { + if (oldByName.containsKey(newValue.getName())) { + continue; // pre-existing name — already validated in pass 1 + } + for (EnumValueDescriptorProto oldValue : oldEnum.toProto().getValueList()) { + if (oldValue.getNumber() != newValue.getNumber()) { + continue; + } + if (oldValue.getName().equals(newValue.getName())) { + continue; // shouldn't happen (newValue is new-only) but defensive + } + if (newByName.containsKey(oldValue.getName())) { + throw sqlException(SQLExceptionCode.PROTOBUF_ENUM_TAG_REUSE, path, + "new enum value '" + newValue.getName() + "' uses tag " + newValue.getNumber() + + " already assigned to '" + oldValue.getName() + "' in the old enum " + + "(introducing a new alias during ALTER is not permitted; the old " + + "enum's allow_alias only preserves pre-existing aliases)"); + } + } + } + } + + private static void checkNestedMessages(Descriptors.Descriptor oldMsg, + Descriptors.Descriptor newMsg, String path, Set visited) throws SQLException { + Map newNestedByName = new HashMap<>(); + for (Descriptors.Descriptor n : newMsg.getNestedTypes()) { + newNestedByName.put(n.getName(), n); + } + for (Descriptors.Descriptor oldNested : oldMsg.getNestedTypes()) { + Descriptors.Descriptor newNested = newNestedByName.get(oldNested.getName()); + if (newNested == null) { + throw sqlException(SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, path, + "nested message '" + oldNested.getName() + "' is missing from the new descriptor"); + } + checkMessage(oldNested, newNested, path + "." + oldNested.getName(), visited); + } + } + + private static SQLException sqlException(SQLExceptionCode code, String path, String detail) { + return new SQLExceptionInfo.Builder(code).setMessage("[" + path + "] " + detail).build() + .buildException(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcher.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcher.java new file mode 100644 index 00000000000..11bed0657cb --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcher.java @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.SQLException; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.InvalidProtocolBufferException; + +/** + * Fetches and parses the {@code FROM ''} FileDescriptorSet for protobuf DDL. Only local + * {@code file:///} URLs are accepted; they are read on the JDBC client and shipped inline. + */ +public final class ProtobufDescriptorFetcher { + + /** + * Hard cap on the number of bytes the fetcher will read from a single URL — matches HBase's + * default per-cell size limit ({@code hbase.client.keyvalue.maxsize}, 10 MiB). Any descriptor + * larger than this won't fit in {@code SYSTEM.PROTO_DESCRIPTORS} so we reject early rather than + * reading megabytes only to fail at the HBase write. + */ + public static final int MAX_BYTES = 10 * 1024 * 1024; + + private static Path toLocalPath(String sourceUrl) { + if (sourceUrl == null) { + return null; + } + try { + URI uri = new URI(sourceUrl); + return "file".equalsIgnoreCase(uri.getScheme()) ? Paths.get(uri) : null; + } catch (URISyntaxException | IllegalArgumentException e) { + return null; + } + } + + /** + * Reads the local {@code file:///} URL and checks that the bytes parse as a + * {@link FileDescriptorSet}, so a bad file fails on the client before any RPC is sent. + * @param sourceUrl the URL from the DDL's {@code FROM ''} clause, e.g. + * {@code "file:///etc/phoenix/descriptors/order.desc"} + * @return the raw bytes read from the file; owned by the caller + * @throws SQLException with {@link SQLExceptionCode#PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED} if the + * URL is not a local {@code file:///} URL; with + * {@link SQLExceptionCode#PROTOBUF_DESCRIPTOR_FETCH_FAILED} if the bytes + * can't be read or exceed the size cap; with + * {@link SQLExceptionCode#PROTOBUF_DESCRIPTOR_PARSE_FAILED} if the bytes + * don't parse as a valid {@code FileDescriptorSet} + */ + public byte[] fetch(String sourceUrl) throws SQLException { + Path path = toLocalPath(sourceUrl); + if (path == null) { + throw urlNotAllowed(sourceUrl); + } + byte[] bytes; + try { + bytes = readAllBytes(path, sourceUrl); + } catch (IOException e) { + throw fetchFailed(sourceUrl, e.getClass().getSimpleName() + ": " + e.getMessage(), e); + } + parseBytes(sourceUrl, bytes); + return bytes; + } + + /** + * Builds the error raised for a {@code FROM} URL that is not a local {@code file:///} URL. + */ + public static SQLException urlNotAllowed(String sourceUrl) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED) + .setMessage(buildFetchMessage(sourceUrl, "only local file:/// URLs are allowed")).build() + .buildException(); + } + + /** + * Parses pre-fetched bytes as a {@link FileDescriptorSet}. Used by: + *

    + *
  • Server-side descriptor-DDL handlers to re-validate inline bytes shipped by a client that + * fetched a local URL (defense-in-depth — never trust the client's claim that the bytes + * parse).
  • + *
  • Client-side {@code MetaDataClient} to pre-validate before shipping the RPC, so the user + * gets a fast local failure for the common "uploaded the .proto instead of the .desc" / + * "truncated download" mistakes.
  • + *
+ * @param sourceUrl the URL the bytes came from — used only for error-message attribution; pass + * {@code ""} or similar if there's no URL + * @param bytes the byte payload (may be the result of a prior fetch, or read directly from an + * RPC field) + * @return the parsed descriptor set + * @throws SQLException with {@link SQLExceptionCode#PROTOBUF_DESCRIPTOR_PARSE_FAILED} if the + * bytes don't parse as a valid {@code FileDescriptorSet}; with + * {@link SQLExceptionCode#PROTOBUF_DESCRIPTOR_FETCH_FAILED} if {@code bytes} + * exceeds the configured size cap + */ + public FileDescriptorSet parseBytes(String sourceUrl, byte[] bytes) throws SQLException { + if (bytes == null) { + throw fetchFailed(sourceUrl, "byte payload is null", null); + } + if (bytes.length > MAX_BYTES) { + throw fetchFailed(sourceUrl, + "byte payload (" + bytes.length + " bytes) exceeds the " + MAX_BYTES + + "-byte cap. The protobuf descriptor must fit in a single HBase cell " + + "(hbase.client.keyvalue.maxsize, default 10 MiB).", + null); + } + try { + return FileDescriptorSet.parseFrom(bytes); + } catch (InvalidProtocolBufferException e) { + throw parseFailed(sourceUrl, bytes.length, e); + } + } + + /** + * Reads the input stream into a byte array, capped at {@link #MAX_BYTES}. If the source is larger + * than the cap, raises a fetch-failed exception identifying the cap rather than silently + * truncating (truncated bytes would later fail at the parse step with a confusing + * "InvalidProtocolBufferException: corrupt" message). + */ + private byte[] readAllBytes(Path path, String sourceUrl) throws IOException, SQLException { + try (InputStream in = Files.newInputStream(path)) { + return readBoundedStream(in, sourceUrl); + } + } + + /** + * Buffered read loop that enforces the {@link #MAX_BYTES} cap. Returns the bytes actually read, + * or throws if the stream exceeds the cap. + */ + private byte[] readBoundedStream(InputStream in, String sourceUrl) + throws IOException, SQLException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int totalRead = 0; + int n; + while ((n = in.read(buf)) > 0) { + totalRead += n; + if (totalRead > MAX_BYTES) { + throw fetchFailed(sourceUrl, + "source exceeds the " + MAX_BYTES + "-byte cap; refusing to read further. " + + "The protobuf descriptor must fit in a single HBase cell " + + "(hbase.client.keyvalue.maxsize, default 10 MiB). Regenerate the .desc " + + "from a smaller subset of .proto files, or split into multiple descriptors.", + null); + } + baos.write(buf, 0, n); + } + return baos.toByteArray(); + } + + private static SQLException fetchFailed(String sourceUrl, String detail, Throwable cause) { + SQLExceptionInfo.Builder b = + new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED) + .setMessage(buildFetchMessage(sourceUrl, detail)); + if (cause != null) { + b.setRootCause(cause); + } + return b.build().buildException(); + } + + private static SQLException parseFailed(String sourceUrl, int byteCount, + InvalidProtocolBufferException cause) { + return new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED) + .setMessage("URL: '" + sourceUrl + "' (" + byteCount + + " bytes fetched); InvalidProtocolBufferException: " + cause.getMessage()) + .setRootCause(cause).build().buildException(); + } + + private static String buildFetchMessage(String sourceUrl, String detail) { + StringBuilder sb = new StringBuilder("URL: '"); + if (sourceUrl != null) { + sb.append(sourceUrl); + } else { + sb.append(""); + } + sb.append("'; ").append(detail); + return sb.toString(); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoader.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoader.java new file mode 100644 index 00000000000..cd107eaac2f --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoader.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.function.Supplier; +import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; + +/** + * {@link ProtoDescriptorRegistry.Loader} implementation that reads descriptor bytes from + * {@code SYSTEM.PROTO_DESCRIPTORS}. + */ +public final class SystemProtoDescriptorsJdbcLoader implements ProtoDescriptorRegistry.Loader { + + private static final String SELECT_BYTES_SQL = + "SELECT " + PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET + " FROM " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " WHERE " + + PhoenixDatabaseMetaData.PROTOBUF_NAME + " = ?"; + + private static final int LOAD_TIMEOUT_SECONDS = 10; + + private final Supplier connectionSupplier; + + public SystemProtoDescriptorsJdbcLoader(Supplier connectionSupplier) { + if (connectionSupplier == null) { + throw new IllegalArgumentException("Connection supplier must not be null"); + } + this.connectionSupplier = connectionSupplier; + } + + @Override + public byte[] load(String fullyQualifiedMessageName) throws IOException { + Connection conn; + try { + conn = connectionSupplier.get(); + } catch (RuntimeException e) { + throw new IOException("Failed to obtain JDBC connection for PROTOBUF descriptor '" + + fullyQualifiedMessageName + "' load", e); + } + if (conn == null) { + throw new IOException("Connection supplier returned null for PROTOBUF descriptor '" + + fullyQualifiedMessageName + "' load"); + } + try { + try (PreparedStatement ps = conn.prepareStatement(SELECT_BYTES_SQL)) { + ps.setQueryTimeout(LOAD_TIMEOUT_SECONDS); + ps.setString(1, fullyQualifiedMessageName); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return null; + } + return rs.getBytes(1); + } + } catch (SQLException e) { + throw new IOException("Failed to load PROTOBUF descriptor '" + fullyQualifiedMessageName + + "' from " + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME, e); + } + } finally { + try { + conn.close(); + } catch (SQLException ignored) { + } + } + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/package-info.java b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/package-info.java new file mode 100644 index 00000000000..027fe5c6365 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/protobuf/descriptor/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * PROTOBUF descriptor registry, resolver and schema-evolution validation. + */ +package org.apache.phoenix.protobuf.descriptor; diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java b/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java index e20edd6b7ba..7c84b5a1a34 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java @@ -1636,6 +1636,17 @@ private void addCoprocessors(byte[] tableName, TableDescriptorBuilder builder, .newBuilder(QueryConstants.CHILD_LINK_META_DATA_ENDPOINT_CLASSNAME) .setPriority(priority).setProperties(Collections.emptyMap()).build()); } + } else if (SchemaUtil.isProtoDescriptorsTable(tableName)) { + // Attach ProtobufDescriptorEndpointImpl to + // SYSTEM.PROTO_DESCRIPTORS so its region serves the ProtobufDescriptorService RPCs + // (CREATE / ALTER / DROP PROTOBUF DESCRIPTOR and CREATE PROTOBUF BUNDLE). The endpoint + // also reads SYSTEM.PROTO_DESC_LINK cross-region during DROP's in-use check via + // ServerUtil.getHTableForCoprocessorScan, so the link table needs no dedicated endpoint. + if (!newDesc.hasCoprocessor(QueryConstants.PROTOBUF_DESCRIPTOR_ENDPOINT_CLASSNAME)) { + builder.setCoprocessor(CoprocessorDescriptorBuilder + .newBuilder(QueryConstants.PROTOBUF_DESCRIPTOR_ENDPOINT_CLASSNAME).setPriority(priority) + .setProperties(Collections.emptyMap()).build()); + } } if (isTransactional) { @@ -4200,6 +4211,21 @@ protected String getIdxCdcTrackerDDL() { return setSystemDDLProperties(QueryConstants.CREATE_IDX_CDC_TRACKER_METADATA); } + // SYSTEM.PROTO_DESCRIPTORS hardcodes VERSIONS=5 so its + // DDL template carries only one %s for KEEP_DELETED_CELLS rather than the standard two. + protected String getProtoDescriptorsDDL() { + return String.format(QueryConstants.CREATE_PROTO_DESCRIPTORS_METADATA, + props.getBoolean(DEFAULT_SYSTEM_KEEP_DELETED_CELLS_ATTRIB, + QueryServicesOptions.DEFAULT_SYSTEM_KEEP_DELETED_CELLS)); + } + + // SYSTEM.PROTO_DESC_LINK uses the standard two %s template (VERSIONS + KEEP_DELETED_CELLS) + // because the link table doesn't need cell-versioning for history — it's a pure + // book-keeping table (one row per descriptor↔column reference). + protected String getProtoDescLinkDDL() { + return setSystemDDLProperties(QueryConstants.CREATE_PROTO_DESC_LINK_METADATA); + } + private String setSystemDDLProperties(String ddl) { return String.format(ddl, props.getInt(DEFAULT_SYSTEM_MAX_VERSIONS_ATTRIB, @@ -4537,6 +4563,14 @@ private void createOtherSystemTables(PhoenixConnection metaConnection) metaConnection.createStatement().executeUpdate(getIdxCdcTrackerDDL()); } catch (TableAlreadyExistsException ignore) { } + try { + metaConnection.createStatement().executeUpdate(getProtoDescriptorsDDL()); + } catch (TableAlreadyExistsException ignore) { + } + try { + metaConnection.createStatement().executeUpdate(getProtoDescLinkDDL()); + } catch (TableAlreadyExistsException ignore) { + } try { // check if we have old PHOENIX_INDEX_TOOL tables // move data to the new tables under System, or simply create the new tables @@ -4864,22 +4898,22 @@ protected PhoenixConnection upgradeSystemCatalogIfRequired(PhoenixConnection met } if (currentServerSideTableTimeStamp < MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0) { metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 9, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 10, PhoenixDatabaseMetaData.PHYSICAL_TABLE_NAME + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 8, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 9, PhoenixDatabaseMetaData.SCHEMA_VERSION + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 7, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 8, PhoenixDatabaseMetaData.EXTERNAL_SCHEMA_ID + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 6, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 7, PhoenixDatabaseMetaData.STREAMING_TOPIC_NAME + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 5, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 6, PhoenixDatabaseMetaData.INDEX_WHERE + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 4, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 5, PhoenixDatabaseMetaData.CDC_INCLUDE_TABLE + " " + PVarchar.INSTANCE.getSqlTypeName()); /** @@ -4887,16 +4921,20 @@ protected PhoenixConnection upgradeSystemCatalogIfRequired(PhoenixConnection met * PHOENIX_TTL Column. See PHOENIX-7023 */ metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 3, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 4, PhoenixDatabaseMetaData.TTL + " " + PVarchar.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 2, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 3, PhoenixDatabaseMetaData.ROW_KEY_MATCHER + " " + PVarbinary.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 1, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 2, PhoenixDatabaseMetaData.IS_STRICT_TTL + " " + PBoolean.INSTANCE.getSqlTypeName()); metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, - MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0, PhoenixDatabaseMetaData.INDEX_CONSISTENCY + " CHAR(1)"); + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0 - 1, + PhoenixDatabaseMetaData.INDEX_CONSISTENCY + " CHAR(1)"); + metaConnection = addColumnsIfNotExists(metaConnection, PhoenixDatabaseMetaData.SYSTEM_CATALOG, + MIN_SYSTEM_TABLE_TIMESTAMP_5_4_0, PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME + " " + + PVarchar.INSTANCE.getSqlTypeName()); // move TTL values stored in descriptor to SYSCAT TTL column. moveTTLFromHBaseLevelTTLToPhoenixLevelTTL(metaConnection); @@ -5124,6 +5162,8 @@ private PhoenixConnection upgradeOtherSystemTablesIfRequired(PhoenixConnection m metaConnection = upgradeSystemCDCStreamStatus(metaConnection); metaConnection = upgradeSystemCDCStream(metaConnection); metaConnection = upgradeSystemIdxCdcTracker(metaConnection); + metaConnection = upgradeSystemProtoDescriptors(metaConnection); + metaConnection = upgradeSystemProtoDescLink(metaConnection); // As this is where the most time will be spent during an upgrade, // especially when there are large number of views. @@ -5455,6 +5495,32 @@ private PhoenixConnection upgradeSystemIdxCdcTracker(PhoenixConnection metaConne return metaConnection; } + // Bootstrap SYSTEM.PROTO_DESCRIPTORS on existing clusters during upgrade. The table is + // brand new in this Phoenix release (PROTOBUF data type), so there is no pre-existing + // version to migrate from and no data to back-fill. Modeled after the simplest + // "create-if-not-exists" upgrade hooks above (e.g. upgradeSystemIdxCdcTracker). + // See the upgrade-path placement in this class's SYSTEM-table create sequence. + private PhoenixConnection upgradeSystemProtoDescriptors(PhoenixConnection metaConnection) + throws SQLException { + try { + metaConnection.createStatement().executeUpdate(getProtoDescriptorsDDL()); + } catch (TableAlreadyExistsException ignored) { + } + return metaConnection; + } + + // Bootstrap SYSTEM.PROTO_DESC_LINK on existing clusters during upgrade. Same shape as + // upgradeSystemProtoDescriptors and upgradeSystemChildLink — both reference tables that + // are book-keeping aids and have no pre-existing data to migrate. + private PhoenixConnection upgradeSystemProtoDescLink(PhoenixConnection metaConnection) + throws SQLException { + try { + metaConnection.createStatement().executeUpdate(getProtoDescLinkDDL()); + } catch (TableAlreadyExistsException ignored) { + } + return metaConnection; + } + // Special method for adding the column qualifier column for 4.10. private PhoenixConnection addColumnQualifierColumn(PhoenixConnection oldMetaConnection, Long timestamp) throws SQLException { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionlessQueryServicesImpl.java b/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionlessQueryServicesImpl.java index abbc08ac31a..0695455ab65 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionlessQueryServicesImpl.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/query/ConnectionlessQueryServicesImpl.java @@ -223,6 +223,20 @@ protected String getIdxCdcTrackerDDL() { return setSystemDDLProperties(QueryConstants.CREATE_IDX_CDC_TRACKER_METADATA); } + // SYSTEM.PROTO_DESCRIPTORS hardcodes VERSIONS=5 so its + // DDL template carries only one %s for KEEP_DELETED_CELLS rather than the standard two. + protected String getProtoDescriptorsDDL() { + return String.format(QueryConstants.CREATE_PROTO_DESCRIPTORS_METADATA, + props.getBoolean(DEFAULT_SYSTEM_KEEP_DELETED_CELLS_ATTRIB, + QueryServicesOptions.DEFAULT_SYSTEM_KEEP_DELETED_CELLS)); + } + + // SYSTEM.PROTO_DESC_LINK uses the standard two %s template (VERSIONS + KEEP_DELETED_CELLS) + // via setSystemDDLProperties. + protected String getProtoDescLinkDDL() { + return setSystemDDLProperties(QueryConstants.CREATE_PROTO_DESC_LINK_METADATA); + } + private String setSystemDDLProperties(String ddl) { return String.format(ddl, props.getInt(DEFAULT_SYSTEM_MAX_VERSIONS_ATTRIB, diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java index aa73c833145..b9f8e384f00 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java @@ -49,6 +49,7 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.EXCEPTION_TRACE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.EXPLAIN_PLAN; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.EXTERNAL_SCHEMA_ID; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.FUNCTION_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.GLOBAL_SCAN_DETAILS; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.GUIDE_POSTS_ROW_COUNT; @@ -104,6 +105,8 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PHYSICAL_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PHYSICAL_TABLE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PK_NAME; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PROTOBUF_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.QUERY; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.QUERY_ID; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.QUERY_STATUS; @@ -140,6 +143,8 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_IDX_CDC_TRACKER_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_LOG_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_MUTEX_TABLE_NAME; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_TABLE; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_TASK_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_TRANSFORM_TABLE; @@ -336,6 +341,8 @@ enum JoinType { "org.apache.phoenix.schema.SystemTaskSplitPolicy"; final String INDEX_REGION_SPLIT_POLICY_CLASSNAME = "org.apache.phoenix.hbase.index.IndexRegionSplitPolicy"; + String SYSTEM_PROTO_DESCRIPTORS_SPLIT_POLICY_CLASSNAME = + "org.apache.phoenix.schema.SystemProtoDescriptorsSplitPolicy"; final String GLOBAL_INDEX_CHECKER_CLASSNAME = "org.apache.phoenix.index.GlobalIndexChecker"; final String INDEX_REGION_OBSERVER_CLASSNAME = @@ -369,6 +376,8 @@ enum JoinType { "org.apache.phoenix.coprocessor.TaskMetaDataEndpoint"; final String CHILD_LINK_META_DATA_ENDPOINT_CLASSNAME = "org.apache.phoenix.coprocessor.ChildLinkMetaDataEndpoint"; + String PROTOBUF_DESCRIPTOR_ENDPOINT_CLASSNAME = + "org.apache.phoenix.coprocessor.ProtobufDescriptorEndpointImpl"; final String PHOENIX_TTL_REGION_OBSERVER_CLASSNAME = "org.apache.phoenix.coprocessor.PhoenixTTLRegionObserver"; final String SYSTEM_CATALOG_REGION_OBSERVER_CLASSNAME = @@ -421,12 +430,12 @@ enum JoinType { + " VARCHAR, \n" + TTL + " VARCHAR, \n" + ROW_KEY_MATCHER + " VARBINARY_ENCODED, \n" + IS_STRICT_TTL + " BOOLEAN, \n" + INDEX_CONSISTENCY + " CHAR(1), \n" + // Column metadata (will be null for table row) - DATA_TYPE + " INTEGER," + COLUMN_SIZE + " INTEGER," + DECIMAL_DIGITS + " INTEGER," + NULLABLE - + " INTEGER," + ORDINAL_POSITION + " INTEGER," + SORT_ORDER + " INTEGER," + ARRAY_SIZE - + " INTEGER,\n" + VIEW_CONSTANT + " VARBINARY,\n" + IS_VIEW_REFERENCED + " BOOLEAN,\n" - + KEY_SEQ + " SMALLINT,\n" + + DATA_TYPE + " INTEGER," + PROTOBUF_DESCRIPTOR_NAME + " VARCHAR," + COLUMN_SIZE + " INTEGER," + + DECIMAL_DIGITS + " INTEGER," + NULLABLE + " INTEGER," + ORDINAL_POSITION + " INTEGER," + + SORT_ORDER + " INTEGER," + ARRAY_SIZE + " INTEGER,\n" + VIEW_CONSTANT + " VARBINARY,\n" + + IS_VIEW_REFERENCED + " BOOLEAN,\n" + KEY_SEQ + " SMALLINT,\n" // Link metadata (only set on rows linking table to index or view) - LINK_TYPE + " UNSIGNED_TINYINT,\n" + + + LINK_TYPE + " UNSIGNED_TINYINT,\n" + // Unused TYPE_NAME + " VARCHAR," + REMARKS + " VARCHAR," + SELF_REFERENCING_COL_NAME + " VARCHAR," + REF_GENERATION + " VARCHAR," + BUFFER_LENGTH + " INTEGER," + NUM_PREC_RADIX + " INTEGER," @@ -611,4 +620,21 @@ enum JoinType { + Boolean.FALSE + ",\n" + UPDATE_CACHE_FREQUENCY + "=" + "7200000" + ",\n" + ColumnFamilyDescriptorBuilder.TTL + "=" + IDX_CDC_TRACKER_TTL + ",\n" + "\"phoenix.max.lookback.age.seconds\"=0"; + + String CREATE_PROTO_DESCRIPTORS_METADATA = + "CREATE TABLE " + SYSTEM_CATALOG_SCHEMA + ".\"" + SYSTEM_PROTO_DESCRIPTORS_TABLE + "\"(\n" + + PROTOBUF_NAME + " VARCHAR NOT NULL,\n" + FILE_DESCRIPTOR_SET + " VARBINARY,\n" + + "CONSTRAINT " + SYSTEM_TABLE_PK_NAME + " PRIMARY KEY (" + PROTOBUF_NAME + "))\n" + + HConstants.VERSIONS + "=5,\n" + ColumnFamilyDescriptorBuilder.KEEP_DELETED_CELLS + "=%s,\n" + + TableDescriptorBuilder.SPLIT_POLICY + "='" + SYSTEM_PROTO_DESCRIPTORS_SPLIT_POLICY_CLASSNAME + + "',\n" + TRANSACTIONAL + "=" + Boolean.FALSE; + + String CREATE_PROTO_DESC_LINK_METADATA = "CREATE TABLE " + SYSTEM_CATALOG_SCHEMA + ".\"" + + SYSTEM_PROTO_DESC_LINK_TABLE + "\"(\n" + PROTOBUF_NAME + " VARCHAR NOT NULL,\n" + TENANT_ID + + " VARCHAR NULL,\n" + TABLE_SCHEM + " VARCHAR NULL,\n" + TABLE_NAME + " VARCHAR NOT NULL,\n" + + COLUMN_FAMILY + " VARCHAR NULL,\n" + COLUMN_NAME + " VARCHAR NOT NULL,\n" + "CONSTRAINT " + + SYSTEM_TABLE_PK_NAME + " PRIMARY KEY (" + PROTOBUF_NAME + "," + TENANT_ID + "," + TABLE_SCHEM + + "," + TABLE_NAME + "," + COLUMN_FAMILY + "," + COLUMN_NAME + "))\n" + HConstants.VERSIONS + + "=%s,\n" + ColumnFamilyDescriptorBuilder.KEEP_DELETED_CELLS + "=%s,\n" + TRANSACTIONAL + "=" + + Boolean.FALSE; } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ColumnMetaDataOps.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ColumnMetaDataOps.java index 9a35cab358b..4bac4358695 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ColumnMetaDataOps.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ColumnMetaDataOps.java @@ -32,6 +32,7 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.NULLABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ORDINAL_POSITION; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PK_NAME; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SORT_ORDER; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE; @@ -83,8 +84,9 @@ public class ColumnMetaDataOps { // access by // metadata // APIs - KEY_SEQ + "," + COLUMN_DEF + "," + COLUMN_QUALIFIER + ", " + IS_ROW_TIMESTAMP - + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + KEY_SEQ + "," + COLUMN_DEF + "," + COLUMN_QUALIFIER + "," + IS_ROW_TIMESTAMP + "," + + PROTOBUF_DESCRIPTOR_NAME + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; public static void addColumnMutation(PhoenixConnection connection, String tenantId, String schemaName, String tableName, PColumn column, String parentTableName, String pkName, @@ -157,6 +159,11 @@ private static void addColumnMutationInternal(PhoenixConnection connection, Stri colUpsert.setBytes(19, column.getColumnQualifierBytes()); } colUpsert.setBoolean(20, column.isRowTimestamp()); + if (column.getProtoMessageName() == null) { + colUpsert.setNull(21, Types.VARCHAR); + } else { + colUpsert.setString(21, column.getProtoMessageName()); + } } colUpsert.execute(); } @@ -213,10 +220,11 @@ public static PColumn newColumn(int position, ColumnDef def, PrimaryKeyConstrain } isNull = false; } - PColumn column = new PColumnImpl(PNameFactory.newName(columnName), familyName, - def.getDataType(), def.getMaxLength(), def.getScale(), isNull, position, sortOrder, - def.getArraySize(), null, false, def.getExpression(), isRowTimestamp, false, - columnQualifierBytes, EnvironmentEdgeManager.currentTimeMillis()); + PColumn column = + new PColumnImpl(PNameFactory.newName(columnName), familyName, def.getDataType(), + def.getMaxLength(), def.getScale(), isNull, position, sortOrder, def.getArraySize(), null, + false, def.getExpression(), isRowTimestamp, false, columnQualifierBytes, + EnvironmentEdgeManager.currentTimeMillis(), false, def.getProtoMessageName()); return column; } catch (IllegalArgumentException e) { // Based on precondition check in constructor throw new SQLException(e); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ConditionalTTLExpression.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ConditionalTTLExpression.java index d504cdff27b..9456236e474 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ConditionalTTLExpression.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/ConditionalTTLExpression.java @@ -247,11 +247,11 @@ private PTable createTempPTable(PhoenixConnection conn, CreateTableStatement cre .newName(defaultFamily == null ? QueryConstants.DEFAULT_COLUMN_FAMILY : defaultFamily); } } - PColumn pColumn = - new PColumnImpl(PNameFactory.newName(columnName), familyName, colDef.getDataType(), - colDef.getMaxLength(), colDef.getScale(), colDef.isNull(), pos++, colDef.getSortOrder(), - colDef.getArraySize(), null, false, colDef.getExpression(), colDef.isRowTimestamp(), - false, Bytes.toBytes(columnName), EnvironmentEdgeManager.currentTimeMillis()); + PColumn pColumn = new PColumnImpl(PNameFactory.newName(columnName), familyName, + colDef.getDataType(), colDef.getMaxLength(), colDef.getScale(), colDef.isNull(), pos++, + colDef.getSortOrder(), colDef.getArraySize(), null, false, colDef.getExpression(), + colDef.isRowTimestamp(), false, Bytes.toBytes(columnName), + EnvironmentEdgeManager.currentTimeMillis(), false, colDef.getProtoMessageName()); allCols.add(pColumn); if (isPK) { pkCols.add(pColumn); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/DelegateColumn.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/DelegateColumn.java index db34328e23f..ce178626a01 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/DelegateColumn.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/DelegateColumn.java @@ -119,4 +119,9 @@ public boolean equals(Object o) { public byte[] getColumnQualifierBytes() { return getDelegate().getColumnQualifierBytes(); } + + @Override + public String getProtoMessageName() { + return getDelegate().getProtoMessageName(); + } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java index cdad48aa0b7..0180c644ef1 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java @@ -147,6 +147,9 @@ import static org.apache.phoenix.util.CDCUtil.CDC_STREAM_NAME_FORMAT; import static org.apache.phoenix.util.MetaDataUtil.getCompatibleTTLExpression; +import com.google.protobuf.ByteString; +import com.google.protobuf.RpcCallback; +import com.google.protobuf.RpcController; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -177,6 +180,7 @@ import java.util.Map.Entry; import java.util.Properties; import java.util.Set; +import java.util.function.Consumer; import org.apache.commons.lang3.mutable.MutableBoolean; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; @@ -189,6 +193,9 @@ import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; +import org.apache.hadoop.hbase.client.coprocessor.Batch; +import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; +import org.apache.hadoop.hbase.ipc.ServerRpcController; import org.apache.hadoop.hbase.security.AccessDeniedException; import org.apache.hadoop.hbase.security.access.AccessControlClient; import org.apache.hadoop.hbase.security.access.Permission; @@ -206,6 +213,12 @@ import org.apache.phoenix.compile.ServerBuildIndexCompiler; import org.apache.phoenix.compile.StatementContext; import org.apache.phoenix.compile.StatementNormalizer; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.AlterProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufBundleRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.DropProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorMutationResponse; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorService; import org.apache.phoenix.coprocessorclient.MetaDataProtocol; import org.apache.phoenix.coprocessorclient.MetaDataProtocol.MetaDataMutationResult; import org.apache.phoenix.coprocessorclient.MetaDataProtocol.MutationCode; @@ -227,6 +240,7 @@ import org.apache.phoenix.monitoring.TableMetricsManager; import org.apache.phoenix.parse.AddColumnStatement; import org.apache.phoenix.parse.AlterIndexStatement; +import org.apache.phoenix.parse.AlterProtobufDescriptorStatement; import org.apache.phoenix.parse.ChangePermsStatement; import org.apache.phoenix.parse.CloseStatement; import org.apache.phoenix.parse.ColumnDef; @@ -235,6 +249,8 @@ import org.apache.phoenix.parse.CreateCDCStatement; import org.apache.phoenix.parse.CreateFunctionStatement; import org.apache.phoenix.parse.CreateIndexStatement; +import org.apache.phoenix.parse.CreateProtobufBundleStatement; +import org.apache.phoenix.parse.CreateProtobufDescriptorStatement; import org.apache.phoenix.parse.CreateSchemaStatement; import org.apache.phoenix.parse.CreateSequenceStatement; import org.apache.phoenix.parse.CreateTableStatement; @@ -243,6 +259,7 @@ import org.apache.phoenix.parse.DropColumnStatement; import org.apache.phoenix.parse.DropFunctionStatement; import org.apache.phoenix.parse.DropIndexStatement; +import org.apache.phoenix.parse.DropProtobufDescriptorStatement; import org.apache.phoenix.parse.DropSchemaStatement; import org.apache.phoenix.parse.DropSequenceStatement; import org.apache.phoenix.parse.DropTableStatement; @@ -260,6 +277,9 @@ import org.apache.phoenix.parse.TruncateTableStatement; import org.apache.phoenix.parse.UpdateStatisticsStatement; import org.apache.phoenix.parse.UseSchemaStatement; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.protobuf.descriptor.ProtobufDescriptorFetcher; import org.apache.phoenix.query.ConnectionQueryServices; import org.apache.phoenix.query.ConnectionQueryServices.Feature; import org.apache.phoenix.query.ConnectionlessQueryServicesImpl; @@ -285,6 +305,7 @@ import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PDate; import org.apache.phoenix.schema.types.PLong; +import org.apache.phoenix.schema.types.PProtobuf; import org.apache.phoenix.schema.types.PTimestamp; import org.apache.phoenix.schema.types.PUnsignedLong; import org.apache.phoenix.schema.types.PVarbinary; @@ -1827,9 +1848,13 @@ public MutationState createIndex(CreateIndexStatement statement, byte[][] splits colName = ColumnName.caseSensitiveColumnName(isLocalIndex ? IndexUtil.getLocalIndexColumnFamily(col.getFamilyName().getString()) : col.getFamilyName().getString(), IndexUtil.getIndexColumnName(col)); + // Preserve col.getProtoMessageName() so that INCLUDE(PROTOBUF-column) + // rebuilds an index-side column def carrying the FQ message name; otherwise + // ColumnDef's PROTOBUF_MESSAGE_NAME_REQUIRED guard rejects the derived def. columnDefs.add(FACTORY.columnDef(colName, col.getDataType().getSqlTypeName(), - col.isNullable(), col.getMaxLength(), col.getScale(), false, col.getSortOrder(), - col.getExpressionStr(), col.isRowTimestamp())); + col.getProtoMessageName(), false, null, col.isNullable(), col.getMaxLength(), + col.getScale(), false, col.getSortOrder(), col.getExpressionStr(), null, + col.isRowTimestamp())); } } @@ -2297,6 +2322,30 @@ private static ColumnDef findColumnDefOrNull(List colDefs, ColumnName return null; } + private void validateProtobufColumnRefs(List colDefs) throws SQLException { + if (colDefs == null || colDefs.isEmpty()) { + return; + } + ProtoDescriptorRegistry registry = null; + for (ColumnDef def : colDefs) { + if (def == null || def.getDataType() != PProtobuf.INSTANCE) { + continue; + } + String name = def.getProtoMessageName(); + if (name == null || name.isEmpty()) { + continue; + } + if (registry == null) { + registry = connection.getProtoDescriptorRegistry(); + } + if (registry.lookup(name) == null) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND) + .setColumnName(def.getColumnDefName().getColumnName()) + .setMessage(", descriptor: '" + name + "'").build().buildException(); + } + } + } + private static boolean checkAndValidateRowTimestampCol(ColumnDef colDef, PrimaryKeyConstraint pkConstraint, boolean rowTimeStampColAlreadyFound, PTableType tableType) throws SQLException { @@ -2933,6 +2982,7 @@ private PTable createTableInternal(CreateTableStatement statement, byte[][] spli } List colDefs = statement.getColumnDefs(); + validateProtobufColumnRefs(colDefs); LinkedHashMap columns; LinkedHashSet pkColumns; @@ -4039,8 +4089,12 @@ public boolean handleCreateTableMutationCode(MetaDataMutationResult result, Muta case AUTO_PARTITION_SEQUENCE_NOT_FOUND: throw new SQLExceptionInfo.Builder(SQLExceptionCode.AUTO_PARTITION_SEQUENCE_UNDEFINED) .setSchemaName(schemaName).setTableName(tableName).build().buildException(); + case PROTO_DESCRIPTOR_NOT_FOUND: + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND) + .setSchemaName(schemaName).setTableName(tableName).build().buildException(); case CANNOT_COERCE_AUTO_PARTITION_ID: case UNABLE_TO_CREATE_CHILD_LINK: + case UNABLE_TO_WRITE_PROTO_DESC_LINK: case PARENT_TABLE_NOT_FOUND: case TABLE_NOT_IN_REGION: throwsSQLExceptionUtil(String.valueOf(code), schemaName, tableName); @@ -4554,6 +4608,12 @@ private MutationCode processMutationResult(String schemaName, String tableName, case ERROR_WRITING_TO_SCHEMA_REGISTRY: throw new SQLExceptionInfo.Builder(ERROR_WRITING_TO_SCHEMA_REGISTRY) .setSchemaName(schemaName).setTableName(tableName).build().buildException(); + case UNABLE_TO_WRITE_PROTO_DESC_LINK: + throw new SQLExceptionInfo.Builder(SQLExceptionCode.UNABLE_TO_WRITE_PROTO_DESC_LINK) + .setSchemaName(schemaName).setTableName(tableName).build().buildException(); + case PROTO_DESCRIPTOR_NOT_FOUND: + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND) + .setSchemaName(schemaName).setTableName(tableName).build().buildException(); default: throw new SQLExceptionInfo.Builder(SQLExceptionCode.UNEXPECTED_MUTATION_CODE) .setSchemaName(schemaName).setTableName(tableName) @@ -4866,6 +4926,7 @@ public MutationState addColumn(PTable table, List origColumnDefs, } else { columnDefs = origColumnDefs == null ? Collections. emptyList() : origColumnDefs; } + validateProtobufColumnRefs(columnDefs); boolean retried = false; boolean changingPhoenixTableProperty = false; @@ -7177,4 +7238,183 @@ private void changePermsOnUser(org.apache.hadoop.hbase.client.Connection hConnec Permission.Action.values()); } } + + /** + * Selects which {@code ProtobufDescriptorService} RPC to invoke from {@link #invokeProtobufRpc}. + * @param the request message type + */ + private interface ProtobufRpcDispatch { + void dispatch(ProtobufDescriptorService instance, RpcController controller, R request, + RpcCallback done); + } + + public MutationState createProtobufDescriptor(CreateProtobufDescriptorStatement stmt) + throws SQLException { + if (isConnectionless()) { + return new MutationState(0, 0, connection); + } + String name = stmt.getProtoMessageName(); + String url = stmt.getSourceUrl(); + CreateProtobufDescriptorRequest.Builder builder = CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName(name).setSourceUrl(url).setIfNotExists(stmt.isIfNotExists()); + attachInlineBytes(url, builder::setInlineDescriptorBytes); + CreateProtobufDescriptorRequest request = builder.build(); + ProtobufDescriptorMutationResponse response = invokeProtobufRpc(Bytes.toBytes(name), request, + ProtobufDescriptorService::createProtobufDescriptor); + return handleResponse(response, name); + } + + public MutationState alterProtobufDescriptor(AlterProtobufDescriptorStatement stmt) + throws SQLException { + if (isConnectionless()) { + return new MutationState(0, 0, connection); + } + String name = stmt.getProtoMessageName(); + String url = stmt.getSourceUrl(); + AlterProtobufDescriptorRequest.Builder builder = AlterProtobufDescriptorRequest.newBuilder() + .setProtobufName(name).setSourceUrl(url).setIfExists(stmt.isIfExists()); + attachInlineBytes(url, builder::setInlineDescriptorBytes); + AlterProtobufDescriptorRequest request = builder.build(); + ProtobufDescriptorMutationResponse response = invokeProtobufRpc(Bytes.toBytes(name), request, + ProtobufDescriptorService::alterProtobufDescriptor); + MutationState result = handleResponse(response, name); + invalidateClientDescriptorCache(name); + return result; + } + + public MutationState dropProtobufDescriptor(DropProtobufDescriptorStatement stmt) + throws SQLException { + if (isConnectionless()) { + return new MutationState(0, 0, connection); + } + String name = stmt.getProtoMessageName(); + DropProtobufDescriptorRequest request = DropProtobufDescriptorRequest.newBuilder() + .setProtobufName(name).setIfExists(stmt.isIfExists()).build(); + ProtobufDescriptorMutationResponse response = invokeProtobufRpc(Bytes.toBytes(name), request, + ProtobufDescriptorService::dropProtobufDescriptor); + MutationState result = handleResponse(response, name); + invalidateClientDescriptorCache(name); + return result; + } + + private void invalidateClientDescriptorCache(String protobufName) { + ProtoDescriptorRegistry registry = ProtoDescriptorRegistryHolder.getIfInstalled(); + if (registry != null) { + registry.invalidate(protobufName); + } + } + + public MutationState createProtobufBundle(CreateProtobufBundleStatement stmt) + throws SQLException { + if (isConnectionless()) { + return new MutationState(0, 0, connection); + } + List names = stmt.getProtoMessageNames(); + if (names.isEmpty()) { + // Parser already rejects empty lists; keep a programmatic-construction guard. + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_MESSAGE_NAME_REQUIRED).build() + .buildException(); + } + String url = stmt.getSourceUrl(); + CreateProtobufBundleRequest.Builder builder = CreateProtobufBundleRequest.newBuilder() + .setSourceUrl(url).setIfNotExists(stmt.isIfNotExists()).addAllProtobufNames(names); + attachInlineBytes(url, builder::setInlineDescriptorBytes); + CreateProtobufBundleRequest request = builder.build(); + // Anchor on the first name; SystemProtoDescriptorsSplitPolicy keeps all rows in one region. + ProtobufDescriptorMutationResponse response = invokeProtobufRpc(Bytes.toBytes(names.get(0)), + request, ProtobufDescriptorService::createProtobufBundle); + return handleResponse(response, names.get(0)); + } + + /** + * Dispatches one {@code ProtobufDescriptorService} RPC to the region that owns {@code rowKey}. + * IOExceptions are translated via {@link ClientUtil#parseServerException}. + */ + private ProtobufDescriptorMutationResponse invokeProtobufRpc(final byte[] rowKey, + final R request, final ProtobufRpcDispatch dispatch) throws SQLException { + org.apache.hadoop.hbase.TableName tableName = + SchemaUtil.getPhysicalName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, + connection.getQueryServices().getProps()); + try (Table table = connection.getQueryServices().getTable(tableName.getName())) { + Map results = + table.coprocessorService(ProtobufDescriptorService.class, rowKey, rowKey, + new Batch.Call() { + @Override + public ProtobufDescriptorMutationResponse call(ProtobufDescriptorService instance) + throws IOException { + ServerRpcController controller = new ServerRpcController(); + CoprocessorRpcUtils.BlockingRpcCallback cb = + new CoprocessorRpcUtils.BlockingRpcCallback<>(); + dispatch.dispatch(instance, controller, request, cb); + if (controller.getFailedOn() != null) { + throw controller.getFailedOn(); + } + return cb.get(); + } + }); + if (results.size() != 1) { + throw new SQLException("Expected exactly one ProtobufDescriptorService response, got " + + results.size() + " (the descriptor system table should be single-region)"); + } + return results.values().iterator().next(); + } catch (IOException e) { + throw ClientUtil.parseServerException(e); + } catch (Throwable t) { + throw new SQLException(t); + } + } + + /** + * Reads the descriptor bytes from the local {@code file:///} URL on the JDBC client and attaches + * them to the request. Any other URL (schemeless, hdfs, s3a, ...) is rejected. + */ + private void attachInlineBytes(String sourceUrl, Consumer sink) throws SQLException { + sink.accept(ByteString.copyFrom(new ProtobufDescriptorFetcher().fetch(sourceUrl))); + } + + /** + * Maps the RPC response to a {@link MutationState} or {@link SQLException}. + * {@code executeUpdate()} is 1 when at least one descriptor changed, 0 on IF EXISTS / IF NOT + * EXISTS no-ops. + */ + private MutationState handleResponse(ProtobufDescriptorMutationResponse response, + String requestName) throws SQLException { + if (!response.hasErrorCode()) { + return response.getRegisteredNamesCount() > 0 + ? new MutationState(1, 1000, connection) + : new MutationState(0, 0, connection); + } + throw buildSqlException(response, requestName); + } + + private static SQLException buildSqlException(ProtobufDescriptorMutationResponse response, + String requestName) { + SQLExceptionCode code = SQLExceptionCode.fromErrorCode(response.getErrorCode()); + if (code == SQLExceptionCode.UNKNOWN_ERROR_CODE) { + code = SQLExceptionCode.PROTOBUF_DESCRIPTOR_INTERNAL_ERROR; + } + StringBuilder msg = new StringBuilder("descriptor=").append(requestName); + if (response.hasOffendingName() && !requestName.equals(response.getOffendingName())) { + msg.append(", offending=").append(response.getOffendingName()); + } + if (response.hasErrorMessage() && !response.getErrorMessage().isEmpty()) { + msg.append(", detail: ").append(response.getErrorMessage()); + } + return new SQLExceptionInfo.Builder(code).setMessage(msg.toString()).build().buildException(); + } + + /** + * Connectionless mode has no live HBase regions, so descriptor DDL is a no-op. + */ + private boolean isConnectionless() { + Object svcs = connection.getQueryServices(); + if (svcs instanceof ConnectionlessQueryServicesImpl) { + return true; + } + if (svcs instanceof DelegateQueryServices) { + return ((DelegateQueryServices) svcs) + .getDelegate() instanceof ConnectionlessQueryServicesImpl; + } + return false; + } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumn.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumn.java index 371b1c470f7..9a724f2371a 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumn.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumn.java @@ -57,4 +57,8 @@ public interface PColumn extends PDatum { boolean isDynamic(); byte[] getColumnQualifierBytes(); + + default String getProtoMessageName() { + return null; + } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumnImpl.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumnImpl.java index 06c9ffc19ce..4b0984a4e25 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumnImpl.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PColumnImpl.java @@ -45,6 +45,7 @@ public class PColumnImpl implements PColumn { private byte[] columnQualifierBytes; private boolean derived; private long timestamp; + private String protoMessageName; public PColumnImpl() { } @@ -58,7 +59,7 @@ public PColumnImpl(PColumn column, byte[] viewConstant, boolean isViewReferenced column.getScale(), column.isNullable(), column.getPosition(), column.getSortOrder(), column.getArraySize(), viewConstant, isViewReferenced, column.getExpressionStr(), column.isRowTimestamp(), column.isDynamic(), column.getColumnQualifierBytes(), - column.getTimestamp(), column.isDerived()); + column.getTimestamp(), column.isDerived(), column.getProtoMessageName()); } public PColumnImpl(PColumn column, boolean derivedColumn, int position) { @@ -70,7 +71,7 @@ public PColumnImpl(PColumn column, boolean derivedColumn, int position, byte[] v column.getScale(), column.isNullable(), position, column.getSortOrder(), column.getArraySize(), viewConstant, column.isViewReferenced(), column.getExpressionStr(), column.isRowTimestamp(), column.isDynamic(), column.getColumnQualifierBytes(), - column.getTimestamp(), derivedColumn); + column.getTimestamp(), derivedColumn, column.getProtoMessageName()); } public PColumnImpl(PName name, PName familyName, PDataType dataType, Integer maxLength, @@ -79,16 +80,26 @@ public PColumnImpl(PName name, PName familyName, PDataType dataType, Integer max boolean isDynamic, byte[] columnQualifierBytes, long timestamp) { this(name, familyName, dataType, maxLength, scale, nullable, position, sortOrder, arrSize, viewConstant, isViewReferenced, expressionStr, isRowTimestamp, isDynamic, - columnQualifierBytes, timestamp, false); + columnQualifierBytes, timestamp, false, null); } public PColumnImpl(PName name, PName familyName, PDataType dataType, Integer maxLength, Integer scale, boolean nullable, int position, SortOrder sortOrder, Integer arrSize, byte[] viewConstant, boolean isViewReferenced, String expressionStr, boolean isRowTimestamp, boolean isDynamic, byte[] columnQualifierBytes, long timestamp, boolean derived) { + this(name, familyName, dataType, maxLength, scale, nullable, position, sortOrder, arrSize, + viewConstant, isViewReferenced, expressionStr, isRowTimestamp, isDynamic, + columnQualifierBytes, timestamp, derived, null); + } + + public PColumnImpl(PName name, PName familyName, PDataType dataType, Integer maxLength, + Integer scale, boolean nullable, int position, SortOrder sortOrder, Integer arrSize, + byte[] viewConstant, boolean isViewReferenced, String expressionStr, boolean isRowTimestamp, + boolean isDynamic, byte[] columnQualifierBytes, long timestamp, boolean derived, + String protoMessageName) { init(name, familyName, dataType, maxLength, scale, nullable, position, sortOrder, arrSize, viewConstant, isViewReferenced, expressionStr, isRowTimestamp, isDynamic, - columnQualifierBytes, timestamp, derived); + columnQualifierBytes, timestamp, derived, protoMessageName); } private PColumnImpl(PName familyName, PName columnName, Long timestamp) { @@ -110,7 +121,8 @@ public static PColumnImpl createExcludedColumn(PName familyName, PName columnNam private void init(PName name, PName familyName, PDataType dataType, Integer maxLength, Integer scale, boolean nullable, int position, SortOrder sortOrder, Integer arrSize, byte[] viewConstant, boolean isViewReferenced, String expressionStr, boolean isRowTimestamp, - boolean isDynamic, byte[] columnQualifierBytes, long timestamp, boolean derived) { + boolean isDynamic, byte[] columnQualifierBytes, long timestamp, boolean derived, + String protoMessageName) { Preconditions.checkNotNull(sortOrder); this.dataType = dataType; if (familyName == null) { @@ -138,6 +150,7 @@ private void init(PName name, PName familyName, PDataType dataType, Integer maxL this.columnQualifierBytes = columnQualifierBytes; this.timestamp = timestamp; this.derived = derived; + this.protoMessageName = protoMessageName; } @Override @@ -267,6 +280,11 @@ public byte[] getColumnQualifierBytes() { return columnQualifierBytes; } + @Override + public String getProtoMessageName() { + return protoMessageName; + } + /** * Create a PColumn instance from PBed PColumn instance */ @@ -323,9 +341,13 @@ public static PColumn createFromProto(PTableProtos.PColumn column) { if (column.hasDerived()) { derived = column.getDerived(); } + String protoMessageName = null; + if (column.hasProtoMessageName()) { + protoMessageName = column.getProtoMessageName(); + } return new PColumnImpl(columnName, familyName, dataType, maxLength, scale, nullable, position, sortOrder, arraySize, viewConstant, isViewReferenced, expressionStr, isRowTimestamp, - isDynamic, columnQualifierBytes, timestamp, derived); + isDynamic, columnQualifierBytes, timestamp, derived, protoMessageName); } public static PTableProtos.PColumn toProto(PColumn column) { @@ -367,6 +389,9 @@ public static PTableProtos.PColumn toProto(PColumn column) { builder.setTimestamp(column.getTimestamp()); } builder.setDerived(column.isDerived()); + if (column.getProtoMessageName() != null) { + builder.setProtoMessageName(column.getProtoMessageName()); + } return builder.build(); } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PMetaDataImpl.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PMetaDataImpl.java index de3ef6cb997..55423a07702 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PMetaDataImpl.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/PMetaDataImpl.java @@ -273,12 +273,13 @@ public void removeColumn(PName tenantId, String tableName, List columns // Update position of columns that follow removed column for (int i = position + 1; i < oldColumns.size(); i++) { PColumn oldColumn = oldColumns.get(i); - PColumn newColumn = new PColumnImpl(oldColumn.getName(), oldColumn.getFamilyName(), - oldColumn.getDataType(), oldColumn.getMaxLength(), oldColumn.getScale(), - oldColumn.isNullable(), i - 1 + positionOffset, oldColumn.getSortOrder(), - oldColumn.getArraySize(), oldColumn.getViewConstant(), oldColumn.isViewReferenced(), - oldColumn.getExpressionStr(), oldColumn.isRowTimestamp(), oldColumn.isDynamic(), - oldColumn.getColumnQualifierBytes(), oldColumn.getTimestamp()); + PColumn newColumn = + new PColumnImpl(oldColumn.getName(), oldColumn.getFamilyName(), oldColumn.getDataType(), + oldColumn.getMaxLength(), oldColumn.getScale(), oldColumn.isNullable(), + i - 1 + positionOffset, oldColumn.getSortOrder(), oldColumn.getArraySize(), + oldColumn.getViewConstant(), oldColumn.isViewReferenced(), oldColumn.getExpressionStr(), + oldColumn.isRowTimestamp(), oldColumn.isDynamic(), oldColumn.getColumnQualifierBytes(), + oldColumn.getTimestamp(), false, oldColumn.getProtoMessageName()); columns.add(newColumn); } table = PTableImpl.builderWithColumns(table, columns).setTimeStamp(tableTimeStamp) diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/tool/SchemaExtractionProcessor.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/tool/SchemaExtractionProcessor.java index d79e5010f1d..023f9f2cb48 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/tool/SchemaExtractionProcessor.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/tool/SchemaExtractionProcessor.java @@ -679,6 +679,9 @@ private String extractColumn(PColumn column) { } } else { buf.append(type); + if (column.getProtoMessageName() != null) { + buf.append('<').append(column.getProtoMessageName()).append('>'); + } appendMaxLengthAndScale(buf, maxLength, scale); } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataType.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataType.java index cf1bcb93fb0..55bf6984c2a 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataType.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataType.java @@ -567,6 +567,7 @@ public int encodeDouble(double v, byte[] b, int o) { public static final int JSON_TYPE = 5000; public static final int BSON_TYPE = 7000; public static final int VARBINARY_ENCODED_TYPE = 9000; + public static final int PROTOBUF_TYPE = 9500; public static final String ARRAY_TYPE_SUFFIX = "ARRAY"; protected static final ThreadLocal RANDOM = new ThreadLocal() { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataTypeFactory.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataTypeFactory.java index 648426bd90c..27b90bd2916 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataTypeFactory.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PDataTypeFactory.java @@ -126,6 +126,7 @@ public int compare(PDataType o1, PDataType o2) { types.add(PJson.INSTANCE); types.add(PBson.INSTANCE); types.add(PVarbinaryEncoded.INSTANCE); + types.add(PProtobuf.INSTANCE); classToInstance = new HashMap<>(types.size()); for (PDataType t : types) { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PProtobuf.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PProtobuf.java new file mode 100644 index 00000000000..be1ee609728 --- /dev/null +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/types/PProtobuf.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.schema.types; + +import java.sql.SQLException; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.schema.IllegalDataException; + +/** + * Phoenix data type for protobuf-encoded payloads (the {@code PROTOBUF} SQL type). + */ +public final class PProtobuf extends PVarbinary { + + public static final PProtobuf INSTANCE = new PProtobuf(); + + private PProtobuf() { + super("PROTOBUF", PDataType.PROTOBUF_TYPE, byte[].class, null, 51); + } + + @Override + public boolean canBePrimaryKey() { + return false; + } + + @Override + public boolean isComparisonSupported() { + return false; + } + + @Override + public boolean isCoercibleTo(@SuppressWarnings("rawtypes") PDataType targetType) { + return equalsAny(targetType, this, PBinary.INSTANCE, PVarbinary.INSTANCE); + } + + @Override + public boolean isBytesComparableWith(@SuppressWarnings("rawtypes") PDataType otherType) { + return otherType == PVarbinary.INSTANCE || otherType == PProtobuf.INSTANCE; + } + + @Override + public int toBytes(Object object, byte[] bytes, int offset) { + if (object == null) { + return 0; + } + byte[] o = (byte[]) object; + System.arraycopy(o, 0, bytes, offset, o.length); + return o.length; + } + + @Override + public Object toObject(String value) { + if (value == null || value.length() == 0) { + return null; + } + SQLException cause = + new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_FROM_STRING_NOT_ALLOWED).build() + .buildException(); + throw new IllegalDataException(cause); + } +} diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/MetaDataUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/MetaDataUtil.java index 9249a8ad68f..bbca8875713 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/MetaDataUtil.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/MetaDataUtil.java @@ -728,6 +728,16 @@ public static byte[] getChildLinkKey(PName parentTenantId, PName parentSchemaNam QueryConstants.SEPARATOR_BYTE_ARRAY, viewName.getBytes()); } + public static byte[] getProtoDescLinkKey(byte[] protobufName, byte[] tenantId, byte[] schemaName, + byte[] tableName, byte[] columnFamily, byte[] columnName) { + return ByteUtil.concat(protobufName, QueryConstants.SEPARATOR_BYTE_ARRAY, + tenantId == null ? ByteUtil.EMPTY_BYTE_ARRAY : tenantId, QueryConstants.SEPARATOR_BYTE_ARRAY, + schemaName == null ? ByteUtil.EMPTY_BYTE_ARRAY : schemaName, + QueryConstants.SEPARATOR_BYTE_ARRAY, tableName, QueryConstants.SEPARATOR_BYTE_ARRAY, + columnFamily == null ? ByteUtil.EMPTY_BYTE_ARRAY : columnFamily, + QueryConstants.SEPARATOR_BYTE_ARRAY, columnName); + } + public static Cell getCell(List cells, byte[] cq) { for (Cell cell : cells) { if ( diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java index 81057f305f4..3c7ef2a1fa0 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java @@ -632,6 +632,21 @@ public static boolean isChildLinkTable(byte[] tableName) { SchemaUtil.getPhysicalTableName(SYSTEM_CHILD_LINK_NAME_BYTES, true).getName()) == 0; } + /** + * True iff {@code tableName} refers to {@code SYSTEM.PROTO_DESCRIPTORS} — either by its logical + * Phoenix table name or its underlying HBase physical table name (which differs when namespace + * mapping is enabled). Used by {@code ConnectionQueryServicesImpl.addCoprocessors} to attach + * {@code ProtobufDescriptorEndpointImpl} when the descriptor system table is created / upgraded. + */ + public static boolean isProtoDescriptorsTable(byte[] tableName) { + return Bytes.compareTo(tableName, PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES) + == 0 + || Bytes.compareTo(tableName, + SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, true) + .getName()) == 0; + } + public static boolean isSequenceTable(PTable table) { return PhoenixDatabaseMetaData.SYSTEM_SEQUENCE_NAME.equals(table.getName().getString()); } diff --git a/phoenix-core-client/src/main/protobuf/MetaDataService.proto b/phoenix-core-client/src/main/protobuf/MetaDataService.proto index 7d87e26436a..1021bc2f6cd 100644 --- a/phoenix-core-client/src/main/protobuf/MetaDataService.proto +++ b/phoenix-core-client/src/main/protobuf/MetaDataService.proto @@ -55,6 +55,8 @@ enum MutationCode { UNABLE_TO_DELETE_CHILD_LINK = 25; UNABLE_TO_UPSERT_TASK = 26; ERROR_WRITING_TO_SCHEMA_REGISTRY = 27; + UNABLE_TO_WRITE_PROTO_DESC_LINK = 28; + PROTO_DESCRIPTOR_NOT_FOUND = 29; }; message SharedTableState { diff --git a/phoenix-core-client/src/main/protobuf/PTable.proto b/phoenix-core-client/src/main/protobuf/PTable.proto index a98239f9ed2..0ab1ac78798 100644 --- a/phoenix-core-client/src/main/protobuf/PTable.proto +++ b/phoenix-core-client/src/main/protobuf/PTable.proto @@ -52,6 +52,7 @@ message PColumn { optional bytes columnQualifierBytes = 15; optional int64 timestamp = 16; optional bool derived = 17 [default = false]; + optional string protoMessageName = 18; } message PTableStats { diff --git a/phoenix-core-client/src/main/protobuf/ProtobufDescriptorService.proto b/phoenix-core-client/src/main/protobuf/ProtobufDescriptorService.proto new file mode 100644 index 00000000000..80269ce857f --- /dev/null +++ b/phoenix-core-client/src/main/protobuf/ProtobufDescriptorService.proto @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Coprocessor RPC envelope for the PROTOBUF DDL surface. Defines the wire contract between +// MetaDataClient (client-side) and MetaDataEndpointImpl (server-side coprocessor) +// for the four DDL forms: +// CREATE PROTOBUF DESCRIPTOR FROM '' +// ALTER PROTOBUF DESCRIPTOR FROM '' +// DROP PROTOBUF DESCRIPTOR +// CREATE PROTOBUF BUNDLE (n1, n2, ...) FROM '' +// +// Uses the unshaded com.google.protobuf:protobuf-java:2.5.0 runtime that HBase 2.x +// ships for its coprocessor RPC ABI — NOT phoenix-shaded-protobuf. +// The shaded runtime is for user-data PROTOBUF column processing (FileDescriptorSet +// parsing in ProtobufDescriptorFetcher); the RPC envelope +// stays on the same unshaded pb 2.5 footing as every other Phoenix coprocessor +// service. This is the same split as the existing MetaDataService / +// ChildLinkMetaDataService / TaskMetaDataService. +// +// Why a dedicated ProtobufDescriptorMutationResponse (rather than reusing +// MetaDataResponse like ChildLinkMetaDataService and TaskMetaDataService do): +// protobuf-descriptor failures (bundle-level atomic failure, descriptor in use, +// FileDescriptorSet fetch failures, per-rule evolution rejections) don't map onto +// the existing MutationCode enum, so the response carries the SQLExceptionCode +// directly instead of growing MutationCode with PROTOBUF_* values. + +option java_package = "org.apache.phoenix.coprocessor.generated"; +option java_outer_classname = "ProtobufDescriptorProtos"; +option java_generic_services = true; +option java_generate_equals_and_hash = true; +option optimize_for = SPEED; + +// All four RPCs use the same response message. A response without `errorCode` +// is a success; otherwise the client rebuilds the SQLException from it. +message ProtobufDescriptorMutationResponse { + // SQLExceptionCode.getErrorCode() of the failure; unset on success. An + // unexpected server-side error is sent as PROTOBUF_DESCRIPTOR_INTERNAL_ERROR. + optional int32 errorCode = 1; + + // Affected descriptor full names. On success, this is the list that was + // registered / updated / dropped (single-entry for CREATE/ALTER/DROP DESCRIPTOR; + // multi-entry for CREATE BUNDLE). On a no-op (IF [NOT] EXISTS hit), empty. + repeated string registeredNames = 2; + + // On failure, the descriptor name the error is about. + optional string offendingName = 3; + + // On failure, the server-side detail for the client to embed in the + // SQLException. Deliberately unset when the server failed with something other + // than a SQLException: the underlying throwable could leak server internals (paths, hostnames) to + // any client able to issue the DDL. The region server logs the full detail. + optional string errorMessage = 4; +} + +// +// Descriptor fetch: +// - `sourceUrl` must be a local `file:///` URL. The JDBC client reads the bytes via +// ProtobufDescriptorFetcher and ships them in `inlineDescriptorBytes`. Schemeless +// paths and distributed schemes (`hdfs`, `s3a`, `gs`, `abfs`, ...) are rejected on +// the client with PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED. +// - Server contract: `inlineDescriptorBytes` is required; a request without it is +// rejected with PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED. The server never fetches +// `sourceUrl` (that would read with the region server's own credentials or local +// disk), and still re-parses the inline bytes for defense-in-depth. `sourceUrl` is +// kept for audit/log attribution only. + +// `CREATE PROTOBUF DESCRIPTOR [IF NOT EXISTS] FROM ''` +message CreateProtobufDescriptorRequest { + // Fully-qualified protobuf message name, e.g. "my.org.OrderV1". + required string protobufName = 1; + // Local URL of the FileDescriptorSet, e.g. "file:///home/alice/order_v1.desc". + // Recorded for audit only; the server never fetches it. + required string sourceUrl = 2; + // True if `IF NOT EXISTS` was specified in the SQL. + required bool ifNotExists = 3; + // FileDescriptorSet bytes the client read from the local `file:///` URL. Required: + // the server rejects the request without them (and still re-parses them for + // defense-in-depth). See ProtobufDescriptorFetcher.fetchAndParse. + optional bytes inlineDescriptorBytes = 4; +} + +// `ALTER PROTOBUF DESCRIPTOR [IF EXISTS] FROM ''` +message AlterProtobufDescriptorRequest { + required string protobufName = 1; + required string sourceUrl = 2; + // True if `IF EXISTS` was specified in the SQL. + required bool ifExists = 3; + // Required inline bytes; see CreateProtobufDescriptorRequest. + optional bytes inlineDescriptorBytes = 4; +} + +// `DROP PROTOBUF DESCRIPTOR [IF EXISTS] ` +// +// DROP carries no descriptor payload — there is no FROM clause and nothing to fetch — +// so the fetch rule above doesn't apply. No `inlineDescriptorBytes` field. +message DropProtobufDescriptorRequest { + required string protobufName = 1; + required bool ifExists = 2; +} + +// `CREATE PROTOBUF BUNDLE [IF NOT EXISTS] (n1, n2, ...) FROM ''` +// +// Atomicity: all names register together or none do. If any name fails resolution +// against the loaded FileDescriptorSet, the whole bundle is rejected with +// PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE naming the offender. +// IF NOT EXISTS is per-name: already-registered names are skipped without +// overwrite; new names are registered. +message CreateProtobufBundleRequest { + // List of fully-qualified protobuf message names to register from this bundle. + // Order matches SQL source-text order for deterministic error messages; the + // registration itself is not order-sensitive. + repeated string protobufNames = 1; + required string sourceUrl = 2; + required bool ifNotExists = 3; + // Required inline bytes; see CreateProtobufDescriptorRequest. + optional bytes inlineDescriptorBytes = 4; +} + +service ProtobufDescriptorService { + rpc createProtobufDescriptor(CreateProtobufDescriptorRequest) + returns (ProtobufDescriptorMutationResponse); + + rpc alterProtobufDescriptor(AlterProtobufDescriptorRequest) + returns (ProtobufDescriptorMutationResponse); + + rpc dropProtobufDescriptor(DropProtobufDescriptorRequest) + returns (ProtobufDescriptorMutationResponse); + + rpc createProtobufBundle(CreateProtobufBundleRequest) + returns (ProtobufDescriptorMutationResponse); +} diff --git a/phoenix-core-server/pom.xml b/phoenix-core-server/pom.xml index c14b4b6c98b..a72c15e97dd 100644 --- a/phoenix-core-server/pom.xml +++ b/phoenix-core-server/pom.xml @@ -54,6 +54,10 @@ org.apache.phoenix.thirdparty phoenix-shaded-guava
+ + org.apache.phoenix.thirdparty + phoenix-shaded-protobuf + diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java index bd38a263fed..e070585d91e 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java @@ -62,6 +62,7 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PARENT_TENANT_ID_BYTES; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PHYSICAL_TABLE_NAME_BYTES; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PK_NAME_BYTES; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME_BYTES; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.RETURN_TYPE_BYTES; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ROW_KEY_MATCHER_BYTES; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SALT_BUCKETS_BYTES; @@ -280,6 +281,7 @@ import org.apache.phoenix.util.ClientUtil; import org.apache.phoenix.util.EncodedColumnsUtil; import org.apache.phoenix.util.EnvironmentEdgeManager; +import org.apache.phoenix.util.IndexUtil; import org.apache.phoenix.util.MetaDataUtil; import org.apache.phoenix.util.PhoenixKeyValueUtil; import org.apache.phoenix.util.PhoenixRuntime; @@ -532,13 +534,16 @@ public class MetaDataEndpointImpl extends MetaDataProtocol implements RegionCopr // storing a value of LinkType.EXCLUDED_COLUMN) private static final KeyValue LINK_TYPE_KV = createFirstOnRow(ByteUtil.EMPTY_BYTE_ARRAY, TABLE_FAMILY_BYTES, LINK_TYPE_BYTES); + // Non-null only for PROTOBUF<...> column rows. + private static final KeyValue PROTOBUF_DESCRIPTOR_NAME_KV = + createFirstOnRow(ByteUtil.EMPTY_BYTE_ARRAY, TABLE_FAMILY_BYTES, PROTOBUF_DESCRIPTOR_NAME_BYTES); private static final List COLUMN_KV_COLUMNS = Lists.newArrayList(DECIMAL_DIGITS_KV, COLUMN_SIZE_KV, NULLABLE_KV, DATA_TYPE_KV, ORDINAL_POSITION_KV, SORT_ORDER_KV, DATA_TABLE_NAME_KV, // included in both column and table // row for metadata APIs ARRAY_SIZE_KV, VIEW_CONSTANT_KV, IS_VIEW_REFERENCED_KV, COLUMN_DEF_KV, IS_ROW_TIMESTAMP_KV, - COLUMN_QUALIFIER_KV, LINK_TYPE_KV); + COLUMN_QUALIFIER_KV, LINK_TYPE_KV, PROTOBUF_DESCRIPTOR_NAME_KV); static { COLUMN_KV_COLUMNS.sort(CellComparator.getInstance()); @@ -562,6 +567,8 @@ public class MetaDataEndpointImpl extends MetaDataProtocol implements RegionCopr // deleted (by storing a value of LinkType.EXCLUDED_COLUMN) private static final int EXCLUDED_COLUMN_LINK_TYPE_KV_INDEX = COLUMN_KV_COLUMNS.indexOf(LINK_TYPE_KV); + private static final int PROTOBUF_DESCRIPTOR_NAME_INDEX = + COLUMN_KV_COLUMNS.indexOf(PROTOBUF_DESCRIPTOR_NAME_KV); // index for link type key value that is used to store linking rows private static final int LINK_TYPE_INDEX = 0; @@ -1039,9 +1046,14 @@ private void addColumnToTable(List results, PName colName, PName famName, ? Arrays.copyOfRange(columnQualifierKV.getValueArray(), columnQualifierKV.getValueOffset(), columnQualifierKV.getValueOffset() + columnQualifierKV.getValueLength()) : (isPkColumn ? null : colName.getBytes()); + Cell protoMessageNameKv = colKeyValues[PROTOBUF_DESCRIPTOR_NAME_INDEX]; + String protoMessageName = protoMessageNameKv == null + ? null + : (String) PVarchar.INSTANCE.toObject(protoMessageNameKv.getValueArray(), + protoMessageNameKv.getValueOffset(), protoMessageNameKv.getValueLength()); PColumn column = new PColumnImpl(colName, famName, dataType, maxLength, scale, isNullable, position - 1, sortOrder, arraySize, viewConstant, isViewReferenced, expressionStr, - isRowTimestamp, false, columnQualifierBytes, timestamp); + isRowTimestamp, false, columnQualifierBytes, timestamp, false, protoMessageName); columns.add(column); } @@ -2952,6 +2964,12 @@ && getSystemTableForChildLinks(clientVersion, env.getConfiguration()) // 1. ordinary table/index mutations (create table/index). // 2. When creating system indexes itself, no further index processing is required. boolean updateCatalogIndexes = !SchemaUtil.isSystemTable(Bytes.toBytes(fullTableName)); + MetaDataResponse linkResponse = writeProtoDescLinks(ProtoDescriptorLinkMutations + .buildPuts(localMutations, EnvironmentEdgeManager.currentTimeMillis())); + if (linkResponse != null) { + done.run(linkResponse); + return; + } mutateRowsWithLocks(this.accessCheckEnabled, env, region, localMutations, Collections. emptySet(), HConstants.NO_NONCE, HConstants.NO_NONCE, updateCatalogIndexes); @@ -3121,6 +3139,7 @@ public void dropTable(RpcController controller, DropTableRequest request, try { List tableMetadata = ProtobufUtil.getMutations(request); List childLinkMutations = Lists.newArrayList(); + List protoDescLinkMutations = Lists.newArrayList(); MetaDataUtil.getTenantIdAndSchemaAndTableName(tableMetadata, rowKeyMetaData); byte[] tenantIdBytes = rowKeyMetaData[PhoenixDatabaseMetaData.TENANT_ID_INDEX]; schemaName = rowKeyMetaData[PhoenixDatabaseMetaData.SCHEMA_NAME_INDEX]; @@ -3265,7 +3284,8 @@ public void dropTable(RpcController controller, DropTableRequest request, List invalidateList = new ArrayList<>(); result = doDropTable(lockKey, tenantIdBytes, schemaName, tableOrViewName, parentTableName, PTableType.fromSerializedValue(tableType), tableMetadata, childLinkMutations, - invalidateList, tableNamesToDelete, sharedTablesToDelete, request.getClientVersion()); + protoDescLinkMutations, invalidateList, tableNamesToDelete, sharedTablesToDelete, + request.getClientVersion()); if (result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) { done.run(MetaDataMutationResult.toProto(result)); return; @@ -3319,6 +3339,9 @@ Collections. emptySet(), HConstants.NO_NONCE, HConstants.NO_NONCE, return; } + // Best effort: DROP DESCRIPTOR ignores links whose column is gone. + writeProtoDescLinks(protoDescLinkMutations); + done.run(MetaDataMutationResult.toProto(result)); dropTableStats = true; @@ -3425,10 +3448,50 @@ private MetaDataResponse processRemoteRegionMutations(byte[] systemTableName, return null; } + private boolean hasMissingDescriptor(List links) throws IOException { + try (Table descriptors = + ServerUtil.getHTableForCoprocessorScan(env, SchemaUtil.getPhysicalTableName( + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, env.getConfiguration()))) { + for (Mutation link : links) { + if (link instanceof Put) { + byte[] row = link.getRow(); + int end = Bytes.indexOf(row, QueryConstants.SEPARATOR_BYTE); + if (!descriptors.exists(new Get(Arrays.copyOf(row, end)))) { + return true; + } + } + } + } + return false; + } + + private MetaDataResponse writeProtoDescLinks(List mutations) throws IOException { + if (mutations.isEmpty()) { + return null; + } + return User.runAsLoginUser(() -> { + RpcCall rpcContext = RpcUtil.getRpcContext(); + RpcUtil.setRpcContext(null); + try { + if (hasMissingDescriptor(mutations)) { + return MetaDataResponse.newBuilder() + .setReturnCode(MetaDataProtos.MutationCode.PROTO_DESCRIPTOR_NOT_FOUND) + .setMutationTime(EnvironmentEdgeManager.currentTimeMillis()).build(); + } + return processRemoteRegionMutations( + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES, mutations, + MetaDataProtos.MutationCode.UNABLE_TO_WRITE_PROTO_DESC_LINK); + } finally { + RpcUtil.setRpcContext(rpcContext); + } + }); + } + private MetaDataMutationResult doDropTable(byte[] key, byte[] tenantId, byte[] schemaName, byte[] tableName, byte[] parentTableName, PTableType tableType, List catalogMutations, - List childLinkMutations, List invalidateList, - List tableNamesToDelete, List sharedTablesToDelete, int clientVersion) + List childLinkMutations, List protoDescLinkMutations, + List invalidateList, List tableNamesToDelete, + List sharedTablesToDelete, int clientVersion) throws IOException, SQLException { Region region = env.getRegion(); @@ -3491,6 +3554,8 @@ private MetaDataMutationResult doDropTable(byte[] key, byte[] tenantId, byte[] s tableNamesToDelete.add(table.getPhysicalName().getBytes()); } invalidateList.add(cacheKey); + protoDescLinkMutations + .addAll(ProtoDescriptorLinkMutations.buildDeletesForTable(table, clientTimeStamp)); byte[][] rowKeyMetaData = new byte[5][]; do { Cell kv = results.get(LINK_TYPE_INDEX); @@ -3558,8 +3623,8 @@ private MetaDataMutationResult doDropTable(byte[] key, byte[] tenantId, byte[] s Delete delete = new Delete(indexKey, clientTimeStamp); catalogMutations.add(delete); MetaDataMutationResult result = doDropTable(indexKey, tenantId, schemaName, indexName, - tableName, PTableType.INDEX, catalogMutations, childLinkMutations, invalidateList, - tableNamesToDelete, sharedTablesToDelete, clientVersion); + tableName, PTableType.INDEX, catalogMutations, childLinkMutations, protoDescLinkMutations, + invalidateList, tableNamesToDelete, sharedTablesToDelete, clientVersion); if (result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) { return result; } @@ -3830,6 +3895,9 @@ private MetaDataMutationResult mutateColumn(final List tableMetadata, // dropped List> tableAndDroppedColumnPairs = mutator.getTableAndDroppedColumnPairs(); + List> droppedPairsSnapshot = + Lists.newArrayList(tableAndDroppedColumnPairs); + List protoDescLinkDeletes = new ArrayList<>(); Iterator> iterator = tableAndDroppedColumnPairs.iterator(); while (iterator.hasNext()) { Pair pair = iterator.next(); @@ -3839,7 +3907,7 @@ private MetaDataMutationResult mutateColumn(final List tableMetadata, iterator.remove(); result = dropIndexes(env, pair.getFirst(), invalidateList, locks, clientTimeStamp, tableMetadata, pair.getSecond(), tableNamesToDelete, sharedTablesToDelete, - clientVersion); + protoDescLinkDeletes, clientVersion); if (result != null && result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) { return result; } @@ -3914,9 +3982,31 @@ private MetaDataMutationResult mutateColumn(final List tableMetadata, boolean updateCatalogIndexes = !Bytes.toString(schemaName) .equalsIgnoreCase(PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA); + MetaDataResponse linkResponse = writeProtoDescLinks(ProtoDescriptorLinkMutations + .buildPuts(localMutations, EnvironmentEdgeManager.currentTimeMillis())); + if (linkResponse != null) { + return MetaDataMutationResult.constructFromProto(linkResponse); + } mutateRowsWithLocks(this.accessCheckEnabled, env, region, localMutations, Collections. emptySet(), HConstants.NO_NONCE, HConstants.NO_NONCE, updateCatalogIndexes); + + for (Pair pair : droppedPairsSnapshot) { + ProtoDescriptorLinkMutations.addDelete(protoDescLinkDeletes, pair.getFirst(), + pair.getSecond(), clientTimeStamp); + // The client drops covering index columns in this same RPC. + String indexColumnName = IndexUtil.getIndexColumnName(pair.getSecond()); + for (PTable index : pair.getFirst().getIndexes()) { + for (PColumn indexColumn : index.getColumns()) { + if (indexColumn.getName().getString().equals(indexColumnName)) { + ProtoDescriptorLinkMutations.addDelete(protoDescLinkDeletes, index, indexColumn, + clientTimeStamp); + } + } + } + } + // Best effort: DROP DESCRIPTOR ignores links whose column is gone. + writeProtoDescLinks(protoDescLinkDeletes); // Invalidate from cache for (ImmutableBytesPtr invalidateKey : invalidateList) { metaDataCache.invalidate(invalidateKey); @@ -4260,7 +4350,8 @@ public void dropColumn(RpcController controller, final DropColumnRequest request private MetaDataMutationResult dropIndexes(RegionCoprocessorEnvironment env, PTable table, List invalidateList, List locks, long clientTimeStamp, List tableMetaData, PColumn columnToDelete, List tableNamesToDelete, - List sharedTablesToDelete, int clientVersion) throws Throwable { + List sharedTablesToDelete, List protoDescLinkDeletes, + int clientVersion) throws Throwable { // Look for columnToDelete in any indexes. If found as PK column, get lock and drop the // index and then invalidate it // Covered columns are deleted from the index by the client @@ -4308,10 +4399,11 @@ private MetaDataMutationResult dropIndexes(RegionCoprocessorEnvironment env, PTa invalidateServerMetadataCache(requests); List childLinksMutations = Lists.newArrayList(); - MetaDataMutationResult result = doDropTable(indexKey, tenantId, - index.getSchemaName().getBytes(), index.getTableName().getBytes(), - table.getName().getBytes(), index.getType(), tableMetaData, childLinksMutations, - invalidateList, tableNamesToDelete, sharedTablesToDelete, clientVersion); + MetaDataMutationResult result = + doDropTable(indexKey, tenantId, index.getSchemaName().getBytes(), + index.getTableName().getBytes(), table.getName().getBytes(), index.getType(), + tableMetaData, childLinksMutations, protoDescLinkDeletes, invalidateList, + tableNamesToDelete, sharedTablesToDelete, clientVersion); if (result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) { return result; } diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointObserver.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointObserver.java index ea66353d0d7..389c3f67499 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointObserver.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointObserver.java @@ -74,4 +74,17 @@ void preCreateViewAddChildLink(final ObserverContext ctx, String tableName) throws IOException; + + default void preCreateProtobufDescriptor( + ObserverContext ctx, List protobufNames) + throws IOException { + } + + default void preAlterProtobufDescriptor(ObserverContext ctx, + String protobufName) throws IOException { + } + + default void preDropProtobufDescriptor(ObserverContext ctx, + String protobufName) throws IOException { + } } diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixAccessController.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixAccessController.java index 770566e50e7..3445274ecf8 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixAccessController.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixAccessController.java @@ -25,6 +25,7 @@ import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -60,7 +61,9 @@ import org.apache.hadoop.hbase.security.access.AccessControlClient; import org.apache.hadoop.hbase.security.access.AccessControlConstants; import org.apache.hadoop.hbase.security.access.AccessControlUtil; +import org.apache.hadoop.hbase.security.access.AccessController; import org.apache.hadoop.hbase.security.access.AuthResult; +import org.apache.hadoop.hbase.security.access.GlobalPermission; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.security.access.Permission.Action; import org.apache.hadoop.hbase.security.access.UserPermission; @@ -102,10 +105,7 @@ private List getAccessControllers() throws IOException { for (RegionCoprocessor cp : cpHost.findCoprocessors(RegionCoprocessor.class)) { if (cp instanceof AccessControlService.Interface && cp instanceof MasterObserver) { oldAccessControllers.add((MasterObserver) cp); - if ( - cp.getClass().getName() - .equals(org.apache.hadoop.hbase.security.access.AccessController.class.getName()) - ) { + if (cp.getClass().getName().equals(AccessController.class.getName())) { hbaseAccessControllerEnabled = true; } } @@ -484,6 +484,109 @@ public void preIndexUpdate(ObserverContext } } + @Override + public void preCreateProtobufDescriptor(ObserverContext ctx, + List protobufNames) throws IOException { + if (!accessCheckEnabled) { + return; + } + requireGlobalAdmin("CreateProtobufDescriptor " + protobufNames); + } + + @Override + public void preAlterProtobufDescriptor(ObserverContext ctx, + String protobufName) throws IOException { + if (!accessCheckEnabled) { + return; + } + requireGlobalAdmin("AlterProtobufDescriptor " + protobufName); + } + + @Override + public void preDropProtobufDescriptor(ObserverContext ctx, + String protobufName) throws IOException { + if (!accessCheckEnabled) { + return; + } + requireGlobalAdmin("DropProtobufDescriptor " + protobufName); + } + + /** Descriptors are global, so DDL on them needs superuser or a GLOBAL-scope ADMIN grant. */ + private void requireGlobalAdmin(String request) throws IOException { + User user = getActiveUser(); + AuthResult result; + if (Superusers.isSuperUser(user) || hasGlobalPermission(user, Action.ADMIN)) { + result = + AuthResult.allow(request, "Global check allowed", user, Action.ADMIN, null, null, null); + logResult(result); + return; + } + result = AuthResult.deny(request, "Global check failed", user, Action.ADMIN, null, null, null); + logResult(result); + throw new AccessDeniedException("Insufficient permissions " + + authString(user.getName(), null, Collections.singleton(Action.ADMIN))); + } + + private boolean hasGlobalPermission(User user, Action action) throws IOException { + Set principals = new HashSet<>(); + principals.add(user.getShortName()); + String[] groupNames = user.getGroupNames(); + if (groupNames != null) { + for (String group : groupNames) { + principals.add(AuthUtil.toGroupEntry(group)); + } + } + for (UserPermission perm : getGlobalUserPermissions()) { + if ( + perm.getPermission() instanceof GlobalPermission && principals.contains(perm.getUser()) + && perm.getPermission().implies(action) + ) { + return true; + } + } + return false; + } + + /** GLOBAL-scope grants from every access controller loaded on this region. */ + private List getGlobalUserPermissions() throws IOException { + return User.runAsLoginUser(() -> { + final List userPermissions = new ArrayList<>(); + final RpcCall rpcContext = RpcUtil.getRpcContext(); + try { + // Clear the RPC context so the calls below run as the login user. + RpcUtil.setRpcContext(null); + for (MasterObserver service : getAccessControllers()) { + if (service.getClass().getName().equals(AccessController.class.getName())) { + // An empty table regex returns the GLOBAL-scope grants. + userPermissions.addAll(AccessControlClient.getUserPermissions(serverConnection, "")); + } else { + AccessControlProtos.GetUserPermissionsRequest request = + AccessControlProtos.GetUserPermissionsRequest.newBuilder() + .setType(AccessControlProtos.Permission.Type.Global).build(); + ((AccessControlService.Interface) service).getUserPermissions(new ServerRpcController(), + request, message -> { + if (message != null) { + for (AccessControlProtos.UserPermission perm : message.getUserPermissionList()) { + userPermissions.add(AccessControlUtil.toUserPermission(perm)); + } + } + }); + } + } + } catch (Throwable e) { + if (e instanceof Exception) { + throw (Exception) e; + } else if (e instanceof Error) { + throw (Error) e; + } + throw new Exception(e); + } finally { + RpcUtil.setRpcContext(rpcContext); + } + return userPermissions; + }); + } + /** * Gets all the permissions for a given tableName for all the users Also, get the permissions at * table's namespace level and merge all of them @@ -502,10 +605,7 @@ public List run() throws Exception { for (MasterObserver service : getAccessControllers()) { // Use AccessControlClient API's if the accessController is an instance of // org.apache.hadoop.hbase.security.access.AccessController - if ( - service.getClass().getName() - .equals(org.apache.hadoop.hbase.security.access.AccessController.class.getName()) - ) { + if (service.getClass().getName().equals(AccessController.class.getName())) { userPermissions.addAll(AccessControlClient.getUserPermissions(serverConnection, tableName.getNameWithNamespaceInclAsString())); userPermissions.addAll(AccessControlClient.getUserPermissions(serverConnection, @@ -540,10 +640,7 @@ public List run() throws Exception { // Setting RPC context as null so that user can be resetted RpcUtil.setRpcContext(null); for (MasterObserver service : getAccessControllers()) { - if ( - service.getClass().getName() - .equals(org.apache.hadoop.hbase.security.access.AccessController.class.getName()) - ) { + if (service.getClass().getName().equals(AccessController.class.getName())) { continue; } else { getUserPermsFromUserDefinedAccessController(userPermissions, diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixMetaDataCoprocessorHost.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixMetaDataCoprocessorHost.java index 339b46a705c..3ee540ee892 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixMetaDataCoprocessorHost.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixMetaDataCoprocessorHost.java @@ -271,4 +271,31 @@ public void call(MetaDataEndpointObserver observer) throws IOException { } }); } + + void preCreateProtobufDescriptor(final List protobufNames) throws IOException { + execOperation(new PhoenixObserverOperation() { + @Override + public void call(MetaDataEndpointObserver observer) throws IOException { + observer.preCreateProtobufDescriptor(this, protobufNames); + } + }); + } + + void preAlterProtobufDescriptor(final String protobufName) throws IOException { + execOperation(new PhoenixObserverOperation() { + @Override + public void call(MetaDataEndpointObserver observer) throws IOException { + observer.preAlterProtobufDescriptor(this, protobufName); + } + }); + } + + void preDropProtobufDescriptor(final String protobufName) throws IOException { + execOperation(new PhoenixObserverOperation() { + @Override + public void call(MetaDataEndpointObserver observer) throws IOException { + observer.preDropProtobufDescriptor(this, protobufName); + } + }); + } } diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixRegionServerEndpoint.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixRegionServerEndpoint.java index 44441185838..8dae154cf74 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixRegionServerEndpoint.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PhoenixRegionServerEndpoint.java @@ -21,7 +21,12 @@ import com.google.protobuf.RpcController; import com.google.protobuf.Service; import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; import java.util.Collections; +import java.util.Properties; +import java.util.function.Supplier; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor; @@ -36,10 +41,15 @@ import org.apache.phoenix.hbase.index.parallel.ThreadPoolManager; import org.apache.phoenix.hbase.index.parallel.WaitForCompletionTaskRunner; import org.apache.phoenix.jdbc.HAGroupStoreManager; +import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.protobuf.ProtobufUtil; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.protobuf.descriptor.SystemProtoDescriptorsJdbcLoader; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.query.QueryServicesOptions; import org.apache.phoenix.util.ClientUtil; +import org.apache.phoenix.util.QueryUtil; import org.apache.phoenix.util.SchemaUtil; import org.apache.phoenix.util.ServerUtil; import org.slf4j.Logger; @@ -63,6 +73,36 @@ public void start(CoprocessorEnvironment env) throws IOException { this.metricsSource = MetricsPhoenixCoprocessorSourceFactory.getInstance().getMetadataCachingSource(); initUncoveredIndexThreadPool(this.conf); + registerProtoDescriptorRegistryFactory(this.conf); + } + + /** + * Registers a lazy {@link ProtoDescriptorRegistry} factory on every RegionServer. + */ + public static void registerProtoDescriptorRegistryFactory(final Configuration conf) { + ProtoDescriptorRegistryHolder.setFactory(() -> { + final Properties serverProps = new Properties(); + QueryUtil.setServerConnection(serverProps); + final String url; + try { + url = QueryUtil.getConnectionUrl(serverProps, conf); + } catch (SQLException e) { + LOGGER.error("Something went wrong with retrieval of JDBC url.", e); + throw new RuntimeException(e); + } + LOGGER.info("PROTOBUF descriptor registry will load descriptors using {}", url); + Supplier connectionSupplier = () -> { + try { + Connection conn = DriverManager.getConnection(url, serverProps); + conn.unwrap(PhoenixConnection.class).getQueryServices().clearUpgradeRequired(); + return conn; + } catch (SQLException e) { + throw new RuntimeException(e); + } + }; + return new ProtoDescriptorRegistry(conf, + new SystemProtoDescriptorsJdbcLoader(connectionSupplier)); + }); } @Override diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtoDescriptorLinkMutations.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtoDescriptorLinkMutations.java new file mode 100644 index 00000000000..1664c087239 --- /dev/null +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtoDescriptorLinkMutations.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.coprocessor; + +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME_BYTES; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellUtil; +import org.apache.hadoop.hbase.HConstants; +import org.apache.hadoop.hbase.PrivateCellUtil; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Mutation; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.query.QueryConstants; +import org.apache.phoenix.schema.PColumn; +import org.apache.phoenix.schema.PName; +import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.types.PProtobuf; +import org.apache.phoenix.util.MetaDataUtil; +import org.apache.phoenix.util.SchemaUtil; + +/** Builds the {@code SYSTEM.PROTO_DESC_LINK} mutations that track PROTOBUF column usage. */ +final class ProtoDescriptorLinkMutations { + + private ProtoDescriptorLinkMutations() { + } + + /** + * Returns one link Put per PROTOBUF column row in {@code catalogMutations}. If there are any, the + * catalog Put cells still at LATEST_TIMESTAMP are set to {@code now}, so links and catalog rows + * share one timestamp. + */ + static List buildPuts(List catalogMutations, long now) throws IOException { + List links = new ArrayList<>(); + for (Mutation m : catalogMutations) { + List cells = m instanceof Put + ? ((Put) m).get(TABLE_FAMILY_BYTES, PROTOBUF_DESCRIPTOR_NAME_BYTES) + : Collections.emptyList(); + if (!cells.isEmpty() && cells.get(0).getValueLength() > 0) { + // tenant, schema, table, column, family + byte[][] key = new byte[5][]; + SchemaUtil.getVarChars(m.getRow(), key); + long ts = cells.get(0).getTimestamp(); + byte[] linkKey = MetaDataUtil.getProtoDescLinkKey(CellUtil.cloneValue(cells.get(0)), key[0], + key[1], key[2], key[4], key[3]); + links.add(new Put(linkKey).addColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, + QueryConstants.EMPTY_COLUMN_BYTES, ts == HConstants.LATEST_TIMESTAMP ? now : ts, + QueryConstants.EMPTY_COLUMN_VALUE_BYTES)); + } + } + if (!links.isEmpty()) { + for (Mutation m : catalogMutations) { + if (m instanceof Put) { + for (List family : m.getFamilyCellMap().values()) { + for (Cell cell : family) { + PrivateCellUtil.updateLatestStamp(cell, now); + } + } + } + } + } + return links; + } + + static List buildDeletesForTable(PTable table, long timestamp) { + List deletes = new ArrayList<>(); + for (PColumn column : table.getColumns()) { + addDelete(deletes, table, column, timestamp); + } + return deletes; + } + + static void addDelete(List deletes, PTable table, PColumn column, long timestamp) { + if (isLinked(column)) { + deletes.add( + new Delete(MetaDataUtil.getProtoDescLinkKey(Bytes.toBytes(column.getProtoMessageName()), + bytes(table.getTenantId()), bytes(table.getSchemaName()), table.getTableName().getBytes(), + bytes(column.getFamilyName()), column.getName().getBytes()), timestamp)); + } + } + + /** Derived columns are skipped: their link belongs to the ancestor that declared them. */ + private static boolean isLinked(PColumn column) { + return column.getDataType() == PProtobuf.INSTANCE && !column.isDerived() + && column.getProtoMessageName() != null && !column.getProtoMessageName().isEmpty(); + } + + private static byte[] bytes(PName name) { + return name == null ? null : name.getBytes(); + } +} diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtobufDescriptorEndpointImpl.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtobufDescriptorEndpointImpl.java new file mode 100644 index 00000000000..45443b95922 --- /dev/null +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/ProtobufDescriptorEndpointImpl.java @@ -0,0 +1,552 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.coprocessor; + +import static org.apache.phoenix.coprocessor.MetaDataEndpointImpl.mutateRowsWithLocks; +import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES; + +import com.google.protobuf.ByteString; +import com.google.protobuf.RpcCallback; +import com.google.protobuf.RpcController; +import com.google.protobuf.Service; +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.CoprocessorEnvironment; +import org.apache.hadoop.hbase.HConstants; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Mutation; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.ResultScanner; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.client.Table; +import org.apache.hadoop.hbase.coprocessor.CoprocessorException; +import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; +import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; +import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; +import org.apache.hadoop.hbase.regionserver.Region; +import org.apache.hadoop.hbase.regionserver.Region.RowLock; +import org.apache.hadoop.hbase.security.AccessDeniedException; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.AlterProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufBundleRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.DropProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorMutationResponse; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorService; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.exception.SQLExceptionInfo; +import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; +import org.apache.phoenix.protobuf.ProtobufUtil; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorResolver; +import org.apache.phoenix.protobuf.descriptor.ProtoEvolutionValidator; +import org.apache.phoenix.protobuf.descriptor.ProtobufDescriptorFetcher; +import org.apache.phoenix.query.QueryConstants; +import org.apache.phoenix.query.QueryServices; +import org.apache.phoenix.query.QueryServicesOptions; +import org.apache.phoenix.util.ClientUtil; +import org.apache.phoenix.util.EnvironmentEdgeManager; +import org.apache.phoenix.util.SchemaUtil; +import org.apache.phoenix.util.ServerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +/** + * Region-side coprocessor for {@link ProtobufDescriptorService} on + * {@code SYSTEM.PROTO_DESCRIPTORS}. CREATE / ALTER / DROP DESCRIPTOR and CREATE BUNDLE all write + * through {@link MetaDataEndpointImpl#mutateRowsWithLocks}. + */ +public class ProtobufDescriptorEndpointImpl extends ProtobufDescriptorService + implements RegionCoprocessor { + + private static final Logger LOGGER = + LoggerFactory.getLogger(ProtobufDescriptorEndpointImpl.class); + + private RegionCoprocessorEnvironment env; + private boolean accessCheckEnabled; + private PhoenixMetaDataCoprocessorHost phoenixAccessCoprocessorHost; + private final ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + + @Override + public void start(CoprocessorEnvironment env) throws IOException { + if (env instanceof RegionCoprocessorEnvironment) { + this.env = (RegionCoprocessorEnvironment) env; + } else { + throw new CoprocessorException("Must be loaded on a table region!"); + } + Configuration conf = env.getConfiguration(); + this.accessCheckEnabled = conf.getBoolean(QueryServices.PHOENIX_ACLS_ENABLED, + QueryServicesOptions.DEFAULT_PHOENIX_ACLS_ENABLED); + this.phoenixAccessCoprocessorHost = new PhoenixMetaDataCoprocessorHost(this.env); + PhoenixRegionServerEndpoint.registerProtoDescriptorRegistryFactory(conf); + } + + @Override + public Iterable getServices() { + return Collections.singleton(this); + } + + @Override + public void createProtobufDescriptor(RpcController controller, + CreateProtobufDescriptorRequest request, RpcCallback done) { + + String protobufName = request.getProtobufName(); + String sourceUrl = request.getSourceUrl(); + boolean ifNotExists = request.getIfNotExists(); + try { + phoenixAccessCoprocessorHost + .preCreateProtobufDescriptor(Collections.singletonList(protobufName)); + byte[] descriptorBytes = + inlineBytesOrNull(request.hasInlineDescriptorBytes(), request.getInlineDescriptorBytes()); + FileDescriptorSet descriptorSet = materializeDescriptor(descriptorBytes, sourceUrl); + + if (!isTopLevelMessageInSet(protobufName, descriptorSet)) { + done.run(typeNotFoundResponse(protobufName)); + return; + } + resolveOrThrow(descriptorBytes, protobufName); + + Region region = env.getRegion(); + List locks = lockRows(region, Collections.singletonList(protobufName)); + try { + if (descriptorRowExists(region, protobufName)) { + if (ifNotExists) { + done.run(okResponse(Collections.emptyList())); + } else { + done.run(alreadyExistsResponse(protobufName)); + } + return; + } + long now = EnvironmentEdgeManager.currentTimeMillis(); + List mutations = + Collections.singletonList(buildDescriptorPut(protobufName, descriptorBytes, now)); + mutateRowsWithLocks(this.accessCheckEnabled, region, mutations, Collections.emptySet(), + HConstants.NO_NONCE, HConstants.NO_NONCE); + } finally { + ServerUtil.releaseRowLocks(locks); + } + done.run(okResponse(Collections.singletonList(protobufName))); + } catch (AccessDeniedException e) { + accessDenied(controller, done, "createProtobufDescriptor", protobufName, e); + } catch (SQLException e) { + done.run(fromSqlException(e, protobufName)); + } catch (Throwable t) { + LOGGER.error("Failed to handle createProtobufDescriptor for {}", protobufName, t); + ProtobufUtil.setControllerException(controller, + ClientUtil.createIOException(protobufName, t)); + } + } + + @Override + public void alterProtobufDescriptor(RpcController controller, + AlterProtobufDescriptorRequest request, RpcCallback done) { + + String protobufName = request.getProtobufName(); + String sourceUrl = request.getSourceUrl(); + boolean ifExists = request.getIfExists(); + try { + phoenixAccessCoprocessorHost.preAlterProtobufDescriptor(protobufName); + byte[] descriptorBytes = + inlineBytesOrNull(request.hasInlineDescriptorBytes(), request.getInlineDescriptorBytes()); + FileDescriptorSet descriptorSet = materializeDescriptor(descriptorBytes, sourceUrl); + + if (!isTopLevelMessageInSet(protobufName, descriptorSet)) { + done.run(typeNotFoundResponse(protobufName)); + return; + } + + Descriptors.Descriptor newDesc = resolveOrThrow(descriptorBytes, protobufName); + Region region = env.getRegion(); + List locks = lockRows(region, Collections.singletonList(protobufName)); + try { + byte[] oldBytes = getDescriptorBytes(region, protobufName); + if (oldBytes == null) { + if (ifExists) { + done.run(okResponse(Collections.emptyList())); + } else { + done.run(notFoundResponse(protobufName)); + } + return; + } + ProtoEvolutionValidator.validate(resolveOrThrow(oldBytes, protobufName), newDesc); + long now = EnvironmentEdgeManager.currentTimeMillis(); + List mutations = + Collections.singletonList(buildDescriptorPut(protobufName, descriptorBytes, now)); + mutateRowsWithLocks(this.accessCheckEnabled, region, mutations, Collections.emptySet(), + HConstants.NO_NONCE, HConstants.NO_NONCE); + } finally { + ServerUtil.releaseRowLocks(locks); + } + invalidateRegistryEntry(protobufName); + done.run(okResponse(Collections.singletonList(protobufName))); + } catch (AccessDeniedException e) { + accessDenied(controller, done, "alterProtobufDescriptor", protobufName, e); + } catch (SQLException e) { + done.run(fromSqlException(e, protobufName)); + } catch (Throwable t) { + LOGGER.error("Failed to handle alterProtobufDescriptor for {}", protobufName, t); + ProtobufUtil.setControllerException(controller, + ClientUtil.createIOException(protobufName, t)); + } + } + + @Override + public void dropProtobufDescriptor(RpcController controller, + DropProtobufDescriptorRequest request, RpcCallback done) { + + String protobufName = request.getProtobufName(); + boolean ifExists = request.getIfExists(); + try { + phoenixAccessCoprocessorHost.preDropProtobufDescriptor(protobufName); + Region region = env.getRegion(); + List locks = lockRows(region, Collections.singletonList(protobufName)); + try { + if (!descriptorRowExists(region, protobufName)) { + if (ifExists) { + done.run(okResponse(Collections.emptyList())); + } else { + done.run(notFoundResponse(protobufName)); + } + return; + } + // Not locked against a concurrent CREATE / ALTER ADD of a column using this descriptor. + // Shared lock between two coproc hooks that do not share same region requires complexity + // that is not worth adding here. + if (isDescriptorInUse(protobufName)) { + done.run(inUseResponse(protobufName)); + return; + } + long now = EnvironmentEdgeManager.currentTimeMillis(); + List mutations = + Collections.singletonList(new Delete(Bytes.toBytes(protobufName), now)); + mutateRowsWithLocks(this.accessCheckEnabled, region, mutations, Collections.emptySet(), + HConstants.NO_NONCE, HConstants.NO_NONCE); + } finally { + ServerUtil.releaseRowLocks(locks); + } + invalidateRegistryEntry(protobufName); + done.run(okResponse(Collections.singletonList(protobufName))); + } catch (AccessDeniedException e) { + accessDenied(controller, done, "dropProtobufDescriptor", protobufName, e); + } catch (Throwable t) { + LOGGER.error("Failed to handle dropProtobufDescriptor for {}", protobufName, t); + ProtobufUtil.setControllerException(controller, + ClientUtil.createIOException(protobufName, t)); + } + } + + private static void accessDenied(RpcController controller, + RpcCallback done, String op, String name, + AccessDeniedException e) { + LOGGER.warn("{} denied for {}: {}", op, name, e); + ProtobufUtil.setControllerException(controller, e); + done.run(null); + } + + private static void invalidateRegistryEntry(String protobufName) { + ProtoDescriptorRegistry registry = ProtoDescriptorRegistryHolder.getIfInstalled(); + if (registry != null) { + registry.invalidate(protobufName); + } + } + + @Override + public void createProtobufBundle(RpcController controller, CreateProtobufBundleRequest request, + RpcCallback done) { + + List names = request.getProtobufNamesList(); + String sourceUrl = request.getSourceUrl(); + boolean ifNotExists = request.getIfNotExists(); + try { + phoenixAccessCoprocessorHost.preCreateProtobufDescriptor(names); + byte[] descriptorBytes = + inlineBytesOrNull(request.hasInlineDescriptorBytes(), request.getInlineDescriptorBytes()); + FileDescriptorSet descriptorSet = materializeDescriptor(descriptorBytes, sourceUrl); + // Every name stores, and caches, its own copy of the set: cap the total at the cache budget. + // The cap grows with the heap and there is no fixed limit. Real sets are small, and this is + // an admin DDL, so a fixed limit is not needed. + long maxBytes = ProtoDescriptorRegistry.cacheMaxBytes(env.getConfiguration()); + if ((long) names.size() * descriptorBytes.length > maxBytes) { + done.run(errorResponse(SQLExceptionCode.PROTOBUF_BUNDLE_TOO_LARGE, names.get(0), + names.size() + " names x " + descriptorBytes.length + " bytes exceeds " + maxBytes)); + return; + } + + Set topLevelMessages = collectTopLevelMessageNames(descriptorSet); + for (String name : names) { + if (!topLevelMessages.contains(name)) { + done.run(typeNotFoundResponse(name)); + return; + } + } + try { + resolveOrThrow(descriptorBytes, names.get(0)); + } catch (SQLException e) { + done.run(fromSqlException(e, names.get(0))); + return; + } + + Region region = env.getRegion(); + List registeredNames = new ArrayList<>(names.size()); + List locks = lockRows(region, names); + try { + long now = EnvironmentEdgeManager.currentTimeMillis(); + List mutations = new ArrayList<>(names.size()); + for (String name : names) { + if (descriptorRowExists(region, name)) { + if (ifNotExists) { + continue; + } + done.run(alreadyExistsResponse(name)); + return; + } + mutations.add(buildDescriptorPut(name, descriptorBytes, now)); + registeredNames.add(name); + } + if (!mutations.isEmpty()) { + mutateRowsWithLocks(this.accessCheckEnabled, region, mutations, Collections.emptySet(), + HConstants.NO_NONCE, HConstants.NO_NONCE); + } + } finally { + ServerUtil.releaseRowLocks(locks); + } + done.run(okResponse(registeredNames)); + } catch (AccessDeniedException e) { + accessDenied(controller, done, "createProtobufBundle", String.valueOf(names), e); + } catch (SQLException e) { + done.run(fromSqlException(e, names.isEmpty() ? "" : names.get(0))); + } catch (Throwable t) { + LOGGER.error("Failed to handle createProtobufBundle for {}", names, t); + ProtobufUtil.setControllerException(controller, + ClientUtil.createIOException(String.valueOf(names), t)); + } + } + + /** + * Parses the inline bytes the client read from its local file:/// URL. The server never fetches + * {@code sourceUrl} itself: doing so would read with the region server's own filesystem + * credentials (or its local disk) on behalf of the caller. + */ + private FileDescriptorSet materializeDescriptor(byte[] inlineBytes, String sourceUrl) + throws SQLException { + if (inlineBytes == null) { + throw ProtobufDescriptorFetcher.urlNotAllowed(sourceUrl); + } + return fetcher.parseBytes(sourceUrl, inlineBytes); + } + + private static byte[] inlineBytesOrNull(boolean hasInline, ByteString inline) { + return hasInline ? inline.toByteArray() : null; + } + + /** Top-level messages only; nested types are not CREATE/ALTER targets. */ + private static boolean isTopLevelMessageInSet(String protobufName, FileDescriptorSet set) { + return collectTopLevelMessageNames(set).contains(protobufName); + } + + private static Set collectTopLevelMessageNames(FileDescriptorSet set) { + Set names = new LinkedHashSet<>(); + for (FileDescriptorProto file : set.getFileList()) { + String pkg = file.hasPackage() ? file.getPackage() : ""; + for (int i = 0; i < file.getMessageTypeCount(); i++) { + String msg = file.getMessageType(i).getName(); + names.add(pkg.isEmpty() ? msg : pkg + "." + msg); + } + } + return names; + } + + /** Write-locks the descriptor rows in sorted order, so overlapping bundles cannot deadlock. */ + private static List lockRows(Region region, Collection names) + throws IOException { + Set rows = new TreeSet<>(Bytes.BYTES_COMPARATOR); + for (String name : names) { + rows.add(Bytes.toBytes(name)); + } + List locks = new ArrayList<>(rows.size()); + try { + for (byte[] row : rows) { + locks.add(region.getRowLock(row, false)); + } + } catch (IOException e) { + ServerUtil.releaseRowLocks(locks); + throw e; + } + return locks; + } + + private static boolean descriptorRowExists(Region region, String protobufName) + throws IOException { + byte[] rowKey = Bytes.toBytes(protobufName); + Get get = new Get(rowKey); + get.addColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, + PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET_BYTES); + Result result = region.get(get); + return result != null && !result.isEmpty(); + } + + /** Currently registered FILE_DESCRIPTOR_SET bytes, or null if the row is missing. */ + private static byte[] getDescriptorBytes(Region region, String protobufName) throws IOException { + byte[] rowKey = Bytes.toBytes(protobufName); + Get get = new Get(rowKey); + get.addColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, + PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET_BYTES); + Result result = region.get(get); + if (result == null || result.isEmpty()) { + return null; + } + return result.getValue(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, + PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET_BYTES); + } + + /** Resolves {@code protobufName} from FileDescriptorSet bytes, or throws. */ + private static Descriptors.Descriptor resolveOrThrow(byte[] descriptorBytes, String protobufName) + throws SQLException { + try { + Descriptors.Descriptor resolved = + new ProtoDescriptorResolver().resolve(descriptorBytes, protobufName); + if (resolved == null) { + throw new SQLExceptionInfo.Builder( + SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE) + .setMessage("descriptor '" + protobufName + "' not present in resolved set").build() + .buildException(); + } + return resolved; + } catch (IOException e) { + throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED) + .setMessage("failed to resolve descriptor '" + protobufName + "': " + e.getMessage()) + .build().buildException(); + } + } + + private static Put buildDescriptorPut(String protobufName, byte[] descriptorBytes, + long timestamp) { + byte[] rowKey = Bytes.toBytes(protobufName); + Put put = new Put(rowKey); + put.addColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, + PhoenixDatabaseMetaData.FILE_DESCRIPTOR_SET_BYTES, timestamp, descriptorBytes); + put.addColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, QueryConstants.EMPTY_COLUMN_BYTES, + timestamp, QueryConstants.EMPTY_COLUMN_VALUE_BYTES); + return put; + } + + /** + * Returns {@code true} if a {@code SYSTEM.PROTO_DESC_LINK} row for {@code protobufName} points at + * a live {@code SYSTEM.CATALOG} column still bound to it. Links whose column is gone are left in + * place; the next link write for the same column overwrites them. + *

+ * A DROP can still race a concurrent CREATE TABLE or ADD COLUMN on the same descriptor: if the + * DROP scans before the new column is written, both succeed and the column points to a missing + * descriptor. PROTO_* queries on it fail until the descriptor is registered again. + */ + private boolean isDescriptorInUse(String protobufName) throws IOException { + byte[] name = Bytes.toBytes(protobufName); + Scan scan = new Scan(); + scan.setStartStopRowForPrefixScan(Bytes.add(name, QueryConstants.SEPARATOR_BYTE_ARRAY)); + scan.setFilter(new FirstKeyOnlyFilter()); + Configuration conf = env.getConfiguration(); + try ( + Table links = ServerUtil.getHTableForCoprocessorScan(env, + SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES, + conf)); + Table catalog = ServerUtil.getHTableForCoprocessorScan(env, + SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES, conf)); + ResultScanner scanner = links.getScanner(scan)) { + for (Result link : scanner) { + // protobuf name, tenant, schema, table, family, column + byte[][] key = new byte[6][]; + SchemaUtil.getVarChars(link.getRow(), key); + byte[] columnKey = SchemaUtil.getColumnKey(Bytes.toString(key[1]), Bytes.toString(key[2]), + Bytes.toString(key[3]), Bytes.toString(key[5]), + key[4].length == 0 ? null : Bytes.toString(key[4])); + Result column = catalog.get(new Get(columnKey).addColumn(TABLE_FAMILY_BYTES, + PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME_BYTES)); + if ( + Bytes.equals(name, + column.getValue(TABLE_FAMILY_BYTES, + PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME_BYTES)) + ) { + return true; + } + } + } + return false; + } + + private static ProtobufDescriptorMutationResponse okResponse(Collection registered) { + return ProtobufDescriptorMutationResponse.newBuilder().addAllRegisteredNames(registered) + .build(); + } + + private static ProtobufDescriptorMutationResponse errorResponse(SQLExceptionCode code, + String name, String message) { + ProtobufDescriptorMutationResponse.Builder b = + ProtobufDescriptorMutationResponse.newBuilder().setErrorCode(code.getErrorCode()); + if (name != null) { + b.setOffendingName(name); + } + if (message != null) { + b.setErrorMessage(message); + } + return b.build(); + } + + private static ProtobufDescriptorMutationResponse alreadyExistsResponse(String name) { + return errorResponse(SQLExceptionCode.PROTOBUF_DESCRIPTOR_ALREADY_EXISTS, name, null); + } + + private static ProtobufDescriptorMutationResponse notFoundResponse(String name) { + return errorResponse(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND, name, null); + } + + private static ProtobufDescriptorMutationResponse typeNotFoundResponse(String name) { + return errorResponse(SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE, name, + "No top-level protobuf message named '" + name + + "' was found in the loaded FileDescriptorSet"); + } + + private static ProtobufDescriptorMutationResponse inUseResponse(String name) { + return errorResponse(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE, name, null); + } + + private static ProtobufDescriptorMutationResponse fromSqlException(SQLException e, String name) { + SQLExceptionCode code = SQLExceptionCode.fromErrorCode(e.getErrorCode()); + if (code == SQLExceptionCode.UNKNOWN_ERROR_CODE) { + code = SQLExceptionCode.PROTOBUF_DESCRIPTOR_INTERNAL_ERROR; + LOGGER.error("Unexpected failure for PROTOBUF descriptor '{}'", name, e); + } else { + LOGGER.info("PROTOBUF descriptor '{}' request rejected: {}", name, e.getMessage()); + } + return errorResponse(code, name, String.valueOf(e.getMessage())); + } +} diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/schema/SystemProtoDescriptorsSplitPolicy.java b/phoenix-core-server/src/main/java/org/apache/phoenix/schema/SystemProtoDescriptorsSplitPolicy.java new file mode 100644 index 00000000000..8a3d4e468f0 --- /dev/null +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/schema/SystemProtoDescriptorsSplitPolicy.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.schema; + +import org.apache.hadoop.hbase.regionserver.DisabledRegionSplitPolicy; + +/** + * Split policy for {@code SYSTEM.PROTO_DESCRIPTORS}. Mirrors {@link SystemTaskSplitPolicy} — a thin + * no-split extension of {@link DisabledRegionSplitPolicy} so the table descriptor names a + * Phoenix-owned class (consistent with the other {@code System*SplitPolicy} entries). + *

+ * The descriptor table holds one row per registered protobuf message name; in practice this is a + * small bounded registry (hundreds of rows, capped at 10 MiB per cell). Single-region is required + * for {@code CREATE PROTOBUF BUNDLE} atomicity: the server-side handler atomically batch-writes N + * descriptor rows via {@code Region.mutateRowsWithLocks}, which HBase only honors when all N keys + * live in the same region. Per-row CREATE / ALTER / DROP work for any number of regions via + * single-key dispatch, but the bundle case forces the structural pin. + */ +public class SystemProtoDescriptorsSplitPolicy extends DisabledRegionSplitPolicy { + // empty +} diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/schema/transform/Transform.java b/phoenix-core-server/src/main/java/org/apache/phoenix/schema/transform/Transform.java index 86e3233831c..e145ed5f49b 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/schema/transform/Transform.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/schema/transform/Transform.java @@ -380,7 +380,7 @@ private static void mutateColumns(PhoenixConnection connection, PTable pOldTable column.getPosition(), column.getSortOrder(), column.getArraySize(), column.getViewConstant(), column.isViewReferenced(), column.getExpressionStr(), column.isRowTimestamp(), column.isDynamic(), column.getColumnQualifierBytes(), - EnvironmentEdgeManager.currentTimeMillis()); + EnvironmentEdgeManager.currentTimeMillis(), false, column.getProtoMessageName()); addColumnMutation(connection, pOldTable.getSchemaName() == null ? null : pOldTable.getSchemaName().getString(), pOldTable.getTableName().getString(), newCol, @@ -437,12 +437,12 @@ public static PTable getTransformedView(PTable pOldView, PTable pNewTable, continue; } - PColumn newCol = - new PColumnImpl(column.getName(), PNameFactory.newName(familyName), column.getDataType(), - column.getMaxLength(), column.getScale(), column.isNullable(), column.getPosition(), - column.getSortOrder(), column.getArraySize(), column.getViewConstant(), - column.isViewReferenced(), column.getExpressionStr(), column.isRowTimestamp(), - column.isDynamic(), colQualifierBytes, EnvironmentEdgeManager.currentTimeMillis()); + PColumn newCol = new PColumnImpl(column.getName(), PNameFactory.newName(familyName), + column.getDataType(), column.getMaxLength(), column.getScale(), column.isNullable(), + column.getPosition(), column.getSortOrder(), column.getArraySize(), + column.getViewConstant(), column.isViewReferenced(), column.getExpressionStr(), + column.isRowTimestamp(), column.isDynamic(), colQualifierBytes, + EnvironmentEdgeManager.currentTimeMillis(), false, column.getProtoMessageName()); newColumns.add(newCol); if (!columnMap.containsKey(newCol.getName().getString())) { columnMap.put(newCol.getName().getString(), newCol); diff --git a/phoenix-core/pom.xml b/phoenix-core/pom.xml index ea81af9ff53..6a1f44198ad 100644 --- a/phoenix-core/pom.xml +++ b/phoenix-core/pom.xml @@ -159,6 +159,11 @@ json-path test + + org.apache.phoenix.thirdparty + phoenix-shaded-protobuf + test + @@ -527,9 +532,36 @@ src/main/java/org/apache/phoenix/coprocessor/generated/*.java src/main/resources/META-INF/services/java.sql.Driver src/it/resources/*.json + + src/test/resources/protobuf/**/*.proto + + src/test/resources/protobuf/**/*.desc + diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsBundleIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsBundleIT.java new file mode 100644 index 00000000000..5d119299dea --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsBundleIT.java @@ -0,0 +1,1223 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.protobuf.text.AcmeWidgetsFixtures; +import org.apache.phoenix.schema.types.PDataType; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FileDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(ParallelStatsDisabledTest.class) +@RunWith(Parameterized.class) +public class AcmeWidgetsBundleIT extends ParallelStatsDisabledIT { + private static final String ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + private static final String WIDGET_ENDPOINT = + "com.example.acmewidgets.governance.v1.WidgetEndpoint"; + private static final String ENTITLEMENT = "com.example.acmewidgets.billing.v1.Entitlement"; + private static final String ORDER = "com.example.acmewidgets.orders.v1.Order"; + + private static final List BUNDLE_NAMES = + Arrays.asList(ACCOUNT, WIDGET_ENDPOINT, ENTITLEMENT, ORDER); + + private static Map descriptorGraph; + + private final boolean columnEncoded; + + public AcmeWidgetsBundleIT(boolean columnEncoded) { + this.columnEncoded = columnEncoded; + } + + @Parameterized.Parameters(name = "columnEncoded={0}") + public static synchronized Collection data() { + return Arrays.asList(new Object[][] { { false }, { true } }); + } + + @BeforeClass + public static synchronized void loadDescriptors() throws Exception { + descriptorGraph = AcmeWidgetsFixtures.loadAndBuildDescriptorGraph(); + } + + private Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private final List createdTables = new ArrayList<>(); + + private String uniqueTableName() { + String name = generateUniqueName(); + createdTables.add(name); + return name; + } + + private void registerBundleIdempotent(Connection conn) throws SQLException { + StringBuilder ddl = new StringBuilder("CREATE PROTOBUF BUNDLE IF NOT EXISTS ("); + for (int i = 0; i < BUNDLE_NAMES.size(); i++) { + if (i > 0) { + ddl.append(", "); + } + ddl.append(BUNDLE_NAMES.get(i)); + } + ddl.append(") FROM '").append(AcmeWidgetsFixtures.bundleFileUrl()).append("'"); + conn.createStatement().execute(ddl.toString()); + } + + @After + public void cleanupTablesAndDescriptors() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + for (String name : BUNDLE_NAMES) { + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + } + createdTables.clear(); + } + + @Test + public void createProtobufBundleRegistersAllExpectedNames() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + for (String name : BUNDLE_NAMES) { + assertTrue("Expected descriptor registered after CREATE PROTOBUF BUNDLE: " + name, + isDescriptorRegistered(conn, name)); + } + assertFalse(isDescriptorRegistered(conn, "com.example.acmewidgets.account.v1.Accoun")); + } + } + + @Test + public void createTableWithBundleRegisteredProtobufColumnSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + assertLinkRowCount(conn, ACCOUNT, table, 1); + } + } + + @Test + public void upsertAndSelectAccountRoundTripsByteIdentity() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "t-alpha", "t-bravo", "t-charlie", "t-delta", "t-echo", "t-foxtrot" }; + byte[][] wires = new byte[tenants.length][]; + for (int i = 0; i < tenants.length; i++) { + wires[i] = AcmeWidgetsFixtures + .newAccount(account, tenants[i], "Name-" + i, i % 2 == 0, "wh-" + i).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < tenants.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] roundTripped = rs.getBytes(2); + assertArrayEquals("row " + i, wires[i], roundTripped); + DynamicMessage parsedBack = DynamicMessage.parseFrom(account, roundTripped); + assertEquals(tenants[i], parsedBack.getField(account.findFieldByName("tenant_key"))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void upsertAndSelectWidgetEndpointWithOneofArmRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + WIDGET_ENDPOINT + ">)" + encodingClause()); + Descriptor widgetEndpoint = AcmeWidgetsFixtures.widgetEndpointDescriptor(descriptorGraph); + Descriptor catalogQuery = AcmeWidgetsFixtures.catalogQueryDescriptor(descriptorGraph); + String[] names = { "ep-a", "ep-b", "ep-c", "ep-d", "ep-e", "ep-f" }; + byte[][] wires = new byte[names.length][]; + for (int i = 0; i < names.length; i++) { + wires[i] = AcmeWidgetsFixtures.newWidgetEndpointWithCatalogQueryArm(widgetEndpoint, + catalogQuery, "tenant-" + i, names[i]).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < names.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] roundTripped = rs.getBytes(2); + assertArrayEquals("row " + i, wires[i], roundTripped); + DynamicMessage parsedBack = DynamicMessage.parseFrom(widgetEndpoint, roundTripped); + assertEquals("catalog_query", parsedBack.getOneofFieldDescriptor( + widgetEndpoint.findFieldByName("catalog_query").getContainingOneof()).getName()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void upsertAndSelectEntitlementWithMapAndRepeatedRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ENTITLEMENT + ">)" + encodingClause()); + boolean[] allowReturns = { true, true, false, false, true, false }; + byte[][] wires = new byte[allowReturns.length][]; + for (int i = 0; i < allowReturns.length; i++) { + wires[i] = buildEntitlementWithToggles("t-" + i, allowReturns[i], i % 2 == 0).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + Descriptor entitlement = AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph); + for (int i = 0; i < allowReturns.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] roundTripped = rs.getBytes(2); + assertArrayEquals("row " + i, wires[i], roundTripped); + DynamicMessage parsedBack = DynamicMessage.parseFrom(entitlement, roundTripped); + assertEquals(2, + parsedBack.getRepeatedFieldCount(entitlement.findFieldByName("policy_toggles"))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void resultSetMetadataReturnsProtobufTypeName() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " LIMIT 0")) { + ResultSetMetaData md = rs.getMetaData(); + assertEquals(2, md.getColumnCount()); + assertEquals("PROTOBUF", md.getColumnTypeName(2)); + assertEquals(PDataType.PROTOBUF_TYPE, md.getColumnType(2)); + } + } + } + + @Test + public void multiRowUpsertAndSelectPreservesAllPayloadsIndependently() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "tenant-A", "tenant-B", "tenant-C", "tenant-D", "tenant-E", "tenant-F" }; + byte[][] wires = new byte[tenants.length][]; + for (int i = 0; i < tenants.length; i++) { + wires[i] = AcmeWidgetsFixtures + .newAccount(account, tenants[i], "N" + i, i % 2 == 0, "wh-" + i).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < tenants.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertArrayEquals("row " + i, wires[i], rs.getBytes(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void nullProtobufColumnValueRoundTripsAsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + boolean[] isNull = { true, false, true, false, true, false }; + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + for (int i = 0; i < isNull.length; i++) { + ps.setLong(1, i + 1L); + if (isNull[i]) { + ps.setNull(2, PDataType.PROTOBUF_TYPE); + } else { + ps.setBytes(2, + AcmeWidgetsFixtures.newAccount(account, "t-" + i, "d", true, "w").toByteArray()); + } + ps.execute(); + } + } + conn.commit(); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < isNull.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] value = rs.getBytes(2); + if (isNull[i]) { + assertNull(value); + assertTrue(rs.wasNull()); + } else { + assertTrue(value != null && value.length > 0); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueScalarStringFieldRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "t-alpha", "t-bravo", "t-charlie", "t-delta", "t-echo", "t-foxtrot" }; + for (int i = 0; i < tenants.length; i++) { + upsertPayload(conn, table, i + 1L, AcmeWidgetsFixtures + .newAccount(account, tenants[i], "N" + i, true, "wh-" + i).toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM " + table + + " ORDER BY ID ASC")) { + for (int i = 0; i < tenants.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals(tenants[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueScalarBoolFieldRoundTripsWithProto3Default() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + boolean[] explicitActive = { true, true, false, true, false, false }; + for (int i = 0; i < explicitActive.length; i++) { + if (i == 1 || i == 4) { + DynamicMessage unset = DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("tenant_key"), "t-" + i) + .setField(account.findFieldByName("display_name"), "d").build(); + upsertPayload(conn, table, i + 1L, unset.toByteArray()); + } else { + upsertPayload(conn, table, i + 1L, AcmeWidgetsFixtures + .newAccount(account, "t-" + i, "d", explicitActive[i], "w").toByteArray()); + } + } + boolean[] expected = { true, false, false, true, false, false }; + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'active', 'BOOLEAN') FROM " + table + + " ORDER BY ID ASC")) { + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getBoolean(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueNestedMessageFieldReturnsInnerBytes() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + WIDGET_ENDPOINT + ">)" + encodingClause()); + Descriptor widgetEndpoint = AcmeWidgetsFixtures.widgetEndpointDescriptor(descriptorGraph); + Descriptor catalogQuery = AcmeWidgetsFixtures.catalogQueryDescriptor(descriptorGraph); + long[] versions = { 10L, 20L, 30L, 40L, 50L, 60L }; + for (int i = 0; i < versions.length; i++) { + DynamicMessage catalogQueryMsg = DynamicMessage.newBuilder(catalogQuery) + .setField(catalogQuery.findFieldByName("version"), versions[i]).build(); + DynamicMessage msg = DynamicMessage.newBuilder(widgetEndpoint) + .setField(widgetEndpoint.findFieldByName("tenant_key"), "tenant-" + i) + .setField(widgetEndpoint.findFieldByName("name"), "ep-" + i) + .setField(widgetEndpoint.findFieldByName("catalog_query"), catalogQueryMsg).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'catalog_query', 'VARBINARY') FROM " + + table + " ORDER BY ID ASC")) { + for (int i = 0; i < versions.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] innerBytes = rs.getBytes(2); + assertTrue("row " + i, innerBytes != null); + DynamicMessage inner = DynamicMessage.parseFrom(catalogQuery, innerBytes); + assertEquals(versions[i], inner.getField(catalogQuery.findFieldByName("version"))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueOneofInactiveArmReturnsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + WIDGET_ENDPOINT + ">)" + encodingClause()); + Descriptor widgetEndpoint = AcmeWidgetsFixtures.widgetEndpointDescriptor(descriptorGraph); + Descriptor catalogQuery = AcmeWidgetsFixtures.catalogQueryDescriptor(descriptorGraph); + for (int i = 0; i < 6; i++) { + DynamicMessage msg = AcmeWidgetsFixtures + .newWidgetEndpointWithCatalogQueryArm(widgetEndpoint, catalogQuery, "t-" + i, "e-" + i); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'bulk_order', 'VARBINARY') FROM " + + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertNull(rs.getBytes(2)); + assertTrue(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueMapValueScalarFieldRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ENTITLEMENT + ">)" + encodingClause()); + boolean[] allowReturns = { true, true, true, false, false, false }; + for (int i = 0; i < allowReturns.length; i++) { + upsertPayload(conn, table, i + 1L, + buildEntitlementWithToggles("t-" + i, allowReturns[i], false).toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery( + "SELECT ID, PROTO_VALUE(PAYLOAD, 'policy_toggles.allow_returns.enabled', 'BOOLEAN')" + + " FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < allowReturns.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, allowReturns[i], rs.getBoolean(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueMissingMapKeyReturnsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ENTITLEMENT + ">)" + encodingClause()); + for (int i = 0; i < 6; i++) { + upsertPayload(conn, table, i + 1L, + buildEntitlementWithToggles("t-" + i, true, false).toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery( + "SELECT ID, PROTO_VALUE(PAYLOAD, 'policy_toggles.never_added.enabled', 'BOOLEAN')" + + " FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + rs.getBoolean(2); + assertTrue(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueChildOfUnsetParentReturnsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + for (int i = 0; i < 6; i++) { + upsertPayload(conn, table, i + 1L, + AcmeWidgetsFixtures.newAccount(account, "t-" + i, "d", true, "w").toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt + .executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'deleted_time.seconds', 'BIGINT') FROM " + + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + rs.getLong(2); + assertTrue(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueWithDefaultAppliesDefault() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + for (int i = 0; i < 6; i++) { + upsertPayload(conn, table, i + 1L, + AcmeWidgetsFixtures.newAccount(account, "t-" + i, "d", true, "w").toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, " + + "'deleted_time.seconds', 'BIGINT', '999999') FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals(999999L, rs.getLong(2)); + assertFalse(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueWithVarcharAndBigintDefaultsMixInSingleQuery() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "t-alpha", "t-beta", "t-gamma", "t-delta", "t-epsilon", "t-zeta" }; + for (int i = 0; i < tenants.length; i++) { + upsertPayload(conn, table, i + 1L, AcmeWidgetsFixtures + .newAccount(account, tenants[i], "d-" + i, i % 2 == 0, "wh-" + i).toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR', 'no-tenant'), " + + "PROTO_VALUE(PAYLOAD, 'deleted_time.seconds', 'BIGINT', '111111') " + "FROM " + table + + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (int i = 0; i < tenants.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, tenants[i], rs.getString(2)); + assertEquals("row " + i, 111111L, rs.getLong(3)); + assertFalse(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueWithLiteralNullDefaultReturnsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + for (long id = 1L; id <= 5L; id++) { + upsertPayload(conn, table, id, + AcmeWidgetsFixtures.newAccount(account, "t-" + id, "d", true, "w").toByteArray()); + } + String sql = + "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'deleted_time.seconds', 'BIGINT', 'null'), " + + "PROTO_VALUE(PAYLOAD, 'deleted_time.seconds', 'BIGINT', 'NULL'), " + + "PROTO_VALUE(PAYLOAD, 'deleted_time.seconds', 'BIGINT', 'NuLl') " + "FROM " + table + + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (long id = 1L; id <= 5L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + for (int col = 2; col <= 4; col++) { + rs.getLong(col); + assertTrue("row " + id + " col " + col, rs.wasNull()); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueWithDoubleDefaultFiresForPastEndRepeatedIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ORDER + ">)" + encodingClause()); + for (long id = 1L; id <= 6L; id++) { + upsertPayload(conn, table, id, AcmeWidgetsFixtures + .newOrderRichlyPopulated(descriptorGraph, "ord-" + id, "cust-" + id).toByteArray()); + } + String sql = + "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'customer.contact.addresses[5].geo.latitude', " + + "'DOUBLE', '999.5'), " + + "PROTO_VALUE(PAYLOAD, 'customer.contact.addresses[9].geo.longitude', " + + "'DOUBLE', '-1.25') " + "FROM " + table + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + assertEquals("row " + id, 999.5d, rs.getDouble(2), 1e-9); + assertFalse(rs.wasNull()); + assertEquals("row " + id, -1.25d, rs.getDouble(3), 1e-9); + assertFalse(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueInWhereClauseFilters() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = + { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel" }; + for (int i = 0; i < tenants.length; i++) { + upsertPayload(conn, table, i + 1L, + AcmeWidgetsFixtures.newAccount(account, tenants[i], "N" + i, true, "w").toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') >= 'charlie'" + + " AND PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') <= 'foxtrot'" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') ASC")) { + String[] expected = { "charlie", "delta", "echo", "foxtrot" }; + long[] expectedIds = { 3L, 4L, 5L, 6L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expected[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') >= 'charlie'" + + " AND PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') <= 'foxtrot'" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') DESC")) { + String[] expected = { "foxtrot", "echo", "delta", "charlie" }; + long[] expectedIds = { 6L, 5L, 4L, 3L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("desc row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expected[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoArrayLengthOnLineItemsCountsRepeatedMessageElements() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ORDER + ">)" + encodingClause()); + Descriptor order = AcmeWidgetsFixtures.orderDescriptor(descriptorGraph); + Descriptor lineItem = AcmeWidgetsFixtures.lineItemDescriptor(descriptorGraph); + int[] lineItemsPerRow = { 0, 1, 3, 5, 2, 4 }; + for (int i = 0; i < lineItemsPerRow.length; i++) { + upsertPayload(conn, table, i + 1L, + newOrderWithLineItems(order, lineItem, "ord-" + (i + 1), lineItemsPerRow[i]) + .toByteArray()); + } + String sql = + "SELECT ID, PROTO_ARRAY_LENGTH(PAYLOAD, 'line_items') FROM " + table + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (int i = 0; i < lineItemsPerRow.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, lineItemsPerRow[i], rs.getInt(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoFieldTypeReturnsCanonicalSqlTypeNamesForOrderFields() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ORDER + ">)" + encodingClause()); + for (long id = 1L; id <= 6L; id++) { + DynamicMessage o = + AcmeWidgetsFixtures.newOrderRichlyPopulated(descriptorGraph, "ord-" + id, "cust-" + id); + upsertPayload(conn, table, id, o.toByteArray()); + } + String sql = "SELECT ID, " + "PROTO_FIELD_TYPE(PAYLOAD, 'order_id'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'customer.contact.addresses[0].geo.latitude'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'line_items[0].quantity'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'line_items[0].line_total.units'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'line_items[0].line_total.nanos') " + "FROM " + table + + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + assertEquals("row " + id, "VARCHAR", rs.getString(2)); + assertEquals("row " + id, "DOUBLE", rs.getString(3)); + assertEquals("row " + id, "INTEGER", rs.getString(4)); + assertEquals("row " + id, "BIGINT", rs.getString(5)); + assertEquals("row " + id, "INTEGER", rs.getString(6)); + } + assertFalse(rs.next()); + } + } + } + + private static DynamicMessage newOrderWithLineItems(Descriptor order, Descriptor lineItem, + String orderId, int lineItemCount) { + DynamicMessage.Builder builder = + DynamicMessage.newBuilder(order).setField(order.findFieldByName("order_id"), orderId); + for (int i = 0; i < lineItemCount; i++) { + DynamicMessage li = + DynamicMessage.newBuilder(lineItem).setField(lineItem.findFieldByName("line_id"), "li-" + i) + .setField(lineItem.findFieldByName("quantity"), i + 1).build(); + builder.addRepeatedField(order.findFieldByName("line_items"), li); + } + return builder.build(); + } + + @Test + public void protoExistsInWhereClauseFiltersRowsByHomeWarehousePresence() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] warehouses = { "w1", "", "w2", "", "w3", "", "w4" }; + for (int i = 0; i < warehouses.length; i++) { + upsertPayload(conn, table, i + 1L, + AcmeWidgetsFixtures + .newAccount(account, "tenant-" + (i + 1), "A" + (i + 1), true, warehouses[i]) + .toByteArray()); + } + String sql = "SELECT ID FROM " + table + + " WHERE PROTO_EXISTS(PAYLOAD, 'home_warehouse') = TRUE ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + long[] expectedIds = { 1L, 3L, 5L, 7L }; + for (long expectedId : expectedIds) { + assertTrue(rs.next()); + assertEquals(expectedId, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueDeepFiveLevelMessageChainWithArrayIndex() throws Exception { + runOrderQuery("PROTO_VALUE(PAYLOAD, 'customer.contact.addresses[0].geo.latitude', 'DOUBLE')", + (rs, i) -> assertEquals(10.0d + i, rs.getDouble(2), 0.0001d)); + } + + @Test + public void protoValueRepeatedOfRepeatedRecursiveTypeChain() throws Exception { + runOrderQuery( + "PROTO_VALUE(PAYLOAD, " + + "'line_items[0].modifiers[0].sub_modifiers[0].amount.units', 'BIGINT')", + (rs, i) -> assertEquals(100L + i, rs.getLong(2))); + } + + @Test + public void protoValueMapValueMessageThenScalarChain() throws Exception { + runOrderQuery("PROTO_VALUE(PAYLOAD, 'line_items[0].regional_prices.US.units', 'BIGINT')", + (rs, i) -> assertEquals(40L, rs.getLong(2))); + } + + @Test + public void protoValueMapOfRecursiveThenRepeatedNestedAccess() throws Exception { + runOrderQuery( + "PROTO_VALUE(PAYLOAD, " + + "'line_items[0].named_modifiers.holiday.sub_modifiers[0].display_name', " + "'VARCHAR')", + (rs, i) -> assertEquals("mod-" + (i + 1), rs.getString(2))); + } + + @Test + public void protoValueRecursiveSelfReferenceChain() throws Exception { + runOrderQuery("PROTO_VALUE(PAYLOAD, 'line_items[0].category.parent.parent.name', 'VARCHAR')", + (rs, i) -> assertEquals("cat-" + (i + 1), rs.getString(2))); + } + + @Test + public void protoValueMultipleCallsPerRowShareCachedPlan() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ORDER + ">)" + encodingClause()); + for (int i = 0; i < 6; i++) { + DynamicMessage order = AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, + "ord-" + (i + 1), "cust-" + (i + 1), 10L * (i + 1), 100L + i, 10.0d + i, i + 1, + "mod-" + (i + 1), "cat-" + (i + 1)); + upsertPayload(conn, table, i + 1L, order.toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, " + " PROTO_VALUE(PAYLOAD, 'order_id', 'VARCHAR')," + + " PROTO_VALUE(PAYLOAD, 'customer.customer_id', 'VARCHAR')," + + " PROTO_VALUE(PAYLOAD, 'line_items[0].line_id', 'VARCHAR')," + + " PROTO_VALUE(PAYLOAD, 'line_items[0].sku', 'VARCHAR')" + " FROM " + table + + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("ord-" + (i + 1), rs.getString(2)); + assertEquals("cust-" + (i + 1), rs.getString(3)); + assertEquals("line-1", rs.getString(4)); + assertEquals("SKU-001", rs.getString(5)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueIndexPastRepeatedEndReturnsNull() throws Exception { + runOrderQuery("PROTO_VALUE(PAYLOAD, 'line_items[99].line_id', 'VARCHAR')", (rs, i) -> { + assertNull(rs.getString(2)); + assertTrue(rs.wasNull()); + }); + } + + @Test + public void protoValueInt64ScalarFieldRoundTrips() throws Exception { + runOrderQuery("PROTO_VALUE(PAYLOAD, 'line_items[0].line_total.units', 'BIGINT')", + (rs, i) -> assertEquals(10L * (i + 1), rs.getLong(2))); + } + + @Test + public void protoValueOnVarbinaryColumnRejectedAtCompile() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW_BYTES VARBINARY)" + encodingClause()); + try (Statement stmt = conn.createStatement()) { + stmt.executeQuery("SELECT PROTO_VALUE(RAW_BYTES, 'foo', 'VARCHAR') FROM " + table); + fail("Expected PROTO_VALUE on VARBINARY column to be rejected"); + } catch (SQLException e) { + assertTrue("Expected error to mention PROTO_VALUE_AT_TAG hint: " + e.getMessage(), + e.getMessage().contains("PROTO_VALUE_AT_TAG") || e.getMessage().contains("PROTOBUF")); + } + } + } + + private interface RowAssertion { + void check(ResultSet rs, int rowIndex) throws SQLException; + } + + private void runOrderQuery(String selectExpr, RowAssertion assertion) throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ORDER + ">)" + encodingClause()); + for (int i = 0; i < 6; i++) { + DynamicMessage order = AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, + "ord-" + (i + 1), "cust-" + (i + 1), 10L * (i + 1), 100L + i, 10.0d + i, i + 1, + "mod-" + (i + 1), "cat-" + (i + 1)); + upsertPayload(conn, table, i + 1L, order.toByteArray()); + } + try (Statement stmt = conn.createStatement(); ResultSet rs = + stmt.executeQuery("SELECT ID, " + selectExpr + " FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertion.check(rs, i); + } + assertFalse(rs.next()); + } + } + } + + private DynamicMessage buildEntitlementWithToggles(String tenantKey, boolean allowReturns, + boolean allowRefunds) { + Descriptor entitlement = AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph); + Descriptor entitlementKey = AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph); + Descriptor entitlementVersion = + AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph); + Descriptor policyToggle = AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph); + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", allowReturns); + toggles.put("allow_refunds", allowRefunds); + return AcmeWidgetsFixtures.newEntitlement(entitlement, entitlementKey, entitlementVersion, + policyToggle, tenantKey, "unlimited-widgets", "ent-xyz", 1L, toggles); + } + + @Test + public void protoValueAtTagExtractsTopLevelStringByTagNumber() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW VARBINARY)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot" }; + for (int i = 0; i < tenants.length; i++) { + upsertRaw(conn, table, i + 1L, AcmeWidgetsFixtures + .newAccount(account, tenants[i], "N" + i, true, "wh-" + i).toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') >= 'bravo'" + + " AND PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') <= 'echo'" + + " ORDER BY PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') ASC")) { + String[] expected = { "bravo", "charlie", "delta", "echo" }; + long[] expectedIds = { 2L, 3L, 4L, 5L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expected[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') >= 'bravo'" + + " AND PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') <= 'echo'" + + " ORDER BY PROTO_VALUE_AT_TAG(RAW, '1', 'VARCHAR') DESC")) { + String[] expected = { "echo", "delta", "charlie", "bravo" }; + long[] expectedIds = { 5L, 4L, 3L, 2L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("desc row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expected[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagNestedOrderLineItemViaTagPath() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW VARBINARY)" + encodingClause()); + for (int i = 0; i < 6; i++) { + DynamicMessage order = AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, + "ord-" + (i + 1), "cust-" + (i + 1), 10L * (i + 1), 100L + i, 10.0d + i, i + 1, + "mod-" + (i + 1), "cat-" + (i + 1)); + upsertRaw(conn, table, i + 1L, order.toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE_AT_TAG(RAW, '3[0].1', 'VARCHAR') FROM " + table + + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("line-1", rs.getString(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagMissingTagReturnsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW VARBINARY)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + for (int i = 0; i < 6; i++) { + upsertRaw(conn, table, i + 1L, + AcmeWidgetsFixtures.newAccount(account, "t-" + i, "d", true, "w").toByteArray()); + } + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( + "SELECT ID, PROTO_VALUE_AT_TAG(RAW, '99', 'VARCHAR') FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagWithDefaultOnMissingTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW VARBINARY)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + for (int i = 0; i < 6; i++) { + upsertRaw(conn, table, i + 1L, + AcmeWidgetsFixtures.newAccount(account, "t-" + i, "d", true, "w").toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE_AT_TAG(RAW, '99', 'VARCHAR', 'fallback') FROM " + + table + " ORDER BY ID ASC")) { + for (int i = 0; i < 6; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("fallback", rs.getString(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagInvalidSyntaxRejectedAtCompile() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, RAW VARBINARY)" + encodingClause()); + try (Statement stmt = conn.createStatement()) { + stmt.executeQuery("SELECT PROTO_VALUE_AT_TAG(RAW, 'abc', 'VARCHAR') FROM " + table); + fail("Expected invalid tag-path syntax to be rejected"); + } catch (SQLException e) { + assertTrue("Expected TAG_PATH_INVALID_SYNTAX: " + e.getMessage(), + e.getErrorCode() == 11004 || e.getMessage().contains("tag-path")); + } + } + } + + private static void upsertRaw(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, RAW) VALUES (?, ?)")) { + ps.setLong(1, id); + ps.setBytes(2, payload); + ps.execute(); + } + conn.commit(); + } + + /** + * Derived tables that cannot be flattened into the outer query (inner LIMIT) and UNION ALL + * derived tables rebuild their columns from the inner projector; the PROTOBUF descriptor binding + * must carry through so PROTO_VALUE still resolves on the outer reference. + */ + @Test + public void protoValueOverDerivedTableAndUnion() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "t-alpha", "t-bravo", "t-charlie", "t-delta", "t-echo", "t-foxtrot" }; + for (int i = 0; i < tenants.length; i++) { + upsertPayload(conn, table, i + 1L, AcmeWidgetsFixtures + .newAccount(account, tenants[i], "N" + i, true, "wh-" + i).toByteArray()); + } + String inner = "SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID LIMIT 5"; + + assertTenants(conn, "SELECT PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM (" + inner + + ") ORDER BY ID DESC", "t-echo", "t-delta", "t-charlie", "t-bravo", "t-alpha"); + assertTenants(conn, + "SELECT PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM (" + inner + + ") WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') >= 't-charlie' ORDER BY ID", + "t-charlie", "t-delta", "t-echo"); + assertTenants(conn, + "SELECT PROTO_VALUE(S.PAYLOAD, 'tenant_key', 'VARCHAR') FROM " + table + " T JOIN (" + inner + + ") S ON T.ID = S.ID WHERE T.ID BETWEEN 2 AND 4 ORDER BY T.ID", + "t-bravo", "t-charlie", "t-delta"); + assertTenants(conn, + "SELECT PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM (SELECT ID, PAYLOAD FROM " + + table + " WHERE ID <= 2 UNION ALL SELECT ID, PAYLOAD FROM " + table + + " WHERE ID >= 5) ORDER BY ID DESC", + "t-foxtrot", "t-echo", "t-bravo", "t-alpha"); + } + } + + @Test + public void protoValueOverUnionOfDifferentDescriptorsRejected() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String accounts = uniqueTableName(); + String endpoints = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + accounts + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + conn.createStatement() + .execute("CREATE TABLE " + endpoints + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + WIDGET_ENDPOINT + ">)" + encodingClause()); + try { + conn.createStatement() + .executeQuery("SELECT PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') FROM (SELECT ID," + + " PAYLOAD FROM " + accounts + " UNION ALL SELECT ID, PAYLOAD FROM " + endpoints + + ")"); + fail("PROTO_VALUE over a UNION ALL of differently bound PROTOBUF columns must fail"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH.getErrorCode(), + e.getErrorCode()); + } + } + } + + private static void assertTenants(Connection conn, String sql, String... expected) + throws SQLException { + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (String tenant : expected) { + assertTrue(sql, rs.next()); + assertEquals(sql, tenant, rs.getString(1)); + } + assertFalse(sql, rs.next()); + } + } + + private static void upsertPayload(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + ps.setLong(1, id); + ps.setBytes(2, payload); + ps.execute(); + } + conn.commit(); + } + + private static void assertLinkRowCount(Connection conn, String protobufName, String tableName, + int expected) throws SQLException { + String sql = "SELECT COUNT(*) FROM SYSTEM.\"PROTO_DESC_LINK\" WHERE PROTOBUF_NAME = ? AND " + + "TABLE_NAME = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + ps.setString(2, tableName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(expected, rs.getInt(1)); + } + } + } + + private static boolean isDescriptorRegistered(Connection conn, String protobufName) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("SELECT 1 FROM SYSTEM.PROTO_DESCRIPTORS WHERE PROTOBUF_NAME = ?")) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + return rs.next(); + } + } + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsProto2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsProto2IT.java new file mode 100644 index 00000000000..0beffa1b227 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AcmeWidgetsProto2IT.java @@ -0,0 +1,360 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.apache.phoenix.protobuf.text.AcmeWidgetsFixtures; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FileDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(ParallelStatsDisabledTest.class) +@RunWith(Parameterized.class) +public class AcmeWidgetsProto2IT extends ParallelStatsDisabledIT { + private static final String TOKEN_REVOCATION = + "com.example.acmewidgets.auth.v1.proto2.TokenRevocation"; + + private static Map descriptorGraph; + + private final boolean columnEncoded; + + public AcmeWidgetsProto2IT(boolean columnEncoded) { + this.columnEncoded = columnEncoded; + } + + @Parameterized.Parameters(name = "columnEncoded={0}") + public static synchronized Collection data() { + return Arrays.asList(new Object[][] { { false }, { true } }); + } + + @BeforeClass + public static synchronized void loadDescriptors() throws Exception { + descriptorGraph = AcmeWidgetsFixtures.loadAndBuildDescriptorGraph(); + } + + private Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private final List createdTables = new ArrayList<>(); + + private String uniqueTableName() { + String name = generateUniqueName(); + createdTables.add(name); + return name; + } + + private void registerTokenRevocationDescriptor(Connection conn) throws SQLException { + conn.createStatement().execute("CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + TOKEN_REVOCATION + + " FROM '" + AcmeWidgetsFixtures.bundleFileUrl() + "'"); + } + + @After + public void cleanupTablesAndDescriptors() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + TOKEN_REVOCATION); + } catch (SQLException ignore) { + } + } + createdTables.clear(); + } + + @Test + public void createProto2DescriptorAndTableSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " LIMIT 0")) { + ResultSetMetaData md = rs.getMetaData(); + assertEquals("PROTOBUF", md.getColumnTypeName(2)); + } + } + } + + @Test + public void upsertAndSelectTokenRevocationAllRequiredFieldsSetRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + Descriptor tokenRevocation = AcmeWidgetsFixtures.tokenRevocationDescriptor(descriptorGraph); + String[] reasons = { "rotated", "revoked", "expired", "stolen", "lost", "other" }; + byte[][] wires = new byte[reasons.length][]; + for (int i = 0; i < reasons.length; i++) { + wires[i] = AcmeWidgetsFixtures + .newTokenRevocation(tokenRevocation, "tenant-" + i, "tok-" + i, reasons[i]).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < reasons.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] roundTripped = rs.getBytes(2); + assertArrayEquals("row " + i, wires[i], roundTripped); + DynamicMessage parsedBack = DynamicMessage.parseFrom(tokenRevocation, roundTripped); + assertTrue(parsedBack.hasField(tokenRevocation.findFieldByName("reason"))); + assertEquals(reasons[i], parsedBack.getField(tokenRevocation.findFieldByName("reason"))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void upsertAndSelectTokenRevocationWithReasonUnsetRoundTrips() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + Descriptor tokenRevocation = AcmeWidgetsFixtures.tokenRevocationDescriptor(descriptorGraph); + FieldDescriptor reason = tokenRevocation.findFieldByName("reason"); + byte[][] wires = new byte[6][]; + for (int i = 0; i < wires.length; i++) { + wires[i] = AcmeWidgetsFixtures + .newTokenRevocationWithReasonUnset(tokenRevocation, "tenant-" + i, "tok-" + i) + .toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < wires.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] roundTripped = rs.getBytes(2); + assertArrayEquals("row " + i, wires[i], roundTripped); + DynamicMessage parsedBack = DynamicMessage.parseFrom(tokenRevocation, roundTripped); + assertFalse(parsedBack.hasField(reason)); + assertEquals("rotated", parsedBack.getField(reason)); + } + assertFalse(rs.next()); + } + // An unset proto2 field reads as its declared default; PROTO_EXISTS still reports it unset. + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT PROTO_VALUE(PAYLOAD, 'reason', 'VARCHAR')," + + " PROTO_EXISTS(PAYLOAD, 'reason') FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < wires.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals("row " + i, "rotated", rs.getString(1)); + assertFalse("row " + i, rs.getBoolean(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void unsetProto2FieldsReadAsDeclaredDefaultAcrossRows() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + Descriptor tokenRevocation = AcmeWidgetsFixtures.tokenRevocationDescriptor(descriptorGraph); + // { reason, soft_revoke }; null means unset. reason defaults to "rotated", soft_revoke to + // false. + Object[][] rows = { { "compromised", true }, { null, null }, { "", null }, + { "rotated", false }, { null, true }, { "expired", null } }; + for (int i = 0; i < rows.length; i++) { + DynamicMessage.Builder b = DynamicMessage.newBuilder(tokenRevocation) + .setField(tokenRevocation.findFieldByName("tenant_id"), "tenant-" + i) + .setField(tokenRevocation.findFieldByName("token_id"), "tok-" + i); + if (rows[i][0] != null) { + b.setField(tokenRevocation.findFieldByName("reason"), rows[i][0]); + } + if (rows[i][1] != null) { + b.setField(tokenRevocation.findFieldByName("soft_revoke"), rows[i][1]); + } + upsertPayload(conn, table, i + 1L, b.build().toByteArray()); + } + + // Row 3 sets reason to "", which is on the wire, so neither default applies and Phoenix + // reads the empty string as NULL. + String[] expectedReason = { "compromised", "rotated", null, "rotated", "rotated", "expired" }; + String[] expectedWithUserDefault = + { "compromised", "none", null, "rotated", "none", "expired" }; + boolean[] expectedSoftRevoke = { true, false, false, false, true, false }; + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'reason', 'VARCHAR')," + + " PROTO_EXISTS(PAYLOAD, 'reason')," + + " PROTO_VALUE(PAYLOAD, 'reason', 'VARCHAR', 'none')," + + " PROTO_VALUE(PAYLOAD, 'soft_revoke', 'BOOLEAN')," + + " PROTO_EXISTS(PAYLOAD, 'soft_revoke') FROM " + table + " ORDER BY ID")) { + for (int i = 0; i < rows.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expectedReason[i], rs.getString(2)); + assertEquals("row " + i, rows[i][0] != null, rs.getBoolean(3)); + assertEquals("row " + i, expectedWithUserDefault[i], rs.getString(4)); + assertEquals("row " + i, expectedSoftRevoke[i], rs.getObject(5)); + assertEquals("row " + i, rows[i][1] != null, rs.getBoolean(6)); + } + assertFalse(rs.next()); + } + + // Filters evaluate on the server, where unset rows match the declared default too. + assertIds(conn, "SELECT ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'reason', 'VARCHAR') = 'rotated' ORDER BY ID", 2L, 4L, 5L); + assertIds(conn, + "SELECT ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'reason', 'VARCHAR', 'none') = 'none' ORDER BY ID", + 2L, 5L); + assertIds(conn, + "SELECT ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'soft_revoke', 'BOOLEAN') = FALSE ORDER BY ID DESC", + 6L, 4L, 3L, 2L); + } + } + + // PROTO_VALUE_AT_TAG coverage of proto2 extensions is not asserted here yet. + @Test + public void upsertAndSelectTokenRevocationWithExtensionSurvivesRoundTrip() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + Descriptor tokenRevocation = AcmeWidgetsFixtures.tokenRevocationDescriptor(descriptorGraph); + FileDescriptor voucherFile = descriptorGraph.get("voucher_revocation_sync.proto"); + String[] partners = { "p-a", "p-b", "p-c", "p-d", "p-e", "p-f" }; + byte[][] wires = new byte[partners.length][]; + for (int i = 0; i < partners.length; i++) { + wires[i] = AcmeWidgetsFixtures.newTokenRevocationWithPartnerSourceExtension(tokenRevocation, + voucherFile, "tenant-" + i, "tok-" + i, partners[i]).toByteArray(); + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < partners.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertArrayEquals("row " + i, wires[i], rs.getBytes(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void multiRowProto2UpsertAndSelectPreservesAllPayloadsIndependently() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerTokenRevocationDescriptor(conn); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + Descriptor tokenRevocation = AcmeWidgetsFixtures.tokenRevocationDescriptor(descriptorGraph); + FileDescriptor voucherFile = descriptorGraph.get("voucher_revocation_sync.proto"); + byte[][] wires = new byte[6][]; + wires[0] = AcmeWidgetsFixtures + .newTokenRevocation(tokenRevocation, "tenant-A", "tok-A", "revoked").toByteArray(); + wires[1] = AcmeWidgetsFixtures + .newTokenRevocationWithReasonUnset(tokenRevocation, "tenant-B", "tok-B").toByteArray(); + wires[2] = AcmeWidgetsFixtures.newTokenRevocationWithPartnerSourceExtension(tokenRevocation, + voucherFile, "tenant-C", "tok-C", "partner-c").toByteArray(); + wires[3] = AcmeWidgetsFixtures + .newTokenRevocation(tokenRevocation, "tenant-D", "tok-D", "expired").toByteArray(); + wires[4] = AcmeWidgetsFixtures + .newTokenRevocationWithReasonUnset(tokenRevocation, "tenant-E", "tok-E").toByteArray(); + wires[5] = AcmeWidgetsFixtures.newTokenRevocationWithPartnerSourceExtension(tokenRevocation, + voucherFile, "tenant-F", "tok-F", "partner-f").toByteArray(); + for (int i = 0; i < wires.length; i++) { + upsertPayload(conn, table, i + 1L, wires[i]); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PAYLOAD FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < wires.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertArrayEquals("row " + i, wires[i], rs.getBytes(2)); + } + assertFalse(rs.next()); + } + } + } + + private static void assertIds(Connection conn, String sql, long... expected) throws SQLException { + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (long id : expected) { + assertTrue(sql, rs.next()); + assertEquals(sql, id, rs.getLong(1)); + } + assertFalse(sql, rs.next()); + } + } + + private static void upsertPayload(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + ps.setLong(1, id); + ps.setBytes(2, payload); + ps.execute(); + } + conn.commit(); + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java index e3fc2ac9ee0..52ccd63a95f 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java @@ -29,6 +29,7 @@ import com.google.protobuf.RpcController; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; +import java.net.URL; import java.security.PrivilegedExceptionAction; import java.sql.Connection; import java.sql.DriverManager; @@ -1704,6 +1705,106 @@ public Void run() throws Exception { verifyAllowed(readTable(phoenixTableName), unprivilegedUser); } + private static final String PROTO_DESC_BUNDLE_RESOURCE = + "/protobuf/acmewidgets/acmewidgets_v1.desc"; + private static final String PROTO_DESC_ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + private static final String PROTO_DESC_CUSTOMER = "com.example.acmewidgets.orders.v1.Customer"; + + private static String protoDescFixtureUrl() { + URL res = BasePermissionsIT.class.getResource(PROTO_DESC_BUNDLE_RESOURCE); + assertTrue("missing test fixture " + PROTO_DESC_BUNDLE_RESOURCE, res != null); + return res.toString(); + } + + private String protoDescTable() { + return isNamespaceMapped + ? SchemaUtil + .getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, true) + .getNameAsString() + : PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME; + } + + private AccessTestAction protoDescLinkCount(final String tableName, final int expected) { + return () -> { + try (Connection conn = getConnection(); ResultSet rs = conn.createStatement().executeQuery( + "SELECT COUNT(*) FROM SYSTEM.PROTO_DESC_LINK WHERE TABLE_NAME = '" + tableName + "'")) { + assertTrue(rs.next()); + assertEquals(expected, rs.getInt(1)); + } + return null; + }; + } + + private AccessTestAction protoDescDdl(final String sql) { + return new AccessTestAction() { + @Override + public Object run() throws Exception { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + assertFalse(stmt.execute(sql)); + } + return null; + } + }; + } + + @Test + public void testProtobufDescriptorDdlRequiresGlobalAdmin() throws Throwable { + final String url = protoDescFixtureUrl(); + final String create = + "CREATE PROTOBUF DESCRIPTOR " + PROTO_DESC_ACCOUNT + " FROM '" + url + "'"; + final String alter = "ALTER PROTOBUF DESCRIPTOR " + PROTO_DESC_ACCOUNT + " FROM '" + url + "'"; + final String drop = "DROP PROTOBUF DESCRIPTOR " + PROTO_DESC_ACCOUNT; + final String dropIfExists = "DROP PROTOBUF DESCRIPTOR IF EXISTS " + PROTO_DESC_CUSTOMER; + final String bundle = + "CREATE PROTOBUF BUNDLE IF NOT EXISTS (" + PROTO_DESC_CUSTOMER + ") FROM '" + url + "'"; + + grantSystemTableAccess(superUser1, regularUser1, unprivilegedUser); + // Full rights on the descriptor table are not enough; only global ADMIN passes. + String descTable = protoDescTable(); + grantPermissions(unprivilegedUser.getShortName(), Collections.singleton(descTable), + Permission.Action.READ, Permission.Action.WRITE, Permission.Action.EXEC, + Permission.Action.CREATE, Permission.Action.ADMIN); + grantPermissions(regularUser1.getShortName(), Collections.singleton(descTable), + Permission.Action.READ, Permission.Action.WRITE, Permission.Action.EXEC); + + verifyAllowed(protoDescDdl(create), superUser1); + + // IF [NOT] EXISTS forms are denied too: authorization runs before the existence check. + for (String sql : Arrays.asList(create, alter, drop, dropIfExists, bundle)) { + verifyDenied(protoDescDdl(sql), AccessDeniedException.class, unprivilegedUser, regularUser1); + } + + verifyAllowed(grantPermissions("A", regularUser1), superUser1); + verifyAllowed(protoDescDdl(alter), regularUser1); + verifyAllowed(protoDescDdl(bundle), regularUser1); + verifyAllowed(protoDescDdl(dropIfExists), regularUser1); + verifyAllowed(protoDescDdl(drop), regularUser1); + verifyAllowed(revokePermissions(regularUser1), superUser1); + } + + @Test + public void testProtobufColumnDdlNeedsNoProtoDescLinkAccess() throws Throwable { + final String table = generateUniqueName(); + // Runs before the grants so the SYSTEM regions it creates exist when ACLs are awaited. + verifyAllowed(protoDescDdl("CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + PROTO_DESC_ACCOUNT + + " FROM '" + protoDescFixtureUrl() + "'"), superUser1); + grantSystemTableAccess(superUser1, regularUser1); + grantPermissions(regularUser1.getShortName(), Collections.singleton(protoDescTable()), + Permission.Action.READ, Permission.Action.EXEC); + grantPermissions(regularUser1.getShortName(), NamespaceDescriptor.DEFAULT_NAMESPACE.getName(), + Permission.Action.CREATE); + + verifyAllowed(protoDescDdl("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + PROTO_DESC_ACCOUNT + ">)"), regularUser1); + verifyAllowed( + protoDescDdl("ALTER TABLE " + table + " ADD B PROTOBUF<" + PROTO_DESC_ACCOUNT + ">"), + regularUser1); + verifyAllowed(protoDescLinkCount(table, 2), superUser1); + verifyAllowed(protoDescDdl("ALTER TABLE " + table + " DROP COLUMN A, B"), regularUser1); + verifyAllowed(protoDescLinkCount(table, 0), superUser1); + verifyAllowed(protoDescDdl("DROP PROTOBUF DESCRIPTOR " + PROTO_DESC_ACCOUNT), superUser1); + } + AccessTestAction onlyCreateImmutableTable(final String tableName) throws SQLException { return new AccessTestAction() { @Override @@ -1781,6 +1882,9 @@ public void getUserPermissions(RpcController controller, request.hasNamespaceName() ? request.getNamespaceName().toStringUtf8() : null; perms.addAll( AccessControlClient.getUserPermissions(connection, AuthUtil.toGroupEntry(namespace))); + } else if (request.getType() == AccessControlProtos.Permission.Type.Global) { + // An empty table regex returns the GLOBAL-scope grants. + perms.addAll(AccessControlClient.getUserPermissions(connection, "")); } response = AccessControlUtil.buildGetUserPermissionsResponse(perms); } catch (Throwable ioe) { diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CoalesceFunctionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CoalesceFunctionIT.java index f6f836860d3..64fdad81963 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CoalesceFunctionIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CoalesceFunctionIT.java @@ -137,6 +137,27 @@ public void coalesceWithSecondParamAsExpression() throws Exception { assertFalse(rs.wasNull()); } + @Test + public void coalesceWithSecondParamAsExpressionUsingProtobufKeywords() throws Exception { + Connection conn = DriverManager.getConnection(getUrl()); + String tableName = generateUniqueName(); + String ddl = "CREATE TABLE " + tableName + + "(bundle BIGINT NOT NULL, descriptor BIGINT CONSTRAINT pk PRIMARY KEY(bundle))"; + conn.createStatement().execute(ddl); + + conn.createStatement() + .execute("UPSERT INTO " + tableName + "(bundle, descriptor) VALUES(2, null)"); + conn.commit(); + + ResultSet rs = conn.createStatement() + .executeQuery("SELECT COALESCE(SUM(protobuf.descriptor), SUM(protobuf.bundle)) FROM " + + tableName + " protobuf GROUP BY protobuf.bundle"); + + assertTrue(rs.next()); + assertEquals(2, rs.getLong(1)); + assertFalse(rs.wasNull()); + } + @Test public void nonTypedSecondParameterLong() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MigrateSystemTablesToSystemNamespaceIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MigrateSystemTablesToSystemNamespaceIT.java index ac0002a4790..73e73c939c7 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MigrateSystemTablesToSystemNamespaceIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MigrateSystemTablesToSystemNamespaceIT.java @@ -68,14 +68,16 @@ public class MigrateSystemTablesToSystemNamespaceIT extends BaseTest { private static final Set HBASE_NAMESPACE_MAPPED_SYSTEM_TABLES = new HashSet<>(Arrays.asList("SYSTEM:PHOENIX_INDEX_TOOL_RESULT", "SYSTEM:PHOENIX_INDEX_TOOL")); - private static final Set PHOENIX_SYSTEM_TABLES = new HashSet<>( - Arrays.asList("SYSTEM.CATALOG", "SYSTEM.SEQUENCE", "SYSTEM.STATS", "SYSTEM.FUNCTION", - "SYSTEM.MUTEX", "SYSTEM.LOG", "SYSTEM.CHILD_LINK", "SYSTEM.TASK", "SYSTEM.TRANSFORM", - "SYSTEM.CDC_STREAM_STATUS", "SYSTEM.CDC_STREAM", "SYSTEM.IDX_CDC_TRACKER")); - private static final Set PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES = new HashSet<>( - Arrays.asList("SYSTEM:CATALOG", "SYSTEM:SEQUENCE", "SYSTEM:STATS", "SYSTEM:FUNCTION", - "SYSTEM:MUTEX", "SYSTEM:LOG", "SYSTEM:CHILD_LINK", "SYSTEM:TASK", "SYSTEM:TRANSFORM", - "SYSTEM:CDC_STREAM_STATUS", "SYSTEM:CDC_STREAM", "SYSTEM:IDX_CDC_TRACKER")); + private static final Set PHOENIX_SYSTEM_TABLES = + new HashSet<>(Arrays.asList("SYSTEM.CATALOG", "SYSTEM.SEQUENCE", "SYSTEM.STATS", + "SYSTEM.FUNCTION", "SYSTEM.MUTEX", "SYSTEM.LOG", "SYSTEM.CHILD_LINK", "SYSTEM.TASK", + "SYSTEM.TRANSFORM", "SYSTEM.CDC_STREAM_STATUS", "SYSTEM.CDC_STREAM", "SYSTEM.IDX_CDC_TRACKER", + "SYSTEM.PROTO_DESCRIPTORS", "SYSTEM.PROTO_DESC_LINK")); + private static final Set PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES = + new HashSet<>(Arrays.asList("SYSTEM:CATALOG", "SYSTEM:SEQUENCE", "SYSTEM:STATS", + "SYSTEM:FUNCTION", "SYSTEM:MUTEX", "SYSTEM:LOG", "SYSTEM:CHILD_LINK", "SYSTEM:TASK", + "SYSTEM:TRANSFORM", "SYSTEM:CDC_STREAM_STATUS", "SYSTEM:CDC_STREAM", "SYSTEM:IDX_CDC_TRACKER", + "SYSTEM:PROTO_DESCRIPTORS", "SYSTEM:PROTO_DESC_LINK")); private static final String SCHEMA_NAME = "MIGRATETEST"; private static final String TABLE_NAME = SCHEMA_NAME + "." + MigrateSystemTablesToSystemNamespaceIT.class.getSimpleName().toUpperCase(); diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueEventualConsistencyIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueEventualConsistencyIndexIT.java new file mode 100644 index 00000000000..c5334256f10 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueEventualConsistencyIndexIT.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.hbase.index.IndexCDCConsumer.INDEX_CDC_CONSUMER_RETRY_PAUSE_MS; +import static org.apache.phoenix.hbase.index.IndexRegionObserver.PHOENIX_INDEX_CDC_MUTATION_SERIALIZE; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; +import org.apache.phoenix.query.QueryServices; +import org.apache.phoenix.util.ReadOnlyProps; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.common.collect.Maps; + +@Category(NeedsOwnMiniClusterTest.class) +@RunWith(Parameterized.class) +public class ProtoValueEventualConsistencyIndexIT extends ProtoValueIndexIT { + private static final long WAIT_MILLIS = 15_000L; + + public ProtoValueEventualConsistencyIndexIT(boolean columnEncoded, boolean coveredIndex) { + super(columnEncoded, coveredIndex); + } + + @Parameterized.Parameters(name = "columnEncoded={0}, coveredIndex={1}") + public static synchronized Collection data() { + return Arrays.asList(new Object[][] { { false, false }, { true, true } }); + } + + @BeforeClass + public static synchronized void doSetup() throws Exception { + Map props = Maps.newHashMapWithExpectedSize(6); + props.put(QueryServices.GLOBAL_INDEX_ROW_AGE_THRESHOLD_TO_DELETE_MS_ATTRIB, Long.toString(0)); + props.put(INDEX_CDC_CONSUMER_RETRY_PAUSE_MS, Integer.toString(5)); + props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Integer.toString(-1)); + props.put(PHOENIX_INDEX_CDC_MUTATION_SERIALIZE, Boolean.TRUE.toString()); + setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); + } + + @Before + public void appendEventualConsistency() { + if (indexDDLOptions.trim().isEmpty()) { + indexDDLOptions = " CONSISTENCY=EVENTUAL"; + } else { + indexDDLOptions = " CONSISTENCY=EVENTUAL," + indexDDLOptions; + } + } + + @Override + protected void waitForEventualConsistency() throws Exception { + Thread.sleep(WAIT_MILLIS); + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java new file mode 100644 index 00000000000..f04c2447e63 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java @@ -0,0 +1,1876 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.compile.ExplainPlan; +import org.apache.phoenix.compile.ExplainPlanAttributes; +import org.apache.phoenix.jdbc.PhoenixPreparedStatement; +import org.apache.phoenix.protobuf.text.AcmeWidgetsFixtures; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.After; +import org.junit.Assume; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FileDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(NeedsOwnMiniClusterTest.class) +@RunWith(Parameterized.class) +public class ProtoValueIndexIT extends ParallelStatsDisabledIT { + private static final String ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + private static final String ENTITLEMENT = "com.example.acmewidgets.billing.v1.Entitlement"; + private static final String ORDER = "com.example.acmewidgets.orders.v1.Order"; + + private static final List BUNDLE_NAMES = Arrays.asList(ACCOUNT, ENTITLEMENT, ORDER); + + private static Map descriptorGraph; + + protected final boolean columnEncoded; + protected final boolean coveredIndex; + + protected String indexDDLOptions = ""; + + public ProtoValueIndexIT(boolean columnEncoded, boolean coveredIndex) { + this.columnEncoded = columnEncoded; + this.coveredIndex = coveredIndex; + } + + protected void waitForEventualConsistency() throws Exception { + } + + @Parameterized.Parameters(name = "columnEncoded={0}, coveredIndex={1}") + public static synchronized Collection data() { + return Arrays.asList( + new Object[][] { { false, false }, { false, true }, { true, false }, { true, true } }); + } + + @BeforeClass + public static synchronized void loadDescriptors() throws Exception { + descriptorGraph = AcmeWidgetsFixtures.loadAndBuildDescriptorGraph(); + } + + private final List createdTables = new ArrayList<>(); + + @After + public void cleanupTablesAndDescriptors() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + for (String name : BUNDLE_NAMES) { + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + } + createdTables.clear(); + } + + @Test + public void topLevelScalarStringIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "tenant-alpha", "tenant-beta", "tenant-charlie", "tenant-delta", + "tenant-echo", "tenant-foxtrot", "tenant-golf", "tenant-hotel" }; + for (int i = 0; i < tenants.length; i++) { + upsertRow(conn, table, (long) (i + 1), "c1-" + tenants[i], AcmeWidgetsFixtures + .newAccount(account, tenants[i], "Name-" + i, i % 2 == 0, "wh-" + i).toByteArray()); + } + + assertIndexRowCount(conn, index, tenants.length); + + String pointSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setString(1, "tenant-echo"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(5L, rs.getLong(1)); + assertEquals("c1-tenant-echo", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeAscSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') >= ?" + + " AND PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') < ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeAscSql)) { + ps.setString(1, "tenant-b"); + ps.setString(2, "tenant-g"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L, 6L }; + String[] expectedC1 = { "c1-tenant-beta", "c1-tenant-charlie", "c1-tenant-delta", + "c1-tenant-echo", "c1-tenant-foxtrot" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("expected row " + i, rs.next()); + assertEquals("row " + i + " id", expectedIds[i], rs.getLong(1)); + assertEquals("row " + i + " c1", expectedC1[i], rs.getString(2)); + } + assertFalse("expected exactly 5 rows in range", rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeDescSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') >= ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeDescSql)) { + ps.setString(1, "tenant-e"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 8L, 7L, 6L, 5L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + } + + @Test + public void deeplyNestedInt64Index() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement().execute( + indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'line_items[0].line_total.units', 'BIGINT')")); + + long[] amounts = { 10L, 20L, 30L, 40L, 50L, 60L, 70L }; + for (int i = 0; i < amounts.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-ord-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, amounts[i], 5L, 37.0d, 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, amounts.length); + + String pointSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'line_items[0].line_total.units', 'BIGINT') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setLong(1, 40L); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-ord-4", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'line_items[0].line_total.units', 'BIGINT') " + + "BETWEEN ? AND ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'line_items[0].line_total.units', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 30L); + ps.setLong(2, 60L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 4L, 5L, 6L }; + String[] expectedC1 = { "c1-ord-3", "c1-ord-4", "c1-ord-5", "c1-ord-6" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse("expected exactly 4 rows in [30, 60]", rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void deeplyNestedDoubleIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement().execute(indexDdl(index, table, + "PROTO_VALUE(PAYLOAD, 'customer.contact.addresses[0].geo.latitude', 'DOUBLE')")); + + double[] lats = { 34.0522d, 36.1699d, 37.7749d, 40.7128d, 41.8781d, 47.6062d, 51.5074d }; + for (int i = 0; i < lats.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-city-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, lats[i], 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, lats.length); + + String pointSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, " + + "'customer.contact.addresses[0].geo.latitude', 'DOUBLE') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setDouble(1, 40.7128d); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-city-4", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeDescSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, " + + "'customer.contact.addresses[0].geo.latitude', 'DOUBLE') > ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, " + + "'customer.contact.addresses[0].geo.latitude', 'DOUBLE') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeDescSql)) { + ps.setDouble(1, 40.0d); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 7L, 6L, 5L, 4L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + } + + @Test + public void mapValueBooleanIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement().execute(indexDdl(index, table, + "PROTO_VALUE(PAYLOAD, 'policy_toggles.allow_returns.enabled', 'BOOLEAN')")); + + boolean[] allowReturns = { true, true, true, false, false }; + for (int i = 0; i < allowReturns.length; i++) { + long id = i + 1L; + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", allowReturns[i]); + upsertRow(conn, table, id, "c1-ent-" + id, buildEntitlement(toggles).toByteArray()); + } + Map keyAbsent = new LinkedHashMap<>(); + keyAbsent.put("allow_refunds", true); + upsertRow(conn, table, 6L, "c1-ent-6", buildEntitlement(keyAbsent).toByteArray()); + + // An unset 'enabled' under a present map entry reads as false, so the false rows (4, 5) + // are indexed; only the key-absent row (6) reads as SQL NULL and is left out. + assertIndexRowCount(conn, index, 5); + + String trueSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'policy_toggles.allow_returns.enabled', 'BOOLEAN') = ?" + + " ORDER BY ID"; + try (PreparedStatement ps = conn.prepareStatement(trueSql)) { + ps.setBoolean(1, true); + try (ResultSet rs = ps.executeQuery()) { + long[] expected = { 1L, 2L, 3L }; + String[] expectedC1 = { "c1-ent-1", "c1-ent-2", "c1-ent-3" }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expected[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nestedInt32Index() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement().execute( + indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'line_items[0].quantity', 'INTEGER')")); + + int[] quantities = { 1, 2, 3, 5, 8, 13 }; + for (int i = 0; i < quantities.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-qty-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, 37.0d, quantities[i], "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, quantities.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'line_items[0].quantity', 'INTEGER') >= ?" + + " AND PROTO_VALUE(PAYLOAD, 'line_items[0].quantity', 'INTEGER') <= ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'line_items[0].quantity', 'INTEGER') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setInt(1, 2); + ps.setInt(2, 8); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L }; + String[] expectedC1 = { "c1-qty-2", "c1-qty-3", "c1-qty-4", "c1-qty-5" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void deepRepeatedOfRepeatedInt64Index() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, + "PROTO_VALUE(PAYLOAD, 'line_items[0].modifiers[0].sub_modifiers[0].amount.units', " + + "'BIGINT')")); + + long[] subAmounts = { 5L, 10L, 15L, 25L, 50L, 100L, 200L }; + for (int i = 0; i < subAmounts.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-sub-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, subAmounts[i], 37.0d, 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, subAmounts.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, " + + "'line_items[0].modifiers[0].sub_modifiers[0].amount.units', 'BIGINT') >= ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, " + + "'line_items[0].modifiers[0].sub_modifiers[0].amount.units', 'BIGINT') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 25L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 7L, 6L, 5L, 4L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void veryDeepSelfReferenceIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement().execute(indexDdl(index, table, + "PROTO_VALUE(PAYLOAD, 'line_items[0].category.parent.parent.name', 'VARCHAR')")); + + String[] categories = + { "Apparel", "Books", "Electronics", "Furniture", "Grocery", "Hardware" }; + for (int i = 0; i < categories.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-cat-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, 37.0d, 2, "Sub", categories[i]).toByteArray()); + } + + assertIndexRowCount(conn, index, categories.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, " + + "'line_items[0].category.parent.parent.name', 'VARCHAR') >= ?" + + " AND PROTO_VALUE(PAYLOAD, " + + "'line_items[0].category.parent.parent.name', 'VARCHAR') < ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, " + + "'line_items[0].category.parent.parent.name', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setString(1, "B"); + ps.setString(2, "G"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L }; + String[] expectedC1 = { "c1-cat-2", "c1-cat-3", "c1-cat-4" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nestedMessageLeafAsVarbinaryEncodedIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + + // VARBINARY_ENCODED (not raw VARBINARY): Phoenix disallows raw VARBINARY as + // the leading segment of a multi-part row key. + conn.createStatement().execute(indexDdl(index, table, + "PROTO_VALUE(PAYLOAD, 'line_items[0].line_total', 'VARBINARY_ENCODED')")); + + upsertRow(conn, table, 1L, "c1-order-1", AcmeWidgetsFixtures + .newOrderRichlyPopulated(descriptorGraph, "ord-1", "cust-1").toByteArray()); + + assertIndexRowCount(conn, index, 1); + String sql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, " + + "'line_items[0].line_total', 'VARBINARY_ENCODED') IS NOT NULL"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals("c1-order-1", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void uint64AsBigIntIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT')")); + + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", true); + long[] versions = { 100L, 150L, 200L, 300L, 500L, 800L }; + for (int i = 0; i < versions.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-ent-" + id, + AcmeWidgetsFixtures + .newEntitlement(AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph), + AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph), "tenant-" + id, + "ent-name", "ent-id", versions[i], toggles) + .toByteArray()); + } + + assertIndexRowCount(conn, index, versions.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT') > ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 200L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 4L, 5L, 6L }; + String[] expectedC1 = { "c1-ent-4", "c1-ent-5", "c1-ent-6" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void unsetScalarIsIndexedAsTypeZero() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + String expr = "PROTO_VALUE(PAYLOAD, 'active', 'BOOLEAN')"; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement().execute(nonPartialIndexDdl(index, table, expr)); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + // proto3 does not serialize false, so rows 2 and 4 carry no 'active' field on the wire. + boolean[] active = { true, false, true, false, true }; + for (int i = 0; i < active.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-" + id, AcmeWidgetsFixtures + .newAccount(account, "tenant-" + id, "Name-" + id, active[i], "wh-" + id).toByteArray()); + } + upsertRow(conn, table, 6L, "c1-6", null); + + // Index rows store a BOOLEAN key as DECIMAL, so false and true read back as 0 and 1. + assertIndexRows(conn, index, new Object[][] { { null, 6L }, { "0", 2L }, { "0", 4L }, + { "1", 1L }, { "1", 3L }, { "1", 5L } }); + assertNullLookup(conn, table, index, expr, 6L); + + String falseSql = "SELECT ID, C1 FROM " + table + " WHERE " + expr + " = ? ORDER BY ID"; + try (PreparedStatement ps = conn.prepareStatement(falseSql)) { + ps.setBoolean(1, false); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("c1-2", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-4", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + // The index must agree with evaluating the expression over the data table. + String allSql = " ID, " + expr + " FROM " + table + " ORDER BY ID"; + assertEquals(queryRows(conn, "SELECT /*+ NO_INDEX */" + allSql), + queryRows(conn, "SELECT" + allSql)); + assertEquals(Arrays.asList("1:true", "2:false", "3:true", "4:false", "5:true", "6:null"), + queryRows(conn, "SELECT /*+ NO_INDEX */" + allSql)); + + // Updates move the index row between zero and non-zero without leaving the old entry. + upsertRow(conn, table, 1L, "c1-1", + AcmeWidgetsFixtures.newAccount(account, "tenant-1", "Name-1", false, "wh-1").toByteArray()); + upsertRow(conn, table, 2L, "c1-2", + AcmeWidgetsFixtures.newAccount(account, "tenant-2", "Name-2", true, "wh-2").toByteArray()); + assertIndexRows(conn, index, new Object[][] { { null, 6L }, { "0", 1L }, { "0", 4L }, + { "1", 2L }, { "1", 3L }, { "1", 5L } }); + upsertRow(conn, table, 1L, "c1-1", + AcmeWidgetsFixtures.newAccount(account, "tenant-1", "Name-1", true, "wh-1").toByteArray()); + assertIndexRows(conn, index, new Object[][] { { null, 6L }, { "0", 4L }, { "1", 1L }, + { "1", 2L }, { "1", 3L }, { "1", 5L } }); + try (PreparedStatement ps = conn.prepareStatement(falseSql)) { + ps.setBoolean(1, false); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + assertEquals(queryRows(conn, "SELECT /*+ NO_INDEX */" + allSql), + queryRows(conn, "SELECT" + allSql)); + } + } + + @Test + public void indexOnExpressionWithDefaultIndexesAbsentFieldAsDefault() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + String expr = "PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR', 'none')"; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + // Index maintenance evaluates the expression, default included, on the region server. + conn.createStatement().execute(indexDdl(index, table, expr)); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] warehouses = { "wh-1", null, "wh-3", null, "wh-5", "none" }; + for (int i = 0; i < warehouses.length; i++) { + long id = i + 1L; + DynamicMessage.Builder b = DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("tenant_key"), "tenant-" + id); + if (warehouses[i] != null) { + b.setField(account.findFieldByName("home_warehouse"), warehouses[i]); + } + upsertRow(conn, table, id, "c1-" + id, b.build().toByteArray()); + } + + assertIndexRows(conn, index, new Object[][] { { "none", 2L }, { "none", 4L }, { "none", 6L }, + { "wh-1", 1L }, { "wh-3", 3L }, { "wh-5", 5L } }); + + String sql = "SELECT ID, C1 FROM " + table + " WHERE " + expr + " = ? ORDER BY ID"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "none"); + try (ResultSet rs = ps.executeQuery()) { + for (long id : new long[] { 2L, 4L, 6L }) { + assertTrue(rs.next()); + assertEquals(id, rs.getLong(1)); + assertEquals("c1-" + id, rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void uint64AsDecimalIndexOrdersByUnsignedValue() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + String expr = "PROTO_VALUE(PAYLOAD, 'version.version', 'DECIMAL')"; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement().execute(indexDdl(index, table, expr)); + + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", true); + // Raw signed bits: Long.MIN_VALUE is 2^63 and -1 is 2^64 - 1 when read as uint64. + long[] versions = { -1L, 1L, Long.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE + 1, 42L }; + for (int i = 0; i < versions.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-ent-" + id, + AcmeWidgetsFixtures + .newEntitlement(AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph), + AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph), "tenant-" + id, + "ent-name", "ent-id", versions[i], toggles) + .toByteArray()); + } + assertIndexRowCount(conn, index, versions.length); + + String rangeSql = + "SELECT ID, " + expr + " FROM " + table + " WHERE " + expr + " >= ? ORDER BY " + expr; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setBigDecimal(1, new BigDecimal(Long.MAX_VALUE)); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 4L, 3L, 5L, 1L }; + String[] expectedValues = { "9223372036854775807", "9223372036854775808", + "9223372036854775809", "18446744073709551615" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(new BigDecimal(expectedValues[i]), rs.getBigDecimal(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String descSql = + "SELECT ID FROM " + table + " WHERE " + expr + " < ? ORDER BY " + expr + " DESC"; + try (PreparedStatement ps = conn.prepareStatement(descSql)) { + ps.setBigDecimal(1, new BigDecimal("9223372036854775808")); + try (ResultSet rs = ps.executeQuery()) { + for (long id : new long[] { 4L, 6L, 2L }) { + assertTrue(rs.next()); + assertEquals(id, rs.getLong(1)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nonPartialIndexIncludesAllRows() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(nonPartialIndexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + upsertRow(conn, table, 1L, "c1-a", + AcmeWidgetsFixtures.newAccount(account, "tenant-a", "A", true, "wh").toByteArray()); + upsertRow(conn, table, 2L, "c1-b", + AcmeWidgetsFixtures.newAccount(account, "tenant-b", "B", true, "wh").toByteArray()); + + upsertRow(conn, table, 3L, "c1-c", DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("display_name"), "C").build().toByteArray()); + + assertIndexRowCount(conn, index, 3); + assertIndexRows(conn, index, + new Object[][] { { null, 3L }, { "tenant-a", 1L }, { "tenant-b", 2L } }); + assertNullLookup(conn, table, index, "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')", 3L); + String sql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "tenant-b"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("c1-b", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nonPartialIndexOnNestedLeafWithMissingParent() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + String expr = "PROTO_VALUE(PAYLOAD, 'key.tenant_key', 'VARCHAR')"; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement().execute(nonPartialIndexDdl(index, table, expr)); + upsertEntitlementsWithAndWithoutKey(conn, table); + + assertIndexRows(conn, index, + new Object[][] { { null, 2L }, { null, 3L }, { "tenant-idx", 1L } }); + assertNullLookup(conn, table, index, expr, 2L, 3L); + try (PreparedStatement ps = + conn.prepareStatement("SELECT ID FROM " + table + " WHERE " + expr + " = ?")) { + ps.setString(1, "tenant-idx"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void coveredIndexIncludingProtobufColumnReturnsPayloadFromIndex() throws Exception { + Assume.assumeTrue("INCLUDE(PAYLOAD) only applies to covered indexes", this.coveredIndex); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute("CREATE INDEX " + index + " ON " + table + + "(PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')) INCLUDE(PAYLOAD) WHERE " + + "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') IS NOT NULL" + indexDDLOptions); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + byte[] alpha = AcmeWidgetsFixtures + .newAccount(account, "alpha-tenant", "Alpha", true, "wh-north").toByteArray(); + byte[] beta = AcmeWidgetsFixtures.newAccount(account, "beta-tenant", "Beta", true, "wh-south") + .toByteArray(); + upsertRow(conn, table, 1L, "c1-a", alpha); + upsertRow(conn, table, 2L, "c1-b", beta); + + assertIndexRowCount(conn, index, 2); + String sql = "SELECT ID, PAYLOAD FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "beta-tenant"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertArrayEquals(beta, rs.getBytes(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void hexLiteralUpsertMaintainsIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + byte[] alpha = AcmeWidgetsFixtures.newAccount(account, "tenant-alpha", "Alpha", true, "wh-1") + .toByteArray(); + byte[] beta = + AcmeWidgetsFixtures.newAccount(account, "tenant-beta", "Beta", false, "wh-2").toByteArray(); + byte[] charlie = AcmeWidgetsFixtures + .newAccount(account, "tenant-charlie", "Charlie", true, "wh-3").toByteArray(); + upsertRowWithHexLiteral(conn, table, 1L, "c1-alpha", alpha); + upsertRowWithHexLiteral(conn, table, 2L, "c1-beta", beta); + upsertRowWithHexLiteral(conn, table, 3L, "c1-charlie", charlie); + + assertIndexRowCount(conn, index, 3); + assertPayloadBytes(conn, table, 1L, alpha); + assertPayloadBytes(conn, table, 2L, beta); + assertPayloadBytes(conn, table, 3L, charlie); + assertTenantLookup(conn, table, index, "tenant-beta", 2L, "c1-beta"); + + // Overwrite row 2 via hex literal with a different tenant_key: the old index entry + // must be removed and the new one must be reachable through the index. + byte[] zulu = + AcmeWidgetsFixtures.newAccount(account, "tenant-zulu", "Zulu", true, "wh-9").toByteArray(); + upsertRowWithHexLiteral(conn, table, 2L, "c1-zulu", zulu); + + assertIndexRowCount(conn, index, 3); + assertPayloadBytes(conn, table, 2L, zulu); + assertTenantLookup(conn, table, index, "tenant-beta", null, null); + assertTenantLookup(conn, table, index, "tenant-zulu", 2L, "c1-zulu"); + + // X'' is an empty byte literal, which Phoenix treats as NULL: the payload is cleared + // and the row drops out of the partial index. + conn.createStatement() + .execute("UPSERT INTO " + table + " (ID, C1, PAYLOAD) VALUES (3, 'c1-cleared', X'')"); + conn.commit(); + + assertIndexRowCount(conn, index, 2); + assertPayloadBytes(conn, table, 3L, null); + assertTenantLookup(conn, table, index, "tenant-charlie", null, null); + assertTenantLookup(conn, table, index, "tenant-alpha", 1L, "c1-alpha"); + } + } + + @Test + public void hexLiteralUpsertCoveredIndexIncludingProtobufColumn() throws Exception { + Assume.assumeTrue("INCLUDE(PAYLOAD) only applies to covered indexes", this.coveredIndex); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute("CREATE INDEX " + index + " ON " + table + + "(PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')) INCLUDE(PAYLOAD) WHERE " + + "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') IS NOT NULL" + indexDDLOptions); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + byte[] alpha = AcmeWidgetsFixtures + .newAccount(account, "alpha-tenant", "Alpha", true, "wh-north").toByteArray(); + byte[] beta = AcmeWidgetsFixtures.newAccount(account, "beta-tenant", "Beta", true, "wh-south") + .toByteArray(); + upsertRowWithHexLiteral(conn, table, 1L, "c1-a", alpha); + upsertRowWithHexLiteral(conn, table, 2L, "c1-b", beta); + + assertIndexRowCount(conn, index, 2); + String sql = "SELECT ID, PAYLOAD, PROTO_VALUE(PAYLOAD, 'display_name', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "beta-tenant"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertArrayEquals(beta, rs.getBytes(2)); + assertEquals("Beta", rs.getString(3)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void multiColumnFunctionalIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(multiColumnIndexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')", + "PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "tenant-a", "tenant-a", "tenant-a", "tenant-b", "tenant-b", "tenant-b", + "tenant-c", "tenant-c", "tenant-d", "tenant-d" }; + String[] warehouses = { "wh-north", "wh-south", "wh-east", "wh-north", "wh-south", "wh-west", + "wh-north", "wh-east", "wh-north", "wh-south" }; + for (int i = 0; i < tenants.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-" + tenants[i] + "-" + warehouses[i], AcmeWidgetsFixtures + .newAccount(account, tenants[i], "Name-" + i, true, warehouses[i]).toByteArray()); + } + + assertIndexRowCount(conn, index, tenants.length); + + String pointSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?" + + " AND PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setString(1, "tenant-b"); + ps.setString(2, "wh-north"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-tenant-b-wh-north", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + // Compound-tenant scan + ORDER BY on the secondary indexed column: Phoenix + // does not use the secondary index for ORDER BY on the second key, so this + // path scans the base table. Assert rows and ORDER BY semantics anyway. + String tenantScanSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(tenantScanSql)) { + ps.setString(1, "tenant-a"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 1L, 2L }; + String[] expectedC1 = + { "c1-tenant-a-wh-east", "c1-tenant-a-wh-north", "c1-tenant-a-wh-south" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } + + String warehouseCountSql = "SELECT PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR'), " + + "COUNT(*) FROM " + table + " GROUP BY PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR')" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR') ASC"; + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(warehouseCountSql)) { + String[] expectedWh = { "wh-east", "wh-north", "wh-south", "wh-west" }; + int[] expectedCounts = { 2, 4, 3, 1 }; + for (int i = 0; i < expectedWh.length; i++) { + assertTrue(rs.next()); + assertEquals(expectedWh[i], rs.getString(1)); + assertEquals(expectedCounts[i], rs.getInt(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void topLevelScalarStringIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "tenant-alpha", "tenant-beta", "tenant-charlie", "tenant-delta", + "tenant-echo", "tenant-foxtrot", "tenant-golf", "tenant-hotel" }; + for (int i = 0; i < tenants.length; i++) { + upsertRow(conn, table, (long) (i + 1), "c1-" + tenants[i], AcmeWidgetsFixtures + .newAccount(account, tenants[i], "Name-" + i, i % 2 == 0, "wh-" + i).toByteArray()); + } + + assertIndexRowCount(conn, index, tenants.length); + + String pointSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setString(1, "tenant-echo"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(5L, rs.getLong(1)); + assertEquals("c1-tenant-echo", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeAscSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') >= ?" + + " AND PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') < ?" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeAscSql)) { + ps.setString(1, "tenant-b"); + ps.setString(2, "tenant-g"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L, 6L }; + String[] expectedC1 = { "c1-tenant-beta", "c1-tenant-charlie", "c1-tenant-delta", + "c1-tenant-echo", "c1-tenant-foxtrot" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("expected row " + i, rs.next()); + assertEquals("row " + i + " id", expectedIds[i], rs.getLong(1)); + assertEquals("row " + i + " c1", expectedC1[i], rs.getString(2)); + } + assertFalse("expected exactly 5 rows in range", rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeDescSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') >= ?" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeDescSql)) { + ps.setString(1, "tenant-e"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 8L, 7L, 6L, 5L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + } + + @Test + public void deeplyNestedInt64IndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].6.2', 'BIGINT')")); + + long[] amounts = { 10L, 20L, 30L, 40L, 50L, 60L, 70L }; + for (int i = 0; i < amounts.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-ord-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, amounts[i], 5L, 37.0d, 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, amounts.length); + + String pointSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].6.2', 'BIGINT') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setLong(1, 40L); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-ord-4", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].6.2', 'BIGINT') " + + "BETWEEN ? AND ?" + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].6.2', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 30L); + ps.setLong(2, 60L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 4L, 5L, 6L }; + String[] expectedC1 = { "c1-ord-3", "c1-ord-4", "c1-ord-5", "c1-ord-6" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse("expected exactly 4 rows in [30, 60]", rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void deeplyNestedDoubleIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '2.3.3[0].6.1', 'DOUBLE')")); + + double[] lats = { 34.0522d, 36.1699d, 37.7749d, 40.7128d, 41.8781d, 47.6062d, 51.5074d }; + for (int i = 0; i < lats.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-city-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, lats[i], 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, lats.length); + + String pointSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'2.3.3[0].6.1', 'DOUBLE') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setDouble(1, 40.7128d); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-city-4", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + String rangeDescSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'2.3.3[0].6.1', 'DOUBLE') > ?" + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'2.3.3[0].6.1', 'DOUBLE') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeDescSql)) { + ps.setDouble(1, 40.0d); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 7L, 6L, 5L, 4L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + } + + @Test + public void mapValueBooleanIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '5[0].2.2', 'BOOLEAN')")); + + boolean[] allowReturns = { true, true, true, false, false }; + for (int i = 0; i < allowReturns.length; i++) { + long id = i + 1L; + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", allowReturns[i]); + upsertRow(conn, table, id, "c1-ent-" + id, buildEntitlement(toggles).toByteArray()); + } + upsertRow(conn, table, 6L, "c1-ent-6", + buildEntitlement(new LinkedHashMap()).toByteArray()); + + // Same BOOLEAN false vs NULL partial-index gap as mapValueBooleanIndex. + // Row 6 is an empty map: tag path '5[0].2.2' would also match allow_refunds. + assertIndexRowCount(conn, index, 3); + + String trueSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '5[0].2.2', 'BOOLEAN') = ?" + " ORDER BY ID"; + try (PreparedStatement ps = conn.prepareStatement(trueSql)) { + ps.setBoolean(1, true); + try (ResultSet rs = ps.executeQuery()) { + long[] expected = { 1L, 2L, 3L }; + String[] expectedC1 = { "c1-ent-1", "c1-ent-2", "c1-ent-3" }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expected[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nestedInt32IndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].4', 'INTEGER')")); + + int[] quantities = { 1, 2, 3, 5, 8, 13 }; + for (int i = 0; i < quantities.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-qty-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, 37.0d, quantities[i], "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, quantities.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].4', 'INTEGER') >= ?" + + " AND PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].4', 'INTEGER') <= ?" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].4', 'INTEGER') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setInt(1, 2); + ps.setInt(2, 8); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L }; + String[] expectedC1 = { "c1-qty-2", "c1-qty-3", "c1-qty-4", "c1-qty-5" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void deepRepeatedOfRepeatedInt64IndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement().execute( + indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].8[0].5[0].4.2', " + "'BIGINT')")); + + long[] subAmounts = { 5L, 10L, 15L, 25L, 50L, 100L, 200L }; + for (int i = 0; i < subAmounts.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-sub-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, subAmounts[i], 37.0d, 2, "Sub", "Root").toByteArray()); + } + + assertIndexRowCount(conn, index, subAmounts.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].8[0].5[0].4.2', 'BIGINT') >= ?" + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].8[0].5[0].4.2', 'BIGINT') DESC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 25L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 7L, 6L, 5L, 4L }; + for (long expected : expectedIds) { + assertTrue(rs.next()); + assertEquals(expected, rs.getLong(1)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void veryDeepSelfReferenceIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].3.3.3.2', 'VARCHAR')")); + + String[] categories = + { "Apparel", "Books", "Electronics", "Furniture", "Grocery", "Hardware" }; + for (int i = 0; i < categories.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-cat-" + id, + AcmeWidgetsFixtures.newOrderRichlyPopulatedSeeded(descriptorGraph, "ord-" + id, + "cust-" + id, 100L, 5L, 37.0d, 2, "Sub", categories[i]).toByteArray()); + } + + assertIndexRowCount(conn, index, categories.length); + + String rangeSql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].3.3.3.2', 'VARCHAR') >= ?" + " AND PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].3.3.3.2', 'VARCHAR') < ?" + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].3.3.3.2', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setString(1, "B"); + ps.setString(2, "G"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L }; + String[] expectedC1 = { "c1-cat-2", "c1-cat-3", "c1-cat-4" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nestedMessageLeafAsVarbinaryEncodedIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ORDER + ">)" + + encodingClause()); + + // VARBINARY_ENCODED (not raw VARBINARY): Phoenix disallows raw VARBINARY as + // the leading segment of a multi-part row key. + conn.createStatement().execute( + indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '3[0].6', 'VARBINARY_ENCODED')")); + + upsertRow(conn, table, 1L, "c1-order-1", AcmeWidgetsFixtures + .newOrderRichlyPopulated(descriptorGraph, "ord-1", "cust-1").toByteArray()); + + assertIndexRowCount(conn, index, 1); + String sql = "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, " + + "'3[0].6', 'VARBINARY_ENCODED') IS NOT NULL"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals("c1-order-1", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void uint64AsBigIntIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '2.1', 'BIGINT')")); + + Map toggles = new LinkedHashMap<>(); + toggles.put("allow_returns", true); + long[] versions = { 100L, 150L, 200L, 300L, 500L, 800L }; + for (int i = 0; i < versions.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-ent-" + id, + AcmeWidgetsFixtures + .newEntitlement(AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph), + AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph), "tenant-" + id, + "ent-name", "ent-id", versions[i], toggles) + .toByteArray()); + } + + assertIndexRowCount(conn, index, versions.length); + + String rangeSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '2.1', 'BIGINT') > ?" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '2.1', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 200L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 4L, 5L, 6L }; + String[] expectedC1 = { "c1-ent-4", "c1-ent-5", "c1-ent-6" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nonPartialIndexIncludesAllRowsAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(nonPartialIndexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + upsertRow(conn, table, 1L, "c1-a", + AcmeWidgetsFixtures.newAccount(account, "tenant-a", "A", true, "wh").toByteArray()); + upsertRow(conn, table, 2L, "c1-b", + AcmeWidgetsFixtures.newAccount(account, "tenant-b", "B", true, "wh").toByteArray()); + + upsertRow(conn, table, 3L, "c1-c", DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("display_name"), "C").build().toByteArray()); + + assertIndexRowCount(conn, index, 3); + assertIndexRows(conn, index, + new Object[][] { { null, 3L }, { "tenant-a", 1L }, { "tenant-b", 2L } }); + assertNullLookup(conn, table, index, "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR')", 3L); + String sql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "tenant-b"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("c1-b", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void nonPartialIndexOnNestedLeafWithMissingParentAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + // key = 1, key.tenant_key = 2 + String expr = "PROTO_VALUE_AT_TAG(PAYLOAD, '1.2', 'VARCHAR')"; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" + + encodingClause()); + conn.createStatement().execute(nonPartialIndexDdl(index, table, expr)); + upsertEntitlementsWithAndWithoutKey(conn, table); + + assertIndexRows(conn, index, + new Object[][] { { null, 2L }, { null, 3L }, { "tenant-idx", 1L } }); + assertNullLookup(conn, table, index, expr, 2L, 3L); + try (PreparedStatement ps = + conn.prepareStatement("SELECT ID FROM " + table + " WHERE " + expr + " = ?")) { + ps.setString(1, "tenant-idx"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void coveredIndexIncludingProtobufColumnReturnsPayloadFromIndexAtTag() throws Exception { + Assume.assumeTrue("INCLUDE(PAYLOAD) only applies to covered indexes", this.coveredIndex); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute("CREATE INDEX " + index + " ON " + table + + "(PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR')) INCLUDE(PAYLOAD) WHERE " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') IS NOT NULL" + indexDDLOptions); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + byte[] alpha = AcmeWidgetsFixtures + .newAccount(account, "alpha-tenant", "Alpha", true, "wh-north").toByteArray(); + byte[] beta = AcmeWidgetsFixtures.newAccount(account, "beta-tenant", "Beta", true, "wh-south") + .toByteArray(); + upsertRow(conn, table, 1L, "c1-a", alpha); + upsertRow(conn, table, 2L, "c1-b", beta); + + assertIndexRowCount(conn, index, 2); + String sql = "SELECT ID, PAYLOAD FROM " + table + + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, "beta-tenant"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertArrayEquals(beta, rs.getBytes(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + } + } + + @Test + public void multiColumnFunctionalIndexAtTag() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerBundleIdempotent(conn); + String table = uniqueTableName(); + String index = "IDX_" + table; + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + conn.createStatement() + .execute(multiColumnIndexDdl(index, table, "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR')", + "PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR')")); + + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + String[] tenants = { "tenant-a", "tenant-a", "tenant-a", "tenant-b", "tenant-b", "tenant-b", + "tenant-c", "tenant-c", "tenant-d", "tenant-d" }; + String[] warehouses = { "wh-north", "wh-south", "wh-east", "wh-north", "wh-south", "wh-west", + "wh-north", "wh-east", "wh-north", "wh-south" }; + for (int i = 0; i < tenants.length; i++) { + long id = i + 1L; + upsertRow(conn, table, id, "c1-" + tenants[i] + "-" + warehouses[i], AcmeWidgetsFixtures + .newAccount(account, tenants[i], "Name-" + i, true, warehouses[i]).toByteArray()); + } + + assertIndexRowCount(conn, index, tenants.length); + + String pointSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') = ?" + + " AND PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setString(1, "tenant-b"); + ps.setString(2, "wh-north"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("c1-tenant-b-wh-north", rs.getString(2)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index, "RANGE SCAN"); + } + + // Compound-tenant scan + ORDER BY on the secondary indexed column: Phoenix + // does not use the secondary index for ORDER BY on the second key, so this + // path scans the base table. Assert rows and ORDER BY semantics anyway. + String tenantScanSql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'VARCHAR') = ?" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR') ASC"; + try (PreparedStatement ps = conn.prepareStatement(tenantScanSql)) { + ps.setString(1, "tenant-a"); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 1L, 2L }; + String[] expectedC1 = + { "c1-tenant-a-wh-east", "c1-tenant-a-wh-north", "c1-tenant-a-wh-south" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedC1[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } + + String warehouseCountSql = "SELECT PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR'), " + + "COUNT(*) FROM " + table + " GROUP BY PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR')" + + " ORDER BY PROTO_VALUE_AT_TAG(PAYLOAD, '9', 'VARCHAR') ASC"; + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(warehouseCountSql)) { + String[] expectedWh = { "wh-east", "wh-north", "wh-south", "wh-west" }; + int[] expectedCounts = { 2, 4, 3, 1 }; + for (int i = 0; i < expectedWh.length; i++) { + assertTrue(rs.next()); + assertEquals(expectedWh[i], rs.getString(1)); + assertEquals(expectedCounts[i], rs.getInt(2)); + } + assertFalse(rs.next()); + } + } + } + + private Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private String uniqueTableName() { + String name = generateUniqueName(); + createdTables.add(name); + return name; + } + + private String indexDdl(String indexName, String tableName, String indexedExpr) { + if (this.coveredIndex) { + return "CREATE INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") INCLUDE(C1) WHERE " + indexedExpr + " IS NOT NULL" + indexDDLOptions; + } + return "CREATE UNCOVERED INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") WHERE " + indexedExpr + " IS NOT NULL" + indexDDLOptions; + } + + private String nonPartialIndexDdl(String indexName, String tableName, String indexedExpr) { + if (this.coveredIndex) { + return "CREATE INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + ") INCLUDE(C1)" + + indexDDLOptions; + } + return "CREATE UNCOVERED INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + ")" + + indexDDLOptions; + } + + private String multiColumnIndexDdl(String indexName, String tableName, String firstExpr, + String secondExpr) { + if (this.coveredIndex) { + return "CREATE INDEX " + indexName + " ON " + tableName + "(" + firstExpr + ", " + secondExpr + + ") INCLUDE(C1) WHERE " + firstExpr + " IS NOT NULL AND " + secondExpr + " IS NOT NULL" + + indexDDLOptions; + } + return "CREATE UNCOVERED INDEX " + indexName + " ON " + tableName + "(" + firstExpr + ", " + + secondExpr + ") WHERE " + firstExpr + " IS NOT NULL AND " + secondExpr + " IS NOT NULL" + + indexDDLOptions; + } + + private void registerBundleIdempotent(Connection conn) throws SQLException { + StringBuilder ddl = new StringBuilder("CREATE PROTOBUF BUNDLE IF NOT EXISTS ("); + for (int i = 0; i < BUNDLE_NAMES.size(); i++) { + if (i > 0) { + ddl.append(", "); + } + ddl.append(BUNDLE_NAMES.get(i)); + } + ddl.append(") FROM '").append(AcmeWidgetsFixtures.bundleFileUrl()).append("'"); + conn.createStatement().execute(ddl.toString()); + } + + private DynamicMessage buildEntitlement(Map toggles) { + return AcmeWidgetsFixtures.newEntitlement( + AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph), + AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph), + AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph), "tenant-idx", + "unlimited-widgets", "ent-xyz", 1L, toggles); + } + + private void upsertEntitlementsWithAndWithoutKey(Connection conn, String table) + throws SQLException { + Descriptor entitlement = AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph); + Descriptor entitlementKey = AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph); + upsertRow(conn, table, 1L, "c1-1", buildEntitlement(Collections.emptyMap()).toByteArray()); + DynamicMessage keyWithoutTenant = DynamicMessage.newBuilder(entitlementKey) + .setField(entitlementKey.findFieldByName("entitlement_name"), "no-tenant").build(); + upsertRow(conn, table, 2L, "c1-2", DynamicMessage.newBuilder(entitlement) + .setField(entitlement.findFieldByName("key"), keyWithoutTenant).build().toByteArray()); + upsertRow(conn, table, 3L, "c1-3", DynamicMessage.newBuilder(entitlement) + .setField(entitlement.findFieldByName("source_warehouse"), "wh-1").build().toByteArray()); + } + + private static void upsertRow(Connection conn, String table, long id, String c1, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, C1, PAYLOAD) VALUES (?, ?, ?)")) { + ps.setLong(1, id); + ps.setString(2, c1); + ps.setBytes(3, payload); + ps.execute(); + } + conn.commit(); + } + + private static void upsertRowWithHexLiteral(Connection conn, String table, long id, String c1, + byte[] payload) throws SQLException { + conn.createStatement().execute("UPSERT INTO " + table + " (ID, C1, PAYLOAD) VALUES (" + id + + ", '" + c1 + "', X'" + Bytes.toHex(payload) + "')"); + conn.commit(); + } + + private static void assertPayloadBytes(Connection conn, String table, long id, byte[] expected) + throws SQLException { + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT PAYLOAD FROM " + table + " WHERE ID = " + id)) { + assertTrue(rs.next()); + assertArrayEquals(expected, rs.getBytes(1)); + assertFalse(rs.next()); + } + } + + private void assertTenantLookup(Connection conn, String table, String indexName, String tenantKey, + Long expectedId, String expectedC1) throws Exception { + waitForEventualConsistency(); + String sql = + "SELECT ID, C1 FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, tenantKey); + try (ResultSet rs = ps.executeQuery()) { + if (expectedId != null) { + assertTrue(rs.next()); + assertEquals(expectedId.longValue(), rs.getLong(1)); + assertEquals(expectedC1, rs.getString(2)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, indexName, "RANGE SCAN"); + } + } + + private void assertIndexRowCount(Connection conn, String indexName, int expected) + throws Exception { + waitForEventualConsistency(); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM " + indexName)) { + assertTrue(rs.next()); + assertEquals(expected, rs.getInt(1)); + } + } + + private void assertIndexRows(Connection conn, String indexName, Object[][] expected) + throws Exception { + waitForEventualConsistency(); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + indexName)) { + ResultSetMetaData md = rs.getMetaData(); + int valueCol = -1; + int idCol = -1; + for (int c = 1; c <= md.getColumnCount(); c++) { + String label = md.getColumnLabel(c); + if (label.contains("PROTO_VALUE")) { + valueCol = c; + } else if (label.equals(":ID")) { + idCol = c; + } + } + assertTrue("index value and ID columns not found", valueCol > 0 && idCol > 0); + for (int i = 0; i < expected.length; i++) { + assertTrue("missing index row " + i, rs.next()); + assertEquals("index row " + i + " value", expected[i][0], rs.getString(valueCol)); + assertEquals("index row " + i + " id", expected[i][1], rs.getLong(idCol)); + } + assertFalse(rs.next()); + } + } + + private void assertNullLookup(Connection conn, String table, String indexName, String indexedExpr, + long... expectedIds) throws Exception { + waitForEventualConsistency(); + try (PreparedStatement ps = + conn.prepareStatement("SELECT ID FROM " + table + " WHERE " + indexedExpr + " IS NULL")) { + try (ResultSet rs = ps.executeQuery()) { + for (long id : expectedIds) { + assertTrue(rs.next()); + assertEquals(id, rs.getLong(1)); + } + assertFalse(rs.next()); + } + validateExplainPlan(ps, indexName, "RANGE SCAN"); + } + } + + private static List queryRows(Connection conn, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + while (rs.next()) { + rows.add(rs.getLong(1) + ":" + rs.getString(2)); + } + } + return rows; + } + + private static void validateExplainPlan(PreparedStatement ps, String indexName, String scanType) + throws SQLException { + ExplainPlan plan = ps.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan(); + ExplainPlanAttributes attrs = plan.getPlanStepsAsAttributes(); + assertEquals(indexName, attrs.getTableName()); + assertEquals("PARALLEL 1-WAY", attrs.getIteratorTypeAndScanSize()); + assertEquals(scanType, attrs.getExplainScanType()); + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValuePackedRepeatedIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValuePackedRepeatedIT.java new file mode 100644 index 00000000000..124e7ee13c0 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValuePackedRepeatedIT.java @@ -0,0 +1,593 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import org.apache.phoenix.compile.ExplainPlan; +import org.apache.phoenix.compile.ExplainPlanAttributes; +import org.apache.phoenix.jdbc.PhoenixPreparedStatement; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(NeedsOwnMiniClusterTest.class) +@RunWith(Parameterized.class) +public class ProtoValuePackedRepeatedIT extends ParallelStatsDisabledIT { + private static final String DESCRIPTOR_PACKAGE = "phoenix.it.packed"; + private static final String DESCRIPTOR_NAME = DESCRIPTOR_PACKAGE + ".Container"; + + private static Path descriptorPath; + private static Descriptors.Descriptor containerDescriptor; + private static Descriptors.EnumDescriptor colorEnum; + + private final boolean columnEncoded; + private final boolean coveredIndex; + private final List createdTables = new ArrayList<>(); + + public ProtoValuePackedRepeatedIT(boolean columnEncoded, boolean coveredIndex) { + this.columnEncoded = columnEncoded; + this.coveredIndex = coveredIndex; + } + + @Parameterized.Parameters(name = "columnEncoded={0}, coveredIndex={1}") + public static synchronized Collection data() { + return Arrays.asList( + new Object[][] { { false, false }, { false, true }, { true, false }, { true, true } }); + } + + @BeforeClass + public static synchronized void buildDescriptor() throws Exception { + EnumDescriptorProto colorEnumProto = EnumDescriptorProto.newBuilder().setName("Color") + .addValue(EnumValueDescriptorProto.newBuilder().setName("UNSPECIFIED").setNumber(0)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("RED").setNumber(1)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("GREEN").setNumber(2)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("BLUE").setNumber(3)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("MAGENTA").setNumber(4)).build(); + DescriptorProto containerProto = + DescriptorProto.newBuilder().setName("Container").addEnumType(colorEnumProto) + .addField(FieldDescriptorProto.newBuilder().setName("nums").setNumber(1) + .setType(Type.TYPE_INT64).setLabel(Label.LABEL_REPEATED).build()) + .addField(FieldDescriptorProto.newBuilder().setName("counts").setNumber(2) + .setType(Type.TYPE_INT32).setLabel(Label.LABEL_REPEATED).build()) + .addField(FieldDescriptorProto.newBuilder().setName("flags").setNumber(3) + .setType(Type.TYPE_BOOL).setLabel(Label.LABEL_REPEATED).build()) + .addField(FieldDescriptorProto.newBuilder().setName("weights").setNumber(4) + .setType(Type.TYPE_FLOAT).setLabel(Label.LABEL_REPEATED).build()) + .addField(FieldDescriptorProto.newBuilder().setName("ratios").setNumber(5) + .setType(Type.TYPE_DOUBLE).setLabel(Label.LABEL_REPEATED).build()) + .addField(FieldDescriptorProto.newBuilder().setName("palette").setNumber(6) + .setType(Type.TYPE_ENUM).setTypeName("Color").setLabel(Label.LABEL_REPEATED).build()) + .build(); + FileDescriptorProto fileProto = + FileDescriptorProto.newBuilder().setName("phoenix_it_packed.proto") + .setPackage(DESCRIPTOR_PACKAGE).setSyntax("proto3").addMessageType(containerProto).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(fileProto).build(); + + descriptorPath = Files.createTempFile("proto-packed-it-", ".desc"); + Files.write(descriptorPath, set.toByteArray()); + + Descriptors.FileDescriptor file = + Descriptors.FileDescriptor.buildFrom(fileProto, new Descriptors.FileDescriptor[0]); + containerDescriptor = file.findMessageTypeByName("Container"); + colorEnum = containerDescriptor.findEnumTypeByName("Color"); + } + + @AfterClass + public static synchronized void deleteDescriptorFile() throws Exception { + if (descriptorPath != null) { + Files.deleteIfExists(descriptorPath); + } + } + + @After + public void cleanupTablesAndDescriptor() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + DESCRIPTOR_NAME); + } catch (SQLException ignore) { + } + } + createdTables.clear(); + } + + @Test + public void packedRepeatedInt64ReadsAllElements() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[][] rows = + { { 100L, 200L, 300L }, { 500L, 600L, 700L, 800L }, { 999L, 1000L, 1001L, 1002L, 1003L }, + { 42L }, { -1L, -2L, -3L }, { Long.MAX_VALUE, Long.MIN_VALUE }, { 0L, 0L, 0L } }; + for (int i = 0; i < rows.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt64Nums(rows[i])); + } + String pointSql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'nums[0]', 'BIGINT'), " + + "PROTO_VALUE(PAYLOAD, 'nums[2]', 'BIGINT'), " + + "PROTO_VALUE(PAYLOAD, 'nums[4]', 'BIGINT') " + "FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(pointSql); + ResultSet rs = ps.executeQuery()) { + Long[] expectedIdx0 = { 100L, 500L, 999L, 42L, -1L, Long.MAX_VALUE, 0L }; + Long[] expectedIdx2 = { 300L, 700L, 1001L, null, -3L, null, 0L }; + Long[] expectedIdx4 = { null, null, 1003L, null, null, null, null }; + for (int i = 0; i < expectedIdx0.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " nums[0]", (long) expectedIdx0[i], rs.getLong(2)); + if (expectedIdx2[i] == null) { + assertEquals(0L, rs.getLong(3)); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " nums[2]", (long) expectedIdx2[i], rs.getLong(3)); + } + if (expectedIdx4[i] == null) { + assertEquals(0L, rs.getLong(4)); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " nums[4]", (long) expectedIdx4[i], rs.getLong(4)); + } + } + assertFalse("expected exactly 7 rows", rs.next()); + } + } + } + + @Test + public void packedRepeatedInt32InRangeFilterOrdersCorrectly() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[][] rows = { { 5, 10 }, { 20, 25, 30 }, { 15 }, { 40, 45 }, { 55, 60, 65, 70 }, + { 75, 80 }, { 100, 200 } }; + for (int i = 0; i < rows.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt32Counts(rows[i])); + } + String rangeSql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'counts[0]', 'INTEGER') " + "FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'counts[0]', 'INTEGER') BETWEEN ? AND ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'counts[0]', 'INTEGER') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setInt(1, 15); + ps.setInt(2, 75); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 2L, 4L, 5L, 6L }; + int[] expectedCount0 = { 15, 20, 40, 55, 75 }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedCount0[i], rs.getInt(2)); + } + assertFalse("expected exactly 5 rows in [15, 75]", rs.next()); + } + } + } + } + + @Test + public void packedRepeatedBoolElementReadsBackCorrectly() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + boolean[][] rows = { { true, false, true }, { false, false }, { true }, + { true, true, true, true }, { false, true, false, true, false } }; + for (int i = 0; i < rows.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithBoolFlags(rows[i])); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'flags[0]', 'BOOLEAN'), " + + "PROTO_VALUE(PAYLOAD, 'flags[1]', 'BOOLEAN') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + boolean[] expected0 = { true, false, true, true, false }; + Boolean[] expected1 = { false, false, null, true, true }; + for (int i = 0; i < expected0.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " flags[0]", expected0[i], rs.getBoolean(2)); + if (expected1[i] == null) { + assertFalse(rs.getBoolean(3)); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " flags[1]", expected1[i], rs.getBoolean(3)); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void packedRepeatedFloatAndDoubleReadCorrectly() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + float[][] weights = { { 1.5f, 2.5f }, { 3.14f, 6.28f, 9.42f }, { 0.001f }, + { 100.0f, 200.0f, 300.0f, 400.0f }, { -1.5f, 2.5f } }; + double[][] ratios = { { 0.1d, 0.2d }, { 1.5d, 2.5d, 3.5d, 4.5d }, { 99.99d }, + { -50.0d, 50.0d }, { 1.0d, 2.0d, 3.0d } }; + for (int i = 0; i < weights.length; i++) { + upsertContainer(conn, table, i + 1L, + buildContainerWithFloatWeightsAndDoubleRatios(weights[i], ratios[i])); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'weights[0]', 'FLOAT'), " + + "PROTO_VALUE(PAYLOAD, 'weights[2]', 'FLOAT'), " + + "PROTO_VALUE(PAYLOAD, 'ratios[0]', 'DOUBLE'), " + + "PROTO_VALUE(PAYLOAD, 'ratios[3]', 'DOUBLE') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + float[] w0 = { 1.5f, 3.14f, 0.001f, 100.0f, -1.5f }; + Float[] w2 = { null, 9.42f, null, 300.0f, null }; + double[] r0 = { 0.1d, 1.5d, 99.99d, -50.0d, 1.0d }; + Double[] r3 = { null, 4.5d, null, null, null }; + for (int i = 0; i < w0.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " weights[0]", w0[i], rs.getFloat(2), 1e-6f); + if (w2[i] == null) { + rs.getFloat(3); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " weights[2]", w2[i], rs.getFloat(3), 1e-6f); + } + assertEquals("row " + i + " ratios[0]", r0[i], rs.getDouble(4), 1e-9d); + if (r3[i] == null) { + rs.getDouble(5); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " ratios[3]", r3[i], rs.getDouble(5), 1e-9d); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void packedRepeatedEnumElementReadsAsInteger() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String[][] palettes = { { "RED", "GREEN", "BLUE" }, { "MAGENTA" }, { "UNSPECIFIED", "RED" }, + { "BLUE", "BLUE", "GREEN" }, { "GREEN", "MAGENTA", "RED", "BLUE" } }; + int[] expectedIdx0 = { 1, 4, 0, 3, 2 }; + int[] expectedIdx2 = { 3, -1, -1, 2, 1 }; + for (int i = 0; i < palettes.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithEnumPalette(palettes[i])); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'palette[0]', 'INTEGER'), " + + "PROTO_VALUE(PAYLOAD, 'palette[2]', 'INTEGER') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < palettes.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " palette[0]", expectedIdx0[i], rs.getInt(2)); + if (expectedIdx2[i] < 0) { + rs.getInt(3); + assertTrue(rs.wasNull()); + } else { + assertEquals("row " + i + " palette[2]", expectedIdx2[i], rs.getInt(3)); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void packedRepeatedWithDefaultForOutOfBoundsIndex() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[][] rowNums = { { 100L }, { 200L, 201L }, { 300L, 301L, 302L, 303L }, { 400L, 401L }, + { 500L, 501L, 502L, 503L, 504L }, { 600L }, { 700L, 701L, 702L, 703L } }; + for (int i = 0; i < rowNums.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt64Nums(rowNums[i])); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'nums[3]', 'BIGINT', '9999999') " + "FROM " + + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + long[] expectedNums3 = { 9999999L, 9999999L, 303L, 9999999L, 503L, 9999999L, 703L }; + for (int i = 0; i < expectedNums3.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expectedNums3[i], rs.getLong(2)); + assertFalse("row " + i, rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void packedRepeatedFloatWithLiteralNullDefaultReturnsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + float[][] weights = + { { 1.0f }, { 2.0f, 3.0f }, { 4.0f }, { 5.0f, 6.0f, 7.0f }, { 8.0f, 9.0f } }; + double[][] emptyRatios = { {}, {}, {}, {}, {} }; + for (int i = 0; i < weights.length; i++) { + upsertContainer(conn, table, i + 1L, + buildContainerWithFloatWeightsAndDoubleRatios(weights[i], emptyRatios[i])); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'weights[10]', 'FLOAT', 'NuLl') " + "FROM " + + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (long id = 1L; id <= 5L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + rs.getFloat(2); + assertTrue("row " + id, rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void packedRepeatedInt64IndexServesRangeQueries() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String index = "IDX_" + table; + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'nums[0]', 'BIGINT')")); + long[][] rows = { { 10L, 100L }, { 20L, 200L, 300L }, { 30L, 400L }, { 40L, 500L, 600L }, + { 50L, 700L }, { 60L, 800L, 900L }, { 70L, 1000L } }; + for (int i = 0; i < rows.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt64Nums(rows[i])); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + index)) { + assertTrue(rs.next()); + assertEquals(rows.length, rs.getInt(1)); + } + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'nums[0]', 'BIGINT') BETWEEN ? AND ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'nums[0]', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 20L); + ps.setLong(2, 60L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L, 6L }; + for (long expectedId : expectedIds) { + assertTrue(rs.next()); + assertEquals(expectedId, rs.getLong(1)); + } + assertFalse("expected exactly 5 rows in [20, 60]", rs.next()); + } + validateExplainPlan(ps, index); + } + } + } + + @Test + public void packedRepeatedDoubleIndexServesRangeQueries() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String index = "IDX_" + table; + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'ratios[0]', 'DOUBLE')")); + double[][] ratiosPerRow = { { 0.1d, 9.9d }, { 0.5d }, { 1.5d, 2.5d, 3.5d }, { 2.5d, 5.0d }, + { 5.5d }, { 7.5d, 8.0d }, { 9.9d } }; + for (int i = 0; i < ratiosPerRow.length; i++) { + upsertContainer(conn, table, i + 1L, + buildContainerWithFloatWeightsAndDoubleRatios(new float[0], ratiosPerRow[i])); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + index)) { + assertTrue(rs.next()); + assertEquals(ratiosPerRow.length, rs.getInt(1)); + } + String rangeSql = "SELECT ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'ratios[0]', 'DOUBLE') BETWEEN ? AND ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'ratios[0]', 'DOUBLE') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setDouble(1, 1.5d); + ps.setDouble(2, 7.5d); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 3L, 4L, 5L, 6L }; + for (long expectedId : expectedIds) { + assertTrue(rs.next()); + assertEquals(expectedId, rs.getLong(1)); + } + assertFalse("expected exactly 4 rows in [1.5, 7.5]", rs.next()); + } + validateExplainPlan(ps, index); + } + } + } + + @Test + public void protoArrayLengthCountsPackedRepeatedInt64Elements() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[][] numsPerRow = + { {}, { 42L }, { 1L, 2L, 3L }, { 10L, 20L }, { 5L }, { 100L, 200L, 300L, 400L } }; + for (int i = 0; i < numsPerRow.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt64Nums(numsPerRow[i])); + } + String sql = + "SELECT ID, PROTO_ARRAY_LENGTH(PAYLOAD, 'nums') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + int[] expected = { 0, 1, 3, 2, 1, 4 }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getInt(2)); + } + assertFalse(rs.next()); + } + } + } + + private String createRegisteredTable(Connection conn) throws SQLException { + String descUrl = "file://" + descriptorPath.toAbsolutePath(); + conn.createStatement().execute( + "CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + DESCRIPTOR_NAME + " FROM '" + descUrl + "'"); + String table = generateUniqueName(); + createdTables.add(table); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + + DESCRIPTOR_NAME + ">)" + encodingClause()); + return table; + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private String indexDdl(String indexName, String tableName, String indexedExpr) { + if (this.coveredIndex) { + return "CREATE INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") INCLUDE(C1) WHERE " + indexedExpr + " IS NOT NULL"; + } + return "CREATE UNCOVERED INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") WHERE " + indexedExpr + " IS NOT NULL"; + } + + private static void upsertContainer(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, C1, PAYLOAD) VALUES (?, ?, ?)")) { + ps.setLong(1, id); + ps.setString(2, "c1-" + id); + ps.setBytes(3, payload); + ps.executeUpdate(); + } + conn.commit(); + } + + private static byte[] buildContainerWithInt64Nums(long[] nums) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(containerDescriptor); + Descriptors.FieldDescriptor field = containerDescriptor.findFieldByName("nums"); + for (long n : nums) { + builder.addRepeatedField(field, n); + } + return builder.build().toByteArray(); + } + + private static byte[] buildContainerWithInt32Counts(int[] counts) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(containerDescriptor); + Descriptors.FieldDescriptor field = containerDescriptor.findFieldByName("counts"); + for (int c : counts) { + builder.addRepeatedField(field, c); + } + return builder.build().toByteArray(); + } + + private static byte[] buildContainerWithBoolFlags(boolean[] flags) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(containerDescriptor); + Descriptors.FieldDescriptor field = containerDescriptor.findFieldByName("flags"); + for (boolean f : flags) { + builder.addRepeatedField(field, f); + } + return builder.build().toByteArray(); + } + + private static byte[] buildContainerWithFloatWeightsAndDoubleRatios(float[] weights, + double[] ratios) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(containerDescriptor); + Descriptors.FieldDescriptor wField = containerDescriptor.findFieldByName("weights"); + Descriptors.FieldDescriptor rField = containerDescriptor.findFieldByName("ratios"); + for (float w : weights) { + builder.addRepeatedField(wField, w); + } + for (double r : ratios) { + builder.addRepeatedField(rField, r); + } + return builder.build().toByteArray(); + } + + private static byte[] buildContainerWithEnumPalette(String[] symbols) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(containerDescriptor); + Descriptors.FieldDescriptor field = containerDescriptor.findFieldByName("palette"); + for (String symbol : symbols) { + builder.addRepeatedField(field, colorEnum.findValueByName(symbol)); + } + return builder.build().toByteArray(); + } + + @Test + public void protoValueAtTagPackedRepeatedInt64ThirdElement() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[][] numsPerRow = + { {}, { 42L }, { 1L, 2L, 3L }, { 10L, 20L }, { 5L }, { 100L, 200L, 300L, 400L } }; + for (int i = 0; i < numsPerRow.length; i++) { + upsertContainer(conn, table, i + 1L, buildContainerWithInt64Nums(numsPerRow[i])); + } + String sql = "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '1[2]', 'BIGINT') FROM " + table + + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + Long[] expected = { null, null, 3L, null, null, 300L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + (i + 1), rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + if (expected[i] == null) { + rs.getLong(2); + assertTrue("row " + (i + 1) + " should be NULL", rs.wasNull()); + } else { + assertEquals("row " + (i + 1), (long) expected[i], rs.getLong(2)); + } + } + assertFalse(rs.next()); + } + } + } + + private static Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private static void validateExplainPlan(PreparedStatement ps, String indexName) + throws SQLException { + ExplainPlan plan = ps.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan(); + ExplainPlanAttributes attrs = plan.getPlanStepsAsAttributes(); + assertEquals(indexName, attrs.getTableName()); + assertEquals("PARALLEL 1-WAY", attrs.getIteratorTypeAndScanSize()); + assertEquals("RANGE SCAN", attrs.getExplainScanType()); + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java new file mode 100644 index 00000000000..3149d4efba1 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java @@ -0,0 +1,1503 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigDecimal; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import org.apache.phoenix.compile.ExplainPlan; +import org.apache.phoenix.compile.ExplainPlanAttributes; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.jdbc.PhoenixPreparedStatement; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import org.apache.phoenix.thirdparty.com.google.protobuf.ByteString; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.MessageOptions; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.OneofDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(NeedsOwnMiniClusterTest.class) +@RunWith(Parameterized.class) +public class ProtoValueTypeCoverageIT extends ParallelStatsDisabledIT { + private static final String DESCRIPTOR_PACKAGE = "phoenix.it.coverage"; + private static final String DESCRIPTOR_NAME = DESCRIPTOR_PACKAGE + ".AllTypes"; + + private static Path descriptorPath; + private static Descriptors.Descriptor allTypesDescriptor; + + private final boolean columnEncoded; + private final boolean coveredIndex; + private final List createdTables = new ArrayList<>(); + + public ProtoValueTypeCoverageIT(boolean columnEncoded, boolean coveredIndex) { + this.columnEncoded = columnEncoded; + this.coveredIndex = coveredIndex; + } + + @Parameterized.Parameters(name = "columnEncoded={0}, coveredIndex={1}") + public static synchronized Collection data() { + return Arrays.asList( + new Object[][] { { false, false }, { false, true }, { true, false }, { true, true } }); + } + + @BeforeClass + public static synchronized void buildDescriptor() throws Exception { + DescriptorProto strIntMapEntry = + mapEntryProto("StrIntMapEntry", Type.TYPE_STRING, Type.TYPE_INT64); + DescriptorProto int32ToStringEntry = + mapEntryProto("Int32ToStringEntry", Type.TYPE_INT32, Type.TYPE_STRING); + DescriptorProto int64ToStringEntry = + mapEntryProto("Int64ToStringEntry", Type.TYPE_INT64, Type.TYPE_STRING); + DescriptorProto strFloatMapEntry = + mapEntryProto("StrFloatMapEntry", Type.TYPE_STRING, Type.TYPE_FLOAT); + DescriptorProto strDoubleMapEntry = + mapEntryProto("StrDoubleMapEntry", Type.TYPE_STRING, Type.TYPE_DOUBLE); + DescriptorProto childProto = DescriptorProto.newBuilder().setName("Child") + .addField(FieldDescriptorProto.newBuilder().setName("payload_string").setNumber(1) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("filler").setNumber(2) + .setType(Type.TYPE_INT32).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("bool_flag").setNumber(3) + .setType(Type.TYPE_BOOL).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("float_val").setNumber(4) + .setType(Type.TYPE_FLOAT).setLabel(Label.LABEL_OPTIONAL).build()) + .build(); + DescriptorProto allTypesProto = + DescriptorProto.newBuilder().setName("AllTypes").addNestedType(strIntMapEntry) + .addNestedType(int32ToStringEntry).addNestedType(int64ToStringEntry) + .addNestedType(strFloatMapEntry).addNestedType(strDoubleMapEntry).addNestedType(childProto) + .addField(FieldDescriptorProto.newBuilder().setName("fixed32_field").setNumber(1) + .setType(Type.TYPE_FIXED32).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("fixed64_field").setNumber(2) + .setType(Type.TYPE_FIXED64).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("sfixed32_field").setNumber(3) + .setType(Type.TYPE_SFIXED32).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("sfixed64_field").setNumber(4) + .setType(Type.TYPE_SFIXED64).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("uint32_field").setNumber(5) + .setType(Type.TYPE_UINT32).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("bytes_field").setNumber(6) + .setType(Type.TYPE_BYTES).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("int64_field").setNumber(7) + .setType(Type.TYPE_INT64).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("child_msg").setNumber(8) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_OPTIONAL).setTypeName("Child").build()) + .addField(FieldDescriptorProto.newBuilder().setName("str_int_map").setNumber(10) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_REPEATED).setTypeName("StrIntMapEntry") + .build()) + .addField(FieldDescriptorProto.newBuilder().setName("int32_map").setNumber(11) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_REPEATED) + .setTypeName("Int32ToStringEntry").build()) + .addField(FieldDescriptorProto.newBuilder().setName("int64_map").setNumber(12) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_REPEATED) + .setTypeName("Int64ToStringEntry").build()) + .addField(FieldDescriptorProto.newBuilder().setName("str_float_map").setNumber(13) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_REPEATED).setTypeName("StrFloatMapEntry") + .build()) + .addField(FieldDescriptorProto.newBuilder().setName("str_double_map").setNumber(14) + .setType(Type.TYPE_MESSAGE).setLabel(Label.LABEL_REPEATED) + .setTypeName("StrDoubleMapEntry").build()) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("choice")) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("_opt_int32")) + .addField(FieldDescriptorProto.newBuilder().setName("opt_int32").setNumber(15) + .setType(Type.TYPE_INT32).setLabel(Label.LABEL_OPTIONAL).setProto3Optional(true) + .setOneofIndex(1).build()) + .addField(FieldDescriptorProto.newBuilder().setName("choice_int").setNumber(16) + .setType(Type.TYPE_INT32).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .build(); + FileDescriptorProto fileProto = + FileDescriptorProto.newBuilder().setName("phoenix_it_coverage.proto") + .setPackage(DESCRIPTOR_PACKAGE).setSyntax("proto3").addMessageType(allTypesProto).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(fileProto).build(); + + descriptorPath = Files.createTempFile("proto-coverage-it-", ".desc"); + Files.write(descriptorPath, set.toByteArray()); + Descriptors.FileDescriptor file = + Descriptors.FileDescriptor.buildFrom(fileProto, new Descriptors.FileDescriptor[0]); + allTypesDescriptor = file.findMessageTypeByName("AllTypes"); + } + + @AfterClass + public static synchronized void deleteDescriptorFile() throws Exception { + if (descriptorPath != null) { + Files.deleteIfExists(descriptorPath); + } + } + + @After + public void cleanupTablesAndDescriptor() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + DESCRIPTOR_NAME); + } catch (SQLException ignore) { + } + } + createdTables.clear(); + } + + @Test + public void singularFixed32AndFixed64UnsignedLeavesReadBackUnsigned() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[] fixed32s = { 0, 1, 100, 1_000_000, Integer.MAX_VALUE, -1, -2 }; + long[] fixed64s = { 0L, 1L, 1_000_000_000_000L, Long.MAX_VALUE, -1L, -2L, -3L }; + for (int i = 0; i < fixed32s.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("fixed32_field"), fixed32s[i]) + .setField(allTypesDescriptor.findFieldByName("fixed64_field"), fixed64s[i]) + // Keeps the payload non-empty when both fields are zero. + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'fixed32_field', 'BIGINT'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'BIGINT'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'BIGINT', '7') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + long[] expectedF32 = + { 0L, 1L, 100L, 1_000_000L, 2_147_483_647L, 4_294_967_295L, 4_294_967_294L }; + // Values of 2^63 and above do not fit in BIGINT and read as NULL, even with a default. + Long[] expectedF64 = { 0L, 1L, 1_000_000_000_000L, Long.MAX_VALUE, null, null, null }; + String[] expectedF64Decimal = { "0", "1", "1000000000000", "9223372036854775807", + "18446744073709551615", "18446744073709551614", "18446744073709551613" }; + for (int i = 0; i < expectedF32.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " f32", expectedF32[i], rs.getLong(2)); + assertEquals("row " + i + " f64", expectedF64[i], rs.getObject(3)); + assertEquals("row " + i + " f64 decimal", 0, + new BigDecimal(expectedF64Decimal[i]).compareTo(rs.getBigDecimal(4))); + // A zero is not serialized in proto3, so row 0 is unset and takes the default. + Long expectedWithDefault = fixed64s[i] == 0L ? Long.valueOf(7L) : expectedF64[i]; + assertEquals("row " + i + " f64 default", expectedWithDefault, rs.getObject(5)); + } + assertFalse("expected exactly 7 rows", rs.next()); + } + } + } + + @Test + public void singularSfixed32AndSfixed64LeavesReadBackWithSign() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[] sfixed32s = { -1000, -1, 0, 1, 1000, Integer.MAX_VALUE, Integer.MIN_VALUE }; + long[] sfixed64s = + { -1_000_000_000_000L, -1L, 0L, 1L, 1_000_000_000_000L, Long.MAX_VALUE, Long.MIN_VALUE }; + for (int i = 0; i < sfixed32s.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("sfixed32_field"), sfixed32s[i]) + .setField(allTypesDescriptor.findFieldByName("sfixed64_field"), sfixed64s[i]).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'sfixed32_field', 'INTEGER'), " + + "PROTO_VALUE(PAYLOAD, 'sfixed64_field', 'BIGINT') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < sfixed32s.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " sf32", sfixed32s[i], rs.getInt(2)); + assertEquals("row " + i + " sf64", sfixed64s[i], rs.getLong(3)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void singularUint32WidenedToBigintPreservesUnsignedSemantics() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[] uintValues = { 0, 1, 100, Integer.MAX_VALUE, -1, -2, -1000 }; + long[] expected = + { 0L, 1L, 100L, 2_147_483_647L, 4_294_967_295L, 4_294_967_294L, 4_294_966_296L }; + for (int i = 0; i < uintValues.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("uint32_field"), uintValues[i]).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'uint32_field', 'BIGINT') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getLong(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void singularBytesLeafReadsBackAsVarbinary() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + byte[][] payloads = + { new byte[0], new byte[] { 0x01 }, new byte[] { 0x00, (byte) 0xFF, 0x7F, (byte) 0x80 }, + "hello".getBytes(), new byte[] { 0x10, 0x20, 0x30, 0x40, 0x50 } }; + for (int i = 0; i < payloads.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("bytes_field"), + ByteString.copyFrom(payloads[i])) + .build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < payloads.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + byte[] got = rs.getBytes(2); + byte[] want = payloads[i]; + assertArrayEquals("row " + i, want, got == null ? new byte[0] : got); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void singularInt64CoercedToDecimalReadsAsBigDecimal() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[] values = { 1L, 1_000_000L, Long.MAX_VALUE, -1L, -1_000_000_000L, Long.MIN_VALUE }; + for (int i = 0; i < values.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), values[i]).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'DECIMAL') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < values.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, 0, new BigDecimal(values[i]).compareTo(rs.getBigDecimal(2))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void singularFloatCoercedToDecimalMapsNonFiniteToNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor childDescriptor = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + float[] values = { 0.1f, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, -2.5f }; + for (int i = 0; i < values.length; i++) { + DynamicMessage child = DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("float_val"), values[i]).build(); + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), child).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = + "SELECT ID, PROTO_VALUE(PAYLOAD, 'child_msg.float_val', 'DECIMAL') FROM " + table; + BigDecimal[] expected = { new BigDecimal("0.1"), null, null, null, new BigDecimal("-2.5") }; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < values.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getBigDecimal(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void tagVarintOutsideIntRangeReadsAsNullForIntegerAndUnsignedInt() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[] values = { 1L, 2147483648L, 4294967297L, 3000000000L, -1L }; + for (int i = 0; i < values.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), values[i]).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'INTEGER'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'UNSIGNED_INT'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'INTEGER', '7'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'UNSIGNED_INT', '7'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'UNSIGNED_LONG', '7') FROM " + table; + Integer[] expectedInt = { 1, null, null, null, -1 }; + Integer[] expectedUnsigned = { 1, null, null, null, null }; + Long[] expectedUnsignedLong = { 1L, 2147483648L, 4294967297L, 3000000000L, null }; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < values.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expectedInt[i], rs.getObject(2)); + assertEquals("row " + i, expectedUnsigned[i], rs.getObject(3)); + assertEquals("row " + i + " with default", expectedInt[i], rs.getObject(4)); + assertEquals("row " + i + " with default", expectedUnsigned[i], rs.getObject(5)); + assertEquals("row " + i + " with default", expectedUnsignedLong[i], rs.getObject(6)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void invalidPathOrTypeIsRejectedAtCompileTimeOnEmptyTable() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int notFound = SQLExceptionCode.PROTOBUF_PATH_FIELD_NOT_FOUND.getErrorCode(); + int syntax = SQLExceptionCode.PROTOBUF_TAG_PATH_INVALID_SYNTAX.getErrorCode(); + int mismatch = SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH.getErrorCode(); + int narrowing = SQLExceptionCode.PROTOBUF_VALUE_TYPE_NARROWING_NOT_PERMITTED.getErrorCode(); + Object[][] cases = { { "PROTO_VALUE(PAYLOAD, 'no.such', 'INTEGER')", notFound }, + { "PROTO_EXISTS(PAYLOAD, 'no.such')", notFound }, + { "PROTO_ARRAY_LENGTH(PAYLOAD, 'no.such')", notFound }, + { "PROTO_VALUE(PAYLOAD, 'int64_field', 'BOGUS')", mismatch }, + { "PROTO_VALUE(PAYLOAD, 'int64_field', 'VARCHAR')", mismatch }, + { "PROTO_VALUE(PAYLOAD, 'int64_field', 'INTEGER')", narrowing }, + { "PROTO_VALUE_AT_TAG(PAYLOAD, '7.', 'BIGINT')", syntax }, + { "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'BOGUS')", mismatch }, + { "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'DATE')", mismatch } }; + for (Object[] c : cases) { + String[] statements = { "SELECT " + c[0] + " FROM " + table, + "CREATE INDEX " + generateUniqueName() + " ON " + table + " (" + c[0] + ")" }; + for (String sql : statements) { + try { + conn.createStatement().execute(sql); + fail("expected compile failure for " + sql); + } catch (SQLException e) { + assertEquals(sql, c[1], e.getErrorCode()); + } + } + } + } + } + + @Test + public void emptyPayloadReadsAsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + upsertPayload(conn, table, 1L, new byte[0]); + upsertPayload(conn, table, 2L, + DynamicMessage.newBuilder(allTypesDescriptor).build().toByteArray()); + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + rs.getLong(2); + assertTrue("empty payload → SQL NULL", rs.wasNull()); + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + rs.getLong(2); + // An all-defaults proto3 message encodes to zero bytes, which is stored as NULL. + assertTrue("proto3 all-defaults payload → SQL NULL", rs.wasNull()); + assertFalse(rs.next()); + } + } + } + + @Test + public void unsetScalarUnderPresentParentReadsAsTypeZero() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor childDescriptor = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + upsertPayload(conn, table, 1L, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build().toByteArray()); + upsertPayload(conn, table, 2L, + DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("filler"), 5).build()) + .build().toByteArray()); + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'child_msg.payload_string', 'VARCHAR'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.bool_flag', 'BOOLEAN'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.float_val', 'FLOAT'), " + + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL'), " + + "PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY'), " + + "PROTO_EXISTS(PAYLOAD, 'uint32_field') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + // child_msg is unset, so its fields read as NULL. + for (int col = 2; col <= 4; col++) { + assertNull("id=1 col " + col, rs.getObject(col)); + } + // Top-level fields: the root message is present. + assertEquals(0, rs.getInt(5)); + assertFalse(rs.wasNull()); + assertEquals(0, BigDecimal.ZERO.compareTo(rs.getBigDecimal(6))); + // Phoenix reads an empty VARCHAR or VARBINARY as NULL. + assertNull(rs.getBytes(7)); + assertFalse("PROTO_EXISTS distinguishes unset from zero", rs.getBoolean(8)); + + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertEquals(Boolean.FALSE, rs.getObject(3)); + assertEquals(0.0f, rs.getFloat(4), 0.0f); + assertFalse(rs.wasNull()); + assertFalse(rs.next()); + } + } + } + + @Test + public void proto3OptionalReadsAsZeroWhenUnsetAndOneofArmReadsAsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + // { opt_int32, choice_int }; null means unset. A set field is on the wire even when zero. + Integer[][] rows = { { null, null }, { 0, null }, { 7, null }, { null, 0 }, { -3, 9 } }; + for (int i = 0; i < rows.length; i++) { + DynamicMessage.Builder b = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L); + if (rows[i][0] != null) { + b.setField(allTypesDescriptor.findFieldByName("opt_int32"), rows[i][0]); + } + if (rows[i][1] != null) { + b.setField(allTypesDescriptor.findFieldByName("choice_int"), rows[i][1]); + } + upsertPayload(conn, table, i + 1L, b.build().toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'opt_int32', 'INTEGER')," + + " PROTO_EXISTS(PAYLOAD, 'opt_int32'), PROTO_VALUE(PAYLOAD, 'choice_int', 'INTEGER')," + + " PROTO_EXISTS(PAYLOAD, 'choice_int') FROM " + table + " ORDER BY ID"; + int[] expectedOpt = { 0, 0, 7, 0, -3 }; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < rows.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + // Explicit presence only changes PROTO_EXISTS; an unset optional still reads as zero. + assertEquals("row " + i, Integer.valueOf(expectedOpt[i]), rs.getObject(2)); + assertEquals("row " + i, rows[i][0] != null, rs.getBoolean(3)); + // An unset oneof arm has no value to fall back to. + assertEquals("row " + i, rows[i][1], rs.getObject(4)); + assertEquals("row " + i, rows[i][1] != null, rs.getBoolean(5)); + } + assertFalse(rs.next()); + } + String zeroSql = "SELECT ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'opt_int32', 'INTEGER') = 0 ORDER BY ID"; + try (PreparedStatement ps = conn.prepareStatement(zeroSql); + ResultSet rs = ps.executeQuery()) { + for (long id : new long[] { 1L, 2L, 4L }) { + assertTrue(rs.next()); + assertEquals(id, rs.getLong(1)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void invalidDefaultLiteralIsRejectedAtCompileTime() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String[][] cases = { { "child_msg.filler", "INTEGER", "abc" }, + { "child_msg.filler", "INTEGER", "99999999999" }, { "int64_field", "BIGINT", "1.5" }, + { "child_msg.bool_flag", "BOOLEAN", "yes" }, { "child_msg.float_val", "FLOAT", "x" }, + { "uint32_field", "UNSIGNED_INT", "-1" }, { "fixed64_field", "UNSIGNED_LONG", "-1" }, + { "fixed64_field", "DECIMAL", "1e" } }; + for (String[] c : cases) { + String sql = "SELECT ID FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, '" + c[0] + "', '" + + c[1] + "', '" + c[2] + "') IS NOT NULL"; + try { + conn.prepareStatement(sql).executeQuery(); + fail("expected default '" + c[2] + "' for " + c[1] + " to be rejected"); + } catch (SQLException e) { + assertEquals(c[1] + " '" + c[2] + "'", + SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH.getErrorCode(), e.getErrorCode()); + } + } + try { + conn + .prepareStatement( + "SELECT PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'BIGINT', 'abc') FROM " + table) + .executeQuery(); + fail("expected PROTO_VALUE_AT_TAG default 'abc' to be rejected"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_VALUE_TYPE_MISMATCH.getErrorCode(), + e.getErrorCode()); + } + } + } + + @Test + public void unrepresentableUnsignedValuesReadAsNullEvenWithDefault() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[] fixed64s = { 5L, Long.MAX_VALUE, -5L }; + int[] uint32s = { 5, Integer.MAX_VALUE, -5 }; + for (int i = 0; i < fixed64s.length; i++) { + upsertPayload(conn, table, i + 1L, + DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("fixed64_field"), fixed64s[i]) + .setField(allTypesDescriptor.findFieldByName("uint32_field"), uint32s[i]).build() + .toByteArray()); + } + String sql = "SELECT PROTO_VALUE(PAYLOAD, 'fixed64_field', 'UNSIGNED_LONG', '7'), " + + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT', '7') FROM " + table; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + Long[] expectedLong = { 5L, Long.MAX_VALUE, null }; + Integer[] expectedInt = { 5, Integer.MAX_VALUE, null }; + for (int i = 0; i < expectedLong.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals("row " + i, expectedLong[i], rs.getObject(1)); + assertEquals("row " + i, expectedInt[i], rs.getObject(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void unsignedAndBooleanDefaultsFireWhenPathAbsent() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + upsertPayload(conn, table, 1L, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build().toByteArray()); + String sql = "SELECT PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT', '12'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'UNSIGNED_LONG', '34'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.bool_flag', 'BOOLEAN', 'TRUE'), " + + "PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY_ENCODED', 'enc'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '5', 'UNSIGNED_INT', '56') FROM " + table; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(12, rs.getInt(1)); + assertEquals(34L, rs.getLong(2)); + assertTrue(rs.getBoolean(3)); + assertArrayEquals("enc".getBytes(), rs.getBytes(4)); + assertEquals(56, rs.getInt(5)); + assertFalse(rs.next()); + } + } + } + + @Test + public void mapInt32KeyBracketLookupReturnsExpectedValues() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[][] keys = { { 10, 20, 30 }, { 20, 40 }, { 15, 25, 30 }, { 10 }, { 40, 50, 60 } }; + String[][] values = { { "v10-a", "v20-a", "v30-a" }, { "v20-b", "v40-b" }, + { "v15-c", "v25-c", "v30-c" }, { "v10-d" }, { "v40-e", "v50-e", "v60-e" } }; + for (int i = 0; i < keys.length; i++) { + upsertPayload(conn, table, i + 1L, buildInt32MapPayload(keys[i], values[i]).toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int32_map[20]', 'VARCHAR') FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'int32_map[20]', 'VARCHAR') IS NOT NULL" + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals("v20-a", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("v20-b", rs.getString(2)); + assertFalse("expected exactly 2 rows with key=20", rs.next()); + } + } + } + + @Test + public void mapInt64KeyBracketLookupReturnsExpectedValues() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[][] keys = { { 100_000_000_000L, 200_000_000_000L }, + { 200_000_000_000L, 300_000_000_000L, 400_000_000_000L }, { 500_000_000_000L }, + { 200_000_000_000L, 600_000_000_000L }, { 700_000_000_000L, 800_000_000_000L } }; + String[][] values = { { "one", "two" }, { "two-b", "three", "four" }, { "five" }, + { "two-d", "six" }, { "seven", "eight" } }; + for (int i = 0; i < keys.length; i++) { + upsertPayload(conn, table, i + 1L, buildInt64MapPayload(keys[i], values[i]).toByteArray()); + } + String sql = + "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_map[200000000000]', " + "'VARCHAR') FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'int64_map[200000000000]', 'VARCHAR') IS NOT NULL" + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 1L, 2L, 4L }; + String[] expectedVals = { "two", "two-b", "two-d" }; + for (int i = 0; i < expectedIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(expectedIds[i], rs.getLong(1)); + assertEquals(expectedVals[i], rs.getString(2)); + } + assertFalse("expected exactly 3 rows with key=200000000000", rs.next()); + } + } + } + + @Test + public void malformedPayloadReadsAsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + DynamicMessage valid = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 42L).build(); + upsertPayload(conn, table, 1L, valid.toByteArray()); + upsertPayload(conn, table, 2L, new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }); + upsertPayload(conn, table, 3L, new byte[] { (byte) 0x08 }); + upsertPayload(conn, table, 4L, "not-a-proto".getBytes()); + upsertPayload(conn, table, 5L, new byte[] { 0x08, (byte) 0xFF }); + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals(42L, rs.getLong(2)); + for (long expectedId = 2L; expectedId <= 5L; expectedId++) { + assertTrue("row id " + expectedId, rs.next()); + assertEquals(expectedId, rs.getLong(1)); + rs.getLong(2); + assertTrue("malformed row id " + expectedId + " must be SQL NULL", rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void childOfUnsetParentReturnsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor childDescriptor = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + upsertPayload(conn, table, 1L, + DynamicMessage.newBuilder(allTypesDescriptor).build().toByteArray()); + upsertPayload(conn, table, 2L, + DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("filler"), 999).build()) + .build().toByteArray()); + upsertPayload(conn, table, 3L, + DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("payload_string"), "hello").build()) + .build().toByteArray()); + upsertPayload(conn, table, 4L, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build().toByteArray()); + String sql = "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', '77') " + + "FROM " + table; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + rs.getInt(2); + assertTrue("id=1 empty payload is stored as NULL, so the default is ignored", rs.wasNull()); + + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("id=2 parent present + filler set → 999", 999, rs.getInt(2)); + assertFalse(rs.wasNull()); + + assertTrue(rs.next()); + assertEquals(3L, rs.getLong(1)); + assertEquals("id=3 parent present + filler absent → user default 77", 77, rs.getInt(2)); + assertFalse("expected user default 77, not SQL NULL", rs.wasNull()); + + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("id=4 non-empty payload, parent absent", 77, rs.getInt(2)); + assertFalse(rs.next()); + } + } + } + + @Test + public void veryDeepMessageChainReadsLeafCorrectly() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + long[] values = { 111L, 222L, 333L, 444L, 555L, 666L, 777L }; + for (int i = 0; i < values.length; i++) { + DynamicMessage payload = + buildStrIntMapPayload(new String[] { "shared-key" }, new long[] { values[i] }); + upsertPayload(conn, table, i + 1L, payload.toByteArray()); + } + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'str_int_map.shared-key', 'BIGINT') " + "FROM " + + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < values.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, values[i], rs.getLong(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void defaultsAcrossAllSupportedSqlTypesFireWhenPathAbsent() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + upsertPayload(conn, table, 1L, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build().toByteArray()); + for (long id = 2L; id <= 6L; id++) { + upsertPayload(conn, table, id, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), id).build().toByteArray()); + } + String sql = + "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'child_msg.payload_string', 'VARCHAR', 'v-def'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', '77'), " + + "PROTO_VALUE(PAYLOAD, 'str_int_map.some-key', 'BIGINT', '9999'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'BIGINT', '111111111111'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'DECIMAL', '3.14159') " + "FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (long expectedId = 1L; expectedId <= 6L; expectedId++) { + assertTrue("row " + expectedId, rs.next()); + assertEquals(expectedId, rs.getLong(1)); + assertEquals("v-def", rs.getString(2)); + assertFalse(rs.wasNull()); + assertEquals(77, rs.getInt(3)); + assertFalse(rs.wasNull()); + assertEquals(9999L, rs.getLong(4)); + assertFalse(rs.wasNull()); + assertEquals(111111111111L, rs.getLong(5)); + assertFalse(rs.wasNull()); + assertEquals(0, new BigDecimal("3.14159").compareTo(rs.getBigDecimal(6))); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void defaultsForBooleanFloatAndVarbinaryFireWhenPathAbsent() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor childDescriptor = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + float[] oddFloats = { 1.25f, 3.75f, 5.25f }; + byte[][] oddBytes = + { "row1-bytes".getBytes(), "row3-bytes".getBytes(), "row5-bytes".getBytes() }; + for (long id = 1L; id <= 6L; id++) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), id); + if (id % 2 == 1) { + int oddIdx = (int) (id / 2); + builder.setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("bool_flag"), true) + .setField(childDescriptor.findFieldByName("float_val"), oddFloats[oddIdx]).build()); + builder.setField(allTypesDescriptor.findFieldByName("bytes_field"), + ByteString.copyFrom(oddBytes[oddIdx])); + } + upsertPayload(conn, table, id, builder.build().toByteArray()); + } + String sql = + "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'child_msg.bool_flag', 'BOOLEAN', 'false'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.float_val', 'FLOAT', '2.5'), " + + "PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY', 'my-default') " + "FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + Boolean[] expectedBool = { true, false, true, false, true, false }; + Float[] expectedFloat = { 1.25f, 2.5f, 3.75f, 2.5f, 5.25f, 2.5f }; + byte[][] expectedBytes = + { "row1-bytes".getBytes(), "my-default".getBytes(), "row3-bytes".getBytes(), + "my-default".getBytes(), "row5-bytes".getBytes(), "my-default".getBytes() }; + for (int i = 0; i < expectedBool.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expectedBool[i], rs.getBoolean(2)); + assertFalse("row " + i, rs.wasNull()); + assertEquals("row " + i, expectedFloat[i], rs.getFloat(3), 1e-6f); + assertFalse("row " + i, rs.wasNull()); + assertArrayEquals("row " + i, expectedBytes[i], rs.getBytes(4)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void defaultsMixedAcrossRowsPresentReturnsValueAbsentReturnsDefault() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor childDescriptor = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + int[] expectedFillerValues = { 100, 555, 300, 555, 500, 555, 555 }; + for (int i = 0; i < expectedFillerValues.length; i++) { + long id = i + 1L; + boolean hasChildMsg = (id % 2 == 1) && id != 7L; + boolean fillerSet = hasChildMsg; + DynamicMessage.Builder outer = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), id); + if (hasChildMsg) { + DynamicMessage.Builder child = DynamicMessage.newBuilder(childDescriptor); + if (fillerSet) { + child.setField(childDescriptor.findFieldByName("filler"), (int) (id * 100L)); + } + outer.setField(allTypesDescriptor.findFieldByName("child_msg"), child.build()); + } + if (id == 7L) { + DynamicMessage.Builder child = DynamicMessage.newBuilder(childDescriptor) + .setField(childDescriptor.findFieldByName("payload_string"), "row7-str"); + outer.setField(allTypesDescriptor.findFieldByName("child_msg"), child.build()); + } + upsertPayload(conn, table, id, outer.build().toByteArray()); + } + String sql = "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', '555') " + + "FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < expectedFillerValues.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expectedFillerValues[i], rs.getInt(2)); + assertFalse("row " + i, rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void defaultFiresForMalformedPayloadInsteadOfSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + DynamicMessage valid = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 42L).build(); + upsertPayload(conn, table, 1L, valid.toByteArray()); + upsertPayload(conn, table, 2L, new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }); + upsertPayload(conn, table, 3L, new byte[] { (byte) 0x08 }); + upsertPayload(conn, table, 4L, "not-a-proto".getBytes()); + upsertPayload(conn, table, 5L, valid.toByteArray()); + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT', '12345') " + "FROM " + + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + long[] expected = { 42L, 12345L, 12345L, 12345L, 42L }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getLong(2)); + assertFalse("row " + i, rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void literalNullDefaultReturnsSqlNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + for (long id = 1L; id <= 6L; id++) { + upsertPayload(conn, table, id, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), id).build().toByteArray()); + } + String sql = "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', 'null'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', 'NULL'), " + + "PROTO_VALUE(PAYLOAD, 'child_msg.filler', 'INTEGER', 'NuLl') " + "FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + for (int col = 2; col <= 4; col++) { + rs.getInt(col); + assertTrue("row " + id + " col " + col, rs.wasNull()); + } + } + assertFalse(rs.next()); + } + } + } + + @Test + public void mapWithFloatAndDoubleScalarValuesExerciseFixedWidthReadScalarBytes() + throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String[] keys = { "alpha", "beta", "gamma", "delta", "epsilon", "zeta" }; + float[] floatValues = { 1.25f, 2.5f, 3.75f, 4.0f, 5.5f, 6.125f }; + double[] doubleValues = { 100.5d, 200.25d, 300.125d, 400.0d, 500.75d, 600.875d }; + for (int i = 0; i < keys.length; i++) { + upsertPayload(conn, table, i + 1L, + buildStrFloatAndDoubleMapPayload(keys, floatValues, doubleValues, i).toByteArray()); + } + String sql = "SELECT ID, " + "PROTO_VALUE(PAYLOAD, 'str_float_map.gamma', 'FLOAT'), " + + "PROTO_VALUE(PAYLOAD, 'str_double_map.epsilon', 'DOUBLE') FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (int i = 0; i < keys.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, 3.75f, rs.getFloat(2), 1e-6f); + assertEquals("row " + i, 500.75d, rs.getDouble(3), 1e-9d); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void singularBigintFieldFunctionalIndexServesRangeQueries() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String index = "IDX_" + table; + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT')")); + long[] values = { 10L, 20L, 30L, 40L, 50L, 60L, 70L }; + for (int i = 0; i < values.length; i++) { + DynamicMessage msg = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), values[i]).build(); + upsertPayload(conn, table, i + 1L, msg.toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + index)) { + assertTrue(rs.next()); + assertEquals(values.length, rs.getInt(1)); + } + String rangeSql = "SELECT ID, C1 FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT') BETWEEN ? AND ?" + + " ORDER BY PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT') ASC"; + try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { + ps.setLong(1, 20L); + ps.setLong(2, 60L); + try (ResultSet rs = ps.executeQuery()) { + long[] expectedIds = { 2L, 3L, 4L, 5L, 6L }; + for (long expectedId : expectedIds) { + assertTrue(rs.next()); + assertEquals(expectedId, rs.getLong(1)); + } + assertFalse("expected exactly 5 rows in [20, 60]", rs.next()); + } + validateExplainPlan(ps, index); + } + } + } + + @Test + public void mapInt32KeyFunctionalIndexServesPointLookups() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String index = "IDX_" + table; + conn.createStatement() + .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'int32_map[42]', 'VARCHAR')")); + int[][] keys = + { { 42 }, { 42, 99 }, { 99 }, { 42, 100 }, { 100 }, { 42, 200 }, { 42, 300, 400 } }; + String[][] values = + { { "row1-v" }, { "row2-v42", "row2-v99" }, { "row3-v99" }, { "row4-v42", "row4-v100" }, + { "row5-v100" }, { "row6-v42", "row6-v200" }, { "row7-v42", "row7-v300", "row7-v400" } }; + for (int i = 0; i < keys.length; i++) { + upsertPayload(conn, table, i + 1L, buildInt32MapPayload(keys[i], values[i]).toByteArray()); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + index)) { + assertTrue(rs.next()); + assertEquals(5, rs.getInt(1)); + } + String pointSql = + "SELECT ID FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'int32_map[42]', 'VARCHAR') = ?"; + try (PreparedStatement ps = conn.prepareStatement(pointSql)) { + ps.setString(1, "row4-v42"); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertFalse(rs.next()); + } + validateExplainPlan(ps, index); + } + } + } + + @Test + public void protoExistsAcrossPresenceAndAbsenceStates() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + Descriptors.Descriptor child = + allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + Descriptors.FieldDescriptor int32MapField = allTypesDescriptor.findFieldByName("int32_map"); + Descriptors.Descriptor int32EntryType = int32MapField.getMessageType(); + byte[][] payloads = new byte[6][]; + payloads[0] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 42L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child) + .setField(child.findFieldByName("payload_string"), "hello").build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v1").build()) + .build().toByteArray(); + payloads[1] = DynamicMessage.newBuilder(allTypesDescriptor) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 99) + .setField(int32EntryType.findFieldByName("value"), "v2").build()) + .build().toByteArray(); + payloads[2] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 100L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("filler"), 1).build()) + .build().toByteArray(); + payloads[3] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 50L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("payload_string"), "") + .build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v3").build()) + .build().toByteArray(); + payloads[4] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 200L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("filler"), 2).build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v5").build()) + .build().toByteArray(); + payloads[5] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child) + .setField(child.findFieldByName("payload_string"), "present").build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v6").build()) + .build().toByteArray(); + for (int i = 0; i < payloads.length; i++) { + upsertPayload(conn, table, i + 1L, payloads[i]); + } + String sql = "SELECT ID, PROTO_EXISTS(PAYLOAD, 'int64_field'), " + + "PROTO_EXISTS(PAYLOAD, 'child_msg.payload_string'), " + + "PROTO_EXISTS(PAYLOAD, 'int32_map[42]') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + boolean[] expInt64 = { true, false, true, true, true, false }; + boolean[] expChildStr = { true, false, false, false, false, true }; + boolean[] expMap42 = { true, false, false, true, true, true }; + for (int i = 0; i < expInt64.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i + " int64_field", expInt64[i], rs.getBoolean(2)); + assertEquals("row " + i + " child_msg.payload_string", expChildStr[i], rs.getBoolean(3)); + assertEquals("row " + i + " int32_map[42]", expMap42[i], rs.getBoolean(4)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoArrayLengthCountsMapEntries() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + int[][] keysPerRow = { {}, { 1 }, { 1, 2, 3 }, { 5, 10 }, { 100 } }; + String[][] valuesPerRow = { {}, { "a" }, { "a", "b", "c" }, { "d", "e" }, { "f" } }; + for (int i = 0; i < keysPerRow.length; i++) { + upsertPayload(conn, table, i + 1L, + buildInt32MapPayload(keysPerRow[i], valuesPerRow[i]).toByteArray()); + } + String sql = + "SELECT ID, PROTO_ARRAY_LENGTH(PAYLOAD, 'int32_map') FROM " + table + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + int[] expected = { 0, 1, 3, 2, 1 }; + for (int i = 0; i < expected.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals("row " + i, expected[i], rs.getInt(2)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void protoFieldTypeReturnsCanonicalSqlTypeNamesAcrossProtoTypes() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + for (long id = 1L; id <= 6L; id++) { + upsertPayload(conn, table, id, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), id).build().toByteArray()); + } + String sql = "SELECT ID, " + "PROTO_FIELD_TYPE(PAYLOAD, 'int64_field'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'fixed32_field'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'sfixed64_field'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'bytes_field'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'child_msg.payload_string'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'child_msg.bool_flag') " + "FROM " + table + + " ORDER BY ID ASC"; + try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + assertEquals("row " + id, "BIGINT", rs.getString(2)); + assertEquals("row " + id, "UNSIGNED_INT", rs.getString(3)); + assertEquals("row " + id, "BIGINT", rs.getString(4)); + assertEquals("row " + id, "VARBINARY", rs.getString(5)); + assertEquals("row " + id, "VARCHAR", rs.getString(6)); + assertEquals("row " + id, "BOOLEAN", rs.getString(7)); + } + assertFalse(rs.next()); + } + } + } + + private String createRegisteredTable(Connection conn) throws SQLException { + String descUrl = "file://" + descriptorPath.toAbsolutePath(); + conn.createStatement().execute( + "CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + DESCRIPTOR_NAME + " FROM '" + descUrl + "'"); + String table = generateUniqueName(); + createdTables.add(table); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + + DESCRIPTOR_NAME + ">)" + encodingClause()); + return table; + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private String indexDdl(String indexName, String tableName, String indexedExpr) { + if (this.coveredIndex) { + return "CREATE INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") INCLUDE(C1) WHERE " + indexedExpr + " IS NOT NULL"; + } + return "CREATE UNCOVERED INDEX " + indexName + " ON " + tableName + "(" + indexedExpr + + ") WHERE " + indexedExpr + " IS NOT NULL"; + } + + private static void upsertPayload(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, C1, PAYLOAD) VALUES (?, ?, ?)")) { + ps.setLong(1, id); + ps.setString(2, "c1-" + id); + ps.setBytes(3, payload); + ps.executeUpdate(); + } + conn.commit(); + } + + private static DynamicMessage buildStrIntMapPayload(String[] keys, long[] values) { + Descriptors.FieldDescriptor mapField = allTypesDescriptor.findFieldByName("str_int_map"); + Descriptors.Descriptor entryType = mapField.getMessageType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(allTypesDescriptor); + for (int i = 0; i < keys.length; i++) { + DynamicMessage entry = + DynamicMessage.newBuilder(entryType).setField(entryType.findFieldByName("key"), keys[i]) + .setField(entryType.findFieldByName("value"), values[i]).build(); + builder.addRepeatedField(mapField, entry); + } + return builder.build(); + } + + private static DynamicMessage buildInt32MapPayload(int[] keys, String[] values) { + Descriptors.FieldDescriptor mapField = allTypesDescriptor.findFieldByName("int32_map"); + Descriptors.Descriptor entryType = mapField.getMessageType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(allTypesDescriptor); + for (int i = 0; i < keys.length; i++) { + DynamicMessage entry = + DynamicMessage.newBuilder(entryType).setField(entryType.findFieldByName("key"), keys[i]) + .setField(entryType.findFieldByName("value"), values[i]).build(); + builder.addRepeatedField(mapField, entry); + } + return builder.build(); + } + + private static DynamicMessage buildInt64MapPayload(long[] keys, String[] values) { + Descriptors.FieldDescriptor mapField = allTypesDescriptor.findFieldByName("int64_map"); + Descriptors.Descriptor entryType = mapField.getMessageType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(allTypesDescriptor); + for (int i = 0; i < keys.length; i++) { + DynamicMessage entry = + DynamicMessage.newBuilder(entryType).setField(entryType.findFieldByName("key"), keys[i]) + .setField(entryType.findFieldByName("value"), values[i]).build(); + builder.addRepeatedField(mapField, entry); + } + return builder.build(); + } + + private static DynamicMessage buildStrFloatAndDoubleMapPayload(String[] keys, float[] floatValues, + double[] doubleValues, int rowIndex) { + Descriptors.FieldDescriptor floatMapField = allTypesDescriptor.findFieldByName("str_float_map"); + Descriptors.FieldDescriptor doubleMapField = + allTypesDescriptor.findFieldByName("str_double_map"); + Descriptors.Descriptor floatEntry = floatMapField.getMessageType(); + Descriptors.Descriptor doubleEntry = doubleMapField.getMessageType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), rowIndex + 1L); + for (int i = 0; i < keys.length; i++) { + builder.addRepeatedField(floatMapField, + DynamicMessage.newBuilder(floatEntry).setField(floatEntry.findFieldByName("key"), keys[i]) + .setField(floatEntry.findFieldByName("value"), floatValues[i]).build()); + builder.addRepeatedField(doubleMapField, + DynamicMessage.newBuilder(doubleEntry).setField(doubleEntry.findFieldByName("key"), keys[i]) + .setField(doubleEntry.findFieldByName("value"), doubleValues[i]).build()); + } + return builder.build(); + } + + private static DescriptorProto mapEntryProto(String name, Type keyType, Type valueType) { + return DescriptorProto.newBuilder().setName(name) + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField(FieldDescriptorProto.newBuilder().setName("key").setNumber(1).setType(keyType) + .setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("value").setNumber(2).setType(valueType) + .setLabel(Label.LABEL_OPTIONAL).build()) + .build(); + } + + @Test + public void protoValueAtTagNestedChildStringByTagNumber() throws Exception { + String table = ensureTable(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + upsertRows(conn, table); + String sql = + "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '8.1', 'VARCHAR') FROM " + table + " ORDER BY ID"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals("hello", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.next()); + assertEquals(3L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.next()); + assertEquals(5L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.next()); + assertEquals(6L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagVarintLeafAsBigint() throws Exception { + String table = ensureTable(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + upsertRows(conn, table); + String sql = + "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'BIGINT') FROM " + table + " ORDER BY ID"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals(42L, rs.getLong(2)); + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertNull(rs.getObject(2)); + assertTrue(rs.next()); + assertEquals(3L, rs.getLong(1)); + assertEquals(100L, rs.getLong(2)); + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals(50L, rs.getLong(2)); + assertTrue(rs.next()); + assertEquals(5L, rs.getLong(1)); + assertEquals(200L, rs.getLong(2)); + assertTrue(rs.next()); + assertEquals(6L, rs.getLong(1)); + assertNull(rs.getObject(2)); + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagMapAsRepeatedIndexAccess() throws Exception { + String table = ensureTable(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + upsertRows(conn, table); + String sql = "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '11[0].2', 'VARCHAR') FROM " + table + + " ORDER BY ID"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertEquals("v1", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertEquals("v2", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(3L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertTrue(rs.next()); + assertEquals(4L, rs.getLong(1)); + assertEquals("v3", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(5L, rs.getLong(1)); + assertEquals("v5", rs.getString(2)); + assertTrue(rs.next()); + assertEquals(6L, rs.getLong(1)); + assertNull(rs.getString(2)); + assertFalse(rs.next()); + } + } + } + + @Test + public void protoValueAtTagWireTypeMismatchReturnsNull() throws Exception { + String table = ensureTable(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + upsertRows(conn, table); + String sql = + "SELECT ID, PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'DOUBLE') FROM " + table + " ORDER BY ID ASC"; + try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + assertNull("row " + id, rs.getObject(2)); + assertTrue("row " + id, rs.wasNull()); + } + assertFalse(rs.next()); + } + } + } + + private String atTagTable; + + private String ensureTable() throws Exception { + if (atTagTable != null) { + return atTagTable; + } + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + atTagTable = generateUniqueName(); + createdTables.add(atTagTable); + conn.createStatement().execute( + "CREATE TABLE " + atTagTable + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD VARBINARY)" + + (columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0")); + upsertRows(conn, atTagTable); + } + return atTagTable; + } + + private void upsertRows(Connection conn, String table) throws SQLException { + Descriptors.FieldDescriptor int32MapField = allTypesDescriptor.findFieldByName("int32_map"); + Descriptors.Descriptor int32EntryType = int32MapField.getMessageType(); + Descriptors.Descriptor child = allTypesDescriptor.findFieldByName("child_msg").getMessageType(); + byte[][] payloads = new byte[6][]; + payloads[0] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 42L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("payload_string"), "hello") + .build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v1").build()) + .build().toByteArray(); + payloads[1] = DynamicMessage.newBuilder(allTypesDescriptor) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 99) + .setField(int32EntryType.findFieldByName("value"), "v2").build()) + .build().toByteArray(); + payloads[2] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 100L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("filler"), 1).build()) + .build().toByteArray(); + payloads[3] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 50L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("payload_string"), "") + .build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v3").build()) + .build().toByteArray(); + payloads[4] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("int64_field"), 200L) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("filler"), 2).build()) + .addRepeatedField(int32MapField, + DynamicMessage.newBuilder(int32EntryType) + .setField(int32EntryType.findFieldByName("key"), 42) + .setField(int32EntryType.findFieldByName("value"), "v5").build()) + .build().toByteArray(); + payloads[5] = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("child_msg"), + DynamicMessage.newBuilder(child).setField(child.findFieldByName("filler"), 3).build()) + .build().toByteArray(); + for (int i = 0; i < payloads.length; i++) { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + ps.setLong(1, i + 1L); + ps.setBytes(2, payloads[i]); + ps.execute(); + } + } + conn.commit(); + } + + private static Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private static void validateExplainPlan(PreparedStatement ps, String indexName) + throws SQLException { + ExplainPlan plan = ps.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan(); + ExplainPlanAttributes attrs = plan.getPlanStepsAsAttributes(); + assertEquals(indexName, attrs.getTableName()); + assertEquals("PARALLEL 1-WAY", attrs.getIteratorTypeAndScanSize()); + assertEquals("RANGE SCAN", attrs.getExplainScanType()); + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufColumnDDLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufColumnDDLIT.java new file mode 100644 index 00000000000..a47b3a784d3 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufColumnDDLIT.java @@ -0,0 +1,972 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Admin; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.Table; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.jdbc.PhoenixConnection; +import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; +import org.apache.phoenix.schema.ColumnNotFoundException; +import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.TableNotFoundException; +import org.apache.phoenix.util.MetaDataUtil; +import org.apache.phoenix.util.PhoenixRuntime; +import org.apache.phoenix.util.PropertiesUtil; +import org.apache.phoenix.util.SchemaUtil; +import org.apache.phoenix.util.TestUtil; +import org.junit.After; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@Category(ParallelStatsDisabledTest.class) +@RunWith(Parameterized.class) +public class ProtobufColumnDDLIT extends ParallelStatsDisabledIT { + private final boolean columnEncoded; + + public ProtobufColumnDDLIT(boolean columnEncoded) { + this.columnEncoded = columnEncoded; + } + + @Parameterized.Parameters(name = "columnEncoded={0}") + public static synchronized Collection data() { + return Arrays.asList(new Object[][] { { false }, { true } }); + } + + private static final String BUNDLE_RESOURCE = "/protobuf/acmewidgets/acmewidgets_v1.desc"; + + private static final String ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + private static final String DELIVERY_WINDOW_RECORD = + "com.example.acmewidgets.delivery.v1.DeliveryWindowRecord"; + private static final String TOKEN_REVOCATION = + "com.example.acmewidgets.auth.v1.proto2.TokenRevocation"; + private static final String UNKNOWN_MESSAGE = "com.example.acmewidgets.account.v1.NotInTheBundle"; + // Registered only after a failed reference, so no other IT may register it. + private static final String POLICY_TOGGLE = "com.example.acmewidgets.billing.v1.PolicyToggle"; + + private static final List KNOWN_FIXTURE_NAMES = + Arrays.asList(ACCOUNT, DELIVERY_WINDOW_RECORD, TOKEN_REVOCATION, POLICY_TOGGLE); + + private static String fixtureFileUrl() { + URL res = ProtobufColumnDDLIT.class.getResource(BUNDLE_RESOURCE); + assertNotNull("Test fixture " + BUNDLE_RESOURCE + " not on the classpath", res); + return res.toString(); + } + + private Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + private String encodingClause() { + return this.columnEncoded ? " COLUMN_ENCODED_BYTES=2" : " COLUMN_ENCODED_BYTES=0"; + } + + private final List createdTables = new ArrayList<>(); + private final List createdViews = new ArrayList<>(); + + private String uniqueTableName() { + String name = generateUniqueName(); + createdTables.add(name); + return name; + } + + private String uniqueViewName() { + String name = generateUniqueName(); + createdViews.add(name); + return name; + } + + @After + public void cleanupTablesAndDescriptors() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : createdViews) { + try { + stmt.execute("DROP VIEW IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + for (String name : createdTables) { + try { + stmt.execute("DROP TABLE IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + for (String name : KNOWN_FIXTURE_NAMES) { + try { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + name); + } catch (SQLException ignore) { + } + } + } + createdTables.clear(); + createdViews.clear(); + } + + private void registerDescriptorsIdempotent(Connection conn, String... names) throws SQLException { + for (String name : names) { + conn.createStatement().execute( + "CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + name + " FROM '" + fixtureFileUrl() + "'"); + } + } + + @Test + public void conditionalTtlOnProtoValueExpiresRowsOnCompaction() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause() + + ", TTL = 'PROTO_VALUE(PAYLOAD, ''active'', ''BOOLEAN'') = TRUE'" + + ", \"phoenix.max.lookback.age.seconds\" = 0"); + try ( + PreparedStatement ps = conn.prepareStatement("UPSERT INTO " + table + " VALUES (?, ?)")) { + ps.setLong(1, 1L); + ps.setBytes(2, new byte[] { 0x0A, 0x01, 'a' }); + ps.executeUpdate(); + ps.setLong(1, 2L); + ps.setBytes(2, new byte[] { 0x0A, 0x01, 'b', 0x20, 0x01 }); + ps.executeUpdate(); + } + conn.commit(); + TestUtil.flush(getUtility(), TableName.valueOf(table)); + TestUtil.majorCompact(getUtility(), TableName.valueOf(table)); + assertEquals(1, TestUtil.getRawRowCount(conn, TableName.valueOf(table))); + try (ResultSet rs = conn.createStatement().executeQuery("SELECT ID FROM " + table)) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertFalse(rs.next()); + } + } + } + + @Test + public void createTableWithProtobufColumnSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "PAYLOAD")); + assertLinkRowCount(conn, ACCOUNT, table, 1); + } + } + + @Test + public void createTableWithMissingDescriptorRaisesNotFound() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + try { + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + UNKNOWN_MESSAGE + ">)" + encodingClause()); + fail("CREATE TABLE with unregistered descriptor must be rejected"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + e.getErrorCode()); + assertTrue(e.getMessage().contains(UNKNOWN_MESSAGE)); + } + assertTableDoesNotExist(conn, table); + } + } + + @Test + public void createTableWithMultipleProtobufColumnsWritesAllLinks() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD, TOKEN_REVOCATION); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + "A PROTOBUF<" + + ACCOUNT + ">, " + "D PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">, " + "T PROTOBUF<" + + TOKEN_REVOCATION + ">)" + encodingClause()); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "A")); + assertEquals(DELIVERY_WINDOW_RECORD, getProtoMessageName(conn, table, "D")); + assertEquals(TOKEN_REVOCATION, getProtoMessageName(conn, table, "T")); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + assertLinkRowCount(conn, TOKEN_REVOCATION, table, 1); + } + } + + @Test + public void createTableWithMixedColumnTypesOnlyLinksProtobufCols() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement().execute( + "CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + "NAME VARCHAR(64), " + + "AGE INTEGER, " + "PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + encodingClause()); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "PAYLOAD")); + assertNull(getProtoMessageName(conn, table, "NAME")); + assertNull(getProtoMessageName(conn, table, "AGE")); + assertLinkRowCount(conn, ACCOUNT, table, 1); + } + } + + @Test + public void alterTableAddProtobufColumnSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, NAME VARCHAR)" + encodingClause()); + conn.createStatement() + .execute("ALTER TABLE " + table + " ADD PAYLOAD PROTOBUF<" + ACCOUNT + ">"); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "PAYLOAD")); + assertLinkRowCount(conn, ACCOUNT, table, 1); + } + } + + @Test + public void messageNameOnNonProtobufColumnIsRejected() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + assertMessageNameNotAllowed(conn, + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, C VARCHAR<" + ACCOUNT + ">)"); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, NAME VARCHAR)" + encodingClause()); + assertMessageNameNotAllowed(conn, "ALTER TABLE " + table + " ADD C VARCHAR<" + ACCOUNT + ">"); + assertLinkRowCount(conn, ACCOUNT, table, 0); + } + } + + private static void assertMessageNameNotAllowed(Connection conn, String sql) { + try { + conn.createStatement().execute(sql); + fail("expected rejection for " + sql); + } catch (SQLException e) { + assertEquals(sql, SQLExceptionCode.PROTOBUF_MESSAGE_NAME_NOT_ALLOWED.getErrorCode(), + e.getErrorCode()); + } + } + + @Test + public void alterTableAddProtobufColumnMissingDescriptorRaisesNotFound() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, NAME VARCHAR)" + encodingClause()); + try { + conn.createStatement() + .execute("ALTER TABLE " + table + " ADD PAYLOAD PROTOBUF<" + UNKNOWN_MESSAGE + ">"); + fail("ALTER TABLE ADD PROTOBUF column with unregistered descriptor must be rejected"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + e.getErrorCode()); + } + assertNull(getProtoMessageName(conn, table, "PAYLOAD")); + assertLinkRowCount(conn, UNKNOWN_MESSAGE, table, 0); + } + } + + @Test + public void createTableSucceedsOnRetryAfterDescriptorIsCreated() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + String ddl = "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + POLICY_TOGGLE + ">)" + encodingClause(); + try { + conn.createStatement().execute(ddl); + fail("CREATE TABLE with unregistered descriptor must be rejected"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + e.getErrorCode()); + } + registerDescriptorsIdempotent(conn, POLICY_TOGGLE); + conn.createStatement().execute(ddl); + assertEquals(POLICY_TOGGLE, getProtoMessageName(conn, table, "PAYLOAD")); + assertLinkRowCount(conn, POLICY_TOGGLE, table, 1); + } + } + + @Test + public void alterTableAddSucceedsOnRetryAfterDescriptorIsCreated() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY)" + encodingClause()); + String ddl = "ALTER TABLE " + table + " ADD PAYLOAD PROTOBUF<" + POLICY_TOGGLE + ">"; + try { + conn.createStatement().execute(ddl); + fail("ALTER TABLE ADD PROTOBUF column with unregistered descriptor must be rejected"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + e.getErrorCode()); + } + registerDescriptorsIdempotent(conn, POLICY_TOGGLE); + conn.createStatement().execute(ddl); + assertEquals(POLICY_TOGGLE, getProtoMessageName(conn, table, "PAYLOAD")); + assertLinkRowCount(conn, POLICY_TOGGLE, table, 1); + } + } + + @Test + public void alterTableAddMultipleProtobufColumnsWritesAllLinks() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY)" + encodingClause()); + conn.createStatement().execute("ALTER TABLE " + table + " ADD " + "A PROTOBUF<" + ACCOUNT + + ">, D PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">"); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "A")); + assertEquals(DELIVERY_WINDOW_RECORD, getProtoMessageName(conn, table, "D")); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + } + } + + @Test + public void dropProtobufDescriptorWithReferencingColumnRejected() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + try { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + fail("DROP PROTOBUF DESCRIPTOR must reject an in-use descriptor"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE.getErrorCode(), e.getErrorCode()); + } + assertTrue(isDescriptorRegistered(conn, ACCOUNT)); + } + } + + @Test + public void dropProtobufDescriptorAfterDroppingTableSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + assertLinkRowCount(conn, ACCOUNT, table, 1); + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + } + } + + @Test + public void dropProtobufDescriptorAfterDroppingColumnSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + "A PROTOBUF<" + + ACCOUNT + ">, " + "D PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">)" + encodingClause()); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN A"); + assertLinkRowCount(conn, ACCOUNT, table, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + try { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + DELIVERY_WINDOW_RECORD); + fail("DELIVERY_WINDOW_RECORD is still referenced by column D"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE.getErrorCode(), e.getErrorCode()); + } + } + } + + @Test + public void dropProtobufDescriptorAfterDroppingTableWithMixedColumnsSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD, TOKEN_REVOCATION); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + + "NAME VARCHAR(64), " + "AGE INTEGER, " + "A PROTOBUF<" + ACCOUNT + ">, " + "D PROTOBUF<" + + DELIVERY_WINDOW_RECORD + ">, " + "T PROTOBUF<" + TOKEN_REVOCATION + ">)" + + encodingClause()); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + assertLinkRowCount(conn, TOKEN_REVOCATION, table, 1); + + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 0); + assertLinkRowCount(conn, TOKEN_REVOCATION, table, 0); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + DELIVERY_WINDOW_RECORD); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + TOKEN_REVOCATION); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + assertFalse(isDescriptorRegistered(conn, DELIVERY_WINDOW_RECORD)); + assertFalse(isDescriptorRegistered(conn, TOKEN_REVOCATION)); + } + } + + @Test + public void droppingNonProtobufColumnDoesNotTouchProtobufLinkRows() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + + "NAME VARCHAR(64), " + "PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + encodingClause()); + assertLinkRowCount(conn, ACCOUNT, table, 1); + + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN NAME"); + assertLinkRowCount(conn, ACCOUNT, table, 1); + try { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + fail("PAYLOAD PROTOBUF column still references ACCOUNT"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE.getErrorCode(), e.getErrorCode()); + } + } + } + + @Test + public void droppingAllProtobufColumnsThenDroppingTableIsNoOpForLinks() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "ID BIGINT NOT NULL PRIMARY KEY, " + "A PROTOBUF<" + + ACCOUNT + ">, " + "D PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">)" + encodingClause()); + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN A"); + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN D"); + assertLinkRowCount(conn, ACCOUNT, table, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 0); + + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 0); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + DELIVERY_WINDOW_RECORD); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + assertFalse(isDescriptorRegistered(conn, DELIVERY_WINDOW_RECORD)); + } + } + + @Test + public void reCreateTableWithSameDescriptorAfterDropSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + String create = "CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + encodingClause(); + conn.createStatement().execute(create); + assertLinkRowCount(conn, ACCOUNT, table, 1); + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + conn.createStatement().execute(create); + assertLinkRowCount(conn, ACCOUNT, table, 1); + } + } + + @Test + public void dropProtobufDescriptorAfterDroppingViewSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + String view = uniqueViewName(); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, BASE_PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + conn.createStatement().execute("CREATE VIEW " + view + " (" + "VIEW_PAYLOAD PROTOBUF<" + + DELIVERY_WINDOW_RECORD + ">) AS SELECT * FROM " + table); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, view, 1); + + conn.createStatement().execute("DROP VIEW " + view); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, view, 0); + assertLinkRowCount(conn, ACCOUNT, table, 1); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + DELIVERY_WINDOW_RECORD); + assertFalse(isDescriptorRegistered(conn, DELIVERY_WINDOW_RECORD)); + } + } + + @Test + public void dropTableCascadeKeepsViewDescriptorInUseUntilViewIsDropped() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + String view = uniqueViewName(); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, BASE_PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + conn.createStatement().execute("CREATE VIEW " + view + " (VIEW_PAYLOAD PROTOBUF<" + + DELIVERY_WINDOW_RECORD + ">) AS SELECT * FROM " + table); + + conn.createStatement().execute("DROP TABLE " + table + " CASCADE"); + + assertLinkRowCount(conn, ACCOUNT, table, 0); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + assertDropDescriptorRejectedAsInUse(conn, DELIVERY_WINDOW_RECORD); + } + } + + @Test + public void linkWithoutCatalogColumnDoesNotBlockDropDescriptor() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + String missing = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + + DELIVERY_WINDOW_RECORD + ">, B PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">)" + + encodingClause()); + upsertLinkRow(conn, ACCOUNT, missing, "PAYLOAD"); + upsertLinkRow(conn, ACCOUNT, table, "A"); + upsertLinkRow(conn, ACCOUNT, table, "NOT_A_COLUMN"); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + assertDropDescriptorRejectedAsInUse(conn, DELIVERY_WINDOW_RECORD); + } + } + + @Test + public void createAndAddColumnRejectDescriptorDroppedBehindClientCache() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + ACCOUNT + ">)" + encodingClause()); + // Deleting the row directly leaves the client's cached descriptor in place. + try (Table descriptors = getUtility().getConnection() + .getTable(TableName.valueOf(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES))) { + descriptors.delete(new Delete(Bytes.toBytes(ACCOUNT))); + } + String rejected = uniqueTableName(); + assertFailsWithCode(conn, "CREATE TABLE " + rejected + + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + ACCOUNT + ">)" + encodingClause(), + SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND); + assertTableDoesNotExist(conn, rejected); + assertFailsWithCode(conn, "ALTER TABLE " + table + " ADD B PROTOBUF<" + ACCOUNT + ">", + SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND); + assertLinkRowCount(conn, ACCOUNT, rejected, 0); + assertLinkRowCount(conn, ACCOUNT, table, 1); + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + registerDescriptorsIdempotent(conn, ACCOUNT); + } + } + + @Test + public void linkTableUnavailableFailsCreateAndAlterButNotDrop() throws Exception { + TableName linkTable = + TableName.valueOf(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES); + Admin admin = getUtility().getAdmin(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + String retried = uniqueTableName(); + String create = "CREATE TABLE " + retried + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + + ACCOUNT + ">)" + encodingClause(); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + ACCOUNT + ">)" + encodingClause()); + admin.disableTable(linkTable); + try { + assertFailsWithCode(conn, create, SQLExceptionCode.UNABLE_TO_WRITE_PROTO_DESC_LINK); + assertFailsWithCode(conn, "ALTER TABLE " + table + " ADD B PROTOBUF<" + ACCOUNT + ">", + SQLExceptionCode.UNABLE_TO_WRITE_PROTO_DESC_LINK); + conn.createStatement().execute("DROP TABLE " + table); + } finally { + admin.enableTable(linkTable); + } + assertTableDoesNotExist(conn, retried); + assertLinkRowCount(conn, ACCOUNT, table, 1); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + + registerDescriptorsIdempotent(conn, ACCOUNT); + conn.createStatement().execute(create); + assertLinkRowCount(conn, ACCOUNT, retried, 1); + } + } + + @Test + public void linkRowsShareCellTimestampWithCatalogColumnRows() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, A PROTOBUF<" + ACCOUNT + + ">, B PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">)" + encodingClause()); + conn.createStatement() + .execute("ALTER TABLE " + table + " ADD C PROTOBUF<" + ACCOUNT + ">, D VARCHAR"); + + assertLinkTimestampMatchesCatalog(ACCOUNT, table, "A"); + assertLinkTimestampMatchesCatalog(DELIVERY_WINDOW_RECORD, table, "B"); + assertLinkTimestampMatchesCatalog(ACCOUNT, table, "C"); + } + } + + @Test + public void dropColumnRemovesLinksOfCoveringAndDroppedIndexes() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + String covering = generateUniqueName(); + String keyed = generateUniqueName(); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, NAME VARCHAR, A PROTOBUF<" + + ACCOUNT + ">, B PROTOBUF<" + DELIVERY_WINDOW_RECORD + ">)" + encodingClause()); + conn.createStatement() + .execute("CREATE INDEX " + covering + " ON " + table + "(NAME) INCLUDE(A, B)"); + conn.createStatement() + .execute("CREATE INDEX " + keyed + " ON " + table + "(NAME) INCLUDE(B)"); + assertLinkRowCount(conn, ACCOUNT, covering, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, covering, 1); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, keyed, 1); + + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN A"); + assertLinkRowCount(conn, ACCOUNT, table, 0); + assertLinkRowCount(conn, ACCOUNT, covering, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, covering, 1); + + conn.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN NAME"); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, covering, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, keyed, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, table, 1); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + } + } + + @Test + public void droppingViewInheritingProtobufButAddingNoneCleanupIsNoOp() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + String view = uniqueViewName(); + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, BASE_PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + conn.createStatement() + .execute("CREATE VIEW " + view + " (VIEW_LABEL VARCHAR) AS SELECT * FROM " + table); + + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, ACCOUNT, view, 0); + + conn.createStatement().execute("DROP VIEW " + view); + + assertLinkRowCount(conn, ACCOUNT, table, 1); + + try { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + fail("Base table's PROTOBUF column still references ACCOUNT"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE.getErrorCode(), e.getErrorCode()); + } + + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + } + } + + @Test + public void dropProtobufDescriptorAfterDroppingSaltedTableAndViewSucceeds() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT, DELIVERY_WINDOW_RECORD); + String table = uniqueTableName(); + String view = uniqueViewName(); + + conn.createStatement().execute( + "CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, BASE_PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause() + ", SALT_BUCKETS=4"); + conn.createStatement().execute("CREATE VIEW " + view + " (" + "VIEW_PAYLOAD PROTOBUF<" + + DELIVERY_WINDOW_RECORD + ">) AS SELECT * FROM " + table); + assertLinkRowCount(conn, ACCOUNT, table, 1); + assertLinkRowCount(conn, ACCOUNT, view, 0); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, view, 1); + + conn.createStatement().execute("DROP VIEW " + view); + assertLinkRowCount(conn, DELIVERY_WINDOW_RECORD, view, 0); + assertLinkRowCount(conn, ACCOUNT, table, 1); + + conn.createStatement().execute("DROP TABLE " + table); + assertLinkRowCount(conn, ACCOUNT, table, 0); + + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + DELIVERY_WINDOW_RECORD); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + assertFalse(isDescriptorRegistered(conn, DELIVERY_WINDOW_RECORD)); + } + } + + @Test + public void dropProtobufDescriptorAfterTenantScopedViewLifecycleSucceeds() throws Exception { + String tenantId = generateUniqueName(); + String table = uniqueTableName(); + String view = uniqueViewName(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "TENANT_ID VARCHAR NOT NULL, ID BIGINT NOT NULL, " + + "CONSTRAINT PK PRIMARY KEY (TENANT_ID, ID)) MULTI_TENANT=true," + encodingClause()); + } + try (Connection tenantConn = getTenantConnection(tenantId)) { + tenantConn.createStatement().execute("CREATE VIEW " + view + " (" + "TENANT_PAYLOAD PROTOBUF<" + + ACCOUNT + ">) AS SELECT * FROM " + table); + + assertLinkRowCountForTenant(tenantConn, ACCOUNT, view, tenantId, 1); + + tenantConn.createStatement().execute("DROP VIEW " + view); + assertLinkRowCountForTenant(tenantConn, ACCOUNT, view, tenantId, 0); + } + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement().execute("DROP TABLE " + table); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertFalse(isDescriptorRegistered(conn, ACCOUNT)); + } + } + + private static Connection getTenantConnection(String tenantId) throws SQLException { + Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); + props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId); + return DriverManager.getConnection(getUrl(), props); + } + + private static void assertLinkRowCountForTenant(Connection conn, String protobufName, + String tableName, String tenantId, int expected) throws SQLException { + String sql = "SELECT COUNT(*) FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA + "." + + "\"" + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE + "\"" + " WHERE " + + PhoenixDatabaseMetaData.PROTOBUF_NAME + " = ? AND " + PhoenixDatabaseMetaData.TENANT_ID + + " = ? AND " + PhoenixDatabaseMetaData.TABLE_NAME + " = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + ps.setString(2, tenantId); + ps.setString(3, tableName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(expected, rs.getInt(1)); + } + } + } + + @Test + public void qualifiedProtobufMessageNamePreservedCaseSensitive() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + conn.createStatement() + .execute("CREATE TABLE " + table + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + + ACCOUNT + ">)" + encodingClause()); + assertEquals(ACCOUNT, getProtoMessageName(conn, table, "PAYLOAD")); + } + } + + @Test + public void createIndexIfNotExistsRetryMatchesOriginalLinkRows() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + String table = uniqueTableName(); + String index = generateUniqueName(); + conn.createStatement() + .execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, NAME VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + encodingClause()); + String indexDdl = + "CREATE INDEX IF NOT EXISTS " + index + " ON " + table + "(NAME) INCLUDE(PAYLOAD)"; + conn.createStatement().execute(indexDdl); + int afterCreate = linkRowCount(conn, ACCOUNT, index); + conn.createStatement().execute(indexDdl); + assertEquals(afterCreate, linkRowCount(conn, ACCOUNT, index)); + conn.createStatement().execute("DROP INDEX " + index + " ON " + table); + assertLinkRowCount(conn, ACCOUNT, index, 0); + } + } + + @Test + public void tenantViewAlterAddProtobufColumnWritesTenantScopedLinkRow() throws Exception { + String tenantId = generateUniqueName(); + String table = uniqueTableName(); + String view = uniqueViewName(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + registerDescriptorsIdempotent(conn, ACCOUNT); + conn.createStatement() + .execute("CREATE TABLE " + table + " (" + "TENANT_ID VARCHAR NOT NULL, ID BIGINT NOT NULL, " + + "CONSTRAINT PK PRIMARY KEY (TENANT_ID, ID)) MULTI_TENANT=true," + encodingClause()); + } + try (Connection tenantConn = getTenantConnection(tenantId)) { + tenantConn.createStatement() + .execute("CREATE VIEW " + view + " (LABEL VARCHAR) AS SELECT * FROM " + table); + tenantConn.createStatement() + .execute("ALTER VIEW " + view + " ADD V1 PROTOBUF<" + ACCOUNT + ">"); + assertLinkRowCountForTenant(tenantConn, ACCOUNT, view, tenantId, 1); + tenantConn.createStatement().execute("DROP VIEW " + view); + } + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + assertLinkRowCount(conn, ACCOUNT, view, 0); + } + } + + private static void assertFailsWithCode(Connection conn, String sql, SQLExceptionCode code) { + try { + conn.createStatement().execute(sql); + fail("Expected " + code + " for: " + sql); + } catch (SQLException e) { + assertEquals(code.getErrorCode(), e.getErrorCode()); + } + } + + private static int linkRowCount(Connection conn, String protobufName, String tableName) + throws SQLException { + String sql = "SELECT COUNT(*) FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA + ".\"" + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE + "\" WHERE " + + PhoenixDatabaseMetaData.PROTOBUF_NAME + " = ? AND " + PhoenixDatabaseMetaData.TABLE_NAME + + " = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + ps.setString(2, tableName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + return rs.getInt(1); + } + } + } + + private static void upsertLinkRow(Connection conn, String protobufName, String tableName, + String columnName) throws SQLException { + String sql = "UPSERT INTO " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA + ".\"" + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE + "\"(" + + PhoenixDatabaseMetaData.PROTOBUF_NAME + "," + PhoenixDatabaseMetaData.TABLE_NAME + "," + + PhoenixDatabaseMetaData.COLUMN_FAMILY + "," + PhoenixDatabaseMetaData.COLUMN_NAME + + ") VALUES (?, ?, '0', ?)"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + ps.setString(2, tableName); + ps.setString(3, columnName); + ps.executeUpdate(); + } + conn.commit(); + } + + private static void assertLinkTimestampMatchesCatalog(String protobufName, String tableName, + String columnName) throws Exception { + try ( + Table links = getUtility().getConnection() + .getTable(TableName.valueOf(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_NAME_BYTES)); + Table catalog = getUtility().getConnection() + .getTable(TableName.valueOf(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES))) { + Result link = links.get(new Get(MetaDataUtil.getProtoDescLinkKey(Bytes.toBytes(protobufName), + null, null, Bytes.toBytes(tableName), Bytes.toBytes("0"), Bytes.toBytes(columnName)))); + Result column = + catalog.get(new Get(SchemaUtil.getColumnKey(null, null, tableName, columnName, "0"))); + assertFalse(link.isEmpty()); + assertEquals( + column.getColumnLatestCell(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES, + PhoenixDatabaseMetaData.PROTOBUF_DESCRIPTOR_NAME_BYTES).getTimestamp(), + link.rawCells()[0].getTimestamp()); + } + } + + private static void assertDropDescriptorRejectedAsInUse(Connection conn, String protobufName) { + try { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + protobufName); + fail("DROP PROTOBUF DESCRIPTOR must be rejected while a column references it"); + } catch (SQLException e) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_IN_USE.getErrorCode(), e.getErrorCode()); + } + } + + private static String getProtoMessageName(Connection conn, String tableName, String columnName) + throws SQLException { + PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); + PTable pTable = pconn.getTable(tableName); + try { + return pTable.getColumnForColumnName(columnName).getProtoMessageName(); + } catch (ColumnNotFoundException e) { + return null; + } + } + + private static void assertLinkRowCount(Connection conn, String protobufName, String tableName, + int expected) throws SQLException { + String sql = "SELECT COUNT(*) FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA + "." + + "\"" + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE + "\"" + " WHERE " + + PhoenixDatabaseMetaData.PROTOBUF_NAME + " = ? AND " + PhoenixDatabaseMetaData.TABLE_NAME + + " = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + ps.setString(2, tableName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(expected, rs.getInt(1)); + } + } + } + + private static boolean isDescriptorRegistered(Connection conn, String protobufName) + throws SQLException { + String sql = "SELECT 1 FROM " + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + + " WHERE " + PhoenixDatabaseMetaData.PROTOBUF_NAME + " = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + return rs.next(); + } + } + } + + private static void assertTableDoesNotExist(Connection conn, String tableName) { + try { + conn.unwrap(PhoenixConnection.class).getTableNoCache(null, tableName); + fail("Table " + tableName + " should not exist after rejected CREATE"); + } catch (TableNotFoundException expected) { + } catch (SQLException e) { + fail("Unexpected SQLException resolving " + tableName + ": " + e.getMessage()); + } + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufDescriptorDDLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufDescriptorDDLIT.java new file mode 100644 index 00000000000..d79503fd103 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtobufDescriptorDDLIT.java @@ -0,0 +1,1187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Admin; +import org.apache.hadoop.hbase.client.Table; +import org.apache.hadoop.hbase.client.TableDescriptor; +import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; +import org.apache.hadoop.hbase.ipc.ServerRpcController; +import org.apache.hadoop.hbase.regionserver.HRegion; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.AlterProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufBundleRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorMutationResponse; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorService; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.jdbc.PhoenixConnection; +import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistryHolder; +import org.apache.phoenix.protobuf.descriptor.ProtoDescriptorResolver; +import org.apache.phoenix.query.QueryConstants; +import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.PTable.ImmutableStorageScheme; +import org.apache.phoenix.schema.PTable.QualifierEncodingScheme; +import org.apache.phoenix.util.EnvironmentEdgeManager; +import org.apache.phoenix.util.PhoenixRuntime; +import org.apache.phoenix.util.PropertiesUtil; +import org.apache.phoenix.util.SchemaUtil; +import org.junit.After; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +@Category(ParallelStatsDisabledTest.class) +public class ProtobufDescriptorDDLIT extends ParallelStatsDisabledIT { + + private static final String BUNDLE_RESOURCE = "/protobuf/acmewidgets/acmewidgets_v1.desc"; + + private static final String ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + private static final String ACCOUNT_SYNC_RESPONSE = + "com.example.acmewidgets.account.v1.AccountSyncResponse"; + private static final String CATALOG_SYNC_HEADER = + "com.example.acmewidgets.common.v1.CatalogSyncHeader"; + private static final String DELIVERY_WINDOW_RECORD = + "com.example.acmewidgets.delivery.v1.DeliveryWindowRecord"; + private static final String TOKEN_REVOCATION = + "com.example.acmewidgets.auth.v1.proto2.TokenRevocation"; + private static final String CUSTOMER = "com.example.acmewidgets.orders.v1.Customer"; + private static final String COMMON_FILE = "widget_common.proto"; + private static final String UNKNOWN_MESSAGE = "com.example.acmewidgets.account.v1.NotInTheBundle"; + + private static final List KNOWN_FIXTURE_NAMES = Arrays.asList(ACCOUNT, + ACCOUNT_SYNC_RESPONSE, CATALOG_SYNC_HEADER, DELIVERY_WINDOW_RECORD, TOKEN_REVOCATION, CUSTOMER); + + private static String fixtureFileUrl() { + URL res = ProtobufDescriptorDDLIT.class.getResource(BUNDLE_RESOURCE); + assertNotNull("Test fixture " + BUNDLE_RESOURCE + " not on the classpath — Maven " + + "test-resources should have copied it from src/test/resources/", res); + return res.toString(); + } + + private Properties testProps() { + return PropertiesUtil.deepCopy(TEST_PROPERTIES); + } + + @After + public void cleanupDescriptors() throws SQLException { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Statement stmt = conn.createStatement()) { + for (String name : KNOWN_FIXTURE_NAMES) { + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + name); + } + } + } + + @Test + public void createDescriptorRoundTripsToSystemTable() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertSystemTableHasDescriptor(conn, ACCOUNT); + + String unpackaged = "U" + generateUniqueName(); + java.nio.file.Path fixture = writeFixture(FileDescriptorSet + .newBuilder().addFile(FileDescriptorProto.newBuilder().setName(unpackaged + ".proto") + .setSyntax("proto3").addMessageType(DescriptorProto.newBuilder().setName(unpackaged))) + .build()); + Properties scnProps = testProps(); + scnProps.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, + Long.toString(EnvironmentEdgeManager.currentTimeMillis())); + try (Connection scnConn = DriverManager.getConnection(getUrl(), scnProps)) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + unpackaged + " FROM '" + fixture.toUri() + "'"); + assertSystemTableHasDescriptor(conn, unpackaged); + assertNotNull( + scnConn.unwrap(PhoenixConnection.class).getProtoDescriptorRegistry().lookup(unpackaged)); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + unpackaged); + Files.deleteIfExists(fixture); + } + } + } + + @Test + public void createDescriptorIfNotExistsIsIdempotent() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String sql = + "CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"; + conn.createStatement().execute(sql); + conn.createStatement().execute(sql); + assertSystemTableHasDescriptor(conn, ACCOUNT); + } + } + + @Test + public void createDescriptorRejectsDuplicateWithoutIfNotExists() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + SQLException ex = expectSQLException(conn, + "CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_ALREADY_EXISTS.getErrorCode(), + ex.getErrorCode()); + + ex = expectSQLException(conn, "CREATE PROTOBUF BUNDLE (" + CUSTOMER + ", " + ACCOUNT + + ") FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_ALREADY_EXISTS.getErrorCode(), + ex.getErrorCode()); + assertSystemTableDoesNotHaveDescriptor(conn, CUSTOMER); + } + } + + @Test + public void createDescriptorRejectsNameNotInFixture() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + SQLException ex = expectSQLException(conn, + "CREATE PROTOBUF DESCRIPTOR " + UNKNOWN_MESSAGE + " FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE.getErrorCode(), + ex.getErrorCode()); + ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + UNKNOWN_MESSAGE + " FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE.getErrorCode(), + ex.getErrorCode()); + assertSystemTableDoesNotHaveDescriptor(conn, UNKNOWN_MESSAGE); + } + } + + @Test + public void alterDescriptorOverwritesRow() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + + conn.createStatement() + .execute("ALTER PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertSystemTableHasDescriptor(conn, ACCOUNT); + } + } + + @Test + public void alterDescriptorCompatibleEvolutionRoundTripsWithVerifiedNewShape() throws Exception { + String widget = "evolve.it.WidgetShape"; + java.nio.file.Path oldFixture = writeWidgetShapeFixture(null, Type.TYPE_INT32); + java.nio.file.Path evolvedFixture = writeWidgetShapeFixture("description", Type.TYPE_INT32); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + widget + " FROM '" + oldFixture.toUri() + "'"); + + Descriptors.Descriptor beforeAlter = readDescriptorFromSystemTable(conn, widget); + assertEquals("old descriptor has 2 fields", 2, beforeAlter.getFields().size()); + assertEquals(Descriptors.FieldDescriptor.Type.STRING, + beforeAlter.findFieldByName("id").getType()); + assertEquals(Descriptors.FieldDescriptor.Type.INT32, + beforeAlter.findFieldByName("count").getType()); + assertNull("old descriptor should not have 'description' yet", + beforeAlter.findFieldByName("description")); + + conn.createStatement().execute( + "ALTER PROTOBUF DESCRIPTOR " + widget + " FROM '" + evolvedFixture.toUri() + "'"); + + Descriptors.Descriptor afterAlter = readDescriptorFromSystemTable(conn, widget); + assertEquals("evolved descriptor has 3 fields (added 'description', kept id + count)", 3, + afterAlter.getFields().size()); + assertEquals("id preserved as STRING", Descriptors.FieldDescriptor.Type.STRING, + afterAlter.findFieldByName("id").getType()); + assertEquals("count preserved as INT32", Descriptors.FieldDescriptor.Type.INT32, + afterAlter.findFieldByName("count").getType()); + assertNotNull("description added", afterAlter.findFieldByName("description")); + assertEquals("description is STRING", Descriptors.FieldDescriptor.Type.STRING, + afterAlter.findFieldByName("description").getType()); + assertEquals("description tag = 3", 3, + afterAlter.findFieldByName("description").getNumber()); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + widget); + } + } finally { + Files.deleteIfExists(oldFixture); + Files.deleteIfExists(evolvedFixture); + } + } + + @Test + public void concurrentAltersAreValidatedAgainstEachOther() throws Exception { + String widget = "evolve.it.WidgetShape"; + List addedFields = Arrays.asList("description", "note"); + java.nio.file.Path oldFixture = writeWidgetShapeFixture(null, Type.TYPE_INT32); + List fixtures = + Arrays.asList(writeWidgetShapeFixture(addedFields.get(0), Type.TYPE_INT32), + writeWidgetShapeFixture(addedFields.get(1), Type.TYPE_INT32)); + ExecutorService pool = Executors.newFixedThreadPool(2); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + widget + " FROM '" + oldFixture.toUri() + "'"); + CyclicBarrier start = new CyclicBarrier(2); + List> results = new ArrayList<>(); + for (java.nio.file.Path fixture : fixtures) { + results.add(pool.submit(() -> { + try (Connection c = DriverManager.getConnection(getUrl(), testProps())) { + start.await(); + c.createStatement() + .execute("ALTER PROTOBUF DESCRIPTOR " + widget + " FROM '" + fixture.toUri() + "'"); + return 0; + } catch (SQLException e) { + return e.getErrorCode(); + } + })); + } + List codes = Arrays.asList(results.get(0).get(), results.get(1).get()); + assertTrue(codes.toString(), codes.contains(0)); + assertTrue(codes.toString(), + codes.contains(SQLExceptionCode.PROTOBUF_FIELD_RENAMED.getErrorCode())); + assertEquals(addedFields.get(codes.indexOf(0)), + readDescriptorFromSystemTable(conn, widget).findFieldByNumber(3).getName()); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + widget); + } + } finally { + pool.shutdownNow(); + Files.deleteIfExists(oldFixture); + for (java.nio.file.Path fixture : fixtures) { + Files.deleteIfExists(fixture); + } + } + } + + @Test + public void alterDescriptorDefaultValueChangeIsRejected() throws Exception { + String message = "evolve.it.WidgetDefault"; + java.nio.file.Path implicitFixture = writeWidgetDefaultFixture(null); + java.nio.file.Path explicitZeroFixture = writeWidgetDefaultFixture("0"); + java.nio.file.Path changedFixture = writeWidgetDefaultFixture("6"); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement().execute( + "CREATE PROTOBUF DESCRIPTOR " + message + " FROM '" + implicitFixture.toUri() + "'"); + conn.createStatement().execute( + "ALTER PROTOBUF DESCRIPTOR " + message + " FROM '" + explicitZeroFixture.toUri() + "'"); + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + message + " FROM '" + changedFixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DEFAULT_VALUE_CHANGE.getErrorCode(), + ex.getErrorCode()); + assertTrue(ex.getMessage(), ex.getMessage().contains("count")); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + message); + } + } finally { + Files.deleteIfExists(implicitFixture); + Files.deleteIfExists(explicitZeroFixture); + Files.deleteIfExists(changedFixture); + } + } + + @Test + public void alterDescriptorNewFirstEnumValueChangesDefaultAndIsRejected() throws Exception { + String message = "evolve.it.WidgetColor"; + java.nio.file.Path oldFixture = writeWidgetColorFixture(false); + java.nio.file.Path newFixture = writeWidgetColorFixture(true); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + message + " FROM '" + oldFixture.toUri() + "'"); + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + message + " FROM '" + newFixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DEFAULT_VALUE_CHANGE.getErrorCode(), + ex.getErrorCode()); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + message); + } + } finally { + Files.deleteIfExists(oldFixture); + Files.deleteIfExists(newFixture); + } + } + + @Test + public void alterDescriptorTypeWideningIsRejected() throws Exception { + String widget = "evolve.it.WidgetShape"; + java.nio.file.Path oldFixture = writeWidgetShapeFixture(null, Type.TYPE_INT32); + java.nio.file.Path widenedFixture = writeWidgetShapeFixture(null, Type.TYPE_INT64); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + widget + " FROM '" + oldFixture.toUri() + "'"); + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + widget + " FROM '" + widenedFixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE.getErrorCode(), + ex.getErrorCode()); + assertTrue(ex.getMessage(), ex.getMessage().contains("count")); + assertEquals(Descriptors.FieldDescriptor.Type.INT32, + readDescriptorFromSystemTable(conn, widget).findFieldByName("count").getType()); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + widget); + } + } finally { + Files.deleteIfExists(oldFixture); + Files.deleteIfExists(widenedFixture); + } + } + + @Test + public void alterAcmeWidgetsTokenRevocationCompatibleEvolutionRoundTrips() throws Exception { + String newFieldName = "audit_trail_id"; + int newFieldTag = 5; + java.nio.file.Path evolvedFixture = + writeTokenRevocationWithAddedField(newFieldName, newFieldTag); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement().execute( + "CREATE PROTOBUF DESCRIPTOR " + TOKEN_REVOCATION + " FROM '" + fixtureFileUrl() + "'"); + + Descriptors.Descriptor beforeAlter = readDescriptorFromSystemTable(conn, TOKEN_REVOCATION); + assertEquals("old TokenRevocation has 4 declared fields", 4, + beforeAlter.getFields().size()); + assertNotNull(beforeAlter.findFieldByName("tenant_id")); + assertNotNull(beforeAlter.findFieldByName("token_id")); + assertNotNull(beforeAlter.findFieldByName("reason")); + assertNotNull(beforeAlter.findFieldByName("soft_revoke")); + assertNull("audit_trail_id should not exist yet", + beforeAlter.findFieldByName(newFieldName)); + + conn.createStatement().execute("ALTER PROTOBUF DESCRIPTOR " + TOKEN_REVOCATION + " FROM '" + + evolvedFixture.toUri() + "'"); + + Descriptors.Descriptor afterAlter = readDescriptorFromSystemTable(conn, TOKEN_REVOCATION); + assertEquals("evolved TokenRevocation has 5 declared fields", 5, + afterAlter.getFields().size()); + assertNotNull("tenant_id preserved", afterAlter.findFieldByName("tenant_id")); + assertNotNull("token_id preserved", afterAlter.findFieldByName("token_id")); + assertNotNull("reason preserved", afterAlter.findFieldByName("reason")); + assertNotNull("soft_revoke preserved", afterAlter.findFieldByName("soft_revoke")); + Descriptors.FieldDescriptor auditField = afterAlter.findFieldByName(newFieldName); + assertNotNull("audit_trail_id added", auditField); + assertEquals("audit_trail_id type is STRING", Descriptors.FieldDescriptor.Type.STRING, + auditField.getType()); + assertEquals("audit_trail_id tag is 5", newFieldTag, auditField.getNumber()); + assertFalse("audit_trail_id is optional (proto2 default for new fields)", + auditField.isRequired()); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + TOKEN_REVOCATION); + } + } finally { + Files.deleteIfExists(evolvedFixture); + } + } + + @Test + public void protoValueDescriptorRefreshAfterAlterReturnsNewField() throws Exception { + String widget = "evolve.it.WidgetShape"; + java.nio.file.Path oldFixture = writeWidgetShapeFixture(null, Type.TYPE_INT32); + java.nio.file.Path newFixture = writeWidgetShapeFixture("description", Type.TYPE_INT32); + Descriptors.Descriptor oldDesc = buildLocalDescriptor(oldFixture, "WidgetShape"); + Descriptors.Descriptor newDesc = buildLocalDescriptor(newFixture, "WidgetShape"); + String table = generateUniqueName(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + widget + " FROM '" + oldFixture.toUri() + "'"); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + widget + ">)"); + String[] oldIds = { "w1", "w2", "w3", "w4", "w5", "w6" }; + int[] oldCounts = { 10, 20, 30, 40, 50, 60 }; + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + for (int i = 0; i < oldIds.length; i++) { + byte[] oldPayload = + DynamicMessage.newBuilder(oldDesc).setField(oldDesc.findFieldByName("id"), oldIds[i]) + .setField(oldDesc.findFieldByName("count"), oldCounts[i]).build().toByteArray(); + ps.setLong(1, i + 1L); + ps.setBytes(2, oldPayload); + ps.execute(); + } + } + conn.commit(); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'id', 'VARCHAR'), " + + "PROTO_VALUE(PAYLOAD, 'count', 'INTEGER') FROM " + table + " ORDER BY ID ASC")) { + for (int i = 0; i < oldIds.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(i + 1L, rs.getLong(1)); + assertEquals(oldIds[i], rs.getString(2)); + assertEquals(oldCounts[i], rs.getInt(3)); + } + assertFalse(rs.next()); + } + conn.createStatement() + .execute("ALTER PROTOBUF DESCRIPTOR " + widget + " FROM '" + newFixture.toUri() + "'"); + String[] newIds = { "n1", "n2", "n3", "n4", "n5", "n6" }; + String[] descriptions = { "d-a", "d-b", "d-c", "d-d", "d-e", "d-f" }; + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + for (int i = 0; i < newIds.length; i++) { + byte[] newPayload = + DynamicMessage.newBuilder(newDesc).setField(newDesc.findFieldByName("id"), newIds[i]) + .setField(newDesc.findFieldByName("count"), 1000 + i) + .setField(newDesc.findFieldByName("description"), descriptions[i]).build() + .toByteArray(); + ps.setLong(1, 10L + i); + ps.setBytes(2, newPayload); + ps.execute(); + } + } + conn.commit(); + try (Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT ID, PROTO_VALUE(PAYLOAD, 'description', 'VARCHAR') FROM " + + table + " WHERE PROTO_VALUE(PAYLOAD, 'description', 'VARCHAR') IS NOT NULL" + + " ORDER BY ID ASC")) { + for (int i = 0; i < descriptions.length; i++) { + assertTrue("row " + i, rs.next()); + assertEquals(10L + i, rs.getLong(1)); + assertEquals(descriptions[i], rs.getString(2)); + } + assertFalse(rs.next()); + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + widget); + } + } + } finally { + Files.deleteIfExists(oldFixture); + Files.deleteIfExists(newFixture); + } + } + + @Test + public void queryAndIndexOnFieldAddedElsewhereReloadDescriptor() throws Exception { + // Unique name, so the per-name forced-refresh rate limit is not shared with other tests. + String messageName = "W" + generateUniqueName(); + String fqName = "refresh.it." + messageName; + FileDescriptorSet v1 = refreshFixture(messageName, false); + FileDescriptorSet v2 = refreshFixture(messageName, true); + Descriptors.Descriptor v2Desc = + Descriptors.FileDescriptor.buildFrom(v2.getFile(0), new Descriptors.FileDescriptor[0]) + .findMessageTypeByName(messageName); + String table = generateUniqueName(); + String index = generateUniqueName(); + java.nio.file.Path v1File = Files.createTempFile("refresh-it-v1-", ".desc"); + Files.write(v1File, v1.toByteArray()); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + fqName + " FROM '" + v1File.toUri() + "'"); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID BIGINT NOT NULL PRIMARY KEY, PAYLOAD PROTOBUF<" + fqName + ">)"); + upsertPayload(conn, table, 1, refreshPayload(v2Desc, "w1", null)); + // Warm the cache with v1 on both the compile and the scan path. + try (ResultSet rs = conn.createStatement() + .executeQuery("SELECT PROTO_VALUE(PAYLOAD, 'id', 'VARCHAR') FROM " + table)) { + assertTrue(rs.next()); + assertEquals("w1", rs.getString(1)); + } + assertNull(cachedField(fqName, "note")); + + try (PreparedStatement ps = conn + .prepareStatement("UPSERT INTO " + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + + " (PROTOBUF_NAME, FILE_DESCRIPTOR_SET) VALUES (?, ?)")) { + ps.setString(1, fqName); + ps.setBytes(2, v2.toByteArray()); + ps.executeUpdate(); + } + conn.commit(); + assertNull("cache still holds v1", cachedField(fqName, "note")); + + upsertPayload(conn, table, 2, refreshPayload(v2Desc, "w2", "n2")); + try (ResultSet rs = conn.createStatement().executeQuery( + "SELECT ID FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, 'note', 'VARCHAR') = 'n2'")) { + assertTrue(rs.next()); + assertEquals(2L, rs.getLong(1)); + assertFalse(rs.next()); + } + assertNotNull("cache reloaded to v2", cachedField(fqName, "note")); + + conn.createStatement().execute( + "CREATE INDEX " + index + " ON " + table + " (PROTO_VALUE(PAYLOAD, 'note', 'VARCHAR'))"); + // Index maintenance evaluates the new field on the region server. + upsertPayload(conn, table, 3, refreshPayload(v2Desc, "w3", "n3")); + String byNote = "SELECT /*+ INDEX(" + table + " " + index + ") */ ID FROM " + table + + " WHERE PROTO_VALUE(PAYLOAD, 'note', 'VARCHAR') = 'n3'"; + try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + byNote)) { + StringBuilder plan = new StringBuilder(); + while (rs.next()) { + plan.append(rs.getString(1)).append('\n'); + } + assertTrue(plan.toString(), plan.toString().contains(index)); + } + try (ResultSet rs = conn.createStatement().executeQuery(byNote)) { + assertTrue(rs.next()); + assertEquals(3L, rs.getLong(1)); + assertFalse(rs.next()); + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + fqName); + } + } + } finally { + Files.deleteIfExists(v1File); + } + } + + private static Descriptors.FieldDescriptor cachedField(String fqName, String field) + throws SQLException { + ProtoDescriptorRegistry registry = ProtoDescriptorRegistryHolder.getIfInstalled(); + assertNotNull(registry); + ProtoDescriptorRegistry.CachedDescriptor cached = registry.lookup(fqName); + assertNotNull(cached); + return cached.getDescriptor().findFieldByName(field); + } + + private static void upsertPayload(Connection conn, String table, long id, byte[] payload) + throws SQLException { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + table + " (ID, PAYLOAD) VALUES (?, ?)")) { + ps.setLong(1, id); + ps.setBytes(2, payload); + ps.executeUpdate(); + } + conn.commit(); + } + + private static byte[] refreshPayload(Descriptors.Descriptor desc, String id, String note) { + DynamicMessage.Builder b = + DynamicMessage.newBuilder(desc).setField(desc.findFieldByName("id"), id); + if (note != null) { + b.setField(desc.findFieldByName("note"), note); + } + return b.build().toByteArray(); + } + + private static FileDescriptorSet refreshFixture(String messageName, boolean withNote) { + DescriptorProto.Builder msg = DescriptorProto.newBuilder().setName(messageName) + .addField(FieldDescriptorProto.newBuilder().setName("id").setNumber(1) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()); + if (withNote) { + msg.addField(FieldDescriptorProto.newBuilder().setName("note").setNumber(2) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()); + } + return FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("refresh_" + messageName + ".proto") + .setPackage("refresh.it").setSyntax("proto3").addMessageType(msg)) + .build(); + } + + private static Descriptors.Descriptor buildLocalDescriptor(java.nio.file.Path fixture, + String messageName) throws Exception { + FileDescriptorSet set = FileDescriptorSet.parseFrom(Files.readAllBytes(fixture)); + + Descriptors.FileDescriptor file = + Descriptors.FileDescriptor.buildFrom(set.getFile(0), new Descriptors.FileDescriptor[0]); + return file.findMessageTypeByName(messageName); + } + + @Test + public void alterDescriptorIncompatibleEvolutionIsRejected() throws Exception { + String widget = "evolve.it.Widget"; + java.nio.file.Path oldFixture = writeMinimalWidgetFixture("id"); + java.nio.file.Path newFixture = writeMinimalWidgetFixture(null); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + try { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + widget + " FROM '" + oldFixture.toUri() + "'"); + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + widget + " FROM '" + newFixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED.getErrorCode(), + ex.getErrorCode()); + + assertTrue("SQLException message should reference removed field 'id': " + ex.getMessage(), + ex.getMessage().contains("id")); + + assertSystemTableHasDescriptor(conn, widget); + } finally { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + widget); + } + } finally { + Files.deleteIfExists(oldFixture); + Files.deleteIfExists(newFixture); + } + } + + @Test + public void alterDescriptorRejectsTypeChangeInImportedMessage() throws Exception { + FileDescriptorSet.Builder evolved = FileDescriptorSet.newBuilder(); + for (FileDescriptorProto file : loadBundleSet().getFileList()) { + if (!COMMON_FILE.equals(file.getName())) { + evolved.addFile(file); + continue; + } + FileDescriptorProto.Builder common = file.toBuilder(); + for (DescriptorProto.Builder msg : common.getMessageTypeBuilderList()) { + if ("WarehouseEndpoint".equals(msg.getName())) { + msg.getFieldBuilder(0).setType(Type.TYPE_INT64); + } + } + evolved.addFile(common); + } + java.nio.file.Path newFixture = writeFixture(evolved.build()); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + CUSTOMER + " FROM '" + fixtureFileUrl() + "'"); + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + CUSTOMER + " FROM '" + newFixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE.getErrorCode(), + ex.getErrorCode()); + assertTrue(ex.getMessage(), ex.getMessage().contains("WarehouseEndpoint")); + assertTrue(ex.getMessage(), ex.getMessage().contains("warehouse_id")); + assertEquals(loadBundleSet(), FileDescriptorSet.parseFrom(storedBytes(conn, CUSTOMER))); + } finally { + Files.deleteIfExists(newFixture); + } + } + + @Test + public void createRejectsSetWithMissingImport() throws Exception { + FileDescriptorSet.Builder withoutCommon = FileDescriptorSet.newBuilder(); + for (FileDescriptorProto file : loadBundleSet().getFileList()) { + if (!COMMON_FILE.equals(file.getName())) { + withoutCommon.addFile(file); + } + } + java.nio.file.Path fixture = writeFixture(withoutCommon.build()); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + SQLException ex = expectSQLException(conn, + "CREATE PROTOBUF DESCRIPTOR " + CUSTOMER + " FROM '" + fixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED.getErrorCode(), + ex.getErrorCode()); + assertTrue(ex.getMessage(), ex.getMessage().contains(COMMON_FILE)); + assertSystemTableDoesNotHaveDescriptor(conn, CUSTOMER); + + ex = expectSQLException(conn, "CREATE PROTOBUF BUNDLE (" + ACCOUNT + ", " + CUSTOMER + + ") FROM '" + fixture.toUri() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED.getErrorCode(), + ex.getErrorCode()); + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + assertSystemTableDoesNotHaveDescriptor(conn, CUSTOMER); + } finally { + Files.deleteIfExists(fixture); + } + } + + @Test + public void alterDescriptorIfExistsMissingIsNoOp() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement().execute( + "ALTER PROTOBUF DESCRIPTOR IF EXISTS " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + } + } + + @Test + public void alterDescriptorRejectsMissingWithoutIfExists() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + SQLException ex = expectSQLException(conn, + "ALTER PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + ex.getErrorCode()); + } + } + + @Test + public void dropDescriptorRemovesRow() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + assertSystemTableHasDescriptor(conn, ACCOUNT); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + } + } + + @Test + public void dropDescriptorIfExistsMissingIsNoOp() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR IF EXISTS " + ACCOUNT); + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + } + } + + @Test + public void dropDescriptorRejectsMissingWithoutIfExists() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + SQLException ex = expectSQLException(conn, "DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_NOT_FOUND.getErrorCode(), + ex.getErrorCode()); + } + } + + @Test + public void dropDescriptorMakesZeroReadsAgainstSystemCatalog() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + + long readsBefore = countReadsOnSystemCatalog(); + conn.createStatement().execute("DROP PROTOBUF DESCRIPTOR " + ACCOUNT); + long readsAfter = countReadsOnSystemCatalog(); + + assertEquals( + "DROP PROTOBUF DESCRIPTOR must not trigger any reads against " + + "SYSTEM.CATALOG (the in-use probe targets SYSTEM.PROTO_DESC_LINK; the descriptor " + + "delete targets SYSTEM.PROTO_DESCRIPTORS). delta=" + (readsAfter - readsBefore), + readsBefore, readsAfter); + } + } + + @Test + public void createBundleRegistersAllNamesAtomically() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement().execute("CREATE PROTOBUF BUNDLE (" + ACCOUNT + ", " + + ACCOUNT_SYNC_RESPONSE + ", " + CATALOG_SYNC_HEADER + ") FROM '" + fixtureFileUrl() + "'"); + assertSystemTableHasDescriptor(conn, ACCOUNT); + assertSystemTableHasDescriptor(conn, ACCOUNT_SYNC_RESPONSE); + assertSystemTableHasDescriptor(conn, CATALOG_SYNC_HEADER); + } + } + + @Test + public void createBundleRejectsAtomicallyOnAnyNameMissing() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + SQLException ex = expectSQLException(conn, "CREATE PROTOBUF BUNDLE (" + ACCOUNT + ", " + + UNKNOWN_MESSAGE + ", " + CATALOG_SYNC_HEADER + ") FROM '" + fixtureFileUrl() + "'"); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE.getErrorCode(), + ex.getErrorCode()); + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + assertSystemTableDoesNotHaveDescriptor(conn, CATALOG_SYNC_HEADER); + } + } + + @Test + public void createBundleIfNotExistsSkipsAlreadyRegistered() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + fixtureFileUrl() + "'"); + conn.createStatement().execute("CREATE PROTOBUF BUNDLE IF NOT EXISTS (" + ACCOUNT + ", " + + ACCOUNT_SYNC_RESPONSE + ") FROM '" + fixtureFileUrl() + "'"); + assertSystemTableHasDescriptor(conn, ACCOUNT); + assertSystemTableHasDescriptor(conn, ACCOUNT_SYNC_RESPONSE); + } + } + + @Test + public void systemProtoDescriptorsHasNonEncodedQualifiersAndOneCellPerColumn() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + conn.createStatement() + .executeQuery( + "SELECT * FROM " + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " LIMIT 1") + .close(); + + PTable pTable = conn.unwrap(PhoenixConnection.class) + .getTable(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME); + assertEquals( + "SYSTEM.PROTO_DESCRIPTORS encoding scheme must stay on NON_ENCODED for " + + "ProtobufDescriptorEndpointImpl.buildDescriptorPut to write Phoenix-readable cells", + QualifierEncodingScheme.NON_ENCODED_QUALIFIERS, pTable.getEncodingScheme()); + assertEquals( + "SYSTEM.PROTO_DESCRIPTORS storage scheme must stay on ONE_CELL_PER_COLUMN " + + "for the data + empty-KV cells to be written separately", + ImmutableStorageScheme.ONE_CELL_PER_COLUMN, pTable.getImmutableStorageScheme()); + } + } + + @Test + public void systemProtoDescriptorsIsPinnedToSingleRegion() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps()); + Admin admin = conn.unwrap(PhoenixConnection.class).getQueryServices().getAdmin()) { + TableName tableName = + SchemaUtil.getPhysicalName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, + conn.unwrap(PhoenixConnection.class).getQueryServices().getProps()); + TableDescriptor descriptor = admin.getDescriptor(tableName); + + assertEquals( + "SYSTEM.PROTO_DESCRIPTORS must declare SystemProtoDescriptorsSplitPolicy " + + "(see QueryConstants.SYSTEM_PROTO_DESCRIPTORS_SPLIT_POLICY_CLASSNAME + " + + "SystemProtoDescriptorsSplitPolicy Javadoc for the rationale)", + QueryConstants.SYSTEM_PROTO_DESCRIPTORS_SPLIT_POLICY_CLASSNAME, + descriptor.getRegionSplitPolicyClassName()); + + int regionCount = admin.getRegions(tableName).size(); + assertEquals("SYSTEM.PROTO_DESCRIPTORS must have exactly one region (split policy is " + + "DisabledRegionSplitPolicy-backed); found " + regionCount, 1, regionCount); + } + } + + @Test + public void descriptorDdlRejectsNonLocalUrls() throws Exception { + String hdfsUrl = hdfsFixtureUrl(); + String localPath = Paths.get(new URI(fixtureFileUrl())).toString(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + for (String url : new String[] { hdfsUrl, "s3a://bucket/acmewidgets_v1.desc", + "abfs://container@account.dfs.core.windows.net/acmewidgets_v1.desc", localPath, + "file://otherhost" + localPath }) { + assertUrlNotAllowed(conn, "CREATE PROTOBUF DESCRIPTOR " + ACCOUNT + " FROM '" + url + "'"); + assertUrlNotAllowed(conn, + "ALTER PROTOBUF DESCRIPTOR IF EXISTS " + ACCOUNT + " FROM '" + url + "'"); + assertUrlNotAllowed(conn, "CREATE PROTOBUF BUNDLE (" + ACCOUNT + ", " + + DELIVERY_WINDOW_RECORD + ") FROM '" + url + "'"); + } + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + } + } + + @Test + public void serverRejectsRequestsWithoutInlineBytes() throws Throwable { + // A client that skips the local read and sends only a URL must not get the region + // server to fetch it, even for a URL the server could read. + String hdfsUrl = hdfsFixtureUrl(); + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + for (String url : new String[] { hdfsUrl, fixtureFileUrl() }) { + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED.getErrorCode(), + invokeRaw(conn, ACCOUNT, + (svc, c, + cb) -> svc.createProtobufDescriptor(c, CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName(ACCOUNT).setSourceUrl(url).setIfNotExists(false).build(), cb)) + .getErrorCode()); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED.getErrorCode(), + invokeRaw(conn, ACCOUNT, + (svc, c, + cb) -> svc.alterProtobufDescriptor(c, AlterProtobufDescriptorRequest.newBuilder() + .setProtobufName(ACCOUNT).setSourceUrl(url).setIfExists(true).build(), cb)) + .getErrorCode()); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED.getErrorCode(), + invokeRaw(conn, ACCOUNT, + (svc, c, + cb) -> svc.createProtobufBundle(c, CreateProtobufBundleRequest.newBuilder() + .addProtobufNames(ACCOUNT).setSourceUrl(url).setIfNotExists(false).build(), cb)) + .getErrorCode()); + } + assertSystemTableDoesNotHaveDescriptor(conn, ACCOUNT); + } + } + + @FunctionalInterface + private interface RawCall { + void run(ProtobufDescriptorService svc, ServerRpcController controller, + CoprocessorRpcUtils.BlockingRpcCallback cb); + } + + private static ProtobufDescriptorMutationResponse invokeRaw(Connection conn, String rowKey, + RawCall call) throws Throwable { + PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); + byte[] key = Bytes.toBytes(rowKey); + try (Table table = pconn.getQueryServices().getTable( + SchemaUtil.getPhysicalName(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME_BYTES, + pconn.getQueryServices().getProps()).getName())) { + Map results = + table.coprocessorService(ProtobufDescriptorService.class, key, key, svc -> { + ServerRpcController controller = new ServerRpcController(); + CoprocessorRpcUtils.BlockingRpcCallback cb = + new CoprocessorRpcUtils.BlockingRpcCallback<>(); + call.run(svc, controller, cb); + if (controller.getFailedOn() != null) { + throw controller.getFailedOn(); + } + return cb.get(); + }); + assertEquals(1, results.size()); + return results.values().iterator().next(); + } + } + + private static void assertUrlNotAllowed(Connection conn, String sql) { + SQLException ex = expectSQLException(conn, sql); + assertEquals(sql, SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED.getErrorCode(), + ex.getErrorCode()); + } + + private static volatile String cachedHdfsFixtureUrl; + private static final Object HDFS_INIT_LOCK = new Object(); + + private static String hdfsFixtureUrl() throws Exception { + if (cachedHdfsFixtureUrl != null) { + return cachedHdfsFixtureUrl; + } + synchronized (HDFS_INIT_LOCK) { + if (cachedHdfsFixtureUrl != null) { + return cachedHdfsFixtureUrl; + } + FileSystem hdfsFs = getUtility().getDFSCluster().getFileSystem(); + Path hdfsTarget = new Path(hdfsFs.getHomeDirectory(), "protobuf/acmewidgets_v1.desc"); + Path hdfsDir = hdfsTarget.getParent(); + if (!hdfsFs.exists(hdfsDir)) { + hdfsFs.mkdirs(hdfsDir); + } + if (!hdfsFs.exists(hdfsTarget)) { + URL localUrl = ProtobufDescriptorDDLIT.class.getResource(BUNDLE_RESOURCE); + assertNotNull("Local fixture " + BUNDLE_RESOURCE + " missing from test classpath", + localUrl); + + Path localPath = new Path(localUrl.getPath()); + hdfsFs.copyFromLocalFile(localPath, hdfsTarget); + } + cachedHdfsFixtureUrl = hdfsFs.makeQualified(hdfsTarget).toString(); + return cachedHdfsFixtureUrl; + } + } + + private void assertSystemTableHasDescriptor(Connection conn, String protobufName) + throws SQLException { + try (PreparedStatement ps = conn.prepareStatement("SELECT FILE_DESCRIPTOR_SET FROM " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " WHERE PROTOBUF_NAME = ?")) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue("Expected row for descriptor '" + protobufName + "' in " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME, rs.next()); + byte[] bytes = rs.getBytes(1); + assertNotNull(bytes); + assertTrue("FILE_DESCRIPTOR_SET cell for '" + protobufName + "' must be non-empty " + + "(the server's Put landed at the right qualifier)", bytes.length > 0); + } + } + } + + private void assertSystemTableDoesNotHaveDescriptor(Connection conn, String protobufName) + throws SQLException { + try (PreparedStatement ps = conn.prepareStatement("SELECT 1 FROM " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " WHERE PROTOBUF_NAME = ?")) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + assertFalse("Did not expect a row for descriptor '" + protobufName + "' in " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME, rs.next()); + } + } + } + + private long countReadsOnSystemCatalog() { + TableName tableName = TableName.valueOf(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME); + long total = 0; + for (HRegion region : getUtility().getMiniHBaseCluster().getRegions(tableName)) { + total += region.getReadRequestsCount(); + } + return total; + } + + private static SQLException expectSQLException(Connection conn, String sql) { + try { + conn.createStatement().execute(sql); + fail("Expected SQLException for: " + sql); + return null; + } catch (SQLException e) { + return e; + } + } + + private static FileDescriptorSet loadBundleSet() throws Exception { + return FileDescriptorSet.parseFrom(Files.readAllBytes(Paths.get(new URI(fixtureFileUrl())))); + } + + private static java.nio.file.Path writeFixture(FileDescriptorSet set) throws Exception { + java.nio.file.Path temp = Files.createTempFile("bundle-variant-", ".desc"); + Files.write(temp, set.toByteArray()); + return temp; + } + + private static byte[] storedBytes(Connection conn, String protobufName) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement("SELECT FILE_DESCRIPTOR_SET FROM " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " WHERE PROTOBUF_NAME = ?")) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + return rs.getBytes(1); + } + } + } + + private static java.nio.file.Path writeMinimalWidgetFixture(String stringFieldName) + throws Exception { + DescriptorProto.Builder msg = DescriptorProto.newBuilder().setName("Widget"); + if (stringFieldName != null) { + msg.addField(FieldDescriptorProto.newBuilder().setName(stringFieldName).setNumber(1) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(FileDescriptorProto.newBuilder() + .setName("evolve.proto").setPackage("evolve.it").setSyntax("proto3").addMessageType(msg)) + .build(); + java.nio.file.Path temp = Files.createTempFile("evolve-it-widget-", ".desc"); + Files.write(temp, set.toByteArray()); + return temp; + } + + private static java.nio.file.Path writeWidgetDefaultFixture(String defaultValue) + throws Exception { + FieldDescriptorProto.Builder count = FieldDescriptorProto.newBuilder().setName("count") + .setNumber(1).setType(Type.TYPE_INT32).setLabel(Label.LABEL_OPTIONAL); + if (defaultValue != null) { + count.setDefaultValue(defaultValue); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("evolve_default.proto") + .setPackage("evolve.it").setSyntax("proto2") + .addMessageType(DescriptorProto.newBuilder().setName("WidgetDefault").addField(count))) + .build(); + java.nio.file.Path temp = Files.createTempFile("evolve-it-widgetdefault-", ".desc"); + Files.write(temp, set.toByteArray()); + return temp; + } + + private static java.nio.file.Path writeWidgetColorFixture(boolean newFirstValue) + throws Exception { + EnumDescriptorProto.Builder color = EnumDescriptorProto.newBuilder().setName("Color") + .addValue(EnumValueDescriptorProto.newBuilder().setName("RED").setNumber(1)); + if (newFirstValue) { + color.clearValue() + .addValue(EnumValueDescriptorProto.newBuilder().setName("GREEN").setNumber(0)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("RED").setNumber(1)); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(FileDescriptorProto.newBuilder() + .setName("evolve_color.proto").setPackage("evolve.it").setSyntax("proto2").addEnumType(color) + .addMessageType(DescriptorProto.newBuilder().setName("WidgetColor") + .addField(FieldDescriptorProto.newBuilder().setName("color").setNumber(1) + .setType(Type.TYPE_ENUM).setTypeName(".evolve.it.Color").setLabel(Label.LABEL_OPTIONAL)))) + .build(); + java.nio.file.Path temp = Files.createTempFile("evolve-it-widgetcolor-", ".desc"); + Files.write(temp, set.toByteArray()); + return temp; + } + + private static java.nio.file.Path writeWidgetShapeFixture(String addedField, Type countType) + throws Exception { + DescriptorProto.Builder msg = DescriptorProto.newBuilder().setName("WidgetShape") + .addField(FieldDescriptorProto.newBuilder().setName("id").setNumber(1) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()) + .addField(FieldDescriptorProto.newBuilder().setName("count").setNumber(2).setType(countType) + .setLabel(Label.LABEL_OPTIONAL).build()); + if (addedField != null) { + msg.addField(FieldDescriptorProto.newBuilder().setName(addedField).setNumber(3) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(FileDescriptorProto.newBuilder() + .setName("evolve.proto").setPackage("evolve.it").setSyntax("proto3").addMessageType(msg)) + .build(); + java.nio.file.Path temp = Files.createTempFile( + addedField != null ? "evolve-it-widgetshape-evolved-" : "evolve-it-widgetshape-old-", + ".desc"); + Files.write(temp, set.toByteArray()); + return temp; + } + + private static java.nio.file.Path writeTokenRevocationWithAddedField(String fieldName, + int fieldTag) throws Exception { + byte[] originalBytes; + try (InputStream in = ProtobufDescriptorDDLIT.class.getResourceAsStream(BUNDLE_RESOURCE)) { + assertNotNull("acmewidgets_v1.desc not on classpath", in); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) { + baos.write(buf, 0, n); + } + originalBytes = baos.toByteArray(); + } + FileDescriptorSet originalSet = FileDescriptorSet.parseFrom(originalBytes); + + FileDescriptorSet.Builder evolvedSet = FileDescriptorSet.newBuilder(); + boolean modified = false; + for (FileDescriptorProto file : originalSet.getFileList()) { + if ("voucher_revocation_sync.proto".equals(file.getName())) { + evolvedSet.addFile(addFieldToTokenRevocation(file, fieldName, fieldTag)); + modified = true; + } else { + evolvedSet.addFile(file); + } + } + assertTrue("voucher_revocation_sync.proto must be present in acmewidgets_v1.desc", modified); + java.nio.file.Path temp = Files.createTempFile("token-revocation-evolved-", ".desc"); + Files.write(temp, evolvedSet.build().toByteArray()); + return temp; + } + + private static FileDescriptorProto addFieldToTokenRevocation(FileDescriptorProto original, + String fieldName, int fieldTag) { + FileDescriptorProto.Builder fileBuilder = original.toBuilder().clearMessageType(); + for (DescriptorProto msg : original.getMessageTypeList()) { + if ("TokenRevocation".equals(msg.getName())) { + DescriptorProto updated = msg + .toBuilder().addField(FieldDescriptorProto.newBuilder().setName(fieldName) + .setNumber(fieldTag).setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).build()) + .build(); + fileBuilder.addMessageType(updated); + } else { + fileBuilder.addMessageType(msg); + } + } + return fileBuilder.build(); + } + + private static Descriptors.Descriptor readDescriptorFromSystemTable(Connection conn, + String protobufName) throws Exception { + byte[] storedBytes = null; + try (PreparedStatement ps = conn.prepareStatement("SELECT FILE_DESCRIPTOR_SET FROM " + + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_NAME + " WHERE PROTOBUF_NAME = ?")) { + ps.setString(1, protobufName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue("Expected row for descriptor '" + protobufName + "'", rs.next()); + storedBytes = rs.getBytes(1); + assertNotNull("FILE_DESCRIPTOR_SET cell must not be null", storedBytes); + } + } + Descriptors.Descriptor resolved = + new ProtoDescriptorResolver().resolve(storedBytes, protobufName); + assertNotNull("Stored bytes for '" + protobufName + "' must resolve to a top-level " + + "message with that name", resolved); + return resolved; + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java index 53adfd85543..f55dd6e1c32 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java @@ -201,6 +201,16 @@ public void testTableMetadataScan() throws SQLException { assertEquals(SYSTEM_MUTEX_TABLE_NAME, rs.getString("TABLE_NAME")); assertTrue(rs.next()); assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM")); + assertEquals(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_TABLE, + rs.getString("TABLE_NAME")); + assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); + assertTrue(rs.next()); + assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM")); + assertEquals(PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE, + rs.getString("TABLE_NAME")); + assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); + assertTrue(rs.next()); + assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM")); assertEquals(TYPE_SEQUENCE, rs.getString("TABLE_NAME")); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); @@ -430,9 +440,11 @@ public void testShowTables() throws SQLException { tables.add(rs.getString("TABLE_NAME")); assertEquals("SYSTEM", rs.getString("TABLE_SCHEM")); } - assertEquals(12, tables.size()); + assertEquals(14, tables.size()); assertTrue(tables.contains("CATALOG")); assertTrue(tables.contains("FUNCTION")); + assertTrue(tables.contains("PROTO_DESCRIPTORS")); + assertTrue(tables.contains("PROTO_DESC_LINK")); tables.clear(); // Add a filter on the table name. diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SkipSystemTablesExistenceCheckIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SkipSystemTablesExistenceCheckIT.java index 3568628ec72..8f62ac9798a 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SkipSystemTablesExistenceCheckIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SkipSystemTablesExistenceCheckIT.java @@ -68,7 +68,8 @@ public class SkipSystemTablesExistenceCheckIT { new HashSet<>(Arrays.asList("SYSTEM.CATALOG", "SYSTEM.SEQUENCE", "SYSTEM.STATS", "SYSTEM.FUNCTION", "SYSTEM.MUTEX", "SYSTEM.LOG", "SYSTEM.CHILD_LINK", "SYSTEM.TASK", "SYSTEM.TRANSFORM", "SYSTEM.CDC_STREAM_STATUS", "SYSTEM.CDC_STREAM", "SYSTEM.IDX_CDC_TRACKER", - "SYSTEM.PHOENIX_INDEX_TOOL_RESULT", "SYSTEM.PHOENIX_INDEX_TOOL")); + "SYSTEM.PHOENIX_INDEX_TOOL_RESULT", "SYSTEM.PHOENIX_INDEX_TOOL", "SYSTEM.PROTO_DESCRIPTORS", + "SYSTEM.PROTO_DESC_LINK")); private static class PhoenixSystemTablesCreationTestDriver extends PhoenixTestDriver { private static ConnectionQueryServices cqs; diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SystemTablesCreationOnConnectionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SystemTablesCreationOnConnectionIT.java index 5d1cb86a2bb..c527670e05b 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SystemTablesCreationOnConnectionIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SystemTablesCreationOnConnectionIT.java @@ -108,13 +108,15 @@ public class SystemTablesCreationOnConnectionIT { new HashSet<>(Arrays.asList("SYSTEM.CATALOG", "SYSTEM.SEQUENCE", "SYSTEM.STATS", "SYSTEM.FUNCTION", "SYSTEM.MUTEX", "SYSTEM.LOG", "SYSTEM.CHILD_LINK", "SYSTEM.TASK", "SYSTEM.TRANSFORM", "SYSTEM.CDC_STREAM_STATUS", "SYSTEM.CDC_STREAM", "SYSTEM.IDX_CDC_TRACKER", - "SYSTEM.PHOENIX_INDEX_TOOL_RESULT", "SYSTEM.PHOENIX_INDEX_TOOL")); + "SYSTEM.PHOENIX_INDEX_TOOL_RESULT", "SYSTEM.PHOENIX_INDEX_TOOL", "SYSTEM.PROTO_DESCRIPTORS", + "SYSTEM.PROTO_DESC_LINK")); private static final Set PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES = new HashSet<>(Arrays.asList("SYSTEM:CATALOG", "SYSTEM:SEQUENCE", "SYSTEM:STATS", "SYSTEM:FUNCTION", "SYSTEM:MUTEX", "SYSTEM:LOG", "SYSTEM:CHILD_LINK", "SYSTEM:TASK", "SYSTEM:TRANSFORM", "SYSTEM:CDC_STREAM_STATUS", "SYSTEM:CDC_STREAM", "SYSTEM:IDX_CDC_TRACKER", - "SYSTEM:PHOENIX_INDEX_TOOL_RESULT", "SYSTEM:PHOENIX_INDEX_TOOL")); + "SYSTEM:PHOENIX_INDEX_TOOL_RESULT", "SYSTEM:PHOENIX_INDEX_TOOL", "SYSTEM:PROTO_DESCRIPTORS", + "SYSTEM:PROTO_DESC_LINK")); private static class PhoenixSysCatCreationServices extends ConnectionQueryServicesImpl { diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java index 338daf1e3cc..872ee352e4d 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java @@ -587,6 +587,12 @@ public void testTableMetadataScan() throws Exception { assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_MUTEX_TABLE_NAME, PTableType.SYSTEM); assertTrue(rs.next()); + assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESCRIPTORS_TABLE, PTableType.SYSTEM); + assertTrue(rs.next()); + assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, + PhoenixDatabaseMetaData.SYSTEM_PROTO_DESC_LINK_TABLE, PTableType.SYSTEM); + assertTrue(rs.next()); assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.TYPE_SEQUENCE, PTableType.SYSTEM); assertTrue(rs.next()); diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/transform/ProtobufColumnTransformIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/transform/ProtobufColumnTransformIT.java new file mode 100644 index 00000000000..49dcd5a5420 --- /dev/null +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/transform/ProtobufColumnTransformIT.java @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.end2end.transform; + +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.apache.phoenix.coprocessor.tasks.TransformMonitorTask; +import org.apache.phoenix.end2end.ParallelStatsDisabledIT; +import org.apache.phoenix.end2end.ParallelStatsDisabledTest; +import org.apache.phoenix.jdbc.PhoenixConnection; +import org.apache.phoenix.mapreduce.util.PhoenixConfigurationUtilHelper; +import org.apache.phoenix.protobuf.text.AcmeWidgetsFixtures; +import org.apache.phoenix.query.QueryServices; +import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.transform.SystemTransformRecord; +import org.apache.phoenix.schema.transform.Transform; +import org.apache.phoenix.util.PropertiesUtil; +import org.apache.phoenix.util.ReadOnlyProps; +import org.apache.phoenix.util.SchemaUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import org.apache.phoenix.thirdparty.com.google.common.collect.Maps; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FileDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +/** + * A storage-format transform rewrites every column's SYSTEM.CATALOG row at cutover. The PROTOBUF + * descriptor binding must survive that rewrite, and PROTOBUF payloads must stay readable through + * every phase: before the transform, during dual-write, after the copy and after cutover. + */ +@Category(ParallelStatsDisabledTest.class) +public class ProtobufColumnTransformIT extends ParallelStatsDisabledIT { + private static final String ACCOUNT = "com.example.acmewidgets.account.v1.Account"; + + // Expected payload fields of rows 1..5, indexed by ID - 1. + private static final String[] ALL_TENANTS = + { "tenant-alpha", "tenant-beta", "tenant-gamma", "tenant-delta", "tenant-epsilon" }; + private static final boolean[] ALL_ACTIVE = { true, false, true, true, false }; + private static final String[] ALL_WAREHOUSES = { "wh-1", "wh-2", null, "wh-4", "wh-5" }; + + private static Map descriptorGraph; + + @BeforeClass + public static synchronized void setup() throws Exception { + TransformMonitorTask.disableTransformMonitorTask(true); + Map serverProps = Maps.newHashMapWithExpectedSize(1); + serverProps.put(PhoenixConfigurationUtilHelper.TRANSFORM_MONITOR_ENABLED, + Boolean.FALSE.toString()); + Map clientProps = Maps.newHashMapWithExpectedSize(1); + clientProps.put(PhoenixConfigurationUtilHelper.TRANSFORM_MONITOR_ENABLED, + Boolean.FALSE.toString()); + clientProps.put(QueryServices.DEFAULT_UPDATE_CACHE_FREQUENCY_ATRRIB, "0"); + setUpTestDriver(new ReadOnlyProps(serverProps.entrySet().iterator()), + new ReadOnlyProps(clientProps.entrySet().iterator())); + descriptorGraph = AcmeWidgetsFixtures.loadAndBuildDescriptorGraph(); + } + + @AfterClass + public static synchronized void cleanup() { + TransformMonitorTask.disableTransformMonitorTask(false); + } + + @Test + public void protoFunctionsWorkAcrossStorageFormatTransform() throws Exception { + String schemaName = generateUniqueName(); + String tableName = generateUniqueName(); + String fullTableName = SchemaUtil.getTableName(schemaName, tableName); + Descriptor account = AcmeWidgetsFixtures.accountDescriptor(descriptorGraph); + try (Connection conn = + DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES))) { + conn.setAutoCommit(true); + conn.createStatement().execute("CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + ACCOUNT + + " FROM '" + AcmeWidgetsFixtures.bundleFileUrl() + "'"); + conn.createStatement() + .execute("CREATE TABLE " + fullTableName + + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ACCOUNT + ">)" + + " IMMUTABLE_ROWS=true, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN," + + " COLUMN_ENCODED_BYTES=NONE"); + upsertAccount(conn, fullTableName, 1L, + AcmeWidgetsFixtures.newAccount(account, "tenant-alpha", "Alpha", true, "wh-1")); + upsertAccount(conn, fullTableName, 2L, + AcmeWidgetsFixtures.newAccount(account, "tenant-beta", "Beta", false, "wh-2")); + upsertAccount(conn, fullTableName, 3L, + DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("tenant_key"), "tenant-gamma") + .setField(account.findFieldByName("active"), true).build()); + assertProtoReads(conn, fullTableName, 1L, 2L, 3L); + + conn.createStatement().execute("ALTER TABLE " + fullTableName + + " SET IMMUTABLE_STORAGE_SCHEME=SINGLE_CELL_ARRAY_WITH_OFFSETS, COLUMN_ENCODED_BYTES=2"); + SystemTransformRecord record = Transform.getTransformRecord(schemaName, tableName, null, null, + conn.unwrap(PhoenixConnection.class)); + assertNotNull(record); + upsertAccount(conn, fullTableName, 4L, + AcmeWidgetsFixtures.newAccount(account, "tenant-delta", "Delta", true, "wh-4")); + assertProtoReads(conn, fullTableName, 1L, 2L, 3L, 4L); + + TransformToolIT.runTransformTool(TransformToolIT.getArgList(schemaName, tableName, null, null, + null, null, false, false, false, false, false).toArray(new String[0]), 0); + Transform.doCutover(conn.unwrap(PhoenixConnection.class), record); + Transform.updateTransformRecord(conn.unwrap(PhoenixConnection.class), record, + PTable.TransformStatus.COMPLETED); + + assertEquals(ACCOUNT, catalogDescriptorName(conn, schemaName, tableName, "PAYLOAD")); + PTable table = conn.unwrap(PhoenixConnection.class).getTableNoCache(fullTableName); + assertEquals(PTable.ImmutableStorageScheme.SINGLE_CELL_ARRAY_WITH_OFFSETS, + table.getImmutableStorageScheme()); + assertEquals(ACCOUNT, table.getColumnForColumnName("PAYLOAD").getProtoMessageName()); + } + + // A fresh connection plans against the post-cutover catalog rows, not a cached PTable. + try (Connection conn = + DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES))) { + assertProtoReads(conn, fullTableName, 1L, 2L, 3L, 4L); + conn.setAutoCommit(true); + upsertAccount(conn, fullTableName, 5L, + AcmeWidgetsFixtures.newAccount(account, "tenant-epsilon", "Epsilon", false, "wh-5")); + // Predicates are not checked here: rows written after cutover are not marked verified, so + // a filtered scan of the new physical table returns them regardless of the filter. + assertProtoProjections(conn, fullTableName, 1L, 2L, 3L, 4L, 5L); + } + } + + private static void upsertAccount(Connection conn, String fullTableName, long id, + DynamicMessage payload) throws Exception { + try (PreparedStatement ps = + conn.prepareStatement("UPSERT INTO " + fullTableName + " VALUES (?, ?, ?)")) { + ps.setLong(1, id); + ps.setString(2, "c" + id); + ps.setBytes(3, payload.toByteArray()); + ps.executeUpdate(); + } + } + + private static void assertProtoReads(Connection conn, String fullTableName, Long... ids) + throws Exception { + assertProtoProjections(conn, fullTableName, ids); + assertIds(conn, + "SELECT ID FROM " + fullTableName + + " WHERE PROTO_VALUE(PAYLOAD, 'active', 'BOOLEAN') = TRUE ORDER BY ID", + Arrays.stream(ids).filter(id -> ALL_ACTIVE[(int) (id - 1)]).toArray(Long[]::new)); + assertIds(conn, + "SELECT ID FROM " + fullTableName + + " WHERE PROTO_EXISTS(PAYLOAD, 'home_warehouse') = TRUE ORDER BY ID", + Arrays.stream(ids).filter(id -> ALL_WAREHOUSES[(int) (id - 1)] != null).toArray(Long[]::new)); + } + + private static void assertProtoProjections(Connection conn, String fullTableName, Long... ids) + throws Exception { + try (ResultSet rs = conn.createStatement() + .executeQuery("SELECT ID, C1, PROTO_VALUE(PAYLOAD, 'tenant_key', 'VARCHAR')," + + " PROTO_VALUE(PAYLOAD, 'active', 'BOOLEAN')," + + " PROTO_VALUE(PAYLOAD, 'home_warehouse', 'VARCHAR') FROM " + fullTableName + + " ORDER BY ID")) { + for (long id : ids) { + int i = (int) id - 1; + assertTrue(rs.next()); + assertEquals(id, rs.getLong(1)); + assertEquals("c" + id, rs.getString(2)); + assertEquals(ALL_TENANTS[i], rs.getString(3)); + assertEquals(ALL_ACTIVE[i], rs.getBoolean(4)); + assertEquals(ALL_WAREHOUSES[i], rs.getString(5)); + } + assertFalse(rs.next()); + } + } + + private static void assertIds(Connection conn, String sql, Long... expected) throws Exception { + List actual = new ArrayList<>(); + try (ResultSet rs = conn.createStatement().executeQuery(sql)) { + while (rs.next()) { + actual.add(rs.getLong(1)); + } + } + assertEquals(sql, Arrays.asList(expected), actual); + } + + private static String catalogDescriptorName(Connection conn, String schemaName, String tableName, + String columnName) throws Exception { + try (PreparedStatement ps = conn.prepareStatement("SELECT PROTOBUF_DESCRIPTOR_NAME" + + " FROM SYSTEM.CATALOG WHERE TENANT_ID IS NULL AND TABLE_SCHEM = ? AND TABLE_NAME = ?" + + " AND COLUMN_NAME = ? AND COLUMN_FAMILY IS NOT NULL")) { + ps.setString(1, schemaName); + ps.setString(2, tableName); + ps.setString(3, columnName); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + String name = rs.getString(1); + assertFalse(rs.next()); + return name; + } + } + } +} diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java index 7ee3f49b9b3..11a7e0add91 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java @@ -26,6 +26,8 @@ import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection; import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithStatement; import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup; +import static org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry.CACHE_TTL_SECONDS_ATTRIB; +import static org.apache.phoenix.protobuf.descriptor.ProtoDescriptorRegistry.MIN_FORCED_REFRESH_INTERVAL_MS_ATTRIB; import static org.apache.phoenix.query.BaseTest.extractThreadPoolExecutorFromCQSI; import static org.apache.phoenix.query.QueryServices.CQSI_THREAD_POOL_ALLOW_CORE_THREAD_TIMEOUT; import static org.apache.phoenix.query.QueryServices.CQSI_THREAD_POOL_CORE_POOL_SIZE; @@ -42,11 +44,16 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.nio.file.Files; +import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; @@ -57,12 +64,15 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; +import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest; import org.apache.phoenix.exception.FailoverSQLException; +import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole; import org.apache.phoenix.monitoring.MetricType; import org.apache.phoenix.query.ConnectionQueryServices; import org.apache.phoenix.query.ConnectionQueryServicesImpl; +import org.apache.phoenix.util.EnvironmentEdgeManager; import org.apache.phoenix.util.PhoenixRuntime; import org.junit.After; import org.junit.AfterClass; @@ -77,6 +87,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; + /** * Test failover basics for {@link FailoverPhoenixConnection}. */ @@ -104,6 +119,11 @@ public static void setUpBeforeClass() throws Exception { Integer.MAX_VALUE); CLUSTERS.getHBaseCluster2().getConfiguration().setInt(INDEX_CDC_CONSUMER_STARTUP_DELAY_MS, Integer.MAX_VALUE); + for (HBaseTestingUtility cluster : Arrays.asList(CLUSTERS.getHBaseCluster1(), + CLUSTERS.getHBaseCluster2())) { + cluster.getConfiguration().setLong(CACHE_TTL_SECONDS_ATTRIB, 2); + cluster.getConfiguration().setLong(MIN_FORCED_REFRESH_INTERVAL_MS_ATTRIB, 3_600_000); + } CLUSTERS.start(); DriverManager.registerDriver(PhoenixDriver.INSTANCE); } @@ -525,6 +545,114 @@ public void testFailoverConnectionExplicitly() throws Exception { doTestBasicOperationsWithConnection(conn, tableName, haGroupName); } + @Test(timeout = 300000) + public void testProtobufDescriptorLoadsFromActiveClusterAfterFailover() throws Exception { + String name = "ha." + haGroupName; + String table = "PB_" + tableName; + // f1 = "a", f2 = "b" + byte[] payload = { 0x0A, 0x01, 'a', 0x12, 0x01, 'b' }; + List fixtures = new ArrayList<>(); + try { + for (int cluster = 1; cluster <= 2; cluster++) { + Path fixture = writeDescriptorFixture(name, cluster); + fixtures.add(fixture); + try (Connection conn = CLUSTERS.getClusterConnection(cluster, haGroup)) { + conn.createStatement() + .execute("CREATE PROTOBUF DESCRIPTOR " + name + " FROM '" + fixture.toUri() + "'"); + conn.createStatement().execute("CREATE TABLE " + table + + " (ID INTEGER PRIMARY KEY, PAYLOAD PROTOBUF<" + name + ">) REPLICATION_SCOPE=0"); + PreparedStatement ps = conn.prepareStatement("UPSERT INTO " + table + " VALUES (1, ?)"); + ps.setBytes(1, payload); + ps.execute(); + conn.commit(); + conn.unwrap(PhoenixConnection.class).getQueryServices().clearCache(); + } + } + try (Connection conn = createFailoverConnection()) { + assertEquals(CLUSTERS.getJdbcUrl1(haGroup), + conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL()); + assertEquals("a", protoValue(conn, table, "f1")); + // The JVM-wide cache may still hold cluster 2's descriptor from its CREATE TABLE. + waitFor(() -> isFieldNotFound(conn, table, "f2"), 100, 10_000); + + // The miss above used up the forced refresh, so only TTL expiry can reveal f2. + CLUSTERS.transitClusterRole(haGroup, ClusterRole.STANDBY, ClusterRole.ACTIVE); + FailoverPhoenixConnection.failover(conn, 30_000); + waitFor(() -> "b".equals(protoValueOrNull(conn, table, "f2")), 100, 10_000); + try (Connection newConn = createFailoverConnection()) { + assertEquals(CLUSTERS.getJdbcUrl2(haGroup), + newConn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL()); + assertEquals("b", protoValue(newConn, table, "f2")); + } + + // Cluster 2's descriptor serves until TTL expiry; every reload after that is cluster 1's. + CLUSTERS.transitClusterRole(haGroup, ClusterRole.ACTIVE, ClusterRole.STANDBY); + FailoverPhoenixConnection.failover(conn, 30_000); + waitFor(() -> isFieldNotFound(conn, table, "f2"), 100, 10_000); + long end = EnvironmentEdgeManager.currentTimeMillis() + 10_000; + while (EnvironmentEdgeManager.currentTimeMillis() < end) { + assertTrue(isFieldNotFound(conn, table, "f2")); + Thread.sleep(100); + } + } + try (Connection newConn = createFailoverConnection()) { + assertEquals(CLUSTERS.getJdbcUrl1(haGroup), + newConn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL()); + assertEquals("a", protoValue(newConn, table, "f1")); + assertTrue(isFieldNotFound(newConn, table, "f2")); + } + } finally { + for (Path fixture : fixtures) { + Files.deleteIfExists(fixture); + } + } + } + + private static String protoValueOrNull(Connection conn, String table, String field) { + try { + return protoValue(conn, table, field); + } catch (SQLException e) { + return null; + } + } + + private static boolean isFieldNotFound(Connection conn, String table, String field) { + try { + protoValue(conn, table, field); + return false; + } catch (SQLException e) { + return e.getErrorCode() == SQLExceptionCode.PROTOBUF_PATH_FIELD_NOT_FOUND.getErrorCode(); + } + } + + /** Writes a descriptor for {@code name} with string fields f1 through f{@code fieldCount}. */ + private static Path writeDescriptorFixture(String name, int fieldCount) throws Exception { + String pkg = name.substring(0, name.lastIndexOf('.')); + DescriptorProto.Builder message = + DescriptorProto.newBuilder().setName(name.substring(pkg.length() + 1)); + for (int i = 1; i <= fieldCount; i++) { + message.addField(FieldDescriptorProto.newBuilder().setName("f" + i).setNumber(i) + .setType(FieldDescriptorProto.Type.TYPE_STRING)); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(FileDescriptorProto.newBuilder() + .setName(name + ".proto").setPackage(pkg).setSyntax("proto3").addMessageType(message)) + .build(); + Path fixture = Files.createTempFile("ha-descriptor-", ".desc"); + Files.write(fixture, set.toByteArray()); + return fixture; + } + + private static String protoValue(Connection conn, String table, String field) + throws SQLException { + try (ResultSet rs = conn.createStatement().executeQuery( + "SELECT PROTO_VALUE(PAYLOAD, '" + field + "', 'VARCHAR') FROM " + table + " ORDER BY ID")) { + assertTrue(rs.next()); + String value = rs.getString(1); + assertFalse(rs.next()); + return value; + } + } + /** * Test that it times out to failover explicitly when two clusters are STANDBY. */ diff --git a/phoenix-core/src/it/java/org/apache/phoenix/schema/tool/SchemaToolExtractionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/schema/tool/SchemaToolExtractionIT.java index 097ea96f4c0..d855bc53c74 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/schema/tool/SchemaToolExtractionIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/schema/tool/SchemaToolExtractionIT.java @@ -39,6 +39,7 @@ import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.parse.ParseException; import org.apache.phoenix.parse.SQLParser; +import org.apache.phoenix.protobuf.text.AcmeWidgetsFixtures; import org.apache.phoenix.schema.PTable; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; @@ -72,6 +73,23 @@ public void testCreateTableStatement() throws Exception { Assert.assertEquals(createTableStmt, result.toUpperCase()); } + @Test + public void testCreateTableStatementWithProtobufColumn() throws Exception { + String tableName = generateUniqueName(); + String schemaName = generateUniqueName(); + String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); + String messageName = "com.example.acmewidgets.account.v1.Account"; + String createTableStmt = + "CREATE TABLE " + pTableFullName + "(K VARCHAR NOT NULL PRIMARY KEY, V1 PROTOBUF<" + + messageName + ">)" + " IMMUTABLE_STORAGE_SCHEME='ONE_CELL_PER_COLUMN'"; + List queries = new ArrayList<>(); + queries.add("CREATE PROTOBUF DESCRIPTOR IF NOT EXISTS " + messageName + " FROM '" + + AcmeWidgetsFixtures.bundleFileUrl() + "'"); + queries.add(createTableStmt); + String result = runSchemaExtractionTool(schemaName, tableName, null, queries); + Assert.assertEquals(createTableStmt, result); + } + @Test public void testCreateTableStatementLowerCase() throws Exception { String tableName = "lowecasetbl1"; diff --git a/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java b/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java index a0bfb49d311..dbfc335332d 100644 --- a/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java +++ b/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java @@ -1086,4 +1086,367 @@ public void testBinaryLiteral() throws Exception { parseQueryThatShouldFail( "SELECT b, x from x WHERE x = " + "b'0 10 ' --comment \n /* comment */ '00 000' \n \n ''"); } + + private void assertSqlExceptionCode(String sql, SQLExceptionCode expectedCode) + throws IOException { + try { + parseQuery(sql); + fail("Expected SQLException with code " + expectedCode.getErrorCode() + " (" + expectedCode + + ") parsing: " + sql); + } catch (SQLException e) { + assertEquals("Wrong SQLException code for: " + sql + " (got: " + e.getMessage() + ")", + expectedCode.getErrorCode(), e.getErrorCode()); + } + } + + private void assertProtobufColumnParses(String sql, String expectedMessageName) + throws IOException, SQLException { + CreateTableStatement stmt = parseQuery(sql, CreateTableStatement.class); + assertNotNull("CREATE TABLE parse returned null for: " + sql, stmt); + ColumnDef found = null; + for (ColumnDef def : stmt.getColumnDefs()) { + if (def.getProtoMessageName() != null) { + found = def; + break; + } + } + assertNotNull("No PROTOBUF column def found in parsed statement for: " + sql, found); + assertEquals( + "Parsed proto message name should preserve the source spelling exactly for: " + sql, + expectedMessageName, found.getProtoMessageName()); + } + + private void assertAlterAddProtobufColumnParses(String sql, String expectedMessageName) + throws IOException, SQLException { + AddColumnStatement stmt = parseQuery(sql, AddColumnStatement.class); + assertNotNull("ALTER TABLE parse returned null for: " + sql, stmt); + ColumnDef found = null; + for (ColumnDef def : stmt.getColumnDefs()) { + if (def.getProtoMessageName() != null) { + found = def; + break; + } + } + assertNotNull("No PROTOBUF column def found in parsed ALTER statement for: " + sql, found); + assertEquals( + "Parsed proto message name should preserve the source spelling exactly for: " + sql, + expectedMessageName, found.getProtoMessageName()); + } + + @Test + public void testProtobufWithoutMessageNameRejects() throws Exception { + assertSqlExceptionCode("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, payload PROTOBUF)", + SQLExceptionCode.PROTOBUF_MESSAGE_NAME_REQUIRED); + } + + @Test + public void testProtobufEmptyAngleBracketsRejects() throws Exception { + assertSqlExceptionCode("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, payload PROTOBUF<>)", + SQLExceptionCode.PROTOBUF_MESSAGE_NAME_REQUIRED); + } + + @Test + public void testProtobufStringLiteralAsNameRejects() throws Exception { + assertSqlExceptionCode("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, payload PROTOBUF<'x'>)", + SQLExceptionCode.PARSER_ERROR); + } + + @Test + public void testProtobufArrayRejected() throws Exception { + assertSqlExceptionCode( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, payloads PROTOBUF ARRAY)", + SQLExceptionCode.PROTOBUF_NOT_ALLOWED_IN_ARRAY); + assertSqlExceptionCode( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, payloads PROTOBUF[])", + SQLExceptionCode.PROTOBUF_NOT_ALLOWED_IN_ARRAY); + } + + @Test + public void testProtobufRejectedAsPrimaryKey() throws Exception { + assertSqlExceptionCode("CREATE TABLE t (payload PROTOBUF PRIMARY KEY)", + SQLExceptionCode.PROTOBUF_NOT_ALLOWED_AS_PRIMARY_KEY); + } + + @Test + public void testAlterTableAddColumnProtobufHitsSameParseAndRejectionPaths() throws Exception { + assertAlterAddProtobufColumnParses("ALTER TABLE t ADD payload PROTOBUF", + "my.org.OrderV1"); + assertSqlExceptionCode("ALTER TABLE t ADD payload PROTOBUF", + SQLExceptionCode.PROTOBUF_MESSAGE_NAME_REQUIRED); + assertSqlExceptionCode("ALTER TABLE t ADD payloads PROTOBUF ARRAY", + SQLExceptionCode.PROTOBUF_NOT_ALLOWED_IN_ARRAY); + } + + @Test + public void testProtobufKeywordIsCaseInsensitive() throws Exception { + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p Protobuf)", "my.org.X"); + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p protobuf)", "my.org.X"); + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p pRoToBuF)", "my.org.X"); + } + + @Test + public void testProtobufWithPrecisionParensParses() throws Exception { + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF(10))", "my.org.X"); + } + + @Test + public void testProtobufArrayWithExplicitSizeRejects() throws Exception { + assertSqlExceptionCode( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, ps PROTOBUF[5])", + SQLExceptionCode.PROTOBUF_NOT_ALLOWED_IN_ARRAY); + } + + @Test + public void testProtobufMessageNameIsCasePreservedEndToEnd() throws Exception { + String[] proofs = { "my.org.OrderV1", "MY.ORG.ORDER", "my.org.order", "MyOrg.MyMessage_Type_v2", + "alllower", "ALLUPPER", "Mix_Of_Cases_AND_digits_123" }; + for (String name : proofs) { + String sql = "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF<" + name + ">)"; + assertProtobufColumnParses(sql, name); + } + } + + @Test + public void testProtobufKeywordCaseFoldsButMessageNameDoesNot() throws Exception { + String sql = + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, " + "payload pRoToBuF)"; + assertProtobufColumnParses(sql, "MyMixedCaseName"); + } + + @Test + public void testProtobufWithReservedKeywordIdentifiersInName() throws Exception { + String[] names = + { "Group", "Order", "Type", "Name", "Index", "View", "Default", "True", "False" }; + for (String name : names) { + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF)", + "my." + name); + } + } + + @Test + public void testProtobufAcceptsBroadSamplingOfPhoenixReservedKeywords() throws Exception { + String[] keywords = { "Select", "Insert", "Upsert", "Update", "Delete", "Create", "Drop", + "Alter", "Truncate", + + "From", "Where", "Group", "Having", "Order", "Limit", "Offset", "Fetch", "Union", "Distinct", + "Join", "Inner", "Outer", "Left", "Right", "Full", "On", "Between", "In", "Exists", + + "Null", "True", "False", + + "Table", "Column", "Index", "View", "Schema", "Constraint", "Primary", "Key", "Sequence", + "Function", "Cursor", "Trace", "Cast", "Default", + + "Type", "Name", "Value", "Values", "Row", "Rows", "Array", "Some", "Any", "All", + + "Row_Timestamp", "Encoded_Qualifier", "Column_Qualifier_Counter", "Update_Only", + "Idx_Mutations", "Data_Row_State", "Defaultvalue", + + "Hint", "Async", "Disable", "Rebuild", "Local", "Constant", "Replace", "List", "Immutable", + "Grant", "Revoke", "Show", "Uncovered", "Regions", "Noverify", "Cdc", "Preserve", "Splits", + "Consistency", "Eventual", "Strong" }; + for (String keyword : keywords) { + String sql = + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF)"; + assertProtobufColumnParses(sql, "my.org." + keyword); + } + } + + @Test + public void testAlterProtobufDescriptorIfExistsParses() throws Exception { + AlterProtobufDescriptorStatement stmt = + parseQuery("ALTER PROTOBUF DESCRIPTOR IF EXISTS my.org.OrderV1 FROM 'file:///x.desc'", + AlterProtobufDescriptorStatement.class); + assertEquals("my.org.OrderV1", stmt.getProtoMessageName()); + assertTrue("IF EXISTS must propagate to AST", stmt.isIfExists()); + assertEquals("file:///x.desc", stmt.getSourceUrl()); + } + + @Test + public void testProtobufDescriptorMissingFromRejected() throws Exception { + parseQueryThatShouldFailWithSQLException("CREATE PROTOBUF DESCRIPTOR my.org.X"); + parseQueryThatShouldFailWithSQLException("ALTER PROTOBUF DESCRIPTOR my.org.X"); + } + + @Test + public void testAlterProtobufDescriptorRejectsIfNotExists() throws Exception { + parseQueryThatShouldFailWithSQLException( + "ALTER PROTOBUF DESCRIPTOR IF NOT EXISTS my.org.X FROM 'file:///x.desc'"); + } + + @Test + public void testProtobufDescriptorStatementsHaveCorrectOperationKind() throws Exception { + CreateProtobufDescriptorStatement create = + parseQuery("CREATE PROTOBUF DESCRIPTOR my.org.X FROM 'file:///x.desc'", + CreateProtobufDescriptorStatement.class); + assertEquals("CREATE PROTOBUF DESCRIPTOR maps to UPSERT (matches CreateSchemaStatement)", + Operation.UPSERT, create.getOperation()); + + AlterProtobufDescriptorStatement alter = + parseQuery("ALTER PROTOBUF DESCRIPTOR my.org.X FROM 'file:///x.desc'", + AlterProtobufDescriptorStatement.class); + assertEquals("ALTER PROTOBUF DESCRIPTOR maps to UPSERT (matches AlterTableStatement)", + Operation.UPSERT, alter.getOperation()); + + DropProtobufDescriptorStatement drop = + parseQuery("DROP PROTOBUF DESCRIPTOR my.org.X", DropProtobufDescriptorStatement.class); + assertEquals("DROP PROTOBUF DESCRIPTOR must map to DELETE (matches DropTable/Schema/Index)", + Operation.DELETE, drop.getOperation()); + } + + @Test + public void testDropProtobufDescriptorParses() throws Exception { + DropProtobufDescriptorStatement basic = + parseQuery("DROP PROTOBUF DESCRIPTOR my.org.OrderV1", DropProtobufDescriptorStatement.class); + assertEquals("my.org.OrderV1", basic.getProtoMessageName()); + assertFalse(basic.isIfExists()); + + DropProtobufDescriptorStatement ifExists = parseQuery( + "DROP PROTOBUF DESCRIPTOR IF EXISTS my.org.OrderV1", DropProtobufDescriptorStatement.class); + assertEquals("my.org.OrderV1", ifExists.getProtoMessageName()); + assertTrue(ifExists.isIfExists()); + } + + @Test + public void testCreateProtobufBundleParses() throws Exception { + String sql = "CREATE PROTOBUF BUNDLE (my.org.OrderV1) FROM 'hdfs:///descriptors/orders.desc'"; + CreateProtobufBundleStatement stmt = parseQuery(sql, CreateProtobufBundleStatement.class); + assertEquals(1, stmt.getProtoMessageNames().size()); + assertEquals("my.org.OrderV1", stmt.getProtoMessageNames().get(0)); + assertFalse(stmt.isIfNotExists()); + assertEquals("hdfs:///descriptors/orders.desc", stmt.getSourceUrl()); + } + + @Test + public void testCreateProtobufBundleNamesPreserveCase() throws Exception { + String sql = + "CREATE PROTOBUF BUNDLE (" + " My.Org.MixedCase_V1, ALLUPPER.X, alllower.y, Mix_Of_Cases_123" + + ") FROM 'file:///x.desc'"; + CreateProtobufBundleStatement stmt = parseQuery(sql, CreateProtobufBundleStatement.class); + assertEquals("My.Org.MixedCase_V1", stmt.getProtoMessageNames().get(0)); + assertEquals("ALLUPPER.X", stmt.getProtoMessageNames().get(1)); + assertEquals("alllower.y", stmt.getProtoMessageNames().get(2)); + assertEquals("Mix_Of_Cases_123", stmt.getProtoMessageNames().get(3)); + } + + @Test + public void testCreateProtobufBundleHasCorrectOperationKind() throws Exception { + CreateProtobufBundleStatement stmt = + parseQuery("CREATE PROTOBUF BUNDLE (my.org.X) FROM 'file:///x.desc'", + CreateProtobufBundleStatement.class); + assertEquals( + "CREATE PROTOBUF BUNDLE maps to UPSERT (matches CreateProtobufDescriptorStatement)", + Operation.UPSERT, stmt.getOperation()); + } + + @Test + public void testCreateProtobufBundleEmptyListRejected() throws Exception { + parseQueryThatShouldFailWithSQLException("CREATE PROTOBUF BUNDLE () FROM 'file:///x.desc'"); + } + + @Test + public void testCreateProtobufBundleMissingFromRejected() throws Exception { + parseQueryThatShouldFailWithSQLException("CREATE PROTOBUF BUNDLE (my.org.X)"); + } + + @Test + public void testCreateProtobufBundleMissingParensRejected() throws Exception { + parseQueryThatShouldFailWithSQLException( + "CREATE PROTOBUF BUNDLE my.org.X FROM 'file:///x.desc'"); + } + + @Test + public void testCreateProtobufBundleAllowsTrailingNoComma() throws Exception { + parseQueryThatShouldFailWithSQLException( + "CREATE PROTOBUF BUNDLE (a.b.X,) FROM 'file:///x.desc'"); + } + + @Test + public void testCreateProtobufBundleSingleNameStillParsesAsBundle() throws Exception { + CreateProtobufBundleStatement bundleStmt = + parseQuery("CREATE PROTOBUF BUNDLE (my.org.OnlyOne) FROM 'file:///x.desc'", + CreateProtobufBundleStatement.class); + assertEquals(1, bundleStmt.getProtoMessageNames().size()); + + CreateProtobufDescriptorStatement singleStmt = + parseQuery("CREATE PROTOBUF DESCRIPTOR my.org.OnlyOne FROM 'file:///x.desc'", + CreateProtobufDescriptorStatement.class); + assertEquals("my.org.OnlyOne", singleStmt.getProtoMessageName()); + } + + @Test + public void testCreateProtobufBundleAcceptsKeywordSegmentNames() throws Exception { + String sql = "CREATE PROTOBUF BUNDLE (" + " my.Group.Order, my.Type.Index, my.View.Cast" + + ") FROM 'file:///x.desc'"; + CreateProtobufBundleStatement stmt = parseQuery(sql, CreateProtobufBundleStatement.class); + assertEquals(3, stmt.getProtoMessageNames().size()); + assertEquals("my.Group.Order", stmt.getProtoMessageNames().get(0)); + assertEquals("my.Type.Index", stmt.getProtoMessageNames().get(1)); + assertEquals("my.View.Cast", stmt.getProtoMessageNames().get(2)); + } + + @Test + public void testReservedProtobufKeywordsUsableAsDoubleQuotedIdentifiers() throws Exception { + parseQuery("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, \"protobuf\" VARCHAR)"); + parseQuery("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, \"descriptor\" VARCHAR)"); + parseQuery("CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, \"bundle\" VARCHAR)"); + + parseQuery("CREATE TABLE \"protobuf\" (id BIGINT NOT NULL PRIMARY KEY)"); + parseQuery("CREATE TABLE \"descriptor\" (id BIGINT NOT NULL PRIMARY KEY)"); + parseQuery("CREATE TABLE \"bundle\" (id BIGINT NOT NULL PRIMARY KEY)"); + + parseQuery("CREATE TABLE \"protobuf\".\"descriptor\" (id BIGINT NOT NULL PRIMARY KEY)"); + + parseQuery("SELECT col AS \"protobuf\" FROM t"); + parseQuery("SELECT col AS \"descriptor\" FROM t"); + parseQuery("SELECT col AS \"bundle\" FROM t"); + } + + @Test + public void testProtobufNameMayConsistEntirelyOfReservedKeywords() throws Exception { + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF)", + "Select.From.Where"); + + assertProtobufColumnParses( + "CREATE TABLE t (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF)", "PROTOBUF"); + } + + /** + * oneStatement pushes a ParseContext in @init and must pop it in its own finally. Parsing many + * mixed statements (PROTOBUF DDL and others) on one long-lived parser must leave the stack empty + * after every statement: no leaked frames, no pops of frames that were never pushed. + */ + @Test + public void testContextStackBalancedAcrossMixedStatements() throws Exception { + String[] stmts = { "SELECT a FROM t", + "CREATE PROTOBUF DESCRIPTOR my.org.X FROM 'file:///x.desc'", "UPSERT INTO t (a) VALUES (1)", + "CREATE PROTOBUF BUNDLE (my.org.A, my.org.B) FROM 'file:///b.desc'", + "CREATE TABLE t2 (id BIGINT NOT NULL PRIMARY KEY, p PROTOBUF)", + "ALTER PROTOBUF DESCRIPTOR my.org.X FROM 'file:///y.desc'", "DELETE FROM t WHERE a = 1", + "DROP PROTOBUF DESCRIPTOR IF EXISTS my.org.X", "SELECT a FROM t UNION ALL SELECT b FROM u", + "EXPLAIN SELECT count(*) FROM t", "DROP TABLE t2" }; + int rounds = 5; + StringBuilder script = new StringBuilder(); + for (int r = 0; r < rounds; r++) { + for (String stmt : stmts) { + script.append(stmt).append(";\n"); + } + } + SQLParser parser = new SQLParser(new StringReader(script.toString())); + assertEquals(0, parser.getContextStackDepth()); + int parsed = 0; + BindableStatement stmt; + while ((stmt = parser.nextStatement(new ParseNodeFactory())) != null) { + parsed++; + assertEquals("ParseContext stack not empty after statement #" + parsed + ": " + stmt, 0, + parser.getContextStackDepth()); + } + assertEquals(rounds * stmts.length, parsed); + assertEquals(0, parser.getContextStackDepth()); + } } diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolverTest.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolverTest.java new file mode 100644 index 00000000000..782c5813fd0 --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoDescriptorResolverTest.java @@ -0,0 +1,572 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import org.junit.Assert; +import org.junit.Test; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +public class ProtoDescriptorResolverTest { + private final ProtoDescriptorResolver resolver = new ProtoDescriptorResolver(); + + @Test + public void resolveSingleFileFindsTopLevelMessage() throws Exception { + FileDescriptorSet set = singleFileSet("test.proto", "test", "Account"); + + Descriptors.Descriptor resolved = resolver.resolve(set.toByteArray(), "test.Account"); + + assertNotNull(resolved); + assertEquals("test.Account", resolved.getFullName()); + assertEquals("Account", resolved.getName()); + assertEquals("test.proto", resolved.getFile().getName()); + } + + @Test + public void resolveSingleFileWithMultipleMessages() throws Exception { + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("test.proto").setPackage("test") + .setSyntax("proto3").addMessageType(DescriptorProto.newBuilder().setName("Foo")) + .addMessageType(DescriptorProto.newBuilder().setName("Bar")) + .addMessageType(DescriptorProto.newBuilder().setName("Baz"))) + .build(); + + assertEquals("Bar", resolver.resolve(set.toByteArray(), "test.Bar").getName()); + assertEquals("Foo", resolver.resolve(set.toByteArray(), "test.Foo").getName()); + assertNull("name not in set returns null", resolver.resolve(set.toByteArray(), "test.Missing")); + } + + @Test + public void resolveUnpackagedMessage() throws Exception { + FileDescriptorSet set = FileDescriptorSet + .newBuilder().addFile(FileDescriptorProto.newBuilder().setName("test.proto") + .setSyntax("proto3").addMessageType(DescriptorProto.newBuilder().setName("Unpackaged"))) + .build(); + + Descriptors.Descriptor resolved = resolver.resolve(set.toByteArray(), "Unpackaged"); + + assertNotNull(resolved); + assertEquals("Unpackaged", resolved.getFullName()); + } + + @Test + public void resolveMultiFileWithDependencyOrder() throws Exception { + FileDescriptorProto common = + FileDescriptorProto.newBuilder().setName("common.proto").setPackage("test.common") + .setSyntax("proto3").addMessageType(DescriptorProto.newBuilder().setName("Header")).build(); + FileDescriptorProto schema = FileDescriptorProto.newBuilder().setName("schema.proto") + .setPackage("test").setSyntax("proto3").addDependency("common.proto") + .addMessageType(DescriptorProto.newBuilder().setName("Order") + .addField(FieldDescriptorProto.newBuilder().setName("header").setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE).setTypeName(".test.common.Header") + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL))) + .build(); + + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(schema).addFile(common).build(); + + Descriptors.Descriptor resolvedOrder = resolver.resolve(set.toByteArray(), "test.Order"); + assertNotNull(resolvedOrder); + + assertEquals("test.common.Header", + resolvedOrder.findFieldByName("header").getMessageType().getFullName()); + + Descriptors.Descriptor resolvedHeader = + resolver.resolve(set.toByteArray(), "test.common.Header"); + assertNotNull(resolvedHeader); + assertEquals("Header", resolvedHeader.getName()); + } + + @Test + public void resolveMissingDependencyThrowsIOException() { + FileDescriptorProto schema = FileDescriptorProto.newBuilder().setName("schema.proto") + .setPackage("test").setSyntax("proto3").addDependency("common.proto") + .addMessageType(DescriptorProto.newBuilder().setName("Order")).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(schema).build(); + + try { + resolver.resolve(set.toByteArray(), "test.Order"); + fail("Expected IOException for missing dependency"); + } catch (IOException e) { + assertTrue("Error message should name the missing dependency: " + e.getMessage(), + e.getMessage().contains("common.proto")); + assertTrue("Error message should suggest --include_imports: " + e.getMessage(), + e.getMessage().contains("--include_imports")); + } + } + + @Test + public void resolveImportCycleDetected() { + FileDescriptorProto a = + FileDescriptorProto.newBuilder().setName("a.proto").setPackage("p").setSyntax("proto3") + .addDependency("b.proto").addMessageType(DescriptorProto.newBuilder().setName("A")).build(); + FileDescriptorProto b = + FileDescriptorProto.newBuilder().setName("b.proto").setPackage("p").setSyntax("proto3") + .addDependency("a.proto").addMessageType(DescriptorProto.newBuilder().setName("B")).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(a).addFile(b).build(); + + try { + resolver.resolve(set.toByteArray(), "p.A"); + fail("Expected IOException for import cycle"); + } catch (IOException e) { + assertTrue("Error message should mention 'cycle': " + e.getMessage(), + e.getMessage().toLowerCase().contains("cycle")); + } + } + + @Test + public void resolveCorruptBytesThrowsIOException() { + byte[] garbage = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef }; + try { + resolver.resolve(garbage, "test.Foo"); + fail("Expected IOException for malformed FileDescriptorSet bytes"); + } catch (IOException e) { + assertTrue("Error message should describe what failed: " + e.getMessage(), + e.getMessage().contains("FileDescriptorSet bytes")); + } + } + + @Test + public void resolveNameNotInSetReturnsNull() throws Exception { + FileDescriptorSet set = singleFileSet("test.proto", "test", "Account"); + assertNull(resolver.resolve(set.toByteArray(), "test.NotThere")); + assertNull(resolver.resolve(set.toByteArray(), "other.Account")); + } + + @Test(expected = IllegalArgumentException.class) + public void resolveNullBytesRejected() throws Exception { + resolver.resolve(null, "test.Foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void resolveNullNameRejected() throws Exception { + resolver.resolve(singleFileSet("test.proto", "test", "Account").toByteArray(), null); + } + + @Test(expected = IllegalArgumentException.class) + public void resolveEmptyNameRejected() throws Exception { + resolver.resolve(singleFileSet("test.proto", "test", "Account").toByteArray(), ""); + } + + @Test + public void resolveOneLevelNestedMessage() throws Exception { + FileDescriptorSet set = FileDescriptorSet + .newBuilder().addFile(FileDescriptorProto.newBuilder().setName("test.proto") + .setPackage("test").setSyntax("proto3").addMessageType(DescriptorProto.newBuilder() + .setName("Container").addNestedType(DescriptorProto.newBuilder().setName("Inner")))) + .build(); + + Descriptors.Descriptor outer = resolver.resolve(set.toByteArray(), "test.Container"); + assertNotNull(outer); + assertEquals("Container", outer.getName()); + + Descriptors.Descriptor inner = resolver.resolve(set.toByteArray(), "test.Container.Inner"); + assertNotNull("Nested message must be resolvable by its full dotted name", inner); + assertEquals("test.Container.Inner", inner.getFullName()); + assertEquals("Inner", inner.getName()); + + assertEquals(outer.getFile().getName(), inner.getFile().getName()); + } + + @Test + public void resolveDeeplyNestedMessage() throws Exception { + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("test.proto").setPackage("test") + .setSyntax("proto3").addMessageType( + DescriptorProto.newBuilder().setName("Outer").addNestedType(DescriptorProto.newBuilder() + .setName("Middle").addNestedType(DescriptorProto.newBuilder().setName("Inner"))))) + .build(); + + assertEquals("Outer", resolver.resolve(set.toByteArray(), "test.Outer").getName()); + assertEquals("Middle", resolver.resolve(set.toByteArray(), "test.Outer.Middle").getName()); + assertEquals("Inner", resolver.resolve(set.toByteArray(), "test.Outer.Middle.Inner").getName()); + } + + @Test + public void resolveSiblingNestedMessages() throws Exception { + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("test.proto").setPackage("test") + .setSyntax("proto3") + .addMessageType(DescriptorProto.newBuilder().setName("Container") + .addNestedType(DescriptorProto.newBuilder().setName("A")) + .addNestedType(DescriptorProto.newBuilder().setName("B")))) + .build(); + + assertEquals("test.Container.A", + resolver.resolve(set.toByteArray(), "test.Container.A").getFullName()); + assertEquals("test.Container.B", + resolver.resolve(set.toByteArray(), "test.Container.B").getFullName()); + assertNull("Sibling that doesn't exist must return null", + resolver.resolve(set.toByteArray(), "test.Container.C")); + } + + @Test + public void resolveNestedMessageDoesNotCollideWithSimilarlyNamedTopLevel() throws Exception { + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("test.proto").setPackage("test") + .setSyntax("proto3") + .addMessageType(DescriptorProto.newBuilder().setName("Outer") + .addNestedType(DescriptorProto.newBuilder().setName("Inner"))) + .addMessageType(DescriptorProto.newBuilder().setName("OuterInner"))) + .build(); + + Descriptors.Descriptor topLevel = resolver.resolve(set.toByteArray(), "test.OuterInner"); + Descriptors.Descriptor nested = resolver.resolve(set.toByteArray(), "test.Outer.Inner"); + assertNotNull(topLevel); + assertNotNull(nested); + assertEquals("OuterInner", topLevel.getName()); + assertEquals("Inner", nested.getName()); + } + + @Test + public void resolveNestedMessageInMultiFileSet() throws Exception { + FileDescriptorProto common = FileDescriptorProto.newBuilder().setName("common.proto") + .setPackage("common").setSyntax("proto3").addMessageType(DescriptorProto.newBuilder() + .setName("Address").addNestedType(DescriptorProto.newBuilder().setName("PostalCode"))) + .build(); + FileDescriptorProto schema = FileDescriptorProto.newBuilder().setName("schema.proto") + .setPackage("test").setSyntax("proto3").addDependency("common.proto") + .addMessageType(DescriptorProto.newBuilder().setName("Order")).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(schema).addFile(common).build(); + + Descriptors.Descriptor nested = + resolver.resolve(set.toByteArray(), "common.Address.PostalCode"); + assertNotNull(nested); + assertEquals("PostalCode", nested.getName()); + assertEquals("common.proto", nested.getFile().getName()); + } + + @Test + public void resolveNestedMessageWithUnpackagedOuter() throws Exception { + FileDescriptorSet set = FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("test.proto").setSyntax("proto3") + .addMessageType(DescriptorProto.newBuilder().setName("Outer") + .addNestedType(DescriptorProto.newBuilder().setName("Inner")))) + .build(); + + Descriptors.Descriptor inner = resolver.resolve(set.toByteArray(), "Outer.Inner"); + assertNotNull(inner); + assertEquals("Outer.Inner", inner.getFullName()); + } + + @Test + public void resolveNestedMessageThatDoesNotExistUnderRealOuterReturnsNull() throws Exception { + FileDescriptorSet set = + FileDescriptorSet + .newBuilder().addFile(FileDescriptorProto.newBuilder().setName("test.proto") + .setPackage("test").setSyntax("proto3").addMessageType(DescriptorProto.newBuilder() + .setName("Container").addNestedType(DescriptorProto.newBuilder().setName("A")))) + .build(); + + assertNull(resolver.resolve(set.toByteArray(), "test.Container.Missing")); + + assertNull(resolver.resolve(set.toByteArray(), "test.NoSuchOuter.Inner")); + } + + private static final String ACMEWIDGETS_BUNDLE_RESOURCE = + "protobuf/acmewidgets/acmewidgets_v1.desc"; + private static final String ACCOUNT_PKG = "com.example.acmewidgets.account.v1"; + private static final String COMMON_PKG = "com.example.acmewidgets.common.v1"; + private static final String BILLING_PKG = "com.example.acmewidgets.billing.v1"; + private static final String GOV_PKG = "com.example.acmewidgets.governance.v1"; + private static final String ENDPOINT_TYPES_PKG = + "com.example.acmewidgets.governance.v1.endpointtypes"; + private static final String PROTO2_AUTH_PKG = "com.example.acmewidgets.auth.v1.proto2"; + private static final String WKT_TIMESTAMP = "google.protobuf.Timestamp"; + + private static byte[] loadAcmeWidgetsBundle() throws IOException { + ClassLoader cl = ProtoDescriptorResolverTest.class.getClassLoader(); + try (InputStream in = cl.getResourceAsStream(ACMEWIDGETS_BUNDLE_RESOURCE)) { + assertNotNull( + "acmewidgets_v1.desc not on test classpath — did mvn test-compile copy " + + "src/test/resources/protobuf/acmewidgets/acmewidgets_v1.desc to target/test-classes?", + in); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) { + baos.write(buf, 0, n); + } + return baos.toByteArray(); + } + } + + @Test + public void resolveTopLevelMessagesInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + assertResolvesToFullName(bundle, ACCOUNT_PKG + ".Account"); + assertResolvesToFullName(bundle, ACCOUNT_PKG + ".AccountSyncResponse"); + assertResolvesToFullName(bundle, COMMON_PKG + ".CatalogSyncHeader"); + assertResolvesToFullName(bundle, COMMON_PKG + ".WarehouseEndpoint"); + assertResolvesToFullName(bundle, COMMON_PKG + ".PartnerEndpoint"); + assertResolvesToFullName(bundle, BILLING_PKG + ".Entitlement"); + assertResolvesToFullName(bundle, BILLING_PKG + ".EntitlementSyncResponse"); + assertResolvesToFullName(bundle, GOV_PKG + ".Policy"); + assertResolvesToFullName(bundle, GOV_PKG + ".WidgetEndpoint"); + assertResolvesToFullName(bundle, GOV_PKG + ".WidgetGovernanceSyncResponse"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".BulkOrder"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".FlashSale"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".PreSaleSignup"); + } + + @Test + public void resolveNestedMessagesInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery.NamedCatalogConnection"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery.QueryOp"); + + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".BulkOrder.NamedCatalogConnectionRef"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".BulkOrder.Key"); + + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".FlashSale.PromotionId"); + assertResolvesToFullName(bundle, ENDPOINT_TYPES_PKG + ".FlashSale.Key"); + } + + @Test + public void resolveNestedMessagePreservesSiblingSimpleNameDistinction() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + Descriptors.Descriptor bulkKey = + resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".BulkOrder.Key"); + Descriptors.Descriptor flashKey = + resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".FlashSale.Key"); + + assertNotNull(bulkKey); + assertNotNull(flashKey); + assertEquals("BulkOrder", bulkKey.getContainingType().getName()); + assertEquals("FlashSale", flashKey.getContainingType().getName()); + + assertEquals("Key", bulkKey.getName()); + assertEquals("Key", flashKey.getName()); + + Assert.assertNotSame(bulkKey, flashKey); + } + + @Test + public void resolveNestedSiblingMessageReferenceWiresUpCorrectly() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + Descriptors.Descriptor queryOp = + resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery.QueryOp"); + assertNotNull(queryOp); + Descriptors.FieldDescriptor defaultConnField = queryOp.findFieldByName("default_connection"); + assertNotNull("QueryOp.default_connection field must exist", defaultConnField); + assertEquals("QueryOp.default_connection must point at the sibling NamedCatalogConnection", + ENDPOINT_TYPES_PKG + ".CatalogQuery.NamedCatalogConnection", + defaultConnField.getMessageType().getFullName()); + } + + @Test + public void resolveCrossFileDependencyInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + Descriptors.Descriptor response = + resolver.resolve(bundle, ACCOUNT_PKG + ".AccountSyncResponse"); + assertNotNull(response); + Descriptors.FieldDescriptor header = response.findFieldByName("header"); + assertNotNull("AccountSyncResponse.header must exist", header); + assertEquals("Cross-file dependency must resolve to CatalogSyncHeader from widget_common.proto", + COMMON_PKG + ".CatalogSyncHeader", header.getMessageType().getFullName()); + } + + @Test + public void resolveWellKnownTypeInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor ts = resolver.resolve(bundle, WKT_TIMESTAMP); + assertNotNull("Well-known google.protobuf.Timestamp must resolve", ts); + assertEquals("Timestamp", ts.getName()); + + assertNotNull(ts.findFieldByName("seconds")); + assertNotNull(ts.findFieldByName("nanos")); + } + + @Test + public void resolveFieldOfWellKnownTypeInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor ent = resolver.resolve(bundle, BILLING_PKG + ".Entitlement"); + assertNotNull(ent); + Descriptors.FieldDescriptor deleted = ent.findFieldByName("deleted_time"); + assertNotNull(deleted); + assertEquals(WKT_TIMESTAMP, deleted.getMessageType().getFullName()); + } + + @Test + public void resolveOneofWithCrossFileMessageArmsInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor widgetEndpoint = resolver.resolve(bundle, GOV_PKG + ".WidgetEndpoint"); + assertNotNull(widgetEndpoint); + Descriptors.OneofDescriptor kind = + widgetEndpoint.findFieldByName("catalog_query").getContainingOneof(); + assertNotNull("catalog_query field must belong to a oneof", kind); + assertEquals("endpoint_kind", kind.getName()); + assertEquals("Oneof must have exactly 4 arms", 4, kind.getFieldCount()); + + for (Descriptors.FieldDescriptor arm : kind.getFields()) { + assertTrue( + "Oneof arm " + arm.getName() + " must resolve to a widget_endpoint_types.proto type, got " + + arm.getMessageType().getFullName(), + arm.getMessageType().getFullName().startsWith(ENDPOINT_TYPES_PKG + ".")); + } + } + + @Test + public void resolveMapFieldEntryInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor ent = resolver.resolve(bundle, BILLING_PKG + ".Entitlement"); + assertNotNull(ent); + Descriptors.FieldDescriptor policyToggles = ent.findFieldByName("policy_toggles"); + assertNotNull(policyToggles); + assertTrue("policy_toggles must be recognized as a map field", policyToggles.isMapField()); + + String entryFqName = BILLING_PKG + ".Entitlement.PolicyTogglesEntry"; + Descriptors.Descriptor entry = resolver.resolve(bundle, entryFqName); + assertNotNull("Synthetic map-entry descriptor " + entryFqName + " must be resolvable", entry); + + assertNotNull(entry.findFieldByName("key")); + assertNotNull(entry.findFieldByName("value")); + assertEquals(PROTO_MAP_ENTRY_KEY_TAG, entry.findFieldByName("key").getNumber()); + assertEquals(PROTO_MAP_ENTRY_VALUE_TAG, entry.findFieldByName("value").getNumber()); + } + + @Test + public void resolveProto2MessageInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + assertResolvesToFullName(bundle, PROTO2_AUTH_PKG + ".TokenRevocation"); + assertResolvesToFullName(bundle, PROTO2_AUTH_PKG + ".AppUserRevocation"); + assertResolvesToFullName(bundle, PROTO2_AUTH_PKG + ".TokenRevocationSyncResponse"); + } + + @Test + public void resolveMissingNameInRealBundleReturnsNull() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + assertNull(resolver.resolve(bundle, ACCOUNT_PKG + ".NonExistentMessage")); + assertNull(resolver.resolve(bundle, "some.random.pkg.NoSuchType")); + + assertNull(resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery.MissingInner")); + } + + private static final String ORDERS_PKG = "com.example.acmewidgets.orders.v1"; + + @Test + public void resolveDeepFixtureAllTopLevelMessages() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + for (String simpleName : new String[] { "Money", "Category", "ContactInfo", "LineItem", + "PaymentMethod", "Customer", "Order" }) { + assertResolvesToFullName(bundle, ORDERS_PKG + "." + simpleName); + } + + Descriptors.Descriptor modifier = resolver.resolve(bundle, ORDERS_PKG + ".LineItem.Modifier"); + assertNotNull("Modifier.Kind nested enum must be findable on the resolved descriptor", + modifier.findEnumTypeByName("Kind")); + } + + @Test + public void resolveDeepFixtureFourLevelNestedGeoPoint() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor geo = + resolver.resolve(bundle, ORDERS_PKG + ".ContactInfo.Address.GeoPoint"); + assertNotNull(geo); + assertEquals("GeoPoint", geo.getName()); + + assertEquals("Address", geo.getContainingType().getName()); + assertEquals("ContactInfo", geo.getContainingType().getContainingType().getName()); + assertNull("ContactInfo is top-level (no containing type)", + geo.getContainingType().getContainingType().getContainingType()); + + assertEquals(Descriptors.FieldDescriptor.Type.DOUBLE, + geo.findFieldByName("latitude").getType()); + } + + @Test + public void resolveDeepFixturePaymentOneofArmsAllResolve() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + for (String arm : new String[] { "CreditCard", "BankAccount", "DigitalWallet" }) { + assertResolvesToFullName(bundle, ORDERS_PKG + ".PaymentMethod." + arm); + } + Descriptors.Descriptor payment = resolver.resolve(bundle, ORDERS_PKG + ".PaymentMethod"); + Descriptors.OneofDescriptor kind = payment.findFieldByName("credit_card").getContainingOneof(); + assertEquals("method_kind", kind.getName()); + assertEquals(3, kind.getFieldCount()); + + for (String armField : new String[] { "credit_card", "bank_account", "digital_wallet" }) { + Descriptors.FieldDescriptor f = payment.findFieldByName(armField); + assertEquals("arm " + armField + " must belong to method_kind oneof", kind, + f.getContainingOneof()); + } + } + + @Test + public void resolveDeepFixtureCrossFileBackReferenceToWidgetCommon() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor customer = resolver.resolve(bundle, ORDERS_PKG + ".Customer"); + Descriptors.FieldDescriptor homeWarehouse = customer.findFieldByName("home_warehouse"); + assertEquals("com.example.acmewidgets.common.v1.WarehouseEndpoint", + homeWarehouse.getMessageType().getFullName()); + } + + @Test + public void resolveDoesNotConfuseTopLevelWithNestedLookupInRealBundle() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + Descriptors.Descriptor catalogQuery = + resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery"); + Descriptors.Descriptor nestedQueryOp = + resolver.resolve(bundle, ENDPOINT_TYPES_PKG + ".CatalogQuery.QueryOp"); + assertNotNull(catalogQuery); + assertNotNull(nestedQueryOp); + assertEquals("CatalogQuery", catalogQuery.getName()); + assertEquals("QueryOp", nestedQueryOp.getName()); + Assert.assertNotSame(catalogQuery, nestedQueryOp); + + assertEquals("CatalogQuery", nestedQueryOp.getContainingType().getName()); + + assertNull(catalogQuery.getContainingType()); + } + + private static final int PROTO_MAP_ENTRY_KEY_TAG = 1; + private static final int PROTO_MAP_ENTRY_VALUE_TAG = 2; + + private void assertResolvesToFullName(byte[] bundle, String fqName) throws IOException { + Descriptors.Descriptor resolved = resolver.resolve(bundle, fqName); + assertNotNull("Real-bundle resolution for '" + fqName + "' must succeed", resolved); + assertEquals("Resolved descriptor's full name must equal the requested FQ name", fqName, + resolved.getFullName()); + } + + private static FileDescriptorSet singleFileSet(String fileName, String pkg, String messageName) { + return FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName(fileName).setPackage(pkg) + .setSyntax("proto3").addMessageType(DescriptorProto.newBuilder().setName(messageName))) + .build(); + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidatorTest.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidatorTest.java new file mode 100644 index 00000000000..6a82cf2ece5 --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtoEvolutionValidatorTest.java @@ -0,0 +1,584 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.SQLException; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.junit.Test; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.DescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumOptions; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FieldOptions; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.OneofDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors; + +public class ProtoEvolutionValidatorTest { + private static final String PKG = "test.evo"; + private static final String MSG_NAME = "Widget"; + private static final String FQ_NAME = PKG + "." + MSG_NAME; + private static final String COMMON_PKG = "test.common"; + + private final ProtoDescriptorResolver resolver = new ProtoDescriptorResolver(); + + @Test + public void renameFieldSameTagIsRejected() throws Exception { + DescriptorProto oldMsg = + message(MSG_NAME).addField(scalar("original_name", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(scalar("renamed_name", 1, Type.TYPE_STRING)).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_FIELD_RENAMED, "renamed_name"); + } + + @Test + public void renumberFieldSameNameIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 2, Type.TYPE_STRING)).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_TAG_RENAMED, "id"); + } + + @Test + public void incompatibleTypeChangeIsRejected() throws Exception { + DescriptorProto oldMsg = + message(MSG_NAME).addField(scalar("count", 1, Type.TYPE_INT32)).build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(scalar("count", 1, Type.TYPE_STRING)).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, "count"); + } + + private static final Type[] SCALAR_TYPES_FOR_MATRIX = { Type.TYPE_DOUBLE, Type.TYPE_FLOAT, + Type.TYPE_INT64, Type.TYPE_UINT64, Type.TYPE_INT32, Type.TYPE_FIXED64, Type.TYPE_FIXED32, + Type.TYPE_BOOL, Type.TYPE_STRING, Type.TYPE_BYTES, Type.TYPE_UINT32, Type.TYPE_ENUM, + Type.TYPE_SFIXED32, Type.TYPE_SFIXED64, Type.TYPE_SINT32, Type.TYPE_SINT64, Type.TYPE_MESSAGE }; + + @Test + public void widenUint32ToUint64IsRejected() throws Exception { + DescriptorProto oldMsg = messageWithTypedFieldAndDeps("count", Type.TYPE_UINT32).build(); + DescriptorProto newMsg = messageWithTypedFieldAndDeps("count", Type.TYPE_UINT64).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, "count"); + } + + @Test + public void widenSint32ToSint64IsRejected() throws Exception { + DescriptorProto oldMsg = messageWithTypedFieldAndDeps("count", Type.TYPE_SINT32).build(); + DescriptorProto newMsg = messageWithTypedFieldAndDeps("count", Type.TYPE_SINT64).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, "count"); + } + + @Test + public void everyScalarTypeSameToSameIsAccepted() throws Exception { + for (Type t : SCALAR_TYPES_FOR_MATRIX) { + DescriptorProto same = messageWithTypedFieldAndDeps("f", t).build(); + ProtoEvolutionValidator.validate(resolve(same), resolve(same)); + } + } + + @Test + public void everyTypeChangeThrowsIncompatibleTypeChange() throws Exception { + for (Type oldType : SCALAR_TYPES_FOR_MATRIX) { + for (Type newType : SCALAR_TYPES_FOR_MATRIX) { + if (oldType == newType) { + continue; + } + DescriptorProto oldMsg = messageWithTypedFieldAndDeps("f", oldType).build(); + DescriptorProto newMsg = messageWithTypedFieldAndDeps("f", newType).build(); + try { + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + fail("Expected PROTOBUF_INCOMPATIBLE_TYPE_CHANGE for " + oldType + " → " + newType); + } catch (SQLException ex) { + assertEquals("Wrong error code for " + oldType + " → " + newType + ": " + ex.getMessage(), + SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE.getErrorCode(), ex.getErrorCode()); + } + } + } + } + + @Test + public void cardinalityChangeOptionalToRepeatedIsRejected() throws Exception { + DescriptorProto oldMsg = + message(MSG_NAME).addField(scalar("tags", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(FieldDescriptorProto.newBuilder().setName("tags").setNumber(1) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_REPEATED).build()).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_CARDINALITY_CHANGE, + "tags"); + } + + @Test + public void addPackedAnnotationIsRejected() throws Exception { + DescriptorProto oldMsg = + message(MSG_NAME).addField(FieldDescriptorProto.newBuilder().setName("nums").setNumber(1) + .setType(Type.TYPE_INT32).setLabel(Label.LABEL_REPEATED).build()).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(FieldDescriptorProto.newBuilder() + .setName("nums").setNumber(1).setType(Type.TYPE_INT32).setLabel(Label.LABEL_REPEATED) + .setOptions(FieldOptions.newBuilder().setPacked(true).build()).build()).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_PACKED_ENCODING_CHANGE, "nums"); + } + + @Test + public void addFieldIntoNewOneofIsAccepted() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(FieldDescriptorProto.newBuilder().setName("email").setNumber(2) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addField(FieldDescriptorProto.newBuilder().setName("phone").setNumber(3) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("contact")).build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void addFieldIntoExistingOneofIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(FieldDescriptorProto.newBuilder().setName("email").setNumber(2) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("contact")).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(FieldDescriptorProto.newBuilder().setName("email").setNumber(2) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addField(FieldDescriptorProto.newBuilder().setName("phone").setNumber(3) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("contact")).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_ONEOF_MEMBERSHIP_CHANGE, "phone"); + } + + @Test + public void moveFieldOutOfExistingOneofIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(FieldDescriptorProto.newBuilder().setName("email").setNumber(2) + .setType(Type.TYPE_STRING).setLabel(Label.LABEL_OPTIONAL).setOneofIndex(0).build()) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("contact")).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(scalar("email", 2, Type.TYPE_STRING)) + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("contact")).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_ONEOF_MEMBERSHIP_CHANGE, "email"); + } + + @Test + public void addNestedMessageIsAccepted() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addNestedType(message("Inner").addField(scalar("value", 1, Type.TYPE_STRING))).build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void removeNestedMessageIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addNestedType(message("Inner").addField(scalar("value", 1, Type.TYPE_STRING))).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, "Inner"); + } + + @Test + public void nestedMessageFieldChangeIsValidatedRecursively() throws Exception { + DescriptorProto oldInner = + message("Inner").addField(scalar("original", 1, Type.TYPE_STRING)).build(); + DescriptorProto newInner = + message("Inner").addField(scalar("renamed", 1, Type.TYPE_STRING)).build(); + DescriptorProto oldMsg = + message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).addNestedType(oldInner).build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).addNestedType(newInner).build(); + SQLException ex = + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_FIELD_RENAMED, "renamed"); + assertTrue("path in error must include nested message name, got: " + ex.getMessage(), + ex.getMessage().contains("Inner")); + } + + @Test + public void packageChangeIsRejected() throws Exception { + DescriptorProto proto = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + Descriptors.Descriptor oldDesc = resolveInPackage(proto, "pkg.one"); + Descriptors.Descriptor newDesc = resolveInPackage(proto, "pkg.two"); + try { + ProtoEvolutionValidator.validate(oldDesc, newDesc); + fail("Expected PROTOBUF_PACKAGE_CHANGED SQLException"); + } catch (SQLException ex) { + assertEquals(SQLExceptionCode.PROTOBUF_PACKAGE_CHANGED.getErrorCode(), ex.getErrorCode()); + } + } + + @Test + public void addEnumValueIsAccepted() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(enumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("ACTIVE", 1)).addValue(enumValue("SUSPENDED", 2))) + .build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void removeEnumValueIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(enumType("Status").addValue(enumValue("UNKNOWN", 0))).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, "ACTIVE"); + } + + @Test + public void renameEnumValueSameTagIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("LIVE", 1))) + .build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_ENUM_VALUE_RENAMED, "LIVE"); + } + + @Test + public void renumberEnumValueSameNameIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType( + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 2))) + .build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_ENUM_VALUE_RENUMBERED, "ACTIVE"); + } + + @Test + public void removeEntireEnumIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(enumType("Status").addValue(enumValue("UNKNOWN", 0))).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_REMOVAL_NOT_SUPPORTED, "Status"); + } + + @Test + public void preExistingAllowAliasEnumSurvivesUnchanged() throws Exception { + DescriptorProto msg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("OK", 1)).addValue(enumValue("SUCCESS", 1))) + .build(); + ProtoEvolutionValidator.validate(resolve(msg), resolve(msg)); + } + + @Test + public void addingNewValueThatDoesNotAliasIsAcceptedOnAllowAliasEnum() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("OK", 1)).addValue(enumValue("SUCCESS", 1))) + .build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("OK", 1)).addValue(enumValue("SUCCESS", 1)) + .addValue(enumValue("SUSPENDED", 2))) + .build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void addingNewAliasToExistingTagOnAllowAliasEnumIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("ACTIVE", 1)).addValue(enumValue("LIVE", 1))) + .build(); + + SQLException ex = + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_ENUM_TAG_REUSE, "LIVE"); + assertTrue("hint should identify the pre-existing colliding name 'ACTIVE': " + ex.getMessage(), + ex.getMessage().contains("ACTIVE")); + } + + @Test + public void addingNewAliasAtBrandNewTagOnAllowAliasEnumIsAccepted() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("ACTIVE", 1))) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addEnumType(allowAliasEnumType("Status").addValue(enumValue("UNKNOWN", 0)) + .addValue(enumValue("ACTIVE", 1)).addValue(enumValue("SUSPENDED", 2)) + .addValue(enumValue("ON_HOLD", 2))) + .build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void syntaxChangeProto3ToProto2IsRejected() throws Exception { + DescriptorProto proto = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + Descriptors.Descriptor oldDesc = resolveInFile(proto, "test.evo.proto", PKG, "proto3"); + + Descriptors.Descriptor newDesc = resolveInFile(proto, "test.evo.proto", PKG, null); + try { + ProtoEvolutionValidator.validate(oldDesc, newDesc); + fail("Expected PROTOBUF_SYNTAX_CHANGED SQLException"); + } catch (SQLException ex) { + assertEquals(SQLExceptionCode.PROTOBUF_SYNTAX_CHANGED.getErrorCode(), ex.getErrorCode()); + } + } + + @Test + public void addFieldOnReservedTagIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addReservedRange(DescriptorProto.ReservedRange.newBuilder().setStart(5).setEnd(6).build()) + .build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(scalar("sneaky", 5, Type.TYPE_STRING)) + .addReservedRange(DescriptorProto.ReservedRange.newBuilder().setStart(5).setEnd(6).build()) + .build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_TAG_RESERVED, "sneaky"); + } + + @Test + public void addFieldOnReservedNameIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addReservedName("retired_name").build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(scalar("retired_name", 2, Type.TYPE_STRING)).addReservedName("retired_name") + .build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_NAME_RESERVED, "retired_name"); + } + + @Test + public void reserveLiveTagIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(scalar("count", 2, Type.TYPE_INT32)).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(scalar("count", 2, Type.TYPE_INT32)) + .addReservedRange(DescriptorProto.ReservedRange.newBuilder().setStart(2).setEnd(3).build()) + .build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_RESERVE_OF_LIVE_TAG, "count"); + } + + @Test + public void reserveLiveNameIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = + message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).addReservedName("id").build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_RESERVE_OF_LIVE_NAME, "id"); + } + + @Test + public void addNewReservedTagAndNameIsAccepted() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addReservedRange(DescriptorProto.ReservedRange.newBuilder().setStart(50).setEnd(60).build()) + .addReservedName("some_future_name").build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(newMsg)); + } + + @Test + public void changeMessageFieldTargetTypeIsRejected() throws Exception { + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField( + FieldDescriptorProto.newBuilder().setName("inner").setNumber(2).setType(Type.TYPE_MESSAGE) + .setTypeName("." + FQ_NAME + ".Inner1").setLabel(Label.LABEL_OPTIONAL).build()) + .addNestedType(message("Inner1")).addNestedType(message("Inner2")).build(); + DescriptorProto newMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField( + FieldDescriptorProto.newBuilder().setName("inner").setNumber(2).setType(Type.TYPE_MESSAGE) + .setTypeName("." + FQ_NAME + ".Inner2").setLabel(Label.LABEL_OPTIONAL).build()) + .addNestedType(message("Inner1")).addNestedType(message("Inner2")).build(); + assertRejected(oldMsg, newMsg, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, "inner"); + } + + @Test + public void renumberInReferencedTopLevelEnumIsRejected() throws Exception { + DescriptorProto holder = message("Holder").build(); + DescriptorProto widget = message(MSG_NAME) + .addField(typed("status", 1, Type.TYPE_ENUM, "." + COMMON_PKG + ".Status")).build(); + EnumDescriptorProto oldStatus = + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 1)).build(); + EnumDescriptorProto newStatus = + enumType("Status").addValue(enumValue("UNKNOWN", 0)).addValue(enumValue("ACTIVE", 2)).build(); + + assertRejectedDescriptors(resolveWithImport(holder, oldStatus, widget), + resolveWithImport(holder, newStatus, widget), SQLExceptionCode.PROTOBUF_ENUM_VALUE_RENUMBERED, + "ACTIVE"); + } + + @Test + public void recursiveMessageIsWalkedOnce() throws Exception { + String self = "." + FQ_NAME; + DescriptorProto oldMsg = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_STRING)) + .addField(typed("parent", 2, Type.TYPE_MESSAGE, self)).build(); + DescriptorProto added = + oldMsg.toBuilder().addField(scalar("name", 3, Type.TYPE_STRING)).build(); + ProtoEvolutionValidator.validate(resolve(oldMsg), resolve(added)); + + DescriptorProto retyped = message(MSG_NAME).addField(scalar("id", 1, Type.TYPE_BYTES)) + .addField(typed("parent", 2, Type.TYPE_MESSAGE, self)).build(); + assertRejected(oldMsg, retyped, SQLExceptionCode.PROTOBUF_INCOMPATIBLE_TYPE_CHANGE, "id"); + } + + @Test(expected = IllegalArgumentException.class) + public void nullOldDescriptorRejected() throws Exception { + ProtoEvolutionValidator.validate(null, resolve(message(MSG_NAME).build())); + } + + @Test(expected = IllegalArgumentException.class) + public void nullNewDescriptorRejected() throws Exception { + ProtoEvolutionValidator.validate(resolve(message(MSG_NAME).build()), null); + } + + @Test + public void realBundleDescriptorIsCompatibleWithItself() throws Exception { + byte[] bundle = loadAcmeWidgetsBundle(); + + String fqName = "com.example.acmewidgets.orders.v1.Order"; + Descriptors.Descriptor resolved = resolver.resolve(bundle, fqName); + ProtoEvolutionValidator.validate(resolved, resolved); + + String modifierFqName = "com.example.acmewidgets.orders.v1.LineItem.Modifier"; + Descriptors.Descriptor modifier = resolver.resolve(bundle, modifierFqName); + ProtoEvolutionValidator.validate(modifier, modifier); + } + + private SQLException assertRejected(DescriptorProto oldMsg, DescriptorProto newMsg, + SQLExceptionCode expectedCode, String expectedInMessage) throws Exception { + return assertRejectedDescriptors(resolve(oldMsg), resolve(newMsg), expectedCode, + expectedInMessage); + } + + private static SQLException assertRejectedDescriptors(Descriptors.Descriptor oldDesc, + Descriptors.Descriptor newDesc, SQLExceptionCode expectedCode, String expectedInMessage) + throws Exception { + try { + ProtoEvolutionValidator.validate(oldDesc, newDesc); + fail("Expected SQLException with code " + expectedCode.name()); + return null; + } catch (SQLException ex) { + assertEquals("Expected error code " + expectedCode.name() + " but got " + ex.getMessage(), + expectedCode.getErrorCode(), ex.getErrorCode()); + assertTrue("Message must reference the offending element '" + expectedInMessage + "', got: " + + ex.getMessage(), ex.getMessage().contains(expectedInMessage)); + return ex; + } + } + + private Descriptors.Descriptor resolve(DescriptorProto proto) throws Exception { + return resolveInPackage(proto, PKG); + } + + private Descriptors.Descriptor resolveInPackage(DescriptorProto proto, String pkg) + throws Exception { + return resolveInFile(proto, "test.proto", pkg, "proto3"); + } + + private Descriptors.Descriptor resolveInFile(DescriptorProto proto, String fileName, String pkg, + String syntaxOrNull) throws Exception { + FileDescriptorProto.Builder file = + FileDescriptorProto.newBuilder().setName(fileName).setPackage(pkg).addMessageType(proto); + if (syntaxOrNull != null) { + file.setSyntax(syntaxOrNull); + } + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(file).build(); + String fqName = pkg + "." + proto.getName(); + return resolver.resolve(set.toByteArray(), fqName); + } + + private Descriptors.Descriptor resolveWithImport(DescriptorProto commonMsg, + EnumDescriptorProto commonEnumOrNull, DescriptorProto main) throws Exception { + FileDescriptorProto.Builder common = FileDescriptorProto.newBuilder().setName("common.proto") + .setPackage(COMMON_PKG).setSyntax("proto3").addMessageType(commonMsg); + if (commonEnumOrNull != null) { + common.addEnumType(commonEnumOrNull); + } + FileDescriptorProto file = + FileDescriptorProto.newBuilder().setName("test.proto").setPackage(PKG).setSyntax("proto3") + .addDependency("common.proto").addMessageType(main).build(); + FileDescriptorSet set = FileDescriptorSet.newBuilder().addFile(common).addFile(file).build(); + return resolver.resolve(set.toByteArray(), PKG + "." + main.getName()); + } + + private static FieldDescriptorProto typed(String name, int number, Type type, String typeName) { + return FieldDescriptorProto.newBuilder().setName(name).setNumber(number).setType(type) + .setTypeName(typeName).setLabel(Label.LABEL_OPTIONAL).build(); + } + + private static DescriptorProto.Builder message(String name) { + return DescriptorProto.newBuilder().setName(name); + } + + private static FieldDescriptorProto scalar(String name, int number, Type type) { + return FieldDescriptorProto.newBuilder().setName(name).setNumber(number).setType(type) + .setLabel(Label.LABEL_OPTIONAL).build(); + } + + private static EnumDescriptorProto.Builder enumType(String name) { + return EnumDescriptorProto.newBuilder().setName(name); + } + + private static EnumDescriptorProto.Builder allowAliasEnumType(String name) { + return EnumDescriptorProto.newBuilder().setName(name) + .setOptions(EnumOptions.newBuilder().setAllowAlias(true).build()); + } + + private static EnumValueDescriptorProto enumValue(String name, int number) { + return EnumValueDescriptorProto.newBuilder().setName(name).setNumber(number).build(); + } + + private static DescriptorProto.Builder messageWithTypedFieldAndDeps(String fieldName, Type type) { + DescriptorProto.Builder builder = DescriptorProto.newBuilder().setName(MSG_NAME) + .addNestedType(DescriptorProto.newBuilder().setName("NestedMsg")).addEnumType( + EnumDescriptorProto.newBuilder().setName("NestedEnum").addValue(enumValue("VAL_0", 0))); + FieldDescriptorProto.Builder fieldBuilder = FieldDescriptorProto.newBuilder().setName(fieldName) + .setNumber(1).setType(type).setLabel(Label.LABEL_OPTIONAL); + if (type == Type.TYPE_MESSAGE || type == Type.TYPE_GROUP) { + fieldBuilder.setTypeName("." + FQ_NAME + ".NestedMsg"); + } else if (type == Type.TYPE_ENUM) { + fieldBuilder.setTypeName("." + FQ_NAME + ".NestedEnum"); + } + return builder.addField(fieldBuilder.build()); + } + + private static byte[] loadAcmeWidgetsBundle() throws IOException { + ClassLoader cl = ProtoEvolutionValidatorTest.class.getClassLoader(); + try (InputStream in = cl.getResourceAsStream("protobuf/acmewidgets/acmewidgets_v1.desc")) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) { + baos.write(buf, 0, n); + } + return baos.toByteArray(); + } + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcherTest.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcherTest.java new file mode 100644 index 00000000000..3e137edf463 --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/ProtobufDescriptorFetcherTest.java @@ -0,0 +1,252 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.sql.SQLException; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.junit.Test; + +public class ProtobufDescriptorFetcherTest { + private static final String BUNDLE_RESOURCE = "protobuf/acmewidgets/acmewidgets_v1.desc"; + + private static String fixtureFileUri() { + URL res = ProtobufDescriptorFetcherTest.class.getClassLoader().getResource(BUNDLE_RESOURCE); + assertNotNull( + "acmewidgets_v1.desc not on test classpath — did mvn test-compile copy " + + "src/test/resources/protobuf/acmewidgets/acmewidgets_v1.desc to target/test-classes?", + res); + return res.toString(); + } + + private static String fileUriOf(Path path) { + return path.toUri().toString(); + } + + @Test + public void nullSourceUrlFailsFast() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertUrlNotAllowed(fetcher, null); + } + + @Test + public void emptySourceUrlFailsFast() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertUrlNotAllowed(fetcher, ""); + } + + @Test + public void nonExistentFileFailsWithFetchFailed() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + Path nope = Paths.get("/tmp", "phoenix-protobuf-nonexistent-" + System.nanoTime() + ".desc"); + String uri = fileUriOf(nope); + SQLException ex = expectSQLException(() -> fetcher.fetch(uri)); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED.getErrorCode(), + ex.getErrorCode()); + + assertTrue("expected URL in fetch-failed message: " + ex.getMessage(), + ex.getMessage().contains(uri)); + } + + @Test + public void oversizeSourceFailsWithFetchFailed() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + Path big = Files.createTempFile("phoenix-protobuf-oversize-", ".desc"); + try { + Files.write(big, new byte[ProtobufDescriptorFetcher.MAX_BYTES + 1], StandardOpenOption.WRITE); + SQLException ex = expectSQLException(() -> fetcher.fetch(fileUriOf(big))); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED.getErrorCode(), + ex.getErrorCode()); + assertTrue("expected size-cap message: " + ex.getMessage(), + ex.getMessage().contains(ProtobufDescriptorFetcher.MAX_BYTES + "-byte cap")); + } finally { + Files.deleteIfExists(big); + } + } + + @Test + public void garbageBytesFailsWithParseFailed() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + Path garbage = writeTempBytes("phoenix-protobuf-garbage-", + new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, 0x42, 0x42 }); + try { + SQLException ex = expectSQLException(() -> fetcher.fetch(fileUriOf(garbage))); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED.getErrorCode(), + ex.getErrorCode()); + assertTrue("expected URL in parse-failed message: " + ex.getMessage(), + ex.getMessage().contains(fileUriOf(garbage))); + } finally { + Files.deleteIfExists(garbage); + } + } + + @Test + public void truncatedDescriptorFailsWithParseFailed() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + URL fixture = ProtobufDescriptorFetcherTest.class.getClassLoader().getResource(BUNDLE_RESOURCE); + assertNotNull(fixture); + byte[] full = Files.readAllBytes(Paths.get(fixture.toURI())); + byte[] truncated = new byte[full.length / 2]; + System.arraycopy(full, 0, truncated, 0, truncated.length); + + Path tmp = writeTempBytes("phoenix-protobuf-truncated-", truncated); + try { + SQLException ex = expectSQLException(() -> fetcher.fetch(fileUriOf(tmp))); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED.getErrorCode(), + ex.getErrorCode()); + } finally { + Files.deleteIfExists(tmp); + } + } + + @Test + public void allowsOnlyLocalFileUrls() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + Path fixture = Paths.get(new URL(fixtureFileUri()).toURI()); + byte[] expected = Files.readAllBytes(fixture); + String path = fixture.toString(); + for (String url : new String[] { "file://" + path, "file:" + path, "FILE://" + path }) { + assertArrayEquals(url, expected, fetcher.fetch(url)); + } + } + + @Test + public void rejectsSchemelessPaths() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertUrlNotAllowed(fetcher, "foo.desc"); + assertUrlNotAllowed(fetcher, "/tmp/foo.desc"); + assertUrlNotAllowed(fetcher, "./descriptors/foo.desc"); + } + + @Test + public void rejectsDistributedAndRemoteSchemes() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + for (String url : new String[] { "hdfs:///descriptors/foo.desc", + "hdfs://namenode:8020/foo.desc", "s3a://bucket/foo.desc", "s3://bucket/foo.desc", + "gs://bucket/foo.desc", "abfs://container@account/foo.desc", + "abfss://container@account/foo.desc", "wasb://c@a/foo.desc", "oss://bucket/foo.desc", + "viewfs://cluster/foo.desc", "webhdfs://nn/foo.desc", "har:///foo.har/foo.desc", + "http://example.com/foo.desc", "https://example.com/foo.desc", + "jar:file:///tmp/foo.jar!/foo.desc" }) { + assertUrlNotAllowed(fetcher, url); + } + } + + @Test + public void rejectsFileUrlsWithHostQueryOrFragment() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertUrlNotAllowed(fetcher, "file://tmp/foo.desc"); + assertUrlNotAllowed(fetcher, "file://otherhost/tmp/foo.desc"); + assertUrlNotAllowed(fetcher, "file://localhost/tmp/foo.desc"); + assertUrlNotAllowed(fetcher, "file://localhost:99/tmp/f.desc"); + assertUrlNotAllowed(fetcher, "file:///tmp/foo.desc?x=1"); + assertUrlNotAllowed(fetcher, "file:///tmp/foo.desc#frag"); + assertUrlNotAllowed(fetcher, "file:foo.desc"); + } + + @Test + public void rejectsMalformedUrls() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertUrlNotAllowed(fetcher, "file:///has space/foo.desc"); + assertUrlNotAllowed(fetcher, "file:///foo fetcher.parseBytes("", garbage)); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_PARSE_FAILED.getErrorCode(), + ex.getErrorCode()); + } + + @Test + public void parseBytesRejectsNullPayload() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + SQLException ex = expectSQLException(() -> fetcher.parseBytes("", null)); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED.getErrorCode(), + ex.getErrorCode()); + } + + @Test + public void parseBytesEnforcesSizeCap() { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + SQLException ex = expectSQLException( + () -> fetcher.parseBytes("", new byte[ProtobufDescriptorFetcher.MAX_BYTES + 1])); + assertEquals(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED.getErrorCode(), + ex.getErrorCode()); + assertTrue("expected size-cap message: " + ex.getMessage(), + ex.getMessage().contains(ProtobufDescriptorFetcher.MAX_BYTES + "-byte cap")); + } + + @Test + public void parseBytesAcceptsEmptyPayloadAsEmptyDescriptorSet() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + assertEquals("empty input yields empty set", 0, + fetcher.parseBytes("", new byte[0]).getFileCount()); + } + + @Test + public void emptyFileParsesAsEmptyDescriptorSet() throws Exception { + ProtobufDescriptorFetcher fetcher = new ProtobufDescriptorFetcher(); + Path empty = Files.createTempFile("phoenix-protobuf-empty-", ".desc"); + try { + assertEquals("zero bytes fetched", 0, fetcher.fetch(fileUriOf(empty)).length); + } finally { + Files.deleteIfExists(empty); + } + } + + private static Path writeTempBytes(String prefix, byte[] bytes) throws IOException { + Path tmp = Files.createTempFile(prefix, ".desc"); + Files.write(tmp, bytes, StandardOpenOption.WRITE); + return tmp; + } + + private void assertUrlNotAllowed(ProtobufDescriptorFetcher fetcher, String sourceUrl) { + SQLException e = expectSQLException(() -> fetcher.fetch(sourceUrl)); + assertEquals("for URL: " + sourceUrl, + SQLExceptionCode.PROTOBUF_DESCRIPTOR_URL_NOT_ALLOWED.getErrorCode(), e.getErrorCode()); + } + + @FunctionalInterface + private interface SqlThrowingRunnable { + void run() throws SQLException; + } + + private SQLException expectSQLException(SqlThrowingRunnable r) { + try { + r.run(); + fail("Expected SQLException"); + return null; + } catch (SQLException e) { + return e; + } + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoaderTest.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoaderTest.java new file mode 100644 index 00000000000..ef43634a496 --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/descriptor/SystemProtoDescriptorsJdbcLoaderTest.java @@ -0,0 +1,149 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.descriptor; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +public class SystemProtoDescriptorsJdbcLoaderTest { + + @Test(expected = IllegalArgumentException.class) + public void nullSupplierRejected() { + new SystemProtoDescriptorsJdbcLoader(null); + } + + @Test + public void constructorDoesNotOpenConnection() { + AtomicInteger calls = new AtomicInteger(); + new SystemProtoDescriptorsJdbcLoader(() -> { + calls.incrementAndGet(); + return mock(Connection.class); + }); + assertEquals(0, calls.get()); + } + + @Test + public void nullConnectionFailsLoad() { + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> null); + try { + loader.load("test.Account"); + fail("Expected IOException"); + } catch (IOException e) { + assertTrue(e.getMessage(), e.getMessage().contains("test.Account")); + } + } + + @Test + public void loadHitReturnsBytesFromResultSet() throws Exception { + byte[] expected = new byte[] { 0x0a, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f }; + Connection conn = mock(Connection.class); + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(conn.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(true); + when(rs.getBytes(1)).thenReturn(expected); + + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> conn); + byte[] actual = loader.load("test.Account"); + + assertArrayEquals(expected, actual); + verify(ps).setString(1, "test.Account"); + verify(rs).close(); + verify(ps).close(); + verify(conn).close(); + } + + @Test + public void loadMissReturnsNullWhenNoRowsFound() throws Exception { + Connection conn = mock(Connection.class); + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(conn.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(false); + + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> conn); + assertNull(loader.load("test.NotRegistered")); + } + + @Test + public void loadNullBytesFromResultSetReturnsNull() throws Exception { + Connection conn = mock(Connection.class); + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(conn.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(true); + when(rs.getBytes(1)).thenReturn(null); + + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> conn); + assertNull(loader.load("test.NullCell")); + } + + @Test + public void sqlExceptionFromPrepareStatementIsWrappedAsIOException() throws Exception { + Connection conn = mock(Connection.class); + SQLException underlying = new SQLException("catalog unreachable"); + doThrow(underlying).when(conn).prepareStatement(anyString()); + + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> conn); + try { + loader.load("test.Account"); + fail("Expected IOException"); + } catch (IOException e) { + assertTrue("Cause should be the original SQLException", e.getCause() == underlying); + assertTrue("Error message should reference the descriptor: " + e.getMessage(), + e.getMessage().contains("test.Account")); + assertTrue("Error message should reference SYSTEM.PROTO_DESCRIPTORS: " + e.getMessage(), + e.getMessage().contains("PROTO_DESCRIPTORS")); + } + } + + @Test + public void sqlExceptionFromExecuteQueryIsWrappedAsIOException() throws Exception { + Connection conn = mock(Connection.class); + PreparedStatement ps = mock(PreparedStatement.class); + when(conn.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenThrow(new SQLException("scan interrupted")); + + SystemProtoDescriptorsJdbcLoader loader = new SystemProtoDescriptorsJdbcLoader(() -> conn); + try { + loader.load("test.Account"); + fail("Expected IOException"); + } catch (IOException e) { + assertTrue(e.getCause() instanceof SQLException); + } + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/AcmeWidgetsFixtures.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/AcmeWidgetsFixtures.java new file mode 100644 index 00000000000..6979b9c5fa5 --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/AcmeWidgetsFixtures.java @@ -0,0 +1,342 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.text; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import org.apache.phoenix.thirdparty.com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.Descriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.DescriptorValidationException; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FieldDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.Descriptors.FileDescriptor; +import org.apache.phoenix.thirdparty.com.google.protobuf.DynamicMessage; + +public final class AcmeWidgetsFixtures { + + public static final String BUNDLE_RESOURCE = "protobuf/acmewidgets/acmewidgets_v1.desc"; + + private AcmeWidgetsFixtures() { + } + + public static String bundleFileUrl() { + URL url = AcmeWidgetsFixtures.class.getClassLoader().getResource(BUNDLE_RESOURCE); + if (url == null) { + throw new IllegalStateException(BUNDLE_RESOURCE + " not on the test classpath"); + } + return url.toString(); + } + + private static FileDescriptorSet loadBundle() throws IOException { + ClassLoader cl = AcmeWidgetsFixtures.class.getClassLoader(); + try (InputStream in = cl.getResourceAsStream(BUNDLE_RESOURCE)) { + if (in == null) { + throw new IOException(BUNDLE_RESOURCE + " not on the test classpath"); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) { + baos.write(buf, 0, n); + } + return FileDescriptorSet.parseFrom(baos.toByteArray()); + } + } + + private static Map buildAllFileDescriptors(FileDescriptorSet set) + throws DescriptorValidationException { + Map byName = new HashMap<>(); + for (FileDescriptorProto fileProto : set.getFileList()) { + FileDescriptor[] deps = new FileDescriptor[fileProto.getDependencyCount()]; + for (int i = 0; i < fileProto.getDependencyCount(); i++) { + FileDescriptor dep = byName.get(fileProto.getDependency(i)); + if (dep == null) { + throw new IllegalStateException(fileProto.getName() + " imports " + + fileProto.getDependency(i) + " but dependency wasn't in the bundle set"); + } + deps[i] = dep; + } + byName.put(fileProto.getName(), FileDescriptor.buildFrom(fileProto, deps)); + } + return byName; + } + + public static Map loadAndBuildDescriptorGraph() + throws IOException, DescriptorValidationException { + return buildAllFileDescriptors(loadBundle()); + } + + public static Descriptor accountDescriptor(Map graph) { + return requireMessage(graph, "account_sync.proto", "Account"); + } + + public static Descriptor widgetEndpointDescriptor(Map graph) { + return requireMessage(graph, "widget_governance.proto", "WidgetEndpoint"); + } + + public static Descriptor catalogQueryDescriptor(Map graph) { + return requireMessage(graph, "widget_endpoint_types.proto", "CatalogQuery"); + } + + public static Descriptor entitlementDescriptor(Map graph) { + return requireMessage(graph, "entitlement_sync.proto", "Entitlement"); + } + + public static Descriptor entitlementKeyDescriptor(Map graph) { + return requireMessage(graph, "entitlement_sync.proto", "EntitlementKey"); + } + + public static Descriptor entitlementVersionDescriptor(Map graph) { + return requireMessage(graph, "entitlement_sync.proto", "EntitlementVersion"); + } + + public static Descriptor policyToggleDescriptor(Map graph) { + return requireMessage(graph, "entitlement_sync.proto", "PolicyToggle"); + } + + public static Descriptor tokenRevocationDescriptor(Map graph) { + return requireMessage(graph, "voucher_revocation_sync.proto", "TokenRevocation"); + } + + public static Descriptor orderDescriptor(Map graph) { + return requireMessage(graph, "widget_order_graph.proto", "Order"); + } + + public static Descriptor lineItemDescriptor(Map graph) { + return requireMessage(graph, "widget_order_graph.proto", "LineItem"); + } + + public static Descriptor moneyDescriptor(Map graph) { + return requireMessage(graph, "widget_order_graph.proto", "Money"); + } + + public static Descriptor customerDescriptor(Map graph) { + return requireMessage(graph, "widget_order_graph.proto", "Customer"); + } + + private static Descriptor requireMessage(Map graph, String file, + String name) { + FileDescriptor fd = graph.get(file); + if (fd == null) { + throw new IllegalStateException(file + " not in descriptor graph"); + } + Descriptor d = fd.findMessageTypeByName(name); + if (d == null) { + throw new IllegalStateException(name + " not in " + file); + } + return d; + } + + public static DynamicMessage newAccount(Descriptor account, String tenantKey, String displayName, + boolean active, String homeWarehouse) { + return DynamicMessage.newBuilder(account) + .setField(account.findFieldByName("tenant_key"), tenantKey) + .setField(account.findFieldByName("display_name"), displayName) + .setField(account.findFieldByName("active"), active) + .setField(account.findFieldByName("home_warehouse"), homeWarehouse).build(); + } + + public static DynamicMessage newWidgetEndpointWithCatalogQueryArm(Descriptor widgetEndpoint, + Descriptor catalogQuery, String tenantKey, String name) { + return DynamicMessage.newBuilder(widgetEndpoint) + .setField(widgetEndpoint.findFieldByName("tenant_key"), tenantKey) + .setField(widgetEndpoint.findFieldByName("name"), name) + .setField(widgetEndpoint.findFieldByName("catalog_query"), + DynamicMessage.newBuilder(catalogQuery).build()) + .build(); + } + + public static DynamicMessage newEntitlement(Descriptor entitlement, Descriptor entitlementKey, + Descriptor entitlementVersion, Descriptor policyToggle, String tenantKey, + String entitlementName, String entitlementId, long version, + Map policyToggles) { + DynamicMessage key = DynamicMessage.newBuilder(entitlementKey) + .setField(entitlementKey.findFieldByName("entitlement_name"), entitlementName) + .setField(entitlementKey.findFieldByName("tenant_key"), tenantKey) + .setField(entitlementKey.findFieldByName("entitlement_id"), entitlementId).build(); + DynamicMessage ver = DynamicMessage.newBuilder(entitlementVersion) + .setField(entitlementVersion.findFieldByName("version"), version).build(); + FieldDescriptor policyTogglesField = entitlement.findFieldByName("policy_toggles"); + Descriptor entryType = policyTogglesField.getMessageType(); + DynamicMessage.Builder builder = + DynamicMessage.newBuilder(entitlement).setField(entitlement.findFieldByName("key"), key) + .setField(entitlement.findFieldByName("version"), ver); + for (Map.Entry e : policyToggles.entrySet()) { + DynamicMessage toggle = DynamicMessage.newBuilder(policyToggle) + .setField(policyToggle.findFieldByName("toggle_name"), e.getKey()) + .setField(policyToggle.findFieldByName("enabled"), e.getValue()).build(); + DynamicMessage mapEntry = + DynamicMessage.newBuilder(entryType).setField(entryType.findFieldByName("key"), e.getKey()) + .setField(entryType.findFieldByName("value"), toggle).build(); + builder.addRepeatedField(policyTogglesField, mapEntry); + } + return builder.build(); + } + + public static DynamicMessage newTokenRevocation(Descriptor tokenRevocation, String tenantId, + String tokenId, String reason) { + return DynamicMessage.newBuilder(tokenRevocation) + .setField(tokenRevocation.findFieldByName("tenant_id"), tenantId) + .setField(tokenRevocation.findFieldByName("token_id"), tokenId) + .setField(tokenRevocation.findFieldByName("reason"), reason).build(); + } + + public static DynamicMessage newTokenRevocationWithReasonUnset(Descriptor tokenRevocation, + String tenantId, String tokenId) { + return DynamicMessage.newBuilder(tokenRevocation) + .setField(tokenRevocation.findFieldByName("tenant_id"), tenantId) + .setField(tokenRevocation.findFieldByName("token_id"), tokenId).build(); + } + + /** + * Richly populated {@code Order} for path-walker tests. See + * {@link #newOrderRichlyPopulatedSeeded} for the leaf-to-parameter map. + */ + public static DynamicMessage newOrderRichlyPopulated(Map graph, + String orderId, String customerId) { + return newOrderRichlyPopulatedSeeded(graph, orderId, customerId, 42L, 5L, 37.7749d, 2, + "Sub Modifier Alpha", "Root Category"); + } + + /** + * Seeded Order for multi-row ITs. Parameters map to line_total.units, + * sub_modifiers[0].amount.units, geo.latitude, quantity, holiday display_name, and + * category.parent.parent.name. + */ + public static DynamicMessage newOrderRichlyPopulatedSeeded(Map graph, + String orderId, String customerId, long lineTotalUnits, long subModifierAmountUnits, + double latitude, int quantity, String subModifierDisplayName, String categoryRootName) { + Descriptor order = orderDescriptor(graph); + Descriptor customer = customerDescriptor(graph); + Descriptor contactInfo = requireMessage(graph, "widget_order_graph.proto", "ContactInfo"); + Descriptor address = contactInfo.findNestedTypeByName("Address"); + Descriptor geoPoint = address.findNestedTypeByName("GeoPoint"); + Descriptor lineItem = lineItemDescriptor(graph); + Descriptor modifier = lineItem.findNestedTypeByName("Modifier"); + Descriptor money = moneyDescriptor(graph); + Descriptor category = requireMessage(graph, "widget_order_graph.proto", "Category"); + + DynamicMessage geo = + DynamicMessage.newBuilder(geoPoint).setField(geoPoint.findFieldByName("latitude"), latitude) + .setField(geoPoint.findFieldByName("longitude"), -122.4194d).build(); + DynamicMessage addr = + DynamicMessage.newBuilder(address).setField(address.findFieldByName("street"), "1 Market St") + .setField(address.findFieldByName("city"), "San Francisco") + .setField(address.findFieldByName("region"), "CA") + .setField(address.findFieldByName("postal_code"), "94103") + .setField(address.findFieldByName("country_code"), "US") + .setField(address.findFieldByName("geo"), geo).build(); + DynamicMessage contact = DynamicMessage.newBuilder(contactInfo) + .setField(contactInfo.findFieldByName("email"), "buyer@example.com") + .setField(contactInfo.findFieldByName("phone"), "+1-555-0100") + .addRepeatedField(contactInfo.findFieldByName("addresses"), addr).build(); + DynamicMessage cust = DynamicMessage.newBuilder(customer) + .setField(customer.findFieldByName("customer_id"), customerId) + .setField(customer.findFieldByName("display_name"), "Deep Customer") + .setField(customer.findFieldByName("contact"), contact).build(); + + DynamicMessage lineTotal = + DynamicMessage.newBuilder(money).setField(money.findFieldByName("currency_code"), "USD") + .setField(money.findFieldByName("units"), lineTotalUnits) + .setField(money.findFieldByName("nanos"), 500000000).build(); + DynamicMessage regionalPriceUS = + DynamicMessage.newBuilder(money).setField(money.findFieldByName("currency_code"), "USD") + .setField(money.findFieldByName("units"), 40L).setField(money.findFieldByName("nanos"), 0) + .build(); + + // sub_modifiers[0] used by both modifiers[0] and named_modifiers["holiday"] + DynamicMessage subAmount = + DynamicMessage.newBuilder(money).setField(money.findFieldByName("currency_code"), "USD") + .setField(money.findFieldByName("units"), subModifierAmountUnits) + .setField(money.findFieldByName("nanos"), 0).build(); + DynamicMessage subModifier = + DynamicMessage.newBuilder(modifier).setField(modifier.findFieldByName("modifier_id"), "sub-1") + .setField(modifier.findFieldByName("display_name"), subModifierDisplayName) + .setField(modifier.findFieldByName("amount"), subAmount).build(); + DynamicMessage topModifier = + DynamicMessage.newBuilder(modifier).setField(modifier.findFieldByName("modifier_id"), "mod-1") + .setField(modifier.findFieldByName("display_name"), "Top Modifier") + .addRepeatedField(modifier.findFieldByName("sub_modifiers"), subModifier).build(); + + // Category self-reference: leaf -> parent -> parent + DynamicMessage grandparentCat = + DynamicMessage.newBuilder(category).setField(category.findFieldByName("id"), "cat-root") + .setField(category.findFieldByName("name"), categoryRootName).build(); + DynamicMessage parentCat = + DynamicMessage.newBuilder(category).setField(category.findFieldByName("id"), "cat-mid") + .setField(category.findFieldByName("name"), "Middle Category") + .setField(category.findFieldByName("parent"), grandparentCat).build(); + DynamicMessage leafCat = + DynamicMessage.newBuilder(category).setField(category.findFieldByName("id"), "cat-leaf") + .setField(category.findFieldByName("name"), "Leaf Category") + .setField(category.findFieldByName("parent"), parentCat).build(); + + FieldDescriptor regionalPricesField = lineItem.findFieldByName("regional_prices"); + Descriptor regionalEntry = regionalPricesField.getMessageType(); + DynamicMessage regionalEntryUs = + DynamicMessage.newBuilder(regionalEntry).setField(regionalEntry.findFieldByName("key"), "US") + .setField(regionalEntry.findFieldByName("value"), regionalPriceUS).build(); + + FieldDescriptor namedModifiersField = lineItem.findFieldByName("named_modifiers"); + Descriptor namedEntry = namedModifiersField.getMessageType(); + DynamicMessage namedEntryHoliday = + DynamicMessage.newBuilder(namedEntry).setField(namedEntry.findFieldByName("key"), "holiday") + .setField(namedEntry.findFieldByName("value"), topModifier).build(); + + DynamicMessage li = + DynamicMessage.newBuilder(lineItem).setField(lineItem.findFieldByName("line_id"), "line-1") + .setField(lineItem.findFieldByName("sku"), "SKU-001") + .setField(lineItem.findFieldByName("category"), leafCat) + .setField(lineItem.findFieldByName("quantity"), quantity) + .setField(lineItem.findFieldByName("line_total"), lineTotal) + .addRepeatedField(regionalPricesField, regionalEntryUs) + .addRepeatedField(lineItem.findFieldByName("modifiers"), topModifier) + .addRepeatedField(namedModifiersField, namedEntryHoliday).build(); + + return DynamicMessage.newBuilder(order).setField(order.findFieldByName("order_id"), orderId) + .setField(order.findFieldByName("customer"), cust) + .addRepeatedField(order.findFieldByName("line_items"), li).build(); + } + + public static DynamicMessage newTokenRevocationWithPartnerSourceExtension( + Descriptor tokenRevocation, FileDescriptor voucherFile, String tenantId, String tokenId, + String partnerSource) { + FieldDescriptor ext = null; + List extensions = voucherFile.getExtensions(); + for (FieldDescriptor candidate : extensions) { + if ("partner_revocation_source".equals(candidate.getName())) { + ext = candidate; + break; + } + } + if (ext == null) { + throw new IllegalStateException( + "partner_revocation_source extension not declared in voucher_revocation_sync.proto"); + } + return DynamicMessage.newBuilder(tokenRevocation) + .setField(tokenRevocation.findFieldByName("tenant_id"), tenantId) + .setField(tokenRevocation.findFieldByName("token_id"), tokenId).setField(ext, partnerSource) + .build(); + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/ProtobufDescriptorServiceWireTest.java b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/ProtobufDescriptorServiceWireTest.java new file mode 100644 index 00000000000..2434842a96f --- /dev/null +++ b/phoenix-core/src/test/java/org/apache/phoenix/protobuf/text/ProtobufDescriptorServiceWireTest.java @@ -0,0 +1,283 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.phoenix.protobuf.text; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.protobuf.ByteString; +import com.google.protobuf.RpcCallback; +import com.google.protobuf.RpcController; +import java.lang.reflect.Method; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.AlterProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufBundleRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.CreateProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.DropProtobufDescriptorRequest; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorMutationResponse; +import org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos.ProtobufDescriptorService; +import org.apache.phoenix.exception.SQLExceptionCode; +import org.junit.Test; + +public class ProtobufDescriptorServiceWireTest { + @Test + public void createDescriptorRequestRoundTrips() throws Exception { + CreateProtobufDescriptorRequest original = CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName("com.example.acmewidgets.account.v1.Account") + .setSourceUrl("file:///phoenix/descriptors/acmewidgets_v1.desc").setIfNotExists(true).build(); + + byte[] wire = original.toByteArray(); + CreateProtobufDescriptorRequest decoded = CreateProtobufDescriptorRequest.parseFrom(wire); + + assertEquals(original, decoded); + assertEquals("com.example.acmewidgets.account.v1.Account", decoded.getProtobufName()); + assertEquals("file:///phoenix/descriptors/acmewidgets_v1.desc", decoded.getSourceUrl()); + assertTrue(decoded.getIfNotExists()); + } + + @Test + public void alterDescriptorRequestRoundTrips() throws Exception { + AlterProtobufDescriptorRequest original = AlterProtobufDescriptorRequest.newBuilder() + .setProtobufName("com.example.acmewidgets.account.v1.Account") + .setSourceUrl("file:///etc/phoenix/order_v2.desc").setIfExists(false).build(); + + AlterProtobufDescriptorRequest decoded = + AlterProtobufDescriptorRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertFalse(decoded.getIfExists()); + } + + @Test + public void dropDescriptorRequestRoundTrips() throws Exception { + DropProtobufDescriptorRequest original = DropProtobufDescriptorRequest.newBuilder() + .setProtobufName("com.example.acmewidgets.delivery.v1.DeliveryWindowRecord").setIfExists(true) + .build(); + + DropProtobufDescriptorRequest decoded = + DropProtobufDescriptorRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + } + + @Test + public void createBundleRequestRoundTrips() throws Exception { + CreateProtobufBundleRequest original = CreateProtobufBundleRequest.newBuilder() + .setSourceUrl("file:///phoenix/descriptors/acmewidgets_v1.desc").setIfNotExists(true) + .addProtobufNames("com.example.acmewidgets.account.v1.Account") + .addProtobufNames("com.example.acmewidgets.account.v1.AccountSyncResponse") + .addProtobufNames("com.example.acmewidgets.common.v1.CatalogSyncHeader").build(); + + CreateProtobufBundleRequest decoded = + CreateProtobufBundleRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertEquals(3, decoded.getProtobufNamesCount()); + assertEquals("com.example.acmewidgets.common.v1.CatalogSyncHeader", + decoded.getProtobufNames(2)); + } + + @Test + public void mutationResponseRoundTripsOnSuccess() throws Exception { + ProtobufDescriptorMutationResponse original = ProtobufDescriptorMutationResponse.newBuilder() + .addRegisteredNames("com.example.acmewidgets.account.v1.Account").build(); + + ProtobufDescriptorMutationResponse decoded = + ProtobufDescriptorMutationResponse.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertFalse(decoded.hasErrorCode()); + } + + @Test + public void mutationResponseCarriesOffendingNameOnTypeNotFound() throws Exception { + ProtobufDescriptorMutationResponse original = ProtobufDescriptorMutationResponse.newBuilder() + .setErrorCode(SQLExceptionCode.PROTOBUF_DESCRIPTOR_TYPE_NOT_FOUND_IN_FILE.getErrorCode()) + .setOffendingName("com.example.acmewidgets.account.v1.NotInTheBundle").setErrorMessage( + "No top-level message named 'NotInTheBundle' in the loaded FileDescriptorSet") + .build(); + + ProtobufDescriptorMutationResponse decoded = + ProtobufDescriptorMutationResponse.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertEquals("com.example.acmewidgets.account.v1.NotInTheBundle", decoded.getOffendingName()); + } + + @Test + public void mutationResponseCarriesErrorMessageOnFetchFailed() throws Exception { + ProtobufDescriptorMutationResponse original = ProtobufDescriptorMutationResponse.newBuilder() + .setErrorCode(SQLExceptionCode.PROTOBUF_DESCRIPTOR_FETCH_FAILED.getErrorCode()) + .setErrorMessage("java.nio.file.NoSuchFileException: /nonexistent/path.desc").build(); + + ProtobufDescriptorMutationResponse decoded = + ProtobufDescriptorMutationResponse.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertTrue(decoded.getErrorMessage().contains("NoSuchFileException")); + } + + @Test + public void createDescriptorRequestRoundTripsInlineBytes() throws Exception { + byte[] payload = { 0x0a, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f }; + CreateProtobufDescriptorRequest original = CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName("com.example.acmewidgets.account.v1.Account") + .setSourceUrl("file:///home/alice/account.desc").setIfNotExists(false) + .setInlineDescriptorBytes(ByteString.copyFrom(payload)).build(); + + CreateProtobufDescriptorRequest decoded = + CreateProtobufDescriptorRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertTrue("inlineDescriptorBytes must be set after round-trip", + decoded.hasInlineDescriptorBytes()); + assertArrayEquals(payload, decoded.getInlineDescriptorBytes().toByteArray()); + } + + @Test + public void alterDescriptorRequestRoundTripsInlineBytes() throws Exception { + byte[] payload = { 0x12, 0x03, 0x66, 0x6f, 0x6f }; + AlterProtobufDescriptorRequest original = AlterProtobufDescriptorRequest.newBuilder() + .setProtobufName("com.example.acmewidgets.account.v1.Account") + .setSourceUrl("file:///home/alice/account_v2.desc").setIfExists(true) + .setInlineDescriptorBytes(ByteString.copyFrom(payload)).build(); + + AlterProtobufDescriptorRequest decoded = + AlterProtobufDescriptorRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertTrue(decoded.hasInlineDescriptorBytes()); + assertArrayEquals(payload, decoded.getInlineDescriptorBytes().toByteArray()); + } + + @Test + public void createBundleRequestRoundTripsInlineBytes() throws Exception { + byte[] payload = new byte[256]; + for (int i = 0; i < payload.length; i++) { + payload[i] = (byte) (i & 0x7f); + } + CreateProtobufBundleRequest original = CreateProtobufBundleRequest.newBuilder() + .setSourceUrl("file:///home/alice/acmewidgets_v1.desc").setIfNotExists(true) + .addProtobufNames("com.example.acmewidgets.account.v1.Account") + .addProtobufNames("com.example.acmewidgets.common.v1.CatalogSyncHeader") + .setInlineDescriptorBytes(ByteString.copyFrom(payload)).build(); + + CreateProtobufBundleRequest decoded = + CreateProtobufBundleRequest.parseFrom(original.toByteArray()); + assertEquals(original, decoded); + assertTrue(decoded.hasInlineDescriptorBytes()); + assertEquals(payload.length, decoded.getInlineDescriptorBytes().size()); + assertArrayEquals(payload, decoded.getInlineDescriptorBytes().toByteArray()); + } + + @Test + public void mutationRequestsWithoutInlineBytesOmitTheField() throws Exception { + CreateProtobufDescriptorRequest noInline = + CreateProtobufDescriptorRequest.newBuilder().setProtobufName("my.org.X") + .setSourceUrl("file:///descriptors/x.desc").setIfNotExists(false).build(); + assertFalse("request built without inline bytes must not set the field", + noInline.hasInlineDescriptorBytes()); + CreateProtobufDescriptorRequest decoded = + CreateProtobufDescriptorRequest.parseFrom(noInline.toByteArray()); + assertFalse(decoded.hasInlineDescriptorBytes()); + } + + @Test + public void dropRequestHasNoInlineDescriptorBytesField() { + boolean hasField = false; + for (Method m : DropProtobufDescriptorRequest.class.getMethods()) { + if ( + m.getName().equals("hasInlineDescriptorBytes") + || m.getName().equals("getInlineDescriptorBytes") + ) { + hasField = true; + break; + } + } + assertFalse("DropProtobufDescriptorRequest must not declare inlineDescriptorBytes", hasField); + } + + @Test + public void wireBytesAreDeterministic() throws Exception { + CreateProtobufDescriptorRequest a = CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName("my.org.X").setSourceUrl("file:///x.desc").setIfNotExists(false).build(); + CreateProtobufDescriptorRequest b = CreateProtobufDescriptorRequest.newBuilder() + .setProtobufName("my.org.X").setSourceUrl("file:///x.desc").setIfNotExists(false).build(); + assertArrayEquals(a.toByteArray(), b.toByteArray()); + } + + @Test + public void serviceDeclaresExpectedRpcs() { + String[] expected = { "createProtobufDescriptor", "alterProtobufDescriptor", + "dropProtobufDescriptor", "createProtobufBundle" }; + for (String rpcName : expected) { + assertTrue( + "expected RPC method '" + rpcName + "' missing from " + "ProtobufDescriptorService", + hasRpcMethod(rpcName)); + } + } + + @Test + public void servicePackageAndNameMatchSpec() { + assertEquals("org.apache.phoenix.coprocessor.generated.ProtobufDescriptorProtos$" + + "ProtobufDescriptorService", ProtobufDescriptorService.class.getName()); + } + + private static boolean hasRpcMethod(String name) { + for (Method m : ProtobufDescriptorService.class.getDeclaredMethods()) { + if (m.getName().equals(name)) { + return true; + } + } + return false; + } + + @Test + public void serviceCanBeSubclassed() { + ProtobufDescriptorService stub = new ProtobufDescriptorService() { + @Override + public void createProtobufDescriptor(RpcController c, CreateProtobufDescriptorRequest r, + RpcCallback done) { + done.run( + ProtobufDescriptorMutationResponse.newBuilder().addRegisteredNames("my.org.X").build()); + } + + @Override + public void alterProtobufDescriptor(RpcController c, AlterProtobufDescriptorRequest r, + RpcCallback done) { + fail("not exercised in this test"); + } + + @Override + public void dropProtobufDescriptor(RpcController c, DropProtobufDescriptorRequest r, + RpcCallback done) { + fail("not exercised in this test"); + } + + @Override + public void createProtobufBundle(RpcController c, CreateProtobufBundleRequest r, + RpcCallback done) { + fail("not exercised in this test"); + } + }; + assertNotNull(stub); + + ProtobufDescriptorMutationResponse[] sink = new ProtobufDescriptorMutationResponse[1]; + stub.createProtobufDescriptor(null, + CreateProtobufDescriptorRequest.newBuilder().setProtobufName("my.org.X") + .setSourceUrl("file:///x.desc").setIfNotExists(false).build(), + response -> sink[0] = response); + assertNotNull(sink[0]); + assertFalse(sink[0].hasErrorCode()); + } +} diff --git a/phoenix-core/src/test/java/org/apache/phoenix/schema/types/PDataTypeTest.java b/phoenix-core/src/test/java/org/apache/phoenix/schema/types/PDataTypeTest.java index 40009dd8fc8..99eb0428a6d 100644 --- a/phoenix-core/src/test/java/org/apache/phoenix/schema/types/PDataTypeTest.java +++ b/phoenix-core/src/test/java/org/apache/phoenix/schema/types/PDataTypeTest.java @@ -1796,7 +1796,7 @@ public void testCoercibleGoldfile() { + "FLOAT ARRAY=[BINARY ARRAY, DECIMAL ARRAY, DOUBLE ARRAY, FLOAT ARRAY, VARBINARY ARRAY], " + "INTEGER=[BIGINT, BINARY, DECIMAL, DOUBLE, FLOAT, INTEGER, VARBINARY], " + "INTEGER ARRAY=[BIGINT ARRAY, BINARY ARRAY, DECIMAL ARRAY, DOUBLE ARRAY, FLOAT ARRAY, INTEGER ARRAY, VARBINARY ARRAY], " - + "JSON=[BINARY, JSON, VARBINARY], " + + "JSON=[BINARY, JSON, VARBINARY], " + "PROTOBUF=[BINARY, PROTOBUF, VARBINARY], " + "SMALLINT=[BIGINT, BINARY, DECIMAL, DOUBLE, FLOAT, INTEGER, SMALLINT, VARBINARY], " + "SMALLINT ARRAY=[BIGINT ARRAY, BINARY ARRAY, DECIMAL ARRAY, DOUBLE ARRAY, FLOAT ARRAY, INTEGER ARRAY, SMALLINT ARRAY, VARBINARY ARRAY], " + "TIME=[BINARY, DATE, TIME, TIMESTAMP, VARBINARY], " diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/account_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/account_sync.proto new file mode 100644 index 00000000000..b6589972ebb --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/account_sync.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; + +package com.example.acmewidgets.account.v1; + +option java_package = "com.example.acmewidgets.account.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message Account { + string tenant_key = 1; + string display_name = 2; + string status = 3; + bool active = 4; + string current_storefront_domain = 5; + string current_storefront_url = 6; + string previous_storefront_domain = 7; + string provisioning_storefront_domain = 8; + string home_warehouse = 9; + google.protobuf.Timestamp deleted_time = 10; + google.protobuf.Timestamp updated_time = 11; +} + +message AccountSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated Account accounts = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/acmewidgets_v1.desc b/phoenix-core/src/test/resources/protobuf/acmewidgets/acmewidgets_v1.desc new file mode 100644 index 0000000000000000000000000000000000000000..21f005bb4d0ea7a74b4a3bb39c555f110be613b4 GIT binary patch literal 15612 zcmcILOK>AeRxQc0r6*gK(>>j8^~}yr4Kq92%c^HIyUfrt!-QqK+wOMTnzB5eWe!DI zO3O8tRNAVN-6nzq5G)67dw>fN>;jjKy$}IhU^zepF%d+-VQ+Ba!im#f;6lKAnOQ&m zTo&t#!}XN;Ugpd9&zJDebFg}0wc6Y>ns&Eq_bPqI_H6bVepUDjv)k|RirMUPImoT3 zQRnYyN3e2aI{efgxO}VE>f2V&W3R#Dg%32W)>`VTskicaA%N|)*sD-*c-yjjNU_D& z(qaTi&;~-Z-%7!9-E_PjcLKbx0Q4m&#F|$S#EE46pL=H4M_N#@Jp{3D0y`OWPOMI+ z%X^+7>8)i1^_9pkx>%d`y)>+Bn4a0O+Xt7u<~BE5++k(N9ozO<*L2R*)`D;L1{Axt z!wvJ?v^wT-N3J5LFA;Rz2eJm_18xZNh3dD6tJAq%8DaJIEj>iU_FzG6c5M!~RH#-H z;H<})j2L|+wH(abj@7n$wKw2uS*WLu=Y`z73;&yfSKGGT?(l~Kay&SB=viIvdMHau zxR&Jr`Go_t4m<_k)UQ_6kha}1d+mztv?FW0>~r_wS)b6I?rfAgXRVt_>XyDX0vGzP|92s9kpp~(iy9o3u5M)KVpRDCVT}2^W1XL0$IKG7z{aq;pOP45iF?er*@Ycp(^La ztR;d5y2?I6e)A6Zc*`IqSOXkXsFsIiwGxP`UQpu+LemHRmKjVhTs>Wlr|H^{Q8Sca zkPXwh+qZizXS*be_*G~rAxn#ecf)eRU z3*A+($593Bp5ohQ6ZbiVLM4j5LMqo%kc|MpzAPw)0QNa#?7q+6o&P^wvA6xcPFTs} zB11?agwD_D{%3g??u=g{tHMjeT#+V4di>R)4G@;{&r-0U2(u!jgYW?VOK6$8+&i^f zzGaeMjKN&r^iG9c%Io5P_PZ%yEq-DSIuzIh=SKFZP`$ZxTTwK_lhb~dhJ0<%Ioo$A zfM`I*H_U}x7QI40&^aoN+AgQUz2YAmERTbp(IP`*3gk!Rq{ErnCLM z6lBQ5{M^+g-0s8$kEo0Gm&o+T9n(EMFgyI`!Sn!G!1VIlP{2^2Ym-4xA*lZu#;67K zBL0x_A1fYpFJD!U!AlgJUwJKjiSvu6vG%G11sM#ky6 z=`~MLOTU2CQ_t%g(n}g$307AB{e2T6d^sajUjL?4-0BX+8?GMkG861kr1;DnCntXMyFk@K1@hiA9VP0oTiJ( z>?!0FcHdo95+YK|)`R)lk5aHQ!bVI3=E%E3XCbRcPdt){Q?y0cE@U7HaI5j7&DUchJ2D-(*86J^Kw|! z>(haUUO$*9X-M{d0y$417Az=Kzn$<{4fP~Yq$$yH3BBK`ru=J{XkjH6Kibd*BsJ@+Wb%FHjAqwrMb5J}IRgq``Vp?Jq z389EaWa1CUEIUBTqQxDI$Rr^4W%q4rq^U1R@o>6Z9^?>qE=>cJf- zM7#`JfJ|+_QM&cOfShmZ3HW3Sfh-4e_5FiJDMg_AVWX60dC1n+8ynlD458iJ+TChw zmF8&V_SX7lDa#75uwQTN?C%|v=4o_8U*Fg&E!4ga$)c)Ai1u$;C}SZ4t3A%8ae=~X zUqowJuTP57{5i81vp#~`n~Ly}psS1HqUx$z2f92D(|76q^(6_dOQ7}_X<+gBLc^{o ziyaJ0#V=2kipUNtaYAyTx-S##dOC!7!!l6<9a7`RmWgDRn^*;Zl7e!4D>qmz`UDo_ ziTMin-VCf3>+|u{z6MF;F(Tc6o`shpwMsWE(oR&AaQN(^{gX66SV+98RC^!tvWQ9< zqKw3H5`f7j%Cq{Bilx#rtKn23{RXU@aIE2?v!i&!?VC+mw$1A$^~0VIA1kM_ZadD_ z$K+H70aFESnw&}(KXrQ4Rs2l~?u7iiK^Z-OLU`W3oW3(rPQ$TOP7GJ5N3l$^!Z8F9 zIsLCWxM%h)qv`M#*4Hhw6E(uGPBOw&3YuL?{~!%Z>wRk@pm~*`V$mS7z(80RLm&$5 zJ;;4=aV7(ODXt6nEu#E!c2ed7SIS=kLpM$S5{U1R{N0Oj<_1Nuj=52A0=@`NPNdb5 zS7OW4qbO>x!&L$kk-R^;2X{!~ybc$)r4bW3u||K4SF3oTGP~sc&oUIYLZWOlS}UD= zpBd7vL}mxI(Rx_imO=0@O;qIZm@o;a(s)o5XU}2YGabA#zcLXXkFX&o>k0|8peT~T zOT)9$_dBYIxIB#8c~ufAq53zC$Qvt4qdj1s)>ua9c^%Ojyhq32Lj2bRE%-u{uU)(2_jDR23_u0 zO`lM1HcswIEKy2J3bP{hYuLnqH5Q{|buG_b%L_UmUzdeCqSzG}As@I=QUjC)q;*@7s7nfR+}Plzh(z=HmCj{Z zlm@0oC)1ou>FVhb=Tdfnjp{Eeg(fgBuX-Ls_M8+zgoM+|ToE0LBG%>fN9p%d~@@NA}=8E?mKOvt5Kq8|3+1N4Aq@D)pwI< zgF-xxtOLtKntt;%&tcWCL`U@g#_2wt%gvRt__t76)K~Cc>6l^ytQocqG!0$7Y`Mm; zEigMB`+~Q$-%LR@uhOpV}dmhRp(%;zPe4MOh5NSD<|k z#kgkD*05;}4-b7q6z5U^6)3UoD>Qj|rO(r0JG<+(-7PHEEkQo~Oi>+fYma`~ETuILx5s%d?K#x~$d!@vVvCU5+&PeQ zZbcEKM(L$}(7|E7zOOfsOh)_LRDAh2*Y0xwixHLaQ6m*<7piW$M9v?#oo^$7$`a(F(2i`-d)flCJVDEMVWR6E1R| zK5>n&!6M$JxfB759>R>+9^KRl81;B;1Ct9hj`<0;{K?+7tBaN;Ijbfni4L{DPr>~m z=Ejoh?@+I>f4tNWN_oTNilLtdi(Z0iWeBq##T9GiRpm9mwU_ZYw0})Q0eb*E>}}rZ zo!G=hj;+fbdA&rR{Zl*y8Jyw8eco*0c3l@2oDtS&aycoo;E+INUCuB6JN6r?|FIbo zyR03K6(!MVMMu;OTKVW#Y&}8$CcOq*g+kwU@o9n-22m@;rWiEa*m92dbwWf$1s^+o zGi`3GmWavaiK#2CJmGeo9(R-yXmRwujPG5hq%Rh}UN_C7v^ z=#sJtQM<Ff1UrhEpgV@@(|J2&D-Hq(-Y#r?ZE>@qbk z>0SXdBW&l!elzTB6M*mtLmrbUxekwYd3A!S-!vV0+J$Now-Q@ag)YD>Zv#! z#bdK~W~lcI>fAp}U{2ylYluWWd_b(9L9vBztjLmIU=ak(zr4_z+*K8dW*qOPL~|st zY~Lz>4iK)N_}ewzGb+EDs&7L03*4L0ZbcC8@$*L0sUk0iU z`)v8!P>Ae9XrRPyA&-=8$7zCL;S;~|`>+&SCQX#v7OytcL|m(4vP?~|R9jm@9T$=! z`>6hjBAWqTnqrDVNSf;ZPOa&cU^_Ps^dnm3~~R zS8_j&?-D)p1zwcR5(In%1xyoq`0`6km(32zX}^sD9Tp3Mw_mbTamsZBL-{_nsF&bU z-A5&nZ*laMt#h=-Wo!h>ivRG*z}&?t2K5xEO?|IMp{j7I(thmHGt|qDZIa!k;3SFN ejVz&pXGgPTBvHYdX5{-SQJ(fxHIR<5i1dFlIsJ_Q literal 0 HcmV?d00001 diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/api_credential_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/api_credential_sync.proto new file mode 100644 index 00000000000..8aea0759bef --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/api_credential_sync.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package com.example.acmewidgets.auth.v1; + +option java_package = "com.example.acmewidgets.auth.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message ApiCredential { + string tenant_key = 1; + string credential_id = 2; + string jwk_json = 3; + string source_warehouse = 4; + google.protobuf.Timestamp deleted_time = 5; + google.protobuf.Timestamp updated_time = 6; +} + +message ApiCredentialSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated ApiCredential credentials = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/delivery_window_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/delivery_window_sync.proto new file mode 100644 index 00000000000..3b5a031e1d9 --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/delivery_window_sync.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package com.example.acmewidgets.delivery.v1; + +option java_package = "com.example.acmewidgets.delivery.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message DeliveryWindowRecord { + string window_pattern = 1; +} + +message DeliveryWindowSync { + string tenant_key = 1; + repeated DeliveryWindowRecord records = 2; + string source_warehouse = 3; + google.protobuf.Timestamp deleted_time = 4; + google.protobuf.Timestamp updated_time = 5; +} + +message DeliveryWindowSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated DeliveryWindowSync windows = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/entitlement_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/entitlement_sync.proto new file mode 100644 index 00000000000..87a8f5abc9c --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/entitlement_sync.proto @@ -0,0 +1,86 @@ +syntax = "proto3"; + +package com.example.acmewidgets.billing.v1; + +option java_package = "com.example.acmewidgets.billing.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message Entitlement { + reserved 4, 11; + reserved "enabling_org_perm", "is_metered_pricing_allowed"; + EntitlementKey key = 1; + EntitlementVersion version = 2; + EntitlementTarget target = 3; + map policy_toggles = 5; + map preference_toggles = 6; + map string_values = 7; + map numeric_values = 8; + map rate_limits = 9; + map resource_limits = 10; + EntitlementStateWrapper.StateEnum state = 12; + MeteredStatusWrapper.StatusEnum metered_pricing_status = 13; + string source_warehouse = 14; + google.protobuf.Timestamp deleted_time = 15; + google.protobuf.Timestamp updated_time = 16; +} + +message EntitlementKey { + string entitlement_name = 1; + string tenant_key = 2; + string entitlement_id = 3; +} + +message EntitlementVersion { + uint64 version = 1; +} + +message EntitlementTarget { + string warehouse_id = 1; + string functional_area = 2; + string warehouse_cell = 3; +} + +message PolicyToggle { + string toggle_name = 1; + bool enabled = 2; +} + +message PreferenceToggle { + string preference_name = 1; + bool enabled = 2; +} + +message StringOrgValue { + string parameter_name = 1; + string value = 2; +} + +message NumericOrgValue { + string parameter_name = 1; + int64 value = 2; +} + +message EntitlementStateWrapper { + enum StateEnum { + NOT_AVAILABLE = 0; + AVAILABLE = 1; + ENABLED = 2; + } +} + +message MeteredStatusWrapper { + enum StatusEnum { + DISABLED = 0; + ENABLED = 1; + NOT_AVAILABLE = 2; + NOT_SUPPORTED = 3; + } +} + +message EntitlementSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated Entitlement entitlements = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/storefront_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/storefront_sync.proto new file mode 100644 index 00000000000..4a85cc0e0f5 --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/storefront_sync.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; + +package com.example.acmewidgets.storefront.v1; + +option java_package = "com.example.acmewidgets.storefront.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message Storefront { + string tenant_key = 1; + string domain_id = 2; + string domain_url = 3; + string feature_namespace = 4; + string source_warehouse = 5; + google.protobuf.Timestamp deleted_time = 6; + google.protobuf.Timestamp updated_time = 7; +} + +message StorefrontSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated Storefront storefronts = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/voucher_revocation_sync.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/voucher_revocation_sync.proto new file mode 100644 index 00000000000..ff4ce9f03c8 --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/voucher_revocation_sync.proto @@ -0,0 +1,41 @@ +syntax = "proto2"; + +package com.example.acmewidgets.auth.v1.proto2; + +option java_package = "com.example.acmewidgets.auth.v1.proto2"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; + +message TokenRevocation { + required string tenant_id = 1; + required string token_id = 2; + optional string reason = 3 [default = "rotated"]; + optional bool soft_revoke = 4 [default = false]; + extensions 100 to 199; + extensions 200 to 299; +} + +message AppUserRevocation { + required string tenant_id = 1; + required string user_id = 2; + required string consumer_key = 3; + optional google.protobuf.Timestamp revoke_before_time = 4; +} + +extend TokenRevocation { + optional string partner_revocation_source = 100; + optional int64 partner_revocation_epoch_ms = 101; +} + +message TokenRevocationSyncResponse { + repeated TokenRevocation revocations = 1; + optional string bookmark = 2; + optional bool more_available = 3 [default = false]; +} + +message AppUserRevocationSyncResponse { + repeated AppUserRevocation revocations = 1; + optional string bookmark = 2; + optional bool more_available = 3 [default = false]; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_common.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_common.proto new file mode 100644 index 00000000000..ed8ad6ecbb0 --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_common.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package com.example.acmewidgets.common.v1; + +option java_package = "com.example.acmewidgets.common.v1"; +option java_multiple_files = true; + +message WarehouseEndpoint { + string warehouse_id = 1; + string region_code = 2; +} + +message PartnerEndpoint { + string partner_id = 1; + string partner_name = 2; + string fulfillment_region = 3; +} + +message CatalogSyncHeader { + string bookmark = 1; + bool more_available = 2; + oneof origin { + WarehouseEndpoint warehouse = 3; + PartnerEndpoint partner = 4; + } +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_endpoint_types.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_endpoint_types.proto new file mode 100644 index 00000000000..61b0e8dff58 --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_endpoint_types.proto @@ -0,0 +1,49 @@ +syntax = "proto3"; + +package com.example.acmewidgets.governance.v1.endpointtypes; + +option java_package = "com.example.acmewidgets.governance.v1.endpointtypes"; +option java_multiple_files = true; + +message CatalogQuery { + message NamedCatalogConnection { + string named_connection_name = 1; + } + message QueryOp { + string id = 1; + string display_name = 2; + string method = 3; + string path = 4; + NamedCatalogConnection default_connection = 5; + } + NamedCatalogConnection named_connection = 1; + repeated QueryOp ops = 2; + uint64 version = 3; +} + +message BulkOrder { + message NamedCatalogConnectionRef { + string named_connection_name = 1; + } + message Key { + NamedCatalogConnectionRef named_connection = 1; + } + Key key = 1; + string authority = 2; + string path = 3; +} + +message FlashSale { + message PromotionId { + string promotion_id = 1; + } + message Key { + PromotionId promotion_id = 1; + string remote_tenant_id = 2; + } + Key key = 1; +} + +message PreSaleSignup { + string path = 1; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_governance.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_governance.proto new file mode 100644 index 00000000000..3e67809daea --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_governance.proto @@ -0,0 +1,93 @@ +syntax = "proto3"; + +package com.example.acmewidgets.governance.v1; + +option java_package = "com.example.acmewidgets.governance.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; +import "widget_endpoint_types.proto"; + +enum RuleMode { + ALL_OF = 0; + ANY_OF = 1; +} + +enum TypedHeader { + BOT = 0; +} + +enum HttpVerb { + GET = 0; + POST = 1; + PUT = 2; + PATCH = 3; + DELETE = 4; + HEAD = 5; + OPTIONS = 6; + TRACE = 7; +} + +message Matcher { + oneof matcher { + HttpHeaderMatcher http_header_matcher = 1; + HttpResourceMatcher http_resource_matcher = 2; + } +} + +message Condition { + RuleMode mode = 1; + repeated Matcher matchers = 2; +} + +message HttpHeaderMatcher { + oneof key { + string name = 1; + TypedHeader typed_header = 2; + } + string value_regex = 3; +} + +message HttpResourceMatcher { + repeated HttpVerb method = 1; + string path_regex = 2; +} + +message PolicyTemplate { + string name = 1; +} + +message Policy { + uint64 version = 1; + string name = 2; + PolicyTemplate template = 3; + string config_json = 4; + int64 execution_order = 5; + Condition condition = 6; +} + +message WidgetEndpoint { + string tenant_key = 1; + uint64 version = 2; + string name = 3; + repeated Policy policies = 4; + oneof endpoint_kind { + .com.example.acmewidgets.governance.v1.endpointtypes.CatalogQuery catalog_query = 5; + .com.example.acmewidgets.governance.v1.endpointtypes.BulkOrder bulk_order = 6; + .com.example.acmewidgets.governance.v1.endpointtypes.FlashSale flash_sale = 7; + .com.example.acmewidgets.governance.v1.endpointtypes.PreSaleSignup pre_sale_signup = 8; + } +} + +message WidgetGovernanceSync { + WidgetEndpoint endpoint = 1; + google.protobuf.Timestamp deleted_time = 2; + string source_warehouse = 3; + google.protobuf.Timestamp updated_time = 4; +} + +message WidgetGovernanceSyncResponse { + com.example.acmewidgets.common.v1.CatalogSyncHeader header = 1; + repeated WidgetGovernanceSync records = 2; +} diff --git a/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_order_graph.proto b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_order_graph.proto new file mode 100644 index 00000000000..d0af738b1cf --- /dev/null +++ b/phoenix-core/src/test/resources/protobuf/acmewidgets/widget_order_graph.proto @@ -0,0 +1,115 @@ +syntax = "proto3"; + +package com.example.acmewidgets.orders.v1; + +option java_package = "com.example.acmewidgets.orders.v1"; +option java_multiple_files = true; + +import "google/protobuf/timestamp.proto"; +import "widget_common.proto"; + +message Money { + string currency_code = 1; + int64 units = 2; + int32 nanos = 3; +} + +message Category { + string id = 1; + string name = 2; + Category parent = 3; + repeated Category children = 4; + map attributes = 5; +} + +message ContactInfo { + string email = 1; + string phone = 2; + message Address { + string street = 1; + string city = 2; + string region = 3; + string postal_code = 4; + string country_code = 5; + message GeoPoint { + double latitude = 1; + double longitude = 2; + } + GeoPoint geo = 6; + } + repeated Address addresses = 3; +} + +message LineItem { + string line_id = 1; + string sku = 2; + Category category = 3; + int32 quantity = 4; + Money unit_price = 5; + Money line_total = 6; + map regional_prices = 7; + message Modifier { + string modifier_id = 1; + string display_name = 2; + enum Kind { + KIND_UNSPECIFIED = 0; + DISCOUNT = 1; + SURCHARGE = 2; + GIFT_WRAP = 3; + } + Kind kind = 3; + Money amount = 4; + repeated Modifier sub_modifiers = 5; + } + repeated Modifier modifiers = 8; + map named_modifiers = 9; +} + +message PaymentMethod { + string payment_id = 1; + Money amount = 2; + message CreditCard { + string masked_pan = 1; + string card_network = 2; + int32 exp_year = 3; + int32 exp_month = 4; + } + message BankAccount { + string masked_iban = 1; + string bank_code = 2; + } + message DigitalWallet { + string wallet_type = 1; + string account_id = 2; + } + oneof method_kind { + CreditCard credit_card = 3; + BankAccount bank_account = 4; + DigitalWallet digital_wallet = 5; + } +} + +message Customer { + string customer_id = 1; + string display_name = 2; + ContactInfo contact = 3; + com.example.acmewidgets.common.v1.WarehouseEndpoint home_warehouse = 4; + map preferences = 5; +} + +message Order { + string order_id = 1; + Customer customer = 2; + repeated LineItem line_items = 3; + repeated PaymentMethod payments = 4; + Money subtotal = 5; + Money tax_total = 6; + Money grand_total = 7; + google.protobuf.Timestamp created_time = 8; + message Event { + google.protobuf.Timestamp when = 1; + string kind = 2; + map payload = 3; + } + repeated Event history = 9; +} diff --git a/pom.xml b/pom.xml index 17a59862040..c436c7fa621 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ along with hbase.version (defined in profiles) --> 3.4.2 - 2.1.0 + 2.2.0 hbase-${hbase.profile} @@ -1343,6 +1343,11 @@ phoenix-shaded-commons-cli ${phoenix.thirdparty.version} + + org.apache.phoenix.thirdparty + phoenix-shaded-protobuf + ${phoenix.thirdparty.version} + joda-time joda-time @@ -1779,6 +1784,29 @@ org.apache.hbase.thirdparty.org.apache.commons.cli.** + + true + New PROTOBUF feature code must use the relocated phoenix-shaded-protobuf runtime + (org.apache.phoenix.thirdparty.com.google.protobuf.*). The unshaded com.google.protobuf + is reserved for the legacy HBase 2.x coprocessor RPC surface and existing Phoenix + coprocessor stubs only; org.apache.hbase.thirdparty.com.google.protobuf belongs to + HBase's internal RPC framework and has no legitimate use in Phoenix code. + org.apache.phoenix.protobuf.ProtobufUtil is grandfathered because it is the legacy + pb-2.5 marshalling helper for HBase coprocessor RPC and predates this rule. + ProtobufDescriptorServiceWireTest is excluded because it tests the + unshaded pb-2.5 coprocessor RPC envelope of ProtobufDescriptorService, + and the generated stub's bytes-field setters require com.google.protobuf.ByteString + to construct the inlineDescriptorBytes payload for round-trip testing. + org.apache.phoenix.protobuf.** + + org.apache.phoenix.protobuf.ProtobufUtil + org.apache.phoenix.protobuf.text.ProtobufDescriptorServiceWireTest + + + com.google.protobuf.** + org.apache.hbase.thirdparty.com.google.protobuf.** + + true Use commons lang 3 diff --git a/src/main/config/spotbugs/spotbugs-exclude.xml b/src/main/config/spotbugs/spotbugs-exclude.xml index 155fe6c1929..cae32e61e5c 100644 --- a/src/main/config/spotbugs/spotbugs-exclude.xml +++ b/src/main/config/spotbugs/spotbugs-exclude.xml @@ -39,4 +39,65 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 151f98408b0245af0d3d6ed66f177031ea5d322e Mon Sep 17 00:00:00 2001 From: Viraj Jasani Date: Wed, 25 Nov 2026 23:22:36 -0800 Subject: [PATCH 2/3] addendum --- .../util/proto/ProtoPathResolver.java | 24 +++-- .../phoenix/end2end/ProtoValueIndexIT.java | 50 ---------- .../end2end/ProtoValueTypeCoverageIT.java | 94 ++++++++++++------- 3 files changed, 75 insertions(+), 93 deletions(-) diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java index 9a9b02d60c8..eb29e621f1b 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoPathResolver.java @@ -88,12 +88,14 @@ public static String canonicalSqlTypeName(FieldDescriptor.Type protoType) { case SINT64: case SFIXED64: return PLong.INSTANCE.getSqlTypeName(); + // Phoenix UNSIGNED_INT and UNSIGNED_LONG only cover the non-negative signed range, so they + // cannot hold the full unsigned range. Use BIGINT for 32-bit and DECIMAL for 64-bit. case UINT32: case FIXED32: - return PUnsignedInt.INSTANCE.getSqlTypeName(); + return PLong.INSTANCE.getSqlTypeName(); case UINT64: case FIXED64: - return PUnsignedLong.INSTANCE.getSqlTypeName(); + return PDecimal.INSTANCE.getSqlTypeName(); case BOOL: return PBoolean.INSTANCE.getSqlTypeName(); case FLOAT: @@ -346,24 +348,26 @@ private static void validateLeafCoercion(FieldDescriptor leafField, PDataType case UINT32: case FIXED32: if ( - requestedType == PLong.INSTANCE || requestedType == PUnsignedInt.INSTANCE - || requestedType == PUnsignedLong.INSTANCE || requestedType == PDecimal.INSTANCE + requestedType == PLong.INSTANCE || requestedType == PUnsignedLong.INSTANCE + || requestedType == PDecimal.INSTANCE ) { return; } - if (requestedType == PInteger.INSTANCE) { + if (requestedType == PInteger.INSTANCE || requestedType == PUnsignedInt.INSTANCE) { + // UNSIGNED_INT tops out at 2^31-1, so values up to 2^32-1 would not fit. throw narrowing(protoType, requestedType, path); } break; case UINT64: case FIXED64: - if ( - requestedType == PUnsignedLong.INSTANCE || requestedType == PLong.INSTANCE - || requestedType == PDecimal.INSTANCE - ) { + if (requestedType == PDecimal.INSTANCE) { return; } - if (requestedType == PInteger.INSTANCE || requestedType == PUnsignedInt.INSTANCE) { + if ( + requestedType == PInteger.INSTANCE || requestedType == PUnsignedInt.INSTANCE + || requestedType == PLong.INSTANCE || requestedType == PUnsignedLong.INSTANCE + ) { + // BIGINT and UNSIGNED_LONG top out at 2^63-1, so values up to 2^64-1 would not fit. throw narrowing(protoType, requestedType, path); } break; diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java index f04c2447e63..cc5c2d3d8ee 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueIndexIT.java @@ -519,56 +519,6 @@ public void nestedMessageLeafAsVarbinaryEncodedIndex() throws Exception { } } - @Test - public void uint64AsBigIntIndex() throws Exception { - try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { - registerBundleIdempotent(conn); - String table = uniqueTableName(); - String index = "IDX_" + table; - conn.createStatement() - .execute("CREATE TABLE " + table - + " (ID BIGINT NOT NULL PRIMARY KEY, C1 VARCHAR, PAYLOAD PROTOBUF<" + ENTITLEMENT + ">)" - + encodingClause()); - conn.createStatement() - .execute(indexDdl(index, table, "PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT')")); - - Map toggles = new LinkedHashMap<>(); - toggles.put("allow_returns", true); - long[] versions = { 100L, 150L, 200L, 300L, 500L, 800L }; - for (int i = 0; i < versions.length; i++) { - long id = i + 1L; - upsertRow(conn, table, id, "c1-ent-" + id, - AcmeWidgetsFixtures - .newEntitlement(AcmeWidgetsFixtures.entitlementDescriptor(descriptorGraph), - AcmeWidgetsFixtures.entitlementKeyDescriptor(descriptorGraph), - AcmeWidgetsFixtures.entitlementVersionDescriptor(descriptorGraph), - AcmeWidgetsFixtures.policyToggleDescriptor(descriptorGraph), "tenant-" + id, - "ent-name", "ent-id", versions[i], toggles) - .toByteArray()); - } - - assertIndexRowCount(conn, index, versions.length); - - String rangeSql = "SELECT ID, C1 FROM " + table - + " WHERE PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT') > ?" - + " ORDER BY PROTO_VALUE(PAYLOAD, 'version.version', 'BIGINT') ASC"; - try (PreparedStatement ps = conn.prepareStatement(rangeSql)) { - ps.setLong(1, 200L); - try (ResultSet rs = ps.executeQuery()) { - long[] expectedIds = { 4L, 5L, 6L }; - String[] expectedC1 = { "c1-ent-4", "c1-ent-5", "c1-ent-6" }; - for (int i = 0; i < expectedIds.length; i++) { - assertTrue("row " + i, rs.next()); - assertEquals(expectedIds[i], rs.getLong(1)); - assertEquals(expectedC1[i], rs.getString(2)); - } - assertFalse(rs.next()); - } - validateExplainPlan(ps, index, "RANGE SCAN"); - } - } - } - @Test public void unsetScalarIsIndexedAsTypeZero() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java index 3149d4efba1..00c591b3ed0 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java @@ -205,26 +205,24 @@ public void singularFixed32AndFixed64UnsignedLeavesReadBackUnsigned() throws Exc upsertPayload(conn, table, i + 1L, msg.toByteArray()); } String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'fixed32_field', 'BIGINT'), " - + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'BIGINT'), " + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL'), " - + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'BIGINT', '7') FROM " + table + " ORDER BY ID ASC"; + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL', '7') FROM " + table + + " ORDER BY ID ASC"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { long[] expectedF32 = { 0L, 1L, 100L, 1_000_000L, 2_147_483_647L, 4_294_967_295L, 4_294_967_294L }; - // Values of 2^63 and above do not fit in BIGINT and read as NULL, even with a default. - Long[] expectedF64 = { 0L, 1L, 1_000_000_000_000L, Long.MAX_VALUE, null, null, null }; String[] expectedF64Decimal = { "0", "1", "1000000000000", "9223372036854775807", "18446744073709551615", "18446744073709551614", "18446744073709551613" }; for (int i = 0; i < expectedF32.length; i++) { assertTrue("row " + i, rs.next()); assertEquals(i + 1L, rs.getLong(1)); assertEquals("row " + i + " f32", expectedF32[i], rs.getLong(2)); - assertEquals("row " + i + " f64", expectedF64[i], rs.getObject(3)); assertEquals("row " + i + " f64 decimal", 0, - new BigDecimal(expectedF64Decimal[i]).compareTo(rs.getBigDecimal(4))); + new BigDecimal(expectedF64Decimal[i]).compareTo(rs.getBigDecimal(3))); // A zero is not serialized in proto3, so row 0 is unset and takes the default. - Long expectedWithDefault = fixed64s[i] == 0L ? Long.valueOf(7L) : expectedF64[i]; - assertEquals("row " + i + " f64 default", expectedWithDefault, rs.getObject(5)); + String expectedWithDefault = fixed64s[i] == 0L ? "7" : expectedF64Decimal[i]; + assertEquals("row " + i + " f64 default", 0, + new BigDecimal(expectedWithDefault).compareTo(rs.getBigDecimal(4))); } assertFalse("expected exactly 7 rows", rs.next()); } @@ -469,7 +467,7 @@ public void unsetScalarUnderPresentParentReadsAsTypeZero() throws Exception { String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'child_msg.payload_string', 'VARCHAR'), " + "PROTO_VALUE(PAYLOAD, 'child_msg.bool_flag', 'BOOLEAN'), " + "PROTO_VALUE(PAYLOAD, 'child_msg.float_val', 'FLOAT'), " - + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT'), " + + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'BIGINT'), " + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL'), " + "PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY'), " + "PROTO_EXISTS(PAYLOAD, 'uint32_field') FROM " + table + " ORDER BY ID ASC"; @@ -481,7 +479,7 @@ public void unsetScalarUnderPresentParentReadsAsTypeZero() throws Exception { assertNull("id=1 col " + col, rs.getObject(col)); } // Top-level fields: the root message is present. - assertEquals(0, rs.getInt(5)); + assertEquals(0L, rs.getLong(5)); assertFalse(rs.wasNull()); assertEquals(0, BigDecimal.ZERO.compareTo(rs.getBigDecimal(6))); // Phoenix reads an empty VARCHAR or VARBINARY as NULL. @@ -553,7 +551,7 @@ public void invalidDefaultLiteralIsRejectedAtCompileTime() throws Exception { String[][] cases = { { "child_msg.filler", "INTEGER", "abc" }, { "child_msg.filler", "INTEGER", "99999999999" }, { "int64_field", "BIGINT", "1.5" }, { "child_msg.bool_flag", "BOOLEAN", "yes" }, { "child_msg.float_val", "FLOAT", "x" }, - { "uint32_field", "UNSIGNED_INT", "-1" }, { "fixed64_field", "UNSIGNED_LONG", "-1" }, + { "uint32_field", "UNSIGNED_LONG", "-1" }, { "fixed64_field", "DECIMAL", "abc" }, { "fixed64_field", "DECIMAL", "1e" } }; for (String[] c : cases) { String sql = "SELECT ID FROM " + table + " WHERE PROTO_VALUE(PAYLOAD, '" + c[0] + "', '" @@ -580,41 +578,71 @@ public void invalidDefaultLiteralIsRejectedAtCompileTime() throws Exception { } @Test - public void unrepresentableUnsignedValuesReadAsNullEvenWithDefault() throws Exception { + public void fullUnsignedRangeReadsLosslesslyWithSuggestedTypes() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { String table = createRegisteredTable(conn); - long[] fixed64s = { 5L, Long.MAX_VALUE, -5L }; - int[] uint32s = { 5, Integer.MAX_VALUE, -5 }; - for (int i = 0; i < fixed64s.length; i++) { - upsertPayload(conn, table, i + 1L, - DynamicMessage.newBuilder(allTypesDescriptor) - .setField(allTypesDescriptor.findFieldByName("fixed64_field"), fixed64s[i]) - .setField(allTypesDescriptor.findFieldByName("uint32_field"), uint32s[i]).build() - .toByteArray()); + // uint32 0xFFFFFFFF and fixed64 2^64-1 (as signed bits -1) + upsertPayload(conn, table, 1L, + DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("fixed64_field"), -1L) + .setField(allTypesDescriptor.findFieldByName("uint32_field"), -1).build().toByteArray()); + String sql = "SELECT PROTO_FIELD_TYPE(PAYLOAD, 'uint32_field'), " + + "PROTO_FIELD_TYPE(PAYLOAD, 'fixed64_field') FROM " + table; + String t32; + String t64; + try (ResultSet rs = conn.createStatement().executeQuery(sql)) { + assertTrue(rs.next()); + t32 = rs.getString(1); + t64 = rs.getString(2); } - String sql = "SELECT PROTO_VALUE(PAYLOAD, 'fixed64_field', 'UNSIGNED_LONG', '7'), " - + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT', '7') FROM " + table; - try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { - Long[] expectedLong = { 5L, Long.MAX_VALUE, null }; - Integer[] expectedInt = { 5, Integer.MAX_VALUE, null }; - for (int i = 0; i < expectedLong.length; i++) { - assertTrue("row " + i, rs.next()); - assertEquals("row " + i, expectedLong[i], rs.getObject(1)); - assertEquals("row " + i, expectedInt[i], rs.getObject(2)); - } + assertEquals("BIGINT", t32); + assertEquals("DECIMAL", t64); + sql = "SELECT PROTO_VALUE(PAYLOAD, 'uint32_field', '" + t32 + "'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', '" + t64 + "'), " + + "PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_LONG') FROM " + table; + try (ResultSet rs = conn.createStatement().executeQuery(sql)) { + assertTrue(rs.next()); + assertEquals(4_294_967_295L, rs.getLong(1)); + assertEquals(0, new BigDecimal("18446744073709551615").compareTo(rs.getBigDecimal(2))); + assertEquals(4_294_967_295L, rs.getLong(3)); assertFalse(rs.next()); } } } + @Test + public void lossyUnsignedTargetTypesAreRejectedAtCompileTime() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String[][] cases = { { "uint32_field", "UNSIGNED_INT" }, { "fixed32_field", "UNSIGNED_INT" }, + { "fixed64_field", "UNSIGNED_LONG" }, { "fixed64_field", "UNSIGNED_INT" }, + { "fixed64_field", "BIGINT" } }; + for (String[] c : cases) { + String expr = "PROTO_VALUE(PAYLOAD, '" + c[0] + "', '" + c[1] + "')"; + String[] statements = { "SELECT " + expr + " FROM " + table, + "CREATE INDEX " + generateUniqueName() + " ON " + table + " (" + expr + ")" }; + for (String sql : statements) { + try { + conn.createStatement().execute(sql); + fail("expected " + c[1] + " to be rejected for " + c[0] + ": " + sql); + } catch (SQLException e) { + assertEquals(sql, + SQLExceptionCode.PROTOBUF_VALUE_TYPE_NARROWING_NOT_PERMITTED.getErrorCode(), + e.getErrorCode()); + } + } + } + } + } + @Test public void unsignedAndBooleanDefaultsFireWhenPathAbsent() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { String table = createRegisteredTable(conn); upsertPayload(conn, table, 1L, DynamicMessage.newBuilder(allTypesDescriptor) .setField(allTypesDescriptor.findFieldByName("int64_field"), 1L).build().toByteArray()); - String sql = "SELECT PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_INT', '12'), " - + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'UNSIGNED_LONG', '34'), " + String sql = "SELECT PROTO_VALUE(PAYLOAD, 'uint32_field', 'UNSIGNED_LONG', '12'), " + + "PROTO_VALUE(PAYLOAD, 'fixed64_field', 'DECIMAL', '34'), " + "PROTO_VALUE(PAYLOAD, 'child_msg.bool_flag', 'BOOLEAN', 'TRUE'), " + "PROTO_VALUE(PAYLOAD, 'bytes_field', 'VARBINARY_ENCODED', 'enc'), " + "PROTO_VALUE_AT_TAG(PAYLOAD, '5', 'UNSIGNED_INT', '56') FROM " + table; @@ -1182,7 +1210,7 @@ public void protoFieldTypeReturnsCanonicalSqlTypeNamesAcrossProtoTypes() throws assertTrue("row " + id, rs.next()); assertEquals(id, rs.getLong(1)); assertEquals("row " + id, "BIGINT", rs.getString(2)); - assertEquals("row " + id, "UNSIGNED_INT", rs.getString(3)); + assertEquals("row " + id, "BIGINT", rs.getString(3)); assertEquals("row " + id, "BIGINT", rs.getString(4)); assertEquals("row " + id, "VARBINARY", rs.getString(5)); assertEquals("row " + id, "VARCHAR", rs.getString(6)); From fb8c6a8aa9967d3d0c6192bb7a12f1b066ead94b Mon Sep 17 00:00:00 2001 From: Viraj Jasani Date: Thu, 26 Nov 2026 09:45:16 -0800 Subject: [PATCH 3/3] some fixes --- .../function/ProtoArrayLengthFunction.java | 12 ++- .../function/ProtoExistsFunction.java | 15 ++- .../function/ProtoValueAtTagFunction.java | 20 +++- .../function/ProtoValueFunction.java | 24 ++++- .../util/proto/ProtoTagPathWalker.java | 24 +++-- .../end2end/ProtoValueTypeCoverageIT.java | 93 +++++++++++++++++-- 6 files changed, 160 insertions(+), 28 deletions(-) diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java index 20efe3cb7e0..eecd755cdba 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoArrayLengthFunction.java @@ -39,7 +39,9 @@ /** * {@code PROTO_ARRAY_LENGTH(payload, path)} — returns the count of elements in a repeated field or * entries in a map at the given path. Returns 0 when the ancestor container is not present - * (child-of-unset-parent) or the target field has zero occurrences. + * (child-of-unset-parent) or the target field has zero occurrences. Returns SQL NULL when the + * payload column value is SQL NULL or the payload is malformed (cannot be parsed along the path). + * Detection is best-effort: only the bytes scanned to resolve the path are validated. */ @FunctionParseNode.BuiltInFunction(name = ProtoArrayLengthFunction.NAME, nodeClass = ProtoArrayLengthParseNode.class, @@ -76,6 +78,11 @@ public String getName() { return NAME; } + @Override + public boolean isNullable() { + return true; + } + @Override public PDataType getDataType() { return PInteger.INSTANCE; @@ -107,8 +114,7 @@ public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { try { count = ProtoPathWalker.walkForCount(buf, offset, length, plan); } catch (IOException e) { - ptr.set(PInteger.INSTANCE.toBytes(0)); - return true; + return ProtoFunctionsUtil.setNull(ptr); } ptr.set(PInteger.INSTANCE.toBytes(count)); return true; diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java index d4394326921..ce1a0821b13 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoExistsFunction.java @@ -39,8 +39,10 @@ /** * {@code PROTO_EXISTS(payload, path)} — returns TRUE if the leaf at the given path is set on the * wire; FALSE for absent leaves (proto3 implicit defaults, unset optional / proto2, missing map - * keys, past-end indices, child-of-unset-parent, malformed payloads); SQL NULL only when the - * payload column value itself is SQL NULL. + * keys, past-end indices, child-of-unset-parent); SQL NULL when the payload column value itself is + * SQL NULL or the payload is malformed (cannot be parsed along the path). A detected malformed + * payload is not reported as FALSE. Detection is best-effort: only the bytes scanned to resolve the + * path are validated, so corruption after the target field may go unnoticed. */ @FunctionParseNode.BuiltInFunction(name = ProtoExistsFunction.NAME, nodeClass = ProtoExistsParseNode.class, @@ -77,6 +79,11 @@ public String getName() { return NAME; } + @Override + public boolean isNullable() { + return true; + } + @Override public PDataType getDataType() { return PBoolean.INSTANCE; @@ -109,9 +116,7 @@ public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { try { leaf = ProtoPathWalker.walk(buf, offset, length, plan); } catch (IOException e) { - // Malformed payload (incl. index-compile dummy-UPSERT probe) → FALSE. - ptr.set(PBoolean.INSTANCE.toBytes(false)); - return true; + return ProtoFunctionsUtil.setNull(ptr); } boolean present = leaf != null && leaf != ProtoPathWalker.LEAF_ABSENT; ptr.set(PBoolean.INSTANCE.toBytes(present)); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java index f83011a8fa7..afd38b4d0f9 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueAtTagFunction.java @@ -54,6 +54,16 @@ * {@code PROTO_VALUE_AT_TAG(payload, tagPath, sqlType[, default])} — extracts a leaf value from raw * protobuf wire bytes at the given tag-number path, decoded as the requested SQL type. Schema-less: * no descriptor registration required. + *

+ * The optional default applies only when the payload is well-formed but the leaf is absent. SQL + * NULL is returned, regardless of the default, when the payload is malformed or the value does not + * fit the requested type. Malformed-payload detection is best-effort: only the bytes scanned up to + * the leaf are validated. + *

+ * Being schema-less, integer types are read from varint fields only, as a two's-complement signed + * 64-bit value: a uint64 of 2^63 or more reads as negative and sint zigzag is not decoded. A field + * present with a different wire type (for example fixed32 or fixed64 read as BIGINT) gives SQL + * NULL, not the default. Use PROTO_VALUE with a registered descriptor for those. */ @FunctionParseNode.BuiltInFunction(name = ProtoValueAtTagFunction.NAME, nodeClass = ProtoValueAtTagParseNode.class, @@ -82,6 +92,11 @@ public String getName() { return NAME; } + @Override + public boolean isNullable() { + return true; + } + @Override public PDataType getDataType() { String dataType = (String) ((LiteralExpression) getChildren().get(2)).getValue(); @@ -115,9 +130,12 @@ public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { try { leaf = ProtoTagPathWalker.walk(buf, offset, length, plan); } catch (IOException e) { - return returnDefaultOrNull(ptr); + return ProtoFunctionsUtil.setNull(ptr); } + if (leaf == ProtoTagPathWalker.WIRE_TYPE_MISMATCH) { + return ProtoFunctionsUtil.setNull(ptr); + } if (leaf == null) { return returnDefaultOrNull(ptr); } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java index e2404022235..0e43e8ac5dd 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/function/ProtoValueFunction.java @@ -52,6 +52,11 @@ /** * {@code PROTO_VALUE(payload, path, type[, default])} — extracts a leaf value from a PROTOBUF-typed * column at the given path, coerced to the requested SQL type. + *

+ * The optional default applies only when the payload is well-formed but the leaf is absent (unset + * field, missing parent, map key or index). SQL NULL is returned, regardless of the default, when + * the payload is malformed or the value does not fit the requested type. Malformed-payload + * detection is best-effort: only the bytes scanned up to the leaf are validated. */ @FunctionParseNode.BuiltInFunction(name = ProtoValueFunction.NAME, nodeClass = ProtoValueParseNode.class, @@ -93,6 +98,11 @@ public String getName() { return NAME; } + @Override + public boolean isNullable() { + return true; + } + @Override public PDataType getDataType() { return getPDataType(); @@ -130,8 +140,7 @@ public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { try { leaf = ProtoPathWalker.walk(buf, offset, length, plan); } catch (IOException e) { - // Malformed wire (including index dummy-UPSERT probes) → SQL NULL, not abort. - return returnDefaultOrNull(ptr); + return ProtoFunctionsUtil.setNull(ptr); } if (leaf == ProtoPathWalker.LEAF_ABSENT) { // Parent present, leaf unset: the user default wins, else the field's own default. @@ -187,6 +196,15 @@ private static boolean isUnsigned64(FieldDescriptor.Type leafType) { return leafType == FieldDescriptor.Type.UINT64 || leafType == FieldDescriptor.Type.FIXED64; } + /** + * Encodes {@code v} as DECIMAL, or returns null when the encoding cannot represent it. + */ + private static byte[] decimalBytesOrNull(BigDecimal v) { + byte[] bytes = PDecimal.INSTANCE.toBytes(v); + BigDecimal decoded = (BigDecimal) PDecimal.INSTANCE.toObject(bytes, 0, bytes.length); + return v.compareTo(decoded) == 0 ? bytes : null; + } + private static byte[] coerceLeaf(Object leaf, PathPlan plan) { PDataType requestedType = plan.getRequestedType(); FieldDescriptor.Type leafType = plan.getLeafProtoFieldType(); @@ -272,7 +290,7 @@ private static byte[] coerceLeaf(Object leaf, PathPlan plan) { } if (leaf instanceof Double) { double v = (Double) leaf; - return Double.isFinite(v) ? PDecimal.INSTANCE.toBytes(BigDecimal.valueOf(v)) : null; + return Double.isFinite(v) ? decimalBytesOrNull(BigDecimal.valueOf(v)) : null; } } if (requestedType == PVarbinary.INSTANCE) { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java index aca0b83268b..c1c070d1cee 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/proto/ProtoTagPathWalker.java @@ -46,6 +46,13 @@ */ public final class ProtoTagPathWalker { + /** + * Returned by {@link #walk} when the tag is present but its wire type does not match the + * requested SQL type (for example a fixed32 field read as BIGINT). Unlike {@code null}, which + * means the tag is absent, this must not trigger a user default. + */ + public static final Object WIRE_TYPE_MISMATCH = new Object(); + private ProtoTagPathWalker() { } @@ -76,13 +83,16 @@ public static int wireTypeForSqlType(PDataType sqlType) { return -1; } - /** - * Walks the payload bytes according to the plan. Returns the decoded leaf value as a Java object, - * or {@code null} if the tag is absent or there is a wire-type mismatch. - */ /** * Walks {@code length} payload bytes starting at {@code offset} in place. The buffer is only - * read, and every returned byte[] or String is a copy. + * read, and every returned byte[] or String is a copy. Returns the decoded leaf value, {@code + * null} if the tag is absent, or {@link #WIRE_TYPE_MISMATCH} if the tag is present with a wire + * type that does not match the requested SQL type. + *

+ * Schema-less limits: integer types are read from varint fields only, as a two's-complement + * signed 64-bit value (so a uint64 of 2^63 or more reads as negative, and sint zigzag is not + * decoded). Fixed-width integer fields never match and give {@link #WIRE_TYPE_MISMATCH}. Use + * PROTO_VALUE with a registered descriptor for those. */ public static Object walk(byte[] buf, int offset, int length, TagPathPlan plan) throws IOException { @@ -125,7 +135,7 @@ private static Object readLeaf(byte[] buf, int offset, int length, TagSegment se int fieldNum = WireFormat.getTagFieldNumber(tag); int wt = WireFormat.getTagWireType(tag); if (fieldNum == seg.tagNumber) { - return wt == expectedWire ? decodeLeaf(cis, expectedWire, reqType) : null; + return wt == expectedWire ? decodeLeaf(cis, expectedWire, reqType) : WIRE_TYPE_MISMATCH; } cis.skipField(tag); } @@ -162,7 +172,7 @@ private static Object findNthElement(byte[] buf, int offset, int length, int tag count++; } } else { - return null; + return WIRE_TYPE_MISMATCH; } } return null; diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java index 00c591b3ed0..71c2788b50e 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProtoValueTypeCoverageIT.java @@ -937,31 +937,106 @@ public void defaultsMixedAcrossRowsPresentReturnsValueAbsentReturnsDefault() thr } @Test - public void defaultFiresForMalformedPayloadInsteadOfSqlNull() throws Exception { + public void malformedPayloadReadsAsSqlNullEvenWithDefault() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { String table = createRegisteredTable(conn); DynamicMessage valid = DynamicMessage.newBuilder(allTypesDescriptor) .setField(allTypesDescriptor.findFieldByName("int64_field"), 42L).build(); + // Valid message with the field unset: the default must still apply here. + DynamicMessage unset = DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("fixed32_field"), 1).build(); upsertPayload(conn, table, 1L, valid.toByteArray()); upsertPayload(conn, table, 2L, new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }); upsertPayload(conn, table, 3L, new byte[] { (byte) 0x08 }); upsertPayload(conn, table, 4L, "not-a-proto".getBytes()); upsertPayload(conn, table, 5L, valid.toByteArray()); - String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT', '12345') " + "FROM " - + table + " ORDER BY ID ASC"; + upsertPayload(conn, table, 6L, unset.toByteArray()); + String sql = "SELECT ID, PROTO_VALUE(PAYLOAD, 'int64_field', 'BIGINT', '12345'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'BIGINT', '12345'), " + + "PROTO_EXISTS(PAYLOAD, 'int64_field'), " + + "PROTO_ARRAY_LENGTH(PAYLOAD, 'int32_map') FROM " + table + " ORDER BY ID ASC"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { - long[] expected = { 42L, 12345L, 12345L, 12345L, 42L }; - for (int i = 0; i < expected.length; i++) { - assertTrue("row " + i, rs.next()); - assertEquals(i + 1L, rs.getLong(1)); - assertEquals("row " + i, expected[i], rs.getLong(2)); - assertFalse("row " + i, rs.wasNull()); + for (long id = 1L; id <= 6L; id++) { + assertTrue("row " + id, rs.next()); + assertEquals(id, rs.getLong(1)); + boolean malformed = id >= 2L && id <= 4L; + if (malformed) { + for (int col = 2; col <= 5; col++) { + rs.getObject(col); + assertTrue("malformed row " + id + " col " + col + " must be SQL NULL", rs.wasNull()); + } + } else if (id == 6L) { + // Well-formed with the field unset: default, FALSE and 0, not NULL. + assertEquals(12345L, rs.getLong(2)); + assertEquals(12345L, rs.getLong(3)); + assertFalse(rs.getBoolean(4)); + assertFalse(rs.wasNull()); + assertEquals(0, rs.getInt(5)); + assertFalse(rs.wasNull()); + } else { + assertEquals(42L, rs.getLong(2)); + assertEquals(42L, rs.getLong(3)); + assertFalse(rs.wasNull()); + assertTrue(rs.getBoolean(4)); + assertFalse(rs.wasNull()); + assertEquals(0, rs.getInt(5)); + assertFalse(rs.wasNull()); + } } assertFalse(rs.next()); } } } + @Test + public void doubleToDecimalOutsideEncodableRangeReadsAsNull() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + String[] keys = { "a", "b", "c", "d", "e", "f" }; + double[] values = { 1.5, 1e100, 1e300, -1e300, 1e-300, Double.MAX_VALUE }; + upsertPayload(conn, table, 1L, + buildStrFloatAndDoubleMapPayload(keys, new float[keys.length], values, 0).toByteArray()); + StringBuilder sql = new StringBuilder("SELECT "); + for (String k : keys) { + sql.append("PROTO_VALUE(PAYLOAD, 'str_double_map.").append(k) + .append("', 'DECIMAL', '7'), "); + } + sql.append("ID FROM ").append(table); + try (ResultSet rs = conn.createStatement().executeQuery(sql.toString())) { + assertTrue(rs.next()); + assertEquals(0, new BigDecimal("1.5").compareTo(rs.getBigDecimal(1))); + assertEquals(0, new BigDecimal("1e100").compareTo(rs.getBigDecimal(2))); + // Out of the DECIMAL exponent range: NULL, never a wrapped value and never the default. + for (int col = 3; col <= 6; col++) { + assertNull("col " + col, rs.getBigDecimal(col)); + } + assertFalse(rs.next()); + } + } + } + + @Test + public void atTagWireTypeMismatchReturnsNullEvenWithDefault() throws Exception { + try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) { + String table = createRegisteredTable(conn); + // fixed32_field (tag 1) is present on the wire as a fixed32, int64_field (tag 7) is absent. + upsertPayload(conn, table, 1L, DynamicMessage.newBuilder(allTypesDescriptor) + .setField(allTypesDescriptor.findFieldByName("fixed32_field"), 1).build().toByteArray()); + String sql = "SELECT PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'BIGINT', '12345'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '1', 'BIGINT'), " + + "PROTO_VALUE_AT_TAG(PAYLOAD, '7', 'BIGINT', '12345') FROM " + table; + try (ResultSet rs = conn.createStatement().executeQuery(sql)) { + assertTrue(rs.next()); + rs.getLong(1); + assertTrue("present with another wire type: NULL, not the default", rs.wasNull()); + rs.getLong(2); + assertTrue(rs.wasNull()); + assertEquals("absent tag takes the default", 12345L, rs.getLong(3)); + assertFalse(rs.next()); + } + } + } + @Test public void literalNullDefaultReturnsSqlNull() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl(), testProps())) {