squirrel2

package module
v0.0.0-...-59718e8 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2025 License: MIT Imports: 12 Imported by: 0

README

My own Squirrel.

I'm starting this fork to add some features I'm missing from Go query builders, like conditional clauses. I've also added the safe-squirrel2 features here because I found then very cool.

Original Squirrel READMED.md.

License

Squirrel is released under the MIT License.

Documentation

Overview

Package squirrel2 provides a fluent SQL generator.

See https://github.com/Masterminds/squirrel2 for examples.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Question is a PlaceholderFormat instance that leaves placeholders as
	// question marks.
	Question = questionFormat{}

	// Dollar is a PlaceholderFormat instance that replaces placeholders with
	// dollar-prefixed positional placeholders (e.g. $1, $2, $3).
	Dollar = dollarFormat{}

	// Colon is a PlaceholderFormat instance that replaces placeholders with
	// colon-prefixed positional placeholders (e.g. :1, :2, :3).
	Colon = colonFormat{}

	// AtP is a PlaceholderFormat instance that replaces placeholders with
	// "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3).
	AtP = atpFormat{}
)
View Source
var ErrNoContextSupport = errors.New("DB does not support Context")

ErrNoContextSupport is returned if a db doesn't support Context.

View Source
var ErrRunnerNotQueryRunner = errors.New("cannot QueryRow; Runner is not a QueryRower")

RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower.

View Source
var ErrRunnerNotSet = errors.New("cannot run; no Runner set (RunWith)")

RunnerNotSet is returned by methods that need a Runner if it isn't set.

View Source
var StatementBuilder = StatementBuilderType()

StatementBuilder is a parent builder for other builders, e.g. SelectBuilder.

Functions

func Alias

func Alias(expr Sqlizer, alias safeString) aliasExpr

Alias allows to define alias for column in SelectBuilder. Useful when column is defined as complex expression like IF or CASE Ex:

.Column(Alias(caseStmt, "case_column"))

func Case

func Case(what ...Sqlizer) caseBuilder

Case returns a new CaseBuilder "what" represents optional case value

func CaseBuilder

func CaseBuilder() caseBuilder

func ConcatExpr

func ConcatExpr(parts ...Sqlizer) concatExpr

ConcatExpr builds an expression by concatenating strings and other expressions.

Ex:

name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName)
ConcatExpr("COALESCE(full_name,", name_expr, ")")

func DangerouslyCastDynamicStringToSafeString deprecated

func DangerouslyCastDynamicStringToSafeString(val string) safeString

DangerouslyCastDynamicStringToSafeString converts a dynamic string to a safeString for use in the methods/types of this package. This should be used with _extreme_ caution, as it will lead to SQL injection if the string has not been properly sanitized.

Deprecated: This function is dangerous and should not be used unless you are _very_ sure you know what you're doing.

func DebugSqlizer

func DebugSqlizer(s Sqlizer) string

DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed

If ToSql returns an error, the result of this method will look like: "[ToSql error: %s]" or "[DebugSqlizer error: %s]"

IMPORTANT: As its name suggests, this function should only be used for debugging. While the string result *might* be valid SQL, this function does not try very hard to ensure it. Additionally, executing the output of this function with any untrusted user input is certainly insecure.

func Delete

func Delete(from safeString) deleteBuilder

Delete returns a new DeleteBuilder with the given table name.

See DeleteBuilder.Table.

func DeleteBuilder

func DeleteBuilder(b statementBuilderType) deleteBuilder

func ExecContextWith

func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error)

ExecContextWith ExecContexts the SQL returned by s with db.

func ExecWith

func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error)

ExecWith Execs the SQL returned by s with db.

func Insert

func Insert(into safeString) insertBuilder

Insert returns a new InsertBuilder with the given table name.

See InsertBuilder.Into.

func InsertBuilder

func InsertBuilder(b statementBuilderType) insertBuilder

func JoinSafeStrings

func JoinSafeStrings(sep safeString, vals ...safeString) safeString

JoinSafeStrings joins multiple 'safeString's into a single 'safeString'

func Placeholders

func Placeholders(count int) safeString

Placeholders returns a string with count ? placeholders joined with commas.

func QueryContextWith

func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error)

QueryContextWith QueryContexts the SQL returned by s with db.

func QueryWith

func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error)

QueryWith Querys the SQL returned by s with db.

func Replace

func Replace(into safeString) insertBuilder

Replace returns a new InsertBuilder with the statement keyword set to "REPLACE" and with the given table name.

See InsertBuilder.Into.

func SafeString

func SafeString(val safeString) safeString

SafeString allows callers to explicitly declare a 'safeString'

func SafeStrings

func SafeStrings(vals ...safeString) []safeString

SafeString allows callers to explicitly declare multiple 'safeString's

func Select

func Select(columns ...safeString) selectBuilder

Select returns a new SelectBuilder, optionally setting some result columns.

See SelectBuilder.Columns.

func SelectBuilder

func SelectBuilder(b statementBuilderType) selectBuilder

func SelectIf

func SelectIf(columns ...valIf[safeString]) selectBuilder

