oracle

package
v1.0.0-...-9d7b6d9 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2016 License: Apache-2.0, BSD-3-Clause Imports: 18 Imported by: 4

Documentation

Overview

Package oracle is translated from cx_Oracle ((c) Anthony Tuininga) by Tamás Gulácsi

Index

Constants

View Source
const (
	// OracleVersion is the OCI version
	OracleVersion = C.ORACLE_VERSION_HEX
	// OracleV10_1 is version 10 rev 1 (begin of 4GB LOBs)
	OracleV10_1 = ((10 << 8) | 1)
	// OracleV12_1 is version 12 rev 1 (begin of 32kB strings)
	OracleV12_1 = ((12 << 8) | 1)
)
View Source
const (
	MaxStringChars = C.MAX_BINARY_BYTES
	MaxBinaryBytes = C.MAX_BINARY_BYTES
)

maximum number of characters/bytes applicable to strings/binaries

View Source
const (
	MaxInt     = int64(int(^uint(0) >> 1))
	IntIs64bit = MaxInt > (1 << 32)
)
View Source
const CTrace = false

CTrace is true iff we are printing TRACE messages

Variables

View Source
var (
	//CursorIsClosed prints cursor is closed
	CursorIsClosed = errgo.New("cursor is closed")
	//QueriesNotSupported prints queries not supported
	QueriesNotSupported = errgo.New("queries not supported: results undefined")
	//ListIsEmpty prints list is empty
	ListIsEmpty = errgo.New("list is empty")
)
View Source
var (
	Warning        = &Error{Code: -(1<<30 - 1), Message: "WARNING"}
	NeedData       = &Error{Code: -(1<<30 - 2), Message: "NEED_DATA"}
	NoDataFound    = &Error{Code: -(1<<30 - 3), Message: "NO_DATA_FOUND"}
	StillExecuting = &Error{Code: -(1<<30 - 4), Message: "STILL_EXECUTING"}
	Continue       = &Error{Code: -(1<<30 - 5), Message: "CONTINUE"}
	Other          = &Error{Code: -(1<<30 - 6), Message: "other"}
	InvalidHandle  = &Error{Code: -(1<<30 - 7), Message: "invalid handle"}
)

Error handling

View Source
var (
	//NotImplemented prints not implemented
	NotImplemented = errgo.New("not implemented")
	//ArrayTooLarge prints array too large
	ArrayTooLarge = errgo.New("array too large")
)
View Source
var BypassMultipleArgs = false

BypassMultipleArgs induces a bypass agains ORA-1008 when a keyword is used more than once in the statement It is false by default, as it makes Execute change the statement!

View Source
var CsIDAl32UTF8 C.ub2

CsIDAl32UTF8 holds the charaterset ID for UTF8

View Source
var DefaultArraySize uint = 50

DefaultArraySize is the default array (PL/SQL) size

View Source
var IsDebug bool

IsDebug print debug messages?

View Source
var (
	// Set it to something like
	// Log.SetHandler(log15.CallerStackHandler("%v", log15.StderrHandler))
	// if you want to see the call stack, too.
	Log = log15.New("lib", "goracle")
)

Log is discarded by default. Use Log.SetHandler to set.

Functions

func ClientVersion

func ClientVersion() []int32

ClientVersion returns the client's version (slice of 5 int32s)

func CountStatementVars

func CountStatementVars(statement string) map[string]int

CountStatementVars returns a mapping of the variable names found in statement, with the number of occurence as the map value

func FindStatementVars

func FindStatementVars(statement string) map[string][]int

FindStatementVars returns a mapping of the variable names found in statement, with the number of occurence as the map value

func FromOraText

func FromOraText(textp *C.OraText, length int) string

FromOraText converts from C.OraText to a string

func MakeDSN

func MakeDSN(host string, port int, sid, serviceName string) string

MakeDSN makea a data source name given the host port and SID.

func OracleVersionHex

func OracleVersionHex(major, minor int) int

OracleVersionHex returns the major.minor version as one number, ready to compare with OracleVersion.

func ProgrammingError

func ProgrammingError(text string) error

ProgrammingError returns a programming error

