godror

package module
v0.11.3-0...-8f07c8d Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2020 License: Apache-2.0, UPL-1.0 Imports: 21 Imported by: 0

README

Travis CircleCI GoDoc Go Report Card codecov

Go DRiver for ORacle

godror is a package which is a database/sql/driver.Driver for connecting to Oracle DB, using Anthony Tuininga's excellent OCI wrapper, ODPI-C.

At least Go 1.11 is required!

Although an Oracle client is NOT required for compiling, it is at run time. One can download it from https://www.oracle.com/database/technologies/instant-client/downloads.html

Connect

In sql.Open("godror", connString), you can provide the classic "user/passw@service_name" as connString, or an URL like "oracle://user:passw@service_name".

You can provide all possible options with ConnectionParams. Watch out the ConnectionParams.String() does redact the password (for security, to avoid logging it - see https://github.com/go-goracle/goracle/issues/79). So use ConnectionParams.StringWithPassword().

More advanced configurations can be set with a connection string such as: user/pass@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=port)))(CONNECT_DATA=(SERVICE_NAME=sn)))

A configuration like this is how you would add functionality such as load balancing across mutliple servers. The portion described in parenthesis above can also be set in the SID field of ConnectionParams.

For other possible connection strings, see https://oracle.github.io/node-oracledb/doc/api.html#connectionstrings and https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-B0437826-43C1-49EC-A94D-B650B6A4A6EE .

TL;DR; the short form is username@[//]host[:port][/service_name][:server][/instance_name], the long form is (DESCRIPTION= (ADDRESS=(PROTOCOL=tcp)(HOST=host)(PORT=port)) (CONNECT_DATA= (SERVICE_NAME=service_name) (SERVER=server) (INSTANCE_NAME=instance_name))).

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

Rationale

With Go 1.9, driver-specific things are not needed, everything (I need) can be achieved with the standard database/sql library. Even calling stored procedures with OUT parameters, or sending/retrieving PL/SQL array types - just give a godror.PlSQLArrays Option within the parameters of Exec!

The array size of the returned PL/SQL arrays can be set with godror.ArraySize(2000)

  • the default is 1024.

Connections are pooled by default (except AS SYSOPER or AS SYSDBA).

Speed

Correctness and simplicity is more important than speed, but the underlying ODPI-C library helps a lot with the lower levels, so the performance is not bad.

Queries are prefetched (256 rows by default, can be changed by adding a godror.FetchRowCount(1000) argument to the call of Query), but you can speed up INSERT/UPDATE/DELETE statements by providing all the subsequent parameters at once, by putting each param's subsequent elements in a separate slice:

Instead of

db.Exec("INSERT INTO table (a, b) VALUES (:1, :2)", 1, "a")
db.Exec("INSERT INTO table (a, b) VALUES (:1, :2)", 2, "b")

do

db.Exec("INSERT INTO table (a, b) VALUES (:1, :2)", []int{1, 2}, []string{"a", "b"})

Logging

godror uses github.com/go-kit/kit/log's concept of a Log function. Either set godror.Log to a logging function globally, or (better) set the logger in the Context of ExecContext or QueryContext:

db.QueryContext(godror.ContextWithLog(ctx, logger.Log), qry)

Tracing

To set ClientIdentifier, ClientInfo, Module, Action and DbOp on the session, to be seen in the Database by the Admin, set godror.TraceTag on the Context:

db.QueryContext(godror.ContextWithTraceTag(godror.TraceTag{
	Module: "processing",
	Action: "first",
}), qry)

Extras

To use the godror-specific functions, you'll need a *godror.conn. That's what godror.DriverConn is for! See z_qrcn_test.go for using that to reach NewSubscription.

Calling stored procedures

Use ExecContext and mark each OUT parameter with sql.Out.

Using cursors returned by stored procedures

Use ExecContext and an interface{} or a database/sql/driver.Rows as the sql.Out destination, then either use the driver.Rows interface, or transform it into a regular *sql.Rows with godror.WrapRows, or (since Go 1.12) just Scan into *sql.Rows.

For examples, see Anthony Tuininga's presentation about Go (page 39)!

Caveats

sql.NullString

sql.NullString is not supported: Oracle DB does not differentiate between an empty string ("") and a NULL, so an

sql.NullString{String:"", Valid:true} == sql.NullString{String:"", Valid:false}

and this would be more confusing than not supporting sql.NullString at all.

Just use plain old string !

NUMBER

NUMBERs are transferred as godror.Number (which is a string) to Go under the hood. This ensures that we don't lose any precision (Oracle's NUMBER has 38 decimal digits), and sql.Scan will hide this and Scan into your int64, float64 or string, as you wish.

For PLS_INTEGER and BINARY_INTEGER (PL/SQL data types) you can use int32.

CLOB, BLOB

From 2.9.0, LOBs are returned as string/[]byte by default (before it needed the ClobAsString() option). Now it's reversed, and the default is string, to get a Lob reader, give the LobAsReader() option.

If you return Lob as a reader, watch out with sql.QueryRow, sql.QueryRowContext ! They close the statement right after you Scan from the returned *Row, the returned Lob will be invalid, producing getSize: ORA-00000: DPI-1002: invalid dpiLob handle.

So, use a separate Stmt or sql.QueryContext.

For writing a LOB, the LOB locator returned from the database is valid only till the Stmt is valid! So Prepare the statement for the retrieval, then Exec, and only Close the stmt iff you've finished with your LOB! For example, see z_lob_test.go, TestLOBAppend.

TIMESTAMP

As I couldn't make TIMESTAMP arrays work, all time.Time is bind as DATE, so fractional seconds are lost. A workaround is converting to string:

time.Now().Format("2-Jan-06 3:04:05.000000 PM")

See #121.

Install

Just

go get github.com/godror/godror

Or if you prefer dep

dep ensure -add github.com/godror/godror

