godror

package module
v0.42.2 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: Apache-2.0, BSD-3-Clause, MIT, + 1 more Imports: 31 Imported by: 229

README

Go PkgGoDev 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.

Build-time Requirements

  • Go 1.15
  • C compiler with CGO_ENABLED=1 - so cross-compilation is hard

Run-time Requirements

  • Oracle Client libraries - see ODPI-C

Although Oracle Client libraries are NOT required for compiling, they are needed at run time. Download the free Basic or Basic Light package from https://www.oracle.com/database/technologies/instant-client/downloads.html.

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 (but not in sql.Named)! For example, the array size of the returned PL/SQL arrays can be set with godror.ArraySize(2000) (default value is 1024).

Documentation

See Godror API Documentation and the Godror User Guide.

Installation

Run:

go get github.com/godror/godror@latest

Then install Oracle Client libraries and you're ready to go!

godror is cgo package. If you want to build your app using godror, you need gcc (a C compiler).

Important: because this is a CGO enabled package, you are required to set the environment variable CGO_ENABLED=1 and have a gcc compile present within your path.

See Godror Installation for more information.

Connection

To connect to Oracle Database use sql.Open("godror", dataSourceName), where dataSourceName is a logfmt-encoded parameter list. Specify at least "user", "password" and "connectString". For example:

db, err := sql.Open("godror", `user="scott" password="tiger" connectString="dbhost:1521/orclpdb1"`)

The connectString can be ANYTHING that SQL*Plus or Oracle Call Interface (OCI) accepts: a service name, an Easy Connect string like host:port/service_name, or a connect descriptor like (DESCRIPTION=...).

You can specify connection timeout seconds with "?connect_timeout=15" - Ping uses this timeout, NOT the Deadline in Context! Note that connect_timeout requires at least 19c client.

For more connection options, see Godor Connection Handling.

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.

As sql.DB will close the statemenet ASAP, for long-lived objects (LOB, REF CURSOR), you have to keep the Stmt alive: Prepare the statement, and Close only after finished with the Lob/Rows.

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.

As sql.DB will close the statemenet ASAP, you have to keep the Stmt alive: Prepare the statement, and Close only after finished with the Rows.

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

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 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.

Watch out, Oracle will error out if the CLOB is too large, and you have to use godror.Lob in such cases!

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 under the old project.

Timezone

See the documentation - but for short, the database's OS' time zone is used, as that's what SYSDATE/SYSTIMESTAMP uses. If you want something different (because you fill DATE columns differently), then set the "location" in the connection string, or the Timezone in the ConnectionParams accord to your chosen timezone.

Stored procedure returning cursor (result set)
var rset1, rset2 driver.Rows

const query = `BEGIN Package.StoredProcA(123, :1, :2); END;`

stmt, err := db.PrepareContext(ctx, query)
if err != nil {
    return fmt.Errorf("%s: %w", query, err)
}
defer stmt.Close()
if _, err := stmt.ExecContext(ctx, sql.Out{Dest: &rset1}, sql.Out{Dest: &rset2}); err != nil {
	log.Printf("Error running %q: %+v", query, err)
	return
}
defer rset1.Close()
defer rset2.Close()

cols1 := rset1.(driver.RowsColumnTypeScanType).Columns()
dests1 := make([]driver.Value, len(cols1))
for {
	if err := rset1.Next(dests1); err != nil {
		if err == io.EOF {
			break
		}
		rset1.Close()
		return err
	}
	fmt.Println(dests1)
}

cols2 := rset1.(driver.RowsColumnTypeScanType).Columns()
dests2 := make([]driver.Value, len(cols2))
for {
	if err := rset2.Next(dests2); err != nil {
		if err == io.EOF {
			break
		}
		rset2.Close()
		return err
	}
	fmt.Println(dests2)
}
Context with Deadline/Timeout

TL;DR; *always close sql.Rows ASAP!

Creating a watchdog goroutine, done channel for each call of rows.Next kills performance, so we create only one watchdog goroutine, at the first rows.Next call. It is defused after rows.Close (or the cursor is exhausted).

If it is not defused, it will Break the currently executing OCI call on the connection, when the Context is canceled/timeouted. You should always call rows.Close ASAP, but if you experience random Breaks, remember this warning!

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 run

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

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

Pre-commit

Download a staticcheck release and add this to .git/hooks/pre-commit:

#!/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

go run ./check
exec staticcheck
Guidelines

As ODPI stores the error buffer in a thread-local-storage, we must ensure that the error is retrieved on the same thread as the prvious function executed on.