func SplitDSN

func SplitDSN(dsn string) (username, password, sid string)

SplitDSN splits username/password@sid

Types

type Connection

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

Connection stores the handles for a connection

func NewConnection

func NewConnection(username, password, dsn string, autocommit bool) (
	conn *Connection, err error)

NewConnection creates a new connection and initializes the connection members.

func (*Connection) AttrSet

func (conn *Connection) AttrSet(key C.ub4, value unsafe.Pointer, valueLength int) error

AttrSet sets an attribute on the connection identified by key setting value with valueLength length

func (*Connection) Begin

func (conn *Connection) Begin(formatID int, transactionID, branchID string) error

Begin begins a new transaction on the connection.

func (*Connection) Cancel

func (conn *Connection) Cancel() error

Cancel executes an OCIBreak() to cause an immediate (asynchronous) abort of any currently executing OCI function.

func (*Connection) Close

func (conn *Connection) Close() (err error)

Close the connection, disconnecting from the database.

func (*Connection) Commit

func (conn *Connection) Commit() error

Commit commits the transaction on the connection.

func (*Connection) Connect

func (conn *Connection) Connect(mode int64, twophase bool) error

Connect to the database. good minimal example: http://www.adp-gmbh.ch/ora/misc/oci/index.html

func (*Connection) Cursor

func (conn *Connection) Cursor() *Cursor

Cursor returns a new cursor.

func (*Connection) Free

func (conn *Connection) Free(freeEnvironment bool)

Free deallocates the connection, disconnecting from the database if necessary.

func (*Connection) GetEnvironment

func (conn *Connection) GetEnvironment() Environment

GetEnvironment returns a (non-modifiable) Environment of the connection

func (*Connection) IsConnected

func (conn *Connection) IsConnected() bool

IsConnected determines if the connection object is connected to the database.

func (*Connection) NewCursor

func (conn *Connection) NewCursor() *Cursor

NewCursor creates a new cursor (statement) referencing the connection.

func (*Connection) NlsSettings

func (conn *Connection) NlsSettings(cur *Cursor) (oci, client, database string, err error)

NlsSettings retrieves NLS parameters: OCI charset, client NLS_LANG and database NLS_LANG cur can be nil (in this case it allocates one)

func (*Connection) Ping

func (conn *Connection) Ping() error

Ping makes a round trip call to the server to confirm that the connection and server are active.

func (*Connection) Prepare

func (conn *Connection) Prepare() (bool, error)

Prepare commits (if there is anything, TWO-PAHSE) the transaction on the connection.

func (*Connection) Rollback

func (conn *Connection) Rollback() error

Rollback rolls back the transaction

func (*Connection) ServerAttrSet

func (conn *Connection) ServerAttrSet(key C.ub4, value unsafe.Pointer, valueLength int) error

ServerAttrSet sets an attribute on the server handle identified by key

func (*Connection) SessionAttrSet

func (conn *Connection) SessionAttrSet(key C.ub4, value unsafe.Pointer, valueLength int) error

SessionAttrSet sets an attribute on the session handle identified by key

type Cursor

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

Cursor holds the handles for a cursor

func NewCursor

func NewCursor(conn *Connection) *Cursor

NewCursor creates a new cursor

func (*Cursor) CallFunc

func (cur *Cursor) CallFunc(
	name string,
	returnType VariableType,
	parameters []interface{},
	keywordParameters map[string]interface{}) (interface{}, error)

CallFunc calls a stored function and return the return value of the function.

func (*Cursor) CallProc

func (cur *Cursor) CallProc(name string,
	parameters []interface{}, keywordParameters map[string]interface{}) (
	results []interface{}, err error)

CallProc calls a stored procedure and return the (possibly modified) arguments.

func (*Cursor) Close

func (cur *Cursor) Close()

Close the cursor.

func (Cursor) Connection

func (cu Cursor) Connection() *Connection

Connection returns the underlying Connection.

func (*Cursor) Execute

func (cur *Cursor) Execute(
	statement string,
	listArgs []interface{},
	keywordArgs map[string]interface{},
) error

Execute the statement. For pointer-backed Variables, get their values, too.