and you're ready to go!

Note that Windows may need some newer gcc (mingw-w64 with gcc 7.2.0).

Contribute

Just as with other Go projects, you don't want to change the import paths, but you can hack on the library in place, just set up different remotes:

cd $GOPATH.src/github.com/godror/godror
git remote add upstream https://github.com/godror/godror.git
git fetch upstream
git checkout -b master upstream/master

git checkout -f master
git pull upstream master
git remote add fork git@github.com:mygithubacc/godror
git checkout -b newfeature upstream/master

Change, experiment as you wish, then

git commit -m 'my great changes' *.go
git push fork newfeature

and you're ready to send a GitHub Pull Request from github.com/mygithubacc/godror, newfeature branch.

pre-commit

Add this to .git/hooks/pre-commit (after go get github.com/golangci/golangci-lint/cmd/golangci-lint)

#!/bin/sh
set -e

output="$(gofmt -l "$@")"

if [ -n "$output" ]; then
	echo >&2 "Go files must be formatted with gofmt. Please run:"
	for f in $output; do
		echo >&2 "  gofmt -w $PWD/$f"
	done
	exit 1
fi

golangci-lint run

Third-party

  • oracall generates a server for calling stored procedures.

Documentation

Overview

Package godror is a database/sql/driver for Oracle DB.

The connection string for the sql.Open("godror", connString) call can be the simple

login/password@sid [AS SYSDBA|AS SYSOPER]

type (with sid being the sexp returned by tnsping), or in the form of

ora://login:password@sid/? \
  sysdba=0& \
  sysoper=0& \
  poolMinSessions=1& \
  poolMaxSessions=1000& \
  poolIncrement=1& \
  connectionClass=POOLED& \
  standaloneConnection=0& \
  enableEvents=0& \
  heterogeneousPool=0& \
  prelim=0& \
  poolWaitTimeout=5m& \
  poolSessionMaxLifetime=1h& \
  poolSessionTimeout=30s& \
  timezone=Local& \
  newPassword= \
  onInit=ALTER+SESSION+SET+current_schema%3Dmy_schema

These are the defaults. Many advocate that a static session pool (min=max, incr=0) is better, with 1-10 sessions per CPU thread. See http://docs.oracle.com/cd/E82638_01/JJUCP/optimizing-real-world-performance.htm#JJUCP-GUID-BC09F045-5D80-4AF5-93F5-FEF0531E0E1D You may also use ConnectionParams to configure a connection.

If you specify connectionClass, that'll reuse the same session pool without the connectionClass, but will specify it on each session acquire. Thus you can cluster the session pool with classes, or use POOLED for DRCP.

For what can be used as "sid", see https://docs.oracle.com/en/database/oracle/oracle-database/19/netag/configuring-naming-methods.html#GUID-E5358DEA-D619-4B7B-A799-3D2F802500F1

Index

Examples

Constants