This means we have to encapsulate each execute-then-retrieve-error sequence in runtime.LockOSThread() and runtime.UnlockOSThread(). For details, see #120.

This is automatically detected by go run ./check which should be called in the pre-commit hook.

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", dataSourceName) call can be the simple

user="login" password="password" connectString="host:port/service_name" sysdba=true

with additional params (here with the defaults):

sysdba=0
sysoper=0
poolMinSessions=1
poolMaxSessions=1000
poolMaxSessionsPerShard=
poolPingInterval=
poolIncrement=1
connectionClass=
standaloneConnection=0
enableEvents=0
heterogeneousPool=0
externalAuth=0
prelim=0
poolWaitTimeout=5m
poolSessionMaxLifetime=1h
poolSessionTimeout=30s
timezone=
noTimezoneCheck=
perSessionTimezone=
newPassword=
onInit="ALTER SESSION SET current_schema=my_schema"
configDir=
libDir=
stmtCacheSize=
charset=UTF-8
noBreakOnContextCancel=

These are the defaults. For external authentication, user and password should be empty with default value(0) for heterogeneousPool parameter. heterogeneousPool(valid for standaloneConnection=0) and externalAuth parameters are internally set. For Proxy support , sessionuser is enclosed in brackets [sessionuser].

To use a heterogeneous Pool with Proxy Support ,user and password parameters should be non-empty and parameter heterogeneousPool should be 1. If user,password are empty and heterogeneousPool is set to 1, different user and password can be passed in subsequent queries.

Many advocate that a static session pool (min=max, incr=0) is better, with 1-10 sessions per CPU thread. See https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-7DFBA826-7CC0-4D16-B19C-31D168069B54 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.

For connectionClass usage, see https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-CE6E4DCC-92DF-4946-92B8-2BDD9845DA35

If you specify server_type as POOLED in sid, DRCP is used. For what can be used as "sid", see https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-E5358DEA-D619-4B7B-A799-3D2F802500F1

Go strings are UTF-8, so the default charset should be used unless there's a really good reason to interfere with Oracle's character set conversion.

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 (
	// DefaultFetchArraySize is the fetch array size by default (if not changed through FetchArraySize statement option).
	DefaultFetchArraySize = C.DPI_DEFAULT_FETCH_ARRAY_SIZE

	// DefaultPrefetchCountis the number of prefetched rows by default (if not changed through PrefetchCount statement option).
	DefaultPrefetchCount = DefaultFetchArraySize

	// 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

	// DefaultPoolMinSessions specifies the default value for minSessions for pool creation.
	DefaultPoolMinSessions = dsn.DefaultPoolMinSessions
	// DefaultPoolMaxSessions specifies the default value for maxSessions for pool creation.
	DefaultPoolMaxSessions = dsn.DefaultPoolMaxSessions
	// DefaultSessionIncrement specifies the default value for increment for pool creation.
	DefaultSessionIncrement = dsn.DefaultSessionIncrement
	// 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 = dsn.DefaultConnectionClass
	// NoConnectionPoolingConnectionClass is a special connection class name to indicate no connection pooling.
	// It is the same as setting standaloneConnection=1
	NoConnectionPoolingConnectionClass = dsn.NoConnectionPoolingConnectionClass
	// DefaultSessionTimeout is the seconds before idle pool sessions get evicted
	DefaultSessionTimeout = dsn.DefaultSessionTimeout
	// DefaultWaitTimeout is the milliseconds to wait for a session to become available
	DefaultWaitTimeout = dsn.DefaultWaitTimeout
	// DefaultMaxLifeTime is the maximum time in seconds till a pooled session may exist
	DefaultMaxLifeTime = dsn.DefaultMaxLifeTime
	//DefaultStandaloneConnection holds the default for standaloneConnection.
	DefaultStandaloneConnection = dsn.DefaultStandaloneConnection
)
View Source
const (
	JSONOptDefault        = JSONOption(C.DPI_JSON_OPT_DEFAULT)
	JSONOptNumberAsString = JSONOption(C.DPI_JSON_OPT_NUMBER_AS_STRING)
)
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 DefaultBatchLimit = 1024
View Source
const MsgIDLength = 16
View Source
const StructTag = "godror"

StructTag is the prefix that tags godror-specific struct fields

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 (
	// ErrNotImplemented is returned when the functionality is not implemented
	ErrNotImplemented = errors.New("not implemented")
	// ErrBadDate is returned when the date is not assignable to Oracle DATE type
	ErrBadDate = errors.New("date out of range (year must be between -4713 and 9999, and must not be 0)")
)
View Source
var DefaultDeqOptions = DeqOptions{
	Mode:         DeqRemove,
	DeliveryMode: DeliverPersistent,
	Navigation:   NavNext,
	Visibility:   VisibleOnCommit,
	Wait:         0,
}

