Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 45 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Tauri-based cross-platform SQL database GUI client with Vue 3 + TypeScript front

### Frontend
```bash
npm run dev # Vite dev server (port 1420)
npm run dev # Vite dev server (port 1521, matches tauri.conf devUrl)
npm run build # Build frontend (vue-tsc + vite)
npm run lint:check # Check linting
npm run lint:fix # Auto-fix lint issues
Expand All @@ -46,6 +46,26 @@ cargo clippy # Linter
npm run tauri dev # Run Tauri app in dev mode
```

### JDBC Bridge (Java, `jdbc-bridge/`)
```bash
cd jdbc-bridge
mvn clean package -DskipTests \
-Dmaven.compiler.source=21 -Dmaven.compiler.target=21
# pom targets Java 25 — override to match a local JDK 21+ toolchain

# Deploy: the app loads ~/.sqlkit/jdbc-bridge/jdbc-bridge-<app-version>.jar
# (current app version, e.g. jdbc-bridge-1.0.2.jar; SQLKIT_JDBC_BRIDGE_JAR overrides)
cp target/jdbc-bridge-1.0.0.jar ~/.sqlkit/jdbc-bridge/jdbc-bridge-1.0.2.jar
pkill -f 'java -jar.*jdbc-bridge' # restart the bridge after every jar swap
```

**Never swap the deployed jar while a bridge JVM is running.** The JVM holds an open handle to the file; an in-place rewrite desyncs its cached zip directory and lazily loaded classes fail with `NoClassDefFoundError` that looks like a broken build. Kill the process first — the app respawns it on the next connection.

Live smoke test (bridge speaks newline-delimited JSON on stdin/stdout):
```bash
echo '{"id":1,"method":"ping"}' | java -jar ~/.sqlkit/jdbc-bridge/jdbc-bridge-1.0.2.jar
```

## Code Style Guidelines

### TypeScript/Frontend
Expand Down Expand Up @@ -182,6 +202,24 @@ src-tauri/src/
└── lib.rs # Command registration
```

## JDBC Bridge Architecture

The bridge is a Java subprocess (`jdbc-bridge/`) speaking newline-delimited JSON-RPC (`{id, method, params}` → `{id, result, error, error_type}`) over stdin/stdout. It owns a HikariCP pool per connection and is shared across all JDBC connections of the app. Drivers resolve on demand: Maven Central for thin JARs, `download_url` for pre-shaded bundles (Cassandra wrapper, GBase), GitHub Releases for the bridge itself.

## CQL Engines (Cassandra/ScyllaDB)

Connection driver: ING's `cassandra-jdbc-wrapper` pre-shaded bundle from its GitHub releases (Maven Central hosts only the thin JAR); configured in `src-tauri/src/database/jdbc_bridge/drivers.toml`. Both engines share one bundle and cache dir.

CQL diverges from SQL in ways the code must honor:

- **Keyspaces map to JDBC schemas, not catalogs.** The wrapper's catalog lookup returns nothing, and its `DatabaseMetaData` only sees the connect-time keyspace. `JdbcBridgeAdapter::fold_catalog_into_schema` routes metadata RPCs to the schema slot, and `list_databases`/`list_tables`/`list_columns` query `system_schema` directly. Foreign keys and views return empty lists (CQL has no FKs; the wrapper throws on those calls).
- **No TLS negotiation in the CQL native protocol.** The server is fixed to TLS-or-plaintext at startup, so `sslmode=prefer` connects plaintext for CQL (libpq's try-then-fallback does not exist here — a TLS attempt against a plaintext server just times out). `require`/`verify-ca`/`verify-full` enforce TLS. The decision lives in three aligned places: frontend `normalizeSslMode`, bridge `SslPropertyMapper.requiresCqlTls`, and the adapter's ssl_mode translation.
- **No sqlparser dialect.** `classify_cql` (keyword classifier) replaces AST parsing on the MCP/AI risk path, and `wrap_query` passes CQL through unparsed — grid sort/filter/paging is intentionally unavailable for CQL. ScyllaDB 6.x additionally rejects `SimpleStrategy` keyspaces (tablet replication).

## Dependency Version Alignment

`libsqlite3-sys` declares `links = "sqlite3"` — cargo allows exactly one version per build. sqlkit, dockit, and data-studio-agent all consume rusqlite, so **rusqlite upgrades must move all three repos in the same train**: framework PR + tag first, then sqlkit/dockit bumps (data-studio-agent is pinned by tag in `src-tauri/Cargo.toml`). rusqlite 0.43+ also made `chrono` an implicit optional-dependency feature — absent from crates.io metadata but still enabled by `features = ["chrono"]`; verify feature existence against the tag's Cargo.toml, not the registry API.

## Key Patterns

**Tauri Commands**: Return `Result<T, String>`, use `State<'_, AppState>`.
Expand Down Expand Up @@ -243,16 +281,15 @@ git push