View Source
const (
	// StartupDefault is the default mode for startup which permits database access to all users.
	StartupDefault = StartupMode(C.DPI_MODE_STARTUP_DEFAULT)
	// StartupForce shuts down a running instance (using ABORT) before starting a new one. This mode should only be used in unusual circumstances.
	StartupForce = StartupMode(C.DPI_MODE_STARTUP_FORCE)
	// StartupRestrict only allows database access to users with both the CREATE SESSION and RESTRICTED SESSION privileges (normally the DBA).
	StartupRestrict = StartupMode(C.DPI_MODE_STARTUP_RESTRICT)
)
View Source
const (
	// ShutdownDefault - further connections to the database are prohibited. Wait for users to disconnect from the database.
	ShutdownDefault = ShutdownMode(C.DPI_MODE_SHUTDOWN_DEFAULT)
	// ShutdownTransactional - further connections to the database are prohibited and no new transactions are allowed to be started. Wait for active transactions to complete.
	ShutdownTransactional = ShutdownMode(C.DPI_MODE_SHUTDOWN_TRANSACTIONAL)
	// ShutdownTransactionalLocal - behaves the same way as ShutdownTransactional but only waits for local transactions to complete.
	ShutdownTransactionalLocal = ShutdownMode(C.DPI_MODE_SHUTDOWN_TRANSACTIONAL_LOCAL)
	// ShutdownImmediate - all uncommitted transactions are terminated and rolled back and all connections to the database are closed immediately.
	ShutdownImmediate = ShutdownMode(C.DPI_MODE_SHUTDOWN_IMMEDIATE)
	// ShutdownAbort - all uncommitted transactions are terminated and are not rolled back. This is the fastest way to shut down the database but the next database startup may require instance recovery.
	ShutdownAbort = ShutdownMode(C.DPI_MODE_SHUTDOWN_ABORT)
	// ShutdownFinal shuts down the database. This mode should only be used in the second call to dpiConn_shutdownDatabase().
	ShutdownFinal = ShutdownMode(C.DPI_MODE_SHUTDOWN_FINAL)
)
View Source
const (
	// DefaultFetchRowCount is the number of prefetched rows by default (if not changed through FetchRowCount statement option).
	DefaultFetchRowCount = 1 << 8

	// DefaultArraySize is the length of the maximum PL/SQL array by default (if not changed through ArraySize statement option).
	DefaultArraySize = 1 << 10
)
View Source
const (
	// DpiMajorVersion is the wanted major version of the underlying ODPI-C library.
	DpiMajorVersion = C.DPI_MAJOR_VERSION
	// DpiMinorVersion is the wanted minor version of the underlying ODPI-C library.
	DpiMinorVersion = C.DPI_MINOR_VERSION
	// DpiPatchLevel is the patch level version of the underlying ODPI-C library
	DpiPatchLevel = C.DPI_PATCH_LEVEL
	// DpiVersionNumber is the underlying ODPI-C version as one number (Major * 10000 + Minor * 100 + Patch)
	DpiVersionNumber = C.DPI_VERSION_NUMBER

	// DriverName is set on the connection to be seen in the DB
	//
	// It cannot be longer than 30 bytes !
	DriverName = "godror : " + Version

	// DefaultPoolMinSessions specifies the default value for minSessions for pool creation.
	DefaultPoolMinSessions = 1
	// DefaultPoolMaxSessions specifies the default value for maxSessions for pool creation.
	DefaultPoolMaxSessions = 1000
	// DefaultPoolIncrement specifies the default value for increment for pool creation.
	DefaultPoolIncrement = 1
	// DefaultConnectionClass is the default connectionClass
	DefaultConnectionClass = "GODROR"
	// 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
)
View Source
const (
	NoWait      = uint32(0)
	WaitForever = uint32(1<<31 - 1)
)
View Source
const (
	// MsgStateReady says that "The message is ready to be processed".
	MsgStateReady = MessageState(C.DPI_MSG_STATE_READY)
	// MsgStateWaiting says that "The message is waiting for the delay time to expire".
	MsgStateWaiting = MessageState(C.DPI_MSG_STATE_WAITING)
	// MsgStateProcessed says that "The message has already been processed and is retained".
	MsgStateProcessed = MessageState(C.DPI_MSG_STATE_PROCESSED)
	// MsgStateExpired says that "The message has been moved to the exception queue".
	MsgStateExpired = MessageState(C.DPI_MSG_STATE_EXPIRED)
)
View Source
const (
	// DeliverPersistent is to Dequeue only persistent messages from the queue. This is the default mode.
	DeliverPersistent = DeliveryMode(C.DPI_MODE_MSG_PERSISTENT)
	// DeliverBuffered is to Dequeue only buffered messages from the queue.
	DeliverBuffered = DeliveryMode(C.DPI_MODE_MSG_BUFFERED)
	// DeliverPersistentOrBuffered is to Dequeue both persistent and buffered messages from the queue.
	DeliverPersistentOrBuffered = DeliveryMode(C.DPI_MODE_MSG_PERSISTENT_OR_BUFFERED)
)
View Source
const (
	// VisibleImmediate means that "The message is not part of the current transaction but constitutes a transaction of its own".
	VisibleImmediate = Visibility(C.DPI_VISIBILITY_IMMEDIATE)
	// VisibleOnCommit means that "The message is part of the current transaction. This is the default value".
	VisibleOnCommit = Visibility(C.DPI_VISIBILITY_ON_COMMIT)
)
View Source
const (
	// DeqRemove reads the message and updates or deletes it. This is the default mode. Note that the message may be retained in the queue table based on retention properties.
	DeqRemove = DeqMode(C.DPI_MODE_DEQ_REMOVE)
	// DeqBrows reads the message without acquiring a lock on the message (equivalent to a SELECT statement).
	DeqBrowse = DeqMode(C.DPI_MODE_DEQ_BROWSE)
	// DeqLocked reads the message and obtain a write lock on the message (equivalent to a SELECT FOR UPDATE statement).
	DeqLocked = DeqMode(C.DPI_MODE_DEQ_LOCKED)
	// DeqPeek confirms receipt of the message but does not deliver the actual message content.
	DeqPeek = DeqMode(C.DPI_MODE_DEQ_REMOVE_NO_DATA)
)
View Source
const (
	// NavFirst retrieves the first available message that matches the search criteria. This resets the position to the beginning of the queue.
	NavFirst = DeqNavigation(C.DPI_DEQ_NAV_FIRST_MSG)
	// NavNext skips the remainder of the current transaction group (if any) and retrieves the first message of the next transaction group. This option can only be used if message grouping is enabled for the queue.
	NavNextTran = DeqNavigation(C.DPI_DEQ_NAV_NEXT_TRANSACTION)
	// NavNext  	Retrieves the next available message that matches the search criteria. This is the default method.
	NavNext = DeqNavigation(C.DPI_DEQ_NAV_NEXT_MSG)
)

Events that can be watched.

View Source
const (
	// OpAll Indicates that notifications should be sent for all operations on the table or query.
	OpAll = Operation(C.DPI_OPCODE_ALL_OPS)
	// OpAllRows Indicates that all rows have been changed in the table or query (or too many rows were changed or row information was not requested).
	OpAllRows = Operation(C.DPI_OPCODE_ALL_ROWS)
	// OpInsert Indicates that an insert operation has taken place in the table or query.
	OpInsert = Operation(C.DPI_OPCODE_INSERT)
	// OpUpdate Indicates that an update operation has taken place in the table or query.
	OpUpdate = Operation(C.DPI_OPCODE_UPDATE)
	// OpDelete Indicates that a delete operation has taken place in the table or query.
	OpDelete = Operation(C.DPI_OPCODE_DELETE)
	// OpAlter Indicates that the registered table or query has been altered.
	OpAlter = Operation(C.DPI_OPCODE_ALTER)
	// OpDrop Indicates that the registered table or query has been dropped.
	OpDrop = Operation(C.DPI_OPCODE_DROP)
	// OpUnknown An unknown operation has taken place.
	OpUnknown = Operation(C.DPI_OPCODE_UNKNOWN)
)
View Source
const MsgIDLength = 16
View Source
const Version = "v0.11.3"

Version of this driver

Variables

View Source
var (
	// Int64 for converting to-from int64.
	Int64 = intType{}
	// Float64 for converting to-from float64.
	Float64 = floatType{}
	// Num for converting to-from Number (string)
	Num = numType{}
)
View Source
var DefaultDeqOptions = DeqOptions{
	Mode:         DeqRemove,
	DeliveryMode: DeliverPersistent,
	Navigation:   NavFirst,
	Visibility:   VisibleImmediate,
	Wait:         30,
}

DefaultDeqOptions is the default set for NewQueue.

