sql

package
v0.0.0-...-5106b98 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultConnectTimeoutSeconds is the shared default for TCP SQL connector startup.
	DefaultConnectTimeoutSeconds = 5
	// DefaultMaxOpenConns is the shared conservative pool size for SQL connectors.
	DefaultMaxOpenConns = 5
	// DefaultMaxIdleConns is the shared idle pool size for SQL connectors.
	DefaultMaxIdleConns = 2
	// DefaultConnMaxIdleTime retires connections that remain unused.
	DefaultConnMaxIdleTime = 5 * time.Minute
	// DefaultConnMaxLifetime bounds how long a connection can retain credentials.
	DefaultConnMaxLifetime = 30 * time.Minute
)

Variables

View Source
var (
	// ErrConnectionFailed indicates that a connection to the SQL data source could not be
	// established.
	ErrConnectionFailed = xerror.ConnectionFailed(xerror.DataSource)

	// ErrQueryExecutionFailed indicates that a SQL query failed during execution.
	ErrQueryExecutionFailed = xerror.Unavailable(xerror.Query)

	// ErrSchemaIntrospection indicates that SQL schema retrieval failed.
	ErrSchemaIntrospection = xerror.Unavailable(xerror.SchemaMetadata)

	// ErrUnknownConnector indicates that the SQL connector type is not registered.
	ErrUnknownConnector = xerror.Unsupported(xerror.DataSource)

	// ErrInvalidConfig indicates that the SQL connector configuration is invalid or incomplete.
	ErrInvalidConfig = xerror.InvalidInput(xerror.DataSource)
)

Functions

func ApplyCredentialDefaults

func ApplyCredentialDefaults(
	user *string,
	password *string,
	connectTimeoutSeconds *int,
	credentials Credentials,
)

ApplyCredentialDefaults merges resolved credentials and shared connection defaults into config fields.

func BytesToStringValue

func BytesToStringValue(value any, _ string) any

BytesToStringValue normalizes byte slices returned by some SQL drivers into strings.

func CloseDB

func CloseDB(db *stdsql.DB) error

CloseDB closes an existing SQL pool with the shared connector error mapping.

func ConfigureAndPingDB

func ConfigureAndPingDB(
	ctx context.Context,
	db *stdsql.DB,
	config OpenDBConfig,
) (*stdsql.DB, error)

ConfigureAndPingDB applies shared pool settings and verifies startup for an already-opened database/sql pool.

func EmptyResultData

func EmptyResultData() *result.SQLResult

EmptyResultData returns a non-nil empty SQL payload for connectors that retain payloads on errors.

func FileOutputRequested

func FileOutputRequested(raw json.RawMessage) (bool, error)

FileOutputRequested decodes the common SQL result-format contract.

func MetadataStatementMatches

func MetadataStatementMatches(kind model.DataSourceType, resource TableMetadataResource, raw json.RawMessage, source bool) bool

MetadataStatementMatches authorizes only a statically identified relation. Dialect syntax the installed parser cannot resolve remains unverified.

func NewExecutionResult

func NewExecutionResult(
	vendorType string,
	start time.Time,
	queryResult Result,
	err error,
) *result.ExecutionResult

NewExecutionResult wraps a harness SQL result with shared duration and vendor metadata.

func NewExecutionResultData

func NewExecutionResultData(
	vendorType string,
	start time.Time,
	sqlResult *result.SQLResult,
	err error,
) *result.ExecutionResult

NewExecutionResultData wraps an already-normalized SQL payload with shared duration metadata.

func NewFailedExecutionResult

func NewFailedExecutionResult(
	vendorType string,
	start time.Time,
	err error,
) *result.ExecutionResult

NewFailedExecutionResult wraps an execution failure without inventing a result payload.

func NormalizeParams

func NormalizeParams(params map[string]types.TypedParam) (map[string]any, error)

NormalizeParams converts TypedParam values to their appropriate SQL types based on the DataType field. SQL databases require strict type matching for prepared statement parameters (e.g., MySQL rejects float64 for integer placeholders).

func NumericBytesToStringValue

func NumericBytesToStringValue(value any, databaseType string) any

NumericBytesToStringValue preserves text-encoded PostgreSQL numerics without converting bytea values to invalid UTF-8 strings.

func OpenDB

func OpenDB(ctx context.Context, config OpenDBConfig) (*stdsql.DB, error)

OpenDB opens, configures, and verifies a database/sql pool for a dialect-owned driver and DSN.

func ReadTableMetadata

func ReadTableMetadata(rows *sql.Rows, resource TableMetadataResource, limits proofevidence.Limits) (json.RawMessage, int64, proofevidence.Outcome)

ReadTableMetadata scans only a fixed, parameterized system-catalog query.

func ResolveConnectTimeoutSeconds

func ResolveConnectTimeoutSeconds(configured int) int

ResolveConnectTimeoutSeconds applies the shared SQL startup timeout only when unset.

func ResultData

func ResultData(queryResult Result) *result.SQLResult

ResultData converts the harness result shape into the stored connector SQL payload.

func RetainQueryFile

func RetainQueryFile(ctx context.Context, limits types.ExecutionLimits, produce func(context.Context, io.Writer) (StreamResult, error)) (*result.SQLResult, error)

RetainQueryFile stages a provider's complete serialized result before exposing it.

func TestDBConnection

func TestDBConnection(ctx context.Context, db *stdsql.DB, connectTimeoutSeconds int) error

TestDBConnection verifies an existing SQL pool with the shared connector error mapping.

Types

type Capabilities

type Capabilities struct {
	// SupportsSchemaIntrospection indicates whether the connector can introspect database schema.
	SupportsSchemaIntrospection bool
	// SupportsPagination indicates whether the connector supports paginated queries.
	SupportsPagination bool
	// SupportsTransactions indicates whether the connector supports transactions.
	SupportsTransactions bool
}

Capabilities describes what a connector can do.

type Column

type Column struct {
	// Name is the name of the column.
	Name string

	// Type is the SQL type of the column (e.g., "INTEGER", "VARCHAR", "TIMESTAMP").
	Type string

	// Nullable indicates whether the column can contain NULL values.
	Nullable bool
}

Column represents a single column in a table.

type Credentials

type Credentials struct {
	Username string
	Password string
}

Credentials carries the username/password pair shared by TCP SQL connectors.

type MetadataColumn

type MetadataColumn struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Nullable bool   `json:"nullable"`
}

type OpenDBConfig

type OpenDBConfig struct {
	DriverName            string
	DSN                   string
	ConnectTimeoutSeconds int
	MaxOpenConns          int
	MaxIdleConns          int
	ConnMaxIdleTime       time.Duration
	ConnMaxLifetime       time.Duration
	StartupErrorMapper    func(error) error
}

OpenDBConfig describes the driver-owned inputs needed for shared database lifecycle setup.

type Result

type Result struct {
	// ColumnNames is the list of column names in the result.
	// Empty for non-query statements (INSERT, UPDATE, DELETE, DDL).
	ColumnNames []string

	// Rows is the list of data rows, where each row is a map of column name -> value.
	// Empty for non-query statements (INSERT, UPDATE, DELETE, DDL).
	Rows []map[string]any

	// RowCount represents either:
	// - For SELECT/query statements: number of rows returned
	// - For INSERT/UPDATE/DELETE: number of rows affected
	// - For DDL statements: typically 0
	RowCount int

	// LastInsertID is the auto-generated ID from an INSERT statement (if applicable).
	// Only populated for INSERT statements on tables with auto-increment columns.
	// Nil for all other statement types (SELECT, UPDATE, DELETE, DDL).
	LastInsertID *int64
}

Result represents the output of a query execution.

func ResultFromExec

func ResultFromExec(execResult stdsql.Result) Result

ResultFromExec maps database/sql exec metadata into the shared SQL result shape.

func ScanRows

func ScanRows(rows *stdsql.Rows, limits types.ExecutionLimits, normalize ValueNormalizer) (Result, error)

ScanRows consumes database/sql rows into maps while enforcing Braidplane row and response byte limits.

type RowStream

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

RowStream writes one bounded row at a time from SQL drivers or provider pages.

func NewRowStream

func NewRowStream(ctx context.Context, dst io.Writer, names []string, limits types.ExecutionLimits) (*RowStream, error)

func (*RowStream) Finish

func (s *RowStream) Finish() (StreamResult, error)

func (*RowStream) WriteRow

func (s *RowStream) WriteRow(row map[string]any) error

type SQLConnector

type SQLConnector interface {
	GetCapabilities() Capabilities
	SQLSchemaIntrospector
}

SQLConnector defines the SQL-specific connector contract.

type SQLSchemaIntrospector

type SQLSchemaIntrospector interface {
	// IntrospectSchema retrieves the SQL schema (tables, columns, types).
	IntrospectSchema(ctx context.Context) (*Schema, error)
}

SQLSchemaIntrospector retrieves SQL database schema metadata.

type Schema

type Schema struct {
	// Tables is a list of tables in the data source.
	Tables []Table
}

Schema represents the SQL schema of a data source.

type StatementExecutor

type StatementExecutor struct {
	DB               *stdsql.DB
	IsQueryStatement func(string) bool
	NormalizeValue   ValueNormalizer
}

StatementExecutor runs already-prepared SQL statements through a shared database/sql path.

func (StatementExecutor) Exec

func (executor StatementExecutor) Exec(ctx context.Context, stmt string, args []any) (Result, error)

Exec executes a non-row statement and normalizes affected rows and insert identity metadata.

func (StatementExecutor) Execute

func (executor StatementExecutor) Execute(
	ctx context.Context,
	stmt string,
	args []any,
	limits types.ExecutionLimits,
) (Result, error)

Execute runs a statement as either QueryContext or ExecContext using the dialect classifier.

func (StatementExecutor) Query

func (executor StatementExecutor) Query(
	ctx context.Context,
	stmt string,
	args []any,
	limits types.ExecutionLimits,
) (Result, error)

Query executes a row-returning statement and scans rows into the shared SQL result shape.

func (StatementExecutor) QueryTo

func (executor StatementExecutor) QueryTo(ctx context.Context, stmt string, args []any, limits types.ExecutionLimits, dst io.Writer) (StreamResult, error)

QueryTo serializes a finite query in one read-only repeatable-read snapshot. Any error invalidates all bytes written; callers must discard partial output.

type StreamResult

type StreamResult struct {
	Metadata    *filestream.Metadata
	ColumnNames []string
	RowCount    int
}

StreamResult describes a complete serialized SQL result without retaining rows.

func StreamRows

func StreamRows(ctx context.Context, rows *stdsql.Rows, limits types.ExecutionLimits, normalize ValueNormalizer, dst io.Writer) (StreamResult, error)

StreamRows serializes database/sql rows without collecting the result.

type Table

type Table struct {
	// Name is the name of the table.
	Name string

	// Columns is a list of columns in the table.
	Columns []Column
}

Table represents a single SQL table in the data source schema.

type TableMetadataResource

type TableMetadataResource struct {
	Host     string `json:"host"`
	Port     uint16 `json:"port"`
	Database string `json:"database"`
	Schema   string `json:"schema"`
	Table    string `json:"table"`
	SSLMode  string `json:"ssl_mode,omitempty"`
}

TableMetadataResource binds the selected table to the connection configuration. SSLMode is protected PostgreSQL configuration, never an API override.

type TableMetadataSnapshot

type TableMetadataSnapshot struct {
	Database string           `json:"database"`
	Schema   string           `json:"schema"`
	Table    string           `json:"table"`
	Columns  []MetadataColumn `json:"columns"`
}

type ValueNormalizer

type ValueNormalizer func(any, string) any

ValueNormalizer adapts database driver values into Braidplane's normalized SQL row shape.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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