SelectIf returns a new SelectBuilder, optionally setting some result columns, only with columns with true boolean value.

See SelectBuilder.Columns.

func StatementBuilderType

func StatementBuilderType() statementBuilderType

func Update

func Update(table safeString) updateBuilder

Update returns a new UpdateBuilder with the given table name.

See UpdateBuilder.Table.

func UpdateBuilder

func UpdateBuilder(b statementBuilderType) updateBuilder

func ValIf

func ValIf[T any](value T, include bool) valIf[T]

Types

type And

type And conj

And conjunction Sqlizers

func (And) ToSql

func (a And) ToSql() (string, []interface{}, error)

type BaseRunner

type BaseRunner interface {
	Execer
	Queryer
}

BaseRunner groups the Execer and Queryer interfaces.

type DBProxy

type DBProxy interface {
	Execer
	Queryer
	QueryRower
	Preparer
}

DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces.

type DBProxyBeginner

type DBProxyBeginner interface {
	DBProxy
	Begin() (*sql.Tx, error)
}

func NewStmtCacheProxy

func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner

type DBProxyContext

type DBProxyContext interface {
	Execer
	Queryer
	QueryRower
	PreparerContext
}

DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces.

func NewStmtCacher

func NewStmtCacher(prep PreparerContext) DBProxyContext

NewStmtCacher is deprecated

Use NewStmtCache instead

type Eq

type Eq map[safeString]interface{}

Eq is syntactic sugar for use with Where/Having/Set methods.

Example
Select("id", "created", "first_name").From("users").Where(Eq{
	"company": 20,
})

func (Eq) ToSql

func (eq Eq) ToSql() (sql string, args []interface{}, err error)

type Execer

type Execer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
}

Execer is the interface that wraps the Exec method.

Exec executes the given query as implemented by database/sql.Exec.

type ExecerContext

type ExecerContext interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

ExecerContext is the interface that wraps the ExecContext method.

Exec executes the given query as implemented by database/sql.ExecContext.

type Gt

type Gt Lt

Gt is syntactic sugar for use with Where/Having/Set methods. Ex:

.Where(Gt{"id": 1}) == "id > 1"

func (Gt) ToSql

func (gt Gt) ToSql() (sql string, args []interface{}, err error)

type GtOrEq

type GtOrEq Lt

GtOrEq is syntactic sugar for use with Where/Having/Set methods. Ex:

.Where(GtOrEq{"id": 1}) == "id >= 1"

func (GtOrEq) ToSql

func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error)

type ILike

type ILike Like

ILike is syntactic sugar for use with ILIKE conditions. Ex:

.Where(ILike{"name": "sq%"})

func (ILike) ToSql

func (ilk ILike) ToSql() (sql string, args []interface{}, err error)

type Like

type Like map[safeString]interface{}

Like is syntactic sugar for use with LIKE conditions. Ex:

.Where(Like{"name": "%irrel"})

func (Like) ToSql

func (lk Like) ToSql() (sql string, args []interface{}, err error)

type Lt

type Lt map[safeString]interface{}

Lt is syntactic sugar for use with Where/Having/Set methods. Ex:

.Where(Lt{"id": 1})

func (Lt) ToSql

func (lt Lt) ToSql() (sql string, args []interface{}, err error)

type LtOrEq

type LtOrEq Lt

LtOrEq is syntactic sugar for use with Where/Having/Set methods. Ex:

.Where(LtOrEq{"id": 1}) == "id <= 1"

func (LtOrEq) ToSql

func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error)

type NotEq

type NotEq Eq

NotEq is syntactic sugar for use with Where/Having/Set methods. Ex:

.Where(NotEq{"id": 1}) == "id <> 1"

func (NotEq) ToSql

func (neq NotEq) ToSql() (sql string, args []interface{}, err error)

type NotILike

type NotILike Like

NotILike is syntactic sugar for use with ILIKE conditions. Ex:

.Where(NotILike{"name": "sq%"})

func (NotILike) ToSql

func (nilk NotILike) ToSql() (sql string, args []interface{}, err error)

type NotLike

type NotLike Like

NotLike is syntactic sugar for use with LIKE conditions. Ex:

.Where(NotLike{"name": "%irrel"})

func (NotLike) ToSql

func (nlk NotLike) ToSql() (sql string, args []interface{}, err error)

type Or

type Or conj

Or conjunction Sqlizers

func (Or) ToSql

func (o Or) ToSql() (string, []interface{}, error)

type PlaceholderFormat

type PlaceholderFormat interface {
	ReplacePlaceholders(sql string) (string, error)
}

PlaceholderFormat is the interface that wraps the ReplacePlaceholders method.

ReplacePlaceholders takes a SQL statement and replaces each question mark placeholder with a (possibly different) SQL placeholder.

type Preparer

type Preparer interface {
	Prepare(query string) (*sql.Stmt, error)
}

Prepareer is the interface that wraps the Prepare method.

Prepare executes the given query as implemented by database/sql.Prepare.

type PreparerContext