View Source
var DefaultEnqOptions = EnqOptions{
	Visibility:   VisibleImmediate,
	DeliveryMode: DeliverPersistent,
}

DefaultEnqOptions is the default set for NewQueue.

View Source
var ErrNoSuchKey = errors.New("no such key")

ErrNoSuchKey is the error for missing key in lookup.

View Source
var ErrNotCollection = errors.New("not collection")

ErrNotCollection is returned when the Object is not a collection.

View Source
var ErrNotExist = errors.New("not exist")

ErrNotExist is returned when the collection's requested element does not exist.

View Source
var ErrNotSupported = errors.New("not supported")
View Source
var Log func(...interface{}) error

Log function. By default, it's nil, and thus logs nothing. If you want to change this, change it to a github.com/go-kit/kit/log.Swapper.Log or analog to be race-free.

Functions

func CallbackSubscr

func CallbackSubscr(ctx unsafe.Pointer, message *C.dpiSubscrMessage)

CallbackSubscr is the callback for C code on subscription event.

func ContextWithLog

func ContextWithLog(ctx context.Context, logF func(...interface{}) error) context.Context

ContextWithLog returns a context with the given log function.

func ContextWithTraceTag

func ContextWithTraceTag(ctx context.Context, tt TraceTag) context.Context

ContextWithTraceTag returns a context with the specified TraceTag, which will be set on the session used.

func ContextWithUserPassw

func ContextWithUserPassw(ctx context.Context, user, password, connClass string) context.Context

ContextWithUserPassw returns a context with the specified user and password, to be used with heterogeneous pools.

func EnableDbmsOutput

func EnableDbmsOutput(ctx context.Context, conn Execer) error

EnableDbmsOutput enables DBMS_OUTPUT buffering on the given connection. This is required if you want to retrieve the output with ReadDbmsOutput later.

func MapToSlice

func MapToSlice(qry string, metParam func(string) interface{}) (string, []interface{})

MapToSlice modifies query for map (:paramname) to :%d placeholders + slice of params.

Calls metParam for each parameter met, and returns the slice of their results.

func NamedToOrdered

func NamedToOrdered(qry string, namedParams map[string]interface{}) (string, []interface{})

NamedToOrdered converts the query from named params (:paramname) to :%d placeholders + slice of params, copying the params verbatim.

func NewConnector

func NewConnector(name string, onInit func(driver.Conn) error) (driver.Connector, error)

NewConnector returns a driver.Connector to be used with sql.OpenDB, (for the default Driver registered with godror) which calls the given onInit if the connection is new.

For an onInit example, see NewSessionIniter.

func NewSessionIniter

func NewSessionIniter(m map[string]string) func(driver.Conn) error

NewSessionIniter returns a function suitable for use in NewConnector as onInit, which calls "ALTER SESSION SET <key>='<value>'" for each element of the given map.

func ReadDbmsOutput

func ReadDbmsOutput(ctx context.Context, w io.Writer, conn preparer) error

ReadDbmsOutput copies the DBMS_OUTPUT buffer into the given io.Writer.

Be sure that you enable it beforehand (either with EnableDbmsOutput or with DBMS_OUTPUT.enable(NULL))

func Timezone

func Timezone(ctx context.Context, ex Execer) (*time.Location, error)

func WrapRows

func WrapRows(ctx context.Context, q Querier, rset driver.Rows) (*sql.Rows, error)

WrapRows transforms a driver.Rows into an *sql.Rows.

Types

type Column

type Column struct {
	Name                      string
	ObjectType                *C.dpiObjectType
	OracleType                C.dpiOracleTypeNum
	NativeType                C.dpiNativeTypeNum
	Size, SizeInChars, DBSize C.uint32_t
	Precision                 C.int16_t
	Scale                     C.int8_t
	Nullable                  bool
}

Column holds the info from a column.

type CompileError

type CompileError struct {
	Owner, Name, Type    string
	Line, Position, Code int64
	Text                 string
	Warning              bool
}

CompileError represents a compile-time error as in user_errors view.

func GetCompileErrors

func GetCompileErrors(queryer queryer, all bool) ([]CompileError, error)

GetCompileErrors returns the slice of the errors in user_errors.

If all is false, only errors are returned; otherwise, warnings, too.

func (CompileError) Error

func (ce CompileError) Error() string

type Conn

type Conn interface {
	driver.Conn
	driver.ConnBeginTx
	driver.ConnPrepareContext
	driver.Pinger

	Break() error
	Commit() error
	Rollback() error
	ClientVersion() (VersionInfo, error)
	ServerVersion() (VersionInfo, error)
	GetObjectType(name string) (ObjectType, error)
	NewSubscription(string, func(Event)) (*Subscription, error)
	Startup(StartupMode) error
	Shutdown(ShutdownMode) error
	NewData(baseType interface{}, SliceLen, BufSize int) ([]*Data, error)

	Timezone() *time.Location
}

Conn is the interface for a connection, to be returned by DriverConn.

func DriverConn

func DriverConn(ctx context.Context, ex Execer) (Conn, error)

DriverConn returns the *godror.conn of the database/sql.Conn

type ConnectionParams

type ConnectionParams struct {
	OnInit                             []string
	Username, Password, SID, ConnClass string
	// NewPassword is used iff StandaloneConnection is true!
	NewPassword                              string
	MinSessions, MaxSessions, PoolIncrement  int
	WaitTimeout, MaxLifeTime, SessionTimeout time.Duration
	Timezone                                 *time.Location
	IsSysDBA, IsSysOper, IsSysASM, IsPrelim  bool
	HeterogeneousPool                        bool
	StandaloneConnection                     bool
	EnableEvents                             bool
}

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

func ParseConnString

func ParseConnString(connString string) (ConnectionParams, error)

ParseConnString parses the given connection string into a struct.

func (*ConnectionParams) Comb