## Common Tasks

**Adding a Database Engine**:
1. Add the variant to `DatabaseType` in `src-tauri/src/database/config.rs` and wire it in `strategy.rs` (connection routing, default port), `state.rs`, `commands/helpers.rs`, `commands/jdbc.rs`, and `jdbc_bridge/fallback.rs` + `registry.rs`
2. Frontend: enum + `dbTypeToBackend`/`dbTypeFromBackend` in `src/store/connectionStore.ts`, icon in `src/composables/useDatabaseIcon.ts`, SSL behavior in `src/types/connection.ts`, form handling in `ServerFormDialog.vue`, labels in all seven `src/lang/*` files
3. Check `src/components/sidebar/dbCapabilities.ts` — feature-gate what the engine cannot do instead of letting UI affordances fail at runtime
4. JDBC engines additionally need a driver entry in `src-tauri/src/database/jdbc_bridge/drivers.toml` and `DatabaseType` → registry key in `jdbc_bridge/registry.rs`

**Adding a Tauri Command**:
1. Add function in `src-tauri/src/commands/`
2. Add `#[tauri::command]` attribute
3. Export from `commands/mod.rs`
4. Register in `lib.rs` `generate_handler![]`

**Adding a Database Adapter**:
1. Create `src-tauri/src/database/newdb.rs`
2. Implement `DatabaseAdapter` trait
3. Add to `mod.rs` exports
4. Add variant to `ActiveConnection` enum in `state.rs`
5. Update command match statements

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ SqlKit supports **70+ databases** across four adapter strategies:
| **Native** (Rust) | PostgreSQL, MySQL, SQL Server, SQLite |
| **PG-wire compat** | CockroachDB, Redshift, YugabyteDB, TimescaleDB, QuestDB, Vastbase, YashanDB, KingbaseES, GaussDB, HighGo, UXDB, OpenGauss, GBase8c, Greenplum, EnterpriseDB, CrateDB, Materialize, AlloyDB, CloudSQLPG, FujitsuPG |
| **MySQL-wire compat** | MariaDB, TiDB, OceanBase, TDSQL, PolarDB, Doris, SelectDB, StarRocks, Databend, GoldenDB, ManticoreSearch, SingleStore, CloudSQLMySQL |
| **JDBC bridge** | Oracle, DuckDB, Firebird, DB2, H2, Snowflake, TDengine, Derby, Hive, Databricks, Hana, Teradata, Vertica, Exasol, BigQuery, Informix, Kylin, Cassandra, Iris, Access, Dameng, XuguDB, GBase8a |
| **JDBC bridge** | Oracle, DuckDB, Firebird, DB2, H2, Snowflake, TDengine, Derby, Hive, Databricks, Hana, Teradata, Vertica, Exasol, BigQuery, Informix, Kylin, Cassandra (3.0+), ScyllaDB, Iris, Access, Dameng, XuguDB, GBase8a |
| **HTTP bridge** | ClickHouse, Trino, Presto, RQLite, Turso |

### Product-Grade Editor
Expand Down
4 changes: 4 additions & 0 deletions docs/SSL_UI_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ Database-specific SSL configuration with dropdown selector + conditional fields.

---

## Apache Cassandra and ScyllaDB

CQL connections offer Disable, Require, Verify CA, and Verify Full. Saved Prefer settings use Require. Require, Verify CA, and Verify Full use TLS for both engines. Require uses the JVM trust store with no hostname check. Verify CA uses the configured CA, and Verify Full also checks the hostname. The certificate and private key fields configure client authentication when both are supplied.

## PostgreSQL