type PreparerContext interface {
	Preparer
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

PrepareerContext is the interface that wraps the Prepare and PrepareContext methods.

Prepare executes the given query as implemented by database/sql.Prepare. PrepareContext executes the given query as implemented by database/sql.PrepareContext.

type QueryRower

type QueryRower interface {
	QueryRow(query string, args ...interface{}) RowScanner
}

QueryRower is the interface that wraps the QueryRow method.

QueryRow executes the given query as implemented by database/sql.QueryRow.

type QueryRowerContext

type QueryRowerContext interface {
	QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner
}

QueryRowerContext is the interface that wraps the QueryRowContext method.

QueryRowContext executes the given query as implemented by database/sql.QueryRowContext.

type Queryer

type Queryer interface {
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

Queryer is the interface that wraps the Query method.

Query executes the given query as implemented by database/sql.Query.

type QueryerContext

type QueryerContext interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}

QueryerContext is the interface that wraps the QueryContext method.

QueryContext executes the given query as implemented by database/sql.QueryContext.

type Row

type Row struct {
	RowScanner
	// contains filtered or unexported fields
}

Row wraps database/sql.Row to let squirrel2 return new errors on Scan.

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) error

Scan returns Row.err or calls RowScanner.Scan.

type RowScanner

type RowScanner interface {
	Scan(...interface{}) error
}

RowScanner is the interface that wraps the Scan method.

Scan behaves like database/sql.Row.Scan.

func QueryRowContextWith

func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner

QueryRowContextWith QueryRowContexts the SQL returned by s with db.

func QueryRowWith

func QueryRowWith(db QueryRower, s Sqlizer) RowScanner

QueryRowWith QueryRows the SQL returned by s with db.

type Runner

type Runner interface {
	Execer
	Queryer
	QueryRower
}

Runner groups the Execer, Queryer, and QueryRower interfaces.

func WrapStdSql

func WrapStdSql(stdSql StdSql) Runner

WrapStdSql wraps a type implementing the standard SQL interface with methods that squirrel2 expects.

type RunnerContext

type RunnerContext interface {
	Runner
	QueryerContext
	QueryRowerContext
	ExecerContext
}

RunnerContext groups the Runner interface, along with the Context versions of each of its methods

func WrapStdSqlCtx

func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext

WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context versions of the methods with methods that squirrel2 expects.

type SetMap

type SetMap map[safeString]interface{}

SetMap can be passed to the SetMap function in various builders

type Sqlizer

type Sqlizer interface {
	ToSql() (string, []interface{}, error)
}

Sqlizer is the interface that wraps the ToSql method.

ToSql returns a SQL representation of the Sqlizer, along with a slice of args as passed to e.g. database/sql.Exec. It can also return an error.

func Expr

func Expr(sql safeString, args ...interface{}) Sqlizer

Expr builds an expression from a SQL fragment and arguments.

Ex:

Expr("FROM_UNIXTIME(?)", t)

func ExprIf

func ExprIf(expression Sqlizer, include bool) Sqlizer

ExprIf is a Sqlizer that conditionally wraps an expression.

Ex:

ExprIf(Expr("FROM_UNIXTIME(?)", t), true) == "FROM_UNIXTIME(t)"
ExprIf(Expr("FROM_UNIXTIME(?)", t), false) == ""

type StdSql

type StdSql interface {
	Query(string, ...interface{}) (*sql.Rows, error)
	QueryRow(string, ...interface{}) *sql.Row
	Exec(string, ...interface{}) (sql.Result, error)
}

StdSql encompasses the standard methods of the *sql.DB type, and other types that wrap these methods.

type StdSqlCtx

type StdSqlCtx interface {
	StdSql
	QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
	QueryRowContext(context.Context, string, ...interface{}) *sql.Row
	ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
}

StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context versions of those methods, and other types that wrap these methods.

type StmtCache

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

StmtCache wraps and delegates down to a Preparer type

It also automatically prepares all statements sent to the underlying Preparer calls for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided query as the key. So that it can be automatically re-used.

func NewStmtCache

func NewStmtCache(prep PreparerContext) *StmtCache

NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts.

Stmts are cached based on the string value of their queries.

func (*StmtCache) Clear

func (sc *StmtCache) Clear() (err error)

Clear removes and closes all the currently cached prepared statements

func (*StmtCache) Exec

func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error)

Exec delegates down to the underlying Preparer using a prepared statement

func (*StmtCache) ExecContext

func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error)

ExecContext delegates down to the underlying PreparerContext using a prepared statement

func (*StmtCache) Prepare

func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error)

Prepare delegates down to the underlying Preparer and caches the result using the provided query as a key

func (*StmtCache) PrepareContext

func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

PrepareContext delegates down to the underlying PreparerContext and caches the result using the provided query as a key

func (*StmtCache) Query

func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error)

Query delegates down to the underlying Preparer using a prepared statement

func (*StmtCache) QueryContext

func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)

QueryContext delegates down to the underlying PreparerContext using a prepared statement

func (*StmtCache) QueryRow

func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner

QueryRow delegates down to the underlying Preparer using a prepared statement

func (*StmtCache) QueryRowContext

func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner

QueryRowContext delegates down to the underlying PreparerContext using a prepared statement

Jump to

Keyboard shortcuts

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