psql

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2024 License: MIT Imports: 24 Imported by: 0

README

Go Reference

psql

Platform SQL code, including object load/save & query builder.

Object binding

After defining a structure, you can use it to load/save data from database.

type Table1 struct {
	Key uint64 `sql:",key=PRIMARY"`
	Name string `sql:"Name,type=VARCHAR,size=64"`
}

// ...

obj, err := psql.Get[Table1](context.Background(), map[string]any{"Key": 42}) // this fetches entry with Key=42

Query builder

Documentation

Index

Constants

View Source
const (
	// Use " for ANSI SQL, and ` for MySQL's own thing
	NameQuoteChar = `"`
	NameQuoteRune = '"'
)

Variables

View Source
var (
	ErrNotReady           = errors.New("database is not ready (no connection is available)")
	ErrNotNillable        = errors.New("field is nil but cannot be nil")
	ErrTxAlreadyProcessed = errors.New("transaction has already been committed or rollbacked")
	ErrDeleteBadAssert    = errors.New("delete operation failed assertion")
)
View Source
var FetchLock = &FetchOptions{Lock: true}
View Source
var FormatTableName = formatCamelSnakeCase

Functions

func ContextBackend added in v0.4.0

func ContextBackend(ctx context.Context, be *Backend) context.Context

func ContextConn added in v0.1.10

func ContextConn(ctx context.Context, conn *sql.Conn) context.Context

func ContextDB added in v0.1.10

func ContextDB(ctx context.Context, db *sql.DB) context.Context

func ContextTx added in v0.1.10

func ContextTx(ctx context.Context, tx *TxProxy) context.Context

func Count added in v0.1.16

func Count[T any](ctx context.Context, where any) (int, error)

func DefineMagicType added in v0.2.10

func DefineMagicType(typ string, definition string)

func Delete added in v0.3.1

func Delete[T any](ctx context.Context, where any, opts ...*FetchOptions) (sql.Result, error)

Delete will delete values from the table matching the where parameters

func DeleteOne added in v0.3.3

func DeleteOne[T any](ctx context.Context, where any, opts ...*FetchOptions) error

DeleteOne will operate the deletion in a separate transaction and ensure only 1 row was deleted or it will rollback the deletion and return an error. This is useful when working with important data and security is more important than performance.

func ErrorNumber

func ErrorNumber(err error) uint16

func Escape

func Escape(val any) string

Escape takes any value and transforms it into a string that can be included in a MySQL query

func EscapeTx added in v0.2.6

func EscapeTx(ctx context.Context) (context.Context, bool)

EscapeTx allows obtaining the context underlying a current transaction, this can be useful if a query needs to be run outside of a transaction (for example to log something, etc)

func Exec

func Exec(q *SQLQuery) error

Exec simply runs a query against the DefaultBackend

func Factory added in v0.3.6

func Factory[T any]() *T

func Fetch

func Fetch[T any](ctx context.Context, where any, opts ...*FetchOptions) ([]*T, error)

func FetchGrouped added in v0.2.9

func FetchGrouped[T any](ctx context.Context, where map[string]any, key string, opts ...*FetchOptions) (map[string][]*T, error)

func FetchMapped added in v0.2.9

func FetchMapped[T any](ctx context.Context, where any, key string, opts ...*FetchOptions) (map[string]*T, error)

func FetchOne

func FetchOne[T any](ctx context.Context, target *T, where any, opts ...*FetchOptions) error

func Get added in v0.1.8

func Get[T any](ctx context.Context, where any, opts ...*FetchOptions) (*T, error)

Get will instanciate a new object of type T and return a pointer to it after loading from database

func HasChanged added in v0.1.2

func HasChanged[T any](obj *T) bool

func Init

func Init(dsn string) error

Init creates a new Backend and sets DefaultBackend

func InitCfg added in v0.1.5

func InitCfg(cfg *mysql.Config) error

InitCfg creates a new MySQL Backend and sets DefaultBackend

func Insert

func Insert[T any](ctx context.Context, target ...*T) error

Insert is a short way to insert objects into database

