psql

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2023 License: MIT Imports: 16 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"`
}

// ...

var obj = &Table1{}
err := psql.FetchOne(nil, obj, 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 ErrNotNillable = errors.New("field is nil but cannot be nil")
View Source
var FormatTableName = formatCamelSnakeCase

Functions

func BeginTx added in v0.1.10

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

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 *sql.Tx) context.Context

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 Exec

func Exec(q *SQLQuery) error

Exec simply runs a query against the database

func Fetch

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

func FetchOne

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

func Get added in v0.1.8

func Get[T any](ctx context.Context, where map[string]any) (*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 starts the database pool and allows all other methods in psql to work

func InitCfg added in v0.1.5

func InitCfg(cfg *mysql.Config) error

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 Raw

func Raw(s string) any

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

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

func Equal

func Equal(a, b any) *Comparison

func (*Comparison) EscapeValue

func (c *Comparison) EscapeValue() string

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

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

type QueryBuilder struct {
	Query     string
	Fields    []any
	Tables    []EscapeTableable
	FieldsSet []any
	WhereData WhereAND
	GroupBy   []any
	OrderBy   []any
	Limit     []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) 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) Render

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

func (*QueryBuilder) Replace

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

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 struct {
	K, V any
}

func (*Set) EscapeValue

func (s *Set) EscapeValue() string

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 TableMeta

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

func Table

func Table[T any]() *TableMeta[T]

func (*TableMeta[T]) Fetch

func (t *TableMeta[T]) Fetch(ctx context.Context, where map[string]interface{}) ([]*T, error)

func (*TableMeta[T]) FetchOne

func (t *TableMeta[T]) FetchOne(ctx context.Context, target *T, where map[string]interface{}) error

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

func (t *TableMeta[T]) Get(ctx context.Context, where map[string]interface{}) (*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 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