sq

package module
v0.0.0-...-7f6cd5c Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2021 License: MIT Imports: 13 Imported by: 0

README

sq

Fluent SQL generator for Go and PostgreSQL.

package main

import (
	"context"
	"log"

	"github.com/silas/sq"
)

func main() {
	ctx := context.Background()
	pool, err := sq.Connect(ctx, "postgresql://postgres:postgres@127.0.0.1:5432/postgres")
	if err != nil {
		log.Fatal(err)
	}

	qb := sq.Select("user").
		From("user").
		Limit(1)

	var user string
	err = pool.Tx(ctx, func(tx sq.Tx) error {
		return tx.QueryRow(ctx, qb).Scan(&user)
	})
	if err != nil {
		log.Fatal(err)
	}

	println(user)
}

This is a fork of sqrl.

NOTE: The API for this library is not yet stable, expect breaking changes.

Documentation

Index

Constants

View Source
const (
	// Class 00 - Successful Completion
	CodeSuccessfulCompletion = "00000"

	// Class 01 - Warning
	CodeWarning                          = "01000"
	CodeDynamicResultSetsReturned        = "0100C"
	CodeImplicitZeroBitPadding           = "01008"
	CodeNullValueEliminatedInSetFunction = "01003"
	CodePrivilegeNotGranted              = "01007"
	CodePrivilegeNotRevoked              = "01006"
	CodeStringDataRightTruncationWarning = "01004"
	CodeDeprecatedFeature                = "01P01"

	// Class 02 - No Data (this is also a warning class per the SQL standard)
	CodeNoData                                = "02000"
	CodeNoAdditionalDynamicResultSetsReturned = "02001"

	// Class 03 - SQL Statement Not Yet Complete
	CodeSQLStatementNotYetComplete = "03000"

	// Class 08 - Connection Exception
	CodeConnectionException                           = "08000"
	CodeConnectionDoesNotExist                        = "08003"
	CodeConnectionFailure                             = "08006"
	CodeSQLClientUnableToEstablishSqlconnection       = "08001"
	CodeSqlserverRejectedEstablishmentOfSqlconnection = "08004"
	CodeTransactionResolutionUnknown                  = "08007"
	CodeProtocolViolation                             = "08P01"

	// Class 09 - Triggered Action Exception
	CodeTriggeredActionException = "09000"

	// Class 0A - Feature Not Supported
	CodeFeatureNotSupported = "0A000"

	// Class 0B - Invalid Transaction Initiation
	CodeInvalidTransactionInitiation = "0B000"

	// Class 0F - Locator Exception
	CodeLocatorException            = "0F000"
	CodeInvalidLocatorSpecification = "0F001"

	// Class 0L - Invalid Grantor
	CodeInvalidGrantor        = "0L000"
	CodeInvalidGrantOperation = "0LP01"

	// Class 0P - Invalid Role Specification
	CodeInvalidRoleSpecification = "0P000"

	// Class 0Z - Diagnostics Exception
	CodeDiagnosticsException                           = "0Z000"
	CodeStackedDiagnosticsAccessedWithoutActiveHandler = "0Z002"

	// Class 20 - Case Not Found
	CodeCaseNotFound = "20000"

	// Class 21 - Cardinality Violation
	CodeCardinalityViolation = "21000"

	// Class 22 - Data Exception
	CodeDataException                         = "22000"
	CodeArraySubscriptError                   = "2202E"
	CodeCharacterNotInRepertoire              = "22021"
	CodeDatetimeFieldOverflow                 = "22008"
	CodeDivisionByZero                        = "22012"
	CodeErrorInAssignment                     = "22005"
	CodeEscapeCharacterConflict               = "2200B"
	CodeIndicatorOverflow                     = "22022"
	CodeIntervalFieldOverflow                 = "22015"
	CodeInvalidArgumentForLogarithm           = "2201E"
	CodeInvalidArgumentForNtileFunction       = "22014"
	CodeInvalidArgumentForNthValueFunction    = "22016"
	CodeInvalidArgumentForPowerFunction       = "2201F"
	CodeInvalidArgumentForWidthBucketFunction = "2201G"
	CodeInvalidCharacterValueForCast          = "22018"
	CodeInvalidDatetimeFormat                 = "22007"
	CodeInvalidEscapeCharacter                = "22019"
	CodeInvalidEscapeOctet                    = "2200D"
	CodeInvalidEscapeSequence                 = "22025"
	CodeNonstandardUseOfEscapeCharacter       = "22P06"
	CodeInvalidIndicatorParameterValue        = "22010"
	CodeInvalidParameterValue                 = "22023"
	CodeInvalidPrecedingOrFollowingSize       = "22013"
	CodeInvalidRegularExpression              = "2201B"
	CodeInvalidRowCountInLimitClause          = "2201W"
	CodeInvalidRowCountInResultOffsetClause   = "2201X"
	CodeInvalidTablesampleArgument            = "2202H"
	CodeInvalidTablesampleRepeat              = "2202G"
	CodeInvalidTimeZoneDisplacementValue      = "22009"
	CodeInvalidUseOfEscapeCharacter           = "2200C"
	CodeMostSpecificTypeMismatch              = "2200G"
	CodeNullValueNotAllowed                   = "22004"
	CodeNullValueNoIndicatorParameter         = "22002"
	CodeNumericValueOutOfRange                = "22003"
	CodeSequenceGeneratorLimitExceeded        = "2200H"
	CodeStringDataLengthMismatch              = "22026"
	CodeStringDataRightTruncation             = "22001"
	CodeSubstringError                        = "22011"
	CodeTrimError                             = "22027"
	CodeUnterminatedCString                   = "22024"
	CodeZeroLengthCharacterString             = "2200F"
	CodeFloatingPointException                = "22P01"
	CodeInvalidTextRepresentation             = "22P02"
	CodeInvalidBinaryRepresentation           = "22P03"
	CodeBadCopyFileFormat                     = "22P04"
	CodeUntranslatableCharacter               = "22P05"
	CodeNotAnXMLDocument                      = "2200L"
	CodeInvalidXMLDocument                    = "2200M"
	CodeInvalidXMLContent                     = "2200N"
	CodeInvalidXMLComment                     = "2200S"
	CodeInvalidXMLProcessingInstruction       = "2200T"
	CodeDuplicateJSONObjectKeyValue           = "22030"
	CodeInvalidJSONText                       = "22032"
	CodeInvalidSQLJSONSubscript               = "22033"
	CodeMoreThanOneSQLJSONItem                = "22034"
	CodeNoSQLJSONItem                         = "22035"
	CodeNonNumericSQLJSONItem                 = "22036"
	CodeNonUniqueKeysInAJSONObject            = "22037"
	CodeSingletonSQLJSONItemRequired          = "22038"
	CodeSQLJSONArrayNotFound                  = "22039"
	CodeSQLJSONMemberNotFound                 = "2203A"
	CodeSQLJSONNumberNotFound                 = "2203B"
	CodeSQLJSONObjectNotFound                 = "2203C"
	CodeTooManyJSONArrayElements              = "2203D"
	CodeTooManyJSONObjectMembers              = "2203E"
	CodeSQLJSONScalarRequired                 = "2203F"

	// Class 23 - Integrity Constraint Violation
	CodeIntegrityConstraintViolation = "23000"
	CodeRestrictViolation            = "23001"
	CodeNotNullViolation             = "23502"
	CodeForeignKeyViolation          = "23503"
	CodeUniqueViolation              = "23505"
	CodeCheckViolation               = "23514"
	CodeExclusionViolation           = "23P01"

	// Class 24 - Invalid Cursor State
	CodeInvalidCursorState = "24000"

	// Class 25 - Invalid Transaction State
	CodeInvalidTransactionState                         = "25000"
	CodeActiveSQLTransaction                            = "25001"
	CodeBranchTransactionAlreadyActive                  = "25002"
	CodeHeldCursorRequiresSameIsolationLevel            = "25008"
	CodeInappropriateAccessModeForBranchTransaction     = "25003"
	CodeInappropriateIsolationLevelForBranchTransaction = "25004"
	CodeNoActiveSQLTransactionForBranchTransaction      = "25005"
	CodeReadOnlySQLTransaction                          = "25006"
	CodeSchemaAndDataStatementMixingNotSupported        = "25007"
	CodeNoActiveSQLTransaction                          = "25P01"
	CodeInFailedSQLTransaction                          = "25P02"
	CodeIdleInTransactionSessionTimeout                 = "25P03"

	// Class 26 - Invalid SQL Statement Name
	CodeInvalidSQLStatementName = "26000"

	// Class 27 - Triggered Data Change Violation
	CodeTriggeredDataChangeViolation = "27000"

	// Class 28 - Invalid Authorization Specification
	CodeInvalidAuthorizationSpecification = "28000"
	CodeInvalidPassword                   = "28P01"

	// Class 2B - Dependent Privilege Descriptors Still Exist
	CodeDependentPrivilegeDescriptorsStillExist = "2B000"
	CodeDependentObjectsStillExist              = "2BP01"

	// Class 2D - Invalid Transaction Termination
	CodeInvalidTransactionTermination = "2D000"

	// Class 2F - SQL Routine Exception
	CodeSQLRoutineException               = "2F000"
	CodeFunctionExecutedNoReturnStatement = "2F005"
	CodeModifyingSQLDataNotPermitted      = "2F002"
	CodeProhibitedSQLStatementAttempted   = "2F003"
	CodeReadingSQLDataNotPermitted        = "2F004"

	// Class 34 - Invalid Cursor Name
	CodeInvalidCursorName = "34000"

	// Class 38 - External Routine Exception
	CodeExternalRoutineException                = "38000"
	CodeExternalContainingSQLNotPermitted       = "38001"
	CodeExternalModifyingSQLDataNotPermitted    = "38002"
	CodeExternalProhibitedSQLStatementAttempted = "38003"
	CodeExternalReadingSQLDataNotPermitted      = "38004"

	// Class 39 - External Routine Invocation Exception
	CodeExternalRoutineInvocationException   = "39000"
	CodeExternalInvalidSqlstateReturned      = "39001"
	CodeExternalNullValueNotAllowed          = "39004"
	CodeExternalTriggerProtocolViolated      = "39P01"
	CodeExternalSRFProtocolViolated          = "39P02"
	CodeExternalEventTriggerProtocolViolated = "39P03"

	// Class 3B - Savepoint Exception
	CodeSavepointException            = "3B000"
	CodeInvalidSavepointSpecification = "3B001"

	// Class 3D - Invalid Catalog Name
	CodeInvalidCatalogName = "3D000"

	// Class 3F - Invalid Schema Name
	CodeInvalidSchemaName = "3F000"

	// Class 40 - Transaction Rollback
	CodeTransactionRollback                     = "40000"
	CodeTransactionIntegrityConstraintViolation = "40002"
	CodeSerializationFailure                    = "40001"
	CodeStatementCompletionUnknown              = "40003"
	CodeDeadlockDetected                        = "40P01"

	// Class 42 - Syntax Error or Access Rule Violation
	CodeSyntaxErrorOrAccessRuleViolation   = "42000"
	CodeSyntaxError                        = "42601"
	CodeInsufficientPrivilege              = "42501"
	CodeCannotCoerce                       = "42846"
	CodeGroupingError                      = "42803"
	CodeWindowingError                     = "42P20"
	CodeInvalidRecursion                   = "42P19"
	CodeInvalidForeignKey                  = "42830"
	CodeInvalidName                        = "42602"
	CodeNameTooLong                        = "42622"
	CodeReservedName                       = "42939"
	CodeDatatypeMismatch                   = "42804"
	CodeIndeterminateDatatype              = "42P18"
	CodeCollationMismatch                  = "42P21"
	CodeIndeterminateCollation             = "42P22"
	CodeWrongObjectType                    = "42809"
	CodeGeneratedAlways                    = "428C9"
	CodeUndefinedColumn                    = "42703"
	CodeUndefinedFunction                  = "42883"
	CodeUndefinedTable                     = "42P01"
	CodeUndefinedParameter                 = "42P02"
	CodeUndefinedObject                    = "42704"
	CodeDuplicateColumn                    = "42701"
	CodeDuplicateCursor                    = "42P03"
	CodeDuplicateDatabase                  = "42P04"
	CodeDuplicateFunction                  = "42723"
	CodeDuplicatePreparedStatement         = "42P05"
	CodeDuplicateSchema                    = "42P06"
	CodeDuplicateTable                     = "42P07"
	CodeDuplicateAlias                     = "42712"
	CodeDuplicateObject                    = "42710"
	CodeAmbiguousColumn                    = "42702"
	CodeAmbiguousFunction                  = "42725"
	CodeAmbiguousParameter                 = "42P08"
	CodeAmbiguousAlias                     = "42P09"
	CodeInvalidColumnReference             = "42P10"
	CodeInvalidColumnDefinition            = "42611"
	CodeInvalidCursorDefinition            = "42P11"
	CodeInvalidDatabaseDefinition          = "42P12"
	CodeInvalidFunctionDefinition          = "42P13"
	CodeInvalidPreparedStatementDefinition = "42P14"
	CodeInvalidSchemaDefinition            = "42P15"
	CodeInvalidTableDefinition             = "42P16"
	CodeInvalidObjectDefinition            = "42P17"

	// Class 44 - WITH CHECK OPTION Violation
	CodeWithCheckOptionViolation = "44000"

	// Class 53 - Insufficient Resources
	CodeInsufficientResources      = "53000"
	CodeDiskFull                   = "53100"
	CodeOutOfMemory                = "53200"
	CodeTooManyConnections         = "53300"
	CodeConfigurationLimitExceeded = "53400"

	// Class 54 - Program Limit Exceeded
	CodeProgramLimitExceeded = "54000"
	CodeStatementTooComplex  = "54001"
	CodeTooManyColumns       = "54011"
	CodeTooManyArguments     = "54023"

	// Class 55 - Object Not In Prerequisite State
	CodeObjectNotInPrerequisiteState = "55000"
	CodeObjectInUse                  = "55006"
	CodeCantChangeRuntimeParam       = "55P02"
	CodeLockNotAvailable             = "55P03"
	CodeUnsafeNewEnumValueUsage      = "55P04"

	// Class 57 - Operator Intervention
	CodeOperatorIntervention = "57000"
	CodeQueryCanceled        = "57014"
	CodeAdminShutdown        = "57P01"
	CodeCrashShutdown        = "57P02"
	CodeCannotConnectNow     = "57P03"
	CodeDatabaseDropped      = "57P04"

	// Class 58 - System Error (errors external to PostgreSQL itself)
	CodeSystemError   = "58000"
	CodeIOError       = "58030"
	CodeUndefinedFile = "58P01"
	CodeDuplicateFile = "58P02"

	// Class 72 - Snapshot Failure
	CodeSnapshotTooOld = "72000"

	// Class F0 - Configuration File Error
	CodeConfigFileError = "F0000"
	CodeLockFileExists  = "F0001"

	// Class HV - Foreign Data Wrapper Error (SQL/MED)
	CodeFDWError                             = "HV000"
	CodeFDWColumnNameNotFound                = "HV005"
	CodeFDWDynamicParameterValueNeeded       = "HV002"
	CodeFDWFunctionSequenceError             = "HV010"
	CodeFDWInconsistentDescriptorInformation = "HV021"
	CodeFDWInvalidAttributeValue             = "HV024"
	CodeFDWInvalidColumnName                 = "HV007"
	CodeFDWInvalidColumnNumber               = "HV008"
	CodeFDWInvalidDataType                   = "HV004"
	CodeFDWInvalidDataTypeDescriptors        = "HV006"
	CodeFDWInvalidDescriptorFieldIdentifier  = "HV091"
	CodeFDWInvalidHandle                     = "HV00B"
	CodeFDWInvalidOptionIndex                = "HV00C"
	CodeFDWInvalidOptionName                 = "HV00D"
	CodeFDWInvalidStringLengthOrBufferLength = "HV090"
	CodeFDWInvalidStringFormat               = "HV00A"
	CodeFDWInvalidUseOfNullPointer           = "HV009"
	CodeFDWTooManyHandles                    = "HV014"
	CodeFDWOutOfMemory                       = "HV001"
	CodeFDWNoSchemas                         = "HV00P"
	CodeFDWOptionNameNotFound                = "HV00J"
	CodeFDWReplyHandle                       = "HV00K"
	CodeFDWSchemaNotFound                    = "HV00Q"
	CodeFDWTableNotFound                     = "HV00R"
	CodeFDWUnableToCreateExecution           = "HV00L"
	CodeFDWUnableToCreateReply               = "HV00M"
	CodeFDWUnableToEstablishConnection       = "HV00N"
	CodePLPGSQLError                         = "P0000"
	CodeRaiseException                       = "P0001"
	CodeNoDataFound                          = "P0002"
	CodeTooManyRows                          = "P0003"
	CodeAssertFailure                        = "P0004"
	CodeInternalError                        = "XX000"
	CodeDataCorrupted                        = "XX001"
	CodeIndexCorrupted                       = "XX002"
)

Variables

View Source
var (
	ErrNoRows           = pgx.ErrNoRows
	ErrTxClosed         = pgx.ErrTxClosed
	ErrTxCommitRollback = pgx.ErrTxCommitRollback
)

Functions

func IsError

func IsError(err error, code string) bool

Types

type And

type And conj

And is syntactic sugar that glues where/having parts with AND clause.

.Where(And{Expr("a > ?", 15), Expr("b < ?", 20), Expr("c is TRUE")})

func (And) ToSQL

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

ToSQL builds the query into a SQL string and bound args.

type CaseBuilder

type CaseBuilder interface {
	// When adds "WHEN ... THEN ..." part to CASE construct
	When(when interface{}, then interface{}) CaseBuilder

	// Else sets optional "ELSE ..." part for CASE construct
	Else(expr interface{}) CaseBuilder

	ToSQL() (sqlStr string, args []interface{}, err error)
}

CaseBuilder builds SQL CASE construct which could be used as parts of queries.

func Case

func Case(what ...interface{}) CaseBuilder

Case returns a new CaseBuilder.

type Config

type Config = pgxpool.Config

func ParseConfig

func ParseConfig(connString string) (*Config, error)

type DeleteBuilder

type DeleteBuilder interface {
	// Prefix adds an expression to the beginning of the query.
	Prefix(sql string, args ...interface{}) DeleteBuilder

	// From sets the FROM clause of the query.
	From(from string) DeleteBuilder

	// Where adds WHERE expressions to the query.
	Where(pred interface{}, args ...interface{}) DeleteBuilder

	// OrderBy adds ORDER BY expressions to the query.
	OrderBy(orderBys ...string) DeleteBuilder

	// Limit sets a LIMIT clause on the query.
	Limit(limit uint64) DeleteBuilder

	// Offset sets a OFFSET clause on the query.
	Offset(offset uint64) DeleteBuilder

	// Suffix adds an expression to the end of the query
	Suffix(sql string, args ...interface{}) DeleteBuilder

	// JoinClause adds a join clause to the query.
	JoinClause(join string) DeleteBuilder

	// Join adds a JOIN clause to the query.
	Join(join string) DeleteBuilder

	// LeftJoin adds a LEFT JOIN clause to the query.
	LeftJoin(join string) DeleteBuilder

	// RightJoin adds a RIGHT JOIN clause to the query.
	RightJoin(join string) DeleteBuilder

	ToSQL() (sqlStr string, args []interface{}, err error)
}

DeleteBuilder builds SQL DELETE statements.

func Delete

func Delete(table string) DeleteBuilder

Delete returns a new DeleteBuilder for given table names.

See DeleteBuilder.From.

func NewDeleteBuilder

func NewDeleteBuilder() DeleteBuilder

NewDeleteBuilder creates new instance of DeleteBuilder

type Eq

type Eq map[string]interface{}

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

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

func (Eq) ToSQL

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

type Executor

type Executor interface {
	Exec(ctx context.Context, qb StatementBuilder) (Result, error)
	Query(ctx context.Context, qb StatementBuilder) (Rows, error)
	QueryRow(ctx context.Context, qb StatementBuilder) Row
}

type Gt

type Gt Lt

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

.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.

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

func (GtOrEq) ToSQL

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

type InsertBuilder

type InsertBuilder interface {
	// Prefix adds an expression to the beginning of the query.
	Prefix(sql string, args ...interface{}) InsertBuilder

	// Options adds keyword options before the INTO clause of the query.
	Options(options ...string) InsertBuilder

	// Into sets the INTO clause of the query.
	Into(into string) InsertBuilder

	// Columns adds insert columns to the query.
	Columns(columns ...string) InsertBuilder

	// Values adds a single row's values to the query.
	Values(values ...interface{}) InsertBuilder

	// Suffix adds an expression to the end of the query.
	Suffix(sql string, args ...interface{}) InsertBuilder

	// SetMap set columns and values for insert builder from a map of column name and value
	// note that it will reset all previous columns and values was set if any.
	SetMap(clauses map[string]interface{}) InsertBuilder

	ToSQL() (sqlStr string, args []interface{}, err error)
}

InsertBuilder builds SQL INSERT statements.

func Insert

func Insert(table string) InsertBuilder

Insert returns a new InsertBuilder with the given table name.

See InsertBuilder.Into.

func NewInsertBuilder

func NewInsertBuilder() InsertBuilder

NewInsertBuilder creates new instance of InsertBuilder

type Lt

type Lt map[string]interface{}

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

.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.

.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.

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

func (NotEq) ToSQL

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

type Or

type Or conj

Or is syntactic sugar that glues where/having parts with OR clause

.Where(And{Expr("a > ?", 15), Expr("b < ?", 20), Expr("c is TRUE")})

func (Or) ToSQL

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

type Pool

type Pool interface {
	Executor

	Tx(ctx context.Context, fn func(tx Tx) error) error
	Close()
}

func Connect

func Connect(ctx context.Context, connString string) (Pool, error)

func ConnectConfig

func ConnectConfig(ctx context.Context, config *Config) (Pool, error)

func NewPool

func NewPool(p *pgxpool.Pool) Pool

type Result

type Result = pgconn.CommandTag

type Row

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

type Rows

type Rows interface {
	Row
	Next() bool
	Close()
}

type SelectBuilder

type SelectBuilder interface {
	// Prefix adds an expression to the beginning of the query.
	Prefix(sql string, args ...interface{}) SelectBuilder

	// Distinct adds a DISTINCT clause to the query.
	Distinct() SelectBuilder

	// Columns adds result columns to the query.
	Columns(columns ...string) SelectBuilder

	// Column adds a result column to the query.
	// Unlike Columns, Column accepts args which will be bound to placeholders in
	// the columns string.
	//
	//   Column("IF(col IN ("+placeholders(3)+"), 1, 0) as col", 1, 2, 3)
	Column(column interface{}, args ...interface{}) SelectBuilder

	// From sets the FROM clause of the query.
	From(from string) SelectBuilder

	// JoinClause adds a join clause to the query.
	JoinClause(join string, args ...interface{}) SelectBuilder

	// Join adds a JOIN clause to the query.
	Join(join string, args ...interface{}) SelectBuilder

	// LeftJoin adds a LEFT JOIN clause to the query.
	LeftJoin(join string, args ...interface{}) SelectBuilder

	// RightJoin adds a RIGHT JOIN clause to the query.
	RightJoin(join string, args ...interface{}) SelectBuilder

	// Where adds an expression to the WHERE clause of the query.
	//
	// Expressions are ANDed together in the generated SQL.
	//
	// Where accepts several types for its pred argument:
	//
	// nil OR "" - ignored.
	//
	// string - SQL expression.
	// If the expression has SQL placeholders then a set of arguments must be passed
	// as well, one for each placeholder.
	//
	// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is
	// transformed into an expression like "<key> = ?", with the corresponding value
	// bound to the placeholder. If the value is nil, the expression will be "<key>
	// IS NULL". If the value is an array or slice, the expression will be "<key> IN
	// (?,?,...)", with one placeholder for each item in the value. These expressions
	// are ANDed together.
	//
	// Where will panic if pred isn't any of the above types.
	Where(pred interface{}, args ...interface{}) SelectBuilder

	// GroupBy adds GROUP BY expressions to the query.
	GroupBy(groupBys ...string) SelectBuilder

	// Having adds an expression to the HAVING clause of the query.
	//
	// See Where.
	Having(pred interface{}, rest ...interface{}) SelectBuilder

	// OrderBy adds ORDER BY expressions to the query.
	OrderBy(orderBys ...string) SelectBuilder

	// Limit sets a LIMIT clause on the query.
	Limit(limit uint64) SelectBuilder

	// Offset sets a OFFSET clause on the query.
	Offset(offset uint64) SelectBuilder

	// Suffix adds an expression to the end of the query.
	Suffix(sql string, args ...interface{}) SelectBuilder

	// Union add UNION to the query.
	Union() SelectBuilder

	// UnionAll add UNION ALL to the query.
	UnionAll() SelectBuilder

	ToSQL() (sqlStr string, args []interface{}, err error)
}

SelectBuilder builds SQL SELECT statements.

func NewSelectBuilder

func NewSelectBuilder() SelectBuilder

NewSelectBuilder creates new instance of SelectBuilder

func Select

func Select(columns ...string) SelectBuilder

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

See SelectBuilder.Columns.

type StatementBuilder

type StatementBuilder interface {
	ToSQL() (string, []interface{}, error)
}

StatementBuilder is the interface that wraps the ToSQL method.

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

func Alias

func Alias(expr StatementBuilder, alias string) StatementBuilder

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

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

func Expr

func Expr(sql string, args ...interface{}) StatementBuilder

Expr builds value expressions for InsertBuilder and UpdateBuilder.

.Values(Expr("FROM_UNIXTIME(?)", t))

type Tx

type Tx interface {
	Executor
}

type UpdateBuilder

type UpdateBuilder interface {
	// Prefix adds an expression to the beginning of the query.
	Prefix(sql string, args ...interface{}) UpdateBuilder

	// Table sets the table to be updated.
	Table(table string) UpdateBuilder

	// Set adds SET clauses to the query.
	Set(column string, value interface{}) UpdateBuilder

	// SetMap is a convenience method which calls .Set for each key/value pair in clauses.
	SetMap(clauses map[string]interface{}) UpdateBuilder

	// From adds FROM clause to the query.
	From(from string) UpdateBuilder

	// Where adds WHERE expressions to the query.
	//
	// See SelectBuilder.Where for more information.
	Where(pred interface{}, args ...interface{}) UpdateBuilder

	// OrderBy adds ORDER BY expressions to the query.
	OrderBy(orderBys ...string) UpdateBuilder

	// Limit sets a LIMIT clause on the query.
	Limit(limit uint64) UpdateBuilder

	// Offset sets a OFFSET clause on the query.
	Offset(offset uint64) UpdateBuilder

	// Suffix adds an expression to the end of the query.
	Suffix(sql string, args ...interface{}) UpdateBuilder

	ToSQL() (sqlStr string, args []interface{}, err error)
}

UpdateBuilder builds SQL UPDATE statements.

func NewUpdateBuilder

func NewUpdateBuilder() UpdateBuilder

NewUpdateBuilder creates new instance of UpdateBuilder.

func Update

func Update(table string) UpdateBuilder

Update returns a new UpdateBuilder with the given table name.

See UpdateBuilder.Table.

type WhereBuilder

type WhereBuilder interface {
	// Where adds WHERE expressions to the query.
	//
	// See SelectBuilder.Where for more information.
	Where(pred interface{}, args ...interface{}) WhereBuilder

	// Select returns a SelectBuilder for this WhereBuilder.
	Select(columns ...string) SelectBuilder

	// Update returns a UpdateBuilder for this WhereBuilder.
	Update(table string) UpdateBuilder

	// Delete returns a DeleteBuilder for this WhereBuilder.
	Delete(table string) DeleteBuilder
}

WhereBuilder builds SQL where statements.

func NewWhereBuilder

func NewWhereBuilder() WhereBuilder

NewWhereBuilder creates new instance of UpdateBuilder.

func Where

func Where(pred interface{}, args ...interface{}) WhereBuilder

Where returns a new WhereBuilder.

type WithBuilder

type WithBuilder interface {
	// With adds a new common table expression to the query.
	With(name string, field ...string) WithBuilder

	// Recursive adds RECURSIVE to the WITH clause.
	Recursive() WithBuilder

	// As sets the AS part of the common table expression.
	As(b StatementBuilder) WithBuilder

	// Select returns the SelectBuilder for the parent query.
	Select(columns ...string) SelectBuilder
}

WithBuilder builds SQL WITH statements.

func NewWithBuilder

func NewWithBuilder() WithBuilder

NewWithBuilder creates new instance of WithBuilder.

func With

func With(name string, field ...string) WithBuilder

With returns a new WithBuilder.

Jump to

Keyboard shortcuts

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