psql.Insert(ctx, obj)

Is equivalent to:

psql.Table(obj).Insert(ctx, obj)

All passed objects must be of the same type

func InsertIgnore added in v0.1.7

func InsertIgnore[T any](ctx context.Context, target ...*T) error

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns true if the error is relative to a table not existing.

See: https://mariadb.com/kb/en/mariadb-error-codes/

Example: Error 1146: Table 'test.Test_Table1' doesn't exist

func Query

func Query(q *SQLQuery, cb func(*sql.Rows) error) error

Query performs a query and use a callback to advance results, meaning there is no need to call sql.Rows.Close()

err = psql.Query(psql.Q("SELECT ..."), func(row *sql.Rows) error { ... })

func QueryContext

func QueryContext(ctx context.Context, q *SQLQuery, cb func(*sql.Rows) error) error

func QuoteName

func QuoteName(v string) string

quote a name (field, etc)

func Replace added in v0.1.7

func Replace[T any](ctx context.Context, target ...*T) error

Replace is a short way to replace objects into database

psql.Replace(ctx, obj)

Is equivalent to:

psql.Table(obj).Replace(ctx, obj)

All passed objects must be of the same type

func SetLogger added in v0.2.11

func SetLogger(l Logger)

SetLogger sets a global logger for debugging psql This can be called easily as follows using go's log package:

psql.SetLogger(log.Default())

Or a better option:

psql.SetLogger(log.New(os.Stderr, "psql: ", log.LstdFlags|log.Lmsgprefix))

func Tx added in v0.1.10

func Tx(ctx context.Context, cb func(ctx context.Context) error) error

Tx can be used to run a function inside a sql transaction for isolation/etc

func Update

func Update[T any](ctx context.Context, target ...*T) error

Update is a short way to insert objects into database

psql.Update(ctx, obj)

Is equivalent to:

psql.Table(obj).Update(ctx, obj)

All passed objects must be of the same type

func V

func V(v driver.Value) driver.Value

V ensures a given value is a value and cannot be interpreted as something else

Types

type Backend added in v0.4.0

type Backend struct {
	// contains filtered or unexported fields
}
var (
	DefaultBackend *Backend
)

func GetBackend added in v0.4.0

func GetBackend(ctx context.Context) *Backend

GetBackend will attempt to find a backend in the provided context and return it, or it will return DefaultBackend if no backend was found.

func New added in v0.4.0

func New(dsn string) (*Backend, error)

New returns a Backend that connects to the provided database

func NewMySQL added in v0.4.0

func NewMySQL(cfg *mysql.Config) (*Backend, error)

func NewPG added in v0.4.0

func NewPG(cfg *pgxpool.Config) (*Backend, error)

func (*Backend) DB added in v0.4.0

func (be *Backend) DB() *sql.DB

func (*Backend) Plug added in v0.4.0

func (be *Backend) Plug(ctx context.Context) context.Context

type Comparison

type Comparison struct {
	A, B any
	Op   string // one of "=", "<", ">", etc...
}

func (*Comparison) EscapeValue

func (c *Comparison) EscapeValue() string

type Engine added in v0.4.0

type Engine int
const (
	EngineUnknown Engine = iota
	EngineMySQL
	EnginePostgreSQL
)

type Error

