feat(oracle): support oci thick connections via windows agent

This commit is contained in:
根正苗红的社会主义接班人 authored and GitHub committed 2026-10-01 04:07:15 +08:00
1 parent a1e2d39ed3
commit 8d9e2dc49f
92 files changed
+2551 -143

No files matched your search

+36
View File
@@ -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`.
+12 -1
View File
@@ -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
)
+24
View File
@@ -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=
+52 -5
View File
@@ -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
+75
View File
@@ -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)
}
}
}
+40
View File
@@ -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
}
+22
View File
@@ -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",
)
}
+92
View File
@@ -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) + `"`
}
+150
View File
@@ -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")
}
}