feat(agents): move agents into dbx repo

This commit is contained in:
t8y2 committed 2026-06-23 11:38:16 +08:00
1 parent ab35fda299
commit 3a25487dea
215 files changed
+29740 -15

No files matched your search

@@ -0,0 +1,205 @@
package com.dbx.agent;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {
private Connection connection;
private String configuredDatabase = "";
@Override
public final Connection getConnection() {
return connection;
}
@Override
public final void connect(ConnectParams params) {
uncheckedVoid(() -> {
loadDriver(params);
connection = openConnection(params);
configuredDatabase = params.getDatabase();
afterConnect(params, connection);
});
}
@Override
public final boolean testConnection(ConnectParams params) {
return unchecked(() -> {
loadDriver(params);
try (Connection conn = openConnection(params)) {
return conn.isValid(5);
}
});
}
private void loadDriver(ConnectParams params) throws Exception {
List<String> driverPaths = params.getJdbc_driver_paths();
String driverClass = params.getJdbc_driver_class();
if (driverClass == null || driverClass.isEmpty()) {
driverClass = driverClass();
}
if (driverPaths != null && !driverPaths.isEmpty()) {
List<URL> urls = new ArrayList<>();
for (String path : driverPaths) {
urls.add(Paths.get(path).toUri().toURL());
}
URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
Driver driver = (Driver) Class.forName(driverClass, true, loader).getDeclaredConstructor().newInstance();
DriverManager.registerDriver(new DriverShim(driver));
} else {
Class.forName(driverClass);
}
}
private static final class DriverShim implements Driver {
private final Driver driver;
DriverShim(Driver driver) {
this.driver = driver;
}
@Override
public Connection connect(String url, java.util.Properties info) throws java.sql.SQLException {
return driver.connect(url, info);
}
@Override
public boolean acceptsURL(String url) throws java.sql.SQLException {
return driver.acceptsURL(url);
}
@Override
public java.sql.DriverPropertyInfo[] getPropertyInfo(String url, java.util.Properties info) throws java.sql.SQLException {
return driver.getPropertyInfo(url, info);
}
@Override
public int getMajorVersion() {
return driver.getMajorVersion();
}
@Override
public int getMinorVersion() {
return driver.getMinorVersion();
}
@Override
public boolean jdbcCompliant() {
return driver.jdbcCompliant();
}
@Override
public java.util.logging.Logger getParentLogger() throws java.sql.SQLFeatureNotSupportedException {
return driver.getParentLogger();
}
}
@Override
public QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options) {
return JdbcExecutor.INSTANCE.execute(
requireConnected(),
sql,
schema,
this::setSchemaSQL,
options.getMaxRows(),
options.getFetchSize(),
options.getTimeoutSecs(),
this::resultValue
);
}
@Override
public QueryPageResult executeQueryPage(String sql, String schema, QueryPageOptions options) {
return JdbcExecutor.INSTANCE.executePage(
requireConnected(),
sql,
schema,
this::setSchemaSQL,
options,
this::resultValue
);
}
@Override
public QueryPageResult fetchQueryPage(String sessionId, int pageSize) {
return JdbcExecutor.INSTANCE.fetchPage(sessionId, pageSize);
}
@Override
public boolean closeQuerySession(String sessionId) {
return JdbcExecutor.INSTANCE.closeQuerySession(sessionId);
}
@Override
public QueryResult executeTransaction(List<String> statements, String schema) {
return TransactionExecutor.executeUpdateStatements(requireConnected(), statements, schema, this::setSchemaSQL);
}
@Override
public void disconnect() {
uncheckedVoid(() -> {
if (connection != null) {
connection.close();
}
connection = null;
});
}
protected abstract String driverClass();
protected abstract String buildJdbcUrl(ConnectParams params);
protected Connection openConnection(ConnectParams params) throws Exception {
return DriverManager.getConnection(buildJdbcUrl(params), params.getUsername(), params.getPassword());
}
protected void afterConnect(ConnectParams params, Connection connection) throws Exception {
}
protected String getConfiguredDatabase() {
return configuredDatabase;
}
protected Object resultValue(ResultSet rs, int index, int sqlType) {
return unchecked(() -> {
Object value;
switch (sqlType) {
case Types.BIGINT:
value = rs.getLong(index);
break;
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
value = rs.getInt(index);
break;
case Types.FLOAT:
case Types.REAL:
value = rs.getFloat(index);
break;
case Types.DOUBLE:
value = rs.getDouble(index);
break;
case Types.DECIMAL:
case Types.NUMERIC:
value = rs.getBigDecimal(index);
break;
case Types.BOOLEAN:
case Types.BIT:
value = rs.getBoolean(index);
break;
default:
value = rs.getString(index);
break;
}
return rs.wasNull() ? null : value;
});
}
}
@@ -0,0 +1,134 @@
package com.dbx.agent;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class AgentProtocol {
public static final int PROTOCOL_VERSION = 1;
public static final String METHOD_HANDSHAKE = "handshake";
public static final String METHOD_CONNECT = "connect";
public static final String METHOD_TEST_CONNECTION = "test_connection";
public static final String METHOD_VALIDATE_CONNECTION = "validate_connection";
public static final String METHOD_LIST_DATABASES = "list_databases";
public static final String METHOD_LIST_SCHEMAS = "list_schemas";
public static final String METHOD_LIST_TABLES = "list_tables";
public static final String METHOD_LIST_OBJECTS = "list_objects";
public static final String METHOD_GET_OBJECT_SOURCE = "get_object_source";
public static final String METHOD_GET_TABLE_DDL = "get_table_ddl";
public static final String METHOD_GET_COLUMNS = "get_columns";
public static final String METHOD_LIST_INDEXES = "list_indexes";
public static final String METHOD_LIST_FOREIGN_KEYS = "list_foreign_keys";
public static final String METHOD_LIST_TRIGGERS = "list_triggers";
public static final String METHOD_EXECUTE_QUERY = "execute_query";
public static final String METHOD_EXECUTE_QUERY_PAGE = "execute_query_page";
public static final String METHOD_FETCH_QUERY_PAGE = "fetch_query_page";
public static final String METHOD_CLOSE_QUERY_SESSION = "close_query_session";
public static final String METHOD_GET_EXPLAIN_INFO = "get_explain_info";
public static final String METHOD_EXECUTE_TRANSACTION = "execute_transaction";
public static final String METHOD_DISCONNECT = "disconnect";
public static final String METHOD_SHUTDOWN = "shutdown";
public static final String MONGO_METHOD_LIST_DATABASES = "list_databases";
public static final String MONGO_METHOD_LIST_COLLECTIONS = "list_collections";
public static final String MONGO_METHOD_FIND_DOCUMENTS = "find_documents";
public static final String MONGO_METHOD_INSERT_DOCUMENT = "insert_document";
public static final String MONGO_METHOD_UPDATE_DOCUMENT = "update_document";
public static final String MONGO_METHOD_DELETE_DOCUMENT = "delete_document";
public static final String KV_METHOD_LIST_PREFIX = "kv_list_prefix";
public static final String KV_METHOD_GET = "kv_get";
public static final String KV_METHOD_PUT = "kv_put";
public static final String KV_METHOD_DELETE = "kv_delete";
public static final String CAPABILITY_CONNECT = "connect";
public static final String CAPABILITY_TEST_CONNECTION = "test_connection";
public static final String CAPABILITY_METADATA = "metadata";
public static final String CAPABILITY_QUERY = "query";
public static final String CAPABILITY_PAGED_QUERY = "paged_query";
public static final String CAPABILITY_TRANSACTION = "transaction";
public static final String CAPABILITY_DDL = "ddl";
public static final String CAPABILITY_KV = "kv";
public static final List<String> CAPABILITIES = Collections.unmodifiableList(Arrays.asList(
CAPABILITY_CONNECT,
CAPABILITY_TEST_CONNECTION,
CAPABILITY_METADATA,
CAPABILITY_QUERY,
CAPABILITY_PAGED_QUERY,
CAPABILITY_TRANSACTION,
CAPABILITY_DDL
));
public static final List<String> ALL_CAPABILITIES = Collections.unmodifiableList(Arrays.asList(
CAPABILITY_CONNECT,
CAPABILITY_TEST_CONNECTION,
CAPABILITY_METADATA,
CAPABILITY_QUERY,
CAPABILITY_PAGED_QUERY,
CAPABILITY_TRANSACTION,
CAPABILITY_DDL,
CAPABILITY_KV
));
public static final List<String> COMMON_METHODS = Collections.unmodifiableList(Arrays.asList(
METHOD_HANDSHAKE,
METHOD_CONNECT,
METHOD_TEST_CONNECTION,
METHOD_VALIDATE_CONNECTION,
METHOD_LIST_DATABASES,
METHOD_LIST_SCHEMAS,
METHOD_LIST_TABLES,
METHOD_LIST_OBJECTS,
METHOD_GET_OBJECT_SOURCE,
METHOD_GET_TABLE_DDL,
METHOD_GET_COLUMNS,
METHOD_LIST_INDEXES,
METHOD_LIST_FOREIGN_KEYS,
METHOD_LIST_TRIGGERS,
METHOD_EXECUTE_QUERY,
METHOD_EXECUTE_QUERY_PAGE,
METHOD_FETCH_QUERY_PAGE,
METHOD_CLOSE_QUERY_SESSION,
METHOD_GET_EXPLAIN_INFO,
METHOD_EXECUTE_TRANSACTION,
METHOD_DISCONNECT,
METHOD_SHUTDOWN
));
public static final List<String> MONGO_LEGACY_METHODS = Collections.unmodifiableList(Arrays.asList(
MONGO_METHOD_LIST_DATABASES,
MONGO_METHOD_LIST_COLLECTIONS,
MONGO_METHOD_FIND_DOCUMENTS,
MONGO_METHOD_INSERT_DOCUMENT,
MONGO_METHOD_UPDATE_DOCUMENT,
MONGO_METHOD_DELETE_DOCUMENT
));
public static final List<String> KV_METHODS = Collections.unmodifiableList(Arrays.asList(
KV_METHOD_LIST_PREFIX,
KV_METHOD_GET,
KV_METHOD_PUT,
KV_METHOD_DELETE
));
private AgentProtocol() {
}
public static HandshakeResult handshakeResult() {
return new HandshakeResult(PROTOCOL_VERSION, PROTOCOL_VERSION, CAPABILITIES);
}
public static final class HandshakeResult {
private final int protocolVersion;
private final int agentProtocolVersion;
private final List<String> capabilities;
private HandshakeResult(int protocolVersion, int agentProtocolVersion, List<String> capabilities) {
this.protocolVersion = protocolVersion;
this.agentProtocolVersion = agentProtocolVersion;
this.capabilities = capabilities;
}
}
}
@@ -0,0 +1,102 @@
package com.dbx.agent;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class BaseDatabaseAgent implements DatabaseAgent {
@Override
public List<ObjectInfo> listObjects(String schema) {
List<ObjectInfo> result = new ArrayList<>();
for (TableInfo table : listTables(schema)) {
result.add(new ObjectInfo(table.getName(), table.getTable_type(), schema, table.getComment()));
}
return result;
}
@Override
public ObjectSource getObjectSource(String schema, String name, String objectType) {
throw new UnsupportedOperationException("Object source is not supported");
}
@Override
public String getTableDdl(String schema, String table) {
List<IndexInfo> indexes;
try {
indexes = listIndexes(schema, table);
} catch (RuntimeException e) {
indexes = Collections.emptyList();
}
List<ForeignKeyInfo> foreignKeys;
try {
foreignKeys = listForeignKeys(schema, table);
} catch (RuntimeException e) {
foreignKeys = Collections.emptyList();
}
return DatabaseAgent.buildTableDdl(schema, table, getColumns(schema, table), indexes, foreignKeys);
}
@Override
public QueryPageResult executeQueryPage(String sql, String schema, QueryPageOptions options) {
Connection conn = requireConnected();
return JdbcExecutor.INSTANCE.executePage(
conn,
sql,
schema,
this::setSchemaSQL,
options,
JdbcExecutor.INSTANCE::defaultResultValue
);
}
@Override
public QueryPageResult fetchQueryPage(String sessionId, int pageSize) {
return JdbcExecutor.INSTANCE.fetchPage(sessionId, pageSize);
}
@Override
public boolean closeQuerySession(String sessionId) {
return JdbcExecutor.INSTANCE.closeQuerySession(sessionId);
}
@Override
public QueryResult executeTransaction(List<String> statements, String schema) {
return TransactionExecutor.executeUpdateStatements(requireConnected(), statements, schema, this::setSchemaSQL);
}
protected Connection requireConnected() {
Connection conn = getConnection();
if (conn == null) {
throw new IllegalStateException("Not connected");
}
return conn;
}
protected static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected static void uncheckedVoid(ThrowingRunnable runnable) {
unchecked(() -> {
runnable.run();
return null;
});
}
protected interface ThrowingSupplier<T> {
T get() throws Exception;
}
protected interface ThrowingRunnable {
void run() throws Exception;
}
}
@@ -0,0 +1,176 @@
package com.dbx.agent;
import java.util.Objects;
public final class ColumnInfo {
private String name;
private String data_type;
private boolean is_nullable;
private String column_default;
private boolean is_primary_key;
private String extra;
private String comment;
private Integer numeric_precision;
private Integer numeric_scale;
private Integer character_maximum_length;
public ColumnInfo() {
this("", "", true, null, false);
}
public ColumnInfo(String name, String data_type, boolean is_nullable, String column_default, boolean is_primary_key) {
this(name, data_type, is_nullable, column_default, is_primary_key, null, null, null, null, null);
}
public ColumnInfo(
String name,
String data_type,
boolean is_nullable,
String column_default,
boolean is_primary_key,
String extra,
String comment,
Integer numeric_precision,
Integer numeric_scale,
Integer character_maximum_length
) {
this.name = name;
this.data_type = data_type;
this.is_nullable = is_nullable;
this.column_default = column_default;
this.is_primary_key = is_primary_key;
this.extra = extra;
this.comment = comment;
this.numeric_precision = numeric_precision;
this.numeric_scale = numeric_scale;
this.character_maximum_length = character_maximum_length;
}
public String getName() {
return name;
}
public String getData_type() {
return data_type;
}
public boolean getIs_nullable() {
return is_nullable;
}
public String getColumn_default() {
return column_default;
}
public boolean getIs_primary_key() {
return is_primary_key;
}
public String getExtra() {
return extra;
}
public String getComment() {
return comment;
}
public Integer getNumeric_precision() {
return numeric_precision;
}
public Integer getNumeric_scale() {
return numeric_scale;
}
public Integer getCharacter_maximum_length() {
return character_maximum_length;
}
public void setName(String name) {
this.name = name;
}
public void setData_type(String data_type) {
this.data_type = data_type;
}
public void setIs_nullable(boolean is_nullable) {
this.is_nullable = is_nullable;
}
public void setColumn_default(String column_default) {
this.column_default = column_default;
}
public void setIs_primary_key(boolean is_primary_key) {
this.is_primary_key = is_primary_key;
}
public void setExtra(String extra) {
this.extra = extra;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setNumeric_precision(Integer numeric_precision) {
this.numeric_precision = numeric_precision;
}
public void setNumeric_scale(Integer numeric_scale) {
this.numeric_scale = numeric_scale;
}
public void setCharacter_maximum_length(Integer character_maximum_length) {
this.character_maximum_length = character_maximum_length;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ColumnInfo)) return false;
ColumnInfo that = (ColumnInfo) other;
return is_nullable == that.is_nullable
&& is_primary_key == that.is_primary_key
&& Objects.equals(name, that.name)
&& Objects.equals(data_type, that.data_type)
&& Objects.equals(column_default, that.column_default)
&& Objects.equals(extra, that.extra)
&& Objects.equals(comment, that.comment)
&& Objects.equals(numeric_precision, that.numeric_precision)
&& Objects.equals(numeric_scale, that.numeric_scale)
&& Objects.equals(character_maximum_length, that.character_maximum_length);
}
@Override
public int hashCode() {
return Objects.hash(
name,
data_type,
is_nullable,
column_default,
is_primary_key,
extra,
comment,
numeric_precision,
numeric_scale,
character_maximum_length
);
}
@Override
public String toString() {
return "ColumnInfo(name=" + name
+ ", data_type=" + data_type
+ ", is_nullable=" + is_nullable
+ ", column_default=" + column_default
+ ", is_primary_key=" + is_primary_key
+ ", extra=" + extra
+ ", comment=" + comment
+ ", numeric_precision=" + numeric_precision
+ ", numeric_scale=" + numeric_scale
+ ", character_maximum_length=" + character_maximum_length
+ ")";
}
}
@@ -0,0 +1,179 @@
package com.dbx.agent;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public abstract class ConfiguredJdbcAgent extends AbstractJdbcAgent {
private final JdbcAgentProfile profile;
private String configuredDatabase = "";
protected ConfiguredJdbcAgent(JdbcAgentProfile profile) {
this.profile = profile;
}
public JdbcAgentProfile getProfile() {
return profile;
}
@Override
protected String driverClass() {
return profile.getDriverClass();
}
@Override
protected String buildJdbcUrl(ConnectParams params) {
return profile.buildUrl(params);
}
@Override
protected void afterConnect(ConnectParams params, Connection connection) {
configuredDatabase = params.getDatabase();
}
@Override
public List<DatabaseInfo> listDatabases() {
return StandardJdbcMetadata.INSTANCE.listDatabases(requireConnection(), configuredDatabase);
}
@Override
public List<String> listSchemas() {
return StandardJdbcMetadata.INSTANCE.listSchemas(requireConnection(), profile);
}
@Override
public List<TableInfo> listTables(String schema) {
return StandardJdbcMetadata.INSTANCE.listTables(requireConnection(), profile, configuredDatabase, schema);
}
@Override
public List<ObjectInfo> listObjects(String schema) {
return StandardJdbcMetadata.INSTANCE.listObjects(listTables(schema), schema);
}
@Override
public ObjectSource getObjectSource(String schema, String name, String objectType) {
throw new UnsupportedOperationException("Object source is not supported");
}
@Override
public List<ColumnInfo> getColumns(String schema, String table) {
return StandardJdbcMetadata.INSTANCE.getColumns(requireConnection(), profile, configuredDatabase, schema, table);
}
@Override
public List<IndexInfo> listIndexes(String schema, String table) {
return StandardJdbcMetadata.INSTANCE.listIndexes(requireConnection(), schema, table);
}
@Override
public List<ForeignKeyInfo> listForeignKeys(String schema, String table) {
return StandardJdbcMetadata.INSTANCE.listForeignKeys(requireConnection(), schema, table);
}
@Override
public List<TriggerInfo> listTriggers(String schema, String table) {
return StandardJdbcMetadata.INSTANCE.listTriggers(schema, table);
}
@Override
public String getTableDdl(String schema, String table) {
List<IndexInfo> indexes;
try {
indexes = listIndexes(schema, table);
} catch (RuntimeException e) {
indexes = Collections.emptyList();
}
List<ForeignKeyInfo> foreignKeys;
try {
foreignKeys = listForeignKeys(schema, table);
} catch (RuntimeException e) {
foreignKeys = Collections.emptyList();
}
return DatabaseAgent.buildTableDdl(schema, table, getColumns(schema, table), indexes, foreignKeys);
}
@Override
public String setSchemaSQL(String schema) {
if (profile.getSkipExecutionContext()) {
return "";
}
return StandardJdbcMetadata.schemaSwitchSql(requireConnection(), profile, schema);
}
protected Connection requireConnection() {
return requireConnected();
}
@Override
protected Object resultValue(ResultSet rs, int index, int sqlType) {
return super.resultValue(rs, index, sqlType);
}
private static String normalizeTableType(String type) {
if (type == null || type.trim().isEmpty()) {
return "TABLE";
}
if ("BASE TABLE".equals(type.toUpperCase(Locale.ROOT))) {
return "TABLE";
}
return type;
}
private static Integer intOrNull(ResultSet rs, String column) throws Exception {
Object value = rs.getObject(column);
return value instanceof Number ? ((Number) value).intValue() : null;
}
private static Integer characterLength(ResultSet rs) throws Exception {
String typeName = rs.getString("TYPE_NAME");
if (typeName == null) {
return null;
}
String normalized = typeName.toLowerCase(Locale.ROOT);
if (!normalized.contains("char") && !normalized.contains("text")) {
return null;
}
return intOrNull(rs, "COLUMN_SIZE");
}
private static String blankToNull(String value) {
return value == null || value.trim().isEmpty() ? null : value;
}
private static void addNonBlank(Set<String> values, String value) {
if (value != null && !value.trim().isEmpty()) {
values.add(value);
}
}
private static final class IndexColumn {
private final int ordinal;
private final String name;
private IndexColumn(int ordinal, String name) {
this.ordinal = ordinal;
this.name = name;
}
private int getOrdinal() {
return ordinal;
}
private String getName() {
return name;
}
}
}
@@ -0,0 +1,243 @@
package com.dbx.agent;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class ConnectParams {
private String host;
private int port;
private String database;
private String username;
private String password;
private String url_params;
private String connection_string;
private boolean mysql_compat_mode;
private String jdbc_driver_class;
private List<String> jdbc_driver_paths;
private boolean ssl;
private String ca_cert_path;
private String client_cert_path;
private String client_key_path;
private String gbase_server;
private String informix_server;
public ConnectParams() {
this("", 0, "", "", "", "", "", false, "", Collections.emptyList());
}
public ConnectParams(
String host,
int port,
String database,
String username,
String password,
String url_params,
String connection_string,
boolean mysql_compat_mode
) {
this(host, port, database, username, password, url_params, connection_string, mysql_compat_mode, "", Collections.emptyList());
}
public ConnectParams(
String host,
int port,
String database,
String username,
String password,
String url_params,
String connection_string,
boolean mysql_compat_mode,
String jdbc_driver_class,
List<String> jdbc_driver_paths
) {
this.host = host;
this.port = port;
this.database = database;
this.username = username;
this.password = password;
this.url_params = url_params;
this.connection_string = connection_string;
this.mysql_compat_mode = mysql_compat_mode;
this.jdbc_driver_class = jdbc_driver_class;
this.jdbc_driver_paths = jdbc_driver_paths;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getDatabase() {
return database;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUrl_params() {
return url_params;
}
public String getConnection_string() {
return connection_string;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setDatabase(String database) {
this.database = database;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUrl_params(String url_params) {
this.url_params = url_params;
}
public void setConnection_string(String connection_string) {
this.connection_string = connection_string;
}
public boolean isMysql_compat_mode() {
return mysql_compat_mode;
}
public void setMysql_compat_mode(boolean mysql_compat_mode) {
this.mysql_compat_mode = mysql_compat_mode;
}
public String getJdbc_driver_class() {
return jdbc_driver_class;
}
public void setJdbc_driver_class(String jdbc_driver_class) {
this.jdbc_driver_class = jdbc_driver_class;
}
public List<String> getJdbc_driver_paths() {
return jdbc_driver_paths;
}
public void setJdbc_driver_paths(List<String> jdbc_driver_paths) {
this.jdbc_driver_paths = jdbc_driver_paths;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public String getCa_cert_path() {
return ca_cert_path;
}
public void setCa_cert_path(String ca_cert_path) {
this.ca_cert_path = ca_cert_path;
}
public String getClient_cert_path() {
return client_cert_path;
}
public void setClient_cert_path(String client_cert_path) {
this.client_cert_path = client_cert_path;
}
public String getClient_key_path() {
return client_key_path;
}
public void setClient_key_path(String client_key_path) {
this.client_key_path = client_key_path;
}
public String getGbase_server() {
return gbase_server;
}
public void setGbase_server(String gbase_server) {
this.gbase_server = gbase_server;
}
public String getInformix_server() {
return informix_server;
}
public void setInformix_server(String informix_server) {
this.informix_server = informix_server;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ConnectParams)) return false;
ConnectParams that = (ConnectParams) other;
return port == that.port
&& Objects.equals(host, that.host)
&& Objects.equals(database, that.database)
&& Objects.equals(username, that.username)
&& Objects.equals(password, that.password)
&& Objects.equals(url_params, that.url_params)
&& Objects.equals(connection_string, that.connection_string)
&& mysql_compat_mode == that.mysql_compat_mode
&& Objects.equals(jdbc_driver_class, that.jdbc_driver_class)
&& Objects.equals(jdbc_driver_paths, that.jdbc_driver_paths)
&& ssl == that.ssl
&& Objects.equals(ca_cert_path, that.ca_cert_path)
&& Objects.equals(client_cert_path, that.client_cert_path)
&& Objects.equals(client_key_path, that.client_key_path)
&& Objects.equals(gbase_server, that.gbase_server)
&& Objects.equals(informix_server, that.informix_server);
}
@Override
public int hashCode() {
return Objects.hash(host, port, database, username, password, url_params, connection_string,
mysql_compat_mode, jdbc_driver_class, jdbc_driver_paths, ssl, ca_cert_path, client_cert_path, client_key_path, gbase_server, informix_server);
}
@Override
public String toString() {
return "ConnectParams(host=" + host
+ ", port=" + port
+ ", database=" + database
+ ", username=" + username
+ ", password=" + password
+ ", url_params=" + url_params
+ ", connection_string=" + connection_string
+ ", mysql_compat_mode=" + mysql_compat_mode
+ ", jdbc_driver_class=" + jdbc_driver_class
+ ", jdbc_driver_paths=" + jdbc_driver_paths
+ ", ssl=" + ssl
+ ", ca_cert_path=" + ca_cert_path
+ ", client_cert_path=" + client_cert_path
+ ", client_key_path=" + client_key_path
+ ", gbase_server=" + gbase_server
+ ", informix_server=" + informix_server
+ ")";
}
}
@@ -0,0 +1,147 @@
package com.dbx.agent;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public interface DatabaseAgent {
void connect(ConnectParams params);
boolean testConnection(ConnectParams params);
List<DatabaseInfo> listDatabases();
List<String> listSchemas();
List<TableInfo> listTables(String schema);
default List<ObjectInfo> listObjects(String schema) {
List<ObjectInfo> result = new ArrayList<>();
for (TableInfo table : listTables(schema)) {
result.add(new ObjectInfo(table.getName(), table.getTable_type(), schema, table.getComment()));
}
return result;
}
List<ColumnInfo> getColumns(String schema, String table);
default ObjectSource getObjectSource(String schema, String name, String objectType) {
throw new UnsupportedOperationException("Object source is not supported");
}
default String getTableDdl(String schema, String table) {
List<IndexInfo> indexes;
try {
indexes = listIndexes(schema, table);
} catch (RuntimeException e) {
indexes = Collections.emptyList();
}
List<ForeignKeyInfo> foreignKeys;
try {
foreignKeys = listForeignKeys(schema, table);
} catch (RuntimeException e) {
foreignKeys = Collections.emptyList();
}
return buildTableDdl(schema, table, getColumns(schema, table), indexes, foreignKeys);
}
List<IndexInfo> listIndexes(String schema, String table);
List<ForeignKeyInfo> listForeignKeys(String schema, String table);
List<TriggerInfo> listTriggers(String schema, String table);
default QueryResult executeQuery(String sql, String schema) {
return executeQuery(sql, schema, new ExecuteQueryOptions());
}
QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options);
default QueryPageResult executeQueryPage(String sql, String schema) {
return executeQueryPage(sql, schema, new QueryPageOptions());
}
default QueryPageResult executeQueryPage(String sql, String schema, QueryPageOptions options) {
Connection conn = getConnection();
if (conn == null) {
throw new IllegalStateException("Not connected");
}
return JdbcExecutor.INSTANCE.executePage(
conn,
sql,
schema,
this::setSchemaSQL,
options,
JdbcExecutor.INSTANCE::defaultResultValue
);
}
default QueryPageResult fetchQueryPage(String sessionId, int pageSize) {
return JdbcExecutor.INSTANCE.fetchPage(sessionId, pageSize);
}
default boolean closeQuerySession(String sessionId) {
return JdbcExecutor.INSTANCE.closeQuerySession(sessionId);
}
/**
* Get DM execution plan. Supports two modes:
* mode="explain" (default) — direct plan, no execution
* mode="autotrace" — enable MONITOR_SQL_EXEC, execute SQL, then get plan with actual stats
* @return plan text
*/
default String getExplainInfo(String sql, String database, String schema, int timeoutSecs, String mode) {
throw new UnsupportedOperationException("getExplainInfo is not supported by this agent");
}
void disconnect();
Connection getConnection();
default QueryResult executeTransaction(List<String> statements, String schema) {
Connection conn = getConnection();
if (conn == null) {
throw new IllegalStateException("Not connected");
}
return TransactionExecutor.executeUpdateStatements(conn, statements, schema, this::setSchemaSQL);
}
default String setSchemaSQL(String schema) {
return "SET SCHEMA " + JdbcIdentifiers.INSTANCE.doubleQuote(schema);
}
static String buildTableDdl(
String schema,
String table,
List<ColumnInfo> columns,
List<IndexInfo> indexes,
List<ForeignKeyInfo> foreignKeys
) {
return DdlBuilder.buildTableDdl(schema, table, columns, indexes, foreignKeys);
}
static String trimSql(String sql) {
String trimmed = sql.trim();
while (trimmed.endsWith(";")) {
trimmed = trimmed.substring(0, trimmed.length() - 1).trim();
}
return trimmed;
}
static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
interface ThrowingSupplier<T> {
T get() throws Exception;
}
}
@@ -0,0 +1,41 @@
package com.dbx.agent;
import java.util.Objects;
public final class DatabaseInfo {
private String name;
public DatabaseInfo() {
this("");
}
public DatabaseInfo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof DatabaseInfo)) return false;
DatabaseInfo that = (DatabaseInfo) other;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return "DatabaseInfo(name=" + name + ")";
}
}
@@ -0,0 +1,195 @@
package com.dbx.agent;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public final class DdlBuilder {
private DdlBuilder() {
}
public static String buildTableDdl(
String schema,
String table,
List<ColumnInfo> columns,
List<IndexInfo> indexes,
List<ForeignKeyInfo> foreignKeys
) {
return buildTableDdl(schema, table, columns, indexes, foreignKeys, false, false);
}
public static String buildTableDdl(
String schema,
String table,
List<ColumnInfo> columns,
List<IndexInfo> indexes,
List<ForeignKeyInfo> foreignKeys,
boolean useBacktick
) {
return buildTableDdl(schema, table, columns, indexes, foreignKeys, useBacktick, false);
}
public static String buildTableDdl(
String schema,
String table,
List<ColumnInfo> columns,
List<IndexInfo> indexes,
List<ForeignKeyInfo> foreignKeys,
boolean useBacktick,
boolean includeColumnComments
) {
String tableRef = qualifiedName(schema, table, useBacktick);
List<String> columnLines = new ArrayList<>();
for (ColumnInfo column : columns) {
StringBuilder line = new StringBuilder();
line.append(" ");
line.append(quoteIdent(column.getName(), useBacktick));
line.append(" ");
line.append(columnTypeSql(column));
if (!column.getIs_nullable()) {
line.append(" NOT NULL");
}
if (notBlank(column.getColumn_default())) {
line.append(" DEFAULT ");
line.append(column.getColumn_default());
}
columnLines.add(line.toString());
}
List<String> primaryKeys = new ArrayList<>();
for (ColumnInfo column : columns) {
if (column.getIs_primary_key()) {
primaryKeys.add(quoteIdent(column.getName(), useBacktick));
}
}
if (!primaryKeys.isEmpty()) {
columnLines.add(" PRIMARY KEY (" + join(primaryKeys, ", ") + ")");
}
for (ForeignKeyInfo fk : foreignKeys) {
columnLines.add(
" CONSTRAINT " + quoteIdent(fk.getName(), useBacktick)
+ " FOREIGN KEY (" + quoteIdent(fk.getColumn(), useBacktick) + ") "
+ "REFERENCES " + quoteIdent(fk.getRef_table(), useBacktick) + "(" + quoteIdent(fk.getRef_column(), useBacktick) + ")"
);
}
StringBuilder ddl = new StringBuilder();
ddl.append("CREATE TABLE ");
ddl.append(tableRef);
ddl.append(" (\n");
ddl.append(join(columnLines, ",\n"));
ddl.append("\n);\n");
if (includeColumnComments) {
for (ColumnInfo column : columns) {
if (!notBlank(column.getComment())) {
continue;
}
ddl.append("\nCOMMENT ON COLUMN ");
ddl.append(tableRef);
ddl.append(".");
ddl.append(quoteIdent(column.getName(), useBacktick));
ddl.append(" IS '");
ddl.append(sqlStringBody(column.getComment()));
ddl.append("';");
}
}
for (IndexInfo index : indexes) {
if (index.getIs_primary()) {
continue;
}
String unique = index.getIs_unique() ? "UNIQUE " : "";
String using = notBlank(index.getIndex_type()) ? " USING " + index.getIndex_type() : "";
List<String> quotedColumns = new ArrayList<>();
for (String column : index.getColumns()) {
quotedColumns.add(quoteIdent(column, useBacktick));
}
String filter = notBlank(index.getFilter()) ? " WHERE " + index.getFilter() : "";
ddl.append("\nCREATE ");
ddl.append(unique);
ddl.append("INDEX ");
ddl.append(quoteIdent(index.getName(), useBacktick));
ddl.append(" ON ");
ddl.append(tableRef);
ddl.append(using);
ddl.append(" (");
ddl.append(join(quotedColumns, ", "));
ddl.append(")");
ddl.append(filter);
ddl.append(";");
if (notBlank(index.getComment())) {
ddl.append("\nCOMMENT ON INDEX ");
if (notBlank(schema)) {
ddl.append(quoteIdent(schema, useBacktick));
ddl.append(".");
}
ddl.append(quoteIdent(index.getName(), useBacktick));
ddl.append(" IS '");
ddl.append(sqlStringBody(index.getComment()));
ddl.append("';");
}
}
return ddl.toString();
}
private static String quoteIdent(String identifier, boolean useBacktick) {
return useBacktick
? JdbcIdentifiers.INSTANCE.backtick(identifier)
: JdbcIdentifiers.INSTANCE.doubleQuote(identifier);
}
private static String qualifiedName(String schema, String name, boolean useBacktick) {
if (!notBlank(schema)) {
return quoteIdent(name, useBacktick);
}
return quoteIdent(schema, useBacktick) + "." + quoteIdent(name, useBacktick);
}
private static String columnTypeSql(ColumnInfo column) {
String type = column.getData_type();
String normalized = type.toLowerCase(Locale.ROOT);
if (isCharacterType(normalized) && column.getCharacter_maximum_length() != null) {
return type + "(" + column.getCharacter_maximum_length() + ")";
}
if (isNumericType(normalized) && column.getNumeric_precision() != null) {
if (column.getNumeric_scale() != null) {
return type + "(" + column.getNumeric_precision() + ", " + column.getNumeric_scale() + ")";
}
return type + "(" + column.getNumeric_precision() + ")";
}
return type;
}
private static boolean isCharacterType(String normalized) {
return "character varying".equals(normalized)
|| "varchar".equals(normalized)
|| "char".equals(normalized)
|| "character".equals(normalized);
}
private static boolean isNumericType(String normalized) {
return "numeric".equals(normalized) || "decimal".equals(normalized);
}
private static boolean notBlank(String value) {
return value != null && !value.trim().isEmpty();
}
private static String sqlStringBody(String value) {
return value.replace("'", "''");
}
private static String join(List<String> values, String separator) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
builder.append(separator);
}
builder.append(values.get(i));
}
return builder.toString();
}
}
@@ -0,0 +1,671 @@
package com.dbx.agent;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Decode PostGIS EWKB / WKB byte streams (and PGgeometry / hex strings) into
* OGC Well-Known Text. Behaves identically to the Rust implementation in
* {@code crates/dbx-core/src/db/postgres.rs::ewkb_to_wkt}, including the
* {@code Z} / {@code M} / {@code ZM} dimension suffixes and {@code EMPTY}
* geometries. Used by the JDBC agent layer so that PostgresLike databases
* such as HighGo / KingBase / Vastbase / openGauss / GaussDB return WKT for
* {@code geometry}/{@code geography} columns instead of opaque hex blobs.
*
* <p>The decoder is permissive: any unrecognized payload (truncated bytes,
* unsupported geometry kind, non-hex strings, etc.) falls back to a hex
* representation prefixed with {@code 0x} so the cell remains visible.
*/
public final class EwkbWktDecoder {
/** Reflectively-detected PGgeometry classes that expose getValue() returning EWKT text. */
private static final String[] PGGEOMETRY_CLASS_NAMES = new String[]{
"org.postgis.PGgeometry", // legacy PostGIS-JDBC
"net.postgis.jdbc.PGgeometry", // modern PostGIS-JDBC (>= 2024 release)
"com.highgo.jdbc.geometry.PGgeometry"
};
/**
* Generic {@code org.postgresql.util.PGobject}-shaped classes. Their
* {@code getValue()} returns the textual representation the driver got off
* the wire. For PostGIS columns on HighGo / KingBase / Vastbase that text
* is the EWKB hex (e.g. {@code 0101000020E61000...}) — we still need to run
* it through the EWKB hex parser.
*/
private static final String[] PGOBJECT_CLASS_NAMES = new String[]{
"org.postgresql.util.PGobject",
"com.highgo.jdbc.util.PGobject",
"org.postgresql.geometric.PGobject"
};
private EwkbWktDecoder() {
}
/**
* Decode a JDBC-returned object from a {@code geometry} / {@code geography}
* column into a textual representation, preferring WKT.
*
* <p>Accepted inputs:
* <ul>
* <li>{@code null} — returned as-is.</li>
* <li>{@code byte[]} — interpreted as raw EWKB.</li>
* <li>A {@code PGgeometry}-like object exposing {@code getValue()} — the
* returned string is taken verbatim (already EWKT/WKT).</li>
* <li>{@link String} — if it looks like hex EWKB (with optional
* {@code 0x}/{@code \\x} prefix and a leading endian byte of
* {@code 00}/{@code 01}), it is decoded; otherwise returned as-is.</li>
* </ul>
*
* @param value raw column value
* @return decoded WKT, or a {@code 0x}-prefixed hex fallback, or {@code null}
*/
public static Object decode(Object value) {
if (value == null) {
return null;
}
if (value instanceof byte[]) {
return decodeBytes((byte[]) value);
}
if (value instanceof String) {
return decodeString((String) value);
}
// PGgeometry / PGobject and friends — pull out their getValue() text
// and run it through the same string path. For PostGIS-JDBC types
// getValue() yields EWKT (passes through unchanged); for the generic
// PGobject driver returns EWKB hex, which decodeString() decodes.
String pgValue = tryReflectiveGetValue(value);
if (pgValue != null) {
return decodeString(pgValue);
}
// Last resort: rely on toString() / underlying value.
return value.toString();
}
/** Decode a raw EWKB byte sequence; returns hex {@code 0x..} on failure. */
static String decodeBytes(byte[] raw) {
if (raw == null) {
return null;
}
String wkt = parseEwkb(raw);
if (wkt != null) {
return wkt;
}
return bytesToHexWithPrefix(raw);
}
/**
* Decode a string column. If the text matches an EWKB hex layout the bytes
* are decoded; otherwise (already WKT, ST_AsText output, etc.) returned
* unchanged.
*/
static String decodeString(String value) {
if (value == null) {
return null;
}
byte[] bytes = tryParseHex(value);
if (bytes == null) {
return value;
}
String wkt = parseEwkb(bytes);
if (wkt != null) {
return wkt;
}
// looked like hex but couldn't be parsed — preserve hex form.
return ensureHexPrefix(value);
}
/**
* Try to extract textual value from PGgeometry / PGobject-like objects via
* {@code getValue()}. Returns {@code null} if the class doesn't match any
* known PostGIS / PostgreSQL JDBC type (or the call fails reflectively).
*/
private static String tryReflectiveGetValue(Object value) {
Class<?> cls = value.getClass();
if (!matchesAnyClassName(cls, PGGEOMETRY_CLASS_NAMES)
&& !matchesAnyClassName(cls, PGOBJECT_CLASS_NAMES)) {
return null;
}
try {
Method getValue = cls.getMethod("getValue");
Object result = getValue.invoke(value);
if (result instanceof String) {
return (String) result;
}
} catch (ReflectiveOperationException ignored) {
// fall through
}
return null;
}
private static boolean matchesAnyClassName(Class<?> cls, String[] names) {
Class<?> current = cls;
while (current != null) {
for (String name : names) {
if (current.getName().equals(name)) {
return true;
}
for (Class<?> iface : current.getInterfaces()) {
if (iface.getName().equals(name)) {
return true;
}
}
}
current = current.getSuperclass();
}
return false;
}
/** @return parsed bytes, or {@code null} if {@code value} is not hex EWKB. */
static byte[] tryParseHex(String value) {
String s = value;
if (s.length() >= 2 && (s.startsWith("0x") || s.startsWith("0X"))) {
s = s.substring(2);
} else if (s.length() >= 2 && (s.startsWith("\\x") || s.startsWith("\\X"))) {
s = s.substring(2);
}
if (s.length() < 10 || (s.length() & 1) != 0) {
return null;
}
// First byte must be the WKB endian marker (00 = big, 01 = little)
char e0 = s.charAt(0);
char e1 = s.charAt(1);
if (!((e0 == '0') && (e1 == '0' || e1 == '1'))) {
return null;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
return null;
}
}
byte[] out = new byte[s.length() / 2];
for (int i = 0; i < out.length; i++) {
int hi = Character.digit(s.charAt(i * 2), 16);
int lo = Character.digit(s.charAt(i * 2 + 1), 16);
out[i] = (byte) ((hi << 4) | lo);
}
return out;
}
private static String ensureHexPrefix(String value) {
if (value.startsWith("0x") || value.startsWith("0X")) {
return value;
}
return "0x" + value;
}
static String bytesToHexWithPrefix(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2 + 2);
sb.append("0x");
for (byte b : bytes) {
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
sb.append(Character.forDigit(b & 0xF, 16));
}
return sb.toString();
}
// ── EWKB parser ────────────────────────────────────────────────────────
private static String parseEwkb(byte[] raw) {
if (raw == null || raw.length == 0) {
return null;
}
Reader reader = new Reader(raw);
Geometry g = parseGeometry(reader);
if (g == null || reader.pos != raw.length) {
return null;
}
return geometryToWkt(g);
}
private static Geometry parseGeometry(Reader reader) {
Integer endian = reader.readU8();
if (endian == null) {
return null;
}
boolean little;
if (endian == 0) {
little = false;
} else if (endian == 1) {
little = true;
} else {
return null;
}
Long typeWordBoxed = reader.readU32(little);
if (typeWordBoxed == null) {
return null;
}
long typeWord = typeWordBoxed;
Dims parsed = parseDimensions(typeWord);
long baseType = parsed.baseType;
if (parsed.hasSrid) {
if (reader.readU32(little) == null) {
return null;
}
}
Dimensions dims = parsed.dims;
switch ((int) baseType) {
case 1: { // Point
int len = dims.coordinateLen();
List<Double> coords = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
Double v = reader.readF64(little);
if (v == null) {
return null;
}
coords.add(v);
}
boolean allNan = true;
for (Double v : coords) {
if (!Double.isNaN(v)) {
allNan = false;
break;
}
}
return new Geometry(GeomKind.POINT, dims, allNan ? null : coords, null, null, null, null, null);
}
case 2: { // LineString
List<List<Double>> points = parsePoints(reader, little, dims);
if (points == null) return null;
return new Geometry(GeomKind.LINESTRING, dims, null, points, null, null, null, null);
}
case 3: { // Polygon
Long ringCount = reader.readU32(little);
if (ringCount == null) return null;
List<List<List<Double>>> rings = new ArrayList<>();
for (int i = 0; i < ringCount; i++) {
List<List<Double>> ring = parsePoints(reader, little, dims);
if (ring == null) return null;
rings.add(ring);
}
return new Geometry(GeomKind.POLYGON, dims, null, null, rings, null, null, null);
}
case 4: { // MultiPoint
Long count = reader.readU32(little);
if (count == null) return null;
List<List<Double>> mpoints = new ArrayList<>();
for (int i = 0; i < count; i++) {
List<Double> coords = readPointCoords(reader, dims);
if (coords == null) {
// sub-point parse failure (returning null != EMPTY); abort.
return null;
}
boolean allNan = true;
for (Double v : coords) {
if (!Double.isNaN(v)) {
allNan = false;
break;
}
}
mpoints.add(allNan ? null : coords);
}
return new Geometry(GeomKind.MULTIPOINT, dims, null, null, null, mpoints, null, null);
}
case 5: { // MultiLineString
Long count = reader.readU32(little);
if (count == null) return null;
List<List<List<Double>>> lines = new ArrayList<>();
for (int i = 0; i < count; i++) {
Geometry sub = parseGeometry(reader);
if (sub == null || sub.kind != GeomKind.LINESTRING) return null;
lines.add(sub.points);
}
return new Geometry(GeomKind.MULTILINESTRING, dims, null, null, lines, null, null, null);
}
case 6: { // MultiPolygon
Long count = reader.readU32(little);
if (count == null) return null;
List<List<List<List<Double>>>> polys = new ArrayList<>();
for (int i = 0; i < count; i++) {
Geometry sub = parseGeometry(reader);
if (sub == null || sub.kind != GeomKind.POLYGON) return null;
polys.add(sub.rings);
}
return new Geometry(GeomKind.MULTIPOLYGON, dims, null, null, null, null, polys, null);
}
case 7: { // GeometryCollection
Long count = reader.readU32(little);
if (count == null) return null;
List<Geometry> children = new ArrayList<>();
for (int i = 0; i < count; i++) {
Geometry sub = parseGeometry(reader);
if (sub == null) return null;
children.add(sub);
}
return new Geometry(GeomKind.GEOMETRYCOLLECTION, dims, null, null, null, null, null, children);
}
default:
return null;
}
}
private static List<List<Double>> parsePoints(Reader reader, boolean little, Dimensions dims) {
Long count = reader.readU32(little);
if (count == null) return null;
int dim = dims.coordinateLen();
List<List<Double>> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
List<Double> coords = new ArrayList<>(dim);
for (int j = 0; j < dim; j++) {
Double v = reader.readF64(little);
if (v == null) return null;
coords.add(v);
}
result.add(coords);
}
return result;
}
private static List<Double> readPointCoords(Reader reader, Dimensions parentDims) {
Integer endian = reader.readU8();
if (endian == null) return null;
boolean little;
if (endian == 0) {
little = false;
} else if (endian == 1) {
little = true;
} else {
return null;
}
Long typeWord = reader.readU32(little);
if (typeWord == null) return null;
Dims parsed = parseDimensions(typeWord);
if (parsed.baseType != 1 || !parsed.dims.equals(parentDims)) {
return null;
}
if (parsed.hasSrid) {
if (reader.readU32(little) == null) return null;
}
int dim = parsed.dims.coordinateLen();
List<Double> coords = new ArrayList<>(dim);
for (int i = 0; i < dim; i++) {
Double v = reader.readF64(little);
if (v == null) return null;
coords.add(v);
}
return coords;
}
private static Dims parseDimensions(long typeWord) {
long baseType = typeWord & 0x1FFF_FFFFL;
boolean hasZ = (typeWord & 0x8000_0000L) != 0;
boolean hasM = (typeWord & 0x4000_0000L) != 0;
boolean hasSrid = (typeWord & 0x2000_0000L) != 0;
if (baseType >= 3000) {
hasZ = true;
hasM = true;
baseType -= 3000;
} else if (baseType >= 2000) {
hasM = true;
baseType -= 2000;
} else if (baseType >= 1000) {
hasZ = true;
baseType -= 1000;
}
return new Dims(baseType, new Dimensions(hasZ, hasM), hasSrid);
}
// ── WKT formatting ─────────────────────────────────────────────────────
private static String geometryToWkt(Geometry g) {
String suffix = g.dims.suffix();
switch (g.kind) {
case POINT:
if (g.coords == null) {
return "POINT" + suffix + " EMPTY";
}
return "POINT" + suffix + "(" + formatCoord(g.coords) + ")";
case LINESTRING:
if (g.points == null || g.points.isEmpty()) {
return "LINESTRING" + suffix + " EMPTY";
}
return "LINESTRING" + suffix + "(" + formatCoordSeq(g.points) + ")";
case POLYGON:
if (g.rings == null || g.rings.isEmpty()) {
return "POLYGON" + suffix + " EMPTY";
}
return "POLYGON" + suffix + "(" + joinRings(g.rings) + ")";
case MULTIPOINT:
if (g.multiPoints == null || g.multiPoints.isEmpty()) {
return "MULTIPOINT" + suffix + " EMPTY";
}
return "MULTIPOINT" + suffix + "(" + joinMultiPoints(g.multiPoints) + ")";
case MULTILINESTRING:
if (g.rings == null || g.rings.isEmpty()) {
return "MULTILINESTRING" + suffix + " EMPTY";
}
return "MULTILINESTRING" + suffix + "(" + joinRings(g.rings) + ")";
case MULTIPOLYGON:
if (g.polygons == null || g.polygons.isEmpty()) {
return "MULTIPOLYGON" + suffix + " EMPTY";
}
return "MULTIPOLYGON" + suffix + "(" + joinPolygons(g.polygons) + ")";
case GEOMETRYCOLLECTION:
if (g.children == null || g.children.isEmpty()) {
return "GEOMETRYCOLLECTION" + suffix + " EMPTY";
}
StringBuilder sb = new StringBuilder("GEOMETRYCOLLECTION").append(suffix).append("(");
for (int i = 0; i < g.children.size(); i++) {
if (i > 0) sb.append(',');
sb.append(geometryToWkt(g.children.get(i)));
}
sb.append(')');
return sb.toString();
default:
throw new IllegalStateException("unknown geometry kind: " + g.kind);
}
}
private static String formatCoord(List<Double> coords) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < coords.size(); i++) {
if (i > 0) sb.append(' ');
sb.append(formatDouble(coords.get(i)));
}
return sb.toString();
}
private static String formatCoordSeq(List<List<Double>> points) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < points.size(); i++) {
if (i > 0) sb.append(',');
sb.append(formatCoord(points.get(i)));
}
return sb.toString();
}
private static String joinRings(List<List<List<Double>>> rings) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rings.size(); i++) {
if (i > 0) sb.append(',');
sb.append('(').append(formatCoordSeq(rings.get(i))).append(')');
}
return sb.toString();
}
private static String joinMultiPoints(List<List<Double>> mpoints) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mpoints.size(); i++) {
if (i > 0) sb.append(',');
List<Double> p = mpoints.get(i);
if (p == null) {
sb.append("EMPTY");
} else {
sb.append('(').append(formatCoord(p)).append(')');
}
}
return sb.toString();
}
private static String joinPolygons(List<List<List<List<Double>>>> polys) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < polys.size(); i++) {
if (i > 0) sb.append(',');
sb.append('(').append(joinRings(polys.get(i))).append(')');
}
return sb.toString();
}
/**
* Format a double the same way Rust's {@code f64::Display} does — shortest
* round-trippable decimal, trailing {@code .0} stripped (so {@code 116.0}
* becomes {@code "116"}, not {@code "116.0"}).
*/
static String formatDouble(double value) {
if (Double.isNaN(value)) {
return "NaN";
}
if (Double.isInfinite(value)) {
return value > 0 ? "inf" : "-inf";
}
String s = Double.toString(value);
// Strip trailing ".0" for whole-number doubles so output matches Rust.
if (s.endsWith(".0")) {
return s.substring(0, s.length() - 2);
}
return s;
}
// ── helper structs ─────────────────────────────────────────────────────
private enum GeomKind {
POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION
}
private static final class Geometry {
final GeomKind kind;
final Dimensions dims;
final List<Double> coords; // POINT
final List<List<Double>> points; // LINESTRING
final List<List<List<Double>>> rings; // POLYGON / MULTILINESTRING (lines == rings shape-wise)
final List<List<Double>> multiPoints; // MULTIPOINT (null entry = EMPTY)
final List<List<List<List<Double>>>> polygons; // MULTIPOLYGON
final List<Geometry> children; // GEOMETRYCOLLECTION
Geometry(
GeomKind kind,
Dimensions dims,
List<Double> coords,
List<List<Double>> points,
List<List<List<Double>>> rings,
List<List<Double>> multiPoints,
List<List<List<List<Double>>>> polygons,
List<Geometry> children
) {
this.kind = kind;
this.dims = dims;
this.coords = coords;
this.points = points;
this.rings = rings;
this.multiPoints = multiPoints;
this.polygons = polygons;
this.children = children;
}
}
private static final class Dimensions {
final boolean hasZ;
final boolean hasM;
Dimensions(boolean hasZ, boolean hasM) {
this.hasZ = hasZ;
this.hasM = hasM;
}
String suffix() {
if (hasZ && hasM) return " ZM";
if (hasZ) return " Z";
if (hasM) return " M";
return "";
}
int coordinateLen() {
return 2 + (hasZ ? 1 : 0) + (hasM ? 1 : 0);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Dimensions)) return false;
Dimensions d = (Dimensions) o;
return hasZ == d.hasZ && hasM == d.hasM;
}
@Override
public int hashCode() {
return (hasZ ? 1 : 0) * 31 + (hasM ? 1 : 0);
}
}
private static final class Dims {
final long baseType;
final Dimensions dims;
final boolean hasSrid;
Dims(long baseType, Dimensions dims, boolean hasSrid) {
this.baseType = baseType;
this.dims = dims;
this.hasSrid = hasSrid;
}
}
private static final class Reader {
final byte[] raw;
int pos;
Reader(byte[] raw) {
this.raw = raw;
}
Integer readU8() {
if (pos >= raw.length) return null;
int v = raw[pos] & 0xFF;
pos += 1;
return v;
}
Long readU32(boolean little) {
if (pos + 4 > raw.length) return null;
long v;
if (little) {
v = ((long) (raw[pos] & 0xFF))
| ((long) (raw[pos + 1] & 0xFF) << 8)
| ((long) (raw[pos + 2] & 0xFF) << 16)
| ((long) (raw[pos + 3] & 0xFF) << 24);
} else {
v = ((long) (raw[pos] & 0xFF) << 24)
| ((long) (raw[pos + 1] & 0xFF) << 16)
| ((long) (raw[pos + 2] & 0xFF) << 8)
| ((long) (raw[pos + 3] & 0xFF));
}
pos += 4;
return v & 0xFFFF_FFFFL;
}
Double readF64(boolean little) {
if (pos + 8 > raw.length) return null;
long bits;
if (little) {
bits = ((long) (raw[pos] & 0xFF))
| ((long) (raw[pos + 1] & 0xFF) << 8)
| ((long) (raw[pos + 2] & 0xFF) << 16)
| ((long) (raw[pos + 3] & 0xFF) << 24)
| ((long) (raw[pos + 4] & 0xFF) << 32)
| ((long) (raw[pos + 5] & 0xFF) << 40)
| ((long) (raw[pos + 6] & 0xFF) << 48)
| ((long) (raw[pos + 7] & 0xFF) << 56);
} else {
bits = ((long) (raw[pos] & 0xFF) << 56)
| ((long) (raw[pos + 1] & 0xFF) << 48)
| ((long) (raw[pos + 2] & 0xFF) << 40)
| ((long) (raw[pos + 3] & 0xFF) << 32)
| ((long) (raw[pos + 4] & 0xFF) << 24)
| ((long) (raw[pos + 5] & 0xFF) << 16)
| ((long) (raw[pos + 6] & 0xFF) << 8)
| ((long) (raw[pos + 7] & 0xFF));
}
pos += 8;
return Double.longBitsToDouble(bits);
}
}
}
@@ -0,0 +1,67 @@
package com.dbx.agent;
import java.util.Objects;
public final class ExecuteQueryOptions {
private int maxRows;
private Integer fetchSize;
private int timeoutSecs;
public ExecuteQueryOptions() {
this(JdbcExecutor.DEFAULT_MAX_ROWS, null, 0);
}
public ExecuteQueryOptions(int maxRows, Integer fetchSize) {
this(maxRows, fetchSize, 0);
}
public ExecuteQueryOptions(int maxRows, Integer fetchSize, int timeoutSecs) {
this.maxRows = maxRows;
this.fetchSize = fetchSize;
this.timeoutSecs = timeoutSecs;
}
public int getMaxRows() {
return maxRows;
}
public Integer getFetchSize() {
return fetchSize;
}
public int getTimeoutSecs() {
return timeoutSecs;
}
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public void setFetchSize(Integer fetchSize) {
this.fetchSize = fetchSize;
}
public void setTimeoutSecs(int timeoutSecs) {
this.timeoutSecs = timeoutSecs;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ExecuteQueryOptions)) return false;
ExecuteQueryOptions that = (ExecuteQueryOptions) other;
return maxRows == that.maxRows
&& timeoutSecs == that.timeoutSecs
&& Objects.equals(fetchSize, that.fetchSize);
}
@Override
public int hashCode() {
return Objects.hash(maxRows, fetchSize, timeoutSecs);
}
@Override
public String toString() {
return "ExecuteQueryOptions(maxRows=" + maxRows + ", fetchSize=" + fetchSize + ", timeoutSecs=" + timeoutSecs + ")";
}
}
@@ -0,0 +1,78 @@
package com.dbx.agent;
import java.util.Objects;
public final class ExecuteQueryParams {
private String sql;
private String schema;
private Integer maxRows;
private Integer fetchSize;
public ExecuteQueryParams() {
this("", null, null, null);
}
public ExecuteQueryParams(String sql, String schema, Integer maxRows, Integer fetchSize) {
this.sql = sql;
this.schema = schema;
this.maxRows = maxRows;
this.fetchSize = fetchSize;
}
public String getSql() {
return sql;
}
public String getSchema() {
return schema;
}
public Integer getMaxRows() {
return maxRows;
}
public Integer getFetchSize() {
return fetchSize;
}
public void setSql(String sql) {
this.sql = sql;
}
public void setSchema(String schema) {
this.schema = schema;
}
public void setMaxRows(Integer maxRows) {
this.maxRows = maxRows;
}
public void setFetchSize(Integer fetchSize) {
this.fetchSize = fetchSize;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ExecuteQueryParams)) return false;
ExecuteQueryParams that = (ExecuteQueryParams) other;
return Objects.equals(sql, that.sql)
&& Objects.equals(schema, that.schema)
&& Objects.equals(maxRows, that.maxRows)
&& Objects.equals(fetchSize, that.fetchSize);
}
@Override
public int hashCode() {
return Objects.hash(sql, schema, maxRows, fetchSize);
}
@Override
public String toString() {
return "ExecuteQueryParams(sql=" + sql
+ ", schema=" + schema
+ ", maxRows=" + maxRows
+ ", fetchSize=" + fetchSize
+ ")";
}
}
@@ -0,0 +1,78 @@
package com.dbx.agent;
import java.util.Objects;
public final class ForeignKeyInfo {
private String name;
private String column;
private String ref_table;
private String ref_column;
public ForeignKeyInfo() {
this("", "", "", "");
}
public ForeignKeyInfo(String name, String column, String ref_table, String ref_column) {
this.name = name;
this.column = column;
this.ref_table = ref_table;
this.ref_column = ref_column;
}
public String getName() {
return name;
}
public String getColumn() {
return column;
}
public String getRef_table() {
return ref_table;
}
public String getRef_column() {
return ref_column;
}
public void setName(String name) {
this.name = name;
}
public void setColumn(String column) {
this.column = column;
}
public void setRef_table(String ref_table) {
this.ref_table = ref_table;
}
public void setRef_column(String ref_column) {
this.ref_column = ref_column;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ForeignKeyInfo)) return false;
ForeignKeyInfo that = (ForeignKeyInfo) other;
return Objects.equals(name, that.name)
&& Objects.equals(column, that.column)
&& Objects.equals(ref_table, that.ref_table)
&& Objects.equals(ref_column, that.ref_column);
}
@Override
public int hashCode() {
return Objects.hash(name, column, ref_table, ref_column);
}
@Override
public String toString() {
return "ForeignKeyInfo(name=" + name
+ ", column=" + column
+ ", ref_table=" + ref_table
+ ", ref_column=" + ref_column
+ ")";
}
}
@@ -0,0 +1,141 @@
package com.dbx.agent;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class IndexInfo {
private String name;
private List<String> columns;
private boolean is_unique;
private boolean is_primary;
private String filter;
private String index_type;
private List<String> included_columns;
private String comment;
public IndexInfo() {
this("", Collections.emptyList(), false, false);
}
public IndexInfo(String name, List<String> columns, boolean is_unique, boolean is_primary) {
this(name, columns, is_unique, is_primary, null, null, null, null);
}
public IndexInfo(
String name,
List<String> columns,
boolean is_unique,
boolean is_primary,
String filter,
String index_type,
List<String> included_columns,
String comment
) {
this.name = name;
this.columns = columns == null ? Collections.emptyList() : columns;
this.is_unique = is_unique;
this.is_primary = is_primary;
this.filter = filter;
this.index_type = index_type;
this.included_columns = included_columns;
this.comment = comment;
}
public String getName() {
return name;
}
public List<String> getColumns() {
return columns;
}
public boolean getIs_unique() {
return is_unique;
}
public boolean getIs_primary() {
return is_primary;
}
public String getFilter() {
return filter;
}
public String getIndex_type() {
return index_type;
}
public List<String> getIncluded_columns() {
return included_columns;
}
public String getComment() {
return comment;
}
public void setName(String name) {
this.name = name;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public void setIs_unique(boolean is_unique) {
this.is_unique = is_unique;
}
public void setIs_primary(boolean is_primary) {
this.is_primary = is_primary;
}
public void setFilter(String filter) {
this.filter = filter;
}
public void setIndex_type(String index_type) {
this.index_type = index_type;
}
public void setIncluded_columns(List<String> included_columns) {
this.included_columns = included_columns;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof IndexInfo)) return false;
IndexInfo that = (IndexInfo) other;
return is_unique == that.is_unique
&& is_primary == that.is_primary
&& Objects.equals(name, that.name)
&& Objects.equals(columns, that.columns)
&& Objects.equals(filter, that.filter)
&& Objects.equals(index_type, that.index_type)
&& Objects.equals(included_columns, that.included_columns)
&& Objects.equals(comment, that.comment);
}
@Override
public int hashCode() {
return Objects.hash(name, columns, is_unique, is_primary, filter, index_type, included_columns, comment);
}
@Override
public String toString() {
return "IndexInfo(name=" + name
+ ", columns=" + columns
+ ", is_unique=" + is_unique
+ ", is_primary=" + is_primary
+ ", filter=" + filter
+ ", index_type=" + index_type
+ ", included_columns=" + included_columns
+ ", comment=" + comment
+ ")";
}
}
@@ -0,0 +1,223 @@
package com.dbx.agent;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class JdbcAgentProfile {
private final String driverClass;
private final String urlTemplate;
private final int defaultPort;
private final boolean skipExecutionContext;
private final Set<String> excludedSchemas;
private final List<String> tableTypes;
private final String identifierQuote;
private final String schemaSwitchPrefix;
private final boolean catalogFallbackEnabled;
private final boolean nativeTableDdlSupported;
private final boolean objectSourceSupported;
private final boolean triggersSupported;
public JdbcAgentProfile(String driverClass, String urlTemplate) {
this(driverClass, urlTemplate, 0);
}
public JdbcAgentProfile(String driverClass, String urlTemplate, int defaultPort) {
this(driverClass, urlTemplate, defaultPort, false);
}
public JdbcAgentProfile(String driverClass, String urlTemplate, int defaultPort, boolean skipExecutionContext) {
this(
driverClass,
urlTemplate,
defaultPort,
skipExecutionContext,
Collections.emptySet(),
Arrays.asList("TABLE", "VIEW", "BASE TABLE", "MATERIALIZED VIEW", "SYSTEM TABLE", "SYSTEM VIEW")
);
}
public JdbcAgentProfile(
String driverClass,
String urlTemplate,
int defaultPort,
boolean skipExecutionContext,
Set<String> excludedSchemas,
List<String> tableTypes
) {
this(
driverClass,
urlTemplate,
defaultPort,
skipExecutionContext,
excludedSchemas,
tableTypes,
"\"",
"SET SCHEMA",
true,
false,
false,
false
);
}
public JdbcAgentProfile(
String driverClass,
String urlTemplate,
int defaultPort,
boolean skipExecutionContext,
Set<String> excludedSchemas,
List<String> tableTypes,
String identifierQuote,
String schemaSwitchPrefix,
boolean catalogFallbackEnabled,
boolean nativeTableDdlSupported,
boolean objectSourceSupported,
boolean triggersSupported
) {
this.driverClass = driverClass;
this.urlTemplate = urlTemplate;
this.defaultPort = defaultPort;
this.skipExecutionContext = skipExecutionContext;
this.excludedSchemas = excludedSchemas;
this.tableTypes = tableTypes;
this.identifierQuote = identifierQuote;
this.schemaSwitchPrefix = schemaSwitchPrefix;
this.catalogFallbackEnabled = catalogFallbackEnabled;
this.nativeTableDdlSupported = nativeTableDdlSupported;
this.objectSourceSupported = objectSourceSupported;
this.triggersSupported = triggersSupported;
}
public String getDriverClass() {
return driverClass;
}
public String getUrlTemplate() {
return urlTemplate;
}
public int getDefaultPort() {
return defaultPort;
}
public boolean getSkipExecutionContext() {
return skipExecutionContext;
}
public Set<String> getExcludedSchemas() {
return excludedSchemas;
}
public List<String> getTableTypes() {
return tableTypes;
}
public String getIdentifierQuote() {
return identifierQuote;
}
public String getSchemaSwitchPrefix() {
return schemaSwitchPrefix;
}
public boolean getCatalogFallbackEnabled() {
return catalogFallbackEnabled;
}
public boolean getNativeTableDdlSupported() {
return nativeTableDdlSupported;
}
public boolean getObjectSourceSupported() {
return objectSourceSupported;
}
public boolean getTriggersSupported() {
return triggersSupported;
}
public String buildUrl(ConnectParams params) {
if (!params.getConnection_string().trim().isEmpty()) {
return params.getConnection_string();
}
int port = params.getPort() > 0 ? params.getPort() : defaultPort;
String base = urlTemplate
.replace("{host}", params.getHost())
.replace("{port}", Integer.toString(port))
.replace("{database}", params.getDatabase());
return appendUrlParams(base, params.getUrl_params());
}
public String quoteIdentifier(String identifier) {
return identifierQuote + identifier.replace(identifierQuote, identifierQuote + identifierQuote) + identifierQuote;
}
public String schemaSwitchSql(String schema) {
return schemaSwitchSql(schema, identifierQuote);
}
public String schemaSwitchSql(String schema, String quote) {
if (skipExecutionContext) {
return "";
}
return schemaSwitchPrefix + " " + quote + schema.replace(quote, quote + quote) + quote;
}
private static String appendUrlParams(String url, String urlParams) {
String params = trimUrlParams(urlParams);
if (params.isEmpty()) {
return url;
}
if (usesColonProperties(url) && !params.endsWith(";")) {
params = params + ";";
}
String separator = urlParamSeparator(url);
return url + separator + params;
}
private static String trimUrlParams(String urlParams) {
String value = urlParams == null ? "" : urlParams.trim();
while (value.startsWith("?") || value.startsWith("&") || value.startsWith(";") || value.startsWith(":") || value.startsWith(",")) {
value = value.substring(1);
}
return value;
}
private static String urlParamSeparator(String url) {
if (startsWithIgnoreCase(url, "jdbc:sqlserver:") || startsWithIgnoreCase(url, "jdbc:exa:")) {
return url.endsWith(";") ? "" : ";";
}
if (startsWithIgnoreCase(url, "jdbc:teradata:")) {
return url.endsWith(",") ? "" : ",";
}
if (usesColonProperties(url)) {
if (url.endsWith(":") || url.endsWith(";")) {
return "";
}
return hasColonProperties(url) ? ";" : ":";
}
return url.contains("?") ? "&" : "?";
}
private static boolean usesColonProperties(String url) {
return startsWithIgnoreCase(url, "jdbc:db2:") || startsWithIgnoreCase(url, "jdbc:informix-sqli:");
}
private static boolean hasColonProperties(String url) {
int schemeEnd = url.indexOf("://");
if (schemeEnd < 0) {
return false;
}
int pathStart = url.indexOf('/', schemeEnd + 3);
if (pathStart < 0) {
return false;
}
return url.indexOf(':', pathStart + 1) >= 0;
}
private static boolean startsWithIgnoreCase(String value, String prefix) {
return value.regionMatches(true, 0, prefix, 0, prefix.length());
}
}
@@ -0,0 +1,652 @@
package com.dbx.agent;
import java.sql.Connection;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public final class JdbcExecutor {
public static final JdbcExecutor INSTANCE = new JdbcExecutor();
public static final int DEFAULT_MAX_ROWS = 10000;
public static final long QUERY_SESSION_IDLE_TIMEOUT_MILLIS = 10 * 60 * 1000L;
private final ConcurrentHashMap<String, QuerySession> sessions = new ConcurrentHashMap<>();
private JdbcExecutor() {
}
public QueryResult execute(Connection conn, String sql, String schema, Function<String, String> setSchemaSql) {
return execute(conn, sql, schema, setSchemaSql, DEFAULT_MAX_ROWS, null, this::defaultResultValue);
}
public QueryResult execute(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql,
int maxRows,
Integer fetchSize
) {
return execute(conn, sql, schema, setSchemaSql, maxRows, fetchSize, this::defaultResultValue);
}
public QueryResult execute(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql,
int maxRows,
Integer fetchSize,
ResultValueReader valueReader
) {
return execute(conn, sql, schema, setSchemaSql, maxRows, fetchSize, 0, valueReader);
}
public QueryResult execute(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql,
int maxRows,
Integer fetchSize,
int timeoutSecs,
ResultValueReader valueReader
) {
return unchecked(() -> {
String trimmedSql = trimSql(sql);
String upperSql = trimmedSql.toUpperCase(Locale.ROOT).trim();
long start = System.currentTimeMillis();
if ("BEGIN".equals(upperSql) || "BEGIN TRANSACTION".equals(upperSql)) {
conn.setAutoCommit(false);
return emptyQueryResult(start);
}
if ("COMMIT".equals(upperSql)) {
conn.commit();
conn.setAutoCommit(true);
return emptyQueryResult(start);
}
if ("ROLLBACK".equals(upperSql)) {
conn.rollback();
conn.setAutoCommit(true);
return emptyQueryResult(start);
}
applySchema(conn, schema, setSchemaSql);
try (Statement stmt = conn.createStatement()) {
int effectiveMaxRows = Math.max(maxRows, 1);
stmt.setMaxRows(effectiveMaxRows + 1);
applyQueryTimeout(stmt, timeoutSecs);
if (fetchSize != null && fetchSize > 0) {
stmt.setFetchSize(fetchSize);
}
boolean hasResultSet = stmt.execute(trimmedSql);
long elapsed = System.currentTimeMillis() - start;
if (hasResultSet) {
try (ResultSet rs = stmt.getResultSet()) {
return readResultSet(rs, elapsed, effectiveMaxRows, valueReader);
}
}
int updateCount = stmt.getUpdateCount();
return new QueryResult(
Collections.emptyList(),
Collections.emptyList(),
updateCount >= 0 ? updateCount : 0,
elapsed,
false
);
}
});
}
public QueryResult readResultSet(ResultSet rs, long executionTimeMs) {
return readResultSet(rs, executionTimeMs, DEFAULT_MAX_ROWS, this::defaultResultValue);
}
public QueryResult readResultSet(
ResultSet rs,
long executionTimeMs,
int maxRows,
ResultValueReader valueReader
) {
return unchecked(() -> {
ResultSetMetaData meta = rs.getMetaData();
int colCount = meta.getColumnCount();
List<String> columns = new ArrayList<>();
List<String> columnTypes = new ArrayList<>();
String[] typeNameByIndex = new String[colCount];
for (int i = 1; i <= colCount; i++) {
columns.add(meta.getColumnLabel(i));
String typeName = safeColumnTypeName(meta, i);
columnTypes.add(typeName);
typeNameByIndex[i - 1] = typeName;
}
List<List<Object>> rows = new ArrayList<>();
boolean truncated = false;
while (rs.next()) {
if (rows.size() >= maxRows) {
truncated = true;
break;
}
rows.add(rowValues(rs, valueReader, typeNameByIndex));
}
return new QueryResult(columns, columnTypes, rows, 0L, executionTimeMs, truncated);
});
}
public QueryPageResult executePage(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql
) {
return executePage(conn, sql, schema, setSchemaSql, new QueryPageOptions(), this::defaultResultValue);
}
public QueryPageResult executePage(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql,
QueryPageOptions options
) {
return executePage(conn, sql, schema, setSchemaSql, options, this::defaultResultValue);
}
public QueryPageResult executePage(
Connection conn,
String sql,
String schema,
Function<String, String> setSchemaSql,
QueryPageOptions options,
ResultValueReader valueReader
) {
return unchecked(() -> {
expireIdleQuerySessions();
String trimmedSql = trimSql(sql);
String upperSql = trimmedSql.toUpperCase(Locale.ROOT).trim();
long start = System.currentTimeMillis();
if ("BEGIN".equals(upperSql) || "BEGIN TRANSACTION".equals(upperSql)) {
conn.setAutoCommit(false);
return emptyQueryPageResult(start);
}
if ("COMMIT".equals(upperSql)) {
conn.commit();
conn.setAutoCommit(true);
return emptyQueryPageResult(start);
}
if ("ROLLBACK".equals(upperSql)) {
conn.rollback();
conn.setAutoCommit(true);
return emptyQueryPageResult(start);
}
applySchema(conn, schema, setSchemaSql);
Statement stmt = conn.createStatement();
try {
applyQueryTimeout(stmt, options.getTimeoutSecs());
if (options.getFetchSize() != null && options.getFetchSize() > 0) {
stmt.setFetchSize(options.getFetchSize());
}
boolean hasResultSet = stmt.execute(trimmedSql);
long elapsed = System.currentTimeMillis() - start;
if (!hasResultSet) {
int updateCount = stmt.getUpdateCount();
stmt.close();
return new QueryPageResult(
Collections.emptyList(),
Collections.emptyList(),
updateCount >= 0 ? updateCount : 0,
elapsed
);
}
ResultSet rs = stmt.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
String sessionId = UUID.randomUUID().toString();
int colCount = meta.getColumnCount();
List<String> columns = new ArrayList<>(colCount);
List<String> columnTypes = new ArrayList<>(colCount);
String[] typeNameByIndex = new String[colCount];
for (int i = 1; i <= colCount; i++) {
columns.add(meta.getColumnLabel(i));
String typeName = safeColumnTypeName(meta, i);
columnTypes.add(typeName);
typeNameByIndex[i - 1] = typeName;
}
QuerySession session = new QuerySession(
sessionId,
stmt,
rs,
columns,
columnTypes,
typeNameByIndex,
Math.max(options.getMaxRows(), 1),
valueReader
);
sessions.put(sessionId, session);
return readSessionPage(session, options.getPageSize(), elapsed);
} catch (Exception e) {
try {
stmt.close();
} catch (Exception ignored) {
}
throw e;
}
});
}
public QueryPageResult fetchPage(String sessionId, int pageSize) {
expireIdleQuerySessions();
QuerySession session = sessions.get(sessionId);
if (session == null) {
throw new IllegalArgumentException("Query session not found");
}
synchronized (session) {
return readSessionPage(session, pageSize, 0L);
}
}
public boolean closeQuerySession(String sessionId) {
return closeSession(sessionId);
}
public void closeAllQuerySessions() {
List<String> ids = new ArrayList<>(sessions.keySet());
for (String id : ids) {
closeSession(id);
}
}
public int expireIdleQuerySessions() {
return expireIdleQuerySessions(System.currentTimeMillis(), QUERY_SESSION_IDLE_TIMEOUT_MILLIS);
}
public int expireIdleQuerySessions(long nowMillis, long idleTimeoutMillis) {
if (idleTimeoutMillis < 0) {
return 0;
}
int closed = 0;
List<QuerySession> snapshot = new ArrayList<>(sessions.values());
for (QuerySession session : snapshot) {
boolean expired;
synchronized (session) {
expired = nowMillis - session.lastAccessedAtMillis >= idleTimeoutMillis;
}
if (expired && closeSession(session.id)) {
closed += 1;
}
}
return closed;
}
public Object defaultResultValue(ResultSet rs, int index, int sqlType) throws SQLException {
Object value;
switch (sqlType) {
case Types.BIGINT:
value = rs.getLong(index);
break;
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
value = rs.getInt(index);
break;
case Types.FLOAT:
case Types.REAL:
value = rs.getFloat(index);
break;
case Types.DOUBLE:
value = rs.getDouble(index);
break;
case Types.DECIMAL:
case Types.NUMERIC:
value = rs.getBigDecimal(index);
break;
case Types.BOOLEAN:
case Types.BIT:
value = rs.getBoolean(index);
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.NCHAR:
case Types.NVARCHAR:
case Types.LONGNVARCHAR:
case Types.CLOB:
case Types.NCLOB:
value = rs.getString(index);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
value = bytesToHex(rs.getBytes(index));
break;
case Types.SQLXML:
value = sqlXmlToString(rs.getSQLXML(index));
break;
default:
value = normalizeResultValue(rs.getObject(index));
break;
}
return rs.wasNull() ? null : value;
}
public static Object stringResultValue(ResultSet rs, int index, int sqlType) throws SQLException {
Object value;
switch (sqlType) {
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
value = bytesToHex(rs.getBytes(index));
break;
case Types.SQLXML:
value = sqlXmlToString(rs.getSQLXML(index));
break;
default:
value = rs.getString(index);
break;
}
return rs.wasNull() ? null : value;
}
public static Object normalizeResultValue(Object value) throws SQLException {
if (value == null) {
return null;
}
if (value instanceof Clob) {
Clob clob = (Clob) value;
return clob.getSubString(1, Math.toIntExact(clob.length()));
}
if (value instanceof Blob) {
Blob blob = (Blob) value;
return bytesToHex(blob.getBytes(1, Math.toIntExact(blob.length())));
}
if (value instanceof SQLXML) {
SQLXML sqlxml = (SQLXML) value;
return sqlxml.getString();
}
if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
return bytesToHex(bytes);
}
return value instanceof Number || value instanceof Boolean ? value : value.toString();
}
public static String bytesToHex(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder result = new StringBuilder(bytes.length * 2 + 2);
result.append("0x");
for (byte b : bytes) {
result.append(Character.forDigit((b >> 4) & 0xF, 16));
result.append(Character.forDigit(b & 0xF, 16));
}
return result.toString();
}
private static String sqlXmlToString(SQLXML value) throws SQLException {
return value == null ? null : value.getString();
}
private QueryPageResult readSessionPage(QuerySession session, int pageSize, long executionTimeMs) {
return unchecked(() -> {
session.lastAccessedAtMillis = System.currentTimeMillis();
int effectivePageSize = Math.max(pageSize, 1);
List<List<Object>> rows = new ArrayList<>();
if (session.pendingRow != null) {
rows.add(session.pendingRow);
session.pendingRow = null;
}
while (rows.size() < effectivePageSize && session.rowsRead < session.maxRows) {
if (!session.resultSet.next()) {
closeSession(session.id);
return new QueryPageResult(session.columns, session.columnTypes, rows, 0L, executionTimeMs, false, null, false);
}
rows.add(rowValues(session.resultSet, session.valueReader, session.typeNameByIndex));
session.rowsRead += 1;
}
if (session.rowsRead >= session.maxRows) {
boolean truncated = session.resultSet.next();
closeSession(session.id);
return new QueryPageResult(session.columns, session.columnTypes, rows, 0L, executionTimeMs, truncated, null, false);
}
boolean hasMore = session.resultSet.next();
if (!hasMore) {
closeSession(session.id);
return new QueryPageResult(session.columns, session.columnTypes, rows, 0L, executionTimeMs, false, null, false);
}
session.pendingRow = rowValues(session.resultSet, session.valueReader, session.typeNameByIndex);
session.rowsRead += 1;
return new QueryPageResult(session.columns, session.columnTypes, rows, 0L, executionTimeMs, false, session.id, true);
});
}
private boolean closeSession(String sessionId) {
QuerySession session = sessions.remove(sessionId);
if (session == null) {
return false;
}
synchronized (session) {
try {
session.resultSet.close();
} catch (Exception ignored) {
}
try {
session.statement.close();
} catch (Exception ignored) {
}
}
return true;
}
static String safeColumnTypeName(ResultSetMetaData meta, int columnIndex) {
try {
String name = meta.getColumnTypeName(columnIndex);
return name == null ? "" : name;
} catch (SQLException ignored) {
return "";
}
}
private List<Object> rowValues(ResultSet rs, ResultValueReader valueReader, String[] typeNameByIndex) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int colCount = meta.getColumnCount();
List<Object> row = new ArrayList<>(colCount);
for (int i = 1; i <= colCount; i++) {
int sqlType = meta.getColumnType(i);
Object value;
if (valueReader instanceof ColumnAwareResultValueReader) {
String typeName = typeNameByIndex != null && i - 1 < typeNameByIndex.length
? typeNameByIndex[i - 1]
: safeColumnTypeName(meta, i);
value = ((ColumnAwareResultValueReader) valueReader).read(rs, i, sqlType, typeName);
} else {
value = valueReader.read(rs, i, sqlType);
}
row.add(value);
}
return row;
}
private void applySchema(Connection conn, String schema, Function<String, String> setSchemaSql) throws SQLException {
if (schema == null || schema.trim().isEmpty()) {
return;
}
// Prefer JDBC standard APIs over database-specific SQL.
// setSchema (JDBC 4.1) and setCatalog (JDBC 1.0) work universally
// across all JDBC drivers without needing to know the database dialect.
try {
conn.setSchema(schema);
return;
} catch (SQLException | AbstractMethodError ignored) {
// setSchema not supported by this driver
}
try {
conn.setCatalog(schema);
return;
} catch (SQLException | AbstractMethodError ignored) {
// setCatalog not supported either
}
// Fallback: execute database-specific SQL (e.g. USE, SET SCHEMA, etc.)
String schemaSql = setSchemaSql.apply(schema);
if (schemaSql == null || schemaSql.trim().isEmpty()) {
return;
}
try (Statement stmt = conn.createStatement()) {
stmt.execute(schemaSql);
}
}
private static void applyQueryTimeout(Statement stmt, int timeoutSecs) throws SQLException {
if (timeoutSecs > 0) {
stmt.setQueryTimeout(timeoutSecs);
}
}
private QueryResult emptyQueryResult(long start) {
return new QueryResult(
Collections.emptyList(),
Collections.emptyList(),
0L,
System.currentTimeMillis() - start
);
}
private QueryPageResult emptyQueryPageResult(long start) {
return new QueryPageResult(
Collections.emptyList(),
Collections.emptyList(),
0L,
System.currentTimeMillis() - start
);
}
static String trimSql(String sql) {
String trimmed = stripTrailingSlashDelimiter(sql.trim());
if (isPlSqlBlock(trimmed)) {
return trimmed;
}
while (trimmed.endsWith(";")) {
trimmed = trimmed.substring(0, trimmed.length() - 1).trim();
}
return trimmed;
}
private static String stripTrailingSlashDelimiter(String sql) {
String trimmed = sql.trim();
if (!trimmed.endsWith("/")) {
return trimmed;
}
int slashStart = trimmed.length() - 1;
int lineStart = trimmed.lastIndexOf('\n', slashStart - 1) + 1;
if (!trimmed.substring(lineStart, slashStart).trim().isEmpty()) {
return trimmed;
}
String beforeSlash = trimmed.substring(0, lineStart).trim();
return isPlSqlBlock(beforeSlash) ? beforeSlash : trimmed;
}
private static boolean isPlSqlBlock(String sql) {
String upperSql = sql.toUpperCase(Locale.ROOT).trim();
if (!upperSql.startsWith("DECLARE") && !upperSql.startsWith("BEGIN")) {
return false;
}
return upperSql.matches("(?s).*\\bEND\\s+(?!IF\\b|LOOP\\b|CASE\\b)[A-Z0-9_$#]+\\s*;\\s*$")
|| upperSql.matches("(?s).*\\bEND\\s*;\\s*$");
}
private static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@FunctionalInterface
public interface ResultValueReader {
Object read(ResultSet rs, int index, int sqlType) throws SQLException;
}
/**
* Optional extension of {@link ResultValueReader} that exposes the JDBC
* {@code getColumnTypeName} alongside the SQL type code, allowing per-driver
* agents to convert vendor-specific column types (e.g. PostGIS
* {@code geometry}) without re-querying the metadata.
*/
public interface ColumnAwareResultValueReader extends ResultValueReader {
Object read(ResultSet rs, int index, int sqlType, String columnTypeName) throws SQLException;
@Override
default Object read(ResultSet rs, int index, int sqlType) throws SQLException {
return read(rs, index, sqlType, safeColumnTypeName(rs.getMetaData(), index));
}
}
private interface ThrowingSupplier<T> {
T get() throws Exception;
}
private static final class QuerySession {
private final String id;
private final Statement statement;
private final ResultSet resultSet;
private final List<String> columns;
private final List<String> columnTypes;
private final String[] typeNameByIndex;
private final int maxRows;
private final ResultValueReader valueReader;
private int rowsRead;
private List<Object> pendingRow;
private long lastAccessedAtMillis;
private QuerySession(
String id,
Statement statement,
ResultSet resultSet,
List<String> columns,
List<String> columnTypes,
String[] typeNameByIndex,
int maxRows,
ResultValueReader valueReader
) {
this.id = id;
this.statement = statement;
this.resultSet = resultSet;
this.columns = columns;
this.columnTypes = columnTypes;
this.typeNameByIndex = typeNameByIndex;
this.maxRows = maxRows;
this.valueReader = valueReader;
this.lastAccessedAtMillis = System.currentTimeMillis();
}
}
}
@@ -0,0 +1,16 @@
package com.dbx.agent;
public final class JdbcIdentifiers {
public static final JdbcIdentifiers INSTANCE = new JdbcIdentifiers();
private JdbcIdentifiers() {
}
public String doubleQuote(String identifier) {
return "\"" + identifier.replace("\"", "\"\"") + "\"";
}
public String backtick(String identifier) {
return "`" + identifier.replace("`", "``") + "`";
}
}
@@ -0,0 +1,301 @@
package com.dbx.agent;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.util.Collections;
import java.util.List;
public final class JsonRpcServer {
private static final long CONNECTION_VALIDATION_INTERVAL_MILLIS = 5_000L;
private final DatabaseAgent agent;
private final Gson gson = new Gson();
private ConnectParams lastConnectParams;
private long lastConnectionValidationTimeMillis;
public JsonRpcServer(DatabaseAgent agent) {
this.agent = agent;
}
public void run() {
System.out.println("{\"ready\":true}");
System.out.flush();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
String response = handleRequest(line);
System.out.println(response);
System.out.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
String handleRequest(String line) {
JsonObject req = JsonParser.parseString(line).getAsJsonObject();
JsonElement id = req.get("id");
String method = req.get("method").getAsString();
JsonObject params = paramsObject(req);
JsonObject response = new JsonObject();
response.addProperty("jsonrpc", "2.0");
response.add("id", id);
try {
Object result = dispatch(method, params);
response.add("result", gson.toJsonTree(result));
return gson.toJson(response);
} catch (Throwable e) {
JsonObject error = new JsonObject();
error.addProperty("code", -1);
error.addProperty("message", e.getMessage() == null ? e.toString() : e.getMessage());
response.add("error", error);
return gson.toJson(response);
}
}
private Object dispatch(String method, JsonObject params) throws Exception {
if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {
return AgentProtocol.handshakeResult();
}
if (AgentProtocol.METHOD_CONNECT.equals(method)) {
lastConnectParams = gson.fromJson(params, ConnectParams.class);
agent.connect(lastConnectParams);
lastConnectionValidationTimeMillis = 0L;
return Collections.singletonMap("ok", true);
}
if (AgentProtocol.METHOD_TEST_CONNECTION.equals(method)) {
if (!agent.testConnection(gson.fromJson(params, ConnectParams.class))) {
throw new RuntimeException("Connection failed");
}
return Collections.singletonMap("ok", true);
}
if (AgentProtocol.METHOD_VALIDATE_CONNECTION.equals(method)) {
Connection conn = agent.getConnection();
boolean valid = false;
if (conn != null) {
try {
valid = !conn.isClosed() && conn.isValid(2);
} catch (Exception ignored) {
}
}
if (!valid) {
throw new IllegalStateException("Connection is not valid");
}
return Collections.singletonMap("ok", true);
}
ensureLiveConnection(method);
if (AgentProtocol.METHOD_LIST_DATABASES.equals(method)) {
return agent.listDatabases();
}
if (AgentProtocol.METHOD_LIST_SCHEMAS.equals(method)) {
switchCatalog(params);
return agent.listSchemas();
}
if (AgentProtocol.METHOD_LIST_TABLES.equals(method)) {
switchCatalog(params);
return agent.listTables(params.get("schema").getAsString());
}
if (AgentProtocol.METHOD_LIST_OBJECTS.equals(method)) {
switchCatalog(params);
return agent.listObjects(params.get("schema").getAsString());
}
if (AgentProtocol.METHOD_GET_OBJECT_SOURCE.equals(method)) {
switchCatalog(params);
return agent.getObjectSource(
params.get("schema").getAsString(),
params.get("name").getAsString(),
params.get("object_type").getAsString()
);
}
if (AgentProtocol.METHOD_GET_TABLE_DDL.equals(method)) {
switchCatalog(params);
return agent.getTableDdl(params.get("schema").getAsString(), params.get("table").getAsString());
}
if (AgentProtocol.METHOD_GET_COLUMNS.equals(method)) {
switchCatalog(params);
return agent.getColumns(params.get("schema").getAsString(), params.get("table").getAsString());
}
if (AgentProtocol.METHOD_LIST_INDEXES.equals(method)) {
switchCatalog(params);
return agent.listIndexes(params.get("schema").getAsString(), params.get("table").getAsString());
}
if (AgentProtocol.METHOD_LIST_FOREIGN_KEYS.equals(method)) {
switchCatalog(params);
return agent.listForeignKeys(params.get("schema").getAsString(), params.get("table").getAsString());
}
if (AgentProtocol.METHOD_LIST_TRIGGERS.equals(method)) {
switchCatalog(params);
return agent.listTriggers(params.get("schema").getAsString(), params.get("table").getAsString());
}
if (AgentProtocol.METHOD_EXECUTE_QUERY.equals(method)) {
return agent.executeQuery(
params.get("sql").getAsString(),
stringOrNull(params, "schema"),
new ExecuteQueryOptions(
intOrDefault(params, "maxRows", JdbcExecutor.DEFAULT_MAX_ROWS),
intOrNull(params, "fetchSize"),
intOrDefault(params, "timeoutSecs", 0)
)
);
}
if (AgentProtocol.METHOD_EXECUTE_QUERY_PAGE.equals(method)) {
return agent.executeQueryPage(
params.get("sql").getAsString(),
stringOrNull(params, "schema"),
new QueryPageOptions(
intOrDefault(params, "pageSize", 100),
intOrNull(params, "fetchSize"),
intOrDefault(params, "maxRows", JdbcExecutor.DEFAULT_MAX_ROWS),
intOrDefault(params, "timeoutSecs", 0)
)
);
}
if (AgentProtocol.METHOD_FETCH_QUERY_PAGE.equals(method)) {
return agent.fetchQueryPage(
params.get("sessionId").getAsString(),
intOrDefault(params, "pageSize", 100)
);
}
if (AgentProtocol.METHOD_CLOSE_QUERY_SESSION.equals(method)) {
return agent.closeQuerySession(params.get("sessionId").getAsString());
}
if (AgentProtocol.METHOD_GET_EXPLAIN_INFO.equals(method)) {
String plan = agent.getExplainInfo(
params.get("sql").getAsString(),
stringOrNull(params, "database"),
stringOrNull(params, "schema"),
intOrDefault(params, "timeoutSecs", -1),
stringOrNull(params, "mode")
);
java.util.HashMap<String, Object> result = new java.util.HashMap<>();
result.put("plan", plan);
result.put("has_actual_stats", "autotrace".equals(stringOrNull(params, "mode")));
return result;
}
if (AgentProtocol.METHOD_EXECUTE_TRANSACTION.equals(method)) {
Type statementsType = new TypeToken<List<String>>() {}.getType();
List<String> statements = gson.fromJson(params.get("statements"), statementsType);
return agent.executeTransaction(statements, stringOrNull(params, "schema"));
}
if (AgentProtocol.METHOD_DISCONNECT.equals(method)) {
JdbcExecutor.INSTANCE.closeAllQuerySessions();
agent.disconnect();
lastConnectParams = null;
return Collections.singletonMap("ok", true);
}
if (AgentProtocol.METHOD_SHUTDOWN.equals(method)) {
JdbcExecutor.INSTANCE.closeAllQuerySessions();
agent.disconnect();
lastConnectParams = null;
System.exit(0);
return Collections.singletonMap("ok", true);
}
throw new IllegalArgumentException("Unknown method: " + method);
}
private void switchCatalog(JsonObject params) throws Exception {
String database = stringOrNull(params, "database");
if (database != null && !database.trim().isEmpty() && agent.getConnection() != null) {
String currentCatalog = null;
try {
currentCatalog = agent.getConnection().getCatalog();
} catch (Exception ignored) {
}
if (currentCatalog == null || !currentCatalog.trim().equalsIgnoreCase(database.trim())) {
try {
agent.getConnection().setCatalog(database);
} catch (Exception ignored) {
}
}
}
}
private void ensureLiveConnection(String method) {
if (lastConnectParams == null || !shouldValidateConnection(method)) {
return;
}
Connection conn = agent.getConnection();
if (conn == null) {
return;
}
long now = System.currentTimeMillis();
if (lastConnectionValidationTimeMillis > 0
&& now - lastConnectionValidationTimeMillis < CONNECTION_VALIDATION_INTERVAL_MILLIS) {
return;
}
boolean valid = false;
try {
valid = !conn.isClosed() && conn.isValid(2);
} catch (Exception ignored) {
}
if (valid) {
lastConnectionValidationTimeMillis = now;
return;
}
JdbcExecutor.INSTANCE.closeAllQuerySessions();
try {
agent.disconnect();
} catch (Exception ignored) {
}
agent.connect(lastConnectParams);
lastConnectionValidationTimeMillis = System.currentTimeMillis();
}
private static boolean shouldValidateConnection(String method) {
return !AgentProtocol.METHOD_HANDSHAKE.equals(method)
&& !AgentProtocol.METHOD_CONNECT.equals(method)
&& !AgentProtocol.METHOD_TEST_CONNECTION.equals(method)
&& !AgentProtocol.METHOD_VALIDATE_CONNECTION.equals(method)
&& !AgentProtocol.METHOD_FETCH_QUERY_PAGE.equals(method)
&& !AgentProtocol.METHOD_CLOSE_QUERY_SESSION.equals(method)
&& !AgentProtocol.METHOD_DISCONNECT.equals(method)
&& !AgentProtocol.METHOD_SHUTDOWN.equals(method);
}
private static JsonObject paramsObject(JsonObject req) {
JsonElement params = req.get("params");
if (params == null || params instanceof JsonNull || !params.isJsonObject()) {
return new JsonObject();
}
return params.getAsJsonObject();
}
private static String stringOrNull(JsonObject object, String key) {
JsonElement element = object.get(key);
if (element == null || element instanceof JsonNull) {
return null;
}
return element.getAsString();
}
private static Integer intOrNull(JsonObject object, String key) {
JsonElement element = object.get(key);
if (element == null || element instanceof JsonNull) {
return null;
}
return element.getAsInt();
}
private static int intOrDefault(JsonObject object, String key, int defaultValue) {
Integer value = intOrNull(object, key);
return value == null ? defaultValue : value;
}
}
@@ -0,0 +1,82 @@
package com.dbx.agent;
import java.util.Objects;
public final class ObjectInfo {
private String name;
private String object_type;
private String schema;
private String comment;
public ObjectInfo() {
this("", "", null, null);
}
public ObjectInfo(String name, String object_type) {
this(name, object_type, null, null);
}
public ObjectInfo(String name, String object_type, String schema, String comment) {
this.name = name;
this.object_type = object_type;
this.schema = schema;
this.comment = comment;
}
public String getName() {
return name;
}
public String getObject_type() {
return object_type;
}
public String getSchema() {
return schema;
}
public String getComment() {
return comment;
}
public void setName(String name) {
this.name = name;
}
public void setObject_type(String object_type) {
this.object_type = object_type;
}
public void setSchema(String schema) {
this.schema = schema;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ObjectInfo)) return false;
ObjectInfo that = (ObjectInfo) other;
return Objects.equals(name, that.name)
&& Objects.equals(object_type, that.object_type)
&& Objects.equals(schema, that.schema)
&& Objects.equals(comment, that.comment);
}
@Override
public int hashCode() {
return Objects.hash(name, object_type, schema, comment);
}
@Override
public String toString() {
return "ObjectInfo(name=" + name
+ ", object_type=" + object_type
+ ", schema=" + schema
+ ", comment=" + comment
+ ")";
}
}
@@ -0,0 +1,82 @@
package com.dbx.agent;
import java.util.Objects;
public final class ObjectSource {
private String name;
private String object_type;
private String schema;
private String source;
public ObjectSource() {
this("", "", null, "");
}
public ObjectSource(String name, String object_type, String source) {
this(name, object_type, null, source);
}
public ObjectSource(String name, String object_type, String schema, String source) {
this.name = name;
this.object_type = object_type;
this.schema = schema;
this.source = source;
}
public String getName() {
return name;
}
public String getObject_type() {
return object_type;
}
public String getSchema() {
return schema;
}
public String getSource() {
return source;
}
public void setName(String name) {
this.name = name;
}
public void setObject_type(String object_type) {
this.object_type = object_type;
}
public void setSchema(String schema) {
this.schema = schema;
}
public void setSource(String source) {
this.source = source;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof ObjectSource)) return false;
ObjectSource that = (ObjectSource) other;
return Objects.equals(name, that.name)
&& Objects.equals(object_type, that.object_type)
&& Objects.equals(schema, that.schema)
&& Objects.equals(source, that.source);
}
@Override
public int hashCode() {
return Objects.hash(name, object_type, schema, source);
}
@Override
public String toString() {
return "ObjectSource(name=" + name
+ ", object_type=" + object_type
+ ", schema=" + schema
+ ", source=" + source
+ ")";
}
}
@@ -0,0 +1,499 @@
package com.dbx.agent;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public abstract class PostgresLikeAgent extends AbstractJdbcAgent {
private final PostgresLikeAgentProfile profile;
private boolean mysqlCompatMode = false;
protected PostgresLikeAgent(PostgresLikeAgentProfile profile) {
this.profile = profile;
}
public PostgresLikeAgentProfile getProfile() {
return profile;
}
public void setMysqlCompatMode(boolean mysqlCompatMode) {
this.mysqlCompatMode = mysqlCompatMode;
}
public boolean isMysqlCompatMode() {
return mysqlCompatMode;
}
@Override
public QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options) {
return JdbcExecutor.INSTANCE.execute(
requireConnected(),
sql,
schema,
this::setSchemaSQL,
options.getMaxRows(),
options.getFetchSize(),
options.getTimeoutSecs(),
geometryAwareResolver()
);
}
@Override
public QueryPageResult executeQueryPage(String sql, String schema, QueryPageOptions options) {
return JdbcExecutor.INSTANCE.executePage(
requireConnected(),
sql,
schema,
this::setSchemaSQL,
options,
geometryAwareResolver()
);
}
/**
* Wrap {@link AbstractJdbcAgent#resultValue} so PostGIS-style {@code geometry}
* and {@code geography} columns are decoded into WKT (matching the native
* tokio_postgres path in {@code crates/dbx-core/src/db/postgres.rs}).
*/
private JdbcExecutor.ColumnAwareResultValueReader geometryAwareResolver() {
return (rs, index, sqlType, columnTypeName) -> {
if (isPostgisGeometryTypeName(columnTypeName)) {
Object raw = rs.getObject(index);
if (rs.wasNull() || raw == null) {
return null;
}
return EwkbWktDecoder.decode(raw);
}
return resultValue(rs, index, sqlType, columnTypeName);
};
}
protected Object resultValue(ResultSet rs, int index, int sqlType, String columnTypeName) {
return resultValue(rs, index, sqlType);
}
static boolean isPostgisGeometryTypeName(String columnTypeName) {
if (columnTypeName == null) {
return false;
}
String trimmed = columnTypeName.trim().toLowerCase(Locale.ROOT);
if (trimmed.isEmpty()) {
return false;
}
// Strip optional schema prefix (e.g. "public.geometry") or "(srid,type)" suffix.
int dot = trimmed.lastIndexOf('.');
if (dot >= 0 && dot < trimmed.length() - 1) {
trimmed = trimmed.substring(dot + 1);
}
int paren = trimmed.indexOf('(');
if (paren >= 0) {
trimmed = trimmed.substring(0, paren);
}
return "geometry".equals(trimmed) || "geography".equals(trimmed);
}
private String quoteIdentifier(String identifier) {
return mysqlCompatMode
? JdbcIdentifiers.INSTANCE.backtick(identifier)
: JdbcIdentifiers.INSTANCE.doubleQuote(identifier);
}
@Override
protected String driverClass() {
return profile.getDriverClass();
}
@Override
protected String buildJdbcUrl(ConnectParams params) {
return profile.buildUrl(params);
}
@Override
public List<DatabaseInfo> listDatabases() {
return unchecked(() -> {
List<DatabaseInfo> result = new ArrayList<>();
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname");
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(new DatabaseInfo(rs.getString("datname")));
}
}
return result;
});
}
@Override
public List<String> listSchemas() {
return unchecked(() -> {
List<String> result = new ArrayList<>();
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(
"SELECT n.nspname AS schema_name " +
"FROM pg_catalog.pg_namespace n " +
"WHERE n.nspname NOT IN ('pg_catalog','information_schema','pg_toast') " +
"AND n.nspname NOT LIKE 'pg_toast_temp_%' " +
"AND n.nspname NOT LIKE 'pg_temp_%' " +
"ORDER BY n.nspname"
); ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(rs.getString("schema_name"));
}
}
return result;
});
}
@Override
public List<TableInfo> listTables(String schema) {
return unchecked(() -> {
List<TableInfo> result = new ArrayList<>();
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(
"SELECT c.relname AS table_name, " +
"CASE c.relkind " +
"WHEN 'r' THEN 'TABLE' " +
"WHEN 'p' THEN 'TABLE' " +
"WHEN 'v' THEN 'VIEW' " +
"WHEN 'm' THEN 'MATERIALIZED VIEW' " +
"WHEN 'f' THEN 'FOREIGN TABLE' " +
"ELSE 'TABLE' END AS table_type, " +
"obj_description(c.oid) AS table_comment " +
"FROM pg_catalog.pg_class c " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"WHERE n.nspname = ? AND c.relkind IN ('r','p','v','m','f') " +
"ORDER BY c.relname"
)) {
stmt.setString(1, schema);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String tableType = normalizeTableType(rs.getString("table_type"));
result.add(new TableInfo(rs.getString("table_name"), tableType, rs.getString("table_comment")));
}
}
}
return result;
});
}
@Override
public List<ObjectInfo> listObjects(String schema) {
return unchecked(() -> {
List<ObjectInfo> result = new ArrayList<>();
for (TableInfo table : listTables(schema)) {
result.add(new ObjectInfo(table.getName(), table.getTable_type(), schema, table.getComment()));
}
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(
"SELECT p.proname AS routine_name, " +
"CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END AS routine_type " +
"FROM pg_catalog.pg_proc p " +
"JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " +
"WHERE n.nspname = ? AND p.prokind IN ('p','f') " +
"ORDER BY p.proname"
)) {
stmt.setString(1, schema);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(new ObjectInfo(rs.getString(1), rs.getString(2), schema, null));
}
}
}
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(
"SELECT c.relname AS sequence_name, 'SEQUENCE' AS object_type " +
"FROM pg_catalog.pg_class c " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"WHERE n.nspname = ? AND c.relkind = 'S' " +
"ORDER BY c.relname"
)) {
stmt.setString(1, schema);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(new ObjectInfo(rs.getString(1), rs.getString(2), schema, null));
}
}
}
return result;
});
}
@Override
public String getTableDdl(String schema, String table) {
List<IndexInfo> indexes;
try {
indexes = listIndexes(schema, table);
} catch (RuntimeException e) {
indexes = Collections.emptyList();
}
List<ForeignKeyInfo> foreignKeys;
try {
foreignKeys = listForeignKeys(schema, table);
} catch (RuntimeException e) {
foreignKeys = Collections.emptyList();
}
return DdlBuilder.buildTableDdl(schema, table, getColumns(schema, table), indexes, foreignKeys, mysqlCompatMode, true);
}
@Override
public ObjectSource getObjectSource(String schema, String name, String objectType) {
return unchecked(() -> {
String upperType = objectType.toUpperCase();
String sql;
if ("VIEW".equals(upperType) || "MATERIALIZED VIEW".equals(upperType)) {
sql = "SELECT pg_get_viewdef(to_regclass(?), true)";
} else if ("FUNCTION".equals(upperType)) {
sql = "SELECT pg_get_functiondef(p.oid)\n" +
"FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n" +
"WHERE n.nspname = ? AND p.proname = ? AND p.prokind = 'f'\n" +
"ORDER BY p.oid LIMIT 1";
} else if ("PROCEDURE".equals(upperType)) {
sql = "SELECT pg_get_functiondef(p.oid)\n" +
"FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n" +
"WHERE n.nspname = ? AND p.proname = ? AND p.prokind = 'p'\n" +
"ORDER BY p.oid LIMIT 1";
} else {
throw new IllegalArgumentException("Unsupported object type: " + objectType);
}
String source;
if ("VIEW".equals(upperType) || "MATERIALIZED VIEW".equals(upperType)) {
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, quoteQualifiedIdentifier(schema, name));
try (ResultSet rs = stmt.executeQuery()) {
source = rs.next() ? coalesce(rs.getString(1)) : "";
}
}
} else {
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, name);
try (ResultSet rs = stmt.executeQuery()) {
source = rs.next() ? coalesce(rs.getString(1)) : "";
}
}
}
return new ObjectSource(name, objectType, schema, source);
});
}
@Override
public List<ColumnInfo> getColumns(String schema, String table) {
return unchecked(() -> {
Set<String> primaryKeys = primaryKeys(schema, table);
List<ColumnInfo> result = new ArrayList<>();
String sql = "SELECT a.attname AS column_name, " +
"format_type(a.atttypid, a.atttypmod) AS data_type, " +
"NOT a.attnotnull AS is_nullable, " +
"pg_get_expr(ad.adbin, ad.adrelid) AS column_default, " +
"col_description(a.attrelid, a.attnum) AS column_comment, " +
"CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 " +
"THEN ((a.atttypmod - 4) >> 16) & 65535 ELSE NULL END AS numeric_precision, " +
"CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 " +
"THEN (a.atttypmod - 4) & 65535 ELSE NULL END AS numeric_scale, " +
"CASE WHEN t.typname IN ('varchar', 'bpchar') AND a.atttypmod > 0 " +
"THEN a.atttypmod - 4 ELSE NULL END AS character_maximum_length " +
"FROM pg_catalog.pg_attribute a " +
"JOIN pg_catalog.pg_type t ON t.oid = a.atttypid " +
"JOIN pg_catalog.pg_class c ON c.oid = a.attrelid " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum " +
"WHERE n.nspname = ? AND c.relname = ? " +
"AND a.attnum > 0 AND NOT a.attisdropped " +
"ORDER BY a.attnum";
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, table);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String colName = rs.getString("column_name");
result.add(new ColumnInfo(
colName,
rs.getString("data_type"),
"YES".equals(rs.getString("is_nullable")),
rs.getString("column_default"),
primaryKeys.contains(colName),
null,
rs.getString("column_comment"),
intObject(rs, "numeric_precision"),
intObject(rs, "numeric_scale"),
intObject(rs, "character_maximum_length")
));
}
}
}
return result;
});
}
private Set<String> primaryKeys(String schema, String table) {
return unchecked(() -> {
Set<String> primaryKeys = new LinkedHashSet<>();
String sql = "SELECT a.attname AS column_name " +
"FROM pg_catalog.pg_constraint co " +
"JOIN pg_catalog.pg_class c ON c.oid = co.conrelid " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"JOIN LATERAL (SELECT unnest(co.conkey) AS attnum, generate_series(1, array_length(co.conkey, 1)) AS ord) AS pk_cols ON true " +
"JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = pk_cols.attnum " +
"WHERE co.contype = 'p' " +
"AND n.nspname = ? " +
"AND c.relname = ? " +
"ORDER BY pk_cols.ord";
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, table);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
primaryKeys.add(rs.getString("column_name"));
}
}
}
return primaryKeys;
});
}
@Override
public List<IndexInfo> listIndexes(String schema, String table) {
return unchecked(() -> {
List<IndexInfo> result = new ArrayList<>();
String sql = "SELECT i.relname AS index_name, am.amname AS index_type, " +
"ix.indisunique AS is_unique, ix.indisprimary AS is_primary, " +
"array_agg(a.attname ORDER BY k.n) AS columns " +
"FROM pg_index ix " +
"JOIN pg_class t ON t.oid = ix.indrelid " +
"JOIN pg_class i ON i.oid = ix.indexrelid " +
"JOIN pg_namespace n ON n.oid = t.relnamespace " +
"JOIN pg_am am ON am.oid = i.relam " +
"JOIN LATERAL (SELECT unnest(ix.indkey) AS attnum, generate_series(1, array_length(ix.indkey, 1)) AS n) AS k ON true " +
"JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum " +
"WHERE n.nspname = ? AND t.relname = ? " +
"GROUP BY i.relname, am.amname, ix.indisunique, ix.indisprimary " +
"ORDER BY i.relname";
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, table);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
Object[] columnArray = (Object[]) rs.getArray("columns").getArray();
List<String> columns = new ArrayList<>();
for (Object column : columnArray) {
columns.add(String.valueOf(column));
}
result.add(new IndexInfo(
rs.getString("index_name"),
columns,
rs.getBoolean("is_unique"),
rs.getBoolean("is_primary"),
null,
rs.getString("index_type"),
null,
null
));
}
}
}
return result;
});
}
@Override
public List<ForeignKeyInfo> listForeignKeys(String schema, String table) {
return unchecked(() -> {
List<ForeignKeyInfo> result = new ArrayList<>();
String sql = "SELECT co.conname AS constraint_name, " +
"a.attname AS column_name, " +
"rc.relname AS ref_table, " +
"ra.attname AS ref_column " +
"FROM pg_catalog.pg_constraint co " +
"JOIN pg_catalog.pg_class c ON c.oid = co.conrelid " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"JOIN pg_catalog.pg_class rc ON rc.oid = co.confrelid " +
"JOIN LATERAL (SELECT unnest(co.conkey) AS attnum, generate_series(1, array_length(co.conkey, 1)) AS ord) AS fk ON true " +
"JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = fk.attnum " +
"JOIN LATERAL (SELECT unnest(co.confkey) AS attnum, generate_series(1, array_length(co.confkey, 1)) AS ord) AS pk ON pk.ord = fk.ord " +
"JOIN pg_catalog.pg_attribute ra ON ra.attrelid = rc.oid AND ra.attnum = pk.attnum " +
"WHERE co.contype = 'f' " +
"AND n.nspname = ? " +
"AND c.relname = ? " +
"ORDER BY co.conname, fk.ord";
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, table);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(new ForeignKeyInfo(
rs.getString("constraint_name"),
rs.getString("column_name"),
rs.getString("ref_table"),
rs.getString("ref_column")
));
}
}
}
return result;
});
}
@Override
public List<TriggerInfo> listTriggers(String schema, String table) {
return unchecked(() -> {
List<TriggerInfo> result = new ArrayList<>();
String sql = "SELECT tg.tgname AS trigger_name, " +
"trim(trailing ',' FROM (" +
"CASE WHEN (tg.tgtype & 4) <> 0 THEN 'INSERT,' ELSE '' END || " +
"CASE WHEN (tg.tgtype & 8) <> 0 THEN 'DELETE,' ELSE '' END || " +
"CASE WHEN (tg.tgtype & 16) <> 0 THEN 'UPDATE,' ELSE '' END || " +
"CASE WHEN (tg.tgtype & 32) <> 0 THEN 'TRUNCATE,' ELSE '' END" +
")) AS event_manipulation, " +
"CASE WHEN (tg.tgtype & 2) <> 0 THEN 'BEFORE' ELSE 'AFTER' END AS action_timing " +
"FROM pg_catalog.pg_trigger tg " +
"JOIN pg_catalog.pg_class c ON c.oid = tg.tgrelid " +
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
"WHERE n.nspname = ? AND c.relname = ? AND NOT tg.tgisinternal " +
"ORDER BY tg.tgname";
try (java.sql.PreparedStatement stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, schema);
stmt.setString(2, table);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
result.add(new TriggerInfo(
rs.getString("trigger_name"),
rs.getString("event_manipulation"),
rs.getString("action_timing")
));
}
}
}
return result;
});
}
@Override
public String setSchemaSQL(String schema) {
return "SET search_path TO " + quoteIdentifier(schema);
}
private java.sql.Connection requireConnection() {
return requireConnected();
}
private static String normalizeTableType(String type) {
if (type == null || type.trim().isEmpty()) return "TABLE";
if ("BASE TABLE".equals(type)) return "TABLE";
return type;
}
private static String coalesce(String value) {
return value == null ? "" : value;
}
private String quoteQualifiedIdentifier(String schema, String name) {
return quoteIdentifier(schema) + "." + quoteIdentifier(name);
}
private static Integer intObject(ResultSet rs, String column) throws Exception {
Object value = rs.getObject(column);
return value instanceof Number ? ((Number) value).intValue() : null;
}
}
@@ -0,0 +1,30 @@
package com.dbx.agent;
public final class PostgresLikeAgentProfile {
private final String driverClass;
private final String urlTemplate;
public PostgresLikeAgentProfile(String driverClass, String urlTemplate) {
this.driverClass = driverClass;
this.urlTemplate = urlTemplate;
}
public String getDriverClass() {
return driverClass;
}
public String getUrlTemplate() {
return urlTemplate;
}
public String buildUrl(ConnectParams params) {
return new JdbcAgentProfile(
driverClass,
urlTemplate,
0,
false,
java.util.Collections.emptySet(),
java.util.Arrays.asList("TABLE", "VIEW", "MATERIALIZED VIEW", "SYSTEM TABLE", "SYSTEM VIEW")
).buildUrl(params);
}
}
@@ -0,0 +1,82 @@
package com.dbx.agent;
import java.util.Objects;
public final class QueryPageOptions {
private int pageSize;
private Integer fetchSize;
private int maxRows;
private int timeoutSecs;
public QueryPageOptions() {
this(100, null, JdbcExecutor.DEFAULT_MAX_ROWS, 0);
}
public QueryPageOptions(int pageSize, Integer fetchSize, int maxRows) {
this(pageSize, fetchSize, maxRows, 0);
}
public QueryPageOptions(int pageSize, Integer fetchSize, int maxRows, int timeoutSecs) {
this.pageSize = pageSize;
this.fetchSize = fetchSize;
this.maxRows = maxRows;
this.timeoutSecs = timeoutSecs;
}
public int getPageSize() {
return pageSize;
}
public Integer getFetchSize() {
return fetchSize;
}
public int getMaxRows() {
return maxRows;
}
public int getTimeoutSecs() {
return timeoutSecs;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setFetchSize(Integer fetchSize) {
this.fetchSize = fetchSize;
}
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public void setTimeoutSecs(int timeoutSecs) {
this.timeoutSecs = timeoutSecs;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof QueryPageOptions)) return false;
QueryPageOptions that = (QueryPageOptions) other;
return pageSize == that.pageSize
&& maxRows == that.maxRows
&& timeoutSecs == that.timeoutSecs
&& Objects.equals(fetchSize, that.fetchSize);
}
@Override
public int hashCode() {
return Objects.hash(pageSize, fetchSize, maxRows, timeoutSecs);
}
@Override
public String toString() {
return "QueryPageOptions(pageSize=" + pageSize
+ ", fetchSize=" + fetchSize
+ ", maxRows=" + maxRows
+ ", timeoutSecs=" + timeoutSecs
+ ")";
}
}
@@ -0,0 +1,90 @@
package com.dbx.agent;
import java.util.Objects;
public final class QueryPageParams {
private String sql;
private String schema;
private Integer pageSize;
private Integer fetchSize;
private Integer maxRows;
public QueryPageParams() {
this("", null, null, null, null);
}
public QueryPageParams(String sql, String schema, Integer pageSize, Integer fetchSize, Integer maxRows) {
this.sql = sql;
this.schema = schema;
this.pageSize = pageSize;
this.fetchSize = fetchSize;
this.maxRows = maxRows;
}
public String getSql() {
return sql;
}
public String getSchema() {
return schema;
}
public Integer getPageSize() {
return pageSize;
}
public Integer getFetchSize() {
return fetchSize;
}
public Integer getMaxRows() {
return maxRows;
}
public void setSql(String sql) {
this.sql = sql;
}
public void setSchema(String schema) {
this.schema = schema;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setFetchSize(Integer fetchSize) {
this.fetchSize = fetchSize;
}
public void setMaxRows(Integer maxRows) {
this.maxRows = maxRows;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof QueryPageParams)) return false;
QueryPageParams that = (QueryPageParams) other;
return Objects.equals(sql, that.sql)
&& Objects.equals(schema, that.schema)
&& Objects.equals(pageSize, that.pageSize)
&& Objects.equals(fetchSize, that.fetchSize)
&& Objects.equals(maxRows, that.maxRows);
}
@Override
public int hashCode() {
return Objects.hash(sql, schema, pageSize, fetchSize, maxRows);
}
@Override
public String toString() {
return "QueryPageParams(sql=" + sql
+ ", schema=" + schema
+ ", pageSize=" + pageSize
+ ", fetchSize=" + fetchSize
+ ", maxRows=" + maxRows
+ ")";
}
}
@@ -0,0 +1,163 @@
package com.dbx.agent;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class QueryPageResult {
private List<String> columns;
private List<String> column_types;
private List<List<Object>> rows;
private long affected_rows;
private long execution_time_ms;
private boolean truncated;
private String session_id;
private boolean has_more;
public QueryPageResult() {
this(Collections.emptyList(), Collections.emptyList(), 0L, 0L, false, null, false);
}
public QueryPageResult(List<String> columns, List<? extends List<?>> rows, long affected_rows, long execution_time_ms) {
this(columns, rows, affected_rows, execution_time_ms, false, null, false);
}
public QueryPageResult(
List<String> columns,
List<? extends List<?>> rows,
long affected_rows,
long execution_time_ms,
boolean truncated
) {
this(columns, rows, affected_rows, execution_time_ms, truncated, null, false);
}
public QueryPageResult(
List<String> columns,
List<? extends List<?>> rows,
long affected_rows,
long execution_time_ms,
boolean truncated,
String session_id,
boolean has_more
) {
this(columns, null, rows, affected_rows, execution_time_ms, truncated, session_id, has_more);
}
public QueryPageResult(
List<String> columns,
List<String> column_types,
List<? extends List<?>> rows,
long affected_rows,
long execution_time_ms,
boolean truncated,
String session_id,
boolean has_more
) {
this.columns = columns == null ? Collections.emptyList() : columns;
this.column_types = column_types == null ? Collections.emptyList() : column_types;
this.rows = QueryResult.normalizeRows(rows);
this.affected_rows = affected_rows;
this.execution_time_ms = execution_time_ms;
this.truncated = truncated;
this.session_id = session_id;
this.has_more = has_more;
}
public List<String> getColumns() {
return columns;
}
public List<String> getColumn_types() {
return column_types;
}
public List<List<Object>> getRows() {
return rows;
}
public long getAffected_rows() {
return affected_rows;
}
public long getExecution_time_ms() {
return execution_time_ms;
}
public boolean getTruncated() {
return truncated;
}
public String getSession_id() {
return session_id;
}
public boolean getHas_more() {
return has_more;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public void setColumn_types(List<String> column_types) {
this.column_types = column_types;
}
public void setRows(List<List<Object>> rows) {
this.rows = rows;
}
public void setAffected_rows(long affected_rows) {
this.affected_rows = affected_rows;
}
public void setExecution_time_ms(long execution_time_ms) {
this.execution_time_ms = execution_time_ms;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public void setSession_id(String session_id) {
this.session_id = session_id;
}
public void setHas_more(boolean has_more) {
this.has_more = has_more;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof QueryPageResult)) return false;
QueryPageResult that = (QueryPageResult) other;
return affected_rows == that.affected_rows
&& execution_time_ms == that.execution_time_ms
&& truncated == that.truncated
&& has_more == that.has_more
&& Objects.equals(columns, that.columns)
&& Objects.equals(column_types, that.column_types)
&& Objects.equals(rows, that.rows)
&& Objects.equals(session_id, that.session_id);
}
@Override
public int hashCode() {
return Objects.hash(columns, column_types, rows, affected_rows, execution_time_ms, truncated, session_id, has_more);
}
@Override
public String toString() {
return "QueryPageResult(columns=" + columns
+ ", column_types=" + column_types
+ ", rows=" + rows
+ ", affected_rows=" + affected_rows
+ ", execution_time_ms=" + execution_time_ms
+ ", truncated=" + truncated
+ ", session_id=" + session_id
+ ", has_more=" + has_more
+ ")";
}
}
@@ -0,0 +1,137 @@
package com.dbx.agent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class QueryResult {
private List<String> columns;
private List<String> column_types;
private List<List<Object>> rows;
private long affected_rows;
private long execution_time_ms;
private boolean truncated;
public QueryResult() {
this(Collections.emptyList(), Collections.emptyList(), 0L, 0L, false);
}
public QueryResult(List<String> columns, List<? extends List<?>> rows, long affected_rows, long execution_time_ms) {
this(columns, rows, affected_rows, execution_time_ms, false);
}
public QueryResult(
List<String> columns,
List<? extends List<?>> rows,
long affected_rows,
long execution_time_ms,
boolean truncated
) {
this(columns, null, rows, affected_rows, execution_time_ms, truncated);
}
public QueryResult(
List<String> columns,
List<String> column_types,
List<? extends List<?>> rows,
long affected_rows,
long execution_time_ms,
boolean truncated
) {
this.columns = columns == null ? Collections.emptyList() : columns;
this.column_types = column_types == null ? Collections.emptyList() : column_types;
this.rows = normalizeRows(rows);
this.affected_rows = affected_rows;
this.execution_time_ms = execution_time_ms;
this.truncated = truncated;
}
public List<String> getColumns() {
return columns;
}
public List<String> getColumn_types() {
return column_types;
}
public List<List<Object>> getRows() {
return rows;
}
public long getAffected_rows() {
return affected_rows;
}
public long getExecution_time_ms() {
return execution_time_ms;
}
public boolean getTruncated() {
return truncated;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public void setColumn_types(List<String> column_types) {
this.column_types = column_types;
}
public void setRows(List<List<Object>> rows) {
this.rows = rows;
}
public void setAffected_rows(long affected_rows) {
this.affected_rows = affected_rows;
}
public void setExecution_time_ms(long execution_time_ms) {
this.execution_time_ms = execution_time_ms;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
static List<List<Object>> normalizeRows(List<? extends List<?>> input) {
if (input == null) {
return Collections.emptyList();
}
List<List<Object>> normalized = new ArrayList<>();
for (List<?> row : input) {
normalized.add(row == null ? Collections.emptyList() : new ArrayList<Object>(row));
}
return normalized;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof QueryResult)) return false;
QueryResult that = (QueryResult) other;
return affected_rows == that.affected_rows
&& execution_time_ms == that.execution_time_ms
&& truncated == that.truncated
&& Objects.equals(columns, that.columns)
&& Objects.equals(column_types, that.column_types)
&& Objects.equals(rows, that.rows);
}
@Override
public int hashCode() {
return Objects.hash(columns, column_types, rows, affected_rows, execution_time_ms, truncated);
}
@Override
public String toString() {
return "QueryResult(columns=" + columns
+ ", column_types=" + column_types
+ ", rows=" + rows
+ ", affected_rows=" + affected_rows
+ ", execution_time_ms=" + execution_time_ms
+ ", truncated=" + truncated
+ ")";
}
}
@@ -0,0 +1,51 @@
package com.dbx.agent;
import java.util.Objects;
public final class SchemaTableParams {
private String schema;
private String table;
public SchemaTableParams() {
this("", "");
}
public SchemaTableParams(String schema, String table) {
this.schema = schema;
this.table = table;
}
public String getSchema() {
return schema;
}
public String getTable() {
return table;
}
public void setSchema(String schema) {
this.schema = schema;
}
public void setTable(String table) {
this.table = table;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof SchemaTableParams)) return false;
SchemaTableParams that = (SchemaTableParams) other;
return Objects.equals(schema, that.schema) && Objects.equals(table, that.table);
}
@Override
public int hashCode() {
return Objects.hash(schema, table);
}
@Override
public String toString() {
return "SchemaTableParams(schema=" + schema + ", table=" + table + ")";
}
}
@@ -0,0 +1,350 @@
package com.dbx.agent;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public final class StandardJdbcMetadata {
public static final StandardJdbcMetadata INSTANCE = new StandardJdbcMetadata();
private StandardJdbcMetadata() {
}
public List<DatabaseInfo> listDatabases(Connection conn, String configuredDatabase) {
return unchecked(() -> {
Set<String> names = new LinkedHashSet<>();
try {
try (ResultSet rs = conn.getMetaData().getCatalogs()) {
while (rs.next()) {
addNonBlank(names, rs.getString("TABLE_CAT"));
}
}
} catch (Exception ignored) {
}
addNonBlank(names, configuredDatabase);
addNonBlank(names, conn.getCatalog());
List<DatabaseInfo> result = new ArrayList<>();
for (String name : names) {
result.add(new DatabaseInfo(name));
}
return result;
});
}
public List<String> listSchemas(Connection conn, JdbcAgentProfile profile) {
return unchecked(() -> {
Set<String> names = new LinkedHashSet<>();
DatabaseMetaData meta = conn.getMetaData();
try {
appendSchemas(names, meta.getSchemas(null, null));
} catch (Exception | AbstractMethodError first) {
try {
appendSchemas(names, meta.getSchemas());
} catch (Exception | AbstractMethodError ignored) {
}
}
try {
addNonBlank(names, conn.getSchema());
} catch (Exception | AbstractMethodError ignored) {
}
List<String> result = new ArrayList<>();
for (String name : names) {
if (!profile.getExcludedSchemas().contains(name.toUpperCase(Locale.ROOT))) {
result.add(name);
}
}
Collections.sort(result);
return result;
});
}
public List<TableInfo> listTables(Connection conn, JdbcAgentProfile profile, String configuredDatabase, String schema) {
return unchecked(() -> {
DatabaseMetaData meta = conn.getMetaData();
List<TableInfo> result = new ArrayList<>();
appendTables(result, meta, profile, null, schema);
if (result.isEmpty() && profile.getCatalogFallbackEnabled() && !configuredDatabase.trim().isEmpty()) {
appendTables(result, meta, profile, configuredDatabase, schema);
}
result.sort(Comparator.comparing(TableInfo::getName));
return result;
});
}
public List<ObjectInfo> listObjects(List<TableInfo> tables, String schema) {
List<ObjectInfo> result = new ArrayList<>();
for (TableInfo table : tables) {
result.add(new ObjectInfo(table.getName(), table.getTable_type(), schema, table.getComment()));
}
return result;
}
public List<ColumnInfo> getColumns(Connection conn, JdbcAgentProfile profile, String configuredDatabase, String schema, String table) {
return unchecked(() -> {
DatabaseMetaData meta = conn.getMetaData();
Set<String> primaryKeys = primaryKeys(meta, null, schema, table);
List<ColumnInfo> result = new ArrayList<>();
appendColumns(result, meta, null, schema, table, primaryKeys);
if (result.isEmpty() && profile.getCatalogFallbackEnabled() && !configuredDatabase.trim().isEmpty()) {
Set<String> fallbackPrimaryKeys = primaryKeys(meta, configuredDatabase, schema, table);
appendColumns(result, meta, configuredDatabase, schema, table, fallbackPrimaryKeys);
}
return result;
});
}
public List<IndexInfo> listIndexes(Connection conn, String schema, String table) {
return unchecked(() -> {
DatabaseMetaData meta = conn.getMetaData();
Map<String, List<IndexColumn>> indexes = new LinkedHashMap<>();
Map<String, Boolean> unique = new LinkedHashMap<>();
try (ResultSet rs = meta.getIndexInfo(null, blankToNull(schema), table, false, false)) {
while (rs.next()) {
String name = rs.getString("INDEX_NAME");
String column = rs.getString("COLUMN_NAME");
if (name == null || column == null) {
continue;
}
indexes.computeIfAbsent(name, ignored -> new ArrayList<>()).add(
new IndexColumn(rs.getShort("ORDINAL_POSITION"), column)
);
unique.put(name, !rs.getBoolean("NON_UNIQUE"));
}
}
List<IndexInfo> result = new ArrayList<>();
for (Map.Entry<String, List<IndexColumn>> entry : indexes.entrySet()) {
List<IndexColumn> orderedColumns = entry.getValue();
orderedColumns.sort(Comparator.comparingInt(IndexColumn::getOrdinal));
List<String> columns = new ArrayList<>();
for (IndexColumn column : orderedColumns) {
columns.add(column.getName());
}
String name = entry.getKey();
result.add(new IndexInfo(
name,
columns,
Boolean.TRUE.equals(unique.get(name)),
"PRIMARY".equalsIgnoreCase(name),
null,
null,
null,
null
));
}
return result;
});
}
public List<ForeignKeyInfo> listForeignKeys(Connection conn, String schema, String table) {
return unchecked(() -> {
DatabaseMetaData meta = conn.getMetaData();
List<ForeignKeyInfo> result = new ArrayList<>();
try (ResultSet rs = meta.getImportedKeys(null, blankToNull(schema), table)) {
while (rs.next()) {
String name = rs.getString("FK_NAME");
result.add(new ForeignKeyInfo(
name == null ? "" : name,
rs.getString("FKCOLUMN_NAME"),
rs.getString("PKTABLE_NAME"),
rs.getString("PKCOLUMN_NAME")
));
}
}
return result;
});
}
public List<TriggerInfo> listTriggers(String schema, String table) {
return Collections.emptyList();
}
private static String[] getDriverTableTypes(DatabaseMetaData meta, JdbcAgentProfile profile) throws Exception {
Set<String> configuredTypes = new LinkedHashSet<>();
for (String type : profile.getTableTypes()) {
if (type != null) {
configuredTypes.add(type.toUpperCase(Locale.ROOT));
}
}
try (ResultSet rs = meta.getTableTypes()) {
List<String> types = new ArrayList<>();
while (rs.next()) {
String type = rs.getString("TABLE_TYPE");
if (type != null && configuredTypes.contains(type.toUpperCase(Locale.ROOT))) {
types.add(type);
}
}
if (!types.isEmpty()) {
return types.toArray(new String[0]);
}
} catch (Exception ignored) {
}
return profile.getTableTypes().toArray(new String[profile.getTableTypes().size()]);
}
public static String getIdentifierQuote(Connection conn, JdbcAgentProfile profile) {
try {
String quote = conn.getMetaData().getIdentifierQuoteString();
if (quote != null && !quote.trim().isEmpty()) {
return quote.trim();
}
} catch (Exception ignored) {
}
return profile.getIdentifierQuote();
}
public static String quoteIdentifier(String identifier, String quote) {
return quote + identifier.replace(quote, quote + quote) + quote;
}
public static String schemaSwitchSql(Connection conn, JdbcAgentProfile profile, String schema) {
if (profile.getSkipExecutionContext()) {
return profile.schemaSwitchSql(schema);
}
String quote = getIdentifierQuote(conn, profile);
return profile.schemaSwitchSql(schema, quote);
}
private void appendTables(List<TableInfo> result, DatabaseMetaData meta, JdbcAgentProfile profile, String catalog, String schema) throws Exception {
String[] tableTypes = getDriverTableTypes(meta, profile);
try (ResultSet rs = meta.getTables(catalog, blankToNull(schema), "%", tableTypes)) {
while (rs.next()) {
result.add(new TableInfo(
rs.getString("TABLE_NAME"),
normalizeTableType(rs.getString("TABLE_TYPE")),
rs.getString("REMARKS")
));
}
}
}
private Set<String> primaryKeys(DatabaseMetaData meta, String catalog, String schema, String table) {
Set<String> keys = new LinkedHashSet<>();
try (ResultSet rs = meta.getPrimaryKeys(catalog, blankToNull(schema), table)) {
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
if (name != null) {
keys.add(name);
}
}
} catch (Exception ignored) {
}
return keys;
}
private static void appendSchemas(Set<String> names, ResultSet rs) throws Exception {
try (ResultSet closeable = rs) {
while (closeable.next()) {
addNonBlank(names, closeable.getString("TABLE_SCHEM"));
}
}
}
private void appendColumns(
List<ColumnInfo> result,
DatabaseMetaData meta,
String catalog,
String schema,
String table,
Set<String> primaryKeys
) throws Exception {
try (ResultSet rs = meta.getColumns(catalog, blankToNull(schema), table, "%")) {
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
result.add(new ColumnInfo(
name,
rs.getString("TYPE_NAME"),
rs.getInt("NULLABLE") != DatabaseMetaData.columnNoNulls,
rs.getString("COLUMN_DEF"),
primaryKeys.contains(name),
null,
rs.getString("REMARKS"),
intOrNull(rs, "COLUMN_SIZE"),
intOrNull(rs, "DECIMAL_DIGITS"),
characterLength(rs)
));
}
}
}
private static String normalizeTableType(String type) {
if (type == null || type.trim().isEmpty()) {
return "TABLE";
}
String normalized = type.toUpperCase(Locale.ROOT);
if ("BASE TABLE".equals(normalized) || "COLUMN TABLE".equals(normalized) || "ROW TABLE".equals(normalized)) {
return "TABLE";
}
return type;
}
private static Integer intOrNull(ResultSet rs, String column) throws Exception {
Object value = rs.getObject(column);
return value instanceof Number ? ((Number) value).intValue() : null;
}
private static Integer characterLength(ResultSet rs) throws Exception {
String typeName = rs.getString("TYPE_NAME");
if (typeName == null) {
return null;
}
String normalized = typeName.toLowerCase(Locale.ROOT);
if (!normalized.contains("char") && !normalized.contains("text")) {
return null;
}
return intOrNull(rs, "COLUMN_SIZE");
}
private static String blankToNull(String value) {
return value == null || value.trim().isEmpty() ? null : value;
}
private static void addNonBlank(Set<String> values, String value) {
if (value != null && !value.trim().isEmpty()) {
values.add(value);
}
}
private static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static final class IndexColumn {
private final int ordinal;
private final String name;
private IndexColumn(int ordinal, String name) {
this.ordinal = ordinal;
this.name = name;
}
private int getOrdinal() {
return ordinal;
}
private String getName() {
return name;
}
}
private interface ThrowingSupplier<T> {
T get() throws Exception;
}
}
@@ -0,0 +1,67 @@
package com.dbx.agent;
import java.util.Objects;
public final class TableInfo {
private String name;
private String table_type;
private String comment;
public TableInfo() {
this("", "", null);
}
public TableInfo(String name, String table_type) {
this(name, table_type, null);
}
public TableInfo(String name, String table_type, String comment) {
this.name = name;
this.table_type = table_type;
this.comment = comment;
}
public String getName() {
return name;
}
public String getTable_type() {
return table_type;
}
public String getComment() {
return comment;
}
public void setName(String name) {
this.name = name;
}
public void setTable_type(String table_type) {
this.table_type = table_type;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof TableInfo)) return false;
TableInfo that = (TableInfo) other;
return Objects.equals(name, that.name)
&& Objects.equals(table_type, that.table_type)
&& Objects.equals(comment, that.comment);
}
@Override
public int hashCode() {
return Objects.hash(name, table_type, comment);
}
@Override
public String toString() {
return "TableInfo(name=" + name + ", table_type=" + table_type + ", comment=" + comment + ")";
}
}
@@ -0,0 +1,135 @@
package com.dbx.agent;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
public final class TransactionExecutor {
private TransactionExecutor() {
}
public static QueryResult executeUpdateStatements(
Connection conn,
List<String> statements,
String schema,
Function<String, String> setSchemaSql
) {
return executeStatements(conn, statements, schema, setSchemaSql, new StatementRunner() {
@Override
public long run(Statement stmt, String sql) throws Exception {
return stmt.executeUpdate(sql);
}
});
}
public static QueryResult executeStatements(
Connection conn,
List<String> statements,
String schema,
Function<String, String> setSchemaSql,
StatementRunner runner
) {
return unchecked(() -> {
long start = System.currentTimeMillis();
if (!supportsTransactions(conn)) {
long totalAffected = executeAll(conn, statements, schema, setSchemaSql, runner);
return result(totalAffected, start);
}
boolean savedAutoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
long totalAffected = executeAll(conn, statements, schema, setSchemaSql, runner);
conn.commit();
return result(totalAffected, start);
} catch (Exception e) {
conn.rollback();
throw e;
} finally {
conn.setAutoCommit(savedAutoCommit);
}
});
}
private static long executeAll(
Connection conn,
List<String> statements,
String schema,
Function<String, String> setSchemaSql,
StatementRunner runner
) throws Exception {
applySchema(conn, schema, setSchemaSql);
long totalAffected = 0;
for (String statement : statements) {
try (Statement stmt = conn.createStatement()) {
totalAffected += runner.run(stmt, JdbcExecutor.trimSql(statement));
}
}
return totalAffected;
}
private static void applySchema(Connection conn, String schema, Function<String, String> setSchemaSql) throws Exception {
if (schema == null || schema.trim().isEmpty()) {
return;
}
// Prefer JDBC standard APIs over database-specific SQL.
try {
conn.setSchema(schema);
return;
} catch (Exception | AbstractMethodError ignored) {
// setSchema not supported by this driver
}
try {
conn.setCatalog(schema);
return;
} catch (Exception | AbstractMethodError ignored) {
// setCatalog not supported either
}
// Fallback: execute database-specific SQL (e.g. USE, SET SCHEMA, etc.)
String schemaSql = setSchemaSql.apply(schema);
if (schemaSql == null || schemaSql.trim().isEmpty()) {
return;
}
try (Statement stmt = conn.createStatement()) {
stmt.execute(schemaSql);
}
}
private static boolean supportsTransactions(Connection conn) {
try {
return conn.getMetaData().supportsTransactions();
} catch (Exception ignored) {
return true;
}
}
private static QueryResult result(long totalAffected, long start) {
return new QueryResult(
Collections.emptyList(),
Collections.emptyList(),
totalAffected,
System.currentTimeMillis() - start,
false
);
}
private static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public interface StatementRunner {
long run(Statement stmt, String sql) throws Exception;
}
private interface ThrowingSupplier<T> {
T get() throws Exception;
}
}
@@ -0,0 +1,63 @@
package com.dbx.agent;
import java.util.Objects;
public final class TriggerInfo {
private String name;
private String event;
private String timing;
public TriggerInfo() {
this("", "", "");
}
public TriggerInfo(String name, String event, String timing) {
this.name = name;
this.event = event;
this.timing = timing;
}
public String getName() {
return name;
}
public String getEvent() {
return event;
}
public String getTiming() {
return timing;
}
public void setName(String name) {
this.name = name;
}
public void setEvent(String event) {
this.event = event;
}
public void setTiming(String timing) {
this.timing = timing;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof TriggerInfo)) return false;
TriggerInfo that = (TriggerInfo) other;
return Objects.equals(name, that.name)
&& Objects.equals(event, that.event)
&& Objects.equals(timing, that.timing);
}
@Override
public int hashCode() {
return Objects.hash(name, event, timing);
}
@Override
public String toString() {
return "TriggerInfo(name=" + name + ", event=" + event + ", timing=" + timing + ")";
}
}
@@ -0,0 +1,75 @@
{
"protocolVersion": 1,
"handshakeMethod": "handshake",
"handshakeResponseFields": [
"protocolVersion",
"agentProtocolVersion",
"capabilities"
],
"allCapabilities": [
"connect",
"test_connection",
"metadata",
"query",
"paged_query",
"transaction",
"ddl",
"kv"
],
"capabilities": [
"connect",
"test_connection",
"metadata",
"query",
"paged_query",
"transaction",
"ddl"
],
"defaultSqlCapabilities": [
"connect",
"test_connection",
"metadata",
"query",
"paged_query",
"transaction",
"ddl"
],
"commonMethods": [
"handshake",
"connect",
"test_connection",
"validate_connection",
"list_databases",
"list_schemas",
"list_tables",
"list_objects",
"get_object_source",
"get_table_ddl",
"get_columns",
"list_indexes",
"list_foreign_keys",
"list_triggers",
"execute_query",
"execute_query_page",
"fetch_query_page",
"close_query_session",
"get_explain_info",
"execute_transaction",
"disconnect",
"shutdown"
],
"mongoLegacyMethods": [
"list_databases",
"list_collections",
"find_documents",
"insert_document",
"update_document",
"delete_document"
],
"kvMethods": [
"kv_list_prefix",
"kv_get",
"kv_put",
"kv_delete"
]
}