Documentation
¶
Index ¶
- Constants
- func ColAttribute(stmt SQLHSTMT, colNum SQLUSMALLINT, fieldId SQLUSMALLINT, charAttr []byte) (strLen SQLSMALLINT, numAttr SQLLEN, ret SQLRETURN)
- func DescribeCol(stmt SQLHSTMT, colNum SQLUSMALLINT, colName []byte) (nameLen SQLSMALLINT, dataType SQLSMALLINT, colSize SQLULEN, ...)
- func DriverConnect(dbc SQLHDBC, hwnd uintptr, inConnStr string, outConnStr []byte, ...) (outLen SQLSMALLINT, ret SQLRETURN)
- func FormatReturnCode(ret SQLRETURN) string
- func GetDiagRec(handleType SQLSMALLINT, handle SQLHANDLE, recNum SQLSMALLINT, sqlState []byte, ...) (nativeError SQLINTEGER, msgLen SQLSMALLINT, ret SQLRETURN)
- func GetInfo(dbc SQLHDBC, infoType SQLUSMALLINT, infoValue []byte) (stringLength SQLSMALLINT, ret SQLRETURN)
- func IsConnectionError(err error) bool
- func IsDataTruncation(err error) bool
- func IsRetryable(err error) bool
- func IsSuccess(ret SQLRETURN) bool
- func NewError(handleType SQLSMALLINT, handle SQLHANDLE) error
- func SQLTypeName(sqlType SQLSMALLINT) string
- type BatchResult
- type ColumnBuffer
- type Conn
- func (c *Conn) Begin() (driver.Tx, error)
- func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)
- func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error
- func (c *Conn) Close() error
- func (c *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)
- func (c *Conn) IsValid() bool
- func (c *Conn) Ping(ctx context.Context) error
- func (c *Conn) Prepare(query string) (driver.Stmt, error)
- func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)
- func (c *Conn) PrepareWithCursor(ctx context.Context, query string, cursorType CursorType) (driver.Stmt, error)
- func (c *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)
- func (c *Conn) ResetSession(ctx context.Context) error
- type Connector
- type ConnectorOption
- type CursorType
- type Decimal
- type DecimalError
- type DiagRecord
- type Driver
- type Error
- type Errors
- type GUID
- type IntervalDaySecond
- type IntervalYearMonth
- type LastInsertIdBehavior
- type NamedParams
- type OutputParam
- type ParamDirection
- type ParameterError
- type Result
- type Rows
- func (r *Rows) Absolute(row int64) error
- func (r *Rows) Close() error
- func (r *Rows) ColumnTypeDatabaseTypeName(index int) string
- func (r *Rows) ColumnTypeLength(index int) (length int64, ok bool)
- func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool)
- func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
- func (r *Rows) ColumnTypeScanType(index int) reflect.Type
- func (r *Rows) Columns() []string
- func (r *Rows) First() error
- func (r *Rows) GetRowData(dest []driver.Value) error
- func (r *Rows) HasNextResultSet() bool
- func (r *Rows) Last() error
- func (r *Rows) Next(dest []driver.Value) error
- func (r *Rows) NextResultSet() error
- func (r *Rows) Prior() error
- func (r *Rows) Relative(offset int64) error
- type SQLCHAR
- type SQLHANDLE
- type SQLHDBC
- type SQLHDESC
- type SQLHENV
- type SQLHSTMT
- type SQLINTEGER
- type SQLLEN
- type SQLRETURN
- func AllocHandle(handleType SQLSMALLINT, inputHandle SQLHANDLE, outputHandle *SQLHANDLE) SQLRETURN
- func BindParameter(stmt SQLHSTMT, paramNum SQLUSMALLINT, ioType SQLSMALLINT, ...) SQLRETURN
- func Cancel(stmt SQLHSTMT) SQLRETURN
- func CloseCursor(stmt SQLHSTMT) SQLRETURN
- func Disconnect(dbc SQLHDBC) SQLRETURN
- func EndTran(handleType SQLSMALLINT, handle SQLHANDLE, completionType SQLSMALLINT) SQLRETURN
- func ExecDirect(stmt SQLHSTMT, query string) SQLRETURN
- func Execute(stmt SQLHSTMT) SQLRETURN
- func Fetch(stmt SQLHSTMT) SQLRETURN
- func FetchScroll(stmt SQLHSTMT, fetchOrientation SQLSMALLINT, fetchOffset SQLLEN) SQLRETURN
- func FreeHandle(handleType SQLSMALLINT, handle SQLHANDLE) SQLRETURN
- func FreeStmt(stmt SQLHSTMT, option SQLUSMALLINT) SQLRETURN
- func GetData(stmt SQLHSTMT, colNum SQLUSMALLINT, targetType SQLSMALLINT, ...) SQLRETURN
- func MoreResults(stmt SQLHSTMT) SQLRETURN
- func NumParams(stmt SQLHSTMT, paramCount *SQLSMALLINT) SQLRETURN
- func NumResultCols(stmt SQLHSTMT, columnCount *SQLSMALLINT) SQLRETURN
- func Prepare(stmt SQLHSTMT, query string) SQLRETURN
- func RowCount(stmt SQLHSTMT, rowCount *SQLLEN) SQLRETURN
- func SetConnectAttr(dbc SQLHDBC, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
- func SetEnvAttr(env SQLHENV, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
- func SetStmtAttr(stmt SQLHSTMT, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
- type SQLSCHAR
- type SQLSMALLINT
- type SQLUINTEGER
- type SQLULEN
- type SQLUSMALLINT
- type SQLWCHAR
- type SQL_DATE_STRUCT
- type SQL_DAY_SECOND_STRUCT
- type SQL_GUID_STRUCT
- type SQL_INTERVAL_STRUCT
- type SQL_NUMERIC_STRUCT
- type SQL_TIMESTAMP_STRUCT
- type SQL_TIME_STRUCT
- type SQL_YEAR_MONTH_STRUCT
- type ScrollableRows
- type Stmt
- func (s *Stmt) Close() error
- func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)
- func (s *Stmt) ExecBatch(ctx context.Context, paramSets [][]driver.NamedValue) (*BatchResult, error)
- func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)
- func (s *Stmt) NumInput() int
- func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)
- func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)
- type Timestamp
- type TimestampPrecision
- type TimestampTZ
- type Tx
- type WideString
Constants ¶
const ( // Connection errors (08xxx) SQLStateConnectionFailure = "08001" // Unable to connect SQLStateConnectionNotOpen = "08003" // Connection not open SQLStateConnectionRejected = "08004" // Connection rejected by server SQLStateConnectionError = "08S01" // Communication link failure // Warning states (01xxx) SQLStateDataTruncation = "01004" // Data truncated SQLStateOptionChanged = "01S02" // Option value changed // No data (02xxx) SQLStateNoData = "02000" // No data found // Data errors (22xxx) SQLStateStringTruncation = "22001" // String data right truncation SQLStateNumericOverflow = "22003" // Numeric value out of range SQLStateInvalidDatetime = "22007" // Invalid datetime format SQLStateDivisionByZero = "22012" // Division by zero // Constraint violations (23xxx) SQLStateDuplicateKey = "23000" // Integrity constraint violation SQLStateConstraintViolation = "23000" // Integrity constraint violation (alias) // Cursor/Transaction states (24xxx, 25xxx) SQLStateInvalidCursorState = "24000" // Invalid cursor state SQLStateInvalidTransState = "25000" // Invalid transaction state // Transaction errors (40xxx) SQLStateDeadlock = "40001" // Serialization failure (deadlock) SQLStateTransactionFailed = "40003" // Statement completion unknown // Syntax/access errors (42xxx) SQLStateSyntaxError = "42000" // Syntax error or access violation SQLStateTableNotFound = "42S02" // Table not found SQLStateColumnNotFound = "42S22" // Column not found // General errors (HYxxx) SQLStateGeneralError = "HY000" // General error SQLStateMemoryAllocationError = "HY001" // Memory allocation error SQLStateFunctionSequenceError = "HY010" // Function sequence error SQLStateInvalidAttrValue = "HY024" // Invalid attribute value SQLStateInvalidStringLength = "HY090" // Invalid string or buffer length SQLStateInvalidDescIndex = "HY091" // Invalid descriptor field identifier SQLStateTimeout = "HYT00" // Timeout expired SQLStateConnectionTimeout = "HYT01" // Connection timeout expired )
SQLState constants for common errors. These follow the ODBC specification and can be used with errors.Is.
const ( SQL_OV_ODBC2 = 2 SQL_OV_ODBC3 = 3 )
ODBC version constants
const ( SQL_AUTOCOMMIT_OFF = 0 SQL_AUTOCOMMIT_ON = 1 )
Autocommit values
const ( SQL_MODE_READ_WRITE = 0 SQL_MODE_READ_ONLY = 1 )
Access mode values
const ( SQL_TXN_READ_UNCOMMITTED = 1 SQL_TXN_READ_COMMITTED = 2 SQL_TXN_REPEATABLE_READ = 4 SQL_TXN_SERIALIZABLE = 8 )
Transaction isolation levels
const ( SQL_CURSOR_FORWARD_ONLY = 0 SQL_CURSOR_KEYSET_DRIVEN = 1 SQL_CURSOR_DYNAMIC = 2 SQL_CURSOR_STATIC = 3 )
Cursor types
const ( SQL_C_CHAR = SQL_CHAR SQL_C_LONG = SQL_INTEGER SQL_C_SHORT = SQL_SMALLINT SQL_C_FLOAT = SQL_REAL SQL_C_DOUBLE = SQL_DOUBLE SQL_C_NUMERIC = SQL_NUMERIC SQL_C_DEFAULT = 99 SQL_C_DATE = SQL_TYPE_DATE SQL_C_TIME = SQL_TYPE_TIME SQL_C_TIMESTAMP = SQL_TYPE_TIMESTAMP SQL_C_BINARY = SQL_BINARY SQL_C_BIT = SQL_BIT SQL_C_WCHAR = SQL_WCHAR SQL_C_SBIGINT = SQL_BIGINT + SQL_SIGNED_OFFSET // -25 SQL_C_UBIGINT = SQL_BIGINT + SQL_UNSIGNED_OFFSET // -27 SQL_C_SLONG = SQL_C_LONG + SQL_SIGNED_OFFSET // -16 SQL_C_SSHORT = SQL_C_SHORT + SQL_SIGNED_OFFSET // -15 SQL_C_STINYINT = SQL_TINYINT + SQL_SIGNED_OFFSET // -26 SQL_C_ULONG = SQL_C_LONG + SQL_UNSIGNED_OFFSET // -18 SQL_C_USHORT = SQL_C_SHORT + SQL_UNSIGNED_OFFSET // -17 SQL_C_UTINYINT = SQL_TINYINT + SQL_UNSIGNED_OFFSET // -28 SQL_C_GUID = SQL_GUID )
const ( SQL_C_INTERVAL_YEAR = SQL_INTERVAL_YEAR SQL_C_INTERVAL_MONTH = SQL_INTERVAL_MONTH SQL_C_INTERVAL_DAY = SQL_INTERVAL_DAY SQL_C_INTERVAL_HOUR = SQL_INTERVAL_HOUR SQL_C_INTERVAL_MINUTE = SQL_INTERVAL_MINUTE SQL_C_INTERVAL_SECOND = SQL_INTERVAL_SECOND SQL_C_INTERVAL_YEAR_TO_MONTH = SQL_INTERVAL_YEAR_TO_MONTH SQL_C_INTERVAL_DAY_TO_HOUR = SQL_INTERVAL_DAY_TO_HOUR SQL_C_INTERVAL_DAY_TO_MINUTE = SQL_INTERVAL_DAY_TO_MINUTE SQL_C_INTERVAL_DAY_TO_SECOND = SQL_INTERVAL_DAY_TO_SECOND SQL_C_INTERVAL_HOUR_TO_MINUTE = SQL_INTERVAL_HOUR_TO_MINUTE SQL_C_INTERVAL_HOUR_TO_SECOND = SQL_INTERVAL_HOUR_TO_SECOND SQL_C_INTERVAL_MINUTE_TO_SECOND = SQL_INTERVAL_MINUTE_TO_SECOND )
C Interval type identifiers (same as SQL types for intervals)
const ( SQL_PARAM_SUCCESS = 0 SQL_PARAM_SUCCESS_WITH_INFO = 1 SQL_PARAM_ERROR = 5 SQL_PARAM_UNUSED = 7 SQL_PARAM_DIAG_UNAVAILABLE = 8 )
Param status values
const ( SQL_NONSCROLLABLE = 0 SQL_SCROLLABLE = 1 )
Cursor scrollability
const (
SQL_PARAM_BIND_BY_COLUMN = 0
)
Param binding types
Variables ¶
This section is empty.
Functions ¶
func ColAttribute ¶
func ColAttribute(stmt SQLHSTMT, colNum SQLUSMALLINT, fieldId SQLUSMALLINT, charAttr []byte) (strLen SQLSMALLINT, numAttr SQLLEN, ret SQLRETURN)
ColAttribute returns a column attribute
func DescribeCol ¶
func DescribeCol(stmt SQLHSTMT, colNum SQLUSMALLINT, colName []byte) (nameLen SQLSMALLINT, dataType SQLSMALLINT, colSize SQLULEN, decDigits SQLSMALLINT, nullable SQLSMALLINT, ret SQLRETURN)
DescribeCol describes a column in a result set
func DriverConnect ¶
func DriverConnect(dbc SQLHDBC, hwnd uintptr, inConnStr string, outConnStr []byte, driverCompletion SQLUSMALLINT) (outLen SQLSMALLINT, ret SQLRETURN)
DriverConnect connects to a data source using a connection string
func FormatReturnCode ¶
FormatReturnCode returns a string representation of an ODBC return code
func GetDiagRec ¶
func GetDiagRec(handleType SQLSMALLINT, handle SQLHANDLE, recNum SQLSMALLINT, sqlState []byte, message []byte) (nativeError SQLINTEGER, msgLen SQLSMALLINT, ret SQLRETURN)
GetDiagRec retrieves diagnostic records
func GetInfo ¶
func GetInfo(dbc SQLHDBC, infoType SQLUSMALLINT, infoValue []byte) (stringLength SQLSMALLINT, ret SQLRETURN)
GetInfo retrieves driver/data source information
func IsConnectionError ¶
IsConnectionError reports whether err indicates a connection problem. Connection errors have SQLState codes starting with "08".
func IsDataTruncation ¶
IsDataTruncation reports whether err indicates data truncation.
func IsRetryable ¶
IsRetryable reports whether err represents a transient error that may succeed if retried. Transient errors include connection failures, timeouts, and deadlocks.
func NewError ¶
func NewError(handleType SQLSMALLINT, handle SQLHANDLE) error
NewError creates an Error from diagnostic records
func SQLTypeName ¶
func SQLTypeName(sqlType SQLSMALLINT) string
SQLTypeName returns a human-readable name for an SQL type
Types ¶
type BatchResult ¶
type BatchResult struct {
// TotalRowsAffected is the sum of all rows affected across all parameter sets
TotalRowsAffected int64
// RowCounts contains the number of rows affected for each parameter set
RowCounts []int64
// Errors contains any error that occurred for each parameter set (nil if success)
Errors []error
}
BatchResult holds the result of a batch execution
func (*BatchResult) HasErrors ¶
func (r *BatchResult) HasErrors() bool
HasErrors returns true if any parameter set resulted in an error
type ColumnBuffer ¶
type ColumnBuffer struct {
Data interface{} // The actual buffer (slice of values)
CType SQLSMALLINT // ODBC C type
SQLType SQLSMALLINT // ODBC SQL type
ColSize SQLULEN // Column size
DecDigits SQLSMALLINT // Decimal digits
Lengths []SQLLEN // Length/indicator array (one per row)
ElemSize int // Size of each element in bytes
}
ColumnBuffer holds the buffer data for array parameter binding
func AllocateColumnArray ¶
func AllocateColumnArray(values []interface{}, numRows int) (*ColumnBuffer, error)
AllocateColumnArray allocates a column buffer for array parameter binding based on the type of the first non-nil value in the column
func (*ColumnBuffer) GetColumnBufferPtr ¶
func (cb *ColumnBuffer) GetColumnBufferPtr() uintptr
GetColumnBufferPtr returns a pointer to the start of the column buffer data
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn implements driver.Conn and represents a connection to a database
func (*Conn) Begin ¶
Begin starts a new transaction with default options. Deprecated: Use BeginTx with context and options instead.
func (*Conn) BeginTx ¶
BeginTx starts a new transaction with the given context and options. It supports setting isolation levels and read-only mode via driver.TxOptions. Returns an error if the connection is already in a transaction.
func (*Conn) CheckNamedValue ¶
func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error
CheckNamedValue validates and converts named values
func (*Conn) Close ¶
Close closes the database connection, releasing all associated ODBC handles. It is safe to call Close multiple times; subsequent calls are no-ops.
func (*Conn) ExecContext ¶
func (c *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)
ExecContext executes a query that doesn't return rows (INSERT, UPDATE, DELETE). It supports context cancellation and query timeout. If args is empty, the query is executed directly; otherwise a prepared statement is used.
func (*Conn) IsValid ¶
IsValid implements driver.Validator and returns true if the connection is usable. Used by database/sql to check if a connection should be discarded.
func (*Conn) Ping ¶
Ping verifies the database connection is still alive. It executes a simple query (SELECT 1) to check connectivity. Returns driver.ErrBadConn if the connection is no longer valid.
func (*Conn) PrepareContext ¶
PrepareContext prepares a statement with context support
func (*Conn) PrepareWithCursor ¶
func (c *Conn) PrepareWithCursor(ctx context.Context, query string, cursorType CursorType) (driver.Stmt, error)
PrepareWithCursor prepares a statement with a specific cursor type. Use this when you need scrollable cursors for random-access navigation.
func (*Conn) QueryContext ¶
func (c *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)
QueryContext executes a query that returns rows (SELECT). It supports context cancellation and query timeout. If args is empty, the query is executed directly; otherwise a prepared statement is used.
type Connector ¶
type Connector struct {
// Enhanced Type Handling options
DefaultTimezone *time.Location // Default timezone for timestamp retrieval (defaults to UTC)
DefaultTimestampPrecision TimestampPrecision // Default precision for Timestamp type (defaults to Milliseconds)
LastInsertIdBehavior LastInsertIdBehavior // How to handle LastInsertId() (defaults to Auto)
// Query execution options
QueryTimeout time.Duration // Default query timeout (0 = no timeout)
// contains filtered or unexported fields
}
Connector implements driver.Connector for efficient connection pooling
type ConnectorOption ¶
type ConnectorOption func(*Connector)
ConnectorOption configures a Connector
func WithLastInsertIdBehavior ¶
func WithLastInsertIdBehavior(behavior LastInsertIdBehavior) ConnectorOption
WithLastInsertIdBehavior sets the behavior for LastInsertId()
func WithQueryTimeout ¶
func WithQueryTimeout(d time.Duration) ConnectorOption
WithQueryTimeout sets the default query timeout for all statements. The timeout is applied using SQL_ATTR_QUERY_TIMEOUT and context cancellation. A value of 0 means no timeout (the default).
func WithTimestampPrecision ¶
func WithTimestampPrecision(precision TimestampPrecision) ConnectorOption
WithTimestampPrecision sets the default timestamp precision
func WithTimezone ¶
func WithTimezone(tz *time.Location) ConnectorOption
WithTimezone sets the default timezone for timestamp handling
type CursorType ¶
type CursorType int
CursorType specifies the type of cursor to use for a query
const ( // CursorForwardOnly is the default cursor type (forward-only, read-only) CursorForwardOnly CursorType = iota // CursorStatic creates a static snapshot of the result set CursorStatic // CursorKeyset uses a keyset-driven cursor CursorKeyset // CursorDynamic creates a fully dynamic cursor CursorDynamic )
type Decimal ¶
type Decimal struct {
Value string // String representation for precision preservation
Precision int // Total digits (1-38)
Scale int // Digits after decimal point (0-Precision)
}
Decimal represents a decimal value with explicit precision and scale. Use this for precise numeric values where floating-point approximation is unacceptable.
func NewDecimal ¶
NewDecimal creates a Decimal from a string with validation
func ParseDecimal ¶
ParseDecimal parses a decimal string with automatic precision/scale detection
type DecimalError ¶
type DecimalError struct {
Message string
}
DecimalError represents a decimal validation error
func (*DecimalError) Error ¶
func (e *DecimalError) Error() string
type DiagRecord ¶
DiagRecord represents a single diagnostic record from ODBC
func GetDiagRecords ¶
func GetDiagRecords(handleType SQLSMALLINT, handle SQLHANDLE) []DiagRecord
GetDiagRecords retrieves all diagnostic records for a handle
type Driver ¶
type Driver struct{}
Driver implements the database/sql/driver.Driver interface
func (*Driver) Open ¶
Open opens a new connection to the database The name is an ODBC connection string, e.g.:
- "DSN=mydsn;UID=user;PWD=password"
- "Driver={SQL Server};Server=localhost;Database=mydb;UID=user;PWD=password"
func (*Driver) OpenConnector ¶
OpenConnector returns a new Connector for the given connection string This implements driver.DriverContext for connection pooling efficiency
func (*Driver) OpenConnectorWithOptions ¶
func (d *Driver) OpenConnectorWithOptions(name string, opts ...ConnectorOption) (*Connector, error)
OpenConnectorWithOptions returns a Connector with custom options for enhanced type handling. Use this when you need to configure timezone, timestamp precision, or other options.
Example:
driver := &odbc.Driver{}
connector, err := driver.OpenConnectorWithOptions(
"Driver={SQL Server};Server=localhost;Database=test",
odbc.WithTimezone(time.Local),
odbc.WithTimestampPrecision(odbc.TimestampPrecisionMicroseconds),
)
type Error ¶
Error represents an ODBC error with diagnostic information from the driver. It implements the error interface and provides SQLState, native error code, and a human-readable message.
type IntervalDaySecond ¶
type IntervalDaySecond struct {
Days int
Hours int
Minutes int
Seconds int
Nanoseconds int
Negative bool
}
IntervalDaySecond represents a day-time interval
func (IntervalDaySecond) ToDuration ¶
func (i IntervalDaySecond) ToDuration() time.Duration
ToDuration converts IntervalDaySecond to time.Duration
type IntervalYearMonth ¶
IntervalYearMonth represents a year-month interval
type LastInsertIdBehavior ¶
type LastInsertIdBehavior int
LastInsertIdBehavior specifies how LastInsertId() should behave
const ( // LastInsertIdAuto automatically detects the database type and executes // the appropriate identity query after INSERT statements LastInsertIdAuto LastInsertIdBehavior = iota // LastInsertIdDisabled returns 0 for LastInsertId() (original behavior) LastInsertIdDisabled // LastInsertIdReturning expects the query to use a RETURNING clause (PostgreSQL style) LastInsertIdReturning )
type NamedParams ¶
type NamedParams struct {
// Query is the converted query with positional ? placeholders
Query string
// Names contains the parameter names in order of their first appearance
Names []string
// Positions maps parameter names to their positions (1-based, matching ODBC binding)
// A single named parameter may appear multiple times in the query
Positions map[string][]int
}
NamedParams holds parsed named parameter information
func ParseNamedParams ¶
func ParseNamedParams(query string) *NamedParams
ParseNamedParams parses a query with named parameters and converts to positional placeholders. Supports the following named parameter styles:
- :name (Oracle/PostgreSQL style)
- @name (SQL Server style)
- $name (PostgreSQL style - not $1 which is positional)
Returns nil if no named parameters are found (query uses positional ? only). The original query is preserved if it contains only ? placeholders.
type OutputParam ¶
type OutputParam struct {
// Value holds the initial value (for InputOutput) or a type hint (for Output).
// For output-only parameters, the type of Value determines the buffer size and type.
// Supported types: int, int32, int64, float32, float64, string, []byte, bool, time.Time
Value interface{}
// Direction specifies whether this is an output or input/output parameter
Direction ParamDirection
// Size specifies the buffer size for variable-length types (string, []byte).
// If 0, a default size will be used (4000 for strings, 8000 for bytes).
Size int
}
OutputParam wraps a value for output or input/output parameter binding. Use this type when calling stored procedures that return values through parameters.
func NewInputOutputParam ¶
func NewInputOutputParam(value interface{}) OutputParam
NewInputOutputParam creates a bidirectional parameter with an initial value.
func NewInputOutputParamWithSize ¶
func NewInputOutputParamWithSize(value interface{}, size int) OutputParam
NewInputOutputParamWithSize creates a bidirectional parameter with a specific buffer size.
func NewOutputParam ¶
func NewOutputParam(typeHint interface{}) OutputParam
NewOutputParam creates an output-only parameter with the given type hint. The type of value determines the expected output type.
func NewOutputParamWithSize ¶
func NewOutputParamWithSize(typeHint interface{}, size int) OutputParam
NewOutputParamWithSize creates an output-only parameter with a specific buffer size. Use this for variable-length types (string, []byte) when you know the maximum size.
type ParamDirection ¶
type ParamDirection int
ParamDirection specifies the direction of a parameter (input, output, or both)
const ( // ParamInput is for input-only parameters (default) ParamInput ParamDirection = iota // ParamOutput is for output-only parameters ParamOutput // ParamInputOutput is for bidirectional parameters ParamInputOutput )
type ParameterError ¶
ParameterError represents an error with parameter binding
func (*ParameterError) Error ¶
func (e *ParameterError) Error() string
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result implements driver.Result for INSERT, UPDATE, DELETE operations
func (*Result) LastInsertId ¶
LastInsertId returns the ID of the last inserted row. When LastInsertIdAuto behavior is configured (default), this automatically executes the appropriate identity query for the connected database type.
func (*Result) OutputParam ¶
OutputParam returns a single output parameter value by index (0-based). Returns nil if the index is out of range or if the parameter was input-only.
func (*Result) OutputParams ¶
func (r *Result) OutputParams() []interface{}
OutputParams returns the values of output parameters after executing a stored procedure. The values are returned in the same order as the parameters were bound. Only parameters marked as ParamOutput or ParamInputOutput will have values. Input-only parameters will have nil values in the corresponding positions.
func (*Result) RowsAffected ¶
RowsAffected returns the number of rows affected by the query
type Rows ¶
type Rows struct {
// contains filtered or unexported fields
}
Rows implements driver.Rows for result set iteration
func (*Rows) Absolute ¶
Absolute moves the cursor to the specified row number (1-based) Positive values count from the beginning, negative values count from the end.
func (*Rows) Close ¶
Close closes the result set and releases associated resources. It is safe to call Close multiple times; subsequent calls are no-ops.
func (*Rows) ColumnTypeDatabaseTypeName ¶
ColumnTypeDatabaseTypeName returns the native database-specific type name for a column. This returns the actual type name from the database driver (e.g., "datetime2", "varchar", "int") rather than a generic ODBC type mapping.
func (*Rows) ColumnTypeLength ¶
ColumnTypeLength returns the maximum length for variable-length column types. Returns ok=true for VARCHAR, VARBINARY, and similar types; ok=false for fixed types.
func (*Rows) ColumnTypeNullable ¶
ColumnTypeNullable reports whether a column may be null. Returns ok=false if nullability cannot be determined.
func (*Rows) ColumnTypePrecisionScale ¶
ColumnTypePrecisionScale returns precision and scale for NUMERIC/DECIMAL columns. Precision is the total number of digits; scale is digits after the decimal point. Returns ok=false for non-numeric types.
func (*Rows) ColumnTypeScanType ¶
ColumnTypeScanType returns the Go type suitable for scanning column values. For example, SQL_INTEGER returns int64, SQL_VARCHAR returns string.
func (*Rows) GetRowData ¶
GetRowData retrieves the current row's data after a scroll operation
func (*Rows) HasNextResultSet ¶
HasNextResultSet reports whether there are additional result sets available. Use NextResultSet to advance to the next result set.
func (*Rows) Next ¶
Next advances to the next row and populates dest with column values. Returns io.EOF when no more rows are available.
func (*Rows) NextResultSet ¶
NextResultSet advances to the next result set from a multi-result query. Returns io.EOF if there are no more result sets.
type SQLHANDLE ¶
type SQLHANDLE uintptr
ODBC Handle types (opaque pointers)
const SQL_NULL_HANDLE SQLHANDLE = 0
Null handle constant
type SQLINTEGER ¶
type SQLINTEGER int32
const ( SQL_ATTR_ODBC_VERSION SQLINTEGER = 200 SQL_ATTR_CONNECTION_POOLING SQLINTEGER = 201 SQL_ATTR_CP_MATCH SQLINTEGER = 202 SQL_ATTR_OUTPUT_NTS SQLINTEGER = 10001 )
Environment attributes
const ( SQL_ATTR_AUTOCOMMIT SQLINTEGER = 102 SQL_ATTR_CONNECTION_DEAD SQLINTEGER = 1209 SQL_ATTR_LOGIN_TIMEOUT SQLINTEGER = 103 SQL_ATTR_ACCESS_MODE SQLINTEGER = 101 SQL_ATTR_TXN_ISOLATION SQLINTEGER = 108 )
Connection attributes
const ( SQL_ATTR_CURSOR_TYPE SQLINTEGER = 6 SQL_ATTR_CONCURRENCY SQLINTEGER = 7 SQL_ATTR_ROW_ARRAY_SIZE SQLINTEGER = 27 SQL_ATTR_ROW_STATUS_PTR SQLINTEGER = 25 SQL_ATTR_ROWS_FETCHED SQLINTEGER = 26 SQL_ATTR_QUERY_TIMEOUT SQLINTEGER = 0 SQL_ATTR_MAX_ROWS SQLINTEGER = 1 SQL_ATTR_CURSOR_SCROLLABLE SQLINTEGER = -1 SQL_ATTR_CURSOR_SENSITIVITY SQLINTEGER = -2 )
Statement attributes
const ( SQL_ATTR_PARAM_BIND_TYPE SQLINTEGER = 18 SQL_ATTR_PARAM_STATUS_PTR SQLINTEGER = 20 SQL_ATTR_PARAMS_PROCESSED_PTR SQLINTEGER = 21 SQL_ATTR_PARAMSET_SIZE SQLINTEGER = 22 )
Statement attributes for batch operations
const SQL_NTS SQLINTEGER = -3
String terminator
type SQLRETURN ¶
type SQLRETURN SQLSMALLINT
const ( SQL_SUCCESS SQLRETURN = 0 SQL_SUCCESS_WITH_INFO SQLRETURN = 1 SQL_ERROR SQLRETURN = -1 SQL_INVALID_HANDLE SQLRETURN = -2 SQL_NO_DATA SQLRETURN = 100 SQL_NEED_DATA SQLRETURN = 99 SQL_STILL_EXECUTING SQLRETURN = 2 )
Return codes
func AllocHandle ¶
func AllocHandle(handleType SQLSMALLINT, inputHandle SQLHANDLE, outputHandle *SQLHANDLE) SQLRETURN
AllocHandle allocates an ODBC handle
func BindParameter ¶
func BindParameter(stmt SQLHSTMT, paramNum SQLUSMALLINT, ioType SQLSMALLINT, valueType SQLSMALLINT, paramType SQLSMALLINT, colSize SQLULEN, decDigits SQLSMALLINT, paramValue uintptr, bufferLen SQLLEN, strLenOrInd *SQLLEN) SQLRETURN
BindParameter binds a parameter to a statement
func EndTran ¶
func EndTran(handleType SQLSMALLINT, handle SQLHANDLE, completionType SQLSMALLINT) SQLRETURN
EndTran commits or rolls back a transaction
func ExecDirect ¶
ExecDirect executes an SQL statement directly
func FetchScroll ¶
func FetchScroll(stmt SQLHSTMT, fetchOrientation SQLSMALLINT, fetchOffset SQLLEN) SQLRETURN
FetchScroll fetches a row from the result set using scroll operations
func FreeHandle ¶
func FreeHandle(handleType SQLSMALLINT, handle SQLHANDLE) SQLRETURN
FreeHandle frees an ODBC handle
func FreeStmt ¶
func FreeStmt(stmt SQLHSTMT, option SQLUSMALLINT) SQLRETURN
FreeStmt frees resources associated with a statement
func GetData ¶
func GetData(stmt SQLHSTMT, colNum SQLUSMALLINT, targetType SQLSMALLINT, targetValue uintptr, bufferLen SQLLEN, strLenOrInd *SQLLEN) SQLRETURN
GetData retrieves data for a single column
func MoreResults ¶
MoreResults checks for more result sets
func NumParams ¶
func NumParams(stmt SQLHSTMT, paramCount *SQLSMALLINT) SQLRETURN
NumParams returns the number of parameters in a prepared statement
func NumResultCols ¶
func NumResultCols(stmt SQLHSTMT, columnCount *SQLSMALLINT) SQLRETURN
NumResultCols returns the number of columns in a result set
func SetConnectAttr ¶
func SetConnectAttr(dbc SQLHDBC, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
SetConnectAttr sets a connection attribute
func SetEnvAttr ¶
func SetEnvAttr(env SQLHENV, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
SetEnvAttr sets an environment attribute
func SetStmtAttr ¶
func SetStmtAttr(stmt SQLHSTMT, attribute SQLINTEGER, value uintptr, stringLength SQLINTEGER) SQLRETURN
SetStmtAttr sets a statement attribute
type SQLSMALLINT ¶
type SQLSMALLINT int16
ODBC Integer types
const ( SQL_HANDLE_ENV SQLSMALLINT = 1 SQL_HANDLE_DBC SQLSMALLINT = 2 SQL_HANDLE_STMT SQLSMALLINT = 3 SQL_HANDLE_DESC SQLSMALLINT = 4 )
Handle type identifiers
const ( SQL_UNKNOWN_TYPE SQLSMALLINT = 0 SQL_CHAR SQLSMALLINT = 1 SQL_NUMERIC SQLSMALLINT = 2 SQL_DECIMAL SQLSMALLINT = 3 SQL_INTEGER SQLSMALLINT = 4 SQL_SMALLINT SQLSMALLINT = 5 SQL_FLOAT SQLSMALLINT = 6 SQL_REAL SQLSMALLINT = 7 SQL_DOUBLE SQLSMALLINT = 8 SQL_DATETIME SQLSMALLINT = 9 SQL_VARCHAR SQLSMALLINT = 12 SQL_TYPE_DATE SQLSMALLINT = 91 SQL_TYPE_TIME SQLSMALLINT = 92 SQL_TYPE_TIMESTAMP SQLSMALLINT = 93 SQL_LONGVARCHAR SQLSMALLINT = -1 SQL_BINARY SQLSMALLINT = -2 SQL_VARBINARY SQLSMALLINT = -3 SQL_LONGVARBINARY SQLSMALLINT = -4 SQL_BIGINT SQLSMALLINT = -5 SQL_TINYINT SQLSMALLINT = -6 SQL_BIT SQLSMALLINT = -7 SQL_BOOLEAN SQLSMALLINT = 16 // DB2 BOOLEAN type SQL_WCHAR SQLSMALLINT = -8 SQL_WVARCHAR SQLSMALLINT = -9 SQL_WLONGVARCHAR SQLSMALLINT = -10 SQL_GUID SQLSMALLINT = -11 )
SQL data types
const ( SQL_SIGNED_OFFSET SQLSMALLINT = -20 SQL_UNSIGNED_OFFSET SQLSMALLINT = -22 )
C data type identifiers for binding
const ( SQL_PARAM_INPUT SQLSMALLINT = 1 SQL_PARAM_INPUT_OUTPUT SQLSMALLINT = 2 SQL_PARAM_OUTPUT SQLSMALLINT = 4 )
Parameter input/output type
const ( SQL_FETCH_NEXT SQLSMALLINT = 1 SQL_FETCH_FIRST SQLSMALLINT = 2 SQL_FETCH_LAST SQLSMALLINT = 3 SQL_FETCH_PRIOR SQLSMALLINT = 4 SQL_FETCH_ABSOLUTE SQLSMALLINT = 5 SQL_FETCH_RELATIVE SQLSMALLINT = 6 )
Fetch direction
const ( SQL_COMMIT SQLSMALLINT = 0 SQL_ROLLBACK SQLSMALLINT = 1 )
Transaction completion types
const ( SQL_NO_NULLS SQLSMALLINT = 0 SQL_NULLABLE SQLSMALLINT = 1 SQL_NULLABLE_UNKNOWN SQLSMALLINT = 2 )
Nullable field values
const ( SQL_INTERVAL_YEAR SQLSMALLINT = 101 SQL_INTERVAL_MONTH SQLSMALLINT = 102 SQL_INTERVAL_DAY SQLSMALLINT = 103 SQL_INTERVAL_HOUR SQLSMALLINT = 104 SQL_INTERVAL_MINUTE SQLSMALLINT = 105 SQL_INTERVAL_SECOND SQLSMALLINT = 106 SQL_INTERVAL_YEAR_TO_MONTH SQLSMALLINT = 107 SQL_INTERVAL_DAY_TO_HOUR SQLSMALLINT = 108 SQL_INTERVAL_DAY_TO_MINUTE SQLSMALLINT = 109 SQL_INTERVAL_DAY_TO_SECOND SQLSMALLINT = 110 SQL_INTERVAL_HOUR_TO_MINUTE SQLSMALLINT = 111 SQL_INTERVAL_HOUR_TO_SECOND SQLSMALLINT = 112 SQL_INTERVAL_MINUTE_TO_SECOND SQLSMALLINT = 113 )
SQL Interval type constants
type SQLUINTEGER ¶
type SQLUINTEGER uint32
type SQLUSMALLINT ¶
type SQLUSMALLINT uint16
const ( SQL_DRIVER_NOPROMPT SQLUSMALLINT = 0 SQL_DRIVER_COMPLETE SQLUSMALLINT = 1 SQL_DRIVER_PROMPT SQLUSMALLINT = 2 SQL_DRIVER_COMPLETE_REQUIRED SQLUSMALLINT = 3 )
SQLDriverConnect options
const ( SQL_CLOSE SQLUSMALLINT = 0 SQL_DROP SQLUSMALLINT = 1 SQL_UNBIND SQLUSMALLINT = 2 SQL_RESET_PARAMS SQLUSMALLINT = 3 )
Free statement options
const ( SQL_DESC_COUNT SQLUSMALLINT = 1001 SQL_DESC_TYPE SQLUSMALLINT = 1002 SQL_DESC_LENGTH SQLUSMALLINT = 1003 SQL_DESC_OCTET_LENGTH_PTR SQLUSMALLINT = 1004 SQL_DESC_PRECISION SQLUSMALLINT = 1005 SQL_DESC_SCALE SQLUSMALLINT = 1006 SQL_DESC_DATETIME_INTERVAL_CODE SQLUSMALLINT = 1007 SQL_DESC_NULLABLE SQLUSMALLINT = 1008 SQL_DESC_INDICATOR_PTR SQLUSMALLINT = 1009 SQL_DESC_DATA_PTR SQLUSMALLINT = 1010 SQL_DESC_NAME SQLUSMALLINT = 1011 SQL_DESC_UNNAMED SQLUSMALLINT = 1012 SQL_DESC_OCTET_LENGTH SQLUSMALLINT = 1013 SQL_DESC_ALLOC_TYPE SQLUSMALLINT = 1099 SQL_DESC_CONCISE_TYPE SQLUSMALLINT = SQL_DESC_TYPE SQL_DESC_DISPLAY_SIZE SQLUSMALLINT = 6 SQL_DESC_UNSIGNED SQLUSMALLINT = 8 SQL_DESC_UPDATABLE SQLUSMALLINT = 10 SQL_DESC_AUTO_UNIQUE_VALUE SQLUSMALLINT = 11 SQL_DESC_TYPE_NAME SQLUSMALLINT = 14 SQL_DESC_TABLE_NAME SQLUSMALLINT = 15 SQL_DESC_SCHEMA_NAME SQLUSMALLINT = 16 SQL_DESC_CATALOG_NAME SQLUSMALLINT = 17 SQL_DESC_BASE_COLUMN_NAME SQLUSMALLINT = 22 SQL_DESC_BASE_TABLE_NAME SQLUSMALLINT = 23 SQL_DESC_LABEL SQLUSMALLINT = 18 SQL_COLUMN_LENGTH SQLUSMALLINT = 3 SQL_COLUMN_PRECISION SQLUSMALLINT = 4 SQL_COLUMN_SCALE SQLUSMALLINT = 5 )
Column attribute identifiers
const ( SQL_DRIVER_NAME SQLUSMALLINT = 6 SQL_DRIVER_VER SQLUSMALLINT = 7 SQL_DBMS_NAME SQLUSMALLINT = 17 SQL_DBMS_VER SQLUSMALLINT = 18 SQL_DATABASE_NAME SQLUSMALLINT = 16 SQL_SERVER_NAME SQLUSMALLINT = 13 SQL_USER_NAME SQLUSMALLINT = 47 SQL_IDENTIFIER_QUOTE_CHAR SQLUSMALLINT = 29 SQL_MAX_IDENTIFIER_LEN SQLUSMALLINT = 10005 )
SQLGetInfo information types
type SQL_DATE_STRUCT ¶
type SQL_DATE_STRUCT struct {
Year SQLSMALLINT
Month SQLUSMALLINT
Day SQLUSMALLINT
}
Date struct
type SQL_DAY_SECOND_STRUCT ¶
type SQL_DAY_SECOND_STRUCT struct {
Day SQLUINTEGER
Hour SQLUINTEGER
Minute SQLUINTEGER
Second SQLUINTEGER
Fraction SQLUINTEGER // billionths of a second
}
SQL_DAY_SECOND_STRUCT for day-time intervals
type SQL_GUID_STRUCT ¶
GUID struct for uniqueidentifier types
func (SQL_GUID_STRUCT) String ¶
func (g SQL_GUID_STRUCT) String() string
String returns the GUID as a formatted string (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
type SQL_INTERVAL_STRUCT ¶
type SQL_INTERVAL_STRUCT struct {
IntervalType SQLSMALLINT
IntervalSign SQLSMALLINT // 0 = positive, 1 = negative
YearMonth SQL_YEAR_MONTH_STRUCT
DaySecond SQL_DAY_SECOND_STRUCT
// contains filtered or unexported fields
}
SQL_INTERVAL_STRUCT is the ODBC interval structure
type SQL_NUMERIC_STRUCT ¶
type SQL_NUMERIC_STRUCT struct {
Precision SQLCHAR
Scale SQLSCHAR
Sign SQLCHAR // 1 = positive, 0 = negative
Val [16]SQLCHAR
}
Numeric struct for decimal/numeric types
type SQL_TIMESTAMP_STRUCT ¶
type SQL_TIMESTAMP_STRUCT struct {
Year SQLSMALLINT
Month SQLUSMALLINT
Day SQLUSMALLINT
Hour SQLUSMALLINT
Minute SQLUSMALLINT
Second SQLUSMALLINT
Fraction SQLUINTEGER // billionths of a second
}
Timestamp struct for date/time binding
type SQL_TIME_STRUCT ¶
type SQL_TIME_STRUCT struct {
Hour SQLUSMALLINT
Minute SQLUSMALLINT
Second SQLUSMALLINT
}
Time struct
type SQL_YEAR_MONTH_STRUCT ¶
type SQL_YEAR_MONTH_STRUCT struct {
Year SQLUINTEGER
Month SQLUINTEGER
}
SQL_YEAR_MONTH_STRUCT for year-month intervals
type ScrollableRows ¶
type ScrollableRows interface {
driver.Rows
First() error
Last() error
Prior() error
Absolute(row int64) error
Relative(offset int64) error
}
ScrollableRows provides methods for scrollable cursor navigation. These methods are only available when the statement was prepared with PrepareWithCursor using a scrollable cursor type (CursorStatic, CursorKeyset, or CursorDynamic).
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Stmt implements driver.Stmt for prepared statements
func (*Stmt) Close ¶
Close releases all resources associated with the prepared statement. It is safe to call Close multiple times; subsequent calls are no-ops.
func (*Stmt) Exec ¶
Exec executes a prepared statement without returning rows. Deprecated: Use ExecContext with context support instead.
func (*Stmt) ExecBatch ¶
func (s *Stmt) ExecBatch(ctx context.Context, paramSets [][]driver.NamedValue) (*BatchResult, error)
ExecBatch executes a prepared statement with multiple parameter sets in a single batch. This uses ODBC array binding (SQL_ATTR_PARAMSET_SIZE) for efficient bulk operations. Returns a BatchResult with per-row status information.
func (*Stmt) ExecContext ¶
ExecContext executes a prepared statement that doesn't return rows. It supports context cancellation and named/positional parameters. Returns a Result with rows affected and output parameter values.
func (*Stmt) NumInput ¶
NumInput returns the number of placeholder parameters in the prepared statement. Returns -1 if the driver cannot determine the count.
func (*Stmt) Query ¶
Query executes a prepared statement that returns rows. Deprecated: Use QueryContext with context support instead.
func (*Stmt) QueryContext ¶
QueryContext executes a prepared statement that returns rows. It supports context cancellation and named/positional parameters.
type Timestamp ¶
type Timestamp struct {
Time time.Time
Precision TimestampPrecision
}
Timestamp wraps time.Time with explicit precision control
func NewTimestamp ¶
func NewTimestamp(t time.Time, precision TimestampPrecision) Timestamp
NewTimestamp creates a Timestamp with the specified precision
type TimestampPrecision ¶
type TimestampPrecision int
TimestampPrecision specifies the fractional seconds precision for timestamps
const ( // TimestampPrecisionSeconds provides no fractional seconds (datetime) TimestampPrecisionSeconds TimestampPrecision = 0 // TimestampPrecisionMilliseconds provides 3 digits (default, datetime2(3)) TimestampPrecisionMilliseconds TimestampPrecision = 3 // TimestampPrecisionMicroseconds provides 6 digits (datetime2(6)) TimestampPrecisionMicroseconds TimestampPrecision = 6 // TimestampPrecisionNanoseconds provides 9 digits (max ODBC precision) TimestampPrecisionNanoseconds TimestampPrecision = 9 )
type TimestampTZ ¶
type TimestampTZ struct {
Time time.Time
Precision TimestampPrecision
TZ *time.Location // nil means use connection default (UTC)
}
TimestampTZ represents a timestamp with timezone awareness
func NewTimestampTZ ¶
func NewTimestampTZ(t time.Time, precision TimestampPrecision, tz *time.Location) TimestampTZ
NewTimestampTZ creates a timezone-aware timestamp
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx implements driver.Tx for transaction support
type WideString ¶
type WideString string
WideString wraps a Go string for explicit UTF-16 (NVARCHAR/NCHAR) binding. Use this when inserting into Unicode columns that require wide character encoding.