func (P *ConnectionParams) Comb()

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 Data

type Data struct {
	ObjectType ObjectType

	NativeTypeNum C.dpiNativeTypeNum
	// contains filtered or unexported fields
}

Data holds the data to/from Oracle.

func NewData

func NewData(v interface{}) (*Data, error)

NewData creates a new Data structure for the given type, populated with the given type.

func (*Data) Get

func (d *Data) Get() interface{}

Get returns the contents of Data.

func (*Data) GetBool

func (d *Data) GetBool() bool

GetBool returns the bool data.

func (*Data) GetBytes

func (d *Data) GetBytes() []byte

GetBytes returns the []byte from the data.

func (*Data) GetFloat32

func (d *Data) GetFloat32() float32

GetFloat32 gets float32 from the data.

func (*Data) GetFloat64

func (d *Data) GetFloat64() float64

GetFloat64 gets float64 from the data.

func (*Data) GetInt64

func (d *Data) GetInt64() int64

GetInt64 gets int64 from the data.

func (*Data) GetIntervalDS

func (d *Data) GetIntervalDS() time.Duration

GetIntervalDS gets duration as interval date-seconds from data.

func (*Data) GetIntervalYM

func (d *Data) GetIntervalYM() IntervalYM

GetIntervalYM gets IntervalYM from the data.

func (*Data) GetLob

func (d *Data) GetLob() *Lob

GetLob gets data as Lob.

func (*Data) GetObject

func (d *Data) GetObject() *Object

GetObject gets Object from data.

As with all Objects, you MUST call Close on it when not needed anymore!

func (*Data) GetStmt

func (d *Data) GetStmt() driver.Stmt

GetStmt gets Stmt from data.

func (*Data) GetTime

func (d *Data) GetTime() time.Time

GetTime gets Time from data.

func (*Data) GetUint64

func (d *Data) GetUint64() uint64

GetUint64 gets data as uint64.

func (*Data) IsNull

func (d *Data) IsNull() bool

IsNull returns whether the data is null.

func (*Data) IsObject

func (d *Data) IsObject() bool

IsObject returns whether the data contains an Object or not.

func (*Data) Set

func (d *Data) Set(v interface{}) error

Set the data.

func (*Data) SetBool

func (d *Data) SetBool(b bool)

SetBool sets the data as bool.

func (*Data) SetBytes

func (d *Data) SetBytes(b []byte)

SetBytes set the data as []byte.

func (*Data) SetFloat32

func (d *Data) SetFloat32(f float32)

SetFloat32 sets the data as float32.

func (*Data) SetFloat64

func (d *Data) SetFloat64(f float64)

SetFloat64 sets the data as float64.

func (*Data) SetInt64

func (d *Data) SetInt64(i int64)

SetInt64 sets the data as int64.

func (*Data) SetIntervalDS

func (d *Data) SetIntervalDS(dur time.Duration)

SetIntervalDS sets the duration as interval date-seconds to data.

func (*Data) SetIntervalYM

func (d *Data) SetIntervalYM(ym IntervalYM)

SetIntervalYM sets IntervalYM to the data.

func (*Data) SetLob

func (d *Data) SetLob(lob *DirectLob)

SetLob sets Lob to the data.

func (*Data) SetNull

func (d *Data) SetNull()

SetNull sets the value of the data to be the null value.

func (*Data) SetObject

func (d *Data) SetObject(o *Object)

SetObject sets Object to data.

func (*Data) SetStmt

func (d *Data) SetStmt(s *statement)

SetStmt sets Stmt to data.

func (*Data) SetTime

func (d *Data) SetTime(t time.Time)

SetTime sets Time to data.

func (*Data) SetUint64

func (d *Data) SetUint64(u uint64)

SetUint64 sets data to uint64.

type DeliveryMode

type DeliveryMode uint32

DeliveryMode constants for delivery modes.

type DeqMode

type DeqMode uint32

DeqMode constants for dequeue modes.

type DeqNavigation

type DeqNavigation uint32

DeqNavigation constants for navigation.

type DeqOptions

type DeqOptions struct {
	Condition, Consumer, Correlation string
	MsgID, Transformation            string
	Mode                             DeqMode
	DeliveryMode                     DeliveryMode
	Navigation                       DeqNavigation
	Visibility                       Visibility
	Wait                             uint32
}

DeqOptions are the options used to dequeue a message.

type DirectLob

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

DirectLob holds a Lob and allows direct (Read/WriteAt, not streaming Read/Write) operations on it.

func (*DirectLob) Close

func (dl *DirectLob) Close() error

Close the Lob.

func (*DirectLob) ReadAt

func (dl *DirectLob) ReadAt(p []byte, offset int64) (int, error)

ReadAt reads at most len(p) bytes into p at offset.

func (*DirectLob) Set

func (dl *DirectLob) Set(p []byte) error

Set the contents of the LOB to the given byte slice. The LOB is cleared first.

func (*DirectLob) Size

func (dl *DirectLob) Size() (int64, error)

Size returns the size of the LOB.

func (*DirectLob) Trim

func (dl *DirectLob) Trim(size int64) error

Trim the LOB to the given size.

func (*DirectLob) WriteAt

func (dl *DirectLob) WriteAt(p []byte, offset int64) (int, error)

WriteAt writes p starting at offset.

type Drv

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

func (*Drv) ClientVersion

func (d *Drv) ClientVersion() (VersionInfo, error)

func (*Drv) NewConnector

func (d *Drv) NewConnector(name string, onInit func(driver.Conn) error) (driver.Connector, error)

NewConnector returns a driver.Connector to be used with sql.OpenDB, which calls the given onInit if the connection is new.

For an onInit example, see NewSessionIniter.

func (*Drv) Open

func (d *Drv) Open(connString string) (driver.Conn, error)

Open returns a new connection to the database. The name is a string in a driver-specific format.