type Error struct {
	Query string
	Err   error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type EscapeTableable

type EscapeTableable interface {
	EscapeTable() string
}

EscapeTableable is a type of value that can be used as a table

type EscapeValueable

type EscapeValueable interface {
	EscapeValue() string
}

func Between added in v0.2.10

func Between(a, start, end any) EscapeValueable

Between is a BETWEEN SQL operation. The BETWEEN operator is inclusive: begin and end values are included.

func Equal

func Equal(a, b any) EscapeValueable

func F

func F(field ...string) EscapeValueable

F allows passing a field name to the query builder. It can be used in multiple ways:

psql.F("field") psql.F("table.field") psql.F("", "field.with.dots") psql.F("table", "field") psql.F("table.with.dots", "field.with.dots") and more...

func Gt added in v0.2.0

func Gt(a, b any) EscapeValueable

func Gte added in v0.2.0

func Gte(a, b any) EscapeValueable

func Lt added in v0.2.0

func Lt(a, b any) EscapeValueable

func Lte added in v0.2.0

func Lte(a, b any) EscapeValueable

func Raw

func Raw(s string) EscapeValueable

type FetchOptions added in v0.1.13

type FetchOptions struct {
	Lock       bool
	LimitCount int             // number of results to return if >0
	LimitStart int             // seek first record if >0
	Sort       []SortValueable // fields to sort by
}

func Limit added in v0.1.15

func Limit(cnt int) *FetchOptions

func LimitFrom added in v0.1.15

func LimitFrom(start, cnt int) *FetchOptions

func Sort added in v0.1.15

func Sort(fields ...SortValueable) *FetchOptions

type FindInSet added in v0.3.6

type FindInSet struct {
	Field any
	Value string
}

func (*FindInSet) EscapeValue added in v0.3.6

func (f *FindInSet) EscapeValue() string

func (*FindInSet) String added in v0.3.6

func (f *FindInSet) String() string

type Future added in v0.3.4

type Future[T any] struct {
	// contains filtered or unexported fields
}

func Lazy added in v0.3.4

func Lazy[T any](col, val string) *Future[T]

Lazy returns an instance of Future that will be resolved in the future. Multiple calls to Lazy in different goroutines will return the same value until it is resolved. This will also attempt to group requests to the same table in the future.

func (*Future[T]) MarshalContextJSON added in v0.3.4

func (f *Future[T]) MarshalContextJSON(ctx context.Context) ([]byte, error)

func (*Future[T]) MarshalJSON added in v0.3.4

func (f *Future[T]) MarshalJSON() ([]byte, error)

func (*Future[T]) Resolve added in v0.3.5

func (f *Future[T]) Resolve(ctx context.Context) (*T, error)

type Hex

type Hex []byte

Hex is a binary value stored as hexadecimal in database

func (*Hex) Scan

func (h *Hex) Scan(src interface{}) error

func (*Hex) Value

func (h *Hex) Value() (driver.Value, error)

type Key

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

Name allows specifying the table name when associating a table with a struct

For example: type X struct { KeyName psql.Key `sql:",type=UNIQUE,fields='A,B'"` ... }

type Like

type Like struct {
	Field any
	Like  string
}

func (*Like) EscapeValue

func (l *Like) EscapeValue() string

func (*Like) String

func (l *Like) String() string

type Logger added in v0.2.11

type Logger interface {
	DebugContext(ctx context.Context, msg string, args ...any)
}

Logger is compatible with go's slog.Logger

type Name

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

Name allows specifying the table name when associating a table with a struct

For example: type X struct { TableName psql.Name `sql:"X"` ... }

type Not added in v0.2.0

type Not struct {
	V any
}

func (*Not) EscapeValue added in v0.2.0

func (n *Not) EscapeValue() string

type QueryBuilder

type QueryBuilder struct {
	Query       string
	Fields      []any
	Tables      []EscapeTableable
	FieldsSet   []any
	WhereData   WhereAND
	GroupBy     []any
	OrderByData []SortValueable
	LimitData   []int

	// flags
	Distinct      bool
	CalcFoundRows bool
	UpdateIgnore  bool
	InsertIgnore  bool
	ForUpdate     bool
	// contains filtered or unexported fields
}

func B

func B() *QueryBuilder

func (*QueryBuilder) AlsoSelect

func (q *QueryBuilder) AlsoSelect(fields ...any) *QueryBuilder

func (*QueryBuilder) Delete

func (q *QueryBuilder) Delete() *QueryBuilder

func (*QueryBuilder) ExecQuery added in v0.3.2

func (q *QueryBuilder) ExecQuery(ctx context.Context) (sql.Result, error)

func (*QueryBuilder) From

func (q *QueryBuilder) From(table any) *QueryBuilder

func (*QueryBuilder) Insert

func (q *QueryBuilder) Insert(fields ...any) *QueryBuilder

func (*QueryBuilder) Into

func (q *QueryBuilder) Into(table EscapeTableable) *QueryBuilder

func (*QueryBuilder) Limit

func (q *QueryBuilder) Limit(v ...int) *QueryBuilder

func (*QueryBuilder) OrderBy

func (q *QueryBuilder) OrderBy(field ...SortValueable) *QueryBuilder

func (*QueryBuilder) Prepare added in v0.2.0

func (q *QueryBuilder) Prepare(ctx context.Context) (*sql.Stmt, error)

func (*QueryBuilder) Render

func (q *QueryBuilder) Render() (string, error)

func (*QueryBuilder) RenderArgs added in v0.2.0

func (q *QueryBuilder) RenderArgs() (string, []any, error)

func (*QueryBuilder) Replace

func (q *QueryBuilder) Replace(table EscapeTableable) *QueryBuilder

func (*QueryBuilder) RunQuery added in v0.2.0

func (q *QueryBuilder) RunQuery(ctx context.Context) (*sql.Rows, error)

func (*QueryBuilder) Select

func (q *QueryBuilder) Select(fields ...any) *QueryBuilder

func (*QueryBuilder) Set

func (q *QueryBuilder) Set(fields ...any) *QueryBuilder

func (*QueryBuilder) Table

func (q *QueryBuilder) Table(table any) *QueryBuilder

func (*QueryBuilder) Update

func (q *QueryBuilder) Update(table any) *QueryBuilder

func (*QueryBuilder) Where

func (q *QueryBuilder) Where(where ...any) *QueryBuilder

type SQLQuery

type SQLQuery struct {
	Query string
	Args  []any
}

func Q

func Q(q string, args ...any) *SQLQuery

Q is a short hand to create a Query object

type Set

type Set []string

func (Set) Has added in v0.3.7

func (s Set) Has(k string) bool

func (*Set) Scan added in v0.3.7

func (s *Set) Scan(src any) error

func (*Set) Set added in v0.3.7

func (s *Set) Set(k string)

func (*Set) Unset added in v0.3.7

func (s *Set) Unset(k string)

func (Set) Value added in v0.3.7

func (s Set) Value() (driver.Value, error)

type ShowFieldsResult

type ShowFieldsResult struct {
	Virtual    Name    `sql:",check=0"`
	Field      string  `sql:",type=VARCHAR,size=256"`
	Type       string  `sql:",type=VARCHAR,size=256"`
	Collation  *string `sql:",type=VARCHAR,size=256,null=1"`
	Null       string  `sql:",type=VARCHAR,size=3"` // "YES" or "NO"
	Key        string  `sql:",type=VARCHAR,size=3"` // "PRI", "UNI", "MUL" or ""
	Default    *string `sql:",type=VARCHAR,size=256"`
	Extra      string  `sql:",type=VARCHAR,size=256"`
	Privileges string  `sql:",type=VARCHAR,size=256"` // "select,insert,update,references"
	Comment    string  `sql:",type=VARCHAR,size=256"`
}

type ShowIndexResult

type ShowIndexResult struct {
	Virtual     Name   `sql:",check=0"`
	Table       string `sql:",type=VARCHAR,size=256"`
	NonUnique   bool   `sql:"Non_unique"`
	KeyName     string `sql:"Key_name,type=VARCHAR,size=256"`
	SeqInIndex  int64  `sql:"Seq_in_index"`
	ColumnName  string `sql:"Column_name,type=VARCHAR,size=256"`
	Collation   string `sql:",type=VARCHAR,size=256"`
	Cardinality int64
	SubPart     *int64 `sql:"Sub_part"`
	// Packed?
	Null         string `sql:",type=VARCHAR,size=3"`             // "YES" or ""
	IndexType    string `sql:"Index_type,type=VARCHAR,size=256"` // BTREE, HASH
	Comment      string `sql:",type=VARCHAR,size=256"`
	IndexComment string `sql:"Index_comment,type=VARCHAR,size=256"`
}

type SortValueable added in v0.1.19

type SortValueable interface {
	// contains filtered or unexported methods
}

SortValueable is a kind of value that can be used for sorting

func S added in v0.1.19

func S(field ...string) SortValueable

type TableMeta

type TableMeta[T any] struct {
	// contains filtered or unexported fields
}

func Table

func Table[T any](ctxs ...context.Context) *TableMeta[T]

Table returns the table object for T against DefaultBackend unless the provided ctx value has a backend.

func (*TableMeta[T]) Count added in v0.1.16

func (t *TableMeta[T]) Count(ctx context.Context, where any) (int, error)

func (*TableMeta[T]) Delete added in v0.3.1

func (t *TableMeta[T]) Delete(ctx context.Context, where any, opts ...*FetchOptions) (sql.Result, error)

func (*TableMeta[T]) DeleteOne added in v0.3.3

func (t *TableMeta[T]) DeleteOne(ctx context.Context, where any, opts ...*FetchOptions) error

func (*TableMeta[T]) Factory added in v0.3.6

func (t *TableMeta[T]) Factory() *T

Factory returns a new object T pre-initialized with its defaults

func (*TableMeta[T]) Fetch

func (t *TableMeta[T]) Fetch(ctx context.Context, where any, opts ...*FetchOptions) ([]*T, error)

func (*TableMeta[T]) FetchGrouped added in v0.2.9

func (t *TableMeta[T]) FetchGrouped(ctx context.Context, where any, key string, opts ...*FetchOptions) (map[string][]*T, error)

func (*TableMeta[T]) FetchMapped added in v0.2.9

func (t *TableMeta[T]) FetchMapped(ctx context.Context, where any, key string, opts ...*FetchOptions) (map[string]*T, error)

func (*TableMeta[T]) FetchOne

func (t *TableMeta[T]) FetchOne(ctx context.Context, target *T, where any, opts ...*FetchOptions) error

func (*TableMeta[T]) Get added in v0.1.8

func (t *TableMeta[T]) Get(ctx context.Context, where any, opts ...*FetchOptions) (*T, error)

func (*TableMeta[T]) HasChanged added in v0.1.2

func (t *TableMeta[T]) HasChanged(obj *T) bool

func (*TableMeta[T]) Insert

func (t *TableMeta[T]) Insert(ctx context.Context, targets ...*T) error

func (*TableMeta[T]) InsertIgnore added in v0.1.7

func (t *TableMeta[T]) InsertIgnore(ctx context.Context, targets ...*T) error

func (*TableMeta[T]) Name

func (t *TableMeta[T]) Name() string

func (*TableMeta[T]) Replace added in v0.1.7

func (t *TableMeta[T]) Replace(ctx context.Context, targets ...*T) error

func (*TableMeta[T]) ScanTo

func (t *TableMeta[T]) ScanTo(row *sql.Rows, v *T) error

func (*TableMeta[T]) Update added in v0.1.4

func (t *TableMeta[T]) Update(ctx context.Context, target ...*T) error

type TableMetaIntf added in v0.1.2

type TableMetaIntf interface {
	Name() string
}

type TxProxy added in v0.1.17

type TxProxy struct {
	*sql.Tx
	// contains filtered or unexported fields
}

func BeginTx added in v0.1.10

func BeginTx(ctx context.Context, opts *sql.TxOptions) (*TxProxy, error)

func (*TxProxy) BeginTx added in v0.1.17

func (t *TxProxy) BeginTx(ctx context.Context, opts *sql.TxOptions) (*TxProxy, error)

func (*TxProxy) Commit added in v0.1.17

func (tx *TxProxy) Commit() error

func (*TxProxy) Rollback added in v0.1.17

func (tx *TxProxy) Rollback() error

type WhereAND

type WhereAND []any

func (WhereAND) EscapeValue

func (w WhereAND) EscapeValue() string

func (WhereAND) String

func (w WhereAND) String() string

type WhereOR

type WhereOR []any

func (WhereOR) EscapeValue

func (w WhereOR) EscapeValue() string

func (WhereOR) String

func (w WhereOR) String() string

Jump to

Keyboard shortcuts

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