Skip to content
项目

关于

The goal of the pure Go driver is to deliver an official, robust and stable driver for Oracle Database.

数据与分析

这些数字如何统计

可以做什么

  • Native Go implementation of Go's sql/driver package
  • Supports Oracle Database versions: 19c and higher
  • Data source: supports Connect Descriptor and EZConnect
  • Protocols: TCP and TCPS

实测星标增长

24小时
0
7天
0
15天
+1
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

Oracle Database Driver for Go

Oracle Database Driver for Go is a native Go driver for Go's database/sql package. It supports Oracle Database versions 19c and higher.

Features

  • Native Go implementation of Go's sql/driver package
  • Supports Oracle Database versions: 19c and higher
  • Data source: supports Connect Descriptor and EZConnect
  • Protocols: TCP and TCPS
  • PL/SQL In/Out parameters (using sql.Out)
  • Statements with in parameters and out parameters (using sql.Out)
  • BLOB support using prefetch and returning []byte
  • CLOB support using prefetch and returning string
  • Native Oracle JSON support via github.com/oracle/go-oracledb/v26/oracle/datatype/json
  • Return query results from PL/SQL REF_CURSORS
  • Authentication:
    • username and password authentication
    • token authentication
  • Transactions: standard and sessionless
  • Inband notifications
  • Oracle LONG and LONG RAW support with materialized Go values

Installation

Run:

go get github.com/oracle/go-oracledb/v26@latest

Examples

For end-to-end examples, go to the examples subdirectory.

Usage

Oracle Database Driver for Go is an implementation of Go's database/sql/driver interface. Import the driver to use the full database/sql API.

The driver name is "oracledb"[^1], and the Data Source Name supports both Easy Connect and Connect Descriptor.

  db, err := sql.Open("oracledb", "myuser/mypassword@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=my_host)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=my_service_name)))")
  if err != nil {
    return nil, err
  }
  rows, err := db.QueryContext(context.Background(), "SELECT 1 FROM DUAL")
  if err != nil {
    log.Fatal(err)
  }
  defer rows.Close()

  var val int
  if rows.Next() {
    if err := rows.Scan(&val); err != nil {
      log.Fatal(err)
    }
  }

Documentation

Data Source Name as a string

When specified as a string, the format of the Data Source Name is:

[username/password@]<connection_string>[?<query_string>]

The "connection string" format can be either "EZConnect":

myuser/mypassword@tcps://my_host:1521/my_service_name?transport_connect_timeout=10

Or TNS Connect Descriptor:

Note that query parameters are not supported when using the TNS format.

myuser/mypassword@(DESCRIPTION=(ADDRESS=(HOST=my_host)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=my_service_name)))

Driver configuration

Public API contract

Application code should import and depend on github.com/oracle/go-oracledb/v26/oracle.

The driver supports several sources of configuration. They apply in the following order of precedence:

  1. Properties in the Data Source Name.
  2. Environment variables.
  3. CLI flags.
  4. Configuration set in the Oracle Connector.

The list of supported configuration items is the fields of the oracle.OracleDriverConfig struct. This type can be used to create a new Oracle connector. All Easy Connect parameters are supported by oracle.OracleConnectionProperties.

Configuration item naming

Configuration item names are prefixed with "oracle.go", e.g. "oracle.go.connectDescriptor". When specified as an environment variable, dots are replaced by underscores and the name is made in uppercase. As an example, the property oracle.foo.bar maps to the ORACLE_FOO_BAR environment variable.

There is a direct mapping of oracle.OracleDriverConfig fields and nested structs' fields to configuration properties and vice versa.

As an example, let's look at the connection descriptor:

type OracleDriverConfig struct {
  //...
  ConnectDescriptor      string 
  //...
}

This configuration field maps:

  1. As a CLI flag, e.g. -oracle.go.ConnectDescriptor="../".
  2. As an environment variable, e.g. ORACLE_GO_CONNECTDESCRIPTOR="...".

Another example using failover connection property:

connectorConfig := oracle.NewOracleDriverConfig()
connectorConfig.ConnectionProperties.Failover=true

