qb

package module
v0.0.0-...-6bc2ae1 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2018 License: LGPL-2.1 Imports: 8 Imported by: 16

README

alt text

qb - the database toolkit for go

Build Status Coverage Status License (LGPL version 2.1) Go Report Card GoDoc

This project is currently pre 1.

Currently, it's not feature complete. It can have potential bugs. There are no tests covering concurrency race conditions. It can crash especially in concurrency. Before 1.x releases, each major release could break backwards compatibility.

About qb

qb is a database toolkit for easier db queries in go. It is inspired from python's best orm, namely sqlalchemy. qb is an orm(sqlx) as well as a query builder. It is quite modular in case of using just expression api and query building stuff.

Documentation

The documentation is hosted in readme.io which has great support for markdown docs. Currently, the docs are about 80% - 90% complete. The doc files will be added to this repo soon. Moreover, you can check the godoc from here. Contributions & Feedbacks in docs are welcome.

Features

  • Support for postgres(9.5.+), mysql & sqlite3
  • Powerful expression API for building queries & table ddls
  • Struct to table ddl mapper where initial table migrations can happen
  • Transactional session api that auto map structs to queries
  • Foreign key definitions
  • Single & Composite column indices
  • Relationships (soon.. probably in 0.3 milestone)

Installation

go get -u github.com/slicebit/qb

If you want to install test dependencies then;

go get -u -t github.com/slicebit/qb

Quick Start

package main

import (
	"fmt"
	"github.com/slicebit/qb"
	_ "github.com/mattn/go-sqlite3"
    _ "github.com/slicebit/qb/dialects/sqlite"
)

type User struct {
	ID       string `db:"id"`
	Email    string `db:"email"`
	FullName string `db:"full_name"`
	Oscars   int    `db:"oscars"`
}

func main() {

	users := qb.Table(
		"users",
		qb.Column("id", qb.Varchar().Size(40)),
		qb.Column("email", qb.Varchar()).NotNull().Unique(),
		qb.Column("full_name", qb.Varchar()).NotNull(),
		qb.Column("oscars", qb.Int()).NotNull().Default(0),
		qb.PrimaryKey("id"),
	)

	db, err := qb.New("sqlite3", "./qb_test.db")
	if err != nil {
		panic(err)
	}

	defer db.Close()

	metadata := qb.MetaData()

	// add table to metadata
	metadata.AddTable(users)

	// create all tables registered to metadata
	metadata.CreateAll(db)
	defer metadata.DropAll(db) // drops all tables

	ins := qb.Insert(users).Values(map[string]interface{}{
		"id":        "b6f8bfe3-a830-441a-a097-1777e6bfae95",
		"email":     "jack@nicholson.com",
		"full_name": "Jack Nicholson",
	})

	_, err = db.Exec(ins)
	if err != nil {
		panic(err)
	}

	// find user
	var user User

	sel := qb.Select(users.C("id"), users.C("email"), users.C("full_name")).
		From(users).
		Where(users.C("id").Eq("b6f8bfe3-a830-441a-a097-1777e6bfae95"))

	err = db.Get(sel, &user)
	fmt.Printf("%+v\n", user)
}

Credits

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DialectRegistry = make(map[string]Dialect)

DialectRegistry is a global registry of dialects

Functions

func DefaultCompileType

func DefaultCompileType(t TypeElem, supportsUnsigned bool) string

DefaultCompileType is a default implementation for Dialect.CompileType

func EscapeAll

func EscapeAll(dialect Dialect, strings []string) []string

EscapeAll common escape all

func RegisterDialect

func RegisterDialect(name string, dialect Dialect)

RegisterDialect add a new dialect to the registry

Types

type AggregateClause

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

AggregateClause is the base struct for building aggregate functions

func Aggregate

func Aggregate(fn string, clause Clause) AggregateClause

Aggregate generates a new aggregate clause given function & clause

func Avg

func Avg(clause Clause) AggregateClause

Avg function generates "avg(%s)" statement for clause

func Count

func Count(clause Clause) AggregateClause

Count function generates "count(%s)" statement for clause

func Max

func Max(clause Clause) AggregateClause

Max function generates "max(%s)" statement for clause

func Min

func Min(clause Clause) AggregateClause

Min function generates "min(%s)" statement for clause

func Sum

func Sum(clause Clause) AggregateClause

Sum function generates "sum(%s)" statement for clause

func (AggregateClause) Accept

func (c AggregateClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitAggregate function

type AliasClause

type AliasClause struct {
	Name       string
	Selectable Selectable
}

AliasClause is a ALIAS sql clause

func Alias

func Alias(name string, selectable Selectable) AliasClause

Alias returns a new AliasClause

func (AliasClause) Accept

func (c AliasClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitAlias function

func (AliasClause) All

func (c AliasClause) All() []Clause

All returns the aliased selectable columns with their "Table" field updated with the alias name

func (AliasClause) C

func (c AliasClause) C(name string) ColumnElem

C returns the aliased selectable column with the given name. Before returning it, the 'Table' field is updated with alias name so that they can be used in Select()

func (AliasClause) ColumnList

func (c AliasClause) ColumnList() []ColumnElem

ColumnList returns the aliased selectable columns with their "Table" field updated with the alias name

func (AliasClause) DefaultName

func (c AliasClause) DefaultName() string

DefaultName returns the alias name

type BinaryExpressionClause

type BinaryExpressionClause struct {
	Left  Clause
	Right Clause
	Op    string
}

BinaryExpressionClause is the base struct for any conditional statements in sql clauses

func BinaryExpression

func BinaryExpression(left Clause, op string, right Clause) BinaryExpressionClause

BinaryExpression generates a condition object to use in update, delete & select statements

func Eq

func Eq(left Clause, right interface{}) BinaryExpressionClause

Eq generates a equals conditional sql clause

func Gt

func Gt(left Clause, right interface{}) BinaryExpressionClause

Gt generates a greater than conditional sql clause

func Gte

func Gte(left Clause, right interface{}) BinaryExpressionClause

Gte generates a greater than or equal to conditional sql clause

func Like

func Like(left Clause, right interface{}) BinaryExpressionClause

Like generates a like conditional sql clause

func Lt

func Lt(left Clause, right interface{}) BinaryExpressionClause

Lt generates a less than conditional sql clause

func Lte

func Lte(left Clause, right interface{}) BinaryExpressionClause

Lte generates a less than or equal to conditional sql clause

func NotEq

func NotEq(left Clause, right interface{}) BinaryExpressionClause

NotEq generates a not equal conditional sql clause

func (BinaryExpressionClause) Accept

func (c BinaryExpressionClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitBinary method

type BindClause

type BindClause struct {
	Value interface{}
}

BindClause binds a value to a placeholder

func Bind

func Bind(value interface{}) BindClause

Bind a value

func (BindClause) Accept

func (c BindClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitBind method

type Builder

type Builder interface {
	// Build takes a dialect and returns a stmt
	Build(dialect Dialect) *Stmt
}

Builder is the common interface for any statement builder in qb such as Insert(), Update(), Delete(), Select() query starters

type Clause

type Clause interface {
	Accept(context *CompilerContext) string
}

Clause is the base interface of all clauses that will get compiled to SQL by Compiler

func GetClauseFrom

func GetClauseFrom(value interface{}) Clause

GetClauseFrom returns the value if already a Clause, or make one if it is a scalar value

func GetListFrom

func GetListFrom(values ...interface{}) Clause

GetListFrom returns a list clause from any list

If only one value is passed and is a ListClause, it is returned as-is. In any other case, a ListClause is built with each value wrapped by a Bind() if not already a Clause

func GuessJoinOnClause

func GuessJoinOnClause(left Selectable, right Selectable) Clause

GuessJoinOnClause finds a join 'ON' clause between two tables

func MakeJoinOnClause

func MakeJoinOnClause(left Selectable, right Selectable, onClause ...Clause) Clause

MakeJoinOnClause assemble a 'ON' clause for a join from either: 0 clause: attempt to guess the join clause (only if left & right are tables),

otherwise panics

1 clause: returns it 2 clauses: returns a Eq() of both otherwise if panics

type ColumnElem

type ColumnElem struct {
	Name        string
	Type        TypeElem
	Table       string // This field should be lazily set by Table() function
	Constraints []ConstraintElem
	Options     ColumnOptions
}

ColumnElem is the definition of any columns defined in a table

func Column

func Column(name string, t TypeElem) ColumnElem

Column generates a ColumnElem given name and type

func (ColumnElem) Accept

func (c ColumnElem) Accept(context *CompilerContext) string

Accept calls the compiler VisitColumn function

func (ColumnElem) AutoIncrement

func (c ColumnElem) AutoIncrement() ColumnElem

AutoIncrement set up “auto increment” semantics for an integer column. Depending on the dialect, the column may be required to be a PrimaryKey too.

func (ColumnElem) Constraint

func (c ColumnElem) Constraint(name string) ColumnElem

Constraint adds a custom constraint to column type

func (ColumnElem) Default

func (c ColumnElem) Default(def interface{}) ColumnElem

Default adds a default constraint to column type

func (ColumnElem) Eq

func (c ColumnElem) Eq(value interface{}) Clause

Eq wraps the Eq(col ColumnElem, value interface{})

func (ColumnElem) Gt

func (c ColumnElem) Gt(value interface{}) Clause

Gt wraps the Gt(col ColumnElem, value interface{})

func (ColumnElem) Gte

func (c ColumnElem) Gte(value interface{}) Clause

Gte wraps the Gte(col ColumnElem, value interface{})

func (ColumnElem) In

func (c ColumnElem) In(values ...interface{}) Clause

In wraps the In(col ColumnElem, values ...interface{})

func (ColumnElem) Like

func (c ColumnElem) Like(pattern string) Clause

Like wraps the Like(col ColumnElem, pattern string)

func (ColumnElem) Lt

func (c ColumnElem) Lt(value interface{}) Clause

Lt wraps the Lt(col ColumnElem, value interface{})

func (ColumnElem) Lte

func (c ColumnElem) Lte(value interface{}) Clause

Lte wraps the Lte(col ColumnElem, value interface{})

func (ColumnElem) NotEq

func (c ColumnElem) NotEq(value interface{}) Clause

NotEq wraps the NotEq(col ColumnElem, value interface{})

func (ColumnElem) NotIn

func (c ColumnElem) NotIn(values ...interface{}) Clause

NotIn wraps the NotIn(col ColumnElem, values ...interface{})

func (ColumnElem) NotNull

func (c ColumnElem) NotNull() ColumnElem

NotNull adds not null constraint to column type

func (ColumnElem) Null

func (c ColumnElem) Null() ColumnElem

Null adds null constraint to column type

func (ColumnElem) PrimaryKey

func (c ColumnElem) PrimaryKey() ColumnElem

PrimaryKey add the column to the primary key

func (ColumnElem) String

func (c ColumnElem) String(dialect Dialect) string

String returns the column element as an sql clause It satisfies the TableSQLClause interface

func (ColumnElem) Unique

func (c ColumnElem) Unique() ColumnElem

Unique adds a unique constraint to column type

type ColumnOptions

type ColumnOptions struct {
	AutoIncrement    bool
	PrimaryKey       bool
	InlinePrimaryKey bool
	Unique           bool
}

ColumnOptions holds options for a column

type CombinerClause

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

CombinerClause is for OR and AND clauses

func And

func And(clauses ...Clause) CombinerClause

And generates an AndClause given conditional clauses

func Or

func Or(clauses ...Clause) CombinerClause

Or generates an AndClause given conditional clauses

func (CombinerClause) Accept

func (c CombinerClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitCombiner entry point

type Compiler

Compiler is a visitor that produce SQL from various types of Clause

type CompilerContext

type CompilerContext struct {
	Binds            []interface{}
	DefaultTableName string
	InSubQuery       bool
	Vars             map[string]interface{}

	Dialect  Dialect
	Compiler Compiler
}

CompilerContext is a data structure passed to all the Compiler visit functions. It contains the bindings, links to the Dialect and Compiler being used, and some contextual informations that can be used by the compiler functions to communicate during the compilation.

func NewCompilerContext

func NewCompilerContext(dialect Dialect) *CompilerContext

NewCompilerContext initialize a new compiler context

type CompositeIndex

type CompositeIndex string

CompositeIndex is the struct definition when building composite indices for any struct that will be mapped into a table

type ConstraintElem

type ConstraintElem struct {
	Name string
}

ConstraintElem is the definition of column & table constraints

func Constraint

func Constraint(name string) ConstraintElem

Constraint generates a custom constraint due to variation of dialects

func Default

func Default(value interface{}) ConstraintElem

Default generates generic default constraint

func NotNull

func NotNull() ConstraintElem

NotNull generates generic not null constraint

func Null

func Null() ConstraintElem

Null generates generic null constraint

func Unique

func Unique() ConstraintElem

Unique generates generic unique constraint if cols are given, then composite unique constraint will be built

func (ConstraintElem) String

func (c ConstraintElem) String() string

String returns the constraint as an sql clause

type DefaultDialect

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

DefaultDialect is a type of dialect that can be used with unsupported sql drivers

func (*DefaultDialect) AutoIncrement

func (d *DefaultDialect) AutoIncrement(column *ColumnElem) string

AutoIncrement generates auto increment sql of current dialect

func (*DefaultDialect) CompileType

func (d *DefaultDialect) CompileType(t TypeElem) string

CompileType compiles a type into its DDL

func (*DefaultDialect) Driver

func (d *DefaultDialect) Driver() string

Driver returns the current driver of dialect

func (*DefaultDialect) Escape

func (d *DefaultDialect) Escape(str string) string

Escape wraps the string with escape characters of the dialect

func (*DefaultDialect) EscapeAll

func (d *DefaultDialect) EscapeAll(strings []string) []string

EscapeAll wraps all elements of string array

func (*DefaultDialect) Escaping

func (d *DefaultDialect) Escaping() bool

Escaping gets the escaping parameter of dialect

func (*DefaultDialect) GetCompiler

func (d *DefaultDialect) GetCompiler() Compiler

GetCompiler returns the default SQLCompiler

func (*DefaultDialect) SetEscaping

func (d *DefaultDialect) SetEscaping(escaping bool)

SetEscaping sets the escaping parameter of dialect

func (*DefaultDialect) SupportsUnsigned

func (d *DefaultDialect) SupportsUnsigned() bool

SupportsUnsigned returns whether driver supports unsigned type mappings or not

func (*DefaultDialect) WrapError

func (d *DefaultDialect) WrapError(err error) Error

WrapError wraps a native error in a qb Error

type DefaultLogger

type DefaultLogger struct {
	*log.Logger
	// contains filtered or unexported fields
}

DefaultLogger is the default logger of qb engine unless engine.SetLogger() is not called

func (*DefaultLogger) LogFlags

func (l *DefaultLogger) LogFlags() LogFlags

LogFlags gets the logflags as an int

func (*DefaultLogger) SetLogFlags

func (l *DefaultLogger) SetLogFlags(logFlags LogFlags)

SetLogFlags sets the logflags It is for changing engine log flags

type DeleteStmt

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

DeleteStmt is the base struct for building delete queries

func Delete

func Delete(table TableElem) DeleteStmt

Delete generates a delete statement and returns it for chaining qb.Delete(usersTable).Where(qb.Eq("id", 5))

func (DeleteStmt) Accept

func (s DeleteStmt) Accept(context *CompilerContext) string

Accept implements Clause.Accept

func (DeleteStmt) Build

func (s DeleteStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of DeleteStmt object

func (DeleteStmt) Returning

func (s DeleteStmt) Returning(cols ...ColumnElem) DeleteStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (DeleteStmt) Where

func (s DeleteStmt) Where(clause Clause) DeleteStmt

Where adds a where clause to the current delete statement

type Dialect

type Dialect interface {
	GetCompiler() Compiler
	CompileType(t TypeElem) string
	Escape(str string) string
	EscapeAll([]string) []string
	SetEscaping(escaping bool)
	Escaping() bool
	AutoIncrement(column *ColumnElem) string
	SupportsUnsigned() bool
	Driver() string
	WrapError(err error) Error
}

Dialect is the common interface for driver changes It is for fixing compatibility issues of different drivers

func NewDefaultDialect

func NewDefaultDialect() Dialect

NewDefaultDialect instanciate a DefaultDialect

func NewDialect

func NewDialect(driver string) Dialect

NewDialect returns a dialect pointer given driver

type Engine

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

Engine is the generic struct for handling db connections

func New

func New(driver string, dsn string) (*Engine, error)

New generates a new engine and returns it as an engine pointer

func (*Engine) Begin

func (e *Engine) Begin() (*Tx, error)

Begin begins a transaction and return a *qb.Tx

func (*Engine) Close

func (e *Engine) Close() error

Close closes the sqlx db connection

func (*Engine) DB

func (e *Engine) DB() *sqlx.DB

DB returns sql.DB of wrapped engine connection

func (Engine) Dialect

func (e Engine) Dialect() Dialect

Dialect returns the engine dialect

func (*Engine) Driver

func (e *Engine) Driver() string

Driver returns the driver as string

func (*Engine) Dsn

func (e *Engine) Dsn() string

Dsn returns the connection dsn

func (*Engine) Exec

func (e *Engine) Exec(builder Builder) (sql.Result, error)

Exec executes insert & update type queries and returns sql.Result and error

func (*Engine) Get

func (e *Engine) Get(builder Builder, model interface{}) error

Get maps the single row to a model

func (*Engine) Logger

func (e *Engine) Logger() Logger

Logger returns the active logger of engine

func (*Engine) Ping

func (e *Engine) Ping() error

Ping pings the db using connection and returns error if connectivity is not present

func (*Engine) Query

func (e *Engine) Query(builder Builder) (*sql.Rows, error)

Query wraps *sql.DB.Query()

func (*Engine) QueryRow

func (e *Engine) QueryRow(builder Builder) Row

QueryRow wraps *sql.DB.QueryRow()

func (*Engine) Select

func (e *Engine) Select(builder Builder, model interface{}) error

Select maps multiple rows to a model array

func (Engine) SetDialect

func (e Engine) SetDialect(dialect Dialect)

SetDialect sets the current engine dialect

func (*Engine) SetLogFlags

func (e *Engine) SetLogFlags(flags LogFlags)

SetLogFlags sets the log flags on the current logger

func (*Engine) SetLogger

func (e *Engine) SetLogger(logger Logger)

SetLogger sets the logger of engine

func (Engine) TranslateError

func (e Engine) TranslateError(err error) error

TranslateError translates the native errors into qb.Error

type Error

type Error struct {
	Code       ErrorCode
	Orig       error // The native error from the driver
	Table      string
	Column     string
	Constraint string
}

Error wraps driver errors. It helps handling constraint error in a generic way, while still giving access to the original error

func (Error) Error

func (err Error) Error() string

type ErrorCode

type ErrorCode int

ErrorCode discriminates the types of errors that qb wraps, mainly the constraint errors The different kind of errors are based on the python dbapi errors (https://www.python.org/dev/peps/pep-0249/#exceptions)

const (
	// ErrAny is for errors that could not be categorized by the dialect
	ErrAny ErrorCode = 0
	// ErrInterface is a bit mask for errors that are related to the database
	// interface rather than the database itself.
	ErrInterface ErrorCode = 1 << 8
	// ErrDatabase is a bit mask for errors that are related to the database.
	ErrDatabase ErrorCode = 1 << 9
)

Bit 8 and 9 are flags to separate interface errors from database errors

const (
	// ErrData is for errors that are due to problems with the processed data
	// like division by zero, numeric value out of range, etc.
	ErrData ErrorCode = ErrDatabase | (iota + 1<<5)
	// ErrOperational is for errors that are related to the database's
	// operation and not necessarily under the control of the programmer, e.g.
	// an unexpected disconnect occurs, the data source name is not found, a
	// transaction could not be processed, a memory allocation error occurred
	// during processing, etc.
	ErrOperational
	// ErrIntegrity is when the relational integrity of the database is
	// affected, e.g. a foreign key check fails
	ErrIntegrity
	// ErrInternal is when the database encounters an internal error, e.g. the
	// cursor is not valid anymore, the transaction is out of sync, etc.
	ErrInternal
	// ErrProgramming is for programming errors, e.g. table not found or
	// already exists, syntax error in the SQL statement, wrong number of
	// parameters specified, etc.
	ErrProgramming
	// ErrNotSupported is in case a method or database API was used which
	// is not supported by the database, e.g. requesting a .rollback() on a
	// connection that does not support transaction or has transactions turned
	// off.
	ErrNotSupported
)

Database error codes are in bits 5 to 7, leaving bits 0 to 4 for detailed codes in a later version

func (ErrorCode) IsDatabaseError

func (err ErrorCode) IsDatabaseError() bool

IsDatabaseError returns true if the error is a Database error

func (ErrorCode) IsInterfaceError

func (err ErrorCode) IsInterfaceError() bool

IsInterfaceError returns true if the error is a Interface error

type ExistsClause

type ExistsClause struct {
	Select SelectStmt
	Not    bool
}

ExistsClause is a EXISTS clause

func Exists

func Exists(sel SelectStmt) ExistsClause

Exists returns a EXISTS clause

func NotExists

func NotExists(sel SelectStmt) ExistsClause

NotExists returns a NOT EXISTS clause

func (ExistsClause) Accept

func (c ExistsClause) Accept(context *CompilerContext) string

Accept calls compiler VisitExists methos

type ForUpdateClause

type ForUpdateClause struct {
	Tables []TableElem
}

ForUpdateClause is a FOR UPDATE expression

func (ForUpdateClause) Accept

func (s ForUpdateClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitForUpdate method

type ForeignKeyConstraint

type ForeignKeyConstraint struct {
	Cols           []string
	RefTable       string
	RefCols        []string
	ActionOnUpdate string
	ActionOnDelete string
}

ForeignKeyConstraint is the main struct for defining foreign key references

func ForeignKey

func ForeignKey(cols ...string) ForeignKeyConstraint

ForeignKey generates a foreign key for table constraint definitions

func (ForeignKeyConstraint) OnDelete

func (fkey ForeignKeyConstraint) OnDelete(action string) ForeignKeyConstraint

OnDelete set the ON DELETE action

func (ForeignKeyConstraint) OnUpdate

func (fkey ForeignKeyConstraint) OnUpdate(action string) ForeignKeyConstraint

OnUpdate set the ON UPDATE action

func (ForeignKeyConstraint) References

func (fkey ForeignKeyConstraint) References(refTable string, refCols ...string) ForeignKeyConstraint

References set the reference part of the foreign key

func (ForeignKeyConstraint) String

func (fkey ForeignKeyConstraint) String(dialect Dialect) string

type ForeignKeyConstraints

type ForeignKeyConstraints struct {
	FKeys []ForeignKeyConstraint
}

ForeignKeyConstraints is the definition of foreign keys in any table

func (ForeignKeyConstraints) String

func (c ForeignKeyConstraints) String(dialect Dialect) string

type HavingClause

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

HavingClause is the base struct for generating having clauses when using select It satisfies SQLClause interface

func (HavingClause) Accept

func (c HavingClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitHaving function

type InClause

type InClause struct {
	BinaryExpressionClause
}

InClause is a IN or NOT IN binary expression

func In

func In(left Clause, values ...interface{}) InClause

In generates an IN conditional sql clause

func NotIn

func NotIn(left Clause, values ...interface{}) InClause

NotIn generates an NOT IN conditional sql clause

func (InClause) Accept

func (c InClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitBinary method

type IndexElem

type IndexElem struct {
	Table   string
	Name    string
	Columns []string
}

IndexElem is the definition of any index elements for a table

func Index

func Index(table string, cols ...string) IndexElem

Index generates an index clause given table and columns as params

func (IndexElem) String

func (i IndexElem) String(dialect Dialect) string

String returns the index element as an sql clause

type InsertStmt

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

InsertStmt is the base struct for any insert statements

func Insert

func Insert(table TableElem) InsertStmt

Insert generates an insert statement and returns it Insert(usersTable).Values(map[string]interface{}{"id": 1})

func (InsertStmt) Accept

func (s InsertStmt) Accept(context *CompilerContext) string

Accept implements Clause.Accept

func (InsertStmt) Build

func (s InsertStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of InsertStmt object

func (InsertStmt) Returning

func (s InsertStmt) Returning(cols ...ColumnElem) InsertStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (InsertStmt) Values

func (s InsertStmt) Values(values map[string]interface{}) InsertStmt

Values accepts map[string]interface{} and forms the values map of insert statement

type JoinClause

type JoinClause struct {
	JoinType string
	Left     Selectable
	Right    Selectable
	OnClause Clause
}

JoinClause is the base struct for generating join clauses when using select It satisfies Clause interface

func Join

func Join(joinType string, left Selectable, right Selectable, onClause ...Clause) JoinClause

Join returns a new JoinClause onClause can be one of:

  • 0 clause: attempt to guess the join clause (only if left & right are tables), otherwise panics
  • 1 clause: use it directly
  • 2 clauses: use a Eq() of both

func (JoinClause) Accept

func (c JoinClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitJoin method

func (JoinClause) All

func (c JoinClause) All() []Clause

All returns the columns from both sides of the join

func (JoinClause) C

func (c JoinClause) C(name string) ColumnElem

C returns the first column with the given name If columns from both sides of the join match the name, the one from the left side will be returned.

func (JoinClause) ColumnList

func (c JoinClause) ColumnList() []ColumnElem

ColumnList returns the columns from both sides of the join

func (JoinClause) DefaultName

func (c JoinClause) DefaultName() string

DefaultName returns an empty string because Joins have no name by default

type ListClause

type ListClause struct {
	Clauses []Clause
}

ListClause is a list of clause elements (for IN operator for example)

func List

func List(clauses ...Clause) ListClause

List returns a list-of-clauses clause

func (ListClause) Accept

func (c ListClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitList method

type LogFlags

type LogFlags uint

LogFlags is the type we use for flags that can be passed to the logger

const (
	// LDefault is the default flag that logs nothing
	LDefault LogFlags = 0
	// LQuery Flag to log queries
	LQuery LogFlags = 1 << iota
	// LBindings Flag to log bindings
	LBindings
)

These are the log flags qb can use

type Logger

type Logger interface {
	Print(...interface{})
	Printf(string, ...interface{})
	Println(...interface{})

	Fatal(...interface{})
	Fatalf(string, ...interface{})
	Fatalln(...interface{})

	Panic(...interface{})
	Panicf(string, ...interface{})
	Panicln(...interface{})

	LogFlags() LogFlags
	SetLogFlags(LogFlags)
}

Logger is the std logger interface of the qb engine

type MetaDataElem

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

MetaDataElem is the container for database structs and tables

func MetaData

func MetaData() *MetaDataElem

MetaData creates a new MetaData object and returns it as a pointer

func (*MetaDataElem) AddTable

func (m *MetaDataElem) AddTable(table TableElem)

AddTable appends table to tables slice

func (*MetaDataElem) CreateAll

func (m *MetaDataElem) CreateAll(engine *Engine) error

CreateAll creates all the tables added to metadata

func (*MetaDataElem) DropAll

func (m *MetaDataElem) DropAll(engine *Engine) error

DropAll drops all the tables which is added to metadata

func (*MetaDataElem) Table

func (m *MetaDataElem) Table(name string) TableElem

Table returns the metadata registered table object. It returns nil if table is not found

func (*MetaDataElem) Tables

func (m *MetaDataElem) Tables() []TableElem

Tables returns the current tables slice

type OrderByClause

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

OrderByClause is the base struct for generating order by clauses when using select It satisfies SQLClause interface

func (OrderByClause) Accept

func (c OrderByClause) Accept(context *CompilerContext) string

Accept generates an order by clause

type PrimaryKeyConstraint

type PrimaryKeyConstraint struct {
	Columns []string
}

PrimaryKeyConstraint is the definition of primary key constraints of any table

func PrimaryKey

func PrimaryKey(cols ...string) PrimaryKeyConstraint

PrimaryKey generates a primary key constraint of any table

func (PrimaryKeyConstraint) String

func (c PrimaryKeyConstraint) String(dialect Dialect) string

String returns the primary key constraints as an sql clause

type Row

type Row struct {
	*sql.Row
	TranslateError func(error) error
}

Row wraps a *sql.Row in order to translate errors

func (Row) Scan

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

Scan wraps sql.Row.Scan()

type SQLCompiler

type SQLCompiler struct {
	Dialect Dialect
}

SQLCompiler aims to provide a SQL ANSI-92 implementation of Compiler

func NewSQLCompiler

func NewSQLCompiler(dialect Dialect) SQLCompiler

NewSQLCompiler returns a new SQLCompiler

func (SQLCompiler) VisitAggregate

func (c SQLCompiler) VisitAggregate(context *CompilerContext, aggregate AggregateClause) string

VisitAggregate compiles aggregate functions (COUNT, SUM...)

func (SQLCompiler) VisitAlias

func (SQLCompiler) VisitAlias(context *CompilerContext, alias AliasClause) string

VisitAlias compiles a '<selectable> AS <aliasname>' SQL clause

func (SQLCompiler) VisitBinary

func (c SQLCompiler) VisitBinary(context *CompilerContext, binary BinaryExpressionClause) string

VisitBinary compiles LEFT <op> RIGHT expressions

func (SQLCompiler) VisitBind

func (SQLCompiler) VisitBind(context *CompilerContext, bind BindClause) string

VisitBind renders a bounded value

func (SQLCompiler) VisitColumn

func (c SQLCompiler) VisitColumn(context *CompilerContext, column ColumnElem) string

VisitColumn returns a column name, optionnaly escaped depending on the dialect configuration

func (SQLCompiler) VisitCombiner

func (c SQLCompiler) VisitCombiner(context *CompilerContext, combiner CombinerClause) string

VisitCombiner compiles AND and OR sql clauses

func (SQLCompiler) VisitDelete

func (c SQLCompiler) VisitDelete(context *CompilerContext, delete DeleteStmt) string

VisitDelete compiles a DELETE statement

func (SQLCompiler) VisitExists

func (SQLCompiler) VisitExists(context *CompilerContext, exists ExistsClause) string

VisitExists compile a EXISTS clause

func (SQLCompiler) VisitForUpdate

func (c SQLCompiler) VisitForUpdate(context *CompilerContext, forUpdate ForUpdateClause) string

VisitForUpdate compiles a 'FOR UPDATE' clause

func (SQLCompiler) VisitHaving

func (c SQLCompiler) VisitHaving(context *CompilerContext, having HavingClause) string

VisitHaving compiles a HAVING clause

func (SQLCompiler) VisitIn

func (c SQLCompiler) VisitIn(context *CompilerContext, in InClause) string

VisitIn compiles a <left> (NOT) IN (<right>)

func (SQLCompiler) VisitInsert

func (c SQLCompiler) VisitInsert(context *CompilerContext, insert InsertStmt) string

VisitInsert compiles a INSERT statement

func (SQLCompiler) VisitJoin

func (c SQLCompiler) VisitJoin(context *CompilerContext, join JoinClause) string

VisitJoin compiles a JOIN (ON) clause

func (SQLCompiler) VisitLabel

func (c SQLCompiler) VisitLabel(context *CompilerContext, label string) string

VisitLabel returns a single label, optionally escaped

func (SQLCompiler) VisitList

func (c SQLCompiler) VisitList(context *CompilerContext, list ListClause) string

VisitList compiles a list of values

func (SQLCompiler) VisitOrderBy

func (c SQLCompiler) VisitOrderBy(context *CompilerContext, OrderByClause OrderByClause) string

VisitOrderBy compiles a ORDER BY sql clause

func (SQLCompiler) VisitSelect

func (c SQLCompiler) VisitSelect(context *CompilerContext, selectStmt SelectStmt) string

VisitSelect compiles a SELECT statement

func (SQLCompiler) VisitTable

func (SQLCompiler) VisitTable(context *CompilerContext, table TableElem) string

VisitTable returns a table name, optionally escaped

func (SQLCompiler) VisitText

func (SQLCompiler) VisitText(context *CompilerContext, text TextClause) string

VisitText return a raw SQL clause as is

func (SQLCompiler) VisitUpdate

func (c SQLCompiler) VisitUpdate(context *CompilerContext, update UpdateStmt) string

VisitUpdate compiles a UPDATE statement

func (SQLCompiler) VisitUpsert

func (c SQLCompiler) VisitUpsert(context *CompilerContext, upsert UpsertStmt) string

VisitUpsert is not implemented and will panic. It should be implemented in each dialect

func (SQLCompiler) VisitWhere

func (c SQLCompiler) VisitWhere(context *CompilerContext, where WhereClause) string

VisitWhere compiles a WHERE clause

type SelectStmt

type SelectStmt struct {
	SelectList      []Clause
	FromClause      Selectable
	GroupByClause   []ColumnElem
	OrderByClause   *OrderByClause
	HavingClause    []HavingClause
	WhereClause     *WhereClause
	ForUpdateClause *ForUpdateClause
	OffsetValue     *int
	LimitValue      *int
}

SelectStmt is the base struct for building select statements

func Select

func Select(clauses ...Clause) SelectStmt

Select generates a select statement and returns it

func (SelectStmt) Accept

func (s SelectStmt) Accept(context *CompilerContext) string

Accept calls the compiler VisitSelect method

func (SelectStmt) Asc

func (s SelectStmt) Asc() SelectStmt

Asc sets the t type of current order by clause NOTE: Please use it after calling OrderBy()

func (SelectStmt) Build

func (s SelectStmt) Build(dialect Dialect) *Stmt

Build compiles the select statement and returns the Stmt

func (SelectStmt) CrossJoin

func (s SelectStmt) CrossJoin(right Selectable) SelectStmt

CrossJoin appends an cross join clause to the select statement

func (SelectStmt) Desc

func (s SelectStmt) Desc() SelectStmt

Desc sets the t type of current order by clause NOTE: Please use it after calling OrderBy()

func (SelectStmt) ForUpdate

func (s SelectStmt) ForUpdate(tables ...TableElem) SelectStmt

ForUpdate adds a "FOR UPDATE" clause

func (SelectStmt) From

func (s SelectStmt) From(selectable Selectable) SelectStmt

From sets the from selectable of select statement

func (SelectStmt) GroupBy

func (s SelectStmt) GroupBy(cols ...ColumnElem) SelectStmt

GroupBy appends columns to group by clause of the select statement

func (SelectStmt) Having

func (s SelectStmt) Having(aggregate AggregateClause, op string, value interface{}) SelectStmt

Having appends a having clause to select statement

func (SelectStmt) InnerJoin

func (s SelectStmt) InnerJoin(right Selectable, onClause ...Clause) SelectStmt

InnerJoin appends an inner join clause to the select statement

func (SelectStmt) LeftJoin

func (s SelectStmt) LeftJoin(right Selectable, onClause ...Clause) SelectStmt

LeftJoin appends an left outer join clause to the select statement

func (SelectStmt) Limit

func (s SelectStmt) Limit(limit int) SelectStmt

Limit sets the limit number of rows

func (SelectStmt) LimitOffset

func (s SelectStmt) LimitOffset(limit, offset int) SelectStmt

LimitOffset sets the limit & offset values of the select statement

func (SelectStmt) Offset

func (s SelectStmt) Offset(value int) SelectStmt

Offset sets the offset

func (SelectStmt) OrderBy

func (s SelectStmt) OrderBy(columns ...ColumnElem) SelectStmt

OrderBy generates an OrderByClause and sets select statement's orderbyclause OrderBy(usersTable.C("id")).Asc() OrderBy(usersTable.C("email")).Desc()

func (SelectStmt) RightJoin

func (s SelectStmt) RightJoin(right Selectable, onClause ...Clause) SelectStmt

RightJoin appends a right outer join clause to select statement

func (SelectStmt) Select

func (s SelectStmt) Select(clauses ...Clause) SelectStmt

Select sets the selected columns

func (SelectStmt) Where

func (s SelectStmt) Where(clauses ...Clause) SelectStmt

Where sets the where clause of select statement

type Selectable

type Selectable interface {
	Clause
	All() []Clause
	ColumnList() []ColumnElem
	C(column string) ColumnElem
	DefaultName() string
}

Selectable is any clause from which we can select columns and is suitable as a FROM clause element

type Stmt

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

Stmt is the base abstraction for all sql queries

func Statement

func Statement() *Stmt

Statement creates a new query and returns its pointer

func (*Stmt) AddBinding

func (s *Stmt) AddBinding(bindings ...interface{})

AddBinding appends a new binding to current query

func (*Stmt) AddSQLClause

func (s *Stmt) AddSQLClause(clause string)

AddSQLClause appends a new clause to current query

func (*Stmt) Bindings

func (s *Stmt) Bindings() []interface{}

Bindings returns all bindings of current query

func (*Stmt) SQL

func (s *Stmt) SQL() string

SQL returns the query struct sql statement

func (*Stmt) SQLClauses

func (s *Stmt) SQLClauses() []string

SQLClauses returns all clauses of current query

func (*Stmt) SetDelimiter

func (s *Stmt) SetDelimiter(delimiter string)

SetDelimiter sets the delimiter of query

func (*Stmt) Text

func (s *Stmt) Text(sql string)

Text is for executing raw sql It parses the sql and generates clauses from

type TableElem

type TableElem struct {
	Name                  string
	Columns               map[string]ColumnElem
	PrimaryKeyConstraint  PrimaryKeyConstraint
	ForeignKeyConstraints ForeignKeyConstraints
	UniqueKeyConstraint   UniqueKeyConstraint
	Indices               []IndexElem
}

TableElem is the definition of any sql table

func Table

func Table(name string, clauses ...TableSQLClause) TableElem

Table generates table struct given name and clauses

func (TableElem) Accept

func (t TableElem) Accept(context *CompilerContext) string

Accept implements Clause.Accept

func (TableElem) All

func (t TableElem) All() []Clause

All returns all columns of table as a column slice

func (TableElem) Build

func (t TableElem) Build(dialect Dialect) *Stmt

Build generates a Statement object out of table ddl

func (TableElem) C

func (t TableElem) C(name string) ColumnElem

C returns the column name given col

func (TableElem) ColumnList

func (t TableElem) ColumnList() []ColumnElem

ColumnList columns of the table

func (TableElem) Create

func (t TableElem) Create(dialect Dialect) string

Create generates create table syntax and returns it as a query struct

func (TableElem) DefaultName

func (t TableElem) DefaultName() string

DefaultName returns the name of the table

func (TableElem) Delete

func (t TableElem) Delete() DeleteStmt

Delete starts a delete statement by setting the table parameter

func (TableElem) Drop

func (t TableElem) Drop(dialect Dialect) string

Drop generates drop table syntax and returns it as a query struct

func (TableElem) Index

func (t TableElem) Index(cols ...string) TableElem

Index appends an IndexElem to current table without giving table name

func (TableElem) Insert

func (t TableElem) Insert() InsertStmt

Insert starts an insert statement by setting the table parameter

func (TableElem) PrimaryCols

func (t TableElem) PrimaryCols() []ColumnElem

PrimaryCols returns the columns that are primary key to the table

func (TableElem) Select

func (t TableElem) Select(clauses ...Clause) SelectStmt

Select starts a select statement by setting from table

func (TableElem) Update

func (t TableElem) Update() UpdateStmt

Update starts an update statement by setting the table parameter

func (TableElem) Upsert

func (t TableElem) Upsert() UpsertStmt

Upsert starts an upsert statement by setting the table parameter

type TableSQLClause

type TableSQLClause interface {
	// String takes the dialect and returns the ddl as an sql string
	String(dialect Dialect) string
}

TableSQLClause is the common interface for ddl generators such as Column(), PrimaryKey(), ForeignKey().Ref(), etc.

type TextClause

type TextClause struct {
	Text string
}

TextClause is a raw SQL clause

func SQLText

func SQLText(text string) TextClause

SQLText returns a raw SQL clause

func (TextClause) Accept

func (c TextClause) Accept(context *CompilerContext) string

Accept calls the compiler VisitText method

type Tx

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

Tx is an in-progress database transaction

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction

func (*Tx) Exec

func (tx *Tx) Exec(builder Builder) (sql.Result, error)

Exec executes insert & update type queries and returns sql.Result and error

func (*Tx) Get

func (tx *Tx) Get(builder Builder, model interface{}) error

Get maps the single row to a model

func (*Tx) Query

func (tx *Tx) Query(builder Builder) (*sql.Rows, error)

Query wraps *sql.DB.Query()

func (*Tx) QueryRow

func (tx *Tx) QueryRow(builder Builder) Row

QueryRow wraps *sql.DB.QueryRow()

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback aborts the transaction

func (*Tx) Select

func (tx *Tx) Select(builder Builder, model interface{}) error

Select maps multiple rows to a model array

func (*Tx) Tx

func (tx *Tx) Tx() *sqlx.Tx

Tx returns the underlying *sqlx.Tx

type TypeElem

type TypeElem struct {
	Name string
	// contains filtered or unexported fields
}

TypeElem is the struct for defining column types

func BigInt

func BigInt() TypeElem

BigInt creates bigint type

func Blob

func Blob() TypeElem

Blob creates a BLOB type

func Boolean

func Boolean() TypeElem

Boolean creates boolean type

func Char

func Char() TypeElem

Char creates char type

func Decimal

func Decimal() TypeElem

Decimal creates a decimal type

func Float

func Float() TypeElem

Float creates float type

func Int

func Int() TypeElem

Int creates int type

func Numeric

func Numeric() TypeElem

Numeric creates a numeric type

func SmallInt

func SmallInt() TypeElem

SmallInt creates smallint type

func Text

func Text() TypeElem

Text creates text type

func Timestamp

func Timestamp() TypeElem

Timestamp creates timestamp type

func TinyInt

func TinyInt() TypeElem

TinyInt creates tinyint type

func Type

func Type(name string) TypeElem

Type returns a new TypeElem while defining columns in table

func UUID

func UUID() TypeElem

UUID creates a UUID type

func Varchar

func Varchar() TypeElem

Varchar creates varchar type

func (TypeElem) Precision

func (t TypeElem) Precision(p int, s int) TypeElem

Precision sets the precision of column type Note: Use it in Float, Decimal and Numeric types

func (TypeElem) Signed

func (t TypeElem) Signed() TypeElem

Signed change the column type to 'signed' Note: Use it in Float, Decimal and Numeric types

func (TypeElem) Size

func (t TypeElem) Size(size int) TypeElem

Size adds size constraint to column type

func (TypeElem) Unsigned

func (t TypeElem) Unsigned() TypeElem

Unsigned change the column type to 'unsigned' Note: Use it in Float, Decimal and Numeric types

type UniqueKeyConstraint

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

UniqueKeyConstraint is the base struct to define composite unique indexes of tables

func UniqueKey

func UniqueKey(cols ...string) UniqueKeyConstraint

UniqueKey generates UniqueKeyConstraint given columns as strings

func (UniqueKeyConstraint) Name

Name set the constraint name

func (UniqueKeyConstraint) String

func (c UniqueKeyConstraint) String(dialect Dialect) string

String generates composite unique indices as sql clause

func (UniqueKeyConstraint) Table

Table optionally set the constraint name based on the table name if a name is already defined, it remains untouched

type UpdateStmt

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

UpdateStmt is the base struct for any update statements

func Update

func Update(table TableElem) UpdateStmt

Update generates an update statement and returns it qb.Update(usersTable). Values(map[string]interface{}{"id": 1}). Where(qb.Eq("id", 5))

func (UpdateStmt) Accept

func (s UpdateStmt) Accept(context *CompilerContext) string

Accept implements Clause.Accept

func (UpdateStmt) Build

func (s UpdateStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of UpdateStmt object

func (UpdateStmt) Returning

func (s UpdateStmt) Returning(cols ...ColumnElem) UpdateStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (UpdateStmt) Values

func (s UpdateStmt) Values(values map[string]interface{}) UpdateStmt

Values accepts map[string]interface{} and forms the values map of insert statement

func (UpdateStmt) Where

func (s UpdateStmt) Where(clause Clause) UpdateStmt

Where adds a where clause to update statement and returns the update statement

type UpsertStmt

type UpsertStmt struct {
	Table         TableElem
	ValuesMap     map[string]interface{}
	ReturningCols []ColumnElem
}

UpsertStmt is the base struct for any insert ... on conflict/duplicate key ... update ... statements

func Upsert

func Upsert(table TableElem) UpsertStmt

Upsert generates an insert ... on (duplicate key/conflict) update statement

func (UpsertStmt) Accept

func (s UpsertStmt) Accept(context *CompilerContext) string

Accept calls the compiler VisitUpsert function

func (UpsertStmt) Build

func (s UpsertStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of UpdateStmt object

func (UpsertStmt) Returning

func (s UpsertStmt) Returning(cols ...ColumnElem) UpsertStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (UpsertStmt) Values

func (s UpsertStmt) Values(values map[string]interface{}) UpsertStmt

Values accepts map[string]interface{} and forms the values map of insert statement

type WhereClause

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

WhereClause is the base of any where clause when using expression api

func Where

func Where(clauses ...Clause) WhereClause

Where generates a compilable where clause

func (WhereClause) Accept

func (c WhereClause) Accept(context *CompilerContext) string

Accept compiles the where clause, returns sql

func (WhereClause) And

func (c WhereClause) And(clauses ...Clause) WhereClause

And combine the current clause and the new ones with a And()

func (WhereClause) Or

func (c WhereClause) Or(clauses ...Clause) WhereClause

Or combine the current clause and the new ones with a Or()

Directories

Path Synopsis
dialects

Jump to

Keyboard shortcuts

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