query

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2023 License: MIT Imports: 7 Imported by: 0

README

query

Go Reference

Query implements SQL query builder for Go. The aim is to provide fast and simple interface to database functions without need to write SQL code at all.

Main features:

  • supporting SELECT (and SELECT COUNT() as subset of SELECT), INSERT, UPDATE and DELETE queries;
  • supporting fields conditions to use in SELECT/UPDATE/DELETE queries;
  • supporting field and table names aliasing;
  • supporting tables JOIN's keeping Golang syntax as close to SQL as possible;
  • provides string types to wrap table and field names constants allows to keep all definitions in single place and avoid mistypings;
  • generated queries could use either '?' or '$N' placeholders depending on your needs;
  • supporting conditionals building over single or several joined tables using complex conditions
  • allows to extend standard conditions library with new condition implementations types when required
  • all query builders are immutable which allows to keep original complex query definitions and easily derive new ones

Here is open source alternatives on 09.09.2022:

  • sqlf - A fast SQL query builder for Go, last v1.3.0 fired 05.01.2022, switches versions ~ once per 3 month
  • dbr - provides additions to Go's database/sql for super fast performance and convenience. Last version v2.7.3 launched 24.12.2021, switches versions ~ once per 6 month.
  • Squirrel - simple and fluent SQL queries builder from composable parts. Last version v1.5.3 launched 20.05.2022. Development complete, bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here.
  • SQLR - fat-free version of squirrel - fluent SQL generator for Go. Actually a merge of squirrel and dbr ideas. No published versions at all, last commit on 28.07.2021. Looks stale.
  • Gocu - An expressive SQL builder and executor. Last version v9.18.0 launched 17.10.2021, before this v9.18.0 about a version per 2 months.

Not really a builders but are the SQL helpers and ORM packages:

  • GORP - provides a simple way to marshal Go structs to and from SQL databases. It uses the database/sql package, and should work with any compliant database/sql driver
  • GORM - fantastic ORM library for Golang, aims to be developer friendly.

Documentation

Overview

Package query provides database queries build helpers.

It helps to simplify query building for relation database CRUD operations, especially in cases when used fields set will be known only in runtime, not on developments stage.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Error indicates different database errors.
	Error = errors.New("query")
)

Functions

This section is empty.

Types

type BaseBuilder

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

BaseBuilder defines a base data structure useful for any queries type.

func (BaseBuilder) Operation

func (b BaseBuilder) Operation() Operation

Operation returns SQL operation of query. If not set DoSelect used by default.

type BaseCondition

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

BaseCondition implements a part of Condition interface. It includes JoinType() to include into real conditions implementations.

func (BaseCondition) IsNegate

func (condition BaseCondition) IsNegate() bool

IsNegate returns true if condition negated GroupAND false otherwise.

func (BaseCondition) Join

func (condition BaseCondition) Join(newJoinType JoinType) BaseCondition

Join returns a copy of BaseCondition having JoinType set to specified value.

func (BaseCondition) JoinType

func (condition BaseCondition) JoinType() JoinType

JoinType defines JoinType to combine condition with previous.

func (BaseCondition) Negate

func (condition BaseCondition) Negate(newNegateIndicator bool) BaseCondition

Negate returns a copy of BaseCondition having IsNegate set to specified value.

func (BaseCondition) RenderJoin

func (condition BaseCondition) RenderJoin(isFirst bool) (result string)

RenderJoin renders join logical operation GroupAND negate suffix to place before condition. If isFirst is true, logical operation is omitted. If negate is false, negate affix is omitted. In case isFirst is true && negate is false result will be empty string. Any other cases result always starts GroupAND finishes with space.

func (BaseCondition) RenderNegate

func (condition BaseCondition) RenderNegate() string

RenderNegate returns either empty string GroupOR "NOT " prefix if condition negated. Used by real condition implementations.

type BaseSelectBuilder

type BaseSelectBuilder struct {
	BaseBuilder
	// contains filtered or unexported fields
}

BaseSelectBuilder helps to build table queries. It does not provide pagination or ordering itself but contains helper methods to generate SelectListBuilder or SelectOneBuilder. It also provides method Count() to generate SelectCountBuilder.

func SelectFrom

func SelectFrom[T TableNameParameter](tableNameProvider T) BaseSelectBuilder

SelectFrom makes a new BaseSelectBuilder instance. Takes string, TableName or TableIdent to build BaseSelectBuilder over it.

func (BaseSelectBuilder) BuildQueryAndParams

func (query BaseSelectBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams generates sql query string with desired parameters set. If query generation failed returns empty query and parameters set or non-nil error.

func (BaseSelectBuilder) Count

func (query BaseSelectBuilder) Count() CountBuilder

Count creates an CountBuilder using parameters of this SelectManyBuilder.

func (BaseSelectBuilder) Delete

func (query BaseSelectBuilder) Delete() DeleteBuilder

Delete generates table DeleteBuilder. Note generated DeleteBuilder will receive only base TableIdent to generate update on it.

func (BaseSelectBuilder) FieldDefinitions

func (query BaseSelectBuilder) FieldDefinitions() (res []FieldDefinition)

FieldDefinitions returns a copy of attached FieldDefinition list.

func (BaseSelectBuilder) Fields

func (query BaseSelectBuilder) Fields(fieldSpecs ...FieldDefinition) (updated BaseSelectBuilder)

Fields returns a copy of SelectManyBuilder having mustField list to retrieve updated with a list of specified FieldDefinition`s.

func (BaseSelectBuilder) FullJoin

func (query BaseSelectBuilder) FullJoin(rightTable TableIdent) IncompleteSelectJoin

FullJoin generates intermediate IncompleteSelectJoin instance for FullJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, FullJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (BaseSelectBuilder) InnerJoin

func (query BaseSelectBuilder) InnerJoin(rightTable TableIdent) IncompleteSelectJoin

InnerJoin generates intermediate IncompleteSelectJoin instance for InnerJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, InnerJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (BaseSelectBuilder) InsertInto

func (query BaseSelectBuilder) InsertInto(insertValues ...FieldValue) InsertBuilder

InsertInto generates SQL INSERT query builder using stored table name. Insert values are optional and could be set later with InsertBuilder.Values. Note generated InsertInto will receive only base TableIdent to generate insert into it.

func (BaseSelectBuilder) Join

func (query BaseSelectBuilder) Join(rightTable TableIdent, joinType TableJoinType) IncompleteSelectJoin

Join generates intermediate IncompleteSelectJoin instance. Takes TableName to join and TableJoinType constant defining required join type to produce. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (BaseSelectBuilder) LeftJoin

func (query BaseSelectBuilder) LeftJoin(rightTable TableIdent) IncompleteSelectJoin

LeftJoin generates intermediate IncompleteSelectJoin instance for LeftJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, LeftJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (BaseSelectBuilder) Limit

func (query BaseSelectBuilder) Limit(limit int) SelectManyBuilder

Limit makes a SelectManyBuilder instance from BaseSelectBuilder setting required records limit to specified value.

func (BaseSelectBuilder) Many

func (query BaseSelectBuilder) Many() SelectManyBuilder

Many makes a SelectManyBuilder instance from BaseSelectBuilder setting ordering and pagination to its default values. See also Offset, Limit and OrderBy.

func (BaseSelectBuilder) Offset

func (query BaseSelectBuilder) Offset(offset uint) SelectManyBuilder

Offset makes SelectManyBuilder instance with offset set to specified value.

func (BaseSelectBuilder) OrderBy

func (query BaseSelectBuilder) OrderBy(orderByFields ...FieldSorting) SelectManyBuilder

OrderBy makes a SelectManyBuilder instance from BaseSelectBuilder setting ordering to specified value.

func (BaseSelectBuilder) Render

func (query BaseSelectBuilder) Render(parametersCount int) (sql string)

func (BaseSelectBuilder) RenderFrom

func (query BaseSelectBuilder) RenderFrom() (fromClause string)

func (BaseSelectBuilder) RenderSQL

func (query BaseSelectBuilder) RenderSQL() (sql string)

func (BaseSelectBuilder) RightJoin

func (query BaseSelectBuilder) RightJoin(rightTable TableIdent) IncompleteSelectJoin

RightJoin generates intermediate IncompleteSelectJoin instance for RightJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, RightJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (BaseSelectBuilder) Single

func (query BaseSelectBuilder) Single() SelectSingleBuilder

Single makes a SelectSingleBuilder instance from BaseSelectBuilder.

func (BaseSelectBuilder) String

func (query BaseSelectBuilder) String() string

String returns a string representation of BaseSelectBuilder.

func (BaseSelectBuilder) TableName

func (query BaseSelectBuilder) TableName() TableName

TableName returns table name to fetch records from.

func (BaseSelectBuilder) Update

func (query BaseSelectBuilder) Update(values ...FieldValue) UpdateBuilder

Update generates table UpdateBuilder. Note generated UpdateBuilder will receive only base TableIdent to generate update on it.

func (BaseSelectBuilder) Values

func (query BaseSelectBuilder) Values() (params []any)

func (BaseSelectBuilder) Where

func (query BaseSelectBuilder) Where(fieldConditions ...Condition) (updated BaseSelectBuilder)

Where adds fields conditions GroupAND returns modified SelectManyBuilder. If any conditions are already added, adds new conditions group joined with logical AND.

type ClauseFromRenderer

type ClauseFromRenderer interface {
	// RenderFrom returns string representation of table name or tables join with possible tables aliases.
	RenderFrom() string
}

ClauseFromRenderer defines interface to use instead of direct table name in SQL FROM clause.

type Condition

type Condition interface {
	ValuesProvider
	CountingClauseRenderer
	RawClauseRenderer

	// JoinType defines JoinType to combine condition with previous.
	JoinType() JoinType

	// RenderJoin renders join logical operation GroupAND negate suffix to place before condition.
	RenderJoin(isFirst bool) (result string)

	// IsNegate returns true if condition negated GroupAND false otherwise.
	IsNegate() bool

	// Join returns a copy of Condition having JoinType set to specified value.
	Join(newJoinType JoinType) Condition

	// Negate returns a copy of Condition having IsNegate set to specified value.
	Negate(newNegate bool) Condition

	// RenderNegate renders negate prefix if condition is market as negated.
	// It should return single "NOT" with no spaces around if negated GroupAND empty string otherwise.
	RenderNegate() string

	// And generates new condition which true on all conditions met.
	And(conditions ...Condition) Condition

	// Or generates new condition group which true on either initial condition is true GroupOR all of additional are true.
	Or(conditions ...Condition) Condition

	// FieldName returns field name of condition applied to.
	FieldName() FieldName

	// ApplyFieldSpec makes a copy of Condition with updated FieldDefinition if fieldName match.
	// If FieldName is not matched it does nothing.
	ApplyFieldSpec(spec FieldDefinition) Condition

	// ApplyFieldTable makes a copy of Condition with updated FieldDefinition table name.
	ApplyFieldTable(table TableName) Condition
}

func And

func And(condition Condition, additionalConditions ...Condition) Condition

And makes condition or condition group with logical join AND. If single condition is specified, its join type is changed to LogicalAND.

func Contains

func Contains(fieldName FieldName, value string) Condition

Contains generates Condition to compare string like fields using LIKE '%value%'. See IContains condition generator to make case-independent `contains` comparison.

func EqualTo

func EqualTo(fieldName FieldName, value interface{}) Condition

EqualTo generates Condition for any field type equalTo to value.

func GreaterOrEqual

func GreaterOrEqual(fieldName FieldName, value interface{}) Condition

GreaterOrEqual generates Condition for any field type matching rows having field values greater or equal to specified value.

func GreaterThan

func GreaterThan(fieldName FieldName, value interface{}) Condition

GreaterThan generates Condition for any field type to match records having field values greater than specified.

func IContains

func IContains(fieldName FieldName, value string) Condition

IContains generates Condition to compare string using case-independent SQL operator ILIKE. It generates comparison of ILIKE '%value%' form. See Contains condition generator to make case-aware contains comparison.

func In

func In(fieldName FieldName, value interface{}) Condition

In generates Condition for any field type to match records having field values in than specified.

func IsNull

func IsNull(fieldName FieldName) Condition

IsNull generates Condition to select rows where specified field name value IS NULL'.

func Less

func Less(fieldName FieldName, value interface{}) Condition

Less generates Condition for any field type to match records having field values less than specified.

func LessOrEqual

func LessOrEqual(fieldName FieldName, value interface{}) Condition

LessOrEqual generates Condition for any field type matching rows having field values less or equal to specified.

func Not

func Not(condition Condition) Condition

Not sets negate flag to single condition or group.

func Or

func Or(condition Condition, additionalConditions ...Condition) Condition

Or makes condition or condition group with logical join OR. If single condition is specified, its join type is changed to LogicalOR.

type CountBuilder

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

CountBuilder helps to build count queries. It utilizes BaseSelectBuilder methods

func Count

func Count(query BaseSelectBuilder, fieldToCount ...FieldName) (countBuilder CountBuilder)

Count prepares SQL SELECT COUNT query builder. Takes BaseSelectBuilder instance and optional mustField name to count over it. If no mustField name specified default '*' will used. Returns CountBuilder instance.

func (CountBuilder) BuildQueryAndParams

func (query CountBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams generates sql query string with desired parameters set. If query generation failed returns empty query and parameters set or non-nil error.

func (CountBuilder) RenderFrom

func (query CountBuilder) RenderFrom() string

RenderFrom returns string representation of table name or tables join with possible tables aliases. Implements ClauseFromRenderer.

type Counter

type Counter interface {
	CountCtx(ctx context.Context, helper CountBuilder) (rowsCount int, err error)
}

Counter requires implementation could fetch total records count using prepared query CountBuilder.

type CountingClauseRenderer

type CountingClauseRenderer interface {
	// Render renders SQL clause or its part with respect of parameters count added previously.
	// Takes existed parameters count (0 means no parameters are defined yet).
	// Implementation should render parameters substitutions starting from number = paramNum+1.
	// It expected substitutions are rendered using "$<number>" notation, as expected by postgresql driver.
	// Values result should contain the same values count as substitutions used in clause.
	// If implementation is condition and condition is negated, implementation SHOULD write negate prefix itself.
	Render(parametersCount int) (sql string)
}

CountingClauseRenderer requires implementations could render its SQL clause part using numbered parameters.

type DeleteBuilder

type DeleteBuilder struct {
	BaseBuilder
	// contains filtered or unexported fields
}

DeleteBuilder helps to build SQL DELETE queries.

func Delete

func Delete[T TableNameParameter](tableNameProvider T) DeleteBuilder

Delete generates table deleter using predefined table helper. Takes table name (of string, TableName or TableIdent types). Use DeleteBuilder.Where and DeleteBuilder.Set to finalize DeleteBuilder configuration.

func (DeleteBuilder) BuildQueryAndParams

func (updater DeleteBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams returns query string and params to fill in SQL DELETE query string. If query build failed returns non-nil error.

func (DeleteBuilder) RenderFrom

func (updater DeleteBuilder) RenderFrom() string

RenderFrom returns string representation of table name or tables join with possible tables aliases.

func (DeleteBuilder) TableName

func (updater DeleteBuilder) TableName() TableName

TableName returns table name to delete.

func (DeleteBuilder) Where

func (updater DeleteBuilder) Where(fieldConditions ...Condition) DeleteBuilder

Where adds fields conditions GroupAND returns modified DeleteBuilder.

type Deleter

type Deleter interface {
	DeleteManyCtx(ctx context.Context, updateParams DeleteBuilder) (affectedRows int, err error)
}

Deleter requires implementation provides records delete method using prepared DeleteBuilder.

type FetchCounter

type FetchCounter interface {
	FetchCountCtx(ctx context.Context, queryParams SelectManyBuilder, target interface{}) (totalRows int, err error)
}

FetchCounter requires implementation could fetch records with total records count using prepared query SelectManyBuilder.

type Fetcher

type Fetcher interface {
	FetchCtx(ctx context.Context, queryParams SelectManyBuilder, target interface{}) (err error)
}

Fetcher requires implementation could fetch records from underline database using prepared query SelectManyBuilder.

type FetcherCounter

type FetcherCounter interface {
	Fetcher
	Counter
}

FetcherCounter provides both FetchCtx and CountCtx methods.

type FieldDefinition

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

FieldDefinition defines field definition data structure. It contains field name, field table name and field name alias. Used as field name wrapper in conditions and fields lists of queries.

func Field

func Field[T FieldNameParameter](spec T) (field FieldDefinition)

Field creates new mustField identification. It can use several forms to define not only mustField name but a table name, an alias or both: 1) identification string with no dots and spaces defines mustField name with empty (unknown) table name and alias; 2) "<table>.<name>" form defines both mustField name and mustField table name; 3) "<name> as <alias>" form defines both mustField name and its alias; 4) "<table>.<name> as <alias>" defines all mustField name, table name and alias. Panics if no format matched. Use FieldOrError constructor if fieldName format is not guaranteed to suit one of formats above.

func FieldOrError

func FieldOrError[T FieldNameParameter](fieldName T) (field *FieldDefinition, err error)

FieldOrError creates new FieldDefinition. Takes string, FieldName of FieldDefinition instance. If FieldDefinition passed as argument it returns immediately with pointer to specified argument and nil error. If FieldName or string argument provided it parsed using rules below. 1) identification string with no dots and spaces defines field name with empty (unknown) table name and alias; 2) "<table>.<name>" form defines both field name and field table name; 3) "<name> as|AS <alias>" form defines both field name and its alias; 4) "<table>.<name> as|AS <alias>" defines all field name, table name and alias. Returns error if no format matched. Use Field constructor if argument fully determined and suits one of formats above. Note setting alias to same value as field name gives empty alias if table name is empty.

func (FieldDefinition) Alias

func (fieldIdent FieldDefinition) Alias() FieldName

Alias returns mustField name alias. Same as FieldName until As not called.

func (FieldDefinition) As

func (fieldIdent FieldDefinition) As(alias FieldName) FieldDefinition

As returns a copy of FieldDefinition with mustField name alias set to specified fieldName. Note setting alias to same name as field name renders FieldDefinition without alias unless table name is not empty.

func (FieldDefinition) FieldName

func (fieldIdent FieldDefinition) FieldName() FieldName

FieldName returns mustField name as wrapped FieldName string type.

func (FieldDefinition) Of

func (fieldIdent FieldDefinition) Of(tableName TableName) FieldDefinition

Of returns a copy of FieldDefinition with table name set to specified baseTable.

func (FieldDefinition) RenderField

func (fieldIdent FieldDefinition) RenderField() string

RenderField returns a mustField identification to use in SQL queries in conditional or sorting clauses.

func (FieldDefinition) RenderSpec

func (fieldIdent FieldDefinition) RenderSpec() string

RenderSpec returns a field specification to use in SQL queries as a fetch items enumeration.

func (FieldDefinition) RenderTableSpec

func (fieldIdent FieldDefinition) RenderTableSpec() string

RenderTableSpec returns a field name in form <table_name>.<field_name> as string value. Used to render SQL JOIN conditional clauses. If value of FieldName type required use TableFieldName instead.

func (FieldDefinition) TableFieldName

func (fieldIdent FieldDefinition) TableFieldName() FieldName

TableFieldName returns a field name in form <table_name>.<field_name> as FieldName value. If value of string type required use RenderTableSpec instead.

func (FieldDefinition) TableName

func (fieldIdent FieldDefinition) TableName() TableName

TableName returns table name of mustField pointed by FieldDefinition.

func (FieldDefinition) Value

func (fieldIdent FieldDefinition) Value(value any) FieldValue

Value generates FieldValue item using current field definition. Note FieldValue keeps its own copy of field definition taken in constructor, so any further changes to FieldDefinition will not affect generated FieldValue. To sync changes made in FieldDefinition after FieldValue generated, use FieldValue.ApplyFieldSpec.

type FieldName

type FieldName string

FieldName wraps string type to provide conditional clauses shortcuts.

func UniqFieldNames

func UniqFieldNames(a []FieldName) []FieldName

UniqFieldNames returns unique FieldName set from supplied FieldName slice.

func (FieldName) Contains

func (fn FieldName) Contains(value string) Condition

Contains generates field contains text Condition. Wraps Contains(string(*FieldName), value).

func (FieldName) EqualTo

func (fn FieldName) EqualTo(value interface{}) Condition

EqualTo generates field equal to value Condition. Wraps EqualTo(string(*FieldName), value).

func (FieldName) Field

func (fn FieldName) Field() FieldDefinition

Field returns FieldDefinition build from FieldName to use in queries. Shorthand to Field((FieldName).fn).

func (FieldName) IContains

func (fn FieldName) IContains(value string) Condition

IContains generates field lookup confition comparing filed value using case-independent comparison. Wraps IContains(string(*FieldName), value).

func (FieldName) In

func (fn FieldName) In(value interface{}) Condition

In generates condition to select values where field value in supplied list. Wraps In(string(*FieldName), value).

func (FieldName) IsNull

func (fn FieldName) IsNull() Condition

IsNull generates `field is null` Condition. Wraps IsNull(string(*FieldName), value).

func (FieldName) String

func (fn FieldName) String() string

String returns string value of FieldName.

func (FieldName) Validate

func (fn FieldName) Validate() error

Validate validates field name. Returns error if field name has unexpected characters or empty.

func (FieldName) Value

func (fn FieldName) Value(value interface{}) FieldValue

Value generates field value. If value is ValueProvider uses ValueProvider.DatabaseValue() instead if direct value.

type FieldNameParameter

type FieldNameParameter interface {
	string | FieldName | FieldDefinition
}

FieldNameParameter allows use a string, FieldName or FieldDefinition in cases where FieldName or FieldDefinition required.

type FieldSorting

type FieldSorting struct {
	FieldDefinition
	// contains filtered or unexported fields
}

FieldSorting groups together field definition GroupAND SortDirection to build ORDER BY clause in SQL SELECT requests.

func ASC

func ASC(fieldName FieldName) FieldSorting

ASC generates new FieldSorting to build ordering clause with Ascending order by specified field name. Note invalid field name leads to panic. Use FieldName.Validate before build ordering when taking field name from insecure environment. To choose ordering direction programmatically use OrderBy constructor instead.

func DESC

func DESC(fieldName FieldName) FieldSorting

DESC generates new FieldSorting to build ordering clause with Descending order by specified field name. Use FieldName.Validate before build ordering when taking field name from insecure environment.

func OrderBy

func OrderBy(fieldName FieldName, direction ...SortDirection) FieldSorting

OrderBy creates FieldSorting instance using field name. If optional direction specified it should be either Ascending or Descending, default is Ascending. When ordering is known during development use ASC or DESC constructors instead. Panics if unexpected order direction requested or field name to order is invalid.

func (FieldSorting) ApplyFieldSpec

func (o FieldSorting) ApplyFieldSpec(spec FieldDefinition) FieldSorting

ApplyFieldSpec returns a copy of FieldSorting item with FieldDefinition updated if field name matches. If mustField names of original FieldSorting item and argument are differs simply returns a copy of original FieldSorting.

func (FieldSorting) Direction

func (o FieldSorting) Direction() SortDirection

Direction returns current sorting direction set.

func (FieldSorting) Render

func (o FieldSorting) Render() string

Render makes an ORDER BY string.

type FieldValue

type FieldValue struct {
	FieldDefinition
	// contains filtered or unexported fields
}

FieldValue joins field name with its value. Used both for conditions build and for update tables clause generation.

func NewFieldValue

func NewFieldValue(fieldName FieldName, fieldValue interface{}) *FieldValue

NewFieldValue creates new FieldValue having specified field name and value.

func (FieldValue) ApplyFieldSpec

func (fieldValue FieldValue) ApplyFieldSpec(spec FieldDefinition) FieldValue

ApplyFieldSpec makes a copy of FieldValue with updated FieldDefinition on when mustField name matched. If field name is not matched it simply returns a copy of original FieldValue.

func (FieldValue) ApplyFieldTable

func (fieldValue FieldValue) ApplyFieldTable(table TableName) FieldValue

ApplyFieldTable makes a copy of FieldValue with updated FieldDefinition table name. Implements Condition.

func (FieldValue) Values

func (fieldValue FieldValue) Values() (result []interface{})

Values returns a slice of interface{} containing single field value.

type Fields

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

Fields handles list of fields to build SQL SELECT clause.

func NewFields

func NewFields(args ...any) Fields

NewFields makes new fields list. Takes a slice of strings, FieldName or FieldDefinition. Any unexpected type argument will cause an error.

func (Fields) FieldDefinitions

func (query Fields) FieldDefinitions() (res []FieldDefinition)

FieldDefinitions returns attached FieldDefinition list copy.

func (Fields) FieldList

func (query Fields) FieldList() string

FieldList returns spec list string with their possible aliases to build select query.

func (Fields) Fields

func (query Fields) Fields(fieldSpecs ...FieldDefinition) (updated Fields)

Fields returns a copy of Fields having mustField list to retrieve updated with a list of specified FieldDefinition`s.

func (Fields) Len

func (query Fields) Len() int

Len returns a length or fields added to Fields. Zero length means no fields explicitly defined and '*' will used instead.

func (Fields) String

func (query Fields) String() string

String returns a string representation of Fields.

type Getter

type Getter interface {
	GetCtx(ctx context.Context, queryParams SelectSingleBuilder, target interface{}) (err error)
}

Getter requires implementation could get single record from underline database using prepared query SelectManyBuilder.

type Group

type Group struct {
	BaseCondition
	// contains filtered or unexported fields
}

Group implements conditions grouping.

func NewGroup

func NewGroup(joinType JoinType, conditions ...Condition) Group

NewGroup makes a group of conditions with default external join AND. All conditions inside group joined with requested joinType.

func (Group) And

func (conditionsGroup Group) And(conditions ...Condition) Condition

And adds a new condition group into current. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical AND operator.

func (Group) ApplyFieldSpec

func (conditionsGroup Group) ApplyFieldSpec(spec FieldDefinition) Condition

ApplyFieldSpec makes a copy of Group with updated FieldDefinition on each child when field name matched. Implements Condition.

func (Group) ApplyFieldTable

func (conditionsGroup Group) ApplyFieldTable(table TableName) Condition

ApplyFieldTable makes a copy of Condition with updated FieldDefinition table name. Implements Condition.

func (Group) FieldName

func (conditionsGroup Group) FieldName() FieldName

FieldName returns empty string. Implements Condition.

func (Group) GroupAND

func (conditionsGroup Group) GroupAND(conditions ...Condition) Group

GroupAND adds a new condition group into current. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical AND operator. Returns new group containing required condition set.

func (Group) GroupOR

func (conditionsGroup Group) GroupOR(conditions ...Condition) Group

GroupOR creates a new condition group. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical OR operator. Returns new group containing required condition set. Used internally to manage groups on externally called Or.

func (Group) Join

func (conditionsGroup Group) Join(newJoinType JoinType) Condition

Join returns a copy of Group having JoinType set to specified value.

func (Group) Negate

func (conditionsGroup Group) Negate(newNegateIndicator bool) Condition

Negate returns a copy of BaseCondition having IsNegate set to specified value.

func (Group) Or

func (conditionsGroup Group) Or(conditions ...Condition) Condition

Or creates a new condition group. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical OR operator.

func (Group) Render

func (conditionsGroup Group) Render(parametersCount int) (sql string)

Render renders SQL SELECT clause part for current group. Takes existed parameters number (0 means no parameters are defined yet) Note Render renders group without brackets itself if called directly. Any child conditions groups are enclosed into brackets internally.

func (Group) RenderSQL

func (conditionsGroup Group) RenderSQL() (sql string)

RenderSQL renders SQL clause or its part. Implementation should render parameters substitutions using standard sql "?"(question) character.

func (Group) Values

func (conditionsGroup Group) Values() (values []interface{})

Values returns a set of values of grouped conditions.

func (Group) WithBrackets

func (conditionsGroup Group) WithBrackets() Group

WithBrackets creates new group having same conditions but required to enclose conditions into brackets.

type IncompleteSelectJoin

type IncompleteSelectJoin interface {
	// On finalises SQL JOIN definition adding left and right tables fields onto JOIN ... ON clause.
	// Note both left and right FieldDefinition's required to contain table name.
	// Returns updated BaseSelectBuilder instance.
	On(leftField FieldDefinition, rightField FieldDefinition) (updated BaseSelectBuilder)
}

IncompleteSelectJoin items is generated in BaseSelectBuilder join generation functions such as SelectFromTableBuilder.Join, BaseSelectBuilder.InnerJoin, SelectFromTableBuilder.LeftJoin, BaseSelectBuilder.RightJoin or BaseSelectBuilder.FullJoin. It provides single method On required to finalize JOIN clause builder and return to BaseSelectBuilder instance.

type IncompleteSelectManyJoiner

type IncompleteSelectManyJoiner interface {
	// On finalises SQL JOIN definition adding left and right tables fields onto JOIN ... ON clause.
	// Note both left and right FieldDefinition's required to contain table name.
	// Returns updated SelectManyBuilder instance.
	On(leftField FieldDefinition, rightField FieldDefinition) (updated SelectManyBuilder)
}

IncompleteSelectManyJoiner items is generated in SelectManyBuilder join generation functions such as SelectFromTableBuilder.Join, SelectManyBuilder.InnerJoin, SelectManyBuilder.LeftJoin, SelectManyBuilder.RightJoin or SelectManyBuilder.FullJoin. It provides single method On required to finalize JOIN clause builder and return to SelectManyBuilder instance. See also IncompleteSelectJoin interface for serve joins on BaseSelectBuilder.

type IncompleteSelectSingleJoiner

type IncompleteSelectSingleJoiner interface {
	// On finalises SQL JOIN definition adding left and right tables fields onto JOIN ... ON clause.
	// Note both left and right FieldDefinition's required to contain table name.
	// Returns updated SelectSingleBuilder instance.
	On(leftField FieldDefinition, rightField FieldDefinition) (updated SelectSingleBuilder)
}

IncompleteSelectSingleJoiner items is generated in SelectSingleBuilder join generation functions such as SelectSingleBuilder.Join, SelectSingleBuilder.InnerJoin, SelectSingleBuilder.LeftJoin, SelectSingleBuilder.RightJoin or SelectSingleBuilder.FullJoin. It provides single method By required to finalize JOIN clause builder and return to SelectSingleBuilder instance. See also IncompleteSelectJoin interface for serve joins on BaseSelectBuilder.

type InsertBuilder

type InsertBuilder struct {
	BaseBuilder
	// contains filtered or unexported fields
}

InsertBuilder helps to build SQL INSERT queries.

func InsertInto

func InsertInto[T TableNameParameter](tableNameProvider T) InsertBuilder

InsertInto generates InsertBuilder. Takes string table name, TableName or TableIdent. Use InsertBuilder.Values to finalize InsertBuilder configuration.

func (InsertBuilder) BuildQueryAndParams

func (inserter InsertBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams generates SQL INSERT query based on the set values. Returns SQL INSERT query string, parameters to fill placeholders in driver. If any errors occurs returns that error.

func (InsertBuilder) RenderFrom

func (inserter InsertBuilder) RenderFrom() string

RenderFrom returns string representation of table name or tables join with possible tables aliases.

func (InsertBuilder) SetValues

func (inserter InsertBuilder) SetValues() []FieldValue

SetValues returns a copy of fields values attached to use in create query.

func (InsertBuilder) TableName

func (inserter InsertBuilder) TableName() TableName

TableName returns table name to insert data into.

func (InsertBuilder) Values

func (inserter InsertBuilder) Values(values ...FieldValue) InsertBuilder

Values generates new InsertBuilder having additional field values to build insert query parameters. Can be called multiple times to set as many field values as required.

type Inserter

type Inserter interface {
	InsertOneCtx(ctx context.Context, updateParams InsertBuilder) (err error)
}

Inserter interface defines field condition methods. Inserter requires implementation provides single record insert method using prepared InsertBuilder.

type JoinCondition

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

JoinCondition defines data structure to store fields parameters used in table join. Could be created with JoinFields. Not intended to use directly but only as a step of TableJoiner definition.

func JoinFields

func JoinFields(fromField FieldDefinition, toField FieldDefinition) JoinCondition

JoinFields makes JoinCondition parameters to render SQL JOIN condition clause. NOTE both FieldDefinition argument MUST already have table name attached.

func (JoinCondition) FullJoin

func (joinCondition JoinCondition) FullJoin() TableJoiner

FullJoin generates FullJoin TableJoiner. Shorthand to Using(FullJoin).

func (JoinCondition) InnerJoin

func (joinCondition JoinCondition) InnerJoin() TableJoiner

InnerJoin generates InnerJoin TableJoiner. Shorthand to Using(InnerJoin).

func (JoinCondition) LeftJoin

func (joinCondition JoinCondition) LeftJoin() TableJoiner

LeftJoin generates LeftJoin TableJoiner. Shorthand to Using(LeftJoin).

func (JoinCondition) Render

func (joinCondition JoinCondition) Render() string

Render renders SQL JOIN condition clause.

func (JoinCondition) RightJoin

func (joinCondition JoinCondition) RightJoin() TableJoiner

RightJoin generates RightJoin TableJoiner. Shorthand to Using(RightJoin).

func (JoinCondition) Using

func (joinCondition JoinCondition) Using(joinType TableJoinType) TableJoiner

Using transforms JoinCondition into TableJoiner. Takes TableJoinType to use. Returns TableJoiner having tables set from JoinCondition fields, specified TableJoinType and JoinCondition itself.

type JoinType

type JoinType string

JoinType defines conditions join variants.

const (
	// LogicalAND defines logical AND operator to join conditions.
	LogicalAND JoinType = "AND"

	// LogicalOR defines logical OR operator to join conditions.
	LogicalOR JoinType = "OR"
)

func (JoinType) Join

func (joinType JoinType) Join(conditions ...Condition) (result Condition)

Join wraps specified condition to combine with previous conditions with logical operation specified by JoinType. Does the same as And() but in method of JoinType.

func (JoinType) SetToAll

func (joinType JoinType) SetToAll(conditions ...Condition) (result []Condition)

SetToAll returns supplied list with join type set to current in every list element.

func (JoinType) String

func (joinType JoinType) String() string

String returns string type value of JoinType.

type Limiter

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

Limiter implements query result limiting clause builder and renderer. It encapsulates limit parameter to build a queries with expected result limitation, an offset parameter to use together with limit when building pagination handlers. It also stores received values of any or both of limit and offset internally to return values to parameters substitution when fully constructed SQL query is passed to execution.

func (Limiter) Limit

func (query Limiter) Limit(limit uint) Limiter

Limit returns a copy of Limiter having limit attribute set to specified value. Original Limiter instance remains the same. Set 0 to disable limit in query.

func (Limiter) Offset

func (query Limiter) Offset(offset uint) Limiter

Offset returns a copy of Limiter having offset attribute set to specified value. Original Limiter instance remains the same.

func (Limiter) Render

func (query Limiter) Render(paramNum int) (sql string)

Render renders Limiter provided SQL clause using numbered parameters. Takes existed parameters count (0 means no parameters are defined yet). Renders parameters substitutions starting from paramNum+1 using "$<number>" notation. Implements CountingClauseRenderer.

func (Limiter) RenderSQL

func (query Limiter) RenderSQL() (sql string)

RenderSQL renders offset and limit clauses using default sql substitution with "?"(question) character. Implements RawClauseRenderer.

func (Limiter) Values

func (query Limiter) Values() (params []any)

Values returns a set of Limiter values to substitute in SQL query generated using RenderSQL or Render methods. If either offset or limit attributes is equal to 0 its value is omitted. When both offset and limit are zeroes returns empty slice.

type Operation

type Operation int

Operation defines base query operation type, i.e. SELECT, INSERT, DELETE or UPDATE.

const (
	// DoSelect defines a constant SQL SELECT Operation type.
	DoSelect Operation = iota
	// DoInsert defines a constant SQL INSERT Operation type.
	DoInsert
	// DoUpdate defines a constant SQL UPDATE Operation type.
	DoUpdate
	// DoDelete defines a constant SQL DELETE Operation type.
	DoDelete
)

func (Operation) New

func (op Operation) New() BaseBuilder

New creates new BaseBuilder of desired operation.

func (Operation) String

func (op Operation) String() string

String returns a string representation of SQL query operation. It equals either to "SELECT", "INSERT", "UPDATE" or "DELETE" when valid Operation used. If invalid returns "unknown(<int>)".

type RawClauseRenderer

type RawClauseRenderer interface {
	// RenderSQL renders SQL clause or its part.
	// Implementation should render parameters substitutions using standard sql "?"(question) character.
	// Values result should contain the same values count as substitutions used in clause.
	// If implementation is condition and condition is negated, implementation SHOULD write negate prefix itself.
	RenderSQL() (sql string)
}

RawClauseRenderer requires implementations could render its SQL clause part using default parameters substitution.

type SQLKeyWord

type SQLKeyWord string

func (SQLKeyWord) String

func (kw SQLKeyWord) String() string

String returns string representation of SQLKeyWord.

type SelectManyBuilder

type SelectManyBuilder struct {
	BaseSelectBuilder
	// contains filtered or unexported fields
}

SelectManyBuilder extends BaseSelectBuilder helps to build SQL SELECT queries with ordering, offset and limit.

func SelectManyFrom

func SelectManyFrom[T TableNameParameter](tableNameProvider T) SelectManyBuilder

SelectManyFrom makes a new query SelectManyBuilder instance.

func SelectManyFromBase

func SelectManyFromBase(builder BaseSelectBuilder) SelectManyBuilder

SelectManyFromBase makes a new query SelectManyBuilder instance using supplied BaseSelectBuilder.

func (SelectManyBuilder) BuildQueryAndParams

func (query SelectManyBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams generates sql query string with desired parameters set. If query generation failed returns empty query and parameters set or non-nil error.

func (SelectManyBuilder) Count

func (query SelectManyBuilder) Count() CountBuilder

Count creates an CountBuilder using parameters of this SelectManyBuilder.

func (SelectManyBuilder) Delete

func (query SelectManyBuilder) Delete() DeleteBuilder

Delete generates table DeleteBuilder. Note generated DeleteBuilder will use only base table even if join conditions added to SelectManyBuilder instance.

func (SelectManyBuilder) FieldDefinitions

func (query SelectManyBuilder) FieldDefinitions() (res []FieldDefinition)

FieldDefinitions returns a copy of attached FieldDefinition list.

func (SelectManyBuilder) FieldList

func (query SelectManyBuilder) FieldList() string

FieldList returns spec list string with their possible aliases to build select query.

func (SelectManyBuilder) Fields

func (query SelectManyBuilder) Fields(fieldSpecs ...FieldDefinition) (updated SelectManyBuilder)

Fields returns a copy of SelectManyBuilder having mustField list to retrieve updated with a list of specified FieldDefinition`s. Note all fields should be set one step as Fields call resets mustField added before.

func (SelectManyBuilder) FullJoin

func (query SelectManyBuilder) FullJoin(rightTable TableName) IncompleteSelectManyJoiner

FullJoin generates intermediate IncompleteSelectJoin instance for FullJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, FullJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectManyBuilder) InnerJoin

func (query SelectManyBuilder) InnerJoin(rightTable TableName) IncompleteSelectManyJoiner

InnerJoin generates intermediate IncompleteSelectJoin instance for InnerJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, InnerJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectManyBuilder) Join

func (query SelectManyBuilder) Join(rightTable TableName, joinType TableJoinType) IncompleteSelectManyJoiner

Join generates intermediate IncompleteSelectJoin instance. Takes TableName to join and TableJoinType constant defining required join type to produce. Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectManyBuilder) LeftJoin

func (query SelectManyBuilder) LeftJoin(rightTable TableName) IncompleteSelectManyJoiner

LeftJoin generates intermediate IncompleteSelectJoin instance for LeftJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, LeftJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectManyBuilder) Limit

func (query SelectManyBuilder) Limit(limit int) SelectManyBuilder

Limit sets limit GroupAND returns modified SelectManyBuilder. Values -1 to disable limit in query.

func (SelectManyBuilder) Offset

func (query SelectManyBuilder) Offset(offset uint) SelectManyBuilder

Offset sets offset GroupAND returns modified SelectManyBuilder.

func (SelectManyBuilder) OrderBy

func (query SelectManyBuilder) OrderBy(orderByFields ...FieldSorting) SelectManyBuilder

OrderBy adds ordering by fields GroupAND returns modified SelectManyBuilder.

func (SelectManyBuilder) RenderFrom

func (query SelectManyBuilder) RenderFrom() string

RenderFrom renders a table name or list of tables joins to represent SQL clause FROM contents.

func (SelectManyBuilder) RightJoin

func (query SelectManyBuilder) RightJoin(rightTable TableName) IncompleteSelectManyJoiner

RightJoin generates intermediate IncompleteSelectJoin instance for RightJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, RightJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectManyBuilder) Update

func (query SelectManyBuilder) Update(values ...FieldValue) UpdateBuilder

Update generates table UpdateBuilder. Note generated UpdateBuilder will use only base table even if join conditions added to SelectManyBuilder instance.

func (SelectManyBuilder) Where

func (query SelectManyBuilder) Where(fieldConditions ...Condition) SelectManyBuilder

Where adds fields conditions GroupAND returns modified SelectManyBuilder. If any conditions are already added, adds new conditions group joined with logical AND.

type SelectSingleBuilder

type SelectSingleBuilder struct {
	BaseSelectBuilder
}

SelectSingleBuilder extends BaseSelectBuilder helps to build SQL SELECT queries to receive single row.

func SelectSingleFrom

func SelectSingleFrom[T TableNameParameter](tableNameProvider T) SelectSingleBuilder

SelectSingleFrom makes a new SelectSingleBuilder instance.

func SelectSingleFromBase

func SelectSingleFromBase(builder BaseSelectBuilder) SelectSingleBuilder

SelectSingleFromBase makes a new SelectSingleBuilder instance using supplied BaseSelectBuilder.

func (SelectSingleBuilder) BuildQueryAndParams

func (query SelectSingleBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams generates sql query string with desired parameters set. If query generation failed returns empty query and parameters set or non-nil error.

func (SelectSingleBuilder) FieldDefinitions

func (query SelectSingleBuilder) FieldDefinitions() (res []FieldDefinition)

FieldDefinitions returns a copy of attached FieldDefinition list.

func (SelectSingleBuilder) FieldList

func (query SelectSingleBuilder) FieldList() string

FieldList returns spec list string with their possible aliases to build select query.

func (SelectSingleBuilder) Fields

func (query SelectSingleBuilder) Fields(fieldSpecs ...FieldDefinition) (updated SelectSingleBuilder)

Fields returns a copy of SelectManyBuilder having mustField list to retrieve updated with a list of specified FieldDefinition`s. Note all fields should be set one step as Fields call resets mustField added before.

func (SelectSingleBuilder) FullJoin

func (query SelectSingleBuilder) FullJoin(rightTable TableName) IncompleteSelectSingleJoiner

FullJoin generates intermediate IncompleteSelectJoin instance for FullJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, FullJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectSingleBuilder) InnerJoin

func (query SelectSingleBuilder) InnerJoin(rightTable TableName) IncompleteSelectSingleJoiner

InnerJoin generates intermediate IncompleteSelectJoin instance for InnerJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, InnerJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectSingleBuilder) Join

Join generates intermediate IncompleteSelectJoin instance. Takes TableName to join and TableJoinType constant defining required join type to produce. Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectSingleBuilder) LeftJoin

func (query SelectSingleBuilder) LeftJoin(rightTable TableName) IncompleteSelectSingleJoiner

LeftJoin generates intermediate IncompleteSelectJoin instance for LeftJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, LeftJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectSingleBuilder) RenderFrom

func (query SelectSingleBuilder) RenderFrom() string

RenderFrom renders a table name or list of tables joins to represent SQL clause FROM contents.

func (SelectSingleBuilder) RightJoin

func (query SelectSingleBuilder) RightJoin(rightTable TableName) IncompleteSelectSingleJoiner

RightJoin generates intermediate IncompleteSelectJoin instance for RightJoin type. Takes TableName to join. Shortcut to Join(rightTable TableName, RightJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (SelectSingleBuilder) Update

func (query SelectSingleBuilder) Update(values ...FieldValue) UpdateBuilder

Update generates table UpdateBuilder. Note generated UpdateBuilder will use only base table even if join conditions added to SelectManyBuilder instance.

func (SelectSingleBuilder) Where

func (query SelectSingleBuilder) Where(fieldConditions ...Condition) SelectSingleBuilder

Where adds fields conditions GroupAND returns modified SelectManyBuilder. If any conditions are already added, adds new conditions group joined with logical AND.

type SortDirection

type SortDirection string

SortDirection wraps string type to define ordering directions in SelectManyBuilder.

const (
	// Ascending defines constant value to indicate ascending ordering required.
	Ascending SortDirection = "ASC"

	// Descending defines constant value to indicate descending ordering required.
	Descending SortDirection = "DESC"
)

func (SortDirection) String

func (direction SortDirection) String() string

String returns string value of SortDirection.

type TableIdent

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

TableIdent defines data structure to represent table in SQL queries generated in query package. It encapsulates table name as well as table alias when it required to use. Alias is used only in case it is not empty and stored value is different from stored table name. Difference requirement leads to empty values set to alias in constructors or As result if alias equals to name. Besides TableName provide and As modifier it also provides a convenient method to generate FieldDefinition items. Used both as self-contained item in single-table queries generators and as a part o TableJoiner instances when SQL JOIN queries are required.

func Table

func Table[T TableNameParameter](name T) TableIdent

Table creates new table identification. It can use 2 forms to define not table name or table name with alias: 1) identification string with no spaces defines table name with no alias; 2) "<name> as|AS <alias>" form defines both table name and its alias; 3) "<name> <alias>" form defines both table name and its alias; Panics if no format matched. Use TableOrError constructor if table name format is not guaranteed to suit one of formats above.

func TableOrError

func TableOrError[T TableNameParameter](name T) (*TableIdent, error)

TableOrError creates new table identification. It can use 2 forms to define not table name or table name with alias: 1) identification string with no spaces defines table name with no alias; 2) "<name> as|AS <alias>" form defines both table name and its alias; 3) "<name> <alias>" form defines both table name and its alias; Returns error if no format matched. Use Table constructor if table name fully determined and suits one of formats above. Note setting alias to same value as table name gives empty alias.

func (TableIdent) Alias

func (tableIdent TableIdent) Alias() TableName

Alias returns a table name alias to use in query. Can be empty string.

func (TableIdent) As

func (tableIdent TableIdent) As(alias TableName) (updated TableIdent)

As returns a copy of TableIdent having Alias set to specified value, leaving original TableIdent settings intact. Note setting alias same as table name will set empty alias, see why in TableIdent structure definition description.

func (TableIdent) Count

func (tableIdent TableIdent) Count(filterConditions ...Condition) CountBuilder

Count generates CountBuilder builder. Specified Condition's will be used to filter values.

func (TableIdent) Delete

func (tableIdent TableIdent) Delete(filterConditions ...Condition) DeleteBuilder

Delete generates table updater instance. Use DeleteBuilder.Where to finalize DeleteBuilder instance configuration before use.

func (TableIdent) Field

func (tableIdent TableIdent) Field(name FieldName) FieldDefinition

Field generates new FieldDefinition having table name filled& If TableIdent alias is not empty it used to fill FieldDefinition table name, otherwise TableIdent.TableName will be used. Note TableIdent alias change with As() will not propagate to fields generated before.

func (TableIdent) FullJoin

func (tableIdent TableIdent) FullJoin(rightTable TableIdent) IncompleteSelectJoin

FullJoin generates intermediate IncompleteSelectJoin instance for FullJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, FullJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableIdent) InnerJoin

func (tableIdent TableIdent) InnerJoin(rightTable TableIdent) IncompleteSelectJoin

InnerJoin generates intermediate IncompleteSelectJoin instance for InnerJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, InnerJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableIdent) InsertInto

func (tableIdent TableIdent) InsertInto(insertValues ...FieldValue) InsertBuilder

InsertInto generates InsertBuilder instance. Optional field values to insert could be set right here.

func (TableIdent) Join

func (tableIdent TableIdent) Join(rightTable TableIdent, joinType TableJoinType) IncompleteSelectJoin

Join generates intermediate IncompleteSelectJoin instance. Takes TableName to join and TableJoinType constant defining required join type to produce. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Call IncompleteSelectJoin.On will return BaseSelectBuilder with join builder data finished.

func (TableIdent) LeftJoin

func (tableIdent TableIdent) LeftJoin(rightTable TableIdent) IncompleteSelectJoin

LeftJoin generates intermediate IncompleteSelectJoin instance for LeftJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, LeftJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableIdent) RenderFrom

func (tableIdent TableIdent) RenderFrom() string

RenderFrom render table identification string to fill SQL FROM clause. The result is "<name>" or "<name> AS <alias>". Implements ClauseFromRenderer.

func (TableIdent) RightJoin

func (tableIdent TableIdent) RightJoin(rightTable TableIdent) IncompleteSelectJoin

RightJoin generates intermediate IncompleteSelectJoin instance for RightJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, RightJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableIdent) Select

func (tableIdent TableIdent) Select(filterConditions ...Condition) BaseSelectBuilder

Select generates BaseSelectBuilder. Specified Condition's will be used to filter values. Shorthand to SelectFrom((TableIdent)).Where(filterConditions...)

func (TableIdent) SelectMany

func (tableIdent TableIdent) SelectMany(filterConditions ...Condition) SelectManyBuilder

SelectMany generates table query helper to fetch many values. Specified Condition's will be used to filter values. Shorthand to SelectManyFrom((TableIdent)).Where(filterConditions...)

func (TableIdent) SelectOne

func (tableIdent TableIdent) SelectOne(filterConditions ...Condition) SelectSingleBuilder

SelectOne generates table query helper to fetch single row. Specified Condition's will be used to filter values. Shorthand to SelectSingleFrom((TableIdent)).Where(filterConditions...)

func (TableIdent) TableName

func (tableIdent TableIdent) TableName() TableName

TableName returns a table name as defined in database.

func (TableIdent) Update

func (tableIdent TableIdent) Update(updateValues ...FieldValue) UpdateBuilder

Update generates table updater instance. Use UpdateBuilder.Where to finalize UpdateBuilder instance configuration before use.

type TableJoinType

type TableJoinType int

TableJoinType defines table join type. See InnerJoin, LeftJoin, RightJoin and FullJoin constants.

const (
	// InnerJoin defines constant to indicate (INNER) JOIN returning records that have matching values in both tables.
	InnerJoin TableJoinType = iota

	// LeftJoin defines constant to indicate LEFT (OUTER) JOIN returning all records from the left table,
	// and the matched records from the right table.
	LeftJoin

	// RightJoin defines constant to indicate RIGHT (OUTER) JOIN returning from the right table,
	// and the matched records from the left table.
	RightJoin

	// FullJoin defines constant to indicate FULL (OUTER) JOIN returning all records
	// when there is a match in either left or right table.
	FullJoin
)

func (TableJoinType) By

func (join TableJoinType) By(leftField FieldDefinition, rightField FieldDefinition) TableJoiner

By generates TableJoiner built as TableJoinType by specified FieldDefinition`s.

func (TableJoinType) String

func (join TableJoinType) String() string

String returns string representation of TableJoinType value. Implements fmt.Stringer. Used in queries builder.

func (TableJoinType) Tables

func (join TableJoinType) Tables(leftTable TableIdent, rightTable TableIdent) IncompleteSelectJoin

Tables generates IncompleteSelectJoin instance built using leftTable BaseBuilder, right table and empty join condition. It should be finalized with IncompleteSelectJoin.On to get BaseSelectBuilder.

type TableJoiner

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

TableJoiner defines a table join definition data structure. It stores internally join type, right table and join conditions.

func NewTableJoiner

func NewTableJoiner(right TableIdent, joinType TableJoinType, on JoinCondition) TableJoiner

NewTableJoiner creates new table joiner.

func (TableJoiner) By

func (tableJoiner TableJoiner) By(leftTableField FieldDefinition, rightTableField FieldDefinition) TableJoiner

By returns a TableJoiner having (re-)defined which fields are using to join tables.

func (TableJoiner) JoinCondition

func (tableJoiner TableJoiner) JoinCondition() JoinCondition

JoinCondition returns tables JoinCondition.

func (TableJoiner) JoinType

func (tableJoiner TableJoiner) JoinType() TableJoinType

JoinType returns TableJoinType.

func (TableJoiner) RenderFrom

func (tableJoiner TableJoiner) RenderFrom() string

RenderFrom returns SQL FROM clause filled with required tables.

type TableName

type TableName string

TableName wraps string to identify table names.

func (TableName) Delete

func (tableName TableName) Delete(filterConditions ...Condition) DeleteBuilder

Delete generates DeleteBuilder instance. Use DeleteBuilder.Where to finalize DeleteBuilder instance configuration before use.

func (TableName) Field

func (tableName TableName) Field(fieldName FieldName) FieldDefinition

Field generates a FieldDefinition instance having TableName set. It's a shorthand for Field(fieldName).Of(baseTable).

func (TableName) FullJoin

func (tableName TableName) FullJoin(rightTable TableIdent) IncompleteSelectJoin

FullJoin generates intermediate IncompleteSelectJoin instance for FullJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, FullJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableName) Ident

func (tableName TableName) Ident() TableIdent

Ident generates a TableIdent instance from a TableName. See also TableOrError and Table constructors.

func (TableName) InnerJoin

func (tableName TableName) InnerJoin(rightTable TableIdent) IncompleteSelectJoin

InnerJoin generates intermediate IncompleteSelectJoin instance for InnerJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, InnerJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableName) InsertInto

func (tableName TableName) InsertInto(insertValues ...FieldValue) InsertBuilder

InsertInto generates table inserter instance.

func (TableName) Join

func (tableName TableName) Join(rightTable TableIdent, joinType TableJoinType) IncompleteSelectJoin

Join generates intermediate IncompleteSelectJoin instance. Takes TableName to join and TableJoinType constant defining required join type to produce. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Call IncompleteSelectJoin.On will return BaseSelectBuilder with join builder data finished.

func (TableName) LeftJoin

func (tableName TableName) LeftJoin(rightTable TableIdent) IncompleteSelectJoin

LeftJoin generates intermediate IncompleteSelectJoin instance for LeftJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, LeftJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableName) RenderFrom

func (tableName TableName) RenderFrom() string

RenderFrom returns TableName string value. Implements ClauseFromRenderer. Returns a string like "<tableName>".

func (TableName) RightJoin

func (tableName TableName) RightJoin(rightTable TableIdent) IncompleteSelectJoin

RightJoin generates intermediate IncompleteSelectJoin instance for RightJoin type. Takes right table name or ident to join. Panics if rightTable is not instance of string, TableName or TableIdent types. Shortcut to Join(rightTable TableName, RightJoin). Call IncompleteSelectJoin.On will return updated BaseSelectBuilder with join builder data finished.

func (TableName) Select

func (tableName TableName) Select(filterConditions ...Condition) BaseSelectBuilder

Select generates BaseSelectBuilder helper. Condition's will be used to filter values if specified. To get SelectSingleBuilder or SelectManyBuilder directly use SelectSingleFrom or SelectManyFrom instead.

func (TableName) SelectMany

func (tableName TableName) SelectMany(filterConditions ...Condition) SelectManyBuilder

SelectMany generates SelectManyBuilder query helper to fetch many values at once. Condition's will be used to filter values if specified. Shorthand to SelectManyFrom((TableName)).Where(filterConditions...)

func (TableName) SelectOne

func (tableName TableName) SelectOne(filterConditions ...Condition) SelectSingleBuilder

SelectOne generates table query helper to fetch single value. Condition's will be used to filter values if specified. Shorthand to SelectSingleFrom((TableName)).Where(filterConditions...).

func (TableName) String

func (tableName TableName) String() string

String returns table name as string.

func (TableName) Update

func (tableName TableName) Update(updateValues ...FieldValue) UpdateBuilder

Update generates UpdateBuilder instance. Use UpdateBuilder.Where to finalize UpdateBuilder instance configuration before use.

type TableNameParameter

type TableNameParameter interface {
	string | TableName | TableIdent
}

TableNameParameter allows use a string, TableName or TableIdent in cases where TableName or TableIdent required.

type TableNameProvider

type TableNameProvider interface {
	TableName() TableName
}

TableNameProvider requires instances could provide used table name.

type UpdateBuilder

type UpdateBuilder struct {
	BaseBuilder
	// contains filtered or unexported fields
}

UpdateBuilder helps to build SQL UPDATE queries.

func Update

func Update[T TableNameParameter](tableNameProvider T) UpdateBuilder

Update generates table updater using predefined table helper. Takes table name (of string, TableName or TableIdent types). Use UpdateBuilder.Where and UpdateBuilder.Set to finalize UpdateBuilder configuration.

func (UpdateBuilder) BuildQueryAndParams

func (updater UpdateBuilder) BuildQueryAndParams() (sql string, params []interface{}, err error)

BuildQueryAndParams returns query string and params to fill in SQL UPDATE query string. If query build failed returns non-nil error.

func (UpdateBuilder) RenderFrom

func (updater UpdateBuilder) RenderFrom() string

RenderFrom returns string representation of table name or tables join with possible tables aliases.

func (UpdateBuilder) Set

func (updater UpdateBuilder) Set(values ...FieldValue) UpdateBuilder

Set generates new UpdateBuilder having extended fields to update array. Can be called multiple times to set as many field values as required.

func (UpdateBuilder) SetValues

func (updater UpdateBuilder) SetValues() []FieldValue

SetValues returns a copy of fields to update.

func (UpdateBuilder) TableName

func (updater UpdateBuilder) TableName() TableName

TableName returns table name to update.

func (UpdateBuilder) Where

func (updater UpdateBuilder) Where(fieldConditions ...Condition) UpdateBuilder

Where adds fields conditions GroupAND returns modified UpdateBuilder.

type Updater

type Updater interface {
	UpdateOneCtx(ctx context.Context, updateParams UpdateBuilder) (err error)
}

Updater requires implementation provides single record update method using prepared UpdateBuilder.

type ValueProvider

type ValueProvider interface {
	DatabaseValue() interface{}
}

ValueProvider implementations provides it's own values to database.

type ValuesMap

type ValuesMap map[string]any

ValuesMap allows to define FieldValue set in mapping style.

func (ValuesMap) FieldValues

func (valuesMap ValuesMap) FieldValues() ([]FieldValue, error)

FieldValues represents ValuesMap as FieldValues. If table name points to valid field name, it will be used as FieldValue field definition table. Returns non-nil error if any key is not valid field name. Note table spec is not applied to elements, its up to caller to adopt values when required.

type ValuesProvider

type ValuesProvider interface {
	// Values returns a set of parameters to substitute when SQL query is fully constructed and passed to execution.
	// Parameters count should be the same as substitutions used in Render result.
	// If implementation requires nothing to substitute it should return empty slice.
	Values() []any
}

ValuesProvider requires clause renderer implementations should provide substitution values slice.

type WhereClause

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

WhereClause wraps conditions Group to handle conditions as whole WHERE clause block.

func NewWhere

func NewWhere() WhereClause

NewWhere creates new empty WhereClause instance.

func (WhereClause) ApplyFieldSpec

func (query WhereClause) ApplyFieldSpec(spec FieldDefinition) (updated WhereClause)

ApplyFieldSpec makes a copy of WhereClause with updated FieldDefinition on each child when field name matched. Implements Condition.

func (WhereClause) Conditions

func (query WhereClause) Conditions() (conditions []Condition)

Conditions returns a copy of attached conditions list.

func (WhereClause) GroupAND

func (query WhereClause) GroupAND(conditions ...Condition) (updated WhereClause)

GroupAND adds a new condition group into current. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical AND operator. Returns updated WhereClause containing required condition set, leaving original WhereClause instance intact.

func (WhereClause) GroupOR

func (query WhereClause) GroupOR(conditions ...Condition) (updated WhereClause)

GroupOR creates a new conditions group in where clause. Specified conditions joined into group with logical AND. Existed conditions are joined into group too. Both groups joined with logical OR operator. Returns new WhereClause containing required condition set, leaving original WhereClause instance intact.

func (WhereClause) Render

func (query WhereClause) Render(parametersCount int) (sql string)

Render renders SQL SELECT clause part for current group. Takes existed parameters number (0 means no parameters are defined yet) Note Render renders group without brackets itself if called directly. Any child conditions groups are enclosed into brackets internally.

func (WhereClause) RenderSQL

func (query WhereClause) RenderSQL() (sql string)

RenderSQL renders SQL clause or its part. Implementation should render parameters substitutions using standard sql "?"(question) character. Values result should contain the same values count as substitutions used in clause.

func (WhereClause) String

func (query WhereClause) String() string

String returns a string representation of WhereClause.

func (WhereClause) Values

func (query WhereClause) Values() (values []interface{})

Values returns a set of values of grouped conditions.

Jump to

Keyboard shortcuts

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