func (*Drv) OpenConnector

func (d *Drv) OpenConnector(name string) (driver.Connector, error)

OpenConnector must parse the name in the same format that Driver.Open parses the name parameter.

type EnqOptions

type EnqOptions struct {
	Transformation string
	Visibility     Visibility
	DeliveryMode   DeliveryMode
}

EnqOptions are the options used to enqueue a message.

type Event

type Event struct {
	Tables  []TableEvent
	Queries []QueryEvent
	DB      string
	Err     error
	Type    EventType
}

Event for a subscription.

type EventType

type EventType C.dpiEventType

EventType is the type of an event.

type Execer

type Execer interface {
	ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
}

Execer is the ExecContext of sql.Conn.

type IntervalYM

type IntervalYM struct {
	Years, Months int
}

IntervalYM holds Years and Months as interval.

type Lob

type Lob struct {
	io.Reader
	IsClob bool
}

Lob is for reading/writing a LOB.

func (*Lob) Hijack

func (lob *Lob) Hijack() (*DirectLob, error)

Hijack the underlying lob reader/writer, and return a DirectLob for reading/writing the lob directly.

After this, the Lob is unusable!

type Message

type Message struct {
	Correlation, ExceptionQ string
	Enqueued                time.Time
	MsgID, OriginalMsgID    [16]byte
	Raw                     []byte
	Delay, Expiration       int32
	Priority, NumAttempts   int32
	Object                  *Object
	DeliveryMode            DeliveryMode
	State                   MessageState
}

Message is a message - either received or being sent.

type MessageState

type MessageState uint32

MessageState constants representing message's state.

type NullTime

type NullTime = sql.NullTime

type Number

type Number string

Number as string

func (Number) MarshalJSON

func (n Number) MarshalJSON() ([]byte, error)

MarshalJSON marshals a Number into a JSON string.

func (Number) MarshalText

func (n Number) MarshalText() ([]byte, error)

MarshalText marshals a Number to text.

func (*Number) Scan

func (n *Number) Scan(v interface{}) error

Scan into the Number from a driver.Value.

func (Number) String

func (n Number) String() string

func (*Number) UnmarshalJSON

func (n *Number) UnmarshalJSON(p []byte) error

UnmarshalJSON parses a JSON string into the Number.

func (*Number) UnmarshalText

func (n *Number) UnmarshalText(p []byte) error

UnmarshalText parses text into a Number.

func (Number) Value

func (n Number) Value() (driver.Value, error)

Value returns the Number as driver.Value

type Object

type Object struct {
	ObjectType
	// contains filtered or unexported fields
}

Object represents a dpiObject.

func (*Object) Close

func (O *Object) Close() error

Close releases a reference to the object.

func (*Object) Collection

func (O *Object) Collection() ObjectCollection

Collection returns &ObjectCollection{Object: O} iff the Object is a collection. Otherwise it returns nil.

func (*Object) Get

func (O *Object) Get(name string) (interface{}, error)

Get scans the named attribute into dest, and returns it.

func (*Object) GetAttribute

func (O *Object) GetAttribute(data *Data, name string) error

GetAttribute gets the i-th attribute into data.

func (*Object) ObjectRef

func (O *Object) ObjectRef() *Object

ObjectRef implements userType interface.

func (*Object) ResetAttributes

func (O *Object) ResetAttributes() error

ResetAttributes prepare all attributes for use the object as IN parameter

func (*Object) Set

func (O *Object) Set(name string, v interface{}) error

Set is a convenience function to set the named attribute with the given value.

func (*Object) SetAttribute

func (O *Object) SetAttribute(name string, data *Data) error

SetAttribute sets the named attribute with data.

type ObjectAttribute

type ObjectAttribute struct {
	Name string

	ObjectType
	// contains filtered or unexported fields
}

ObjectAttribute is an attribute of an Object.

func (ObjectAttribute) Close

func (A ObjectAttribute) Close() error

Close the ObjectAttribute.

type ObjectCollection

type ObjectCollection struct {
	*Object
}

ObjectCollection represents a Collection of Objects - itself an Object, too.

func (ObjectCollection) Append

func (O ObjectCollection) Append(v interface{}) error

Append v to the collection.

func (ObjectCollection) AppendData

func (O ObjectCollection) AppendData(data *Data) error

AppendData to the collection.

func (ObjectCollection) AppendObject

func (O ObjectCollection) AppendObject(obj *Object) error

AppendObject adds an Object to the collection.

func (ObjectCollection) AsSlice

func (O ObjectCollection) AsSlice(dest interface{}) (interface{}, error)

AsSlice retrieves the collection into a slice.

func (ObjectCollection) Delete

func (O ObjectCollection) Delete(i int) error

Delete i-th element of the collection.

func (ObjectCollection) First

func (O ObjectCollection) First() (int, error)

First returns the first element's index of the collection.

func (ObjectCollection) Get

func (O ObjectCollection) Get(i int) (interface{}, error)

Get the i-th element of the collection.

func (ObjectCollection) GetItem

func (O ObjectCollection) GetItem(data *Data, i int) error

GetItem gets the i-th element of the collection into data.

func (ObjectCollection) Last

func (O ObjectCollection) Last() (int, error)

Last returns the index of the last element.

func (ObjectCollection) Len

func (O ObjectCollection) Len() (int, error)

Len returns the length of the collection.

func (ObjectCollection) Next

func (O ObjectCollection) Next(i int) (int, error)

Next returns the succeeding index of i.

func (ObjectCollection) Set

func (O ObjectCollection) Set(i int, v interface{}) error

Set the i-th element of the collection with value.

func (ObjectCollection) SetItem

func (O ObjectCollection) SetItem(i int, data *Data) error

SetItem sets the i-th element of the collection with data.

func (ObjectCollection) Trim

func (O ObjectCollection) Trim(n int) error

Trim the collection to n.

