dsn

package
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2020 License: Apache-2.0, BSD-3-Clause, MIT, + 1 more Imports: 12 Imported by: 20

README

Connect

Connect to Oracle Database using sql.Open("godror", dataSourceName) where dataSourceName contains options such as the user credentials, the database connection string, and other configuration settings.
It should be a logfmt-encoded parameter list.
For example:

db, err := sql.Open("godror", `user="scott" password="tiger" connectString="dbhost:1521/orclpdb1" 
	poolSessionTimeout=42s configDir=/tmp/admin 
	heterogeneousPool=false standaloneConnection=false`)

Other connection and driver options can also be used:

db, err := sql.Open("godror", `user="scott" password="tiger" 
	connectString="dbhost:1521/orclpdb1?connect_timeout=2" 
	poolSessionTimeout=42s configDir="/opt/oracle/configdir" 
	heterogeneousPool=false standaloneConnection=false`)

All godror parameters (see here) should also be specified logfmt-ted.

You can use ConnectionParams to properly build such a string:

var P godror.ConnectionParams
P.Username, P.Password = "scott", godror.NewPassword("tiger")
P.ConnectString = "dbhost:1521/orclpdb1?connect_timeout=2"
P.SessionTimeout = 42 * time.Second
P.SetSessionParamOnInit("NLS_NUMERIC_CHARACTERS", ",.")
P.SetSessionParamOnInit("NLS_LANGUAGE", "FRENCH")
fmt.Println(P.StringWithPassword())
db := sql.OpenDB(godror.NewConnector(P))

Or if you really want to build it "by hand", use connstr.AppendLogfmt:

var buf strings.Builder
connstr.AppendLogfmt(&buf, "user", "scott")
connstr.AppendLogfmt(&buf, "password", "tiger")
connstr.AppendLogfmt(&buf, "connectString", "dbhost:1521/orclpdb1?connect_timeout=2")
fmt.Println(buf.String())

Connection Strings

The connectString parameter can be one of:

  • An Easy Connect String

    Easy Connect strings like the one shown above are most convenient to use. The syntax allows a number of options to be set without requiring an external tnsnames.ora configuration file. A more complex example usable with Oracle Client libraries 19c or later is:

    connectString="tcps://salesserver1:1521/sales.us.example.com?ssl_server_cert_dn=\"cn=sales,cn=Oracle Context Server,dc=us,dc=example,dc=com\"&sdu=8128&connect_timeout=60"
    

    Common options are connect_timeout to return an error if connection takes too long, and expire_time to make sure idle connections are not closed by firewalls.

    The technical article Oracle Database 19c Easy Connect Plus Configurable Database Connection Syntax contains more information.

  • An Oracle Net Connect Descriptor String

    Full descriptors can be used, such as connectString="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=dbhost.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))"

  • An Oracle Net Service Name

    Connect Descriptor Strings are commonly stored in a tnsnames.ora file and associated with a Net Service Name. This name can be used directly for connectString. For example, given a tnsnames.ora file with the following contents:

       ORCLPDB1 =
          (DESCRIPTION =
             (ADDRESS = (PROTOCOL = TCP)(HOST = dbhost.example.com)(PORT = 1521))
             (CONNECT_DATA =
                (SERVER = DEDICATED)
                (SERVICE_NAME = orclpdb1)
             )
          )
    

    then you could connect using connectString=ORCLPDB1

    See "Optional Oracle Net Configuration Files" below.

Optional Oracle Net Configuration Files

Optional Oracle Net configuration files are used by the Oracle Client libraries during the first call to sql.Open. The directory containing the files can be specified in the sql.Open() data source name with the configDir option.

The common files are:

  • tnsnames.ora: A configuration file that defines databases aliases for establishing connections.

  • sqlnet.ora: A profile configuration file that may contain information on features such as connection failover, network encryption, logging, and tracing. See Oracle Net Services Reference for more information.

The files should be in a directory accessible to godror, not on the database server host.