This configuration field maps:

  1. As a CLI flag, e.g. -oracle.go.DriverProperties.Failover="true".
  2. As an environment variable, e.g. ORACLE_GO_DRIVERPROPERTIES_FAILOVER="true".
  3. As a query parameter, e.g. oracle.go.DriverProperties.Failover="true"
Easy Connect plus query parameters

For compatibility with other Oracle drivers, the Easy Connect parameter names set in the Data Source Name query parameters are the ones listed here: https://docs.oracle.com/en/database/oracle/oracle-database/26/netag/support-easy-connect-plus.html As an example, when the failover property oracle.go.ConnectionProperties.Failover is set as a query parameter, it translates to myuser/mypassword@//my_host:1521/my_service_name?failover=true.

Display configuration

The oracle.OracleDriverConfig struct implements the Go Stringer interface.

 conf := oracle.NewOracleDriverConfig()
 fmt.Printf("Oracle configuration: [%v]", conf)

The -oracledb-config-help flag can also be set in the application. When set, all available configuration flags are displayed on STDOUT.

Configuration types

The driver uses the following Go types for configuration: oracle.OracleDriverConfig, oracle.OracleLoggingConfig, oracle.OracleCredentials, oracle.OracleNLSParameters, oracle.OracleDriverProperties, and oracle.OracleConnectionProperties. Use oracle.NewOracleDriverConfig() and oracle.NewOracleLoggingConfig() to create these objects.

These functions are the only supported way to obtain new instances, and they ensure each struct is properly initialized with default values before use. The oracle.OracleDriverConfig type has the Validate() method which validates that all fields and all nested type fields are set with valid values.

Programmatic configuration interfaces

Connector Configuration

When specific configuration is required, sql.OpenDB can be used. The required connector is then created with the oracle.NewOracleDriverConfig() API. Once the oracle.OracleDriverConfig instance is created and populated with custom values, the Validate method will be called before creating connectors. Note that when this API is used, credentials must be provided using the Credentials struct.

  connectorConfig := oracle.NewOracleDriverConfig()
  connectorConfig.ConnectDescriptor = "(description=(address=(protocol=tcps)(host=127.0.0.1)(port=1521))(connect_data=(service_name=freepdb1)))"
  connectorConfig.Credentials.User = "myuser"
  connectorConfig.Credentials.Password = "mypassword"

  // Optional validation operation. 
  err  := connectorConfig.Validate()
	if err != nil {
		// ...
	}

  connector, err := oracle.NewOracleConnector(connectorConfig)
  if err != nil {
	// ...
  }
  db := sql.OpenDB(connector)
  rows, err := db.QueryContext(context.Background(), "SELECT 1 FROM DUAL")
  if err != nil {
	// ...
  }
  defer rows.Close()
  // ... 
Logging Configuration

The driver logging is configured by using the ApplyDriverLoggingConfig API. The configuration items are set by assigning an oracle.OracleLoggingConfig struct. The configuration items are:

  1. Level: The logging level as a string. Should be one of the slog.Level.
  2. Destination: The destination of the logging, it can be a file path, "STDOUT", "STDERR" or "NULL".
  3. IncludeSensitive: Is sensitive information allowed in the logs ?
  4. Truncate: Does the driver truncate the file at startup ?

ApplyDriverLoggingConfig can be called more than once when the logging configuration needs to change during the application lifetime. Note that this method is not thread-safe.

Example :

    loggingConfig := oracle.NewOracleLoggingConfig()
    loggingConfig.Destination = "STDOUT"
    loggingConfig.Level = "DEBUG"
    oracle.GetDefaultDriver().ApplyDriverLoggingConfig(loggingConfig)

Example using flags:

    /bin/go -oracle.go.logging.Level=DEBUG ....
Environment variables

Besides driver properties, here is the list of environment variables that can be set.

  • ORACLE_GO_DRIVER_DEBUG_PACKETS activates dumps of exchanged packets (requires sensitive logging parameter to be enabled)

Errors