type ObjectScanner

type ObjectScanner interface {
	sql.Scanner
	// contains filtered or unexported methods
}

ObjectScanner assigns a value from a database object

type ObjectType

type ObjectType struct {
	Schema, Name string
	Attributes   map[string]ObjectAttribute

	DBSize, ClientSizeInBytes, CharSize int
	CollectionOf                        *ObjectType
	OracleTypeNum                       C.dpiOracleTypeNum
	NativeTypeNum                       C.dpiNativeTypeNum
	Precision                           int16
	Scale                               int8
	FsPrecision                         uint8
	// contains filtered or unexported fields
}

ObjectType holds type info of an Object.

func GetObjectType

func GetObjectType(ctx context.Context, ex Execer, typeName string) (ObjectType, error)

GetObjectType returns the ObjectType for the name.

func (ObjectType) FullName

func (t ObjectType) FullName() string

FullName returns the object's name with the schame prepended.

func (ObjectType) NewCollection

func (t ObjectType) NewCollection() (ObjectCollection, error)

NewCollection returns a new Collection object with ObjectType type. If the ObjectType is not a Collection, it returns ErrNotCollection error.

func (ObjectType) NewObject

func (t ObjectType) NewObject() (*Object, error)

NewObject returns a new Object with ObjectType type.

As with all Objects, you MUST call Close on it when not needed anymore!

func (ObjectType) String

func (t ObjectType) String() string

type ObjectWriter

type ObjectWriter interface {
	WriteObject() error
	// contains filtered or unexported methods
}

ObjectWriter update database object before binding

type Operation

type Operation C.dpiOpCode

Operation in the DB.

type Option

type Option func(*stmtOptions)

Option holds statement options.

var PlSQLArrays Option = func(o *stmtOptions) { o.plSQLArrays = true }

PlSQLArrays is to signal that the slices given in arguments of Exec to be left as is - the default is to treat them as arguments for ExecMany.

func ArraySize

func ArraySize(arraySize int) Option

ArraySize returns an option to set the array size to be used, overriding DefaultArraySize.

func ClobAsString

func ClobAsString() Option

ClobAsString returns an option to force fetching CLOB columns as strings.

DEPRECATED.

func FetchRowCount

func FetchRowCount(rowCount int) Option

FetchRowCount returns an option to set the rows to be fetched, overriding DefaultFetchRowCount.

func LobAsReader

func LobAsReader() Option

LobAsReader is an option to set query columns of CLOB/BLOB to be returned as a Lob.

LOB as a reader and writer is not the most performant at all. Yes, OCI and ODPI-C provide a way to retrieve this data directly. Effectively, all you need to do is tell ODPI-C that you want a "long string" or "long raw" returned. You can do that by telling ODPI-C you want a variable with oracleTypeNum=DPI_ORACLE_TYPE_LONG_VARCHAR or DPI_ORACLE_TYPE_LONG_RAW and nativeTypeNum=DPI_NATIVE_TYPE_BYTES. ODPI-C will handle all of the dynamic fetching and allocation that is required. :-) You can also use DPI_ORACLE_TYPE_VARCHAR and DPI_ORACLE_TYPE_RAW as long as you set the size > 32767 -- whichever way you wish to use.

With the use of LOBs, there is one round-trip to get the LOB locators, then a round-trip for each read() that is performed. If you request the length there is another round-trip required. So if you fetch 100 rows with 2 CLOB columns, that means you get 401 round-trips. Using string/[]bytes directly means only one round trip. So you can see that if your database is remote with high latency you can have a significant performance penalty!

func MagicTypeConversion

func MagicTypeConversion() Option

MagicTypeConversion returns an option to force converting named scalar types (e.g. "type underlying int64") to their scalar underlying type.

func NumberAsString

func NumberAsString() Option

NumberAsString returns an option to return numbers as string, not Number.

func ParseOnly

func ParseOnly() Option

ParseOnly returns an option to set the ExecMode to only Parse.

type OraErr

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

OraErr is an error holding the ORA-01234 code and the message.

func AsOraErr

func AsOraErr(err error) (*OraErr, bool)

AsOraErr returns the underlying *OraErr and whether it succeeded.

func (*OraErr) Code

func (oe *OraErr) Code() int

Code returns the OraErr's error code.

func (*OraErr) Error

func (oe *OraErr) Error() string

func (*OraErr) Message

func (oe *OraErr) Message() string

Message returns the OraErr's message.

type Querier

type Querier interface {
	QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
}

Querier is the QueryContext of sql.Conn.

type QueryColumn

type QueryColumn struct {
	Name                           string
	Type, Length, Precision, Scale int
	Nullable                       bool
}

QueryColumn is the described column.

func DescribeQuery

func DescribeQuery(ctx context.Context, db Execer, qry string) ([]QueryColumn, error)

DescribeQuery describes the columns in the qry.

This can help using unknown-at-compile-time, a.k.a. dynamic queries.

type QueryEvent

type QueryEvent struct {
	Tables []TableEvent
	ID     uint64
	Operation
}

QueryEvent is an event of a Query.

type Queue

type Queue struct {
	PayloadObjectType ObjectType
	// contains filtered or unexported fields
}

Queue represents an Oracle Advanced Queue.

func NewQueue

func NewQueue(ctx context.Context, execer Execer, name string, payloadObjectTypeName string) (*Queue, error)

NewQueue creates a new Queue.

WARNING: the connection given to it must not be closed before the Queue is closed! So use an sql.Conn for it.

func (*Queue) Close

func (Q *Queue) Close() error

Close the queue.

func (*Queue) DeqOptions

func (Q *Queue) DeqOptions() (DeqOptions, error)

DeqOptions returns the queue's dequeue options in effect.

func (*Queue) Dequeue

func (Q *Queue) Dequeue(messages []Message) (int, error)

