tsqlruntime

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: GPL-3.0 Imports: 26 Imported by: 0

README

tsqlruntime - T-SQL Runtime Interpreter

Runtime interpreter for T-SQL, enabling execution of dynamic SQL at runtime in Go applications.

Overview

tsqlruntime solves the "dynamic SQL problem" for T-SQL to Go migrations. Instead of requiring manual rewrites for stored procedures containing EXEC(@sql) or sp_executesql, the transpiler can now generate code that interprets the dynamic SQL at runtime.

Stage 1 Features

  • Type System: Full T-SQL type support with NULL handling

    • Integer types: bit, tinyint, smallint, int, bigint
    • Decimal types: decimal, numeric, money, smallmoney
    • Floating point: float, real
    • String types: char, varchar, nchar, nvarchar
    • Date/time: date, time, datetime, datetime2, smalldatetime
    • Binary: binary, varbinary
  • CAST/CONVERT: Full type conversion with SQL Server style codes

  • Expression Evaluator: Evaluates T-SQL expressions at runtime

  • 40+ Built-in Functions: String, DateTime, Numeric, NULL handling

Stage 2 Features

  • Temp Tables (#table): CREATE, DROP, TRUNCATE, SELECT, INSERT, UPDATE, DELETE
  • Global Temp Tables (##table): Same operations, persist across session clear
  • Table Variables (@table): DECLARE, INSERT, SELECT, UPDATE, DELETE
  • TRY/CATCH: Error catching with ERROR_NUMBER(), ERROR_MESSAGE(), etc.
  • RAISERROR/THROW: Error generation with severity and state
  • Transactions: BEGIN/COMMIT/ROLLBACK TRANSACTION
  • ExecutionContext: Variable scoping, system variables, nested contexts

Stage 3 Features

  • Cursors: Full cursor support

    • DECLARE CURSOR with options (LOCAL/GLOBAL, FORWARD_ONLY/SCROLL, STATIC/KEYSET/DYNAMIC)
    • OPEN cursor with query execution
    • FETCH (NEXT, PRIOR, FIRST, LAST, ABSOLUTE, RELATIVE)
    • CLOSE and DEALLOCATE
    • @@FETCH_STATUS tracking
  • JSON Functions (full implementations):

    • ISJSON(json_string) - Validates JSON
    • JSON_VALUE(json, '$.path') - Extracts scalar values
    • JSON_QUERY(json, '$.path') - Extracts objects/arrays
    • JSON_MODIFY(json, '$.path', value) - Modifies JSON
    • OPENJSON(json) - Shreds JSON into rows
    • FOR JSON PATH/AUTO - Converts result set to JSON
  • XML Functions (full implementations):

    • .value('/xpath', 'type') - Extracts scalar values from XML
    • .query('/xpath') - Extracts XML fragments
    • .exist('/xpath') - Checks if XPath matches
    • .nodes('/xpath') - Shreds XML into rows
    • OPENXML(xml, '/xpath', flags) - Parses XML into table
    • FOR XML RAW/PATH - Converts result set to XML
  • Additional Functions:

    • Hash: HASHBYTES (MD5, SHA1, SHA256, SHA512), CHECKSUM, BINARY_CHECKSUM
    • Logical: GREATEST, LEAST
    • Conversion: TRY_CAST, TRY_CONVERT, TRY_PARSE, PARSE
    • System: HOST_NAME, APP_NAME, USER_NAME, SYSTEM_USER, etc.
    • Metadata: COL_NAME, COL_LENGTH, TYPE_ID, TYPE_NAME

Usage

Basic Usage
import (
    "context"
    "database/sql"
    "github.com/ha1tch/tgpiler/tsqlruntime"
)

// Create interpreter with database connection
db, _ := sql.Open("postgres", connStr)
interp := tsqlruntime.NewInterpreter(db, tsqlruntime.DialectPostgres)

// Execute dynamic SQL
result, err := interp.Execute(ctx, `
    DECLARE @Status INT = 1
    SELECT * FROM Orders WHERE Status = @Status
`, nil)
Cursor Example
result, err := interp.Execute(ctx, `
    DECLARE @id INT, @name VARCHAR(50)
    
    DECLARE user_cursor CURSOR FOR
    SELECT id, name FROM users WHERE active = 1
    
    OPEN user_cursor
    
    FETCH NEXT FROM user_cursor INTO @id, @name
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @name
        FETCH NEXT FROM user_cursor INTO @id, @name
    END
    
    CLOSE user_cursor
    DEALLOCATE user_cursor
`, nil)
TRY/CATCH Example
result, err := interp.Execute(ctx, `
    BEGIN TRY
        INSERT INTO orders (id, total) VALUES (1, 100)
    END TRY
    BEGIN CATCH
        DECLARE @err NVARCHAR(200)
        SET @err = ERROR_MESSAGE()
        RAISERROR(@err, 16, 1)
    END CATCH
`, nil)
Temp Tables Example
result, err := interp.Execute(ctx, `
    CREATE TABLE #temp (
        id INT IDENTITY(1,1),
        name VARCHAR(50),
        value DECIMAL(18,2)
    )
    
    INSERT INTO #temp (name, value) VALUES ('A', 10.5)
    INSERT INTO #temp (name, value) VALUES ('B', 20.75)
    
    SELECT * FROM #temp WHERE value > 15
    
    DROP TABLE #temp
`, nil)
JSON Example
result, err := interp.Execute(ctx, `
    DECLARE @json NVARCHAR(MAX) = '{"customer": {"name": "Alice", "orders": [{"id": 1}, {"id": 2}]}}'
    
    -- Extract scalar value
    SELECT JSON_VALUE(@json, '$.customer.name') AS CustomerName
    
    -- Extract object
    SELECT JSON_QUERY(@json, '$.customer.orders') AS Orders
    
    -- Modify JSON
    SET @json = JSON_MODIFY(@json, '$.customer.name', 'Bob')
    
    -- Shred JSON into rows (using OPENJSON with schema)
    SELECT id
    FROM OPENJSON(@json, '$.customer.orders')
    WITH (id INT '$.id')
`, nil)
XML Example
result, err := interp.Execute(ctx, `
    DECLARE @xml XML = '<root><item id="1">A</item><item id="2">B</item></root>'
    
    -- Extract scalar value
    SELECT @xml.value('(/root/item[@id="1"])[1]', 'VARCHAR(10)') AS FirstItem
    
    -- Check if path exists
    SELECT @xml.exist('/root/item[@id="3"]') AS HasItem3
    
    -- Shred XML into rows
    SELECT 
        n.value('@id', 'INT') AS ItemId,
        n.value('.', 'VARCHAR(10)') AS ItemValue
    FROM @xml.nodes('/root/item') AS t(n)
`, nil)
FOR JSON/XML Example
result, err := interp.Execute(ctx, `
    -- Convert query to JSON
    SELECT id, name, total
    FROM orders
    WHERE status = 'active'
    FOR JSON PATH, ROOT('orders')
    
    -- Convert query to XML
    SELECT id, name, total
    FROM orders
    WHERE status = 'active'
    FOR XML PATH('order'), ROOT('orders'), ELEMENTS
`, nil)

Dialects

tsqlruntime.DialectPostgres   // $1, $2, ...
tsqlruntime.DialectMySQL      // ?, ?, ...
tsqlruntime.DialectSQLite     // ?, ?, ...
tsqlruntime.DialectSQLServer  // @p0, @p1, ...

Testing

go test ./tsqlruntime/... -v

Coverage Summary

Stage Features Coverage
Stage 1 Types, CAST/CONVERT, Expressions, Functions ~70% of dynamic SQL
Stage 2 Temp tables, TRY/CATCH, Transactions +25% (total ~95%)
Stage 3 Cursors, More functions +5% (total ~100%)

Documentation

Overview

Package tsqlruntime provides runtime support for transpiled T-SQL procedures.

SPLogger provides structured logging for stored procedure errors, matching the common T-SQL pattern of logging errors to a table in CATCH blocks.

Package tsqlruntime provides table variable support for transpiled T-SQL code.

Package tsqlruntime provides a runtime interpreter for T-SQL, enabling execution of dynamic SQL at runtime in Go applications.

Index

Constants

View Source
const (
	ErrDivideByZero        = 8134
	ErrConversionFailed    = 245
	ErrArithmeticOverflow  = 8115
	ErrNullNotAllowed      = 515
	ErrConstraintViolation = 547
	ErrDuplicateKey        = 2627
	ErrDeadlock            = 1205
	ErrTimeout             = -2
	ErrInvalidObject       = 208
	ErrInvalidColumn       = 207
	ErrSyntaxError         = 102
	ErrPermissionDenied    = 229
	ErrRaiseError          = 50000
)

Common SQL Server error numbers

Variables

This section is empty.

Functions

func All added in v0.5.0

func All[T any](slice []T, predicate func(T) bool) bool

All returns true if all elements in the slice satisfy the predicate. Returns true for empty slices (vacuous truth).

func Any added in v0.5.0

func Any[T any](slice []T, predicate func(T) bool) bool

Any returns true if any element in the slice satisfies the predicate. Equivalent to T-SQL EXISTS (SELECT 1 FROM @TableVar WHERE ...).

func AvgFloat64 added in v0.5.0

func AvgFloat64[T any](slice []T, getter func(T) float64) float64

AvgFloat64 computes the average of float64 values extracted from slice elements. Returns 0 for empty slices.

func ClearErrorContext

func ClearErrorContext()

ClearErrorContext clears the error context

func Count added in v0.5.0

func Count[T any](slice []T, predicate func(T) bool) int

Count returns the number of elements that satisfy the predicate. Equivalent to T-SQL SELECT COUNT(*) FROM @TableVar WHERE ...

func CountAll added in v0.5.0

func CountAll[T any](slice []T) int

CountAll returns the total number of elements in the slice. Equivalent to T-SQL SELECT COUNT(*) FROM @TableVar.

func Distinct added in v0.5.0

func Distinct[T any](slice []T) []T

Distinct returns a new slice with duplicate elements removed. Elements are compared using reflect.DeepEqual. Equivalent to T-SQL SELECT DISTINCT.

func Filter added in v0.5.0

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter returns a new slice containing only elements that satisfy the predicate. Equivalent to T-SQL WHERE clause on a table variable.

func Find added in v0.5.0

func Find[T any](slice []T, predicate func(T) bool) (T, bool)

Find returns the first element that satisfies the predicate and true, or the zero value and false if no element matches.

func FindIndex added in v0.5.0

func FindIndex[T any](slice []T, predicate func(T) bool) int

FindIndex returns the index of the first element that satisfies the predicate, or -1 if no element matches.

func First added in v0.5.0

func First[T any](slice []T) (T, bool)

First returns the first element of a slice and true, or the zero value and false if the slice is empty. Equivalent to T-SQL TOP 1.

func FirstN added in v0.5.0

func FirstN[T any](slice []T, n int) []T

FirstN returns up to n elements from the start of a slice. Equivalent to T-SQL TOP n.

func ForJSON

func ForJSON(columns []string, rows [][]Value, options ForJSONOptions) (string, error)

ForJSON converts rows to JSON format

func ForXML

func ForXML(columns []string, rows [][]Value, options ForXMLOptions) (string, error)

ForXML converts rows to XML format

func FromValue

func FromValue(v Value) interface{}

FromValue converts a runtime Value to a Go value

func GetMockUUIDCounter

func GetMockUUIDCounter() uint64

GetMockUUIDCounter returns the current mock UUID counter value.

func GroupBy added in v0.5.0

func GroupBy[T any, K comparable](slice []T, keyFunc func(T) K) map[K][]T

GroupBy groups elements by a key extracted from each element. Returns a map from keys to slices of elements with that key. Equivalent to T-SQL GROUP BY.

func IsCriticalError

func IsCriticalError(err *SQLError) bool

IsCriticalError returns true if the error should abort the batch

func IsTableVariable

func IsTableVariable(name string) bool

IsTableVariable checks if a name refers to a table variable

func IsTempTable

func IsTempTable(name string) bool

IsTempTable checks if a table name refers to a temp table

func Last added in v0.5.0

func Last[T any](slice []T) (T, bool)

Last returns the last element of a slice and true, or the zero value and false if the slice is empty.

func LoadFromRows added in v0.5.0

func LoadFromRows[T any](rows *sql.Rows, scanner func(*sql.Rows) (T, error)) ([]T, error)

LoadFromRows loads all rows from a sql.Rows cursor into a slice. The scanner function should create a new row and scan values into it.

func LoadFromRowsWithCapacity added in v0.5.0

func LoadFromRowsWithCapacity[T any](rows *sql.Rows, capacity int, scanner func(*sql.Rows) (T, error)) ([]T, error)

LoadFromRowsWithCapacity is like LoadFromRows but pre-allocates the slice with the given capacity hint for better performance.

func LogSPError

func LogSPError(ctx context.Context, err SPError) error

LogSPError logs an error using the default logger.

func Map added in v0.5.0

func Map[T any, R any](slice []T, transform func(T) R) []R

Map transforms each element of a slice using the provided function. Equivalent to T-SQL SELECT expression FROM @TableVar.

func MaxFloat64 added in v0.5.0

func MaxFloat64[T any](slice []T, getter func(T) float64) (float64, bool)

MaxFloat64 returns the maximum float64 value from the slice. Returns 0 and false for empty slices.

func MaxInt added in v0.5.0

func MaxInt[T any](slice []T, getter func(T) int) (int, bool)

MaxInt returns the maximum int value from the slice. Returns 0 and false for empty slices.

func MinFloat64 added in v0.5.0

func MinFloat64[T any](slice []T, getter func(T) float64) (float64, bool)

MinFloat64 returns the minimum float64 value from the slice. Returns 0 and false for empty slices.

func MinInt added in v0.5.0

func MinInt[T any](slice []T, getter func(T) int) (int, bool)

MinInt returns the minimum int value from the slice. Returns 0 and false for empty slices.

func NextMockUUID

func NextMockUUID() string

NextMockUUID generates a predictable sequential UUID for testing. UUIDs are formatted as: 00000000-0000-0000-0000-000000000001, etc. This allows tests to assert on specific UUID values.

func None added in v0.5.0

func None[T any](slice []T, predicate func(T) bool) bool

None returns true if no elements in the slice satisfy the predicate. Equivalent to T-SQL NOT EXISTS.

func OpenJSONWithSchema

func OpenJSONWithSchema(jsonStr string, path string, schema []OpenJSONColumn) ([]map[string]Value, error)

OpenJSONWithSchema parses JSON with a schema (WITH clause)

func Reduce added in v0.5.0

func Reduce[T any, R any](slice []T, initial R, accumulator func(R, T) R) R

Reduce aggregates all elements of a slice into a single value. Equivalent to T-SQL aggregate functions over a table variable.

func RegisterStage3Functions

func RegisterStage3Functions(registry *FunctionRegistry)

RegisterStage3Functions registers additional functions for Stage 3 Note: Many functions already exist in functions.go, so only truly new ones are added here

func ResetMockUUID

func ResetMockUUID()

ResetMockUUID resets the mock UUID counter to zero. Call this at the start of each test to ensure predictable UUIDs.

func SetDefaultSPLogger

func SetDefaultSPLogger(logger SPLogger)

SetDefaultSPLogger sets the global default logger.

func SetErrorContext

func SetErrorContext(errNum int, msg string, line int, proc string, state int, severity int)

SetErrorContext updates the error context for error functions

func SetMockUUID

func SetMockUUID(value uint64)

SetMockUUID sets the mock UUID counter to a specific value. The next call to NextMockUUID will return value+1.

func ShouldRollback

func ShouldRollback(err *SQLError, xactAbort bool) bool

ShouldRollback returns true if the error should trigger a rollback

func SumFloat64 added in v0.5.0

func SumFloat64[T any](slice []T, getter func(T) float64) float64

SumFloat64 sums float64 values extracted from slice elements.

func SumInt added in v0.5.0

func SumInt[T any](slice []T, getter func(T) int) int

SumInt sums integer values extracted from slice elements.

func SumInt32 added in v0.5.0

func SumInt32[T any](slice []T, getter func(T) int32) int32

SumInt32 sums int32 values extracted from slice elements.

func SumInt64 added in v0.5.0

func SumInt64[T any](slice []T, getter func(T) int64) int64

SumInt64 sums int64 values extracted from slice elements.

Types

type BufferedSPLogger

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

BufferedSPLogger buffers errors and flushes them in batches.

func NewBufferedSPLogger

func NewBufferedSPLogger(inner SPLogger, batchSize int, flushInterval time.Duration) *BufferedSPLogger

NewBufferedSPLogger creates a buffered logger.

func (*BufferedSPLogger) Close

func (l *BufferedSPLogger) Close(ctx context.Context) error

Close flushes remaining errors and stops the flush loop.

func (*BufferedSPLogger) Flush

func (l *BufferedSPLogger) Flush(ctx context.Context) error

Flush immediately flushes all buffered errors.

func (*BufferedSPLogger) LogEntry

func (l *BufferedSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry delegates to the inner logger.

func (*BufferedSPLogger) LogError

func (l *BufferedSPLogger) LogError(ctx context.Context, err SPError) error

LogError adds the error to the buffer.

func (*BufferedSPLogger) LogExit

func (l *BufferedSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit delegates to the inner logger.

type ColumnDef

type ColumnDef struct {
	Name         string
	TypeName     string
	Nullable     bool
	Identity     bool
	IdentitySeed int64
	IdentityIncr int64
	DefaultExpr  string
	PrimaryKey   bool
}

ColumnDef is a simple column definition for parsing

type Cursor

type Cursor struct {
	Name        string
	Query       string
	Columns     []string
	Rows        [][]Value
	CurrentRow  int // -1 = before first, len(rows) = after last
	IsOpen      bool
	IsAllocated bool
	CursorType  CursorType
	ScrollType  CursorScrollType
	LockType    CursorLockType
	IsGlobal    bool
	// contains filtered or unexported fields
}

Cursor represents a T-SQL cursor

func (*Cursor) Close

func (c *Cursor) Close() error

Close closes the cursor

func (*Cursor) FetchAbsolute

func (c *Cursor) FetchAbsolute(position int) ([]Value, int)

FetchAbsolute fetches the row at the absolute position (for scrollable cursors)

func (*Cursor) FetchFirst

func (c *Cursor) FetchFirst() ([]Value, int)

FetchFirst fetches the first row (for scrollable cursors)

func (*Cursor) FetchLast

func (c *Cursor) FetchLast() ([]Value, int)

FetchLast fetches the last row (for scrollable cursors)

func (*Cursor) FetchNext

func (c *Cursor) FetchNext() ([]Value, int)

FetchNext fetches the next row Returns the row values and fetch status (0 = success, -1 = no more rows, -2 = row missing)

func (*Cursor) FetchPrior

func (c *Cursor) FetchPrior() ([]Value, int)

FetchPrior fetches the previous row (for scrollable cursors)

func (*Cursor) FetchRelative

func (c *Cursor) FetchRelative(offset int) ([]Value, int)

FetchRelative fetches relative to current position (for scrollable cursors)

func (*Cursor) GetColumnIndex

func (c *Cursor) GetColumnIndex(name string) int

GetColumnIndex returns the index of a column by name

func (*Cursor) GetCurrentRow

func (c *Cursor) GetCurrentRow() ([]Value, bool)

GetCurrentRow returns the current row values

func (*Cursor) Open

func (c *Cursor) Open(columns []string, rows [][]Value) error

Open opens the cursor with result data

func (*Cursor) RowCount

func (c *Cursor) RowCount() int

RowCount returns the number of rows in the cursor

func (*Cursor) Status

func (c *Cursor) Status() int

CursorStatus returns information about a cursor (for CURSOR_STATUS function)

type CursorLockType

type CursorLockType int

CursorLockType represents the lock type

const (
	CursorReadOnly CursorLockType = iota
	CursorScrollLocks
	CursorOptimistic
)

type CursorManager

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

CursorManager manages cursors for a session

func NewCursorManager

func NewCursorManager() *CursorManager

NewCursorManager creates a new cursor manager

func (*CursorManager) ClearSession

func (m *CursorManager) ClearSession()

ClearSession clears all local cursors

func (*CursorManager) DeallocateCursor

func (m *CursorManager) DeallocateCursor(name string) error

DeallocateCursor deallocates a cursor

func (*CursorManager) DeclareCursor

func (m *CursorManager) DeclareCursor(name string, query string, isGlobal bool, cursorType CursorType, scrollType CursorScrollType, lockType CursorLockType) (*Cursor, error)

DeclareCursor declares a new cursor

func (*CursorManager) GetCursor

func (m *CursorManager) GetCursor(name string) (*Cursor, bool)

GetCursor retrieves a cursor by name

type CursorScrollType

type CursorScrollType int

CursorScrollType represents scroll capability

const (
	CursorScrollNone CursorScrollType = iota
	CursorScrollForward
	CursorScrollBackward
	CursorScrollAbsolute
	CursorScrollRelative
	CursorScrollFirst
	CursorScrollLast
)

type CursorType

type CursorType int

CursorType represents the type of cursor

const (
	CursorForwardOnly CursorType = iota
	CursorStatic
	CursorKeyset
	CursorDynamic
	CursorFastForward
)

type DDLHandler

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

DDLHandler handles DDL statements for temp tables

func NewDDLHandler

func NewDDLHandler(ctx *ExecutionContext) *DDLHandler

NewDDLHandler creates a new DDL handler

func (*DDLHandler) DeclareTableVariable

func (h *DDLHandler) DeclareTableVariable(name string, columns []TempTableColumn) error

DeclareTableVariable handles DECLARE @t TABLE (...)

func (*DDLHandler) ExecuteCreateTable

func (h *DDLHandler) ExecuteCreateTable(stmt *ast.CreateTableStatement) error

ExecuteCreateTable handles CREATE TABLE for temp tables

func (*DDLHandler) ExecuteDropTable

func (h *DDLHandler) ExecuteDropTable(stmt *ast.DropTableStatement) error

ExecuteDropTable handles DROP TABLE for temp tables

func (*DDLHandler) ExecuteSelectInto

func (h *DDLHandler) ExecuteSelectInto(columns []string, rows [][]Value, intoTable string) error

ExecuteSelectInto handles SELECT INTO #temp

func (*DDLHandler) ExecuteTruncateTable

func (h *DDLHandler) ExecuteTruncateTable(stmt *ast.TruncateTableStatement) error

ExecuteTruncateTable handles TRUNCATE TABLE for temp tables

type DataType

type DataType int

DataType represents T-SQL data types

const (
	TypeUnknown DataType = iota
	// Integer types
	TypeBit
	TypeTinyInt
	TypeSmallInt
	TypeInt
	TypeBigInt
	// Exact numeric
	TypeDecimal
	TypeNumeric
	TypeMoney
	TypeSmallMoney
	// Approximate numeric
	TypeFloat
	TypeReal
	// Date/time
	TypeDate
	TypeTime
	TypeDateTime
	TypeDateTime2
	TypeSmallDateTime
	TypeDateTimeOffset
	// String
	TypeChar
	TypeVarChar
	TypeNChar
	TypeNVarChar
	TypeText
	TypeNText
	// Binary
	TypeBinary
	TypeVarBinary
	// Other
	TypeUniqueIdentifier
	TypeXML
	TypeTable
)

func ParseDataType

func ParseDataType(typeName string) (DataType, int, int, int)

ParseDataType parses a T-SQL type name into DataType with precision/scale/maxlen

func (DataType) IsDateTime

func (dt DataType) IsDateTime() bool

IsDateTime returns true if the type is a date/time type

func (DataType) IsInteger

func (dt DataType) IsInteger() bool

IsInteger returns true if the type is an integer type

func (DataType) IsNumeric

func (dt DataType) IsNumeric() bool

IsNumeric returns true if the type is numeric

func (DataType) IsString

func (dt DataType) IsString() bool

IsString returns true if the type is a string type

func (DataType) String

func (dt DataType) String() string

type DatabaseLoggerColumns

type DatabaseLoggerColumns struct {
	ProcedureName string
	Parameters    string
	ErrorMessage  string
	ErrorNumber   string
	Severity      string
	State         string
	Line          string
	Timestamp     string
	StackTrace    string
}

DatabaseLoggerColumns defines the column names for the error log table.

func DefaultDatabaseLoggerColumns

func DefaultDatabaseLoggerColumns() DatabaseLoggerColumns

DefaultDatabaseLoggerColumns returns the default column names.

type DatabaseSPLogger

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

DatabaseSPLogger logs stored procedure errors to a database table, matching the common T-SQL pattern of INSERT INTO ErrorLog in CATCH blocks.

func NewDatabaseSPLogger

func NewDatabaseSPLogger(db *sql.DB, tableName, dialect string) *DatabaseSPLogger

NewDatabaseSPLogger creates a new database logger.

func (*DatabaseSPLogger) LogEntry

func (l *DatabaseSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry is a no-op for the database logger (can be extended).

func (*DatabaseSPLogger) LogError

func (l *DatabaseSPLogger) LogError(ctx context.Context, err SPError) error

LogError inserts the error into the database table.

func (*DatabaseSPLogger) LogExit

func (l *DatabaseSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit is a no-op for the database logger (can be extended).

func (*DatabaseSPLogger) WithColumns

WithColumns sets custom column names.

type Dialect

type Dialect int

Dialect represents the target SQL dialect

const (
	DialectGeneric Dialect = iota
	DialectPostgres
	DialectMySQL
	DialectSQLite
	DialectSQLServer
)

type ErrorContext

type ErrorContext struct {
	HasError    bool
	LastError   *SQLError
	ErrorNumber int
	ErrorMsg    string
	ErrorLine   int
	ErrorProc   string
	ErrorState  int
	ErrorSev    int
	XactState   int // -1 = uncommittable, 0 = no transaction, 1 = committable
}

ErrorContext holds error state for TRY/CATCH

func NewErrorContext

func NewErrorContext() *ErrorContext

NewErrorContext creates a new error context

func (*ErrorContext) Clear

func (ec *ErrorContext) Clear()

Clear clears the error state

func (*ErrorContext) SetError

func (ec *ErrorContext) SetError(err *SQLError)

SetError sets the current error

type ExecutionContext

type ExecutionContext struct {
	// Database connection
	DB *sql.DB
	Tx *sql.Tx

	// Dialect for query generation
	Dialect Dialect

	// Variables
	Variables map[string]Value

	// Temp tables and table variables
	TempTables *TempTableManager

	// Cursors
	Cursors *CursorManager

	// Error handling
	ErrorHandler *TryCatchHandler

	// System variables
	RowCount     int64
	LastInsertID int64
	FetchStatus  int
	TranCount    int
	Error        int
	NoCount      bool
	XactAbort    bool

	// Execution state
	ReturnValue *Value
	HasReturned bool

	// Result sets
	ResultSets []ResultSet

	// Parent context for nested execution
	Parent *ExecutionContext

	// Debugging
	Debug bool
	// contains filtered or unexported fields
}

ExecutionContext holds all state for a T-SQL execution session

func NewExecutionContext

func NewExecutionContext(db *sql.DB, dialect Dialect) *ExecutionContext

NewExecutionContext creates a new execution context

func (*ExecutionContext) AddResultSet

func (ec *ExecutionContext) AddResultSet(rs ResultSet)

AddResultSet adds a result set to the output

func (*ExecutionContext) BeginTransaction

func (ec *ExecutionContext) BeginTransaction(ctx context.Context) error

BeginTransaction starts a transaction

func (*ExecutionContext) ClearResultSets

func (ec *ExecutionContext) ClearResultSets()

ClearResultSets clears all result sets

func (*ExecutionContext) CommitTransaction

func (ec *ExecutionContext) CommitTransaction() error

CommitTransaction commits the current transaction

func (*ExecutionContext) DeclareVariable

func (ec *ExecutionContext) DeclareVariable(name string, dt DataType, precision, scale, maxLen int)

DeclareVariable declares a new variable with a type

func (*ExecutionContext) GetExecutor

func (ec *ExecutionContext) GetExecutor() QueryExecutor

GetExecutor returns the query executor (Tx if in transaction, DB otherwise)

func (*ExecutionContext) GetVariable

func (ec *ExecutionContext) GetVariable(name string) (Value, bool)

GetVariable gets a variable value

func (*ExecutionContext) NewChildContext

func (ec *ExecutionContext) NewChildContext() *ExecutionContext

NewChildContext creates a child context for nested execution

func (*ExecutionContext) RollbackTransaction

func (ec *ExecutionContext) RollbackTransaction() error

RollbackTransaction rolls back the current transaction

func (*ExecutionContext) SetVariable

func (ec *ExecutionContext) SetVariable(name string, value Value)

SetVariable sets a variable value

func (*ExecutionContext) UpdateError

func (ec *ExecutionContext) UpdateError(errNum int)

UpdateError updates @@ERROR

func (*ExecutionContext) UpdateFetchStatus

func (ec *ExecutionContext) UpdateFetchStatus(status int)

UpdateFetchStatus updates @@FETCH_STATUS

func (*ExecutionContext) UpdateLastInsertID

func (ec *ExecutionContext) UpdateLastInsertID(id int64)

UpdateLastInsertID updates @@IDENTITY

func (*ExecutionContext) UpdateRowCount

func (ec *ExecutionContext) UpdateRowCount(count int64)

UpdateRowCount updates @@ROWCOUNT

type ExecutionResult

type ExecutionResult struct {
	ResultSets   []ResultSet
	RowsAffected int64
	LastInsertID int64
	ReturnValue  *int64
	Error        *SQLError
}

ExecutionResult contains the results of executing dynamic SQL

type ExpressionEvaluator

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

ExpressionEvaluator evaluates T-SQL expressions at runtime

func NewExpressionEvaluator

func NewExpressionEvaluator() *ExpressionEvaluator

NewExpressionEvaluator creates a new expression evaluator

func (*ExpressionEvaluator) Evaluate

func (e *ExpressionEvaluator) Evaluate(expr ast.Expression) (Value, error)

Evaluate evaluates an AST expression and returns its value

func (*ExpressionEvaluator) GetVariable

func (e *ExpressionEvaluator) GetVariable(name string) (Value, bool)

GetVariable gets a variable value

func (*ExpressionEvaluator) SetVariable

func (e *ExpressionEvaluator) SetVariable(name string, value Value)

SetVariable sets a variable value

func (*ExpressionEvaluator) SetVariables

func (e *ExpressionEvaluator) SetVariables(vars map[string]interface{})

SetVariables sets multiple variables from a map

type FileSPLogger

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

FileSPLogger logs errors to a file in JSON or text format.

func NewFileSPLogger

func NewFileSPLogger(path string, format string) (*FileSPLogger, error)

NewFileSPLogger creates a file-based logger.

func (*FileSPLogger) Close

func (l *FileSPLogger) Close() error

Close closes the file.

func (*FileSPLogger) LogEntry

func (l *FileSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry writes entry to the file.

func (*FileSPLogger) LogError

func (l *FileSPLogger) LogError(ctx context.Context, err SPError) error

LogError writes the error to the file.

func (*FileSPLogger) LogExit

func (l *FileSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit writes exit to the file.

type ForJSONMode

type ForJSONMode int

ForJSON converts a result set to JSON

const (
	ForJSONAuto ForJSONMode = iota
	ForJSONPath
	ForJSONRaw
)

type ForJSONOptions

type ForJSONOptions struct {
	Mode                ForJSONMode
	RootName            string // ROOT('name')
	IncludeNullValues   bool
	WithoutArrayWrapper bool
}

ForJSONOptions holds options for FOR JSON clause

type ForXMLMode

type ForXMLMode int

ForXMLMode represents the FOR XML mode

const (
	ForXMLRaw ForXMLMode = iota
	ForXMLAuto
	ForXMLPath
	ForXMLExplicit
)

type ForXMLOptions

type ForXMLOptions struct {
	Mode        ForXMLMode
	ElementName string // For RAW('name') or PATH('name')
	RootName    string // ROOT('name')
	Elements    bool   // ELEMENTS option
	XSINil      bool   // XSINIL option
}

ForXMLOptions holds options for FOR XML clause

type Function

type Function func(args []Value) (Value, error)

Function is a T-SQL function implementation

type FunctionRegistry

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

FunctionRegistry holds all registered functions

func NewFunctionRegistry

func NewFunctionRegistry() *FunctionRegistry

NewFunctionRegistry creates a new function registry with built-in functions

func (*FunctionRegistry) Call

func (r *FunctionRegistry) Call(name string, args []Value) (Value, error)

Call invokes a function by name

func (*FunctionRegistry) Has

func (r *FunctionRegistry) Has(name string) bool

Has returns true if the function exists

func (*FunctionRegistry) Register

func (r *FunctionRegistry) Register(name string, fn Function)

Register adds a function to the registry

type Interpreter

type Interpreter struct {

	// Options
	Debug bool
	// contains filtered or unexported fields
}

Interpreter executes T-SQL dynamically

func NewInterpreter

func NewInterpreter(db *sql.DB, dialect Dialect) *Interpreter

NewInterpreter creates a new T-SQL interpreter

func NewInterpreterWithContext

func NewInterpreterWithContext(ctx *ExecutionContext) *Interpreter

NewInterpreterWithContext creates an interpreter with an existing context

func (*Interpreter) Execute

func (i *Interpreter) Execute(ctx context.Context, sqlStr string, params map[string]interface{}) (*ExecutionResult, error)

Execute parses and executes dynamic SQL

func (*Interpreter) ExecuteNonQuery

func (i *Interpreter) ExecuteNonQuery(ctx context.Context, sql string, params map[string]interface{}) (int64, error)

ExecuteNonQuery executes a non-query statement and returns rows affected

func (*Interpreter) ExecuteQuery

func (i *Interpreter) ExecuteQuery(ctx context.Context, sql string, params map[string]interface{}) (*ResultSet, error)

ExecuteQuery executes a single query and returns results

func (*Interpreter) ExecuteScalar

func (i *Interpreter) ExecuteScalar(ctx context.Context, sql string, params map[string]interface{}) (interface{}, error)

ExecuteScalar executes a query and returns the first column of the first row

func (*Interpreter) GetCursor

func (i *Interpreter) GetCursor(name string) (*Cursor, bool)

GetCursor returns a cursor by name (for testing)

func (*Interpreter) GetTableVariable

func (i *Interpreter) GetTableVariable(name string) (*TableVariable, bool)

GetTableVariable returns a table variable by name (for testing)

func (*Interpreter) GetTempTable

func (i *Interpreter) GetTempTable(name string) (*TempTable, bool)

GetTempTable returns a temp table by name (for testing)

func (*Interpreter) GetVariable

func (i *Interpreter) GetVariable(name string) (interface{}, bool)

GetVariable gets a variable value

func (*Interpreter) SetTransaction

func (i *Interpreter) SetTransaction(tx *sql.Tx)

SetTransaction sets the transaction for execution

func (*Interpreter) SetVariable

func (i *Interpreter) SetVariable(name string, value interface{})

SetVariable sets a variable value

type MultiSPLogger

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

MultiSPLogger logs to multiple loggers simultaneously.

func NewMultiSPLogger

func NewMultiSPLogger(loggers ...SPLogger) *MultiSPLogger

NewMultiSPLogger creates a logger that writes to multiple destinations.

func (*MultiSPLogger) LogEntry

func (l *MultiSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry logs to all configured loggers.

func (*MultiSPLogger) LogError

func (l *MultiSPLogger) LogError(ctx context.Context, err SPError) error

LogError logs to all configured loggers.

func (*MultiSPLogger) LogExit

func (l *MultiSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit logs to all configured loggers.

type NopSPLogger

type NopSPLogger struct{}

NopSPLogger is a no-op logger that discards all log entries.

func NewNopSPLogger

func NewNopSPLogger() *NopSPLogger

NewNopSPLogger creates a no-op logger.

func (*NopSPLogger) LogEntry

func (l *NopSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry does nothing.

func (*NopSPLogger) LogError

func (l *NopSPLogger) LogError(ctx context.Context, err SPError) error

LogError does nothing.

func (*NopSPLogger) LogExit

func (l *NopSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit does nothing.

type OpenJSONColumn

type OpenJSONColumn struct {
	Name     string
	Type     DataType
	JSONPath string // Optional, defaults to $.Name
}

OpenJSONColumn represents a column in OPENJSON WITH clause

type OpenJSONResult

type OpenJSONResult struct {
	Key   string
	Value string
	Type  int // 0=null, 1=string, 2=number, 3=bool, 4=array, 5=object
}

OpenJSONResult represents a row from OPENJSON

func OpenJSON

func OpenJSON(jsonStr string, path string) ([]OpenJSONResult, error)

OpenJSON implements OPENJSON - parses JSON into rows

type OpenXMLColumn

type OpenXMLColumn struct {
	Name   string
	Type   DataType
	MaxLen int
	XPath  string // Optional XPath for the column
}

OpenXMLColumn represents a column definition for OPENXML

type OpenXMLResult

type OpenXMLResult struct {
	Rows []map[string]Value
}

OpenXMLResult represents the result of OPENXML

func OpenXML

func OpenXML(xmlStr string, xpath string, flags int, schema []OpenXMLColumn) (*OpenXMLResult, error)

OpenXML implements OPENXML for parsing XML into a table

type QueryExecutor

type QueryExecutor interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}

QueryExecutor is an interface for executing queries

type ResultSet

type ResultSet struct {
	Columns []string
	Rows    [][]Value
}

ResultSet represents a single result set from a query

type SPError

type SPError struct {
	// ProcedureName is the name of the stored procedure where the error occurred.
	ProcedureName string `json:"procedure_name" xml:"ProcedureName"`

	// Parameters contains the input parameters at the time of the error.
	Parameters map[string]interface{} `json:"parameters" xml:"Parameters"`

	// ErrorMessage is the error message (equivalent to ERROR_MESSAGE()).
	ErrorMessage string `json:"error_message" xml:"ErrorMessage"`

	// ErrorNumber is the error number (equivalent to ERROR_NUMBER()).
	// In Go, this is typically 0 unless parsed from a specific error type.
	ErrorNumber int `json:"error_number" xml:"ErrorNumber"`

	// Severity is the error severity (equivalent to ERROR_SEVERITY()).
	// In Go, this is typically mapped: 0=info, 10=warning, 16=error, 20+=critical.
	Severity int `json:"severity" xml:"Severity"`

	// State is the error state (equivalent to ERROR_STATE()).
	State int `json:"state" xml:"State"`

	// Line is the approximate line number where the error occurred.
	Line int `json:"line" xml:"Line"`

	// Timestamp is when the error occurred.
	Timestamp time.Time `json:"timestamp" xml:"Timestamp"`

	// StackTrace contains the Go stack trace if available.
	StackTrace string `json:"stack_trace,omitempty" xml:"StackTrace,omitempty"`

	// RecoveredValue is the raw value from recover() if this came from a panic.
	RecoveredValue interface{} `json:"-" xml:"-"`
}

SPError represents an error captured in a stored procedure's CATCH block.

func CaptureError

func CaptureError(procName string, recovered interface{}, params map[string]interface{}) SPError

CaptureError creates an SPError from a recovered panic value. This is the primary helper for use in generated CATCH blocks.

func CaptureErrorWithCaller

func CaptureErrorWithCaller(procName string, recovered interface{}, params map[string]interface{}, skip int) SPError

CaptureErrorWithCaller creates an SPError with a custom caller skip level.

func (SPError) ToJSON

func (e SPError) ToJSON() string

ToJSON returns the error as JSON.

func (SPError) ToXML

func (e SPError) ToXML() string

ToXML returns the error as XML, matching the T-SQL FOR XML PATH pattern.

type SPLogger

type SPLogger interface {
	// LogError logs an error from a CATCH block.
	LogError(ctx context.Context, err SPError) error

	// LogEntry logs procedure entry (optional, for tracing).
	LogEntry(ctx context.Context, procName string, params map[string]interface{})

	// LogExit logs procedure exit (optional, for tracing).
	LogExit(ctx context.Context, procName string, duration time.Duration, err error)
}

SPLogger is the interface for logging stored procedure errors.

func GetDefaultSPLogger

func GetDefaultSPLogger() SPLogger

GetDefaultSPLogger returns the global default logger.

type SQLError

type SQLError struct {
	Number    int
	Severity  int
	State     int
	Message   string
	Procedure string
	Line      int
}

SQLError represents a T-SQL error

func NewSQLError

func NewSQLError(number int, message string) *SQLError

NewSQLError creates a new SQL error

func RaiseError

func RaiseError(msg string, severity, state int, args ...interface{}) *SQLError

RaiseError creates a RAISERROR

func ThrowError

func ThrowError(number int, message string, state int) *SQLError

ThrowError creates a THROW error

func WrapError

func WrapError(err error) *SQLError

WrapError wraps a Go error as a SQLError

func (*SQLError) Error

func (e *SQLError) Error() string

type SlogSPLogger

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

SlogSPLogger logs stored procedure errors using Go's slog package.

func NewSlogSPLogger

func NewSlogSPLogger(logger *slog.Logger) *SlogSPLogger

NewSlogSPLogger creates a new slog-based logger.

func NewSlogSPLoggerWithHandler

func NewSlogSPLoggerWithHandler(handler slog.Handler) *SlogSPLogger

NewSlogSPLoggerWithHandler creates a logger with a custom handler.

func (*SlogSPLogger) LogEntry

func (l *SlogSPLogger) LogEntry(ctx context.Context, procName string, params map[string]interface{})

LogEntry logs procedure entry.

func (*SlogSPLogger) LogError

func (l *SlogSPLogger) LogError(ctx context.Context, err SPError) error

LogError logs the error using slog.

func (*SlogSPLogger) LogExit

func (l *SlogSPLogger) LogExit(ctx context.Context, procName string, duration time.Duration, err error)

LogExit logs procedure exit.

type TableRow added in v0.5.0

type TableRow interface {
	// ColumnNames returns the names of all columns in the row.
	ColumnNames() []string

	// ColumnValues returns the values of all columns as a slice of any.
	// The order matches ColumnNames().
	ColumnValues() []any

	// ScanFrom populates the row from a database row.
	// Returns an error if the scan fails.
	ScanFrom(row *sql.Row) error

	// ScanFromRows populates the row from a database rows cursor.
	// Returns an error if the scan fails.
	ScanFromRows(rows *sql.Rows) error
}

TableRow is the interface implemented by all generated table variable row types. It provides reflection-free access to column metadata and values, enabling generic operations on table variable rows without sacrificing type safety in the generated code.

type TableVariable

type TableVariable struct {
	*TempTable
}

TableVariable represents a table variable (@table)

type TempTable

type TempTable struct {
	Name       string
	Columns    []TempTableColumn
	Rows       [][]Value
	PrimaryKey []string
	Indexes    map[string]*TempTableIndex
	// contains filtered or unexported fields
}

TempTable represents an in-memory temporary table (#table or ##table)

func (*TempTable) CreateIndex

func (t *TempTable) CreateIndex(name string, columns []string, unique bool) error

CreateIndex creates an index on the temp table

func (*TempTable) Delete

func (t *TempTable) Delete(predicate func(row []Value) bool) int

Delete removes rows matching the predicate

func (*TempTable) GetColumn

func (t *TempTable) GetColumn(name string) (*TempTableColumn, bool)

GetColumn returns column info by name

func (*TempTable) GetColumnIndex

func (t *TempTable) GetColumnIndex(name string) int

GetColumnIndex returns the index of a column by name

func (*TempTable) Insert

func (t *TempTable) Insert(values map[string]Value) (int64, error)

Insert inserts a row into the temp table

func (*TempTable) InsertRow

func (t *TempTable) InsertRow(values []Value) (int64, error)

InsertRow inserts a row with values in column order

func (*TempTable) OrderBy

func (t *TempTable) OrderBy(columnName string, ascending bool) error

OrderBy sorts the temp table in place

func (*TempTable) RowCount

func (t *TempTable) RowCount() int

RowCount returns the number of rows

func (*TempTable) Select

func (t *TempTable) Select(predicate func(row []Value) bool) [][]Value

Select returns rows matching the predicate

func (*TempTable) SelectAll

func (t *TempTable) SelectAll() [][]Value

SelectAll returns all rows

func (*TempTable) SelectColumns

func (t *TempTable) SelectColumns(columnNames []string, predicate func(row []Value) bool) ([]string, [][]Value)

SelectColumns returns specified columns

func (*TempTable) ToResultSet

func (t *TempTable) ToResultSet() ResultSet

ToResultSet converts the temp table to a ResultSet

func (*TempTable) Truncate

func (t *TempTable) Truncate()

Truncate removes all rows

func (*TempTable) Update

func (t *TempTable) Update(updates map[string]Value, predicate func(row []Value) bool) int

Update updates rows matching the predicate

type TempTableColumn

type TempTableColumn struct {
	Name         string
	Type         DataType
	Precision    int
	Scale        int
	MaxLen       int
	Nullable     bool
	DefaultValue Value
	Identity     bool
	IdentitySeed int64
	IdentityIncr int64
}

TempTableColumn represents a column in a temp table

func ParseColumnDefinitions

func ParseColumnDefinitions(defs []ColumnDef) []TempTableColumn

ParseColumnDefinitions parses column definitions from CREATE TABLE

type TempTableIndex

type TempTableIndex struct {
	Name      string
	Columns   []string
	Unique    bool
	Clustered bool
}

TempTableIndex represents an index on a temp table

type TempTableManager

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

TempTableManager manages temporary tables for a session

func NewTempTableManager

func NewTempTableManager() *TempTableManager

NewTempTableManager creates a new temp table manager

func (*TempTableManager) ClearSession

func (m *TempTableManager) ClearSession()

ClearSession clears all session-scoped temp tables and table variables

func (*TempTableManager) CreateTableVariable

func (m *TempTableManager) CreateTableVariable(name string, columns []TempTableColumn) (*TableVariable, error)

CreateTableVariable creates a table variable

func (*TempTableManager) CreateTempTable

func (m *TempTableManager) CreateTempTable(name string, columns []TempTableColumn) (*TempTable, error)

CreateTempTable creates a new temporary table

func (*TempTableManager) DropTempTable

func (m *TempTableManager) DropTempTable(name string) error

DropTempTable drops a temporary table

func (*TempTableManager) GetTableVariable

func (m *TempTableManager) GetTableVariable(name string) (*TableVariable, bool)

GetTableVariable retrieves a table variable

func (*TempTableManager) GetTempTable

func (m *TempTableManager) GetTempTable(name string) (*TempTable, bool)

GetTempTable retrieves a temp table by name

func (*TempTableManager) TempTableExists

func (m *TempTableManager) TempTableExists(name string) bool

TempTableExists checks if a temp table exists

type TryCatchHandler

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

TryCatchHandler handles TRY/CATCH block execution

func NewTryCatchHandler

func NewTryCatchHandler() *TryCatchHandler

NewTryCatchHandler creates a new TRY/CATCH handler

func (*TryCatchHandler) EnterCatch

func (h *TryCatchHandler) EnterCatch()

EnterCatch marks entry into a CATCH block

func (*TryCatchHandler) EnterTry

func (h *TryCatchHandler) EnterTry()

EnterTry marks entry into a TRY block

func (*TryCatchHandler) ExitCatch

func (h *TryCatchHandler) ExitCatch()

ExitCatch marks exit from a CATCH block

func (*TryCatchHandler) ExitTry

func (h *TryCatchHandler) ExitTry()

ExitTry marks exit from a TRY block

func (*TryCatchHandler) GetErrorLine

func (h *TryCatchHandler) GetErrorLine() int

GetErrorLine returns ERROR_LINE()

func (*TryCatchHandler) GetErrorMessage

func (h *TryCatchHandler) GetErrorMessage() string

GetErrorMessage returns ERROR_MESSAGE()

func (*TryCatchHandler) GetErrorNumber

func (h *TryCatchHandler) GetErrorNumber() int

GetErrorNumber returns ERROR_NUMBER()

func (*TryCatchHandler) GetErrorProcedure

func (h *TryCatchHandler) GetErrorProcedure() string

GetErrorProcedure returns ERROR_PROCEDURE()

func (*TryCatchHandler) GetErrorSeverity

func (h *TryCatchHandler) GetErrorSeverity() int

GetErrorSeverity returns ERROR_SEVERITY()

func (*TryCatchHandler) GetErrorState

func (h *TryCatchHandler) GetErrorState() int

GetErrorState returns ERROR_STATE()

func (*TryCatchHandler) GetXactState

func (h *TryCatchHandler) GetXactState() int

GetXactState returns XACT_STATE()

func (*TryCatchHandler) HandleError

func (h *TryCatchHandler) HandleError(err error) bool

HandleError processes an error during TRY block execution Returns true if error was caught, false if it should propagate

func (*TryCatchHandler) HasCaughtError

func (h *TryCatchHandler) HasCaughtError() bool

HasCaughtError returns true if an error was caught

func (*TryCatchHandler) SetXactState

func (h *TryCatchHandler) SetXactState(state int)

SetXactState sets the transaction state

type Value

type Value struct {
	Type      DataType
	IsNull    bool
	Precision int // For decimal/numeric
	Scale     int // For decimal/numeric
	MaxLen    int // For string/binary types
	// contains filtered or unexported fields
}

Value represents a runtime T-SQL value with type information

func Cast

func Cast(v Value, targetType DataType, precision, scale, maxLen int) (Value, error)

Cast converts a value to the target type

func Convert

func Convert(v Value, targetType DataType, precision, scale, maxLen int, style int) (Value, error)

Convert converts a value to the target type with optional style

func IsJSON

func IsJSON(str string) (Value, error)

IsJSON implements ISJSON - checks if a string is valid JSON

func JSONModify

func JSONModify(jsonStr string, path string, newValue interface{}) (Value, error)

JSONModify implements JSON_MODIFY - modifies a value in JSON

func JSONQuery

func JSONQuery(jsonStr string, path string) (Value, error)

JSONQuery implements JSON_QUERY - extracts an object or array from JSON

func JSONValue

func JSONValue(jsonStr string, path string) (Value, error)

JSONValue implements JSON_VALUE - extracts a scalar value from JSON

func NewBigInt

func NewBigInt(v int64) Value

NewBigInt creates a bigint value

func NewBinary

func NewBinary(v []byte) Value

NewBinary creates a binary value

func NewBit

func NewBit(v bool) Value

NewBit creates a bit value

func NewChar

func NewChar(v string, length int) Value

NewChar creates a char value (padded to length)

func NewDate

func NewDate(v time.Time) Value

NewDate creates a date value

func NewDateTime

func NewDateTime(v time.Time) Value

NewDateTime creates a datetime value

func NewDecimal

func NewDecimal(v decimal.Decimal, precision, scale int) Value

NewDecimal creates a decimal value

func NewDecimalFromString

func NewDecimalFromString(s string, precision, scale int) (Value, error)

NewDecimalFromString creates a decimal from a string

func NewFloat

func NewFloat(v float64) Value

NewFloat creates a float value

func NewInt

func NewInt(v int64) Value

NewInt creates an integer value

func NewMoney

func NewMoney(v decimal.Decimal) Value

NewMoney creates a money value

func NewNVarChar

func NewNVarChar(v string, maxLen int) Value

NewNVarChar creates an nvarchar value

func NewReal

func NewReal(v float32) Value

NewReal creates a real value

func NewSmallInt

func NewSmallInt(v int16) Value

NewSmallInt creates a smallint value

func NewTime

func NewTime(v time.Time) Value

NewTime creates a time value

func NewTinyInt

func NewTinyInt(v uint8) Value

NewTinyInt creates a tinyint value

func NewVarBinary

func NewVarBinary(v []byte, maxLen int) Value

NewVarBinary creates a new varbinary value

func NewVarChar

func NewVarChar(v string, maxLen int) Value

NewVarChar creates a varchar value

func NewXML

func NewXML(s string) Value

NewXML creates a new XML value

func Null

func Null(dt DataType) Value

Null returns a NULL value of the given type

func ToValue

func ToValue(v interface{}) Value

ToValue converts a Go value to a runtime Value

func XMLExist

func XMLExist(xmlStr string, xpath string) (Value, error)

XMLExist implements .exist() - checks if XPath matches

func XMLQuery

func XMLQuery(xmlStr string, xpath string) (Value, error)

XMLQuery implements .query() - extracts XML fragment

func XMLValue

func XMLValue(xmlStr string, xpath string, targetType DataType) (Value, error)

XMLValue implements .value() - extracts a scalar value from XML

func (Value) Add

func (v Value) Add(other Value) Value

Add performs addition

func (Value) And

func (v Value) And(other Value) Value

And performs logical AND

func (Value) AsBool

func (v Value) AsBool() bool

AsBool returns the value as bool, with type coercion

func (Value) AsDecimal

func (v Value) AsDecimal() decimal.Decimal

AsDecimal returns the value as decimal.Decimal, with type coercion

func (Value) AsFloat

func (v Value) AsFloat() float64

AsFloat returns the value as float64, with type coercion

func (Value) AsInt

func (v Value) AsInt() int64

AsInt returns the value as int64, with type coercion

func (Value) AsString

func (v Value) AsString() string

AsString returns the value as string, with type coercion

func (Value) AsTime

func (v Value) AsTime() time.Time

AsTime returns the value as time.Time, with type coercion

func (Value) BitwiseAnd

func (v Value) BitwiseAnd(other Value) Value

BitwiseAnd performs bitwise AND

func (Value) BitwiseNot

func (v Value) BitwiseNot() Value

BitwiseNot performs bitwise NOT

func (Value) BitwiseOr

func (v Value) BitwiseOr(other Value) Value

BitwiseOr performs bitwise OR

func (Value) BitwiseXor

func (v Value) BitwiseXor(other Value) Value

BitwiseXor performs bitwise XOR

func (Value) Clone

func (v Value) Clone() Value

Clone creates a copy of the value

func (Value) Compare

func (v Value) Compare(other Value) int

Compare compares two values, returning -1, 0, or 1

func (Value) Div

func (v Value) Div(other Value) Value

Div performs division

func (Value) Equals

func (v Value) Equals(other Value) Value

Equals checks if two values are equal (handles NULL)

func (Value) GreaterThan

func (v Value) GreaterThan(other Value) Value

GreaterThan compares values

func (Value) GreaterThanOrEqual

func (v Value) GreaterThanOrEqual(other Value) Value

GreaterThanOrEqual compares values

func (Value) IsTruthy

func (v Value) IsTruthy() bool

IsTruthy returns true if the value is considered "true" in a boolean context

func (Value) LessThan

func (v Value) LessThan(other Value) Value

LessThan compares values

func (Value) LessThanOrEqual

func (v Value) LessThanOrEqual(other Value) Value

LessThanOrEqual compares values

func (Value) Mod

func (v Value) Mod(other Value) Value

Mod performs modulo

func (Value) Mul

func (v Value) Mul(other Value) Value

Mul performs multiplication

func (Value) Neg

func (v Value) Neg() Value

Neg negates the value

func (Value) Not

func (v Value) Not() Value

Not performs logical NOT

func (Value) NotEquals

func (v Value) NotEquals(other Value) Value

NotEquals checks if two values are not equal

func (Value) Or

func (v Value) Or(other Value) Value

Or performs logical OR

func (Value) Power

func (v Value) Power(exp Value) Value

Power raises v to the power of exp

func (Value) Sub

func (v Value) Sub(other Value) Value

Sub performs subtraction

func (Value) ToInterface

func (v Value) ToInterface() interface{}

ToInterface converts the Value to a Go interface{} for use with JSON/XML

type XMLNode

type XMLNode struct {
	Name       string
	Value      string
	Attributes map[string]string
	Children   []*XMLNode
	Parent     *XMLNode
}

XMLNode represents a parsed XML node

func ParseXML

func ParseXML(xmlStr string) (*XMLNode, error)

ParseXML parses an XML string into a tree structure

type XMLNodesResult

type XMLNodesResult struct {
	Node *XMLNode
}

XMLNodesResult represents a row from .nodes()

func XMLNodes

func XMLNodes(xmlStr string, xpath string) ([]XMLNodesResult, error)

XMLNodes implements .nodes() - shreds XML into rows

Jump to

Keyboard shortcuts

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