func (*Cursor) ExecuteMany

func (cur *Cursor) ExecuteMany(statement string, params []map[string]interface{}) error

ExecuteMany executes the statement many times. The number of times is equivalent to the number of elements in the array of dictionaries.

func (*Cursor) ExecuteManyPrepared

func (cur *Cursor) ExecuteManyPrepared(numIters uint) error

ExecuteManyPrepared executes the prepared statement the number of times requested. At this point, the statement must have been already prepared and the bind variables must have their values set.

func (*Cursor) FetchAll

func (cur *Cursor) FetchAll() ([][]interface{}, error)

FetchAll fetches all remaining rows from the cursor.

func (*Cursor) FetchMany

func (cur *Cursor) FetchMany(rowLimit int) ([][]interface{}, error)

FetchMany fetches multiple rows from the cursor based on the arraysize. for default (arraySize) row limit, use negative rowLimit

func (*Cursor) FetchOne

func (cur *Cursor) FetchOne() (row []interface{}, err error)

FetchOne fetches a single row from the cursor.

func (*Cursor) FetchOneInto

func (cur *Cursor) FetchOneInto(row ...interface{}) (err error)

FetchOneInto fetches a single row from the cursor into the given column pointers

func (*Cursor) GetBindNames

func (cur *Cursor) GetBindNames() ([]string, error)

GetBindNames returns a list of bind variable names.

func (*Cursor) GetDescription

func (cur *Cursor) GetDescription() (descs []VariableDescription, err error)

GetDescription returns a list of 7-tuples consisting of the description of the define variables.

func (Cursor) GetRowCount

func (cur Cursor) GetRowCount() int

GetRowCount returns the rowcount of the statement (0 for select, rows affected for DML)

func (*Cursor) IsDDL

func (cur *Cursor) IsDDL() bool

IsDDL checks whether the cursor is of Data Definition Language

func (*Cursor) IsOpen

func (cur *Cursor) IsOpen() bool

IsOpen checks whether the cursor is open

func (*Cursor) NewArrayVar

func (cur *Cursor) NewArrayVar(varType *VariableType, values []interface{}, size uint) (v *Variable, err error)

NewArrayVar creates an array bind variable and return it.

func (*Cursor) NewVar

func (cur *Cursor) NewVar(value interface{},
) (v *Variable, err error)

NewVar creates a bind variable and returns it. If value is a pointer, then after cur.Execute, data will be returned into it automatically, no need to call v.GetValue.

func (*Cursor) NewVariable

func (cur *Cursor) NewVariable(numElements uint, varType *VariableType, size uint) (v *Variable, err error)

NewVariable allocates a new variable

WARNING: if you want an array, use numElements > 1!

func (*Cursor) NewVariableArrayByValue

func (cur *Cursor) NewVariableArrayByValue(element interface{}, numElements uint) (*Variable, error)

NewVariableArrayByValue allocates a new PL/SQL array by looking at the data

func (*Cursor) NewVariableByValue

func (cur *Cursor) NewVariableByValue(value interface{}, numElements uint) (v *Variable, err error)

NewVariableByValue is the default method for determining the type of variable to use for the data.

func (*Cursor) Parse

func (cur *Cursor) Parse(statement string) error

Parse the statement without executing it. This also retrieves information about the select list for select statements.

func (*Cursor) Prepare

func (cur *Cursor) Prepare(statement, statementTag string) error

Prepare the statement for execution. statementTag is optional

func (*Cursor) SetInputSizesByName

func (cur *Cursor) SetInputSizesByName(types map[string]VariableType) error

SetInputSizesByName sets the sizes of the bind variables by name (map).

func (*Cursor) SetInputSizesByPos

func (cur *Cursor) SetInputSizesByPos(types []VariableType) error

SetInputSizesByPos sets the sizes of the bind variables by position (array).

func (*Cursor) SetOutputSize

func (cur *Cursor) SetOutputSize(outputSize, outputSizeColumn int)

SetOutputSize sets the size of all of the long columns or just one of them. use -1 for outputSizeColumn if set outputSize for all columns!

func (*Cursor) String

func (cur *Cursor) String() string