Dequeues messages into the given slice. Returns the number of messages filled in the given slice.

func (*Queue) EnqOptions

func (Q *Queue) EnqOptions() (EnqOptions, error)

EnqOptions returns the queue's enqueue options in effect.

func (*Queue) Enqueue

func (Q *Queue) Enqueue(messages []Message) error

Enqueue all the messages given.

WARNING: calling this function in parallel on different connections acquired from the same pool may fail due to Oracle bug 29928074. Ensure that this function is not run in parallel, use standalone connections or connections from different pools, or make multiple calls to Queue.enqOne() instead. The function Queue.Dequeue() call is not affected.

func (*Queue) Name

func (Q *Queue) Name() string

Name of the queue.

func (*Queue) SetDeqCorrelation

func (Q *Queue) SetDeqCorrelation(correlation string) error

SetDeqCorrelation is a convenience function setting the Correlation DeqOption

func (*Queue) SetDeqOptions

func (Q *Queue) SetDeqOptions(D DeqOptions) error

SetDeqOptions sets all the dequeue options

func (*Queue) SetEnqOptions

func (Q *Queue) SetEnqOptions(E EnqOptions) error

SetEnqOptions sets all the enqueue options

type RowEvent

type RowEvent struct {
	Rowid string
	Operation
}

RowEvent is for row-related event.

type ShutdownMode

type ShutdownMode C.dpiShutdownMode

ShutdownMode for the database.

Example

ExampleShutdownMode is an example of how to shut down a database.

package main

import (
	"context"
	"database/sql"
	"log"

	errors "golang.org/x/xerrors"

	godror "github.com/godror/godror"
)

func main() {
	dsn := "oracle://?sysdba=1" // equivalent to "/ as sysdba"
	db, err := sql.Open("godror", dsn)
	if err != nil {
		log.Fatal(errors.Errorf("%s: %w", dsn, err))
	}
	defer db.Close()

	if err = exampleShutdown(db, godror.ShutdownTransactionalLocal); err != nil {
		log.Fatal(err)
	}
}

func exampleShutdown(db *sql.DB, shutdownMode godror.ShutdownMode) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	oraDB, err := godror.DriverConn(ctx, db)
	if err != nil {
		return err
	}
	log.Printf("Beginning shutdown %v", shutdownMode)
	if err = oraDB.Shutdown(shutdownMode); err != nil {
		return err
	}

	if shutdownMode == godror.ShutdownAbort {
		return nil
	}

	log.Println("Closing database")
	if _, err = db.Exec("alter database close normal"); err != nil {
		return err
	}
	log.Println("Unmounting database")
	if _, err = db.Exec("alter database dismount"); err != nil {
		return err
	}
	log.Println("Finishing shutdown")
	if err = oraDB.Shutdown(godror.ShutdownFinal); err != nil {
		return err
	}
	return nil
}
Output:

type StartupMode

type StartupMode C.dpiStartupMode

StartupMode for the database.

Example

ExampleStartupMode calls exampleStartup to start a database.

package main

import (
	"context"
	"database/sql"
	"log"

	errors "golang.org/x/xerrors"

	godror "github.com/godror/godror"
)

func main() {
	if err := exampleStartup(godror.StartupDefault); err != nil {
		log.Fatal(err)
	}
}
func exampleStartup(startupMode godror.StartupMode) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	dsn := "oracle://?sysdba=1&prelim=1"
	db, err := sql.Open("godror", dsn)
	if err != nil {
		log.Fatal(errors.Errorf("%s: %w", dsn, err))
	}
	defer db.Close()

	oraDB, err := godror.DriverConn(ctx, db)
	if err != nil {
		return err
	}
	log.Println("Starting database")
	if err = oraDB.Startup(startupMode); err != nil {
		return err
	}

	db2, err := sql.Open("godror", "oracle://?sysdba=1")
	if err != nil {
		return err
	}
	defer db2.Close()

	log.Println("Mounting database")
	if _, err = db2.Exec("alter database mount"); err != nil {
		return err
	}
	log.Println("Opening database")
	if _, err = db2.Exec("alter database open"); err != nil {
		return err
	}
	return nil
}
Output:

type Subscription

type Subscription struct {
	ID uint64
	// contains filtered or unexported fields
}

Subscription for events in the DB.

func (*Subscription) Close

func (s *Subscription) Close() error

Close the subscription.

This code is EXPERIMENTAL yet!

func (*Subscription) Register

func (s *Subscription) Register(qry string, params ...interface{}) error

Register a query for Change Notification.

This code is EXPERIMENTAL yet!

type TableEvent

type TableEvent struct {
	Rows []RowEvent
	Name string
	Operation
}

TableEvent is for a Table-related event.

type TraceTag

type TraceTag struct {
	// ClientIdentifier - specifies an end user based on the logon ID, such as HR.HR
	ClientIdentifier string
	// ClientInfo - client-specific info
	ClientInfo string
	// DbOp - database operation
	DbOp string
	// Module - specifies a functional block, such as Accounts Receivable or General Ledger, of an application
	Module string
	// Action - specifies an action, such as an INSERT or UPDATE operation, in a module
	Action string
}

TraceTag holds tracing information for the session. It can be set on the session with ContextWithTraceTag.

type VersionInfo

type VersionInfo struct {
	ServerRelease                                           string
	Version, Release, Update, PortRelease, PortUpdate, Full uint8
}

VersionInfo holds version info returned by Oracle DB.

func ClientVersion

func ClientVersion(ctx context.Context, ex Execer) (VersionInfo, error)

ClientVersion returns the VersionInfo from the DB.

func ServerVersion

func ServerVersion(ctx context.Context, ex Execer) (VersionInfo, error)

ServerVersion returns the VersionInfo of the client.

func (VersionInfo) String

func (V VersionInfo) String() string

type Visibility

type Visibility uint32

Visibility constants represents visibility.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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