+ * 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
+ * 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
+ *
+ * @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