String implements Stringer on Cursor

type Environment

type Environment struct {
	MaxBytesPerCharacter uint
	FixedWidth           bool
	Encoding, Nencoding  string
	// contains filtered or unexported fields
}

Environment holds handles for the database environment

func NewEnvironment

func NewEnvironment() (*Environment, error)

NewEnvironment creates and initializes a new environment object

func (*Environment) AttrGet

func (env *Environment) AttrGet(parent unsafe.Pointer, parentType, key int,
	dst unsafe.Pointer, errText string) (int, error)

AttrGet gets the parent's attribute identified by key, and stores it in dst

func (*Environment) AttrGetName

func (env *Environment) AttrGetName(parent unsafe.Pointer, parentType, key int,
	errText string) ([]byte, error)

AttrGetName retrieves the name of the parent's attribute identified by key

func (*Environment) AttrSet

func (env *Environment) AttrSet(parent unsafe.Pointer, parentTyp C.ub4,
	key C.ub4, value unsafe.Pointer, valueLength int) error

AttrSet sets an attribute on the given parent pointer

func (*Environment) CheckStatus

func (env *Environment) CheckStatus(status C.sword, at string) error

CheckStatus checks for an error in the last call and if an error has occurred, retrieve the error message from the database environment

func (*Environment) Free

func (env *Environment) Free() error

Free frees the used handles

func (*Environment) FromEncodedString

func (env *Environment) FromEncodedString(text []byte) string

FromEncodedString returns string decoded from Oracle's representation

func (*Environment) GetCharacterSetName

func (env *Environment) GetCharacterSetName(attribute uint32) (string, error)

GetCharacterSetName retrieves the IANA character set name for the attribute.

type Error

type Error struct {
	Code    int
	Message string
	At      string
	Offset  int
}

Error is an error struct holding additional info

func NewError

func NewError(code int, message string) *Error

NewError creates a new error, pointing to the code with the given message

func NewErrorAt

func NewErrorAt(code int, message, at string) *Error

NewErrorAt creates a new error, pointing to the code with the given message

func (Error) Error

func (err Error) Error() string

Error returns a string representation of the error (implenets error)

func (Error) String

func (err Error) String() string

String prints a nice(er) error message (implements Stringer)

type ExternalLobVar

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

ExternalLobVar is an external LOB var type. It is NOT concurrent-safe ATM.

func NewExternalLobVar

func NewExternalLobVar(v *Variable,
	idx uint,
) *ExternalLobVar

NewExternalLobVar creates a new external LOB variable.

func (*ExternalLobVar) Close

func (lv *ExternalLobVar) Close() error

Close the LOB.

func (*ExternalLobVar) FileExists

func (lv *ExternalLobVar) FileExists() (bool, error)

FileExists returns a boolean indicating if the BFIILE lob exists.

func (*ExternalLobVar) GetChunkSize

func (lv *ExternalLobVar) GetChunkSize() (int, error)

GetChunkSize returns the chunk size that should be used when reading/writing the LOB in chunks.

func (*ExternalLobVar) GetFileName

func (lv *ExternalLobVar) GetFileName() (string, string, error)

GetFileName returns the directory alias and file name for the BFILE lob.

func (*ExternalLobVar) IsOpen

func (lv *ExternalLobVar) IsOpen() (bool, error)

IsOpen returns a boolean indicating if the lob is open or not.

func (*ExternalLobVar) Open

func (lv *ExternalLobVar) Open() error

Open the LOB to speed further accesses.

func (*ExternalLobVar) Read

func (lv *ExternalLobVar) Read(p []byte) (int, error)

Read returns a portion (or all) of the data in the external LOB variable.

WARNING: if you use concurrency with database/sql, and sometimes gets

"cannot get internal size of <ExternalLobVar>: -1073741817: invalid handle"
errors, then the culprit may be database/sql closing the underlying driver.Conn.

The usual reason for this is that you use QueryRow, which closes the connection right after the Scan. To fix this, don't be lazy and use Query, and the returned Rows.

func (*ExternalLobVar) ReadAll

func (lv *ExternalLobVar) ReadAll() ([]byte, error)

