+ * 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
+ * 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,
+ 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
+ * 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,
+ 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
+ * Segment classification:
+ *
+ * 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:
+ *
+ * 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
+ * Grammar:
+ *
+ *
+ * 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 {
+ 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
+ * 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
+ * {@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
+ * 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:
+ *
+ * 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:
+ *
+ *
+ * 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
+ * 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
+ * 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
+ *
+ */
+public final class ProtoPathResolver {
+
+ private ProtoPathResolver() {
+ }
+
+ public static PathPlan resolve(List
+ *
+ * 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()}.
+ *
+ * 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
+ * ALTER PROTOBUF DESCRIPTOR [ IF EXISTS ] qualified_proto_name
+ * FROM url_string_literal -- URL of a serialized FileDescriptorSet
+ *
+ *
+ * CREATE PROTOBUF BUNDLE [ IF NOT EXISTS ] (
+ * qualified_proto_name [, qualified_proto_name ]*
+ * )
+ * FROM url_string_literal
+ * ;
+ *
+ *
+ *
+ * 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
+ * CREATE PROTOBUF DESCRIPTOR [ IF NOT EXISTS ] qualified_proto_name
+ * FROM url_string_literal -- URL of a serialized FileDescriptorSet
+ *
+ *
+ * DROP PROTOBUF DESCRIPTOR [ IF EXISTS ] qualified_proto_name
+ *
+ *
+ *
+ * @param sourceUrl the URL the bytes came from — used only for error-message attribution; pass
+ * {@code "
+ * 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
+ * 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 @@