If the configDir connection option is not used, then a search heuristic is used to find the directory containing the files. The search includes:

  • $TNS_ADMIN
  • /opt/oracle/instantclient_19_8/network/admin if Instant Client is in /opt/oracle/instantclient_19_8.
  • /usr/lib/oracle/19.8/client64/lib/network/admin if Oracle 19.8 Instant Client RPMs are used on Linux.
  • $ORACLE_HOME/network/admin if godror is using libraries from a database installation.

Oracle Session Pooling

Set standaloneConnection=0- this is the default.
The old advice of setting db.SetMaxIdleConns(0) are obsolete with Go 1.14.6.
It does no harm, but the revised connection pooling (synchronous ResetSession before pooling the connection) eliminates the need for it.

To use heterogeneous pools, set heterogeneousPool=1 and provide the username and password through godror.ContextWithUserPassw or godror.ContextWithParams.

Backward compatibility

For backward compatibility, you can still provide ANYTHING as the dataSourceName, if it is one line, and is not logfmt-encoded, then it will be treated as a connectString. So

  • scott@tcps://salesserver1:1521/sales.us.example.com?ssl_server_cert_dn="cn=sales,cn=Oracle Context Server,dc=us,dc=example,dc=com"&sdu=8128&connect_timeout=60
  • scott/tiger@salesserver1/sales.us.example.com
  • oracle://scott:tiger@salesserver1/sales.us.example.com&poolSessionTimeout=42s
  • scott@tcps://salesserver1:1521/sales.us.example.com?ssl_server_cert_dn="cn=sales,cn=Oracle Context Server,dc=us,dc=example,dc=com"&sdu=8128&connect_timeout=60

works, too.

Documentation

Index

Examples

Constants

View Source
const (
	// DefaultPoolMinSessions specifies the default value for minSessions for pool creation.
	DefaultPoolMinSessions = 1
	// DefaultPoolMaxSessions specifies the default value for maxSessions for pool creation.
	DefaultPoolMaxSessions = 1000
	// DefaultSessionIncrement specifies the default value for increment for pool creation.
	DefaultSessionIncrement = 1
	// DefaultPoolIncrement is a deprecated name for DefaultSessionIncrement.
	DefaultPoolIncrement = DefaultSessionIncrement
	// DefaultConnectionClass is empty, which allows to use the poolMinSessions created as part of session pool creation for non-DRCP. For DRCP, connectionClass needs to be explicitly mentioned.
	DefaultConnectionClass = ""
	// NoConnectionPoolingConnectionClass is a special connection class name to indicate no connection pooling.
	// It is the same as setting standaloneConnection=1
	NoConnectionPoolingConnectionClass = "NO-CONNECTION-POOLING"
	// DefaultSessionTimeout is the seconds before idle pool sessions get evicted
	DefaultSessionTimeout = 5 * time.Minute
	// DefaultWaitTimeout is the milliseconds to wait for a session to become available
	DefaultWaitTimeout = 30 * time.Second
	// DefaultMaxLifeTime is the maximum time in seconds till a pooled session may exist
	DefaultMaxLifeTime = 1 * time.Hour
	//DefaultStandaloneConnection holds the default for standaloneConnection.
	DefaultStandaloneConnection = false
)

Variables

This section is empty.

Functions

func AppendLogfmt

func AppendLogfmt(w io.Writer, key, value interface{}) error

AppendLogfmt appends the key=val logfmt-formatted.

Example
var buf strings.Builder
AppendLogfmt(&buf, "user", "scott")
AppendLogfmt(&buf, "password", "tiger")
AppendLogfmt(&buf, "connectString", "dbhost:1521/orclpdb1?connect_timeout=2")
fmt.Println(buf.String())
Output:

user=scott
password=tiger
connectString="dbhost:1521/orclpdb1?connect_timeout=2"

func Fuzz

func Fuzz(data []byte) int

See https://github.com/dvyukov/go-fuzz