DefaultDeqOptions is the default set for NewQueue.

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

DefaultEnqOptions is the default set for NewQueue.

View Source
var DriverName = "godror : " + Version

DriverName is set on the connection to be seen in the DB

It cannot be longer than 30 bytes !

View Source
var ErrCLOB = errors.New("CLOB is not supported")
View Source
var ErrInvalidJSON = errors.New("invalid JSON Document")
View Source
var ErrInvalidType = errors.New("invalid JSON Scalar Type")
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 Version = "v0.42.2"

Functions

func CallbackSubscr

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

CallbackSubscr is the callback for C code on subscription event.

func ContextWithLogger added in v0.27.0

func ContextWithLogger(ctx context.Context, logger *slog.Logger) context.Context

ContextWithLogger returns a context with the given logger.

func ContextWithParams added in v0.15.0

func ContextWithParams(ctx context.Context, commonParams dsn.CommonParams, connParams dsn.ConnParams) context.Context

ContextWithParams returns a context with the specified parameters. These parameters are used to modify the session acquired from the pool.

WARNING: set ALL the parameters you don't want as default (Timezone, for example), as it won't inherit the pool's params! Start from an already parsed ConnectionParams for example.

If a standalone connection is being used this will have no effect.

Also, you should disable the Go connection pool with DB.SetMaxIdleConns(0).

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.

WARNING: this will NOT set other elements of the parameter hierarchy, they will be inherited.

If a standalone connection is being used this will have no effect.

Also, you should disable the Go connection pool with DB.SetMaxIdleConns(0).

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.

Warning! EnableDbmsOutput, the code that uses DBMS_OUTPUT and ReadDbmsOutput must all execute on the same session - for example by using the same *sql.Tx, or *sql.Conn. A *sql.DB connection pool won't work!

func GuardWithFinalizers added in v0.39.3

func GuardWithFinalizers(b bool)

GuardWithFinalizers sets whether we should guard resources with Finalizers.

func IsBadConn added in v0.24.3

func IsBadConn(err error) bool

func LogLingeringResourceStack added in v0.39.3

func LogLingeringResourceStack(b bool)

LogLingeringResourceStack sets whether to log the lingering resource's (allocation) stack in Finalizer. Default is to not log, as it consumes a few kiB for each resource (stmt, conn, queue, object type).

Should not cause problem with bug-free program, that closes all stmt's ASAP.

For programs that'd benefit this stack, enabling it may raise memory consumption significantly over time. So enable it only for debugging!

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(params dsn.ConnectionParams) driver.Connector

NewConnector returns a driver.Connector to be used with sql.OpenDB, (for the default Driver registered with godror)

ConnectionParams must be complete, so start with what ParseDSN returns!

func NewDriver added in v0.23.1

func NewDriver() *drv

func NewSessionIniter

func NewSessionIniter(m map[string]string) func(context.Context, driver.ConnPrepareContext) error

NewSessionIniter returns a function suitable for use in NewConnector as onInit,

Deprecated. Use ParseDSN + ConnectionParams.SetSessionParamOnInit and NewConnector. which calls "ALTER SESSION SET <key>='<value>'" for each element of the given map.

func Raw added in v0.15.0

func Raw(ctx context.Context, ex Execer, f func(driverConn Conn) error) error

Raw executes f on the given *sql.DB or *sql.Conn.

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))

Warning! EnableDbmsOutput, the code that uses DBMS_OUTPUT and ReadDbmsOutput must all execute on the same session - for example by using the same *sql.Tx, or *sql.Conn. A *sql.DB connection pool won't work!

func ReplaceQuestionPlacholders added in v0.35.1

func ReplaceQuestionPlacholders(qry string) string

ReplaceQuestionPlacholders replaces ? marks with Oracle-supported :%d placeholders.

THIS IS JUST A SIMPLE CONVENIENCE FUNCTION, WITHOUT WARRANTIES: - does not handle '?' - mark in string - does not handle --? - mark in line comment - does not handle /*?*/ - mark in block comment

func SetLogger added in v0.27.0

func SetLogger(logger *slog.Logger)

SetLogger sets the global logger.

func Timezone

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

Timezone returns the timezone of the connection (database).

func WithDeqOptions added in v0.19.4

func WithDeqOptions(o DeqOptions) queueOption

WithDeqOptions returns a queueOption usable in NewQueue, applying the given DeqOptions.

