diff --git a/.github/scripts/bump-agent-versions.mjs b/.github/scripts/bump-agent-versions.mjs index 310520a0a2..58779afcf1 100644 --- a/.github/scripts/bump-agent-versions.mjs +++ b/.github/scripts/bump-agent-versions.mjs @@ -54,6 +54,7 @@ const nativeDriverDirectories = { hive: "hive-go", argo: "argo-go", oracle: "oracle-go", + "oracle-oci": "oracle-go", kingbase: "kingbase-go", iotdb: "iotdb", neo4j: "neo4j-go", @@ -69,7 +70,7 @@ const nativeDriverDirectories = { const crateNativeDriverDirectories = { "sqlite-worker": "crates/dbx-sqlite-worker", }; -const nativeDriverModules = new Set(["cassandra", "duckdb", "hive", "argo", "oracle", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2", "sqlite-worker"]); +const nativeDriverModules = new Set(["cassandra", "duckdb", "hive", "argo", "oracle", "oracle-oci", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2", "sqlite-worker"]); const nativeDriverSharedPaths = { hive: [ "agents/go-common/go-gssapi", diff --git a/.github/scripts/bump-agent-versions.test.mjs b/.github/scripts/bump-agent-versions.test.mjs index 212dd67c11..577e7ebc6f 100644 --- a/.github/scripts/bump-agent-versions.test.mjs +++ b/.github/scripts/bump-agent-versions.test.mjs @@ -48,6 +48,38 @@ test("bumps the SQLite SSH worker from its crate path", () => { assert.deepEqual(result.nativeModules, ["sqlite-worker"]); }); +test("bumps both Oracle variants when their shared module changes", () => { + // `oracle` and `oracle-oci` are built from the same `oracle-go` module (with + // and without the `oci` build tag), so a change there must rebuild and + // re-release both artifacts — otherwise the `oci` variant silently keeps a + // stale version and `reuse-previous-assets` re-publishes the old binary. + const result = evaluateAgentVersionBump({ + versions: { oracle: "0.1.66", "oracle-oci": "0.1.0" }, + changedFiles: ["agents/drivers/oracle-go/oci.go"], + moduleExists: (path) => path === "agents/drivers/oracle-go", + readModuleFile: () => "", + }); + + assert.equal(result.versions.oracle, "0.1.67"); + assert.equal(result.versions["oracle-oci"], "0.1.1"); + assert.deepEqual(result.changedModules.sort(), ["oracle", "oracle-oci"]); + assert.deepEqual(result.nativeModules.sort(), ["oracle", "oracle-oci"]); +}); + +test("keeps a manually versioned Oracle OCI release without touching the thin variant", () => { + const result = evaluateAgentVersionBump({ + versions: { oracle: "0.1.66", "oracle-oci": "0.1.0" }, + prevVersions: { oracle: "0.1.66" }, + changedFiles: ["agents/versions.json"], + moduleExists: (path) => path === "agents/drivers/oracle-go", + readModuleFile: () => "", + }); + + assert.equal(result.versions["oracle-oci"], "0.1.0"); + assert.equal(result.versions.oracle, "0.1.66"); + assert.deepEqual(result.changedModules, ["oracle-oci"]); +}); + test("classifies TDengine Rust changes as native-only", () => { const result = evaluateAgentVersionBump({ versions: { tdengine: "0.1.39" }, diff --git a/.github/scripts/reuse-agent-release-assets.mjs b/.github/scripts/reuse-agent-release-assets.mjs index ae27a018b9..d5ab3d32f5 100644 --- a/.github/scripts/reuse-agent-release-assets.mjs +++ b/.github/scripts/reuse-agent-release-assets.mjs @@ -15,7 +15,14 @@ import { basename, join } from "node:path"; import { tmpdir } from "node:os"; const REGISTRY_ASSET = "agent-registry.json"; -const NATIVE_MODULES = new Set(["duckdb", "oracle", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2"]); +const NATIVE_MODULES = new Set(["duckdb", "oracle", "oracle-oci", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2"]); +// Native modules that intentionally publish a subset of the six platforms. The +// Oracle OCI ("thick") agent links the Oracle Client through CGO and is built +// for Windows x64 only, so a reused release must cover exactly that platform — +// requiring all six would reject a perfectly complete release. +const NATIVE_MODULE_PLATFORMS = { + "oracle-oci": ["windows-x64"], +}; const PLATFORMS = [ "macos-aarch64", "macos-x64", @@ -25,6 +32,10 @@ const PLATFORMS = [ "windows-x64", ]; +function expectedNativePlatforms(moduleName) { + return [...(NATIVE_MODULE_PLATFORMS[moduleName] ?? PLATFORMS)].sort(); +} + function artifactFilename(url) { return basename(url.split(/[?#]/, 1)[0]); } @@ -78,8 +89,9 @@ export function collectReusableAssetPlan({ registry, release, versions, modules, const nativePlatforms = Object.keys(driver.native ?? {}).sort(); if (NATIVE_MODULES.has(moduleName)) { - const missingPlatforms = PLATFORMS.filter((platform) => !nativePlatforms.includes(platform)); - const extraPlatforms = nativePlatforms.filter((platform) => !PLATFORMS.includes(platform)); + const expectedPlatforms = expectedNativePlatforms(moduleName); + const missingPlatforms = expectedPlatforms.filter((platform) => !nativePlatforms.includes(platform)); + const extraPlatforms = nativePlatforms.filter((platform) => !expectedPlatforms.includes(platform)); if (missingPlatforms.length > 0 || extraPlatforms.length > 0) { throw new Error( `Previous native artifacts are incomplete for ${moduleName}: missing=${missingPlatforms.join(",") || "none"}, extra=${extraPlatforms.join(",") || "none"}`, @@ -223,7 +235,7 @@ export function extractReusableDriverPackages({ packagesDir, outputDir, versions extracted += 1; } - if (NATIVE_MODULES.has(moduleName) && nativePlatforms.length !== PLATFORMS.length) { + if (NATIVE_MODULES.has(moduleName) && nativePlatforms.length !== expectedNativePlatforms(moduleName).length) { throw new Error(`Reusable native package set is incomplete for ${moduleName}.`); } if (!filenames.has(javaName) && nativePlatforms.length === 0) { diff --git a/.github/scripts/reuse-agent-release-assets.test.mjs b/.github/scripts/reuse-agent-release-assets.test.mjs index 174a2865bb..9a2cf099b3 100644 --- a/.github/scripts/reuse-agent-release-assets.test.mjs +++ b/.github/scripts/reuse-agent-release-assets.test.mjs @@ -132,6 +132,39 @@ test("requires all RocketMQ native platforms when reusing a release", () => { ); }); +test("reuses the Windows-only Oracle OCI native package", () => { + const native = { "windows-x64": artifact("dbx-agent-oracle-oci-0.1.0-windows-x64.tar.zst", "a") }; + const registry = { drivers: { "oracle-oci": { version: "0.1.0", native } }, jres: {} }; + + const plan = collectReusableAssetPlan({ + registry, + release: releaseFor(Object.values(native)), + versions: { "oracle-oci": "0.1.0" }, + modules: ["oracle-oci"], + reuseJre: false, + }); + + // Windows-only is the complete platform set for this module, so requiring all + // six platforms would reject a correct release. + assert.deepEqual(plan.driverAssets.map((asset) => asset.platform), ["windows-x64"]); +}); + +test("rejects an Oracle OCI release that lost its Windows native package", () => { + const native = { "linux-x64": artifact("dbx-agent-oracle-oci-0.1.0-linux-x64.tar.zst", "a") }; + const registry = { drivers: { "oracle-oci": { version: "0.1.0", native } }, jres: {} }; + + assert.throws( + () => collectReusableAssetPlan({ + registry, + release: releaseFor(Object.values(native)), + versions: { "oracle-oci": "0.1.0" }, + modules: ["oracle-oci"], + reuseJre: false, + }), + /missing=windows-x64, extra=linux-x64/, + ); +}); + test("ignores zero-size legacy JAR placeholders for native-only modules", () => { const native = Object.fromEntries( platforms.map((platform, index) => [platform, artifact(`dbx-agent-duckdb-0.1.2-${platform}.tar.zst`, String(index + 1))]), diff --git a/.github/workflows/agents-release.yml b/.github/workflows/agents-release.yml index b43ce6a24f..50628ca063 100644 --- a/.github/workflows/agents-release.yml +++ b/.github/workflows/agents-release.yml @@ -214,6 +214,62 @@ jobs: name: oracle-native path: "release-native/dbx-agent-oracle-*" + # Oracle OCI(thick)变体:同一个 oracle-go 模块加上 `oci` 构建标记,用 CGO 链接 + # Oracle 客户端,因此需要 gcc(MinGW-w64)与 Instant Client 的 SDK(头文件 + 导入库)。 + # Instant Client 是分平台的,本任务只产出 Windows x64(当前 OCI 模式仅支持 Windows)。 + build-oracle-oci-native: + needs: [bump-versions] + if: ${{ contains(fromJSON(needs.bump-versions.outputs.native_modules), 'oracle-oci') }} + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + # godror 需要 Go >= 1.21;thin 的 Windows 7 兼容线仍由 build-oracle-native 用 Go 1.20 构建。 + go-version: "1.25.x" + cache-dependency-path: agents/drivers/oracle-go/go.sum + - name: Prepare MinGW-w64 and the Oracle Instant Client + shell: bash + run: | + cc="$(command -v gcc || true)" + if [ -z "$cc" ]; then + choco install mingw -y --no-progress + cc="$(ls /c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin/gcc.exe | head -1)" + fi + mkdir -p instantclient + curl -fsSL -o ic-basic.zip "https://download.oracle.com/otn_software/nt/instantclient/2326300/instantclient-basic-windows.x64-23.26.3.0.0.zip" + curl -fsSL -o ic-sdk.zip "https://download.oracle.com/otn_software/nt/instantclient/2326300/instantclient-sdk-windows.x64-23.26.3.0.0.zip" + tar -xf ic-basic.zip -C instantclient + tar -xf ic-sdk.zip -C instantclient + ic_dir="$(ls -d "${GITHUB_WORKSPACE}/instantclient"/instantclient_* | head -1)" + echo "MinGW gcc: $cc / Instant Client: $ic_dir" + { + echo "CGO_ENABLED=1" + echo "GOOS=windows" + echo "GOARCH=amd64" + echo "CC=${cc}" + echo "CGO_CFLAGS=-I${ic_dir}/sdk/include" + echo "CGO_LDFLAGS=-L${ic_dir}/sdk/lib/msvc" + } >> "$GITHUB_ENV" + - name: Test Oracle agent with the OCI build tag + shell: bash + working-directory: agents/drivers/oracle-go + run: go test -mod=mod -tags oci ./... + - name: Build Oracle OCI agent (Windows x64) + shell: bash + working-directory: agents/drivers/oracle-go + run: | + mkdir -p ../../../release-native + output="../../../release-native/dbx-agent-oracle-oci-windows-x64.exe" + # go.mod 的 go 指令保持 1.20(thin 的 Windows 7 兼容线);OCI 变体要求更高, + # 因此允许就地更新 go.mod —— 只影响本任务的检出目录,不会被提交。 + go build -mod=mod -tags oci -trimpath -ldflags="-s -w" -o "$output" . + ls -lh ../../../release-native + - uses: actions/upload-artifact@v4 + with: + name: oracle-oci-native + path: "release-native/dbx-agent-oracle-oci-*" + build-xugu-native: needs: [bump-versions] if: ${{ contains(fromJSON(needs.bump-versions.outputs.native_modules), 'xugu') }} @@ -1295,7 +1351,7 @@ jobs: retention-days: 1 release: - needs: [bump-versions, commit-versions, build-agents, build-oracle-native, build-xugu-native, build-rabbitmq-native, build-rocketmq-native, build-etcd-native, build-etcd2-native, build-zookeeper-native, build-cassandra-native, build-hive-native, build-argo-native, build-kingbase-native, build-vastbase-native, build-neo4j-native, build-nebula-native, build-iotdb-native, build-duckdb-native, build-sqlite-worker-native, build-tdengine-native, build-jre, reuse-previous-assets] + needs: [bump-versions, commit-versions, build-agents, build-oracle-native, build-oracle-oci-native, build-xugu-native, build-rabbitmq-native, build-rocketmq-native, build-etcd-native, build-etcd2-native, build-zookeeper-native, build-cassandra-native, build-hive-native, build-argo-native, build-kingbase-native, build-vastbase-native, build-neo4j-native, build-nebula-native, build-iotdb-native, build-duckdb-native, build-sqlite-worker-native, build-tdengine-native, build-jre, reuse-previous-assets] if: ${{ always() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') }} runs-on: ubuntu-latest steps: @@ -1434,6 +1490,7 @@ jobs: tdengine) echo "TDengine" ;; etcd) echo "etcd" ;; etcd2) echo "etcd 2.x (v2 API)" ;; + oracle-oci) echo "Oracle (OCI)" ;; *) echo "$name" ;; esac } @@ -1497,7 +1554,7 @@ jobs: [ -n "$DRIVERS" ] && DRIVERS="${DRIVERS},"$'\n' DRIVERS="${DRIVERS}$(generate_jar_entry "$name" "$label" "$f" "$jre_key" "$version" "$external_driver" "$native_json")" done - for name in oracle xugu kingbase vastbase neo4j nebula iotdb duckdb sqlite-worker rabbitmq rocketmq zookeeper cassandra hive argo tdengine etcd etcd2; do + for name in oracle oracle-oci xugu kingbase vastbase neo4j nebula iotdb duckdb sqlite-worker rabbitmq rocketmq zookeeper cassandra hive argo tdengine etcd etcd2; do version=$(get_module_version "$name") [ -f "release/dbx-agent-${name}-${version}.jar" ] && continue native_json=$(generate_native_platforms "$name" "$version") @@ -1592,6 +1649,7 @@ jobs: tdengine) echo "TDengine" ;; etcd) echo "etcd" ;; etcd2) echo "etcd 2.x (v2 API)" ;; + oracle-oci) echo "Oracle (OCI)" ;; *) echo "$name" ;; esac } diff --git a/agents/README.md b/agents/README.md index add479359c..84cb3d096f 100644 --- a/agents/README.md +++ b/agents/README.md @@ -27,6 +27,7 @@ Each agent runs as a standalone process and communicates with DBX via stdin/stdo | gbase8a | GBase 8a | External GBase 8a JDBC | | gbase8s | GBase 8s | External GBase 8s JDBC | | oracle | Oracle 10g+ | go-ora native agent | +| oracle-oci | Oracle OCI (thick driver) | godror native agent (Windows x64, CGO; shares `drivers/oracle-go`, built with `-tags oci`) | | h2 | H2 | H2 JDBC | | snowflake | Snowflake | Snowflake JDBC | | trino | Trino (Presto) | Trino JDBC | diff --git a/agents/drivers/oracle-go/README.md b/agents/drivers/oracle-go/README.md index 847b78d5ab..b4cff67629 100644 --- a/agents/drivers/oracle-go/README.md +++ b/agents/drivers/oracle-go/README.md @@ -34,3 +34,39 @@ To restore the Java agent: ```bash rm ~/.dbx/agents/drivers/oracle/agent ``` + +## OCI (thick driver) variant + +The `oracle-oci` driver shipped for Windows x64 is this same agent compiled with +the `oci` build tag, which swaps the pure-Go `go-ora` driver for +`github.com/godror/godror` (Oracle Call Interface through CGO): + +- Connections that select the OCI driver profile (`driver_profile: "oci"`) use + the OCI driver; every other Oracle connection keeps the thin `go-ora` path, + and a thin binary asked for OCI fails with an explicit "install the + oracle-oci driver" error instead of a driver-not-found surprise. +- The agent builds a `user/password@connectString [AS SYSDBA]` DSN. Service + name / SID / descriptor / TNS alias all come from the connection string DBX + sends; `buildOCIDSN` in `oci_dsn.go` covers those rules and is unit tested + without the build tag, so the regular CI test run covers them. +- Process-scoped client settings come from DBX's launch environment: the + Instant Client directory is prepended to `PATH`, `TNS_ADMIN` points at + `tnsnames.ora`, and `NLS_LANG` sets the client character set. + +### Building the OCI variant (Windows x64) + +Building requires the Oracle Instant Client **SDK** (headers + import library) +and a C compiler for CGO (MinGW-w64 GCC): + +```powershell +$env:CGO_ENABLED=1 +$env:GOOS="windows"; $env:GOARCH="amd64" +$env:CC="C:/mingw64/bin/gcc.exe" +$env:CGO_CFLAGS="-IC:/instantclient/sdk/include" +$env:CGO_LDFLAGS="-LC:/instantclient/sdk/lib/msvc" +# go.mod keeps `go 1.20` for the Windows 7-compatible thin build; the OCI +# variant needs Go >= 1.21 (godror), so -mod=mod updates go.mod in place. +go build -mod=mod -tags oci -trimpath -ldflags="-s -w" -o oracle-oci.exe . +``` + +At runtime only `oci.dll` is needed, located through `PATH`. diff --git a/agents/drivers/oracle-go/go.mod b/agents/drivers/oracle-go/go.mod index 225f55818a..676f644ee9 100644 --- a/agents/drivers/oracle-go/go.mod +++ b/agents/drivers/oracle-go/go.mod @@ -4,4 +4,15 @@ go 1.20 require github.com/sijms/go-ora/v2 v2.9.0 -require golang.org/x/text v0.22.0 +require ( + github.com/godror/godror v0.51.5 + golang.org/x/text v0.22.0 +) + +require ( + github.com/VictoriaMetrics/easyproto v0.1.4 // indirect + github.com/go-logfmt/logfmt v0.6.0 // indirect + github.com/godror/knownpb v0.3.0 // indirect + golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // indirect + google.golang.org/protobuf v1.36.6 // indirect +) diff --git a/agents/drivers/oracle-go/go.sum b/agents/drivers/oracle-go/go.sum index a0fd27bc80..04707f0ac6 100644 --- a/agents/drivers/oracle-go/go.sum +++ b/agents/drivers/oracle-go/go.sum @@ -1,4 +1,28 @@ +github.com/VictoriaMetrics/easyproto v0.1.4 h1:r8cNvo8o6sR4QShBXQd1bKw/VVLSQma/V2KhTBPf+Sc= +github.com/VictoriaMetrics/easyproto v0.1.4/go.mod h1:QlGlzaJnDfFd8Lk6Ci/fuLxfTo3/GThPs2KH23mv710= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/godror/godror v0.40.0 h1:ZVsBx4XAkfVy2uHWpTTGMWbaZP1olTx78MDkQOJEjqM= +github.com/godror/godror v0.40.0/go.mod h1:WoiPqkjCGtKxZ5gJtB64kmOUy6O2h7dR4dxdsnxjgCA= +github.com/godror/godror v0.51.5 h1:NFvDtLILwg5mTU31DtL7Ae2AQvkDNL7nip+pSdMS4ow= +github.com/godror/godror v0.51.5/go.mod h1:ZxKkyFw54Ou5CGeXhP4EjK0s9PSB+2W87GyL765XbO8= +github.com/godror/knownpb v0.3.0 h1:+caUdy8hTtl7X05aPl3tdL540TvCcaQA6woZQroLZMw= +github.com/godror/knownpb v0.3.0/go.mod h1:PpTyfJwiOEAzQl7NtVCM8kdPCnp3uhxsZYIzZ5PV4zU= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/oklog/ulid/v2 v2.0.2 h1:r4fFzBm+bv0wNKNh5eXTwU7i85y5x+uwkxCUTNVQqLc= +github.com/oklog/ulid/v2 v2.0.2/go.mod h1:mtBL0Qe/0HAx6/a4Z30qxVIAL1eQDweXq5lxOEiwQ68= github.com/sijms/go-ora/v2 v2.9.0 h1:+iQbUeTeCOFMb5BsOMgUhV8KWyrv9yjKpcK4x7+MFrg= github.com/sijms/go-ora/v2 v2.9.0/go.mod h1:QgFInVi3ZWyqAiJwzBQA+nbKYKH77tdp1PYoCqhR2dU= +golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ= +golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8= +golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ/GnQx2BE33L8BOHQkI= +golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.go index d69bc2272b..c78664945a 100644 --- a/agents/drivers/oracle-go/main.go +++ b/agents/drivers/oracle-go/main.go @@ -285,6 +285,13 @@ type connectParams struct { SysDBA bool `json:"sysdba"` URLParams string `json:"url_params"` ConnectionString string `json:"connection_string"` + // DriverProfile 由 DBX 下传;"oci" 走 OCI(thick)驱动,其余走内置的 thin 驱动。 + DriverProfile string `json:"driver_profile"` +} + +// usesOCIProfile 判断本次连接是否选择了 OCI(thick)驱动。 +func usesOCIProfile(params connectParams) bool { + return strings.EqualFold(strings.TrimSpace(params.DriverProfile), "oci") } type completionAssistantRequest struct { @@ -1256,6 +1263,11 @@ func openDB(params connectParams) (*sql.DB, error) { } func openDBWithStringConverter(params connectParams, stringConverter converters.IStringConverter) (*sql.DB, error) { + if usesOCIProfile(params) { + // OCI 由 Oracle 客户端负责字符集转换(NLS_LANG 在进程环境里生效), + // go-ora 的 string converter 机制不适用于它。 + return openOCIDB(params) + } dsn, err := buildDSNForConnect(params) if err != nil { return nil, err @@ -1278,6 +1290,10 @@ func openAndPingDB(params connectParams, timeout time.Duration) (*sql.DB, error) } if err := pingDB(db, timeout); err != nil { db.Close() + if usesOCIProfile(params) { + // OCI 的字符集由客户端决定,重试 go-ora 的转换器没有意义。 + return nil, err + } stringConverter, ok := oracleStringConverterForUnsupportedCharsetError(err) if !ok { return nil, err @@ -1472,25 +1488,56 @@ var ( func parseOracleJDBCURL(value string) jdbcURLInfo { value = strings.TrimSpace(value) lower := strings.ToLower(value) - if !strings.HasPrefix(lower, "jdbc:oracle:thin:@") { + prefix := "" + for _, candidate := range []string{"jdbc:oracle:thin:@", "jdbc:oracle:oci8:@", "jdbc:oracle:oci:@"} { + if strings.HasPrefix(lower, candidate) { + prefix = candidate + break + } + } + if prefix == "" { return jdbcURLInfo{} } - descriptor := strings.TrimSpace(value[len("jdbc:oracle:thin:@"):]) + descriptor := strings.TrimSpace(value[len(prefix):]) if strings.HasPrefix(descriptor, "(") { return jdbcURLInfo{Kind: "descriptor", Descriptor: descriptor} } - if match := oracleJDBCServiceRegexp.FindStringSubmatch(value); len(match) == 4 { + if alias := oracleTnsAliasName(descriptor); alias != "" { + return jdbcURLInfo{Kind: "tns", Database: alias} + } + // 下面的正则按 thin 前缀书写,统一归一后再匹配,因此 oci8 与 thin 共用一套解析。 + normalized := "jdbc:oracle:thin:@" + descriptor + if match := oracleJDBCServiceRegexp.FindStringSubmatch(normalized); len(match) == 4 { return jdbcURLInfo{Kind: "service", Host: match[1], Port: parsePort(match[2]), Database: match[3]} } - if match := oracleJDBCSIDRegexp.FindStringSubmatch(value); len(match) == 4 { + if match := oracleJDBCSIDRegexp.FindStringSubmatch(normalized); len(match) == 4 { return jdbcURLInfo{Kind: "sid", Host: match[1], Port: parsePort(match[2]), Database: match[3]} } - if match := oracleJDBCLegacyRegexp.FindStringSubmatch(value); len(match) == 4 { + if match := oracleJDBCLegacyRegexp.FindStringSubmatch(normalized); len(match) == 4 { return jdbcURLInfo{Kind: "service", Host: match[1], Port: parsePort(match[2]), Database: match[3]} } return jdbcURLInfo{} } +// oracleTnsAliasName 返回 `@` 之后、查询串之前的 TNS 别名;不是别名时返回空串。 +// +// 判定与前端 parseOracleTnsConnectionString 保持一致:别名不含描述符括号、 +// 网络前缀(//)以及路径/端口分隔符(: / \)。 +func oracleTnsAliasName(value string) string { + alias := value + if index := strings.IndexByte(alias, '?'); index >= 0 { + alias = alias[:index] + } + alias = strings.TrimSpace(alias) + if alias == "" || strings.HasPrefix(alias, "(") || strings.HasPrefix(alias, "//") { + return "" + } + if strings.ContainsAny(alias, ":/\\") { + return "" + } + return alias +} + func parsePort(value string) int { port, _ := strconv.Atoi(value) return port diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.go index 2e1fcd221a..40421cf034 100644 --- a/agents/drivers/oracle-go/main_test.go +++ b/agents/drivers/oracle-go/main_test.go @@ -4345,3 +4345,78 @@ func TestRewriteOracleOpaqueObjectExplicitColumnKeepsLinkedAlias(t *testing.T) { t.Fatalf("rewriteOracleSelectSQL() = %s, want %s", sqlText, want) } } + +// OCI 模式的连接串解析:oci8 前缀、TNS 别名与 thin 形式共用同一套规则。 +func TestParseOracleJDBCURLAcceptsOci8FormsAndTnsAliases(t *testing.T) { + cases := []struct { + name string + url string + want jdbcURLInfo + }{ + { + name: "service", + url: "jdbc:oracle:oci8:@//db.example.com:1521/ORCLPDB1", + want: jdbcURLInfo{Kind: "service", Host: "db.example.com", Port: 1521, Database: "ORCLPDB1"}, + }, + { + name: "sid", + url: "jdbc:oracle:oci8:@db.example.com:1521:ORCL", + want: jdbcURLInfo{Kind: "sid", Host: "db.example.com", Port: 1521, Database: "ORCL"}, + }, + { + name: "descriptor", + url: "jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=x)))", + want: jdbcURLInfo{Kind: "descriptor", Descriptor: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=x)))"}, + }, + { + name: "tns alias", + url: "jdbc:oracle:oci8:@ORCLPDB1", + want: jdbcURLInfo{Kind: "tns", Database: "ORCLPDB1"}, + }, + { + name: "tns alias with admin query", + url: "jdbc:oracle:oci8:@ORCLPDB1?TNS_ADMIN=C:/wallets", + want: jdbcURLInfo{Kind: "tns", Database: "ORCLPDB1"}, + }, + { + name: "thin form still parses", + url: "jdbc:oracle:thin:@//db.example.com:1521/ORCLPDB1", + want: jdbcURLInfo{Kind: "service", Host: "db.example.com", Port: 1521, Database: "ORCLPDB1"}, + }, + } + for _, tc := range cases { + if got := parseOracleJDBCURL(tc.url); got != tc.want { + t.Errorf("%s: parseOracleJDBCURL(%q) = %+v, want %+v", tc.name, tc.url, got, tc.want) + } + } +} + +func TestParseOracleJDBCURLRejectsUnknownSchemes(t *testing.T) { + for _, url := range []string{ + "jdbc:postgresql://db/app", + "jdbc:mysql://db:3306/app", + "", + } { + if got := parseOracleJDBCURL(url); got != (jdbcURLInfo{}) { + t.Errorf("parseOracleJDBCURL(%q) = %+v, want the zero value", url, got) + } + } +} + +func TestOracleTnsAliasName(t *testing.T) { + cases := []struct{ in, want string }{ + {"ORCLPDB1", "ORCLPDB1"}, + {"ORCLPDB1?TNS_ADMIN=C:/wallets", "ORCLPDB1"}, + {"ORCLPDB1 ", "ORCLPDB1"}, + {"(DESCRIPTION=(ADDRESS=...))", ""}, + {"//host:1521/svc", ""}, + {"host:1521:orcl", ""}, + {"host/svc", ""}, + {"", ""}, + } + for _, tc := range cases { + if got := oracleTnsAliasName(tc.in); got != tc.want { + t.Errorf("oracleTnsAliasName(%q) = %q, want %q", tc.in, got, tc.want) + } + } +} diff --git a/agents/drivers/oracle-go/oci.go b/agents/drivers/oracle-go/oci.go new file mode 100644 index 0000000000..62dbaa75db --- /dev/null +++ b/agents/drivers/oracle-go/oci.go @@ -0,0 +1,40 @@ +//go:build oci + +// Oracle OCI(thick)支持。 +// +// 这个文件只在带上 `oci` 构建标记时参与编译(目前只发布 Windows 版): +// godror 通过 CGO 调用 Oracle 客户端,构建期需要 Instant Client 的 SDK +// (头文件 + 导入库),运行期只需要 oci.dll —— 由 DBX 注入的 PATH 定位。 +// thin 版本(CGO_ENABLED=0,跨平台)不包含这个文件,也不会引入任何原生依赖。 +// +// 连接串构造在 oci_dsn.go(无构建标记,CI 的常规测试会覆盖)。 + +package main + +import ( + "database/sql" + "time" + + _ "github.com/godror/godror" +) + +// ociBuildEnabled 报告当前二进制是否包含 OCI(thick)支持。 +func ociBuildEnabled() bool { return true } + +// openOCIDB 用 godror(OCI thick 模式)建立连接。 +// +// 连接池参数与 thin 路径保持一致,避免两种驱动在会话数上出现差异。 +func openOCIDB(params connectParams) (*sql.DB, error) { + dsn, err := buildOCIDSN(params) + if err != nil { + return nil, err + } + db, err := sql.Open("godror", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(4) + db.SetMaxIdleConns(1) + db.SetConnMaxLifetime(30 * time.Minute) + return db, nil +} diff --git a/agents/drivers/oracle-go/oci_disabled.go b/agents/drivers/oracle-go/oci_disabled.go new file mode 100644 index 0000000000..adea92f628 --- /dev/null +++ b/agents/drivers/oracle-go/oci_disabled.go @@ -0,0 +1,22 @@ +//go:build !oci + +package main + +import ( + "database/sql" + "errors" +) + +// ociBuildEnabled 报告当前二进制是否包含 OCI(thick)支持: +// thin 版本(默认构建,跨平台、CGO_ENABLED=0)不包含。 +func ociBuildEnabled() bool { return false } + +// openOCIDB 在未带 `oci` 构建标记的二进制里给出明确错误。 +// +// 连接级错误会原样回传前端,因此这里说明清楚该装哪个驱动,而不是抛出一个 +// 难以理解的驱动缺失错误。 +func openOCIDB(params connectParams) (*sql.DB, error) { + return nil, errors.New( + "this Oracle agent build does not include OCI support; install the oracle-oci driver (Windows) to use the OCI (thick) mode", + ) +} diff --git a/agents/drivers/oracle-go/oci_dsn.go b/agents/drivers/oracle-go/oci_dsn.go new file mode 100644 index 0000000000..49a0b5631b --- /dev/null +++ b/agents/drivers/oracle-go/oci_dsn.go @@ -0,0 +1,92 @@ +package main + +import ( + "errors" + "fmt" + "strings" +) + +// OCI(thick)连接的 DSN 构造。 +// +// 这里不导入 godror、也没有构建标记:除字符串拼装外没有任何依赖,因此 +// thin 构建与 CI 的常规 `go test` 都能覆盖这些规则。真正加载 Oracle +// 客户端的部分在 oci.go(构建标记 oci)。 + +// buildOCIDSN 把 DBX 传来的连接信息归一成 godror 的连接串。 +// +// 采用 godror 的 logfmt 形式(含 `connectString=` 即按参数串解析): +// 只有 URL 与 logfmt 形式会解析参数,旧式的 `user/pass@connectString` 不会, +// 而我们需要下传 timezone(godror 要求显式声明连接时区,否则取 TIMESTAMP +// WITH LOCAL TIME ZONE 时无法判断换算基准)。取数批量是 per-statement 选项, +// godror 的 DSN 解析器没有 prefetchRows/fetchArraySize 键,不能放进连接串。 +// +// 进程级设置仍由 DBX 注入的启动环境提供:Instant Client 目录在 PATH 上, +// TNS_ADMIN 指向 tnsnames.ora 所在目录 —— 两者都在 agent 进程启动时确定, +// 连接建立之后无法更改。 +func buildOCIDSN(params connectParams) (string, error) { + target := ociConnectTarget(params) + if target == "" { + return "", errors.New("OCI connection requires a host with a service name, or a TNS alias") + } + fields := []string{ + "connectString=" + ociLogfmtValue(target), + "user=" + ociLogfmtValue(params.Username), + "password=" + ociLogfmtValue(params.Password), + } + // 会话时区由客户端(OCI/NLS)确定,显式告知 godror 以本地时区换算, + // 消除 “SESSIONTIMEZONE 与 SYSTIMESTAMP 不一致” 的告警。 + fields = append(fields, "timezone="+ociLogfmtValue("Local")) + if params.SysDBA { + fields = append(fields, "sysdba=1") + } + return strings.Join(fields, " "), nil +} + +// ociConnectTarget 返回 OCI 连接目标:完整连接描述符或 TNS 别名。 +// +// 优先使用 DBX 下发的连接串(oci8 或 thin 形式,两种都按同一套规则解析), +// 没有连接串时退回 host + port + 服务名,保证手工构造的连接也能用。 +func ociConnectTarget(params connectParams) string { + info := parseOracleJDBCURL(params.ConnectionString) + switch info.Kind { + case "descriptor": + return info.Descriptor + case "tns": + return info.Database + case "service": + return ociDescriptor(info.Host, info.Port, "SERVICE_NAME", info.Database) + case "sid": + return ociDescriptor(info.Host, info.Port, "SID", info.Database) + } + host := strings.TrimSpace(params.Host) + database := strings.TrimSpace(params.Database) + if host == "" || database == "" { + return "" + } + port := params.Port + if port <= 0 { + port = 1521 + } + return ociDescriptor(host, port, "SERVICE_NAME", database) +} + +func ociDescriptor(host string, port int, key, value string) string { + return fmt.Sprintf( + "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d))(CONNECT_DATA=(%s=%s)))", + host, port, key, value, + ) +} + +// ociLogfmtValue 按 logfmt 规则给值加引号并转义反斜杠、引号与换行/制表符。 +// 只做这些可预测的转义(不用 strconv.Quote 的 \xNN/\uNNNN 形式), +// 因为 godror 侧的解码器只认常见的反斜杠转义。 +func ociLogfmtValue(value string) string { + replacer := strings.NewReplacer( + `\`, `\\`, + `"`, `\"`, + "\n", `\n`, + "\r", `\r`, + "\t", `\t`, + ) + return `"` + replacer.Replace(value) + `"` +} diff --git a/agents/drivers/oracle-go/oci_dsn_test.go b/agents/drivers/oracle-go/oci_dsn_test.go new file mode 100644 index 0000000000..1c963702f2 --- /dev/null +++ b/agents/drivers/oracle-go/oci_dsn_test.go @@ -0,0 +1,150 @@ +package main + +import ( + "strings" + "testing" +) + +// 期望的公共尾部:显式时区(godror 的 DSN 解析器没有 prefetchRows/ +// fetchArraySize 键,取数批量是 per-statement 选项,不进连接串) +const ociDSNTail = ` timezone="Local"` + +func TestBuildOCIDSNDerivesDescriptorFromPlainParams(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{ + Host: "db.example.com", + Port: 1522, + Database: "ORCLPDB1", + Username: "scott", + Password: "tiger", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := `connectString="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db.example.com)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)))"` + + ` user="scott" password="tiger"` + ociDSNTail + if dsn != want { + t.Fatalf("dsn = %q, want %q", dsn, want) + } +} + +func TestBuildOCIDSNDefaultsThePort(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{Host: "h", Database: "svc", Username: "u", Password: "p"}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.Contains(dsn, "(PORT=1521)") { + t.Fatalf("dsn = %q, want the default port 1521", dsn) + } +} + +func TestBuildOCIDSNKeepsTheOci8ConnectionString(t *testing.T) { + cases := []struct { + name string + connectionString string + wantTarget string + }{ + { + name: "service", + connectionString: "jdbc:oracle:oci8:@//db.example.com:1521/ORCLPDB1", + wantTarget: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)))", + }, + { + name: "sid", + connectionString: "jdbc:oracle:oci8:@db.example.com:1521:ORCL", + wantTarget: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db.example.com)(PORT=1521))(CONNECT_DATA=(SID=ORCL)))", + }, + { + name: "descriptor", + connectionString: "jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SID=x)))", + wantTarget: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SID=x)))", + }, + { + name: "tns alias", + connectionString: "jdbc:oracle:oci8:@ORCLPDB1", + wantTarget: "ORCLPDB1", + }, + { + name: "thin form is accepted too", + connectionString: "jdbc:oracle:thin:@//db.example.com:1521/ORCLPDB1", + wantTarget: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)))", + }, + } + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{ + ConnectionString: testCase.connectionString, + Username: "u", + Password: "p", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := `connectString="` + testCase.wantTarget + `" user="u" password="p"` + ociDSNTail + if dsn != want { + t.Fatalf("dsn = %q, want %q", dsn, want) + } + }) + } +} + +func TestBuildOCIDSNAddsSysdba(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{ + ConnectionString: "jdbc:oracle:oci8:@ORCLPDB1", + Username: "sys", + Password: "change_on_install", + SysDBA: true, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.HasSuffix(dsn, "sysdba=1") { + t.Fatalf("dsn = %q, want a sysdba=1 suffix", dsn) + } +} + +func TestBuildOCIDSNQuotesCredentials(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{ + ConnectionString: "jdbc:oracle:oci8:@ORCLPDB1", + Username: `do@main\user`, + Password: "pa\"ss\nword", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.Contains(dsn, `user="do@main\\user"`) { + t.Fatalf("dsn = %q, want a quoted, escaped user", dsn) + } + if !strings.Contains(dsn, `password="pa\"ss\nword"`) { + t.Fatalf("dsn = %q, want a quoted, escaped password", dsn) + } +} + +func TestBuildOCIDSNOmitsPerStatementFetchParams(t *testing.T) { + dsn, err := buildOCIDSN(connectParams{ + ConnectionString: "jdbc:oracle:oci8:@ORCLPDB1", + Username: "u", + Password: "p", + URLParams: "prefetch_rows=2000&useSSL=false", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if strings.Contains(dsn, "prefetchRows=") || strings.Contains(dsn, "fetchArraySize=") { + t.Fatalf("dsn = %q, want no per-statement fetch params in the DSN", dsn) + } +} + +func TestBuildOCIDSNRejectsMissingTarget(t *testing.T) { + if _, err := buildOCIDSN(connectParams{Username: "u", Password: "p"}); err == nil { + t.Fatal("expected an error when neither a connection string nor host+service is given") + } +} + +func TestOCIProfileDetection(t *testing.T) { + if !usesOCIProfile(connectParams{DriverProfile: "OCI"}) { + t.Fatal("the oci driver profile must be detected case-insensitively") + } + if usesOCIProfile(connectParams{DriverProfile: "oracle"}) || usesOCIProfile(connectParams{}) { + t.Fatal("plain Oracle connections must keep using the thin driver") + } +} diff --git a/agents/scripts/driver_release_packages_test.py b/agents/scripts/driver_release_packages_test.py index 7773a9cde4..6dc4fe04e3 100644 --- a/agents/scripts/driver_release_packages_test.py +++ b/agents/scripts/driver_release_packages_test.py @@ -9,9 +9,74 @@ import zipfile from pathlib import Path from build_driver_zips import build_driver_zips, remove_raw_driver_artifacts +from validate_agents import CRATE_NATIVE_AGENT_MODULES, NATIVE_ONLY_AGENT_MODULES from version_agent_artifacts import NATIVE_DRIVERS, version_agent_artifacts +AGENTS_ROOT = Path(__file__).resolve().parent.parent + + +def native_only_modules() -> set[str]: + declared = { + name + for name, relative in {**NATIVE_ONLY_AGENT_MODULES, **CRATE_NATIVE_AGENT_MODULES}.items() + if (AGENTS_ROOT / relative).exists() + } + return declared + + +class NativeReleaseCoverageTest(unittest.TestCase): + """Guards the hand-maintained native module list in the release packaging. + + `version_agent_artifacts` renames `dbx-agent--` into the + versioned name the registry generator looks for. A native module missing from + its list is not a loud failure: the raw artifact is dropped, the module never + reaches `agent-registry.json`, and the driver simply disappears from the app. + `oracle-oci` was lost exactly that way, so cross-check the list against the + modules `validate_agents` treats as native-only rather than trusting it to be + maintained by hand. + """ + + def test_lists_every_native_only_module(self) -> None: + declared = native_only_modules() + listed = set(NATIVE_DRIVERS) + + self.assertEqual( + sorted(listed - declared), + [], + "NATIVE_DRIVERS lists entries validate_agents no longer declares native-only", + ) + self.assertEqual( + sorted(declared - listed), + [], + "native-only modules missing from version_agent_artifacts.NATIVE_DRIVERS", + ) + + def test_every_listed_module_has_a_version(self) -> None: + versions = json.loads((AGENTS_ROOT / "versions.json").read_text(encoding="utf-8")) + + missing = sorted(name for name in NATIVE_DRIVERS if not versions.get(name)) + + self.assertEqual(missing, [], "native modules without a versions.json entry") + + def test_versions_platform_limited_native_artifacts(self) -> None: + # A module published for one platform only (Oracle OCI is Windows x64) + # must still be versioned; platforms it does not publish are skipped. + with tempfile.TemporaryDirectory() as temp_dir: + release_dir = Path(temp_dir) + source = release_dir / "dbx-agent-oracle-oci-windows-x64.exe" + source.write_bytes(b"MZtest-oracle-oci-agent") + versions = {driver: "0.1.0" for driver in NATIVE_DRIVERS} + versions["oracle-oci"] = "0.1.7" + + renamed = version_agent_artifacts(release_dir, versions) + versioned = release_dir / "dbx-agent-oracle-oci-0.1.7-windows-x64.exe" + + self.assertEqual(renamed, [versioned]) + self.assertFalse(source.exists()) + self.assertEqual(versioned.read_bytes(), b"MZtest-oracle-oci-agent") + + class DriverReleasePackagesTest(unittest.TestCase): def test_builds_java_and_platform_specific_native_driver_tar_zstd_packages(self) -> None: with tempfile.TemporaryDirectory() as temp_dir: @@ -41,6 +106,7 @@ class DriverReleasePackagesTest(unittest.TestCase): versions = { "h2": "0.2.5", "oracle": "0.1.10", + "oracle-oci": "0.1.0", "xugu": "0.1.20", "kingbase": "0.1.34", "iotdb": "0.1.30", diff --git a/agents/scripts/validate_agents.py b/agents/scripts/validate_agents.py index cad121643f..ea771ddd11 100644 --- a/agents/scripts/validate_agents.py +++ b/agents/scripts/validate_agents.py @@ -18,6 +18,7 @@ NATIVE_ONLY_AGENT_MODULES = { "hive": "drivers/hive-go", "argo": "drivers/argo-go", "oracle": "drivers/oracle-go", + "oracle-oci": "drivers/oracle-go", "kingbase": "drivers/kingbase-go", "iotdb": "drivers/iotdb", "neo4j": "drivers/neo4j-go", diff --git a/agents/scripts/validate_agents_test.py b/agents/scripts/validate_agents_test.py index 1604ee287f..58926b576a 100644 --- a/agents/scripts/validate_agents_test.py +++ b/agents/scripts/validate_agents_test.py @@ -171,7 +171,7 @@ class ValidateAgentsTest(unittest.TestCase): ): (root / "drivers" / driver).mkdir(parents=True) (root / "versions.json").write_text( - json.dumps({"h2": "0.1.0", "cassandra": "0.1.0", "hive": "0.1.0", "oracle": "0.1.0", "kingbase": "0.1.0", "iotdb": "0.1.0", "neo4j": "0.1.0", "vastbase": "0.1.0", "xugu": "0.1.0", "rabbitmq": "0.1.0", "rocketmq": "0.1.0", "zookeeper": "0.1.0", "tdengine": "0.1.0"}), + json.dumps({"h2": "0.1.0", "cassandra": "0.1.0", "hive": "0.1.0", "oracle": "0.1.0", "oracle-oci": "0.1.0", "kingbase": "0.1.0", "iotdb": "0.1.0", "neo4j": "0.1.0", "vastbase": "0.1.0", "xugu": "0.1.0", "rabbitmq": "0.1.0", "rocketmq": "0.1.0", "zookeeper": "0.1.0", "tdengine": "0.1.0"}), encoding="utf-8", ) diff --git a/agents/scripts/version_agent_artifacts.py b/agents/scripts/version_agent_artifacts.py index 238f7abdeb..99cc882b78 100644 --- a/agents/scripts/version_agent_artifacts.py +++ b/agents/scripts/version_agent_artifacts.py @@ -4,7 +4,14 @@ import json from pathlib import Path -NATIVE_DRIVERS = ("cassandra", "hive", "argo", "oracle", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "duckdb", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2", "sqlite-worker") +# Every module that publishes platform-native agent binaries, keyed by its +# artifact name. `oracle-oci` is built from the same `oracle-go` module as +# `oracle` with the `oci` build tag, so it needs its own entry here: the release +# job stages it as `dbx-agent-oracle-oci-`, and only a versioned name +# is picked up by the registry generator. Platforms it does not publish are +# skipped by `rename_artifact`, which keeps Windows-only drivers like +# `oracle-oci` working without special casing. +NATIVE_DRIVERS = ("cassandra", "hive", "argo", "oracle", "oracle-oci", "xugu", "kingbase", "iotdb", "neo4j", "nebula", "vastbase", "duckdb", "rabbitmq", "rocketmq", "zookeeper", "tdengine", "etcd", "etcd2", "sqlite-worker") PLATFORMS = ( "macos-aarch64", "macos-x64", diff --git a/agents/versions.json b/agents/versions.json index 4d8a9876cf..783d623646 100644 --- a/agents/versions.json +++ b/agents/versions.json @@ -27,6 +27,7 @@ "nebula": "0.1.0", "oceanbase-oracle": "0.1.68", "oracle": "0.1.66", + "oracle-oci": "0.1.0", "snowflake": "0.1.71", "sqlite-worker": "0.1.5", "spanner": "0.1.24", diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue index 97ffb7e0ba..40cf0451b7 100644 --- a/apps/desktop/src/components/connection/ConnectionDialog.vue +++ b/apps/desktop/src/components/connection/ConnectionDialog.vue @@ -71,6 +71,7 @@ import { } from "@/lib/plugins/frontendPlugin"; import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation"; import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { isWindows } from "@/lib/backend/platform"; import { applyMeilisearchBasePathToExternalConfig, applyParsedConnectionUrl, normalizeMongoConnectionString, parseConnectionUrl } from "@/lib/connection/connectionUrl"; import { hasXuguConnectionDatabase } from "@/lib/connection/xuguDatabase"; import { DEFAULT_QUERY_TIMEOUT_SECS, MAX_CONNECT_TIMEOUT_SECS, MAX_QUERY_TIMEOUT_SECS } from "@/lib/connection/timeoutLimits"; @@ -141,6 +142,7 @@ import { Pipette, Plus, RefreshCw, + Save, Search, ShieldAlert, ShieldCheck, @@ -422,6 +424,8 @@ const defaultForm = (): ConnectionForm => ({ client_cert_path: "", client_key_path: "", sysdba: false, + oracle_oci_nls_lang: "", + oracle_oci_tns_admin: "", oracle_connection_type: "service_name", connection_string: undefined, jdbc_driver_class: undefined, @@ -807,6 +811,8 @@ const appliedConnectionUrlInput = ref(""); const meilisearchHostInput = ref(""); const appliedMeilisearchHostInput = ref(""); const oracleTnsAdminPath = ref(""); +/** 每次进入 OCI 模式只提醒一次 Instant Client 目录,避免反复点“测试”时刷屏。 */ +const oracleOciClientPathReminded = ref(false); const oceanbaseSubMode = ref<"mysql" | "oracle">("mysql"); const h2ConnectionMode = ref("file"); const dremioConnectionMode = ref("legacy"); @@ -3105,6 +3111,8 @@ watch( idle_timeout_secs: config.idle_timeout_secs ?? 60, keepalive_interval_secs: config.keepalive_interval_secs ?? 30, sysdba: config.sysdba || isOracleSysUser(config), + oracle_oci_nls_lang: config.oracle_oci_nls_lang || "", + oracle_oci_tns_admin: config.oracle_oci_tns_admin || "", oracle_connection_type: config.oracle_connection_type || "service_name", connection_string: config.connection_string, jdbc_driver_class: config.db_type === "sundb" ? sundbJdbcDriverClass(config) : config.jdbc_driver_class, @@ -3467,6 +3475,156 @@ function switchH2DriverProfile(profile: "h2" | "h2-v1" | "h2-v2" | "h2-v3" | "h2 resetTestState(); } +/** + * Oracle driver mode: thin (go-ora agent, default) or OCI (thick driver, + * requires a globally configured Oracle Instant Client). The oci.dll path + * lives in the global settings on purpose — one configuration is shared by + * every OCI connection, and new OCI connections backfill it automatically. + */ +// OCI(thick)驱动目前只发布 Windows x64 产物:非 Windows 平台不显示模式切换, +// 避免用户选到无法安装的驱动。已保存的 OCI 连接仍按原样打开(连接时会得到 +// 明确的“驱动未安装”错误),并把 Thin 按钮留在原地便于切回。 +const oracleOciDriverSelectable = isWindows(); + +function switchOracleDriverMode(mode: "thin" | "oci") { + form.value.driver_profile = mode === "oci" ? "oci" : "oracle"; + oracleOciClientPathReminded.value = false; + resetTestState(); +} + +function persistOracleOciClientPath() { + void settingsStore.updateEditorSettings({ + oracleOciClientPath: settingsStore.editorSettings.oracleOciClientPath, + }); +} + +/** + * NLS_LANG is a per-connection override: an empty value follows the global + * default, a filled value makes this connection own a dedicated agent process + * (the variable is process-scoped for OCI). The dropdown lists the common + * client character sets; the save button promotes the current value to the + * global default for reuse. + */ +const OCI_NLS_LANG_FOLLOW_GLOBAL = "__follow_global__"; +const ORACLE_NLS_LANG_OPTIONS = [ + "AMERICAN_AMERICA.AL32UTF8", + "AMERICAN_AMERICA.UTF8", + "AMERICAN_AMERICA.WE8ISO8859P1", + "AMERICAN_AMERICA.ZHS16GBK", + "SIMPLIFIED CHINESE_CHINA.AL32UTF8", + "SIMPLIFIED CHINESE_CHINA.ZHS16GBK", + "TRADITIONAL CHINESE_TAIWAN.AL32UTF8", + "TRADITIONAL CHINESE_TAIWAN.ZHT16MSWIN950", + "JAPANESE_JAPAN.AL32UTF8", + "JAPANESE_JAPAN.JA16SJIS", + "KOREAN_KOREA.AL32UTF8", + "KOREAN_KOREA.KO16MSWIN949", +] as const; + +const oracleOciNlsLangSelection = computed(() => (form.value.oracle_oci_nls_lang?.trim() ? form.value.oracle_oci_nls_lang.trim() : OCI_NLS_LANG_FOLLOW_GLOBAL)); + +/** A stored value that predates the preset list must stay selectable. */ +const oracleOciNlsLangCustomValue = computed(() => { + const value = form.value.oracle_oci_nls_lang?.trim(); + if (!value) return null; + return (ORACLE_NLS_LANG_OPTIONS as readonly string[]).includes(value) ? null : value; +}); + +const oracleOciNlsLangPlaceholder = computed(() => { + const globalValue = settingsStore.editorSettings.oracleOciNlsLang?.trim(); + return globalValue ? t("connection.oracleOciNlsLangPlaceholderGlobal", { value: globalValue }) : t("connection.oracleOciNlsLangPlaceholder"); +}); + +/** Names the global default in effect, so promoting a value becomes visible in place. */ +const oracleOciNlsLangFollowGlobalLabel = computed(() => { + const globalValue = settingsStore.editorSettings.oracleOciNlsLang?.trim(); + return globalValue ? t("connection.oracleOciNlsLangFollowGlobalValue", { value: globalValue }) : t("connection.oracleOciNlsLangFollowGlobal"); +}); + +function onOciNlsLangSelected(value: unknown) { + const selected = typeof value === "string" ? value : ""; + form.value.oracle_oci_nls_lang = selected === OCI_NLS_LANG_FOLLOW_GLOBAL ? "" : selected; + resetTestState(); +} + +async function saveOciNlsLangAsGlobalDefault() { + const value = form.value.oracle_oci_nls_lang?.trim(); + if (!value) { + toast(t("connection.oracleOciNlsLangSaveGlobalEmpty"), 3000); + return; + } + try { + await settingsStore.updateEditorSettingsAndPersist({ oracleOciNlsLang: value }); + toast(t("connection.oracleOciNlsLangSavedGlobal", { value }), 3000); + } catch (error) { + toast(error instanceof Error ? error.message : String(error), 5000); + } +} + +/** + * 连接级 TNS_ADMIN(tnsnames.ora / sqlnet.ora / 钱包目录):留空跟随全局默认, + * 填写后本连接使用自己的目录——ADB 钱包、sqlnet.ora 网络选项因此不依赖 + * TNS 连接方式。目录同样是进程级的,随 agent 启动注入。 + */ +const oracleOciTnsAdminPlaceholder = computed(() => { + const globalValue = settingsStore.editorSettings.oracleOciTnsAdmin?.trim(); + return globalValue ? t("connection.oracleOciTnsAdminPlaceholderGlobal", { value: globalValue }) : t("connection.oracleTnsAdminPlaceholder"); +}); + +async function saveOciTnsAdminAsGlobalDefault() { + const value = form.value.oracle_oci_tns_admin?.trim(); + if (!value) { + toast(t("connection.oracleOciTnsAdminSaveGlobalEmpty"), 3000); + return; + } + try { + await settingsStore.updateEditorSettingsAndPersist({ oracleOciTnsAdmin: value }); + toast(t("connection.oracleOciTnsAdminSavedGlobal", { value }), 3000); + } catch (error) { + toast(error instanceof Error ? error.message : String(error), 5000); + } +} + +async function browseOciTnsAdminDirectory() { + if (!isTauriRuntime()) { + toast(t("connection.oraclePathPickerDesktopOnly")); + return; + } + const { open } = await import("@tauri-apps/plugin-dialog"); + const selected = await open({ + title: t("connection.oracleTnsAdminBrowse"), + directory: true, + multiple: false, + }); + if (typeof selected === "string") { + form.value.oracle_oci_tns_admin = selected; + resetTestState(); + } +} + +/** + * Prompts for the Oracle Instant Client directory. The desktop shell is the + * only runtime that can resolve a local path, so the picker explains itself + * on the web build instead of silently doing nothing. + */ +async function browseOciClientDirectory() { + if (!isTauriRuntime()) { + toast(t("connection.oraclePathPickerDesktopOnly")); + return; + } + const { open } = await import("@tauri-apps/plugin-dialog"); + const selected = await open({ + title: t("connection.oracleOciPathBrowse"), + directory: true, + multiple: false, + }); + if (typeof selected === "string") { + settingsStore.editorSettings.oracleOciClientPath = selected; + persistOracleOciClientPath(); + resetTestState(); + } +} + const damengDriverMode = computed(() => damengDriverModeForConfig(form.value)); const isDamengCustomDriver = computed(() => form.value.db_type === "dameng" && damengDriverMode.value === "custom"); @@ -4718,6 +4876,11 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi // service, SID, and descriptor JDBC strings exactly as before. config.connection_string = undefined; } + if (config.db_type === "oracle" && config.driver_profile === "oci" && !settingsStore.editorSettings.oracleOciClientPath?.trim() && !oracleOciClientPathReminded.value) { + // 非阻断提醒:没有配置 Instant Client 目录时,agent 进程只能依赖系统 PATH 里已有的 oci.dll。 + oracleOciClientPathReminded.value = true; + toast(t("connection.oracleOciClientPathMissing"), 5000); + } normalizeConnectionTimeouts(config, editGlobalConnectTimeoutSecs.value, editGlobalQueryTimeoutSecs.value); if (config.db_type === "manticoresearch") { config.url_params = ""; @@ -4947,9 +5110,25 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi if (config.db_type !== "oracle") { config.sysdba = undefined; config.oracle_connection_type = undefined; + config.oracle_oci_nls_lang = undefined; + config.oracle_oci_tns_admin = undefined; } else { config.sysdba = !!config.sysdba || isOracleSysUser(config); config.oracle_connection_type = config.oracle_connection_type || "service_name"; + // Driver mode is encoded as the driver profile so the agent router picks + // the OCI (thick) agent; everything else stays on the thin agent. + if (config.driver_profile === "oci") { + config.driver_label = "Oracle (OCI)"; + config.oracle_oci_nls_lang = config.oracle_oci_nls_lang?.trim() || undefined; + config.oracle_oci_tns_admin = config.oracle_oci_tns_admin?.trim() || undefined; + } else { + // Only default when empty: saved legacy profiles (oracle-legacy, + // oracle-10g) must survive edits untouched. + if (!config.driver_profile) config.driver_profile = "oracle"; + config.driver_label = "Oracle"; + config.oracle_oci_nls_lang = undefined; + config.oracle_oci_tns_admin = undefined; + } } if (config.db_type !== "redis") { config.redis_connection_mode = undefined; @@ -6639,12 +6818,17 @@ async function browseHiveKerberosFile(target: "krb5" | "jaas") { } async function browseOracleTnsNamesFile() { - if (!isTauriRuntime()) return; + // TNS_ADMIN is a directory; accept a folder pick. Desktop-only, so the web + // build gets an explanation instead of a silent no-op. + if (!isTauriRuntime()) { + toast(t("connection.oraclePathPickerDesktopOnly")); + return; + } const { open } = await import("@tauri-apps/plugin-dialog"); const selected = await open({ title: t("connection.oracleTnsAdminBrowse"), + directory: true, multiple: false, - filters: [{ name: "Oracle TNS names", extensions: ["ora"] }], }); if (typeof selected === "string") { oracleTnsAdminPath.value = normalizeOracleTnsAdminPath(selected); @@ -8938,11 +9122,99 @@ function openExternalUrl(url: string) { +
+ +
+ + +
+
+ + +
- +