ReadAll returns all of the data in the external LOB variable.

func (*ExternalLobVar) ReadAt

func (lv *ExternalLobVar) ReadAt(p []byte, off int64) (int, error)

ReadAt returns a portion (or all) of the data in the external LOB variable.

func (*ExternalLobVar) Seek

func (lv *ExternalLobVar) Seek(offset int64, whence int) (ret int64, err error)

Seek as os.File.Seek: sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any.

func (*ExternalLobVar) SetFileName

func (lv *ExternalLobVar) SetFileName(dirAlias, name string) error

SetFileName sets the directory alias and file name for the BFILE lob.

func (*ExternalLobVar) Size

func (lv *ExternalLobVar) Size(inChars bool) (int64, error)

Size returns the size of the data in the LOB variable.

func (*ExternalLobVar) String

func (lv *ExternalLobVar) String() string

String returns a short representation of the ExternalLobVar

func (*ExternalLobVar) Trim

func (lv *ExternalLobVar) Trim(newSize int) error

Trim the LOB variable to the specified length.

func (*ExternalLobVar) Verify

func (lv *ExternalLobVar) Verify() error

Verify that the external LOB var is still valid.

func (*ExternalLobVar) Write

func (lv *ExternalLobVar) Write(p []byte) (int, error)

Write writes the value to the LOB variable; return the number of bytes written.

func (*ExternalLobVar) WriteAt

func (lv *ExternalLobVar) WriteAt(value []byte, off int64) (n int, err error)

WriteAt writes a value to the LOB variable at the specified offset; return the number of bytes written.

type OraTyper

type OraTyper interface {
	GetVarType() *VariableType
}

OraTyper is a Go => Oracle type conversion interface

type Pool

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

Pool is a simple Pool for connections.

func NewPool

func NewPool(dsn string) Pool

NewPool returns a new pool.

func (Pool) Get

func (p Pool) Get() (*Connection, error)

Get an old/new connection.

func (Pool) Put

func (p Pool) Put(cx *Connection)

Put the connection back to the pool.

type Variable

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

Variable holds the handles for a variable

func (Variable) AllocatedElements

func (v Variable) AllocatedElements() uint

//----------------------------------------------------------------------------- // Variable_Repr() // Return a string representation of the variable. //----------------------------------------------------------------------------- static PyObject *Variable_Repr(

udt_Variable *var)                  // variable to return the string for
{
    PyObject *valueRepr, *value, *module, *name, *result, *format, *formatArgs;

    if (var->isArray)
        value = Variable_GetArrayValue(var, var->actualElements);
    else if (var->allocatedElements == 1)
        value = Variable_GetSingleValue(var, 0);
    else value = Variable_GetArrayValue(var, var->allocatedElements);
    if (!value)
        return NULL;
    valueRepr = PyObject_Repr(value);
    Py_DECREF(value);
    if (!valueRepr)
        return NULL;
    format = cxString_FromAscii("<%s.%s with value %s>");
    if (!format) {
        Py_DECREF(valueRepr);
        return NULL;
    }
    if (GetModuleAndName(Py_TYPE(var), &module, &name) < 0) {
        Py_DECREF(valueRepr);
        Py_DECREF(format);
        return NULL;
    }
    formatArgs = PyTuple_Pack(3, module, name, valueRepr);
    Py_DECREF(module);
    Py_DECREF(name);
    Py_DECREF(valueRepr);
    if (!formatArgs) {
        Py_DECREF(format);
        return NULL;
    }
    result = cxString_Format(format, formatArgs);
    Py_DECREF(format);
    Py_DECREF(formatArgs);
    return result;
}

func (Variable) ArrayLength

func (v Variable) ArrayLength() uint

ArrayLength returns the number of allocated elements (array length for arrays)

func (*Variable) Bind

func (v *Variable) Bind(cur *Cursor, name string, pos uint) error

Bind allocates a variable and bind it to the given statement. bind to name or pos

func (*Variable) Free

func (v *Variable) Free()

Free an existing variable.

func (*Variable) GetValue

func (v *Variable) GetValue(arrayPos uint) (interface{}, error)

GetValue returns the value of the variable.

func (*Variable) GetValueInto

func (v *Variable) GetValueInto(dest interface{}, arrayPos uint) error

GetValueInto inserts the value of the variable into the given pointer

func (Variable) IsArray

func (v Variable) IsArray() bool

func (*Variable) Len

func (v *Variable) Len() int

Len returns the array's actual length

func (*Variable) SetValue

func (v *Variable) SetValue(arrayPos uint, value interface{}) error

SetValue sets the value of the variable. If value is a pointer, then v will put its gained data into it.

func (Variable) Size

func (v Variable) Size() uint

func (*Variable) String

func (v *Variable) String() string

String returns a (short) representation of the variable

type VariableDescription

type VariableDescription struct {
	Name                                              string
	Type, InternalSize, DisplaySize, Precision, Scale int
	NullOk                                            bool
}

VariableDescription holds the description of a variable

type VariableType

type VariableType struct {
	Name string
	// contains filtered or unexported fields
}

VariableType holds data for a variable

var (
	//DateTimeVarType is the variable type for DateTime
	DateTimeVarType *VariableType
	//IntervalVarType is the variable type for Interval
	IntervalVarType *VariableType
)
var (
	//ClobVarType is a VariableType for CLOB
	ClobVarType *VariableType
	//NClobVarType is a VariableType for NCLOB
	NClobVarType *VariableType
	//BlobVarType is a VariableType for BLOB
	BlobVarType *VariableType
	//BFileVarType is a VariableType for BFILE
	BFileVarType *VariableType
)
var (
	//LongStringVarType is a VariableType for LONG strings
	LongStringVarType *VariableType
	//LongBinaryVarType is a VariableType for RAW strings
	LongBinaryVarType *VariableType
)
var (
	//FloatVarType is a VariableType for floats
	FloatVarType *VariableType
	//NativeFloatVarType is a VariableType for native floatss
	NativeFloatVarType *VariableType
	//Int32VarType is a VariableType for int32s
	Int32VarType *VariableType
	//Int64VarType is a VariableType for int64s
	Int64VarType *VariableType
	//LongIntegerVarType is a VariableType for long ints
	LongIntegerVarType *VariableType
	//NumberAsStringVarType is a VariableType for numbers represented as strings
	NumberAsStringVarType *VariableType
	//BooleanVarType is a VariableType for bools
	BooleanVarType *VariableType
)
var (
	//StringVarType is a VariableType for VARCHAR2
	StringVarType *VariableType
	//FixedCharVarType is a VariableType for CHAR
	FixedCharVarType *VariableType
	//BinaryVarType is a VariableType for RAW
	BinaryVarType *VariableType
	//RowidVarType is a VariableType for ROWID
	RowidVarType *VariableType
)
var CursorVarType *VariableType

CursorVarType is the VariableType for a cursor

func VarTypeByValue

func VarTypeByValue(data interface{}) (vt *VariableType, size uint, numElements uint, err error)

VarTypeByValue returns a variable type given a Go object or error if the Go value does not have a corresponding variable type.

func (*VariableType) IsBinary

func (t *VariableType) IsBinary() bool

IsBinary returns whether the VariableType is a binary type

func (*VariableType) IsDate

func (t *VariableType) IsDate() bool

IsDate checks whether the variable type is Date or Interval

func (*VariableType) IsFloat

func (t *VariableType) IsFloat() bool

IsFloat returns whether the VariableType represents a float

func (*VariableType) IsInteger

func (t *VariableType) IsInteger() bool

IsInteger returns whether the VariableType represents an integer

func (*VariableType) IsNumber

func (t *VariableType) IsNumber() bool

IsNumber returns whether the VariableType represents a number

func (*VariableType) IsString

func (t *VariableType) IsString() bool

IsString returns whether the VariableType is a string type

func (*VariableType) NewVariable

func (t *VariableType) NewVariable(cur *Cursor, numElements uint, size uint) (*Variable, error)

NewVariable returns a new Variable of the given VariableType

func (*VariableType) String

func (t *VariableType) String() string

String returns a string representation of the VariableType

Jump to

Keyboard shortcuts

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