func WithEnqOptions added in v0.19.4

func WithEnqOptions(o EnqOptions) queueOption

WithEnqOptions returns a queueOption usable in NewQueue, applying the given EnqOptions.

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 Annotation added in v0.41.0

type Annotation struct{ Key, Value string }

type Batch added in v0.25.6

type Batch struct {
	Stmt *sql.Stmt

	Limit int
	// contains filtered or unexported fields
}

Batch collects the Added rows and executes in batches, after collecting Limit number of rows. The default Limit is DefaultBatchLimit.

func (*Batch) Add added in v0.25.6

func (b *Batch) Add(ctx context.Context, values ...interface{}) error

Add the values. The first call initializes the storage, so all the subsequent calls to Add must use the same number of values, with the same types.

When the number of added rows reaches Size, Flush is called.

func (*Batch) Flush added in v0.25.6

func (b *Batch) Flush(ctx context.Context) error

Flush executes the statement is and the clears the storage.

func (*Batch) Size added in v0.25.6

func (b *Batch) Size() int

Size returns the buffered (unflushed) number of records.

type Column

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

Column holds the info from a column.

type CommonParams added in v0.15.0

type CommonParams = dsn.CommonParams

dsn is separated out for fuzzing, but keep it as "internal"

type CompileError

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

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

func GetCompileErrors

func GetCompileErrors(ctx context.Context, queryer Querier, 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)
	Startup(StartupMode) error
	Shutdown(ShutdownMode) error

	NewSubscription(string, func(Event), ...SubscriptionOption) (*Subscription, error)
	GetObjectType(name string) (*ObjectType, error)
	NewData(baseType interface{}, SliceLen, BufSize int) ([]*Data, error)
	NewTempLob(isClob bool) (*DirectLob, error)

	Timezone() *time.Location
	GetPoolStats() (PoolStats, error)
}

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

func DriverConn

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

DriverConn will return the connection of ex. For connection pools (*sql.DB) this may be a new connection.

type ConnParams added in v0.15.0

type ConnParams = dsn.ConnParams

dsn is separated out for fuzzing, but keep it as "internal"

type ConnPool added in v0.34.0

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

ConnPool is a concurrent-safe fixed size connection pool.

This is a very simple implementation, usable, but serving more as an example - if possible, use *sql.DB !

func NewConnPool added in v0.34.0

func NewConnPool(pool interface {
	Conn(context.Context) (*sql.Conn, error)
}, size int) *ConnPool

NewConnPool returns a connection pool that acquires new connections from the given pool (an *sql.DB for example).

The default size is 1.

func (*ConnPool) Close added in v0.34.0

func (p *ConnPool) Close() error

Close releases all the pooled resources.

func (*ConnPool) Conn added in v0.34.0

func (p *ConnPool) Conn(ctx context.Context) (*PooledConn, error)

Conn returns a pooled connection if there exists one, or creates a new if not.

You must call Close on the returned PooledConn to return it to the pool!

type ConnectionParams

type ConnectionParams = dsn.ConnectionParams

dsn is separated out for fuzzing, but keep it as "internal"

func ParseConnString

func ParseConnString(s string) (ConnectionParams, error)

ParseConnString is deprecated, use ParseDSN.

func ParseDSN added in v0.19.0

func ParseDSN(dataSourceName string) (P ConnectionParams, err error)

ParseDSN parses the given dataSourceName and returns a ConnectionParams structure for use in sql.OpenDB(godror.NewConnector(P)).

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) GetJSON added in v0.26.0

func (d *Data) GetJSON() JSON

func (*Data) GetJSONArray added in v0.26.0

func (d *Data) GetJSONArray() JSONArray

func (*Data) GetJSONObject added in v0.26.0

func (d *Data) GetJSONObject() JSONObject

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, in the local time zone.

func (*Data) GetTimeIn added in v0.15.0

func (d *Data) GetTimeIn(serverTZ *time.Location) time.Time

GetTimeIn gets Time from data using the given Location (use the server's for correct value).

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                            []byte
	Transformation                   string
	Mode                             DeqMode
	DeliveryMode                     DeliveryMode
	Navigation                       DeqNavigation
	Visibility                       Visibility
	Wait                             time.Duration
}

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) GetFileName added in v0.20.0

func (dl *DirectLob) GetFileName() (dir, file string, err error)

GetFileName Return directory alias and file name for a BFILE type 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.

CLOB's offset must be in amount of characters, and does not work reliably!