### UI Layout
Expand Down
52 changes: 38 additions & 14 deletions jdbc-bridge/src/main/java/sqlkit/bridge/ConnectionManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class ConnectionManager {

private final Map<String, HikariDataSource> pools = new HashMap<>();
private final Map<String, DriverClassLoader> loaders = new HashMap<>();
private final Map<String, SslPropertyMapper.CqlTlsSettings> cqlTls = new HashMap<>();

/**
* Driver classes loaded once per JAR set.
Expand Down Expand Up @@ -44,7 +45,7 @@ public void connect(String connId, String url, String username,
boolean credentialsInUrl,
String sslMode, String sslCaCert,
String sslClientCert, String sslClientKey,
boolean trustServerCertificate) throws ClassifiedException, Exception {
boolean trustServerCertificate, String cqlKeyspace) throws ClassifiedException, Exception {
if (pools.containsKey(connId)) {
throw new Exception("Connection already exists: " + connId);
}
Expand All @@ -62,7 +63,10 @@ public void connect(String connId, String url, String username,

final java.sql.Driver driver = sharedDriver(driverClass, driverJars);
DriverClassLoader loader = loaderFor(driverJars);
loaders.put(connId, loader);
final SslPropertyMapper.CqlTlsSettings tls = SslPropertyMapper.requiresCqlTls(driverClass, sslMode)
? SslPropertyMapper.cqlTlsSettings(jdbcUrl, username, password, sslMode,
sslCaCert, sslClientCert, sslClientKey)
: null;

HikariConfig config = new HikariConfig();
// Keep HikariCP's read-only flag aligned with the connection the driver
Expand All @@ -72,17 +76,21 @@ public void connect(String connId, String url, String username,
config.setReadOnly(isReadOnlyUrl(jdbcUrl));
config.setDataSource(new javax.sql.DataSource() {
public java.sql.Connection getConnection() throws java.sql.SQLException {
java.util.Properties info = new java.util.Properties();
if (username != null) info.setProperty("user", username);
if (password != null) info.setProperty("password", password);
SslPropertyMapper.applySslProperties(driverClass, jdbcUrl, sslMode, sslCaCert, sslClientCert, sslClientKey, trustServerCertificate, info);
return driver.connect(jdbcUrl, info);
return getConnection(username, password);
}
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException {
java.util.Properties info = new java.util.Properties();
if (u != null) info.setProperty("user", u);
if (p != null) info.setProperty("password", p);
SslPropertyMapper.applySslProperties(driverClass, jdbcUrl, sslMode, sslCaCert, sslClientCert, sslClientKey, trustServerCertificate, info);
if (cqlKeyspace != null) {
// URL paths are validated as unquoted names by the wrapper.
info.setProperty("databaseName", "\"" + cqlKeyspace.replace("\"", "\"\"") + "\"");
}
if (tls != null) {
info.putAll(tls.properties);
} else {
SslPropertyMapper.applySslProperties(driverClass, jdbcUrl, sslMode, sslCaCert, sslClientCert, sslClientKey, trustServerCertificate, info);
}
return driver.connect(jdbcUrl, info);
}
public java.io.PrintWriter getLogWriter() { return null; }
Expand All @@ -104,18 +112,28 @@ public void setLoginTimeout(int seconds) {}
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);

HikariDataSource ds = new HikariDataSource(config);

// Verify connection works
try (Connection c = ds.getConnection()) {
// ok
HikariDataSource ds = null;
try {
ds = new HikariDataSource(config);
try (Connection c = ds.getConnection()) {
// Verify the pool can open a connection.
}
} catch (Exception e) {
ds.close();
if (ds != null) {
ds.close();
}
if (tls != null) {
tls.close();
}
ErrorClassifier.ErrorType errorType = ErrorClassifier.classify(e);
throw new ClassifiedException("Failed to verify connection: " + e.getMessage(), e, errorType);
}

pools.put(connId, ds);
loaders.put(connId, loader);
if (tls != null) {
cqlTls.put(connId, tls);
}
}

/** Reuse one {@link DriverClassLoader} per set of driver JARs. */
Expand Down Expand Up @@ -174,6 +192,10 @@ public void disconnect(String connId) {
// The loader is shared with other connections (see sharedLoaders), so it is
// only closed when the whole bridge shuts down.
loaders.remove(connId);
SslPropertyMapper.CqlTlsSettings tls = cqlTls.remove(connId);
if (tls != null) {
tls.close();
}
}

/**
Expand Down Expand Up @@ -216,6 +238,8 @@ public void closeAll() {
ds.close();
}
pools.clear();
cqlTls.values().forEach(SslPropertyMapper.CqlTlsSettings::close);
cqlTls.clear();
for (DriverClassLoader loader : loaders.values()) {
try { loader.close(); } catch (Exception ignored) { }
}
Expand Down
9 changes: 6 additions & 3 deletions jdbc-bridge/src/main/java/sqlkit/bridge/ProtocolHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ public ObjectNode handle(JsonNode request) {
break;

case "connect":
handleConnect(params, response);
case "connect_cql_tls":
case "connect_cql":
handleConnect(params, response, "connect_cql".equals(method));
break;

case "disconnect":
Expand Down Expand Up @@ -155,7 +157,7 @@ private static String buildErrorMessage(Throwable e) {
return sb.toString();
}

private void handleConnect(JsonNode params, ObjectNode response) throws Exception {
private void handleConnect(JsonNode params, ObjectNode response, boolean cql) throws Exception {
String connId = requiredString(params, "conn_id",
UUID.randomUUID().toString());
String url = requiredString(params, "url", null);
Expand All @@ -181,7 +183,8 @@ private void handleConnect(JsonNode params, ObjectNode response) throws Exceptio
String sslClientKey = params.has("ssl_client_key") && !params.get("ssl_client_key").isNull() ? params.get("ssl_client_key").asText() : null;
boolean trustServerCertificate = params.has("trust_server_certificate") && params.get("trust_server_certificate").asBoolean(false);

connectionManager.connect(connId, url, username, password, driverClass, driverJars, poolMin, poolMax, credentialsInUrl, sslMode, sslCaCert, sslClientCert, sslClientKey, trustServerCertificate);
String cqlKeyspace = cql ? requiredString(params, "database", null) : null;
connectionManager.connect(connId, url, username, password, driverClass, driverJars, poolMin, poolMax, credentialsInUrl, sslMode, sslCaCert, sslClientCert, sslClientKey, trustServerCertificate, cqlKeyspace);
response.put("result", connId);
}

Expand Down
100 changes: 100 additions & 0 deletions jdbc-bridge/src/main/java/sqlkit/bridge/SslPropertyMapper.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package sqlkit.bridge;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.*;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
Expand All @@ -10,9 +16,12 @@
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class SslPropertyMapper {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String KEYSTORE_PASSWORD = "changeit";

public static void applySslProperties(String driverClass, String jdbcUrl,
Expand Down Expand Up @@ -124,6 +133,97 @@ public static void applySslProperties(String driverClass, String jdbcUrl,
}
}

static boolean requiresCqlTls(String driverClass, String mode) {
return "com.ing.data.cassandra.jdbc.CassandraDriver".equals(driverClass)
&& ("require".equals(mode) || "verify-ca".equals(mode) || "verify-full".equals(mode));
}

/** Connection-local TLS settings for the Cassandra wrapper. */
static final class CqlTlsSettings implements AutoCloseable {
final Properties properties = new Properties();
private final List<Path> files = new ArrayList<>();

void addStore(ObjectNode ssl, String kind, String store) throws IOException {
if (store == null) {
throw new IOException("Could not load CQL TLS " + kind);
}
files.add(Path.of(store));
ssl.put(kind + "-path", store);
ssl.put(kind + "-password", KEYSTORE_PASSWORD);
}

@Override
public void close() {
for (Path file : files) {
try {
Files.deleteIfExists(file);
} catch (IOException e) {
file.toFile().deleteOnExit();
}
}
}
}

static CqlTlsSettings cqlTlsSettings(String url, String user, String password, String mode,
String ca, String cert, String key) throws IOException {
CqlTlsSettings tls = new CqlTlsSettings();
boolean verifyHostname = "verify-full".equals(mode);
if (ca == null && cert == null && key == null) {
tls.properties.setProperty("enableSsl", "true");
tls.properties.setProperty("hostnameVerification", Boolean.toString(verifyHostname));
return tls;
}
try {
if ((cert == null) != (key == null)) {
throw new IOException("CQL TLS client authentication requires both a certificate and a private key");
}
// A driver config file replaces the wrapper's programmatic settings.
// Include the original datacenter and credentials alongside the TLS stores.
String dc = null;
String query = URI.create(url.substring("jdbc:".length())).getQuery();
if (query != null) {
for (String param : query.split("&")) {
if (param.startsWith("localdatacenter=")) {
dc = URLDecoder.decode(param.substring("localdatacenter=".length()), StandardCharsets.UTF_8);
break;
}
}
}
if (dc == null || dc.isBlank()) {
throw new IOException("CQL TLS requires a local datacenter");
}

ObjectNode root = MAPPER.createObjectNode();
ObjectNode driver = root.putObject("datastax-java-driver");
driver.putObject("basic").putObject("load-balancing-policy").put("local-datacenter", dc);
ObjectNode advanced = driver.putObject("advanced");
if (user != null && !user.isEmpty() && password != null) {
ObjectNode auth = advanced.putObject("auth-provider");
auth.put("class", "PlainTextAuthProvider");
auth.put("username", user);
auth.put("password", password);
}
ObjectNode ssl = advanced.putObject("ssl-engine-factory");
ssl.put("class", "DefaultSslEngineFactory");
ssl.put("hostname-validation", verifyHostname);
if (ca != null) {
tls.addStore(ssl, "truststore", convertPemCaCertToPkcs12(ca));
}
if (cert != null) {
tls.addStore(ssl, "keystore", convertPemClientCertToPkcs12(cert, key));
}
Path configuration = Files.createTempFile("sqlkit-cql-tls-", ".conf");
tls.files.add(configuration);
configuration.toFile().deleteOnExit();
Files.writeString(configuration, root.toString());
tls.properties.setProperty("configFile", configuration.toString());
return tls;
} catch (IOException | RuntimeException e) {
tls.close();
throw e;
}
}

private static String convertPemCaCertToPkcs12(String pemPath) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Expand Down
Loading
Loading