diff --git a/AGENTS.md b/AGENTS.md index 8fb4cd82..28429ac5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 @@ -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-.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 @@ -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`, use `State<'_, AppState>`. @@ -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 - diff --git a/README.md b/README.md index 7a1fb0cc..b2e2d370 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/SSL_UI_DESIGN.md b/docs/SSL_UI_DESIGN.md index 3c094bc5..514fb5da 100644 --- a/docs/SSL_UI_DESIGN.md +++ b/docs/SSL_UI_DESIGN.md @@ -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 diff --git a/jdbc-bridge/src/main/java/sqlkit/bridge/ConnectionManager.java b/jdbc-bridge/src/main/java/sqlkit/bridge/ConnectionManager.java index da0f0339..054ad889 100644 --- a/jdbc-bridge/src/main/java/sqlkit/bridge/ConnectionManager.java +++ b/jdbc-bridge/src/main/java/sqlkit/bridge/ConnectionManager.java @@ -14,6 +14,7 @@ public class ConnectionManager { private final Map pools = new HashMap<>(); private final Map loaders = new HashMap<>(); + private final Map cqlTls = new HashMap<>(); /** * Driver classes loaded once per JAR set. @@ -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); } @@ -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 @@ -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; } @@ -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. */ @@ -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(); + } } /** @@ -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) { } } diff --git a/jdbc-bridge/src/main/java/sqlkit/bridge/ProtocolHandler.java b/jdbc-bridge/src/main/java/sqlkit/bridge/ProtocolHandler.java index e04896c2..4cf4381d 100644 --- a/jdbc-bridge/src/main/java/sqlkit/bridge/ProtocolHandler.java +++ b/jdbc-bridge/src/main/java/sqlkit/bridge/ProtocolHandler.java @@ -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": @@ -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); @@ -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); } diff --git a/jdbc-bridge/src/main/java/sqlkit/bridge/SslPropertyMapper.java b/jdbc-bridge/src/main/java/sqlkit/bridge/SslPropertyMapper.java index 7503fe0f..aa097a04 100644 --- a/jdbc-bridge/src/main/java/sqlkit/bridge/SslPropertyMapper.java +++ b/jdbc-bridge/src/main/java/sqlkit/bridge/SslPropertyMapper.java @@ -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; @@ -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, @@ -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 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"); diff --git a/jdbc-bridge/src/test/java/sqlkit/bridge/SslPropertyMapperTest.java b/jdbc-bridge/src/test/java/sqlkit/bridge/SslPropertyMapperTest.java index 9025111b..627a9416 100644 --- a/jdbc-bridge/src/test/java/sqlkit/bridge/SslPropertyMapperTest.java +++ b/jdbc-bridge/src/test/java/sqlkit/bridge/SslPropertyMapperTest.java @@ -5,6 +5,7 @@ import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class SslPropertyMapperTest { @@ -35,6 +36,25 @@ void unknownDriversReceiveNoProperties() { assertTrue(apply("com.example.UnknownDriver", "require").isEmpty()); } + @Test + void cqlRequiredModesEnableEncryptionAndUseTheRequestedHostnameCheck() throws Exception { + String url = "jdbc:cassandra://localhost:9042/system?localdatacenter=datacenter1"; + assertTrue(SslPropertyMapper.requiresCqlTls("com.ing.data.cassandra.jdbc.CassandraDriver", "require")); + try (var require = SslPropertyMapper.cqlTlsSettings(url, "", null, "require", null, null, null); + var verify = SslPropertyMapper.cqlTlsSettings(url, "", null, "verify-full", null, null, null)) { + assertEquals("true", require.properties.getProperty("enableSsl")); + assertEquals("false", require.properties.getProperty("hostnameVerification")); + assertEquals("true", verify.properties.getProperty("enableSsl")); + assertEquals("true", verify.properties.getProperty("hostnameVerification")); + } + } + + @Test + void cqlPreferModeConnectsPlaintext() { + assertFalse(SslPropertyMapper.requiresCqlTls("com.ing.data.cassandra.jdbc.CassandraDriver", "prefer")); + assertTrue(apply("com.ing.data.cassandra.jdbc.CassandraDriver", "prefer").isEmpty()); + } + @Test void knownDriversKeepTheirSslProperties() { assertEquals("require", apply("org.postgresql.Driver", "require").getProperty("sslmode")); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 02c666b0..7a06b656 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -89,18 +89,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.4" @@ -286,7 +274,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -917,7 +905,7 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -1208,7 +1196,7 @@ dependencies = [ "bitflags 2.13.0", "core-foundation 0.10.1", "core-graphics-types", - "foreign-types 0.5.0", + "foreign-types", "libc", ] @@ -1553,8 +1541,8 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" [[package]] name = "data-studio-agent" -version = "0.2.0" -source = "git+https://github.com/geek-fun/data-studio-agent.git?tag=v0.2.0#fa67e809d810350ff0029b10069a6311ed81b0af" +version = "0.2.2" +source = "git+https://github.com/geek-fun/data-studio-agent.git?tag=v0.2.2#0da714f15a87ef1c5fb34d0abd8f641992cee196" dependencies = [ "async-openai", "async-trait", @@ -2232,15 +2220,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared 0.1.1", -] - [[package]] name = "foreign-types" version = "0.5.0" @@ -2248,7 +2227,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ "foreign-types-macros", - "foreign-types-shared 0.3.1", + "foreign-types-shared", ] [[package]] @@ -2262,12 +2241,6 @@ dependencies = [ "syn 2.0.118", ] -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "foreign-types-shared" version = "0.3.1" @@ -2828,7 +2801,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.8", + "ahash", ] [[package]] @@ -2836,9 +2809,6 @@ name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash 0.8.12", -] [[package]] name = "hashbrown" @@ -2856,14 +2826,17 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] [[package]] name = "hashlink" -version = "0.9.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "hashbrown 0.14.5", + "hashbrown 0.17.1", ] [[package]] @@ -3029,22 +3002,6 @@ dependencies = [ "webpki-roots 1.0.8", ] -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.20" @@ -3406,7 +3363,7 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link 0.2.1", ] @@ -3620,12 +3577,13 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" dependencies = [ "cc", "pkg-config", + "sqlcipher-src", "vcpkg", ] @@ -3856,7 +3814,7 @@ dependencies = [ "once_cell", "png 0.18.1", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -3932,23 +3890,6 @@ dependencies = [ "zstd", ] -[[package]] -name = "native-tls" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe 0.2.1", - "openssl-sys", - "schannel", - "security-framework 3.7.0", - "security-framework-sys", - "tempfile", -] - [[package]] name = "ndk" version = "0.9.0" @@ -4344,31 +4285,6 @@ dependencies = [ "pathdiff", ] -[[package]] -name = "openssl" -version = "0.10.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" -dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "foreign-types 0.3.2", - "libc", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - [[package]] name = "openssl-probe" version = "0.1.6" @@ -4381,18 +4297,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "openssl-sys" -version = "0.9.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - [[package]] name = "option-ext" version = "0.2.0" @@ -4446,7 +4350,7 @@ dependencies = [ "objc2-osa-kit", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4504,7 +4408,7 @@ dependencies = [ "log", "rand 0.10.1", "sha2 0.11.0", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "windows 0.62.2", "windows-strings 0.5.1", @@ -5109,7 +5013,7 @@ dependencies = [ "rustc-hash 2.1.2", "rustls 0.23.40", "socket2 0.6.4", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -5130,7 +5034,7 @@ dependencies = [ "rustls 0.23.40", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -5296,7 +5200,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5365,22 +5269,17 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", - "encoding_rs", "futures-core", "futures-util", - "h2", "http", "http-body", "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", - "mime", "mime_guess", - "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -5392,7 +5291,6 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", "tokio-rustls 0.26.4", "tokio-util", "tower", @@ -5557,11 +5455,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "rusqlite" -version = "0.32.1" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" dependencies = [ "bitflags 2.13.0", "chrono", @@ -5570,6 +5477,7 @@ dependencies = [ "hashlink", "libsqlite3-sys", "smallvec", + "sqlite-wasm-rs", ] [[package]] @@ -5647,7 +5555,7 @@ dependencies = [ "spki 0.8.0-rc.4", "ssh-encoding", "subtle", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "typenum", "universal-hash 0.6.1", @@ -6532,6 +6440,23 @@ dependencies = [ "der 0.8.0", ] +[[package]] +name = "sqlcipher-src" +version = "420.0.0+sqlcipher-4.20.0-sqlite-3.54.1-libtomcrypt-1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6b5280ed2593d07b2816ec531821c15c306903bcca224716f1fbcc2bbfedfe" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", + "sqlcipher-src", +] + [[package]] name = "sqlkit" version = "0.8.7" @@ -6750,6 +6675,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -6928,7 +6864,7 @@ dependencies = [ "tauri-runtime", "tauri-runtime-wry", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tray-icon", "url", @@ -6979,7 +6915,7 @@ dependencies = [ "sha2 0.10.9", "syn 2.0.118", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "url", "uuid", @@ -7030,7 +6966,7 @@ dependencies = [ "tauri", "tauri-plugin", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "url", "windows-registry", @@ -7051,7 +6987,7 @@ dependencies = [ "tauri", "tauri-plugin", "tauri-plugin-fs", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", ] @@ -7074,7 +7010,7 @@ dependencies = [ "tauri", "tauri-plugin", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml 1.1.2+spec-1.1.0", "url", ] @@ -7095,7 +7031,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "windows 0.61.3", "zbus", @@ -7116,7 +7052,7 @@ dependencies = [ "sys-locale", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -7139,7 +7075,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin-deep-link", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "windows-sys 0.60.2", @@ -7157,7 +7093,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] @@ -7187,7 +7123,7 @@ dependencies = [ "tauri", "tauri-plugin", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tokio", "url", @@ -7207,7 +7143,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -7228,7 +7164,7 @@ dependencies = [ "serde", "serde_json", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "webkit2gtk", "webview2-com", @@ -7291,7 +7227,7 @@ dependencies = [ "serde_json", "serde_with", "swift-rs", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml 1.1.2+spec-1.1.0", "url", "urlpattern", @@ -7350,11 +7286,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -7370,13 +7306,13 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -7537,16 +7473,6 @@ dependencies = [ "syn 2.0.118", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-postgres" version = "0.7.18" @@ -7849,7 +7775,7 @@ dependencies = [ "once_cell", "png 0.18.1", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -8370,7 +8296,7 @@ version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" dependencies = [ - "thiserror 2.0.18", + "thiserror 2.0.21", "windows 0.61.3", "windows-core 0.61.2", ] @@ -8986,7 +8912,7 @@ dependencies = [ "sha2 0.10.9", "soup3", "tao-macros", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "webkit2gtk", "webkit2gtk-sys", @@ -9270,7 +9196,7 @@ dependencies = [ "memchr", "pbkdf2 0.12.2", "sha1 0.10.6", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "xz2", "zeroize", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 0cd6530b..7a1cb517 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -61,7 +61,7 @@ tiberius = { version = "0.12", default-features = false, features = [ "rust_decimal" ] } tokio-util = { version = "0.7", features = [ "compat" ] } -rusqlite = { version = "0.32", default-features = false, features = [ "chrono" ] } +rusqlite = { version = "0.43", default-features = false, features = [ "chrono" ] } # C library bundling is selected by cargo features: # default → rusqlite/bundled (SQLite) # sqlcipher → rusqlite/bundled-sqlcipher (SQLCipher, encrypted SQLite) @@ -90,7 +90,7 @@ http = "1" log = "0.4" futures = "0.3" rand = "0.8" -data-studio-agent = { git = "https://github.com/geek-fun/data-studio-agent.git", tag = "v0.2.0" } +data-studio-agent = { git = "https://github.com/geek-fun/data-studio-agent.git", tag = "v0.2.2" } # Archive extraction (JRE downloads) flate2 = "1.0" diff --git a/src-tauri/src/capabilities/sql.rs b/src-tauri/src/capabilities/sql.rs index a1fdad80..00dcd4c2 100644 --- a/src-tauri/src/capabilities/sql.rs +++ b/src-tauri/src/capabilities/sql.rs @@ -497,7 +497,7 @@ impl CapabilityHandler for ExecuteQueryHandler { // Read-only guard: reject write/delete/ddl statements with actionable // guidance so agents migrate to the split write tools. - let db_type = crate::capabilities::sql_write::adapter_db_type(&adapter); + let db_type = crate::capabilities::sql_write::adapter_db_type(&adapter).await; crate::capabilities::sql_write::ensure_read_only(&db_type, sql)?; // Check connection quality and warn the AI agent about flaky connections diff --git a/src-tauri/src/capabilities/sql_write.rs b/src-tauri/src/capabilities/sql_write.rs index 0cec1d02..ab74758a 100644 --- a/src-tauri/src/capabilities/sql_write.rs +++ b/src-tauri/src/capabilities/sql_write.rs @@ -31,6 +31,9 @@ pub(crate) enum SqlKind { /// Classify a SQL statement by its top-level AST variant, using the dialect /// that matches the connection's database type. pub(crate) fn classify_sql(db_type: &str, sql: &str) -> Result { + if crate::database::config::DatabaseType::slug_is_cql(db_type) { + return Ok(classify_cql(sql)); + } let dialect: Box = match db_type.to_lowercase().as_str() { "postgres" | "postgresql" | "duckdb" | "cockroachdb" | "gbase8c" | "kingbasees" | "yashandb" | "xugudb" | "oceanbase" | "dameng" => Box::new(PostgreSqlDialect {}), @@ -49,6 +52,26 @@ pub(crate) fn classify_sql(db_type: &str, sql: &str) -> Result Ok(classify_statement(&stmt)) } +/// Classify exactly one statement as split by the CQL executor. +fn classify_cql(sql: &str) -> SqlKind { + let Ok(statements) = crate::database::cql::split_statements(sql) else { + return SqlKind::Other; + }; + let [statement] = statements.as_slice() else { + return SqlKind::Other; + }; + match crate::database::sql_classification::first_executable_keyword(statement) + .map(str::to_ascii_uppercase) + .as_deref() + { + Some("SELECT") => SqlKind::Read, + Some("INSERT" | "UPDATE") => SqlKind::Write, + Some("DELETE" | "TRUNCATE") => SqlKind::Delete, + Some("CREATE" | "ALTER" | "DROP") => SqlKind::Ddl, + _ => SqlKind::Other, + } +} + /// Merge kinds found in different parts of one statement. /// /// The most restrictive kind wins so a destructive statement never rides @@ -253,7 +276,7 @@ async fn run_classified( let sql = sql_from(args)?; let adapter = resolve_adapter(&conn_id).await?; - let db_type = adapter_db_type(&adapter); + let db_type = adapter_db_type(&adapter).await; let kind = classify_sql(&db_type, &sql)?; if !allowed.contains(&kind) { return Err(format!( @@ -279,14 +302,16 @@ async fn run_classified( serde_json::to_string(&result).map_err(|e| e.to_string()) } -pub(crate) fn adapter_db_type(adapter: &crate::state::ActiveConnection) -> String { +pub(crate) async fn adapter_db_type(adapter: &crate::state::ActiveConnection) -> String { match adapter { crate::state::ActiveConnection::Postgres(_) => "postgres".to_string(), crate::state::ActiveConnection::MySQL(_) => "mysql".to_string(), crate::state::ActiveConnection::SQLite(_) => "sqlite".to_string(), crate::state::ActiveConnection::SQLServer(_) => "sqlserver".to_string(), crate::state::ActiveConnection::ClickHouse(_) => "clickhouse".to_string(), - crate::state::ActiveConnection::JdbcBridge(_) => "generic".to_string(), + crate::state::ActiveConnection::JdbcBridge(adapter) => { + adapter.lock().await.config.db_type.slug() + } crate::state::ActiveConnection::HttpSql(_) => "generic".to_string(), crate::state::ActiveConnection::Rqlite(_) => "generic".to_string(), crate::state::ActiveConnection::Turso(_) => "generic".to_string(), @@ -399,6 +424,94 @@ pub(crate) fn register_write_tools(reg: &mut CapabilityRegistry) { mod tests { use super::*; + #[tokio::test] + async fn cql_dialect_does_not_change_while_the_adapter_is_busy() { + use crate::database::{ConnectionConfig, DatabaseType, JdbcBridgeAdapter}; + use crate::state::ActiveConnection; + use tokio::sync::Mutex; + + let config = ConnectionConfig::new(DatabaseType::ScyllaDB, "localhost", 9042, ""); + let adapter = Arc::new(Mutex::new(JdbcBridgeAdapter::new(config))); + let connection = ActiveConnection::JdbcBridge(adapter.clone()); + let busy = adapter.lock().await; + assert!( + tokio::time::timeout(std::time::Duration::ZERO, adapter_db_type(&connection)) + .await + .is_err() + ); + drop(busy); + assert_eq!(adapter_db_type(&connection).await, "scylladb"); + } + + #[test] + fn classifies_cql_without_a_sqlparser_dialect() { + assert_eq!( + classify_sql("cassandra", "SELECT * FROM ks.tbl WHERE id = 1").unwrap(), + SqlKind::Read + ); + assert_eq!( + classify_sql( + "scylladb", + "SELECT JSON * FROM ks.tbl PER PARTITION LIMIT 1" + ) + .unwrap(), + SqlKind::Read + ); + assert_eq!( + classify_sql("cassandra", " -- leading comment\n SELECT 1").unwrap(), + SqlKind::Read + ); + assert_eq!( + classify_sql("cassandra", "INSERT INTO ks.tbl (id) VALUES (1)").unwrap(), + SqlKind::Write + ); + assert_eq!( + classify_sql("Cassandra", "DELETE FROM ks.tbl WHERE id = 1").unwrap(), + SqlKind::Delete + ); + assert_eq!( + classify_sql("cassandra", "TRUNCATE ks.tbl").unwrap(), + SqlKind::Delete + ); + assert_eq!( + classify_sql("cassandra", "CREATE TABLE ks.t (id int PRIMARY KEY)").unwrap(), + SqlKind::Ddl + ); + assert_eq!( + classify_sql("cassandra", "DROP KEYSPACE ks").unwrap(), + SqlKind::Ddl + ); + assert_eq!(classify_sql("cassandra", "USE ks").unwrap(), SqlKind::Other); + } + + #[test] + fn cql_multi_statement_detection_ignores_literals_and_comments() { + assert_eq!( + classify_sql( + "cassandra", + "SELECT * FROM ks.t WHERE v = '-- note'; SELECT * FROM ks.t", + ) + .unwrap(), + SqlKind::Other + ); + assert_eq!( + classify_sql("cassandra", "SELECT * FROM ks.t WHERE v = 'a;b'").unwrap(), + SqlKind::Read + ); + assert_eq!( + classify_sql("cassandra", "SELECT * FROM ks.t; -- trailing").unwrap(), + SqlKind::Read + ); + assert_eq!( + classify_sql("cassandra", "SELECT 1; DROP KEYSPACE ks").unwrap(), + SqlKind::Other + ); + assert_eq!( + classify_sql("cassandra", "SELECT 'it''s; fine' FROM ks.t").unwrap(), + SqlKind::Read + ); + } + #[test] fn classifies_select_as_read() { assert_eq!( diff --git a/src-tauri/src/commands/browse.rs b/src-tauri/src/commands/browse.rs index 62b83215..d8386baa 100644 --- a/src-tauri/src/commands/browse.rs +++ b/src-tauri/src/commands/browse.rs @@ -107,6 +107,10 @@ fn build_paginated_select( .unwrap_or_default(); match db_type { + "cql" => format!( + "SELECT * FROM {qualified_table}{where_clause} LIMIT {}", + limit.max(1) + ), "sqlserver" => format!( "SELECT * FROM {}{} ORDER BY (SELECT NULL) OFFSET {} ROWS FETCH NEXT {} ROWS ONLY", qualified_table, where_clause, offset, limit @@ -363,6 +367,25 @@ async fn get_table_data_inner( offset_val: u32, db_type: &str, ) -> DbResult { + if let ActiveConnection::JdbcBridge(adapter) = connection { + let adapter = adapter.lock().await; + if adapter.config.db_type.is_cql() { + if offset_val != 0 { + return Err(crate::database::error::DbError::UnsupportedOperation( + "CQL does not support row offsets. Use a filtered query to browse more rows." + .into(), + )); + } + let keyspace = query + .schema + .as_deref() + .or(query.database.as_deref()) + .unwrap_or_else(|| adapter.config.cql_keyspace()); + let qualified = build_qualified_table(Some(keyspace), &query.table, db_type); + let sql = build_paginated_select(&qualified, filter_ref, limit_val, 0, "cql"); + return adapter.execute_query(&sql).await; + } + } let qualified = build_qualified_table(query.schema.as_deref(), &query.table, db_type); let sql = build_paginated_select(&qualified, filter_ref, limit_val, offset_val, db_type); @@ -451,6 +474,18 @@ async fn get_table_count_inner( filter_ref: Option<&str>, db_type: &str, ) -> DbResult { + if let ActiveConnection::JdbcBridge(adapter) = connection { + let adapter = adapter.lock().await; + if adapter.config.db_type.is_cql() { + let keyspace = schema + .or(database) + .unwrap_or_else(|| adapter.config.cql_keyspace()); + let qualified = build_qualified_table(Some(keyspace), table, db_type); + return adapter + .execute_query(&build_count_query(&qualified, filter_ref)) + .await; + } + } let qualified = build_qualified_table(schema, table, db_type); let query = build_count_query(&qualified, filter_ref); @@ -522,6 +557,24 @@ fn build_pk_where(pk_values: &HashMap, db_type: &str) -> Stri .join(" AND ") } +async fn cql_mutation_keyspace<'a>( + connection: &ActiveConnection, + schema: Option<&'a str>, + database: Option<&'a str>, +) -> Result, String> { + if let ActiveConnection::JdbcBridge(adapter) = connection { + let adapter = adapter.lock().await; + if adapter.config.db_type.is_cql() { + return schema + .filter(|name| !name.is_empty()) + .or(database.filter(|name| !name.is_empty())) + .map(Some) + .ok_or_else(|| "A target keyspace is required for CQL row changes".to_string()); + } + } + Ok(None) +} + /// Update a single row in a table identified by its primary key values. /// /// # Arguments @@ -549,12 +602,17 @@ pub async fn update_table_row( let connection = state.ensure_connection(&connection_id).await?; let db_type = get_db_type_string(&connection); + let cql_keyspace = + cql_mutation_keyspace(&connection, schema.as_deref(), database.as_deref()).await?; + if cql_keyspace.is_some() && updates.keys().any(|column| pk_values.contains_key(column)) { + return Err("CQL primary-key columns cannot be updated".to_string()); + } let build_update_sql = |db_type: &str| -> Result { if pk_values.is_empty() { return Err("Cannot update row: no primary key values provided".to_string()); } - let qualified = build_qualified_table(schema.as_deref(), &table, db_type); + let qualified = build_qualified_table(cql_keyspace.or(schema.as_deref()), &table, db_type); let set_clause = updates .iter() .map(|(col, val)| { @@ -681,9 +739,11 @@ pub async fn delete_table_row( let connection = state.ensure_connection(&connection_id).await?; let db_type = get_db_type_string(&connection); + let cql_keyspace = + cql_mutation_keyspace(&connection, schema.as_deref(), database.as_deref()).await?; let build_delete_sql = |db_type: &str| -> String { - let qualified = build_qualified_table(schema.as_deref(), &table, db_type); + let qualified = build_qualified_table(cql_keyspace.or(schema.as_deref()), &table, db_type); let where_clause = build_pk_where(&pk_values, db_type); format!("DELETE FROM {} WHERE {}", qualified, where_clause) }; @@ -1135,6 +1195,39 @@ mod tests { assert!(query_with_filter.contains("OFFSET 5")); } + #[test] + fn cql_preview_uses_a_limit_without_an_offset() { + let qualified = build_qualified_table(Some("events_keyspace"), "events", "jdbc"); + assert_eq!( + build_paginated_select(&qualified, Some("id = 7"), 100, 0, "cql"), + "SELECT * FROM \"events_keyspace\".\"events\" WHERE id = 7 LIMIT 100" + ); + } + + #[tokio::test] + async fn cql_row_changes_require_the_selected_keyspace() { + let config = crate::database::ConnectionConfig::new( + crate::database::DatabaseType::Cassandra, + "localhost", + 9042, + "", + ) + .with_database("default_keyspace"); + let connection = ActiveConnection::JdbcBridge(std::sync::Arc::new( + tokio::sync::Mutex::new(JdbcBridgeAdapter::new(config)), + )); + let target = cql_mutation_keyspace(&connection, None, Some("CaseReview")) + .await + .unwrap(); + assert_eq!( + build_qualified_table(target, "events", "jdbc"), + "\"CaseReview\".\"events\"" + ); + assert!(cql_mutation_keyspace(&connection, None, None) + .await + .is_err()); + } + #[test] fn test_build_count_query() { let query = build_count_query("\"table\"", None); diff --git a/src-tauri/src/commands/helpers.rs b/src-tauri/src/commands/helpers.rs index be66e6f9..795f7452 100644 --- a/src-tauri/src/commands/helpers.rs +++ b/src-tauri/src/commands/helpers.rs @@ -213,6 +213,7 @@ fn db_type_to_enum(db_type: &str) -> Result Ok(DatabaseType::Informix), "kylin" => Ok(DatabaseType::Kylin), "cassandra" => Ok(DatabaseType::Cassandra), + "scylladb" => Ok(DatabaseType::ScyllaDB), "iris" | "intersystems_iris" => Ok(DatabaseType::Iris), "access" | "ms_access" | "microsoft_access" => Ok(DatabaseType::Access), _ => Err(format!("Unsupported database type: {}", db_type)), diff --git a/src-tauri/src/commands/jdbc.rs b/src-tauri/src/commands/jdbc.rs index 3d294600..0512b291 100644 --- a/src-tauri/src/commands/jdbc.rs +++ b/src-tauri/src/commands/jdbc.rs @@ -193,6 +193,7 @@ fn parse_db_type(s: &str) -> Result { "informix" => Ok(DatabaseType::Informix), "kylin" => Ok(DatabaseType::Kylin), "cassandra" => Ok(DatabaseType::Cassandra), + "scylladb" => Ok(DatabaseType::ScyllaDB), "iris" => Ok(DatabaseType::Iris), "access" => Ok(DatabaseType::Access), "tdengine" | "td" => Ok(DatabaseType::TDengine), diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rs index da60022c..2b70aff3 100644 --- a/src-tauri/src/commands/query.rs +++ b/src-tauri/src/commands/query.rs @@ -322,7 +322,10 @@ pub async fn execute_sorted_query( // Derive database type from the active connection let db_type = { let connection = state.ensure_connection(&connection_id).await?; - crate::commands::browse::get_db_type_string(&connection).to_string() + match &connection { + ActiveConnection::JdbcBridge(adapter) => adapter.lock().await.config.db_type.slug(), + _ => crate::commands::browse::get_db_type_string(&connection).to_string(), + } }; // Inject the database type into options and build the wrapped SQL diff --git a/src-tauri/src/database/config.rs b/src-tauri/src/database/config.rs index 8737b57b..2d65ec7d 100644 --- a/src-tauri/src/database/config.rs +++ b/src-tauri/src/database/config.rs @@ -137,6 +137,8 @@ pub enum DatabaseType { Kylin, /// Apache Cassandra — JDBC bridge. Cassandra, + /// ScyllaDB — CQL-compatible wide-column store, JDBC bridge. + ScyllaDB, /// InterSystems IRIS — JDBC bridge. Iris, /// Microsoft Access — JDBC bridge. @@ -160,6 +162,27 @@ pub enum DatabaseType { } impl DatabaseType { + pub(crate) fn is_cql(self) -> bool { + matches!(self, Self::Cassandra | Self::ScyllaDB) + } + + /// Whether a backend slug (`db_type` string as used by the SQL services + /// and MCP tools) identifies a CQL engine. Case-insensitive on purpose: + /// the slug arrives from several layers with mixed casing. + pub(crate) fn slug_is_cql(slug: &str) -> bool { + matches!(slug.to_lowercase().as_str(), "cassandra" | "scylladb") + } + + /// The backend slug for this type — the same `db_type` string the SQL + /// services key their dialect lookups on (matches the serde lowercase + /// representation the frontend persists). + pub(crate) fn slug(self) -> String { + serde_json::to_value(self) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_else(|| "generic".to_string()) + } + /// Whether this connection type has an SSL/TLS concept at all. /// /// Embedded / file-based engines mirror the frontend @@ -344,10 +367,45 @@ impl ConnectionConfig { /// Set the database name. pub fn with_database(mut self, database: impl Into) -> Self { - self.database = Some(database.into()); + let database = database.into(); + if self.db_type.is_cql() { + // Older connection records store the datacenter in the database value. + let (keyspace, params) = database.split_once('?').unwrap_or((&database, "")); + if let Some((_, dc)) = url::form_urlencoded::parse(params.as_bytes()) + .find(|(name, _)| name.eq_ignore_ascii_case("localdatacenter")) + { + self.options + .insert("localdatacenter".into(), dc.into_owned()); + } + let keyspace = keyspace.trim(); + self.database = Some( + keyspace + .strip_prefix('"') + .and_then(|name| name.strip_suffix('"')) + .unwrap_or(keyspace) + .to_string(), + ); + } else { + self.database = Some(database); + } self } + pub(crate) fn cql_keyspace(&self) -> &str { + self.database + .as_deref() + .filter(|name| !name.is_empty()) + .unwrap_or("system") + } + + pub(crate) fn cql_datacenter(&self) -> &str { + self.options + .get("localdatacenter") + .map(|dc| dc.trim()) + .filter(|dc| !dc.is_empty()) + .unwrap_or("datacenter1") + } + /// Set the password. pub fn with_password(mut self, password: impl Into) -> Self { self.password = Some(password.into()); diff --git a/src-tauri/src/database/cql.rs b/src-tauri/src/database/cql.rs new file mode 100644 index 00000000..10ff0053 --- /dev/null +++ b/src-tauri/src/database/cql.rs @@ -0,0 +1,118 @@ +/// Split CQL into the same statements used for authorization and JDBC execution. +pub(crate) fn split_statements(script: &str) -> Result, &'static str> { + let bytes = script.as_bytes(); + let mut statements = Vec::new(); + let mut start = None; + let mut end = 0; + let mut in_batch = false; + let mut after_apply = false; + let mut i = 0; + while let Some(&byte) = bytes.get(i) { + let remaining = &bytes[i..]; + if byte.is_ascii_whitespace() { + i += 1; + continue; + } + if remaining.starts_with(b"--") || remaining.starts_with(b"//") { + while i < bytes.len() && !matches!(bytes[i], b'\n' | b'\r') { + i += 1; + } + continue; + } + if remaining.starts_with(b"/*") { + i = scan_delimited(script, i + 2, "*/")?; + continue; + } + if byte == b';' && !in_batch { + if let Some(start) = start.take() { + statements.push(&script[start..end]); + } + i += 1; + continue; + } + + let first_token = start.is_none(); + start.get_or_insert(i); + if matches!(byte, b'\'' | b'"') { + i = scan_quoted(bytes, i, byte)?; + after_apply = false; + } else if remaining.starts_with(b"$$") { + i = scan_delimited(script, i + 2, "$$")?; + after_apply = false; + } else if byte.is_ascii_alphanumeric() || byte == b'_' { + let word_start = i; + while bytes + .get(i) + .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_') + { + i += 1; + } + let word = &script[word_start..i]; + if first_token && word.eq_ignore_ascii_case("BEGIN") { + in_batch = true; + } else if in_batch && after_apply && word.eq_ignore_ascii_case("BATCH") { + in_batch = false; + } + after_apply = in_batch && word.eq_ignore_ascii_case("APPLY"); + } else { + i += 1; + after_apply = false; + } + end = i; + } + if in_batch { + return Err("CQL batch is missing APPLY BATCH"); + } + if let Some(start) = start { + statements.push(&script[start..end]); + } + Ok(statements) +} + +fn scan_delimited(script: &str, start: usize, delimiter: &str) -> Result { + script[start..] + .find(delimiter) + .map(|offset| start + offset + delimiter.len()) + .ok_or("Unterminated CQL comment or dollar-quoted literal") +} + +fn scan_quoted(bytes: &[u8], start: usize, quote: u8) -> Result { + let mut i = start + 1; + while let Some(&byte) = bytes.get(i) { + i += 1; + if byte == quote { + if bytes.get(i) != Some("e) { + return Ok(i); + } + i += 1; + } + } + Err("Unterminated CQL quoted identifier or literal") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cql_preserves_batches_and_splits_following_statements() { + let batch = "BEGIN UNLOGGED BATCH\n INSERT INTO events (id) VALUES (1);\n INSERT INTO events (id) VALUES (2);\n APPLY /* end */ BATCH"; + let script = format!("// header\r\n{batch}; -- end\nSELECT * FROM events;"); + assert_eq!( + split_statements(&script), + Ok(vec![batch, "SELECT * FROM events"]) + ); + assert!(split_statements("BEGIN BATCH INSERT INTO events (id) VALUES (1);").is_err()); + } + + #[test] + fn cql_ignores_quoted_separators_and_preserves_internal_comments() { + let select = + "SELECT \"part;name\" FROM events WHERE value = $$a;b$$ /* note */ ALLOW FILTERING"; + assert_eq!( + split_statements(&format!("{select}; // tail")), + Ok(vec![select]) + ); + assert!(split_statements("SELECT * FROM events /* unfinished").is_err()); + } +} diff --git a/src-tauri/src/database/jdbc_bridge/adapter.rs b/src-tauri/src/database/jdbc_bridge/adapter.rs index d09db5f9..122c7edd 100644 --- a/src-tauri/src/database/jdbc_bridge/adapter.rs +++ b/src-tauri/src/database/jdbc_bridge/adapter.rs @@ -2,7 +2,7 @@ use crate::database::{ adapter::DatabaseAdapter, - config::ConnectionConfig, + config::{ConnectionConfig, DatabaseType}, error::{DbError, DbResult}, types::{ ColumnInfo, ConnectionStatus, DatabaseSchema, ForeignKeyInfo, IndexInfo, ObjectInfo, @@ -38,11 +38,42 @@ impl JdbcBridgeAdapter { } } + fn fold_catalog_into_schema<'a>( + &self, + database: Option<&'a str>, + schema: Option<&'a str>, + ) -> (Option<&'a str>, Option<&'a str>) { + if self.config.db_type.is_cql() { + (None, schema.or(database)) + } else { + (database, schema) + } + } + + /// Run a CQL query and return its rows, bypassing `DatabaseMetaData` for + /// introspection (see `list_tables` / `list_columns`). + async fn cql_rows(&self, sql: &str) -> DbResult> { + let launcher = self.launcher()?; + let data = Self::send_request( + launcher, + JdbcRequest::new( + JdbcMethod::ExecuteQuery, + serde_json::json!({ + "conn_id": self.conn_id, + "sql": sql, + }), + ), + ) + .await?; + Ok(Self::parse_query_result(data)?.rows) + } + /// Ensure all prerequisites are met: JRE, bridge JAR, and JDBC driver. /// Uses the fallback chain to try multiple driver versions automatically. async fn init_bridge(&mut self) -> DbResult>> { let db_type = self.config.db_type; let ssl_mode_str = match self.config.ssl_mode { + crate::database::config::SslMode::Prefer if db_type.is_cql() => "disable", crate::database::config::SslMode::Disable => "disable", crate::database::config::SslMode::Prefer => "prefer", crate::database::config::SslMode::Require => "require", @@ -61,11 +92,27 @@ impl JdbcBridgeAdapter { // Use fallback chain for JDBC-dependent databases (Oracle, DB2, H2, etc.) // For non-registry types, fall back to the old single-driver approach + let database = if db_type.is_cql() { + let keyspace = self.config.cql_keyspace(); + if !keyspace.starts_with(|c: char| c.is_ascii_alphabetic()) + || !keyspace + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'_') + { + return Err(DbError::Connection(format!( + "Invalid CQL keyspace: {keyspace}" + ))); + } + Some(keyspace) + } else { + self.config.database.as_deref() + }; let (_version, conn_id, launcher) = super::fallback::run_fallback_chain( db_type, &self.config.host, self.config.port, - self.config.database.as_deref(), + database, + db_type.is_cql().then(|| self.config.cql_datacenter()), &self.config.username, &self.config.password, self.config.oracle_options.as_ref(), @@ -160,6 +207,7 @@ impl JdbcBridgeAdapter { schema: Option<&str>, table: Option<&str>, ) -> DbResult { + let (database, schema) = self.fold_catalog_into_schema(database, schema); let launcher = self.launcher()?; let data = Self::send_request( launcher, @@ -219,15 +267,37 @@ impl DatabaseAdapter for JdbcBridgeAdapter { ), ) .await?; - Self::parse_connection_status(data) + let mut status = Self::parse_connection_status(data)?; + if self.config.db_type.is_cql() { + if self.config.db_type == DatabaseType::Cassandra + && status + .server_version + .as_deref() + .and_then(|version| version.split('.').next()) + .and_then(|major| major.parse::().ok()) + .is_some_and(|major| major < 3) + { + return Err(DbError::UnsupportedOperation( + "Cassandra 3.0 or later is required for keyspace and table browsing.".into(), + )); + } + // JDBC getCatalog() exposes the cluster name for the CQL wrapper. + status.current_database = Some(self.config.cql_keyspace().to_string()); + } + Ok(status) } async fn execute_query(&self, query: &str) -> DbResult { let launcher = self.launcher()?; - let statements = split_sql_statements_for_dialect( - query, - self.config.db_type == super::super::DatabaseType::Oracle, - ); + let statements = if self.config.db_type.is_cql() { + crate::database::cql::split_statements(query) + .map_err(|error| DbError::InvalidQuery(error.into()))? + .into_iter() + .map(str::to_owned) + .collect() + } else { + split_sql_statements_for_dialect(query, self.config.db_type == DatabaseType::Oracle) + }; if statements.is_empty() { return Ok(QueryResult { columns: Vec::new(), @@ -291,6 +361,22 @@ impl DatabaseAdapter for JdbcBridgeAdapter { } async fn list_databases(&self) -> DbResult> { + if self.config.db_type.is_cql() { + // The wrapper's catalog listing reports the cluster name, not + // keyspaces — read them from system_schema instead. + return Ok(self + .cql_rows("SELECT keyspace_name FROM system_schema.keyspaces") + .await? + .iter() + .filter_map(|row| row.get("keyspace_name").and_then(|v| v.as_string())) + .map(|name| DatabaseSchema { + is_system: name.starts_with("system"), + name, + description: None, + metadata: HashMap::new(), + }) + .collect()); + } let launcher = self.launcher()?; let data = Self::send_request( launcher, @@ -316,6 +402,12 @@ impl DatabaseAdapter for JdbcBridgeAdapter { } async fn list_schemas(&self, database: Option<&str>) -> DbResult> { + let (database, schema) = if self.config.db_type.is_cql() { + // The wrapper reports keyspaces as schemas — carry the database there. + (None, database) + } else { + (database, None) + }; let launcher = self.launcher()?; let data = Self::send_request( launcher, @@ -324,6 +416,7 @@ impl DatabaseAdapter for JdbcBridgeAdapter { serde_json::json!({ "conn_id": self.conn_id, "database": database, + "schema": schema, }), ), ) @@ -337,6 +430,42 @@ impl DatabaseAdapter for JdbcBridgeAdapter { database: Option<&str>, schema: Option<&str>, ) -> DbResult> { + if self.config.db_type.is_cql() { + // The wrapper's DatabaseMetaData only reports objects of the + // keyspace bound at connect time and ignores the catalog/schema + // arguments — so browsing a keyspace picked later in the UI would + // come back empty. Read system_schema directly instead, which also + // keeps working when the session keyspace is `system`. + let keyspace = schema.or(database); + let sql = match keyspace { + Some(ks) => format!( + "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '{}'", + ks.replace('\'', "''") + ), + None => "SELECT keyspace_name, table_name FROM system_schema.tables".to_string(), + }; + let rows = self.cql_rows(&sql).await?; + return Ok(rows + .iter() + .filter_map(|row| { + let table = row.get("table_name")?.as_string()?; + let ks = row + .get("keyspace_name") + .and_then(|v| v.as_string()) + .or_else(|| keyspace.map(|k| k.to_string())); + Some(TableInfo { + schema: ks, + name: table, + table_type: "TABLE".to_string(), + row_count: None, + size_bytes: None, + description: None, + metadata: HashMap::new(), + }) + }) + .collect()); + } + let (database, schema) = self.fold_catalog_into_schema(database, schema); let launcher = self.launcher()?; let data = Self::send_request( launcher, @@ -378,6 +507,59 @@ impl DatabaseAdapter for JdbcBridgeAdapter { schema: Option<&str>, table: &str, ) -> DbResult> { + if self.config.db_type.is_cql() { + // Same session-keyspace limitation as list_tables: read the column + // definitions (and primary-key flags) from system_schema. + let keyspace = schema + .or(database) + .unwrap_or_else(|| self.config.cql_keyspace()); + let sql = format!( + "SELECT column_name, kind, position, type FROM system_schema.columns \ + WHERE keyspace_name = '{}' AND table_name = '{}'", + keyspace.replace('\'', "''"), + table.replace('\'', "''") + ); + let mut cols: Vec<(String, bool, String)> = self + .cql_rows(&sql) + .await? + .iter() + .filter_map(|row| { + let name = row.get("column_name").and_then(|v| v.as_string())?; + let kind = row + .get("kind") + .and_then(|v| v.as_string()) + .unwrap_or_default(); + let ty = row + .get("type") + .and_then(|v| v.as_string()) + .unwrap_or_default(); + Some(( + name, + kind.contains("partition_key") || kind.contains("clustering"), + ty, + )) + }) + .collect(); + // Primary-key columns first, then the rest, mirroring CQL's layout. + cols.sort_by_key(|(_, is_pk, _)| !*is_pk); + return Ok(cols + .into_iter() + .map(|(name, is_primary_key, data_type)| ColumnInfo { + name, + data_type, + nullable: !is_primary_key, + default_value: None, + is_primary_key, + is_auto_increment: false, + max_length: None, + precision: None, + scale: None, + description: None, + metadata: HashMap::new(), + }) + .collect()); + } + let (database, schema) = self.fold_catalog_into_schema(database, schema); let launcher = self.launcher()?; let data = Self::send_request( launcher, @@ -449,6 +631,9 @@ impl DatabaseAdapter for JdbcBridgeAdapter { database: Option<&str>, schema: Option<&str>, ) -> DbResult> { + if self.config.db_type.is_cql() { + return Ok(Vec::new()); + } self.send_list_request(JdbcMethod::ListViews, database, schema, None) .await } @@ -497,6 +682,9 @@ impl DatabaseAdapter for JdbcBridgeAdapter { schema: Option<&str>, table: &str, ) -> DbResult> { + if self.config.db_type.is_cql() { + return Ok(Vec::new()); + } self.send_list_request(JdbcMethod::ListForeignKeys, database, schema, Some(table)) .await } @@ -506,6 +694,9 @@ impl DatabaseAdapter for JdbcBridgeAdapter { database: Option<&str>, schema: Option<&str>, ) -> DbResult> { + if self.config.db_type.is_cql() { + return Ok(Vec::new()); + } self.send_list_request(JdbcMethod::GetForeignKeys, database, schema, None) .await } @@ -776,6 +967,49 @@ fn split_sql_statements_for_dialect(sql: &str, oracle: bool) -> Vec { mod tests { use super::*; + #[tokio::test] + #[ignore = "Requires a disposable Cassandra server and the current JDBC bridge JAR"] + async fn cql_bridge_opens_exact_keyspace_and_executes_an_intact_batch() { + let port = std::env::var("SQLKIT_CQL_TEST_PORT") + .expect("set SQLKIT_CQL_TEST_PORT to the disposable server's local port") + .parse() + .expect("valid Cassandra port"); + let config = ConnectionConfig::new(DatabaseType::Cassandra, "127.0.0.1", port, "") + .with_ssl_mode(crate::database::SslMode::Disable); + let mut admin = JdbcBridgeAdapter::new(config.clone()); + admin.connect().await.unwrap(); + let keyspace = format!("CqlTest{}", uuid::Uuid::new_v4().simple()); + let quoted = format!("\"{keyspace}\""); + admin + .execute_query(&format!( + "CREATE KEYSPACE {quoted} WITH replication = \ + {{'class': 'SimpleStrategy', 'replication_factor': 1}}" + )) + .await + .unwrap(); + let mut scoped = JdbcBridgeAdapter::new(config.with_database("ed)); + let rows = async { + scoped.connect().await?; + scoped + .execute_query( + "CREATE TABLE events (id int PRIMARY KEY); \ + BEGIN UNLOGGED BATCH \ + INSERT INTO events (id) VALUES (1); \ + INSERT INTO events (id) VALUES (2); \ + APPLY BATCH; SELECT * FROM events", + ) + .await + } + .await; + scoped.disconnect().await.unwrap(); + admin + .execute_query(&format!("DROP KEYSPACE {quoted}")) + .await + .unwrap(); + admin.disconnect().await.unwrap(); + assert_eq!(rows.unwrap().rows.len(), 2); + } + #[test] fn comments_preserve_token_boundaries() { assert_eq!( diff --git a/src-tauri/src/database/jdbc_bridge/download.rs b/src-tauri/src/database/jdbc_bridge/download.rs index 4ade2a69..2bf23584 100644 --- a/src-tauri/src/database/jdbc_bridge/download.rs +++ b/src-tauri/src/database/jdbc_bridge/download.rs @@ -321,9 +321,17 @@ pub async fn download_jdbc_driver_direct(db_type: &str) -> DbResult<()> { return Ok(()); } - // Drivers with a direct download URL (non-Maven, e.g. GBase 8a) + // Drivers with a direct download URL (non-Maven, e.g. GBase 8a or the + // Cassandra wrapper bundle). Name the cached file the way the Java + // resolver does (`{artifact}-{version}.jar`, version = cap ?? "1.0.0") so + // the pre-flight download satisfies both the pinned-cache lookup and the + // bridge's own ResolveDriver short-circuit instead of re-downloading. if let Some(download_url) = &config.download_url { - let jar_name = config.maven_artifact.clone() + ".jar"; + let version = config + .version_cap + .clone() + .unwrap_or_else(|| "1.0.0".to_string()); + let jar_name = format!("{}-{}.jar", config.maven_artifact, version); let dest = dest_dir.join(&jar_name); if dest.exists() { return Ok(()); diff --git a/src-tauri/src/database/jdbc_bridge/drivers.toml b/src-tauri/src/database/jdbc_bridge/drivers.toml index 6899efa6..d4220922 100644 --- a/src-tauri/src/database/jdbc_bridge/drivers.toml +++ b/src-tauri/src/database/jdbc_bridge/drivers.toml @@ -304,13 +304,39 @@ min_jre_version = "11" version_error_signatures = [ "driver version not compatible", ] # ── Apache Cassandra ── +# +# Uses ING's open-source Cassandra JDBC wrapper (Apache 2.0), which wraps the +# Cassandra java-driver 4.x and speaks plain `jdbc:cassandra://` URLs. +# Maven Central only hosts the thin JAR, so we download the pre-shaded +# "bundle" JAR (all deps included) from the wrapper's GitHub releases — +# same direct-download flow as GBase 8a. SQLKit uses system_schema for +# metadata and supports Cassandra 3.0 and later and ScyllaDB. [databases.cassandra] name = "Apache Cassandra" -class_name = "com.simba.cassandra.jdbc.Driver" -maven_group = "com.simba" -maven_artifact = "cassandra-jdbc" -jdbc_url_template = "jdbc:cassandra://{host}:{port}/{database}" +class_name = "com.ing.data.cassandra.jdbc.CassandraDriver" +maven_group = "com.ing.data" +maven_artifact = "cassandra-jdbc-wrapper" +version_cap = "4.16.7" +download_url = "https://github.com/ing-bank/cassandra-jdbc-wrapper/releases/download/v4.16.7/cassandra-jdbc-wrapper-4.16.7-bundle.jar" +jdbc_url_template = "jdbc:cassandra://{host}:{port}{database}" +default_port = 9042 +min_jre_version = "11" +version_error_signatures = [ "driver version not compatible", ] + +# ── ScyllaDB ── +# +# CQL-compatible wide-column store; shares the Cassandra wrapper bundle, +# cache dir and JDBC URL scheme above. + +[databases.scylladb] +name = "ScyllaDB" +class_name = "com.ing.data.cassandra.jdbc.CassandraDriver" +maven_group = "com.ing.data" +maven_artifact = "cassandra-jdbc-wrapper" +version_cap = "4.16.7" +download_url = "https://github.com/ing-bank/cassandra-jdbc-wrapper/releases/download/v4.16.7/cassandra-jdbc-wrapper-4.16.7-bundle.jar" +jdbc_url_template = "jdbc:cassandra://{host}:{port}{database}" default_port = 9042 min_jre_version = "11" version_error_signatures = [ "driver version not compatible", ] diff --git a/src-tauri/src/database/jdbc_bridge/fallback.rs b/src-tauri/src/database/jdbc_bridge/fallback.rs index cf3306b8..fb060379 100644 --- a/src-tauri/src/database/jdbc_bridge/fallback.rs +++ b/src-tauri/src/database/jdbc_bridge/fallback.rs @@ -105,6 +105,7 @@ pub async fn try_driver( host: &str, port: u16, database: Option<&str>, + cql_datacenter: Option<&str>, username: &str, password: &Option, use_cap: bool, @@ -115,7 +116,15 @@ pub async fn try_driver( ssl_client_key: Option<&str>, trust_server_certificate: bool, ) -> DriverAttempt { - let url = build_oracle_url(config, host, port, database, oracle_options); + let url = if let Some(dc) = cql_datacenter { + // The wrapper decodes the URI query and then decodes each parameter. + let encoded = url::form_urlencoded::byte_serialize(dc.as_bytes()).collect::(); + let encoded = url::form_urlencoded::byte_serialize(encoded.as_bytes()).collect::(); + let query = format!("?localdatacenter={encoded}"); + super::registry::build_jdbc_url(config, host, port, Some(&query)) + } else { + build_oracle_url(config, host, port, database, oracle_options) + }; // Reuse the app-wide bridge process: a fresh JVM would re-map DuckDB's // ~107 MB native library (~1.4 s) on every single connection attempt. @@ -162,7 +171,10 @@ pub async fn try_driver( // On the first attempt, try without version_cap (LATEST). // If the config has no cap, or we're explicitly using it, send the cap. - let effective_cap = if use_cap { + // Direct-download drivers are version-pinned by definition: always send + // the cap so the Java resolver names the cached JAR deterministically + // (a null cap would name it "-1.0.0.jar" and duplicate the download). + let effective_cap = if use_cap || config.download_url.is_some() { config.version_cap.as_deref() } else { None @@ -283,7 +295,14 @@ async fn connect_with_jar( } }; - let req = JdbcRequest::new(JdbcMethod::Connect, params); + // The bridge must honor the separately supplied keyspace and TLS mode. + let cql = db_type_from_config(config).is_cql(); + let method = if cql { + JdbcMethod::ConnectCql + } else { + JdbcMethod::Connect + }; + let req = JdbcRequest::new(method, params); // 30s timeout per attempt let conn_result = tokio::time::timeout(std::time::Duration::from_secs(30), async { @@ -295,6 +314,11 @@ async fn connect_with_jar( match conn_result { Ok(Ok(resp)) => { if let Some(ref err) = resp.error { + if cql && err.starts_with("Unknown method") { + return DriverAttempt::Fatal(DbError::Connection( + "The installed JDBC bridge does not support the Cassandra and ScyllaDB connection protocol. Update the bridge in Settings → JRE & Drivers.".into(), + )); + } let category = classify_connection_error( db_type_from_config(config), err, @@ -356,6 +380,7 @@ pub async fn run_fallback_chain( host: &str, port: u16, database: Option<&str>, + cql_datacenter: Option<&str>, username: &str, password: &Option, oracle_options: Option<&OracleConnectionOptions>, @@ -429,6 +454,7 @@ pub async fn run_fallback_chain( host, port, database, + cql_datacenter, username, password, false, @@ -462,6 +488,7 @@ pub async fn run_fallback_chain( host, port, database, + cql_datacenter, username, password, true, @@ -489,7 +516,6 @@ pub async fn run_fallback_chain( } } - fn db_type_from_config(config: &DatabaseDriverConfig) -> DatabaseType { match config.name.as_str() { "Oracle Database" => DatabaseType::Oracle, @@ -510,6 +536,7 @@ fn db_type_from_config(config: &DatabaseDriverConfig) -> DatabaseType { "IBM Informix" => DatabaseType::Informix, "Apache Kylin" => DatabaseType::Kylin, "Apache Cassandra" => DatabaseType::Cassandra, + "ScyllaDB" => DatabaseType::ScyllaDB, "InterSystems IRIS" => DatabaseType::Iris, "Microsoft Access" => DatabaseType::Access, _ => DatabaseType::PostgreSQL, // fallback, shouldn't happen diff --git a/src-tauri/src/database/jdbc_bridge/protocol.rs b/src-tauri/src/database/jdbc_bridge/protocol.rs index 71520679..8824311c 100644 --- a/src-tauri/src/database/jdbc_bridge/protocol.rs +++ b/src-tauri/src/database/jdbc_bridge/protocol.rs @@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize}; #[serde(rename_all = "snake_case")] pub enum JdbcMethod { Connect, + ConnectCql, Disconnect, ExecuteQuery, ListDatabases, diff --git a/src-tauri/src/database/jdbc_bridge/registry.rs b/src-tauri/src/database/jdbc_bridge/registry.rs index 8928b459..568e9a76 100644 --- a/src-tauri/src/database/jdbc_bridge/registry.rs +++ b/src-tauri/src/database/jdbc_bridge/registry.rs @@ -200,6 +200,7 @@ fn db_type_to_registry_key(db: DatabaseType) -> Option<&'static str> { DatabaseType::Informix => Some("informix"), DatabaseType::Kylin => Some("kylin"), DatabaseType::Cassandra => Some("cassandra"), + DatabaseType::ScyllaDB => Some("scylladb"), DatabaseType::Iris => Some("iris"), DatabaseType::Access => Some("access"), DatabaseType::YashanDB => Some("yashandb"), @@ -238,6 +239,7 @@ mod tests { assert!(registry.databases.contains_key("informix")); assert!(registry.databases.contains_key("kylin")); assert!(registry.databases.contains_key("cassandra")); + assert!(registry.databases.contains_key("scylladb")); assert!(registry.databases.contains_key("iris")); assert!(registry.databases.contains_key("access")); } @@ -250,6 +252,22 @@ mod tests { assert_eq!(config.unwrap().name, "Oracle Database"); } + #[test] + fn test_cassandra_and_scylladb_share_driver_bundle() { + let registry = DriverRegistry::load(); + let cassandra = registry + .get_config_by_name("cassandra") + .expect("cassandra should have a driver config"); + let scylla = registry + .get_config_by_name("scylladb") + .expect("scylladb should have a driver config"); + // Both entries resolve to the same wrapper bundle JAR and cache dir, + // so a single download serves both connection types. + assert_eq!(cassandra.maven_artifact, scylla.maven_artifact); + assert_eq!(cassandra.download_url, scylla.download_url); + assert_eq!(cassandra.version_cap, scylla.version_cap); + } + #[test] fn test_get_config_db2_returns_config() { let registry = DriverRegistry::load(); diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index 2c84a63e..885cb7d1 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -62,6 +62,7 @@ pub mod adapter; pub mod clickhouse; pub mod config; +pub(crate) mod cql; pub mod error; pub mod explain; pub mod http_sql; diff --git a/src-tauri/src/database/sql_classification.rs b/src-tauri/src/database/sql_classification.rs index affa7451..0d3750a6 100644 --- a/src-tauri/src/database/sql_classification.rs +++ b/src-tauri/src/database/sql_classification.rs @@ -36,7 +36,7 @@ pub(crate) fn statement_returns_rows( /// comments. Returns `None` when the first executable token is not a word /// (e.g. `(`) or nothing executable remains (unterminated comment) — those /// cases fall through to the parser-based classification. -fn first_executable_keyword(sql: &str) -> Option<&str> { +pub(crate) fn first_executable_keyword(sql: &str) -> Option<&str> { let bytes = sql.as_bytes(); let mut i = 0; while i < bytes.len() { diff --git a/src-tauri/src/database/sql_service.rs b/src-tauri/src/database/sql_service.rs index 396a4cd2..4a756a9f 100644 --- a/src-tauri/src/database/sql_service.rs +++ b/src-tauri/src/database/sql_service.rs @@ -122,6 +122,31 @@ pub struct WrapQueryOptions { /// 4. Wraps it in a derived table if sort/filter/pagination are needed /// 5. Applies WHERE, ORDER BY, and LIMIT/OFFSET clauses pub fn wrap_query(options: WrapQueryOptions) -> SqlBuildResult { + if crate::database::config::DatabaseType::slug_is_cql(&options.database_type) { + let needs_wrapping = !options.sort.is_empty() + || !options.filters.is_empty() + || options.limit.is_some() + || options.offset.is_some(); + if needs_wrapping { + return SqlBuildResult::err( + "grid sort/filter/paging is not available for CQL (Cassandra/ScyllaDB) — \ + add ORDER BY / LIMIT to the statement itself", + ); + } + let Ok(statements) = crate::database::cql::split_statements(&options.original_sql) else { + return SqlBuildResult::err("invalid CQL statement"); + }; + return match statements.as_slice() { + [statement] + if crate::database::sql_classification::first_executable_keyword(statement) + .is_some_and(|word| word.eq_ignore_ascii_case("SELECT")) => + { + SqlBuildResult::ok(statement.to_string()) + } + _ => SqlBuildResult::err("expected a single CQL SELECT statement"), + }; + } + // ── Step 1: Clean the SQL ── let cleaned = strip_trailing(&options.original_sql); if cleaned.is_empty() { diff --git a/src-tauri/src/database/sqlite.rs b/src-tauri/src/database/sqlite.rs index a9d4db2f..d35e0df6 100644 --- a/src-tauri/src/database/sqlite.rs +++ b/src-tauri/src/database/sqlite.rs @@ -425,6 +425,23 @@ impl SQLiteAdapter { }) } else { // For non-SELECT queries (INSERT, UPDATE, DELETE, etc.) + // rusqlite 0.43 rejects empty / comment-only SQL with Error::Empty; + // the editor legitimately produces those (comment-only runs, trailing + // comments after statement splitting) — report zero affected rows. + if crate::database::sql_classification::first_executable_keyword(query).is_none() { + drop(conn_guard); + pool.return_conn(conn)?; + return Ok(QueryResult { + columns: Vec::new(), + column_types: Vec::new(), + rows: Vec::new(), + rows_affected: Some(0), + execution_time_ms: None, + truncated: false, + result_sets: Vec::new(), + }); + } + let rows_affected = conn_guard .execute(query, []) .map_err(|e| DbError::QueryExecution(format!("Failed to execute query: {}", e)))?; diff --git a/src-tauri/src/database/strategy.rs b/src-tauri/src/database/strategy.rs index 86ffa02a..689f1261 100644 --- a/src-tauri/src/database/strategy.rs +++ b/src-tauri/src/database/strategy.rs @@ -84,6 +84,7 @@ pub fn resolve_effective_type(db: DatabaseType) -> ConnectionStrategy { Informix => ConnectionStrategy::JdbcBridge, Kylin => ConnectionStrategy::JdbcBridge, Cassandra => ConnectionStrategy::JdbcBridge, + ScyllaDB => ConnectionStrategy::JdbcBridge, Iris => ConnectionStrategy::JdbcBridge, Access => ConnectionStrategy::JdbcBridge, YashanDB => ConnectionStrategy::JdbcBridge, @@ -154,6 +155,7 @@ pub fn default_port(db: DatabaseType) -> Option { Informix => Some(9088), Kylin => Some(7070), Cassandra => Some(9042), + ScyllaDB => Some(9042), Iris => Some(1972), Access => Some(0), Trino => Some(8080), @@ -270,6 +272,7 @@ mod tests { DatabaseType::Informix, DatabaseType::Kylin, DatabaseType::Cassandra, + DatabaseType::ScyllaDB, DatabaseType::Iris, DatabaseType::Access, DatabaseType::YashanDB, diff --git a/src-tauri/src/database/types.rs b/src-tauri/src/database/types.rs index 96c557aa..42df71c6 100644 --- a/src-tauri/src/database/types.rs +++ b/src-tauri/src/database/types.rs @@ -89,6 +89,16 @@ pub enum QueryValue { DateTime(String), } +impl QueryValue { + /// Text of a string-like value, or `None` for any other variant. + pub fn as_string(&self) -> Option { + match self { + QueryValue::String(s) | QueryValue::DateTime(s) => Some(s.clone()), + _ => None, + } + } +} + /// Represents a single row in a query result. pub type QueryRow = HashMap; diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 009ac1d2..c8562689 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -214,6 +214,7 @@ impl ServerConfig { "informix" => Ok(DatabaseType::Informix), "kylin" => Ok(DatabaseType::Kylin), "cassandra" => Ok(DatabaseType::Cassandra), + "scylladb" => Ok(DatabaseType::ScyllaDB), "iris" => Ok(DatabaseType::Iris), "access" => Ok(DatabaseType::Access), _ => Err(format!("Unsupported database type: {}", self.db_type)), @@ -242,6 +243,13 @@ impl ServerConfig { crate::database::config::duckdb_database_value(&self.host, self.read_only) .map_err(|e| format!("Invalid DuckDB database path: {}", e))?; config = config.with_database(database); + } else if db_type.is_cql() { + config = config.with_database( + self.database + .as_deref() + .filter(|name| !name.trim().is_empty()) + .unwrap_or("system"), + ); } else if let Some(ref database) = self.database { config = config.with_database(database); } @@ -566,6 +574,27 @@ mod tests { assert!(reopened.prompt.is_none()); } + #[test] + fn cql_split_keeps_the_local_datacenter_on_a_keyspace_switch() { + for db_type in ["cassandra", "scylladb"] { + let mut server = ServerConfig::new( + "CQL".into(), + db_type.into(), + "127.0.0.1".into(), + 9042, + "".into(), + ); + server.database = Some("system?localdatacenter=dc%2Bwest".into()); + let mut config = server.to_connection_config().unwrap(); + assert_eq!(config.cql_keyspace(), "system"); + assert_eq!(config.cql_datacenter(), "dc+west"); + + config.database = Some("events".into()); + assert_eq!(config.cql_keyspace(), "events"); + assert_eq!(config.cql_datacenter(), "dc+west"); + } + } + #[test] fn duckdb_maps_the_file_path_into_the_database_field() { let config = file_config("duckdb", "/tmp/analytics.duckdb", false) diff --git a/src-tauri/tests/sqlite_integration.rs b/src-tauri/tests/sqlite_integration.rs index f899473d..1c615d96 100644 --- a/src-tauri/tests/sqlite_integration.rs +++ b/src-tauri/tests/sqlite_integration.rs @@ -100,6 +100,49 @@ async fn test_connection_in_memory() { adapter.disconnect().await.expect("Failed to disconnect"); } +#[tokio::test] +async fn test_empty_and_comment_only_sql() { + // rusqlite 0.43 rejects empty / comment-only SQL (Error::Empty); the + // adapter must report zero affected rows instead of surfacing the error. + let config = get_test_config_memory(); + let mut adapter = SQLiteAdapter::new(config); + + adapter.connect().await.expect("Failed to connect"); + + adapter + .execute_query("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)") + .await + .expect("Failed to create table"); + + for sql in [ + "-- only a comment", + "/* block comment */", + "", + " \n\t ", + ] { + let result = adapter + .execute_query(sql) + .await + .unwrap_or_else(|e| panic!("comment-only / empty SQL must not fail: {sql:?} -> {e}")); + assert_eq!(result.rows_affected, Some(0), "sql: {sql:?}"); + } + + // Statement + trailing comment: the statement runs, the comment is ignored. + let insert = adapter + .execute_query("INSERT INTO t (id, v) VALUES (1, 'a'); -- trailing comment") + .await + .expect("trailing comment must not fail"); + assert_eq!(insert.rows_affected, Some(1)); + + let select = adapter + .execute_query("SELECT id, v FROM t WHERE v = 'a'") + .await + .expect("Failed to select"); + assert_eq!(select.rows.len(), 1); + + adapter.disconnect().await.expect("Failed to disconnect"); +} + #[tokio::test] async fn test_create_and_query_table() { let db_name = "test_create_query"; diff --git a/src/__tests__/dataTablePagination.test.ts b/src/__tests__/dataTablePagination.test.ts index ad49dfd1..dfeec640 100644 --- a/src/__tests__/dataTablePagination.test.ts +++ b/src/__tests__/dataTablePagination.test.ts @@ -8,7 +8,7 @@ jest.mock('@tauri-apps/plugin-dialog', () => ({ save: jest.fn() })) jest.mock('@/components/pagination', () => ({ PaginationControls: { name: 'PaginationControls', - props: { currentPage: Number, pageCount: Number, pageSize: [Number, String], disabled: Boolean, allowAll: Boolean }, + props: { currentPage: Number, pageCount: Number, pageSize: [Number, String], disabled: Boolean, allowAll: Boolean, preview: Boolean }, template: '
', }, })) @@ -20,9 +20,15 @@ jest.mock('@/components/ui/destructive-confirm-dialog', () => ({ DestructiveConf jest.mock('@/components/ui/dialog', () => Object.fromEntries( ['Dialog', 'DialogContent', 'DialogTitle'].map(name => [name, { template: '
' }]), )) +let mockDbType = 'POSTGRESQL' + jest.mock('@/store', () => ({ ConnectionStatus: { CONNECTED: 'connected' }, - useConnectionStore: () => ({ getConnectionStatus: () => 'connected' }), + DatabaseType: { CASSANDRA: 'CASSANDRA', SCYLLADB: 'SCYLLADB' }, + useConnectionStore: () => ({ + getConnectionStatus: () => 'connected', + getConnectionById: () => ({ type: mockDbType }), + }), })) jest.mock('@/composables/useMinLoadingTime', () => ({ useMinLoadingTime: () => ({ withMinLoadingTime: (operation: () => Promise) => operation() }), @@ -43,6 +49,7 @@ const mountTable = () => shallowMount(DataTableView, { const lastQuery = () => mockInvoke.mock.calls.filter(([command]) => command === 'get_table_data').slice(-1)[0][1].query beforeEach(() => { + mockDbType = 'POSTGRESQL' total = 235 mockInvoke.mockReset().mockImplementation(async (command, args) => { if (command === 'get_table_count') @@ -60,6 +67,22 @@ beforeEach(() => { }) describe('table browsing with shared pagination', () => { + it.each(['CASSANDRA', 'SCYLLADB'])('shows a bounded preview for %s', async (dbType) => { + mockDbType = dbType + const wrapper = mountTable() + await flushPromises() + const controls = wrapper.findComponent({ name: 'PaginationControls' }) + expect(controls.props('preview')).toBe(true) + expect(lastQuery()).toMatchObject({ limit: 100, offset: 0 }) + expect(mockInvoke.mock.calls.map(([command]) => command)).not.toContain('get_table_count') + expect(wrapper.get('[role="status"]').text()).toContain('components.dataTableView.previewRows {"count":100}') + controls.vm.$emit('pageChange', 2) + controls.vm.$emit('pageSizeChange', 25) + await flushPromises() + expect(lastQuery()).toMatchObject({ limit: 25, offset: 0 }) + expect(mockInvoke.mock.calls.filter(([command]) => command === 'get_table_data')).toHaveLength(2) + wrapper.unmount() + }) it('keeps returned rows visible without claiming a total when the count fails', async () => { const normalInvoke = mockInvoke.getMockImplementation()! mockInvoke.mockImplementation((command, args) => command === 'get_table_count' diff --git a/src/__tests__/queryResultPanel.test.ts b/src/__tests__/queryResultPanel.test.ts index 82a51872..a0a2a38b 100644 --- a/src/__tests__/queryResultPanel.test.ts +++ b/src/__tests__/queryResultPanel.test.ts @@ -4,7 +4,7 @@ import { flushPromises, shallowMount } from '@vue/test-utils' import QueryResultPanel from '@/components/database-browser/QueryResultPanel.vue' jest.mock('@tauri-apps/api/core', () => ({ invoke: jest.fn() })) -jest.mock('@/store', () => ({ useConnectionStore: () => ({ getConnectionById: () => ({ type: 'postgresql' }) }) })) +jest.mock('@/store', () => ({ useConnectionStore: () => ({ getConnectionById: (id: string) => ({ type: id === 'cql' ? 'cassandra' : 'postgresql' }) }) })) jest.mock('@/composables/useDataGridCopy', () => ({ useDataGridCopy: () => ({ copyRowsAs: jest.fn(), exportToFile: jest.fn() }), })) @@ -53,8 +53,8 @@ const empty = resultSet('refund_id', []) const last = resultSet('balance', [{ balance: '2700' }]) const scriptResult = { ...last, resultSets: [first, empty, last] } -const mountPanel = (results: QueryResult | null = scriptResult) => shallowMount(QueryResultPanel, { - props: { results, sql: 'BEGIN; SELECT 1; COMMIT;', connectionId: 'test' }, +const mountPanel = (results: QueryResult | null = scriptResult, connectionId = 'test') => shallowMount(QueryResultPanel, { + props: { results, sql: 'SELECT * FROM events', connectionId }, global: { stubs: { DataGrid: false } }, }) @@ -117,4 +117,17 @@ describe('script query results', () => { expect(wrapper.findComponent({ name: 'DataGrid' }).props('rows')).toEqual(last.rows) expect(wrapper.findComponent({ name: 'DataGrid' }).props('filterable')).toBe(true) }) + + it('keeps CQL result rows visible without offering server-side filters', async () => { + const { invoke } = jest.requireMock('@tauri-apps/api/core') + const wrapper = mountPanel(last, 'cql') + await flushPromises() + invoke.mockClear() + const grid = wrapper.findComponent({ name: 'DataGrid' }) + expect(grid.props('filterable')).toBe(false) + expect(grid.props('rows')).toEqual(last.rows) + grid.vm.$emit('filter-change', [{ column: 'balance', operator: 'eq', value: '2700' }]) + await flushPromises() + expect(invoke).not.toHaveBeenCalled() + }) }) diff --git a/src/assets/images/database-icons/cassandra-logo.svg b/src/assets/images/database-icons/cassandra-logo.svg index 769e72ea..79822542 100644 --- a/src/assets/images/database-icons/cassandra-logo.svg +++ b/src/assets/images/database-icons/cassandra-logo.svg @@ -1 +1 @@ - +Apache Cassandra \ No newline at end of file diff --git a/src/assets/images/database-icons/scylladb-logo.png b/src/assets/images/database-icons/scylladb-logo.png new file mode 100644 index 00000000..c049a400 Binary files /dev/null and b/src/assets/images/database-icons/scylladb-logo.png differ diff --git a/src/components/SQLEditor.vue b/src/components/SQLEditor.vue index f0ad617a..0872567f 100644 --- a/src/components/SQLEditor.vue +++ b/src/components/SQLEditor.vue @@ -12,6 +12,7 @@ import { ThemeType, useAppStore } from '@/store/appStore' type Props = { modelValue?: string dialect?: SQLDialect + cql?: boolean readOnly?: boolean minimap?: boolean fontSize?: number @@ -70,6 +71,7 @@ const isSettingValueFromProp = ref(false) const editorOptions: MonacoEditorOptions = { language: props.dialect, + isCql: () => props.cql ?? false, readOnly: props.readOnly, minimap: props.minimap, fontSize: props.fontSize, diff --git a/src/components/connections/ServerFormDialog.vue b/src/components/connections/ServerFormDialog.vue index f27cbffd..bc8cdfdb 100644 --- a/src/components/connections/ServerFormDialog.vue +++ b/src/components/connections/ServerFormDialog.vue @@ -29,7 +29,7 @@ import { toast } from '@/composables/useNotifications' import { usePlatform } from '@/composables/usePlatform' import { jdbcApi } from '@/datasources/jdbcApi' import { buildOracleOptions, buildTransportLayers, databasePlaceholderFor, DatabaseType, dbTypeToBackend, isDatabaseRequired, isJdbcDatabase, resolveDatabase, useConnectionStore, useEntitlementStore } from '@/store' -import { DEFAULT_SSL_MODE, sslModeToBackend, validateSslConfig } from '@/types/connection' +import { DEFAULT_SSL_MODE, isCqlDatabase, normalizeSslMode, sslModeToBackend, validateSslConfig } from '@/types/connection' import { buildMemoryDatabaseHost, createMemoryDatabaseLabel, isMemoryDatabaseHost, isSameDatabaseFile, memoryDatabaseLabel } from '@/utils/databaseFiles' import { classifyDuckDbFailure } from '@/utils/duckdbErrors' import ConnectionPromptDialog from './ConnectionPromptDialog.vue' @@ -117,6 +117,7 @@ const defaultPorts: Record = { [DatabaseType.INFORMIX]: 9088, [DatabaseType.KYLIN]: 7070, [DatabaseType.CASSANDRA]: 9042, + [DatabaseType.SCYLLADB]: 9042, [DatabaseType.IRIS]: 1972, [DatabaseType.ACCESS]: 0, [DatabaseType.FIREBIRD]: 3050, @@ -137,6 +138,28 @@ const defaultConnection: ServerConnection = { } const formData = ref({ ...defaultConnection }) +// CQL stores (Cassandra/ScyllaDB) need an explicit local datacenter for the +// driver's default load-balancing policy — kept as its own field and composed +// into the keyspace value on save/test (see resolveDatabase on the store side). +const isCassandraFamily = computed(() => isCqlDatabase(formData.value.type)) +const localDatacenter = ref('datacenter1') + +const databaseWithLocalDc = () => { + if (!isCassandraFamily.value) + return formData.value.database + const keyspace = formData.value.database?.trim() || 'system' + const dc = localDatacenter.value.trim() || 'datacenter1' + return `${keyspace}?localdatacenter=${encodeURIComponent(dc)}` +} + +const splitLocalDatacenter = (database?: string) => { + if (!isCassandraFamily.value || !database) + return + const [keyspace, query = ''] = database.split('?') + const dc = [...new URLSearchParams(query)].find(([key]) => key.toLowerCase() === 'localdatacenter') + localDatacenter.value = dc?.[1] || 'datacenter1' + formData.value.database = keyspace +} const testStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle') const testError = ref('') /** The last test ran without the saved SSH tunnel (Ultimate-only feature). */ @@ -227,8 +250,10 @@ const { platform } = usePlatform() watch(() => props.open, (open) => { if (open) { + localDatacenter.value = 'datacenter1' if (props.connection) { formData.value = { ...props.connection } + splitLocalDatacenter(formData.value.database) // Detect SQLite mode from path if (props.connection.type === DatabaseType.SQLITE) { if (props.connection.host === ':memory:') { @@ -494,6 +519,8 @@ const showsStandardHostFields = computed(() => ) const databaseLabel = computed(() => { + if (isCassandraFamily.value) + return t('components.serverForm.labels.keyspace') if (isOracle.value && oracleMethod.value === 'basic') { return oracleSidOrService.value === 'sid' ? t('components.serverForm.oracle.sid') @@ -792,8 +819,8 @@ async function handleTestConnection() { port: formData.value.port, username: formData.value.username || '', password: formData.value.password || undefined, - database: resolveDatabase(formData.value.type, formData.value.database) ?? undefined, - ssl_mode: sslModeToBackend(formData.value.ssl), + database: resolveDatabase(formData.value.type, databaseWithLocalDc()) ?? undefined, + ssl_mode: sslModeToBackend(formData.value.ssl, formData.value.type), ssl_ca_cert: formData.value.ssl.caCertPath || null, ssl_client_cert: formData.value.ssl.clientCertPath || null, ssl_client_key: formData.value.ssl.clientKeyPath || null, @@ -903,7 +930,13 @@ function handleSave() { return } - emit('save', { ...formData.value }) + if (isCassandraFamily.value) + formData.value.database = databaseWithLocalDc() + + emit('save', { + ...formData.value, + ssl: { ...formData.value.ssl, mode: normalizeSslMode(formData.value.ssl.mode, formData.value.type) }, + }) isOpen.value = false } @@ -1010,7 +1043,7 @@ function handleSave() {
+
+ + +
diff --git a/src/components/connections/ssl/SslConfigSection.vue b/src/components/connections/ssl/SslConfigSection.vue index 3c06bc60..f012c4eb 100644 --- a/src/components/connections/ssl/SslConfigSection.vue +++ b/src/components/connections/ssl/SslConfigSection.vue @@ -4,9 +4,11 @@ import type { SslConfig, SslMode } from '@/types/connection' import { computed } from 'vue' import { DEFAULT_SSL_MODE, + isCqlDatabase, isSslSupported, needsCertFields, needsSqlServerOptions, + normalizeSslMode, } from '@/types/connection' import SslCertFields from './SslCertFields.vue' import SslModeSelect from './SslModeSelect.vue' @@ -53,7 +55,8 @@ function handleModeChange(mode: SslMode) {