WARNING: for historical reasons, Oracle stores CLOBs and NCLOBs using the UTF-16 encoding, regardless of what encoding is otherwise in use by the database. The number of characters, however, is defined by the number of UCS-2 codepoints. For this reason, if a character requires more than one UCS-2 codepoint, the size returned will be inaccurate and care must be taken to account for the difference!

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.

WARNING: for historical reasons, Oracle stores CLOBs and NCLOBs using the UTF-16 encoding, regardless of what encoding is otherwise in use by the database. The number of characters, however, is defined by the number of UCS-2 codepoints. For this reason, if a character requires more than one UCS-2 codepoint, the size returned will be inaccurate and care must be taken to account for the difference!

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 DomainAnnotation added in v0.41.0

type DomainAnnotation struct {
	DomainName  string
	Annotations []Annotation
}

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 {
	Err     error
	DB      string
	Tables  []TableEvent
	Queries []QueryEvent
	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 JSON added in v0.26.0

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

JSON holds the JSON data to/from Oracle. It is like a root node in JSON tree.

func (JSON) Get added in v0.26.0

func (j JSON) Get(data *Data, opts JSONOption) error

Get retrieves the data stored in JSON based on option, opts.

func (JSON) GetJSONArray added in v0.26.0

func (j JSON) GetJSONArray(opts JSONOption) (JSONArray, error)

GetJSONArray retrieves JSONArray from JSON based on option, opts. It returns error if JSON doesnt represent array type.

func (JSON) GetJSONObject added in v0.26.0

func (j JSON) GetJSONObject(opts JSONOption) (JSONObject, error)

GetJSONObject retrieves JSONObject from JSON based on option, opts. It returns error if JSON doesnt represent object type.

func (JSON) GetJSONScalar added in v0.26.0

func (j JSON) GetJSONScalar(opts JSONOption) (JSONScalar, error)

GetJSONScalar retrieves JSONScalar from JSON based on option, opts.

func (JSON) GetValue added in v0.26.0

func (j JSON) GetValue(opts JSONOption) (interface{}, error)

GetValue converts the native DB type stored in JSON into an interface value. The scalar values stored in JSON get converted as below.

map[string]interface{}, for JSON object type
[]interface{}, for JSON arrays
godror.Number or float64 based on options for NUMBER
bool , for boolean
byte[], for RAW
time.Duration, for INTERVAL DAY TO SECOND
time.Time, for TIMESTAMP
string, for VARCHAR2(string)

func (JSON) String added in v0.26.0

func (j JSON) String() string

String returns standard JSON formatted string

type JSONArray added in v0.26.0

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

JSONArray represents the array input.

func (JSONArray) Get added in v0.26.0

func (j JSONArray) Get(nodes []Data) []Data

Get returns the data array from JSONArray

func (JSONArray) GetElement added in v0.26.0

func (j JSONArray) GetElement(i int) Data

GetElement returns the ith element in JSONArray as data.

func (JSONArray) GetValue added in v0.26.0

func (j JSONArray) GetValue() (nodes []interface{}, err error)

GetValue converts native DB type, array into []interface{}.

func (JSONArray) Len added in v0.26.0

func (j JSONArray) Len() int

Len returns the number of elements in the JSONArray.

type JSONObject added in v0.26.0

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

JSONObject represents the map input.

func (JSONObject) Get added in v0.26.0

func (j JSONObject) Get() map[string]Data

Get returns the map, map[string]Data from JSONObject

func (JSONObject) GetInto added in v0.26.0

func (j JSONObject) GetInto(v interface{})

GetInto takes pointer to struct and populates the fields. The struct name fields are matched with DB JSON keynames but not the struct json tags.

func (JSONObject) GetValue added in v0.26.0

func (j JSONObject) GetValue() (m map[string]interface{}, err error)

GetValue converts native DB type, array into map[string]interface{}.

func (JSONObject) Len added in v0.26.0

func (j JSONObject) Len() int

Len returns the number of keys in the JSONObject

type JSONOption added in v0.26.0

type JSONOption uint8

JSONOption provides an option to retrieve scalar values from JSON tree.

DPI_JSON_OPT_NUMBER_AS_STRING - returns value stored as NUMBER in DB as godror.Number. DPI_JSON_OPT_DEAFULT - returns value stored as NUMBER in DB as float64.

type JSONScalar added in v0.26.0

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

JSONScalar holds the JSON data to/from Oracle. It includes all scalar values such as int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string, map, array, string, byte[], time.Time, time.Duration, godror.Number and bool.

func (JSONScalar) GetValue added in v0.26.0

func (j JSONScalar) GetValue() (val interface{}, err error)

GetValue converts native DB type stored in JSONScalar to an interface value. The scalar value stored in JSONScalar gets converted as below.

map[string]interface{}, for JSON object type
[]interface{}, for JSON arrays
godror.Number or float64 based on options for NUMBER
bool , for JSON boolean
byte[], for JSON RAW
time.Duration, for INTERVAL DAY TO SECOND
time.Time, for TIMESTAMP
string, for VARCHAR2(string)

type JSONString added in v0.26.0

type JSONString struct {
	Flags JSONStringFlags // standard , extended types for OSON, BSON
	Value string          // JSON input
}

JSONString encapsulates JSON formatted string.

type JSONStringFlags added in v0.26.0

type JSONStringFlags uint

JSONStringFlags represents the input JSON string format. It can be standard JSON format or it can include ORACLE extended types, BSON extended types.

type JSONValue added in v0.26.0

type JSONValue struct {
	Value interface{}
}

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!

func (*Lob) NewBufferedReader added in v0.24.0

func (lob *Lob) NewBufferedReader(size int) *bufio.Reader

NewBufferedReader returns a new bufio.Reader with the given size (or 1M if 0).

func (*Lob) ReadAt added in v0.27.1

func (lob *Lob) ReadAt(p []byte, off int64) (int, error)

ReadAt exposes the underlying Reader's ReadAt method, if it is supported.

func (*Lob) Size added in v0.27.1

func (lob *Lob) Size() (int64, error)

Size exposes the underlying Reader's Size method, if it is supported.

func (*Lob) WriteTo added in v0.24.0

func (lob *Lob) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes data to w until there's no more data to write or when an error occurs. The return value n is the number of bytes written. Any error encountered during the write is also returned.

Will use Lob.Reader.WriteTo, if Lob.Reader implements io.WriterTo.

type Message

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

Message is a message - either received or being sent.

func (Message) Deadline added in v0.15.0

func (M Message) Deadline() time.Time

Deadline return the message's intended deadline: enqueue time + delay + expiration.

func (Message) IsZero added in v0.20.0

func (M Message) IsZero() bool

type MessageState

type MessageState uint32

MessageState constants representing message's state.

type NullTime added in v0.11.0

type NullTime = sql.NullTime

NullTime is an alias for sql.NullTime

type Number

type Number string

Number as string

func (*Number) Compose added in v0.20.6

func (N *Number) Compose(form byte, negative bool, coefficient []byte, exponent int32) error

Compose sets the internal decimal value from parts. If the value cannot be represented then an error should be returned.

func (Number) Decompose added in v0.20.6

func (N Number) Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)