(cd /tmp && go get -u github.com/dvyukov/go-fuzz/go-fuzz github.com/dvyukov/go-fuzz/go-fuzz-build) PATH=$HOME/sdk/go1.14.6/bin:$PATH GO111MODULE=on go-fuzz-build go-fuzz

func ParseTZ

func ParseTZ(s string) (int, error)

ParseTZ parses timezone specification ("Europe/Budapest" or "+01:00") and returns the offset in seconds.

Types

type CommonParams

type CommonParams struct {
	Username, ConnectString string
	Password                Password
	ConfigDir, LibDir       string
	// OnInit is executed on session init. Overrides AlterSession and OnInitStmts!
	OnInit func(driver.Conn) error
	// OnInitStmts are executed on session init, iff OnInit is nil.
	OnInitStmts []string
	// AlterSession key-values are set with "ALTER SESSION SET key=value" on session init, iff OnInit is nil.
	AlterSession [][2]string
	Timezone     *time.Location
	EnableEvents bool
}

CommonParams holds the common parameters for pooled or standalone connections.

func (CommonParams) String

func (P CommonParams) String() string

String returns the string representation of CommonParams.

type ConnParams

type ConnParams struct {
	NewPassword                             Password
	ConnClass                               string
	IsSysDBA, IsSysOper, IsSysASM, IsPrelim bool
	ShardingKey, SuperShardingKey           []interface{}
}

ConnParams holds the connection-specific parameters.

func (ConnParams) String

func (P ConnParams) String() string

String returns the string representation of the ConnParams.

type ConnectionParams

type ConnectionParams struct {
	CommonParams
	ConnParams
	PoolParams
	// NewPassword is used iff StandaloneConnection is true!
	NewPassword          Password
	StandaloneConnection bool
}

ConnectionParams holds the params for a connection (pool). You can use ConnectionParams{...}.StringWithPassword() as a connection string in sql.Open.

func Parse

func Parse(dataSourceName string) (ConnectionParams, error)

Parse parses the given connection string into a struct.

func (ConnectionParams) IsStandalone

func (P ConnectionParams) IsStandalone() bool

IsStandalone returns whether the connection should be standalone, not pooled.

func (*ConnectionParams) SetSessionParamOnInit

func (P *ConnectionParams) SetSessionParamOnInit(k, v string)

SetSessionParamOnInit adds an "ALTER SESSION k=v" to the OnInit task list.

func (ConnectionParams) String

func (P ConnectionParams) String() string

String returns the string representation of ConnectionParams. The password is replaced with a "SECRET" string!

func (ConnectionParams) StringNoClass

func (P ConnectionParams) StringNoClass() string

StringNoClass returns the string representation of ConnectionParams, without class info. The password is replaced with a "SECRET" string!

func (ConnectionParams) StringWithPassword

func (P ConnectionParams) StringWithPassword() string

StringWithPassword returns the string representation of ConnectionParams (as String() does), but does NOT obfuscate the password, just prints it as is.

type Password

type Password struct {
	// contains filtered or unexported fields
}

Password is printed obfuscated with String, use Secret to reveal the secret.

func NewPassword

func NewPassword(secret string) Password

NewPassword creates a new Password, containing the given secret.

func (Password) IsZero

func (P Password) IsZero() bool

IsZero returns whether the password is emtpy.

func (Password) Len

func (P Password) Len() int

Len returns the length of the password.

func (*Password) Reset

func (P *Password) Reset()

Reset the password.

func (Password) Secret

func (P Password) Secret() string

Secret reveals the real password.

func (Password) String

func (P Password) String() string

String returns the secret obfuscated irreversibly.

type PoolParams

type PoolParams struct {
	MinSessions, MaxSessions, SessionIncrement int
	WaitTimeout, MaxLifeTime, SessionTimeout   time.Duration
	Heterogeneous, ExternalAuth                bool
}

PoolParams holds the configuration of the Oracle Session Pool.

func (PoolParams) String

func (P PoolParams) String() string

String returns the string representation of PoolParams.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL