sq

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2019 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoColumn = core.ErrNoColumn
	ErrNoRows   = core.ErrNoRows
)

Errors

View Source
var DefaultLogger = Logger(func(entry *LogEntry) {
	log.Print("query=`", entry.Query, "` arg=", entry.Args, " error=", entry.Error, " t=", entry.Duration)
})

DefaultLogger ...

View Source
var DollarMarker = OptionFunc(func(db *Database) {
	db.marker = '$'
})

DollarMarker ...

View Source
var QuestionMarker = OptionFunc(func(db *Database) {
	db.marker = '?'
})

QuestionMarker ...

Functions

func BacktickEscape

func BacktickEscape(db *Database)

BacktickEscape ...

func DoubleQuoteEscape

func DoubleQuoteEscape(db *Database)

DoubleQuoteEscape ...

func UseArrayInsteadOfJSON

func UseArrayInsteadOfJSON(db *Database, b bool)

UseArrayInsteadOfJSON ...

Types

type ABSTRACT_TYPE

type ABSTRACT_TYPE string

type AS

type AS string

type And

type And []WriterTo

func (*And) Append

func (ps *And) Append(preds ...interface{}) And

func (And) WriteSQLTo

func (ps And) WriteSQLTo(w core.SQLWriter) error

type BeforeInsertInterface

type BeforeInsertInterface interface {
	BeforeInsert() error
}

type BeforeUpdateInterface

type BeforeUpdateInterface interface {
	BeforeUpdate() error
}

type ColumnFilter

type ColumnFilter ColumnFilterPtr

ColumnFilter and ColumnFilterPtr are shorthand for quickly writting predication. Sample code:

    db.Where(
        FilterByID(1234),
        FilterByState(state).Optional(),
        FilterByPartnerID(5678).Optional(),
    )

	func FilterByID(id int64) *ColumnFilter {
		return &ColumnFilter{
			Column: "id",
			Value:  id,
			IsZero: id == 0,
		}
	}

	func FilterByID(id *int64) *ColumnFilterPtr {
		return &ColumnFilterPtr{
			Column: "id",
			Value:  id,
			IsNil:  id == nil,
			IsZero: id == nil && *id == 0,
		}
	}

Explaination of different modes:

	func FilterByID(id int64)

	| mode      | id == 0           | id != 0 | notes                                  |
    |-----------|-------------------|---------|----------------------------------------|
	| (default) | (error)           | id = ?  | if id == 0, returns error              |
	| Optional  | (skip)            | id = ?  | if if == 0, skips                      |
	| Nullable  | IS NULL OR id = 0 | id = ?  | if id == 0, translates to "id IS NULL" |

	func FilterByPtrID(id *int64)

	| mode         | id == nil | *id == 0          | *id != 0 | explain                                                                             |
    |--------------|-----------|-------------------|----------|-------------------------------------------------------------------------------------|
	| (default)    | (error)   | IS NULL OR id = 0 | id = ?   | if id == nil, returns error; else if *id == 0, translates to "id IS NULL OR id = 0" |
	| Optional     | (skip)    | IS NULL OR id = 0 | id = ?   | if id == nil, skips; else if *id == 0, translates to "id IS NULL OR if = 0"         |
	| Nullable     | IS NULL   | id = 0            | id = ?   | if id == nil, translates to "id IS NULL"; else if *id == 0, translates to "id = 0"  |
    | RequiredZero | (error)   | id == 0           | id = ?   |                                                                                     |
    | RequiredNull | (error)   | IS NULL           | id = ?   |                                                                                     |
    | OptionalZero | (skip)    | id == 0           | id = ?   |                                                                                     |
    | OptionalNull | (skip)    | IS NULL           | id = ?   |                                                                                     |

func (*ColumnFilter) Nullable

func (p *ColumnFilter) Nullable() *ColumnFilter

func (*ColumnFilter) Optional

func (p *ColumnFilter) Optional() *ColumnFilter

func (*ColumnFilter) WriteSQLTo

func (p *ColumnFilter) WriteSQLTo(w core.SQLWriter) error

type ColumnFilterPtr

type ColumnFilterPtr struct {
	Prefix string
	Column string
	Value  interface{}
	IsNil  bool
	IsZero bool
	// contains filtered or unexported fields
}

func (*ColumnFilterPtr) Gt

func (op *ColumnFilterPtr) Gt()

func (*ColumnFilterPtr) Gte

func (op *ColumnFilterPtr) Gte()

func (*ColumnFilterPtr) Lt

func (op *ColumnFilterPtr) Lt()

func (*ColumnFilterPtr) Lte

func (op *ColumnFilterPtr) Lte()

func (*ColumnFilterPtr) Nullable

func (p *ColumnFilterPtr) Nullable() *ColumnFilterPtr

func (*ColumnFilterPtr) Optional

func (p *ColumnFilterPtr) Optional() *ColumnFilterPtr

func (*ColumnFilterPtr) OptionalNull

func (p *ColumnFilterPtr) OptionalNull() *ColumnFilterPtr

func (*ColumnFilterPtr) OptionalZero

func (p *ColumnFilterPtr) OptionalZero() *ColumnFilterPtr

func (*ColumnFilterPtr) RequiredNull

func (p *ColumnFilterPtr) RequiredNull() *ColumnFilterPtr

func (*ColumnFilterPtr) RequiredZero

func (p *ColumnFilterPtr) RequiredZero() *ColumnFilterPtr

func (*ColumnFilterPtr) WriteSQLTo

func (p *ColumnFilterPtr) WriteSQLTo(w core.SQLWriter) error

type CommonQuery

type CommonQuery = core.CommonQuery

type DBInterface

type DBInterface = core.DBInterface

type DEL

type DEL int

type Database

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

Database ...

func Connect

func Connect(driver, connStr string, opts ...Option) (*Database, error)

Connect ...

func MustConnect

func MustConnect(driver, connStr string, opts ...Option) *Database

MustConnect ...

func (*Database) Apply

func (db *Database) Apply(funcs ...func(CommonQuery)) Query

func (*Database) Begin

func (db *Database) Begin() (Tx, error)

Begin ...

func (*Database) BeginContext

func (db *Database) BeginContext(ctx context.Context) (Tx, error)

BeginContext ...

func (*Database) Count

func (db *Database) Count(obj core.ITableName, preds ...interface{}) (uint64, error)

Count ...

func (*Database) DB

func (db *Database) DB() *sql.DB

func (*Database) Delete

func (db *Database) Delete(obj core.ITableName) (int64, error)

Delete ...

func (*Database) Exec

func (db *Database) Exec(query string, args ...interface{}) (_ sql.Result, err error)

Exec ...

func (*Database) ExecContext

func (db *Database) ExecContext(ctx context.Context, query string, args ...interface{}) (_ sql.Result, err error)

ExecContext ...

func (*Database) Exists

func (db *Database) Exists(column string, exists bool) Query

Exists ...

func (*Database) Find

func (db *Database) Find(objs core.IFind, preds ...interface{}) error

Find ...

func (*Database) From

func (db *Database) From(table string) Query

From ...

func (*Database) Get

func (db *Database) Get(obj core.IGet, preds ...interface{}) (bool, error)

Get ...

func (*Database) GroupBy

func (db *Database) GroupBy(groupBys ...string) Query

GroupBy adds GROUP BY expressions to the query.

func (*Database) In

func (db *Database) In(column string, args ...interface{}) Query

In ...

func (*Database) Insert

func (db *Database) Insert(objs ...core.IInsert) (int64, error)

Insert ...

func (*Database) IsNull

func (db *Database) IsNull(column string, null bool) Query

IsNull ...

func (*Database) Limit

func (db *Database) Limit(limit uint64) Query

Limit sets a LIMIT clause on the query.

func (*Database) MustExec

func (db *Database) MustExec(query string, args ...interface{}) sql.Result

MustExec ...

func (*Database) NewQuery

func (db *Database) NewQuery() Query

NewQuery ...

func (*Database) NotIn

func (db *Database) NotIn(column string, args ...interface{}) Query

NotIn ...

func (*Database) Offset

func (db *Database) Offset(offset uint64) Query

Offset sets a OFFSET clause on the query.

func (*Database) Opts

func (db *Database) Opts() core.Opts

func (*Database) OrderBy

func (db *Database) OrderBy(orderBys ...string) Query

OrderBy adds ORDER BY expressions to the query.

func (*Database) Prefix

func (db *Database) Prefix(sql string, args ...interface{}) Query

Prefix adds an expression to the start of the query

func (*Database) Preload

func (db *Database) Preload(table string, preds ...interface{}) Query

func (*Database) Query

func (db *Database) Query(query string, args ...interface{}) (_ *sql.Rows, err error)

Query ...

func (*Database) QueryContext

func (db *Database) QueryContext(ctx context.Context, query string, args ...interface{}) (_ *sql.Rows, err error)

QueryContext ...

func (*Database) QueryRow

func (db *Database) QueryRow(query string, args ...interface{}) Row

QueryRow ...

func (*Database) QueryRowContext

func (db *Database) QueryRowContext(ctx context.Context, query string, args ...interface{}) Row

QueryRowContext ...

func (*Database) SQL

func (db *Database) SQL(args ...interface{}) Query

SQL ...

func (*Database) Select

func (db *Database) Select(cols ...string) Query

Select ...

func (*Database) Suffix

func (db *Database) Suffix(sql string, args ...interface{}) Query

Suffix adds an expression to the end of the query

func (*Database) Table

func (db *Database) Table(sql string) Query

Table ...

func (*Database) Update

func (db *Database) Update(objs ...core.IUpdate) (int64, error)

Update ...

func (*Database) UpdateAll

func (db *Database) UpdateAll() Query

UpdateAll ...

func (*Database) UpdateMap

func (db *Database) UpdateMap(m map[string]interface{}) (int64, error)

UpdateMap ...

func (*Database) Where

func (db *Database) Where(args ...interface{}) Query

Where ...

type DynamicLogger

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

DynamicLogger ...

func NewDynamicLogger

func NewDynamicLogger(logger Logger) *DynamicLogger

NewDynamicLogger ...

func (*DynamicLogger) SQLOption

func (d *DynamicLogger) SQLOption(db *Database)

SQLOption ...

func (*DynamicLogger) SetLogger

func (d *DynamicLogger) SetLogger(logger Logger)

SetLogger ...

type Error

type Error = core.Error

Error ...

type ErrorMapper

type ErrorMapper func(error, *LogEntry) error

ErrorMapper ...

func (ErrorMapper) SQLOption

func (m ErrorMapper) SQLOption(db *Database)

SQLOption ...

type Expr

type Expr struct {
	SQL  []byte
	Args []interface{}
}

func (Expr) WriteSQLTo

func (e Expr) WriteSQLTo(w core.SQLWriter) error

type ExprString

type ExprString struct {
	SQL  string
	Args []interface{}
}

func (ExprString) WriteSQLTo

func (e ExprString) WriteSQLTo(w core.SQLWriter) error

type FilterMode

type FilterMode int

Bit layout

______ÑO ______NZ

Z: Equal to Zero (id = 0)
N: Equal to NULL (id IS NULL)
O: Optional, won't throw error if the field is empty
Ñ: Nullable, the column value can be null
const (
	ModeDefault      FilterMode = iota
	ModeOptional     FilterMode = 1<<8 + 0 // _O & __
	ModeNullable     FilterMode = 2<<8 + 1 // Ñ_ & _Z
	ModeRequiredZero FilterMode = 0<<8 + 1 // __ & _Z
	ModeRequiredNull FilterMode = 0<<8 + 2 // __ & N_
	ModeOptionalZero FilterMode = 1<<8 + 1 // _O & _Z
	ModeOptionalNull FilterMode = 1<<8 + 2 // _O & N_
)

type Flags

type Flags uint

Flags ...

func (Flags) IsBuild

func (f Flags) IsBuild() bool

IsBuild ...

func (Flags) IsQuery

func (f Flags) IsQuery() bool

IsQuery ...

func (Flags) IsTx

func (f Flags) IsTx() bool

IsTx ...

func (Flags) MarshalJSON

func (f Flags) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (Flags) Type

func (f Flags) Type() Type

Type ...

type INS

type INS int

type InPart

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

func (InPart) WriteSQLTo

func (p InPart) WriteSQLTo(w core.SQLWriter) error

type InsPart

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

In with multple columns

func (InsPart) WriteSQLTo

func (p InsPart) WriteSQLTo(w core.SQLWriter) error

type IsNullPart

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

func (IsNullPart) WriteSQLTo

func (p IsNullPart) WriteSQLTo(w core.SQLWriter) error

type JOIN_TYPE

type JOIN_TYPE = core.JoinType
const (
	JOIN         JOIN_TYPE = ""
	FULL_JOIN    JOIN_TYPE = "FULL"
	LEFT_JOIN    JOIN_TYPE = "LEFT"
	RIGHT_JOIN   JOIN_TYPE = "RIGHT"
	NATURAL_JOIN JOIN_TYPE = "NATURAL"
	CROSS_JOIN   JOIN_TYPE = "CROSS"
	SELF_JOIN    JOIN_TYPE = "SELF"
)

type LogArgs

type LogArgs []interface{}

LogArgs ...

func (LogArgs) MarshalJSON

func (args LogArgs) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (LogArgs) ToSQLValues

func (args LogArgs) ToSQLValues() (res []interface{}, _err error)

ToSQLValues ...

type LogEntry

type LogEntry struct {
	Ctx       context.Context `json:"-"`
	Query     string          `json:"query"`
	Args      LogArgs         `json:"args"`
	Error     error           `json:"error"`
	OrigError error           `json:"orig_error"`
	Time      time.Time       `json:"time"`
	Duration  time.Duration   `json:"duration"`

	Flags `json:"flags"`

	// Only be set if Type is Commit or Revert
	TxQueries []*LogEntry `json:"tx_queries"`
}

LogEntry ...

type Logger

type Logger func(*LogEntry)

Logger ...

func (Logger) SQLOption

func (l Logger) SQLOption(db *Database)

SQLOption ...

type ON

type ON string

type Once

type Once []WriterTo

func (Once) WriteSQLTo

func (ps Once) WriteSQLTo(w core.SQLWriter) error

type Option

type Option interface {
	SQLOption(*Database)
}

Option ...

func SetErrorMapper

func SetErrorMapper(mapper ErrorMapper) Option

SetErrorMapper ...

func SetLogger

func SetLogger(logger Logger) Option

SetLogger ...

type OptionFunc

type OptionFunc func(*Database)

OptionFunc ...

func (OptionFunc) SQLOption

func (fn OptionFunc) SQLOption(db *Database)

SQLOption ...

type Or

type Or []WriterTo

func (*Or) Append

func (ps *Or) Append(preds ...interface{}) Or

func (Or) WriteSQLTo

func (ps Or) WriteSQLTo(w core.SQLWriter) error

type Parts

type Parts []WriterTo

func (*Parts) Append

func (ps *Parts) Append(preds ...interface{}) Parts

func (Parts) WriteSQLTo

func (ps Parts) WriteSQLTo(w core.SQLWriter, sep string) error

type PoolConfig

type PoolConfig struct {
	MaxLifetime time.Duration // <= 0: connections are reused forever
	MaxIdle     int           // default 2
	MaxOpen     int           // default 0: unlimited
}

PoolConfig connection pool config

func (PoolConfig) SQLOption

func (cfg PoolConfig) SQLOption(db *Database)

type Query

type Query = core.Query

type Row

type Row = core.Row

type SEL

type SEL int

type SQLWriter

type SQLWriter = core.SQLWriter

type TABLE

type TABLE string

type Tx

type Tx interface {
	Commit() error
	Rollback() error

	DBInterface
	CommonQuery
}

Tx ...

type Type

type Type int

Type ...

const (
	TypeExec     Type = 1
	TypeQuery    Type = 2
	TypeQueryRow Type = 3
	TypeCommit   Type = 5
	TypeRollback Type = 6

	FlagTx    = 1 << 4
	FlagBuild = 1 << 8
)

Constants ...

type UPD

type UPD int

type Writer

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

func NewWriter

func NewWriter(opts core.Opts, quote byte, marker byte, size int) *Writer

func (*Writer) Args

func (w *Writer) Args() []interface{}

func (*Writer) Len

func (w *Writer) Len() int

func (*Writer) Opts

func (w *Writer) Opts() core.Opts

func (*Writer) ScanArgs

func (w *Writer) ScanArgs() []interface{}

func (*Writer) String

func (w *Writer) String() string

func (*Writer) TrimLast

func (w *Writer) TrimLast(n int)

TrimLast removes n last bytes written

func (*Writer) WriteArg

func (w *Writer) WriteArg(arg interface{})

func (*Writer) WriteArgs

func (w *Writer) WriteArgs(args []interface{})

func (*Writer) WriteByte

func (w *Writer) WriteByte(b byte)

func (*Writer) WriteMarker

func (w *Writer) WriteMarker()

func (*Writer) WriteMarkers

func (w *Writer) WriteMarkers(n int)

func (*Writer) WriteName

func (w *Writer) WriteName(name string)

func (*Writer) WritePrefixedName

func (w *Writer) WritePrefixedName(schema, name string)

func (*Writer) WriteQuery

func (w *Writer) WriteQuery(query []byte)

func (*Writer) WriteQueryName

func (w *Writer) WriteQueryName(name string)

func (*Writer) WriteQueryString

func (w *Writer) WriteQueryString(query string)

func (*Writer) WriteQueryStringWithPrefix

func (w *Writer) WriteQueryStringWithPrefix(prefix, query string)

func (*Writer) WriteRaw

func (w *Writer) WriteRaw(query []byte)

func (*Writer) WriteRawString

func (w *Writer) WriteRawString(query string)

func (*Writer) WriteScanArg

func (w *Writer) WriteScanArg(arg interface{})

func (*Writer) WriteScanArgs

func (w *Writer) WriteScanArgs(args []interface{})

type WriterTo

type WriterTo interface {
	WriteSQLTo(w core.SQLWriter) error
}

func Filter

func Filter(prefix, pred string, args ...interface{}) WriterTo

func In

func In(column string, args ...interface{}) WriterTo

func Ins

func Ins(columns []string, args ...interface{}) WriterTo

func NewExpr

func NewExpr(preds ...interface{}) WriterTo

func NewInPart

func NewInPart(in bool, column string, args ...interface{}) WriterTo

func NewInsPart

func NewInsPart(in bool, columns []string, args ...interface{}) WriterTo

func NewIsNullPart

func NewIsNullPart(column string, null bool) WriterTo

func NotIn

func NotIn(column string, args ...interface{}) WriterTo

func NotIns

func NotIns(columns []string, args ...interface{}) WriterTo

type WriterToFunc

type WriterToFunc func(w core.SQLWriter) error

func (WriterToFunc) WriteSQLTo

func (fn WriterToFunc) WriteSQLTo(w core.SQLWriter) error

Jump to

Keyboard shortcuts

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