Errors are returned as oracle.SQLError which implements Go's Error interface and adds an ErrorCode() string function that allows to retrieve the error code which will be either "ORA-XXXXX" for Oracle Database errors, or "OGD-XXXXX" for driver errors.

  db, err := sql.Open("oracledb", "myuser/mypassword@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=my_host)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=my_service_name)))")
  if err != nil {
    if sqlError, ok := err.(oracle.SQLError); ok {
      if sqlError.ErrorCode() == string(oracle.InvalidCredential) {
        log.Fatal("Invalid username or password")
      }
    }
  }

Data-type support

Character and Text Types

Oracle Type Driver returns
CHAR string
NCHAR string
VARCHAR2 string
NVARCHAR2 string
CLOB string
NCLOB string

Numeric Types

Oracle NUMBER Driver returns
NUMBER(p,0) int64
NUMBER(p,s) string
NUMBER (unknown scale) string
FLOAT float64
BINARY_FLOAT float32 → float64
BINARY_DOUBLE float64

Important
Mapping NUMBER to float64 by default is discouraged due to precision loss.
Use string for NUMBER values that exceed the range or precision of Go's numeric types, such as integers outside the int64 range. This preserves the value and lets users choose an appropriate representation.


Date and Time Types

Oracle Type Driver returns
DATE time.Time
TIMESTAMP time.Time
TIMESTAMP WITH TIME ZONE time.Time
TIMESTAMP WITH LOCAL TIME ZONE time.Time
INTERVAL YEAR TO MONTH string
INTERVAL DAY TO SECOND string

Binary and RAW Types

Oracle Type Driver returns
RAW []byte
BLOB []byte

LONG and LONG RAW Types

Oracle type Query result Bind value Recommended replacement
LONG string datatype.Long CLOB
LONG RAW []byte datatype.LongRaw BLOB

Use datatype.Long and datatype.LongRaw from github.com/oracle/go-oracledb/v26/oracle/datatype to bind these Oracle types. Ordinary Go string and []byte binds use their regular Oracle types.

LONG and LONG RAW are materialized as complete Go values; the driver does not stream them. The per-value limit is 2,147,483,647 bytes (2 GiB - 1) and applies to the value buffered by the driver. It does not guarantee that the process has that amount of memory available. The driver currently buffers fetched rows eagerly, so total memory use can grow with the number and size of returned rows.

Oracle PL/SQL limits LONG and LONG RAW variables to 32,760 bytes. A value larger than this cannot be retrieved from a LONG or LONG RAW column into a corresponding PL/SQL variable. See Oracle PL/SQL data types.

Multi-row UPDATE operations with LONG or LONG RAW bind values are not supported yet.


Boolean Types

Oracle Type Driver returns Supported values
SQL BOOLEAN (23ai) bool true, false
NUMBER(1) bool 0 and 1
VARCHAR2 bool 'TRUE' and 'FALSE'

Advanced and Complex Types

JSON

Oracle Database JSON type support requires Oracle Database 21c or higher.

  • Fetch Oracle JSON into oracle/datatype/json.JSON.
  • Bind existing JSON text with oracle/datatype/json.JSONString.
  • Bind supported Go values with oracle/datatype/json.JSON.

See the JSON guide for binding, fetching, lazy access, conversion options, and null handling. For an example of JSON usage, see the JSON example.

Oracle Type Driver returns
JSON (21c+) oracle/datatype/json.JSON

Unsupported Column Types

The driver does not yet support all Oracle Database data types. The types below are examples of unsupported types.

  • LONG
  • LONG RAW
  • ROWID
  • UROWID
  • BFILE
  • VECTOR
  • XMLType
  • Collections

This list is not exhaustive. Support for additional data types will continue to be added in future releases.


Help

Are you having trouble with Oracle Database Driver for Go? We want to help!

For help programming with Oracle Oracle Database Driver for Go, ask questions on Stack Overflow tagged with go-oracledb. The development team monitors Stack Overflow regularly.

Issues may be opened as described in our contribution guide.

Security

Please consult the security guide for our responsible security vulnerability disclosure process

Contributing

See CONTRIBUTING

[^1]: "oracledb" was previously used by go-oracledb driver which is no longer maintained.

License

Copyright (c) 2026 Oracle and/or its affiliates. Released under the Universal Permissive License v1.0 as shown at https://oss.oracle.com/licenses/upl/.

探索相关项目

加载中…