Decompose returns the internal decimal state in parts. If the provided buf has sufficient capacity, buf may be returned as the coefficient with the value set and length set as appropriate.

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) AsMap added in v0.30.0

func (O *Object) AsMap(recursive bool) (map[string]interface{}, error)

AsMap is a convenience function that returns the object's attributes as a map[string]interface{}. It allocates, so use it as a guide how to implement your own converter function.

If recursive is true, then the embedded objects are converted, too, recursively.

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) FromJSON added in v0.30.1

func (O *Object) FromJSON(dec *json.Decoder) error

func (*Object) FromMap added in v0.30.0

func (O *Object) FromMap(recursive bool, m map[string]interface{}) error

FromMap populates the Object starting from a map, according to the Object's Attributes.

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.

func (*Object) String added in v0.30.0

func (O *Object) String() string

func (*Object) ToJSON added in v0.30.0

func (O *Object) ToJSON(w io.Writer) error

ToJSON writes the Object as JSON into the io.Writer.

type ObjectAttribute

type ObjectAttribute struct {
	*ObjectType

	Name     string
	Sequence uint32
	// 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) AsMapSlice added in v0.30.0

func (O ObjectCollection) AsMapSlice(recursive bool) ([]map[string]interface{}, error)

AsMapSlice retrieves the collection into a []map[string]interface{}. If recursive is true, then all subsequent Objects/ObjectsCollections are translated.

This is horrendously inefficient, use it only as a guide!

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) FromJSON added in v0.30.1

func (O ObjectCollection) FromJSON(dec *json.Decoder) error

func (ObjectCollection) FromMapSlice added in v0.30.0

func (O ObjectCollection) FromMapSlice(recursive bool, m []map[string]interface{}) error

FromMapSlice populates the ObjectCollection starting from a slice of map, according to the Collections's Attributes.

func (ObjectCollection) FromSlice added in v0.38.0

func (O ObjectCollection) FromSlice(v []interface{}) error

FromSlice read from a slice of primitives.

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) String added in v0.30.0

func (O ObjectCollection) String() string

func (ObjectCollection) ToJSON added in v0.30.0

func (O ObjectCollection) ToJSON(w io.Writer) error

ToJSON writes the ObjectCollection as JSON to the io.Writer.

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 {
	CollectionOf *ObjectType
	Attributes   map[string]ObjectAttribute

	Schema, Name, PackageName           string
	Annotations                         []Annotation
	DBSize, ClientSizeInBytes, CharSize int

	OracleTypeNum C.dpiOracleTypeNum
	NativeTypeNum C.dpiNativeTypeNum
	DomainAnnotation
	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) AttributeNames added in v0.34.0

func (t *ObjectType) AttributeNames() []string

AttributeNames returns the Attributes' names ordered as on the database (by ObjectAttribute.Sequence).

func (*ObjectType) Close added in v0.15.0

func (t *ObjectType) Close() error

Close releases a reference to the object type.

func (*ObjectType) FullName

func (t *ObjectType) FullName() string

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

func (*ObjectType) IsObject added in v0.30.1

func (t *ObjectType) IsObject() bool

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 ObjectTypeName added in v0.34.0

type ObjectTypeName struct{}

ObjectTypeName is for allowing reflection-based Object - struct mapping.

Include an ObjectTypeName in your struct, and set the "godror" struct tag to the type name.

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.

Use it "naked", without sql.Named!

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.

Use it "naked", without sql.Named!

func ArraySize

func ArraySize(arraySize int) Option

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

Use it "naked", without sql.Named!

func BoolToString added in v0.12.0

func BoolToString(trueVal, falseVal string) Option

BoolToString is an option that governs convertsion from bool to string in the database. This is for converting from bool to string, from outside of the database (which does not have a BOOL(EAN) column (SQL) type, only a BOOLEAN PL/SQL type).

This will be used only with DML statements and when the PlSQLArrays Option is not used.

For the other way around, use an sql.Scanner that converts from string to bool. For example:

type Booler bool
var _ sql.Scanner = Booler{}
func (b Booler) Scan(src interface{}) error {
  switch src := src.(type) {
    case int: *b = x == 1
    case string: *b = x == "Y" || x == "T"  // or any string your database model treats as truth value
    default: return fmt.Errorf("unknown scanner source %T", src)
  }
  return nil
}

Such a type cannot be included in this package till we can inject the truth strings into the scanner method.

func ClobAsString deprecated

func ClobAsString() Option

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

Deprecated: CLOBs are returned as string by default - for CLOB, use LobAsReader. EXCEPT for Object attributes, those are returned as-is - as lobReader.

Use it "naked", without sql.Named!

func DeleteFromCache added in v0.25.4

func DeleteFromCache() Option

DeleteFromCache is an option to delete the statement from the statement cache.

func FetchArraySize added in v0.17.0

func FetchArraySize(rowCount int) Option

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

For choosing FetchArraySize and PrefetchCount, see https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#choosing-values-for-arraysize-and-prefetchrows

Use it "naked", without sql.Named!

func FetchRowCount

func FetchRowCount(rowCount int) Option

FetchRowCount is DEPRECATED, use FetchArraySize.

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

Use it "naked", without sql.Named!

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!

EXCEPT for Object attributes, those are returned as-is - as lobReader.

Use it "naked", without sql.Named!

func NullDateAsZeroTime added in v0.16.0

func NullDateAsZeroTime() Option

NullDateAsZeroTime is an option to return NULL DATE columns as time.Time{} instead of nil. If you must Scan into time.Time (cannot use sql.NullTime), this may help.

func NumberAsFloat64 added in v0.38.0

func NumberAsFloat64() Option

NumberAsFloat64 is an option to return numbers as float64, not Number (which is a string).

func NumberAsString

func NumberAsString() Option

NumberAsString is 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.

Use it "naked", without sql.Named!

func PrefetchCount added in v0.17.0

func PrefetchCount(rowCount int) Option

PrefetchCount returns an option to set the rows to be fetched, overriding DefaultPrefetchCount.

For choosing FetchArraySize and PrefetchCount, see https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#choosing-values-for-arraysize-and-prefetchrows

WARNING: If you will take a REF CURSOR, the driver will start prefetching, so if you give that cursor to a stored procedure, that won't see the prefetched rows!

Use it "naked", without sql.Named!

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) Action added in v0.13.0

func (oe *OraErr) Action() string

Action returns the internal action that was being performed when the error took place. This is a null-terminated ASCII string.

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) FunName added in v0.13.0

func (oe *OraErr) FunName() string

FunName returns the public ODPI-C function name which was called in which the error took place. This is a null-terminated ASCII string.

func (*OraErr) IsWarning added in v0.17.0

func (oe *OraErr) IsWarning() bool

func (*OraErr) Message

func (oe *OraErr) Message() string

Message returns the OraErr's message.

func (*OraErr) Offset added in v0.13.0

func (oe *OraErr) Offset() int

Offset returns the parse error offset (in bytes) when executing a statement or the row offset when performing bulk operations or fetching batch error information. If neither of these cases are true, the value is 0.

func (*OraErr) Recoverable added in v0.13.0

func (oe *OraErr) Recoverable() bool

Recoverable indicates if the error is recoverable. This is always false unless both client and server are at release 12.1 or higher.

func (*OraErr) SQLState added in v0.13.0

func (oe *OraErr) SQLState() string

SQLState returns the SQLSTATE code associated with the error. This is a 5 character null-terminated string.

type Password added in v0.18.0

type Password = dsn.Password

dsn is separated out for fuzzing, but keep it as "internal"

func NewPassword added in v0.18.0

func NewPassword(s string) Password

type PoolParams added in v0.15.0

type PoolParams = dsn.PoolParams

dsn is separated out for fuzzing, but keep it as "internal"

type PoolStats added in v0.16.0

type PoolStats struct {
	Busy, Open, Max                   uint32
	MaxLifetime, Timeout, WaitTimeout time.Duration
}

PoolStats contains Oracle session pool statistics

func (PoolStats) AsDBStats added in v0.34.0

func (p PoolStats) AsDBStats() sql.DBStats

func (PoolStats) String added in v0.16.0

func (s PoolStats) String() string

type PooledConn added in v0.34.0

type PooledConn struct {
	*sql.Conn
	// contains filtered or unexported fields
}

PooledConn is a wrapped *sql.Conn that puts back the Conn into the pool on Close is possible (or does a real Close when the pool is full).

func (*PooledConn) Close added in v0.34.0

func (c *PooledConn) Close() error

Close tries to return the connection to the pool, or Closes it when the pools is full.

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, options ...queueOption) (*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) PurgeExpired added in v0.31.0

func (Q *Queue) PurgeExpired(ctx context.Context) error

Purge the expired messages from 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"
	"fmt"
	"log"

	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(fmt.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()
	err := godror.Raw(ctx, db, func(oraDB godror.Conn) error {
		log.Printf("Beginning shutdown %v", shutdownMode)
		return oraDB.Shutdown(shutdownMode)
	})
	if 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")
	return godror.Raw(ctx, db, func(oraDB godror.Conn) error {
		return oraDB.Shutdown(godror.ShutdownFinal)
	})
}
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"
	"fmt"
	"log"

	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(fmt.Errorf("%s: %w", dsn, err))
	}
	defer db.Close()

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

	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 SubscriptionOption added in v0.13.0

type SubscriptionOption func(*subscriptionParams)

SubscriptionOption is for setting various parameters of the Subscription.

func SubscrClientInitiated added in v0.13.0

func SubscrClientInitiated(b bool) SubscriptionOption

SubscrClientInitiated sets whether the subscription is client-initated.

func SubscrHostPort added in v0.13.0

func SubscrHostPort(address string, port uint32) SubscriptionOption

SubscrHostPort is a SubscriptionOption that sets tha IPAddress and Port to the specified values.

The address is on which the subscription listens to receive notifications, for a server-initiated connection.

The address can be an IPv4 address in dotted decimal format such as 192.1.2.34 or an IPv6 address in hexadecimal format such as 2001:0db8:0000:0000:0217:f2ff:fe4b:4ced.

By default (address is the empty string), an IP address will be selected by the Oracle client.

The port number on which to receive notifications, for a server-initiated connection.

The default value of 0 means that a port number will be selected by the Oracle client.

type TableEvent

type TableEvent struct {
	Name string
	Rows []RowEvent
	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.

func (TraceTag) String added in v0.18.0

func (tt TraceTag) String() string

type UserPasswdConnClassTag added in v0.24.0

type UserPasswdConnClassTag struct {
	Username  string
	Password  dsn.Password
	ConnClass string
}

UserPasswdConnClassTag consists of Username, Password and ConnectionClass values that can be set with ContextWithUserPassw

func (UserPasswdConnClassTag) String added in v0.33.1

func (up UserPasswdConnClassTag) String() string

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) (vi VersionInfo, err error)

ClientVersion returns the VersionInfo from the DB.

func ServerVersion

func ServerVersion(ctx context.Context, ex Execer) (vi VersionInfo, err 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