Documentation
¶
Overview ¶
Package types contains the core database interface definitions for go-bricks. These interfaces are separate from the main database package to avoid import cycles and to make them easily accessible for mocking and testing.
Index ¶
- func ValidateSubquery(subquery SelectQueryBuilder)
- type DeleteQueryBuilder
- type Filter
- type FilterFactory
- type Interface
- type JoinFilter
- type JoinFilterFactory
- type QueryBuilderInterface
- type RawExpression
- type Row
- type SelectQueryBuilder
- type Statement
- type TableRef
- type Tx
- type UpdateQueryBuilder
- type Vendor
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ValidateSubquery ¶ added in v0.14.2
func ValidateSubquery(subquery SelectQueryBuilder)
ValidateSubquery checks if a subquery is valid for use in filter expressions. Panics if subquery is nil or produces invalid SQL (fail-fast validation).
This function is called internally by filter implementations to ensure subqueries are constructed correctly before query execution.
Types ¶
type DeleteQueryBuilder ¶ added in v0.13.0
type DeleteQueryBuilder interface {
// Filtering
Where(filter Filter) DeleteQueryBuilder
// Batch operations
Limit(limit uint64) DeleteQueryBuilder
OrderBy(orderBys ...string) DeleteQueryBuilder
// SQL generation
ToSQL() (sql string, args []any, err error)
}
DeleteQueryBuilder defines the interface for DELETE query building with type-safe filtering. This interface wraps squirrel.DeleteBuilder with Filter API support.
type Filter ¶ added in v0.13.0
type Filter interface {
squirrel.Sqlizer
// ToSQL is a convenience method with idiomatic Go naming.
// It should delegate to ToSql() in implementations.
ToSQL() (sql string, args []any, err error)
}
Filter represents a composable WHERE clause filter that can be combined with AND/OR/NOT operators. Filters are created through FilterFactory methods obtained from QueryBuilder.Filter().
Filter embeds squirrel.Sqlizer for compatibility with Squirrel's query builder, and adds ToSQL() as a convenience method with idiomatic Go naming (uppercase SQL).
This is an interface to support mocking and testing. The concrete implementation is in database/internal/builder package.
type FilterFactory ¶ added in v0.13.0
type FilterFactory interface {
// Comparison operators
Eq(column string, value any) Filter
NotEq(column string, value any) Filter
Lt(column string, value any) Filter
Lte(column string, value any) Filter
Gt(column string, value any) Filter
Gte(column string, value any) Filter
In(column string, values any) Filter
NotIn(column string, values any) Filter
Like(column, pattern string) Filter
Null(column string) Filter
NotNull(column string) Filter
Between(column string, lowerBound, upperBound any) Filter
// Logical operators
And(filters ...Filter) Filter
Or(filters ...Filter) Filter
Not(filter Filter) Filter
// Raw escape hatch
Raw(condition string, args ...any) Filter
// Subquery support (v2.1+)
Exists(subquery SelectQueryBuilder) Filter
NotExists(subquery SelectQueryBuilder) Filter
InSubquery(column string, subquery SelectQueryBuilder) Filter
}
FilterFactory provides methods for creating composable, type-safe query filters. Filters maintain vendor-specific quoting rules and can be combined with AND/OR/NOT logic.
type Interface ¶
type Interface interface {
// Query execution
Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRow(ctx context.Context, query string, args ...any) Row
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
// Prepared statements
Prepare(ctx context.Context, query string) (Statement, error)
// Transaction support
Begin(ctx context.Context) (Tx, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (Tx, error)
// Health and diagnostics
Health(ctx context.Context) error
Stats() (map[string]any, error)
// Connection management
Close() error
// Database-specific features
DatabaseType() string
// Migration support
GetMigrationTable() string
CreateMigrationTable(ctx context.Context) error
}
Interface defines the common database operations supported by the framework. This is the main interface that applications and modules should depend on for database operations, allowing for easy mocking and testing.
type JoinFilter ¶ added in v0.13.0
type JoinFilter interface {
squirrel.Sqlizer
// ToSQL is a convenience method with idiomatic Go naming.
// It should delegate to ToSql() in implementations.
ToSQL() (sql string, args []any, err error)
}
JoinFilter represents a filter specifically for JOIN ON conditions where columns are compared to other columns (not to values). This follows Single Responsibility Principle by separating column-to-column comparisons (JOIN) from column-to-value comparisons (WHERE).
JoinFilters are created through JoinFilterFactory methods obtained from QueryBuilder.JoinFilter().
Example:
jf := qb.JoinFilter()
query := qb.Select("*").From("users").JoinOn("profiles", jf.EqColumn("users.id", "profiles.user_id"))
This is an interface to support mocking and testing. The concrete implementation is in database/internal/builder package.
type JoinFilterFactory ¶ added in v0.13.0
type JoinFilterFactory interface {
// Column-to-column comparison operators
EqColumn(leftColumn, rightColumn string) JoinFilter
NotEqColumn(leftColumn, rightColumn string) JoinFilter
LtColumn(leftColumn, rightColumn string) JoinFilter
LteColumn(leftColumn, rightColumn string) JoinFilter
GtColumn(leftColumn, rightColumn string) JoinFilter
GteColumn(leftColumn, rightColumn string) JoinFilter
// Column-to-value comparison operators (v2.2+)
// These methods accept any value type, including RawExpression for complex SQL.
// Regular values generate placeholders; RawExpression values are inserted verbatim.
Eq(column string, value any) JoinFilter
NotEq(column string, value any) JoinFilter
Lt(column string, value any) JoinFilter
Lte(column string, value any) JoinFilter
Gt(column string, value any) JoinFilter
Gte(column string, value any) JoinFilter
In(column string, values any) JoinFilter
NotIn(column string, values any) JoinFilter
Like(column, pattern string) JoinFilter
Null(column string) JoinFilter
NotNull(column string) JoinFilter
Between(column string, lowerBound, upperBound any) JoinFilter
// Logical operators for complex JOIN conditions
And(filters ...JoinFilter) JoinFilter
Or(filters ...JoinFilter) JoinFilter
// Raw escape hatch for complex JOIN conditions
Raw(condition string, args ...any) JoinFilter
}
JoinFilterFactory provides methods for creating type-safe JOIN ON filters. JoinFilters support both column-to-column comparisons and column-to-value comparisons, enabling mixed JOIN conditions without requiring Raw() for common cases.
Column-to-value methods accept RawExpression for complex SQL expressions:
jf.Eq("amount", qb.Expr("TO_NUMBER(?)"), 100) // Expression support
jf.Eq("status", "active") // Simple value with placeholder
type QueryBuilderInterface ¶ added in v0.8.1
type QueryBuilderInterface interface {
// Vendor information
Vendor() string
// Filter factories
Filter() FilterFactory
JoinFilter() JoinFilterFactory
// Expression builder (v2.1+)
Expr(sql string, alias ...string) RawExpression
// Query builders
Select(columns ...any) SelectQueryBuilder
Insert(table string) squirrel.InsertBuilder
InsertWithColumns(table string, columns ...string) squirrel.InsertBuilder
Update(table string) UpdateQueryBuilder
Delete(table string) DeleteQueryBuilder
// Vendor-specific helpers
BuildCaseInsensitiveLike(column, value string) squirrel.Sqlizer
BuildUpsert(table string, conflictColumns []string, insertColumns, updateColumns map[string]any) (query string, args []any, err error)
// Database function builders
BuildCurrentTimestamp() string
BuildUUIDGeneration() string
BuildBooleanValue(value bool) any
// Identifier escaping
EscapeIdentifier(identifier string) string
}
QueryBuilderInterface defines the interface for vendor-specific SQL query building. This interface allows for dependency injection and mocking of query builders, enabling unit testing of business logic that constructs queries without actually generating SQL strings.
type RawExpression ¶ added in v0.14.2
type RawExpression struct {
SQL string // The raw SQL expression
Alias string // Optional alias (AS clause)
}
RawExpression represents a raw SQL expression that can be used in SELECT, GROUP BY, and ORDER BY clauses. It allows using SQL functions, aggregations, calculations, and other expressions that go beyond simple column names.
SECURITY WARNING: Raw SQL expressions are NOT escaped or sanitized by the framework. Never interpolate user input directly into expressions - this creates SQL injection vulnerabilities. Only use static SQL or carefully validated values in expressions.
Safe usage:
qb.Select(qb.Expr("COUNT(*)", "total")) // Aggregation with alias
qb.Select(qb.Expr("UPPER(name)")) // Function without alias
qb.Select(qb.Expr("price * quantity", "total")) // Calculation with alias
Unsafe usage (NEVER do this):
userInput := req.Query("column")
qb.Select(qb.Expr(fmt.Sprintf("UPPER(%s)", userInput))) // SQL INJECTION RISK!
func Expr ¶ added in v0.14.2
func Expr(sql string, alias ...string) RawExpression
Expr creates a raw SQL expression with optional alias for use in SELECT, GROUP BY, and ORDER BY clauses.
Parameters:
- sql: The raw SQL expression (e.g., "COUNT(*)", "UPPER(name)", "price * quantity")
- alias: Optional alias for the expression (e.g., "total", "upper_name"). Max 1 alias allowed.
Validation (fail-fast with panic):
- SQL cannot be empty
- Maximum 1 alias parameter allowed
- Alias cannot contain dangerous characters: ; ' " -- (SQL injection patterns)
Examples:
// Aggregation with alias
qb.Expr("COUNT(*)", "total")
// Function without alias
qb.Expr("UPPER(name)")
// Calculation with alias
qb.Expr("price * quantity", "line_total")
// Window function with alias
qb.Expr("ROW_NUMBER() OVER (PARTITION BY category ORDER BY date)", "row_num")
SECURITY WARNING: Never interpolate user input directly into the sql parameter. This function does NOT sanitize SQL - you are responsible for ensuring safety.
type Row ¶ added in v0.9.0
Row represents a single result set row with basic scanning behaviour.
func NewRowFromSQL ¶ added in v0.9.0
NewRowFromSQL wraps the provided *sql.Row in a Row. If row is nil, NewRowFromSQL returns nil.
type SelectQueryBuilder ¶ added in v0.11.0
type SelectQueryBuilder interface {
// Core SELECT builder methods
// From accepts either string table names or *TableRef instances with optional aliases
From(from ...any) SelectQueryBuilder
// Type-safe JOIN methods with JoinFilter (v2.0+)
// Each accepts either string table name or *TableRef instance with optional alias
JoinOn(table any, filter JoinFilter) SelectQueryBuilder
LeftJoinOn(table any, filter JoinFilter) SelectQueryBuilder
RightJoinOn(table any, filter JoinFilter) SelectQueryBuilder
InnerJoinOn(table any, filter JoinFilter) SelectQueryBuilder
CrossJoinOn(table any) SelectQueryBuilder
GroupBy(groupBys ...any) SelectQueryBuilder
Having(pred any, rest ...any) SelectQueryBuilder
OrderBy(orderBys ...any) SelectQueryBuilder
Limit(limit uint64) SelectQueryBuilder
Offset(offset uint64) SelectQueryBuilder
Paginate(limit, offset uint64) SelectQueryBuilder
// Composable WHERE clause
Where(filter Filter) SelectQueryBuilder
// SQL generation
ToSQL() (sql string, args []any, err error)
}
SelectQueryBuilder defines the interface for enhanced SELECT query building with type safety. This interface extends basic squirrel.SelectBuilder functionality with additional methods for composable filters, JOIN operations, and vendor-specific query features.
type Statement ¶
type Statement interface {
// Query execution
Query(ctx context.Context, args ...any) (*sql.Rows, error)
QueryRow(ctx context.Context, args ...any) Row
Exec(ctx context.Context, args ...any) (sql.Result, error)
// Statement management
Close() error
}
Statement defines the interface for prepared statements
type TableRef ¶ added in v0.14.2
type TableRef struct {
// contains filtered or unexported fields
}
TableRef represents a table reference with optional alias for SQL queries. Use the Table() function to create instances.
Example:
Table("customers").As("c") // Table with alias
Table("users") // Table without alias
func Table ¶ added in v0.14.2
Table creates a new table reference. Panics if name is empty (fail fast). Call As() to add an alias, or use directly for tables without aliases.
Example:
qb.Select("*").From(Table("users").As("u"))
func (*TableRef) Alias ¶ added in v0.14.2
Alias returns the table alias, or empty string if no alias.
func (*TableRef) As ¶ added in v0.14.2
As sets the alias for this table reference. Panics if alias is empty (fail fast). Returns the same TableRef for method chaining.
Example:
Table("customers").As("c")
type Tx ¶
type Tx interface {
// Query execution within transaction
Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRow(ctx context.Context, query string, args ...any) Row
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
// Prepared statements within transaction
Prepare(ctx context.Context, query string) (Statement, error)
// Transaction control
Commit() error
Rollback() error
}
Tx defines the interface for database transactions
type UpdateQueryBuilder ¶ added in v0.13.0
type UpdateQueryBuilder interface {
// Data modification
Set(column string, value any) UpdateQueryBuilder
SetMap(clauses map[string]any) UpdateQueryBuilder
// Filtering
Where(filter Filter) UpdateQueryBuilder
// SQL generation
ToSQL() (sql string, args []any, err error)
}
UpdateQueryBuilder defines the interface for UPDATE query building with type-safe filtering. This interface wraps squirrel.UpdateBuilder with Filter API support and vendor-specific quoting.