psql

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: MIT Imports: 33 Imported by: 0

README

Go Reference

psql

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

This works in some ways similar to gorm but with focus on supporting and using modern Go syntax & features.

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
Enum Support

The library supports SQL ENUM types with different implementations for MySQL and PostgreSQL:

type StatusEnum string

const (
    StatusPending  StatusEnum = "pending"
    StatusActive   StatusEnum = "active"
    StatusInactive StatusEnum = "inactive"
)

type MyTable struct {
    ID     uint64     `sql:",key=PRIMARY"`
    Status StatusEnum `sql:",type=enum,values=pending,active,inactive"`
}

In MySQL, this creates a standard ENUM column.

In PostgreSQL, this creates a custom type named according to the EnumTypeName method of the configured Namer (default: enum_tablename_columnname) and automatically handles type creation and column mapping.

go 1.23

New go 1.23 iterators can be used

res, err := psql.Iter[Table1](context.Background(), map[string]any{"Type": "A"}) // this fetches entries with Type=A
if err != nil {
    return err
}
for v := range res {
    // v is of type *Table1
}

Query builder

The query builder provides a fluent interface for constructing SQL queries programmatically. It supports SELECT, INSERT, UPDATE, DELETE, and REPLACE operations with full support for WHERE clauses, JOINs, ORDER BY, LIMIT, and more.

Basic Usage

Start building a query with psql.B():

// Simple SELECT
query := psql.B().Select("name", "email").From("users")

// SELECT with WHERE clause
query := psql.B().Select().From("users").Where(map[string]any{"status": "active"})

// UPDATE
query := psql.B().Update("users").Set(map[string]any{"status": "inactive"}).Where(map[string]any{"id": 123})

// DELETE
query := psql.B().Delete().From("users").Where(map[string]any{"id": 123})
Helper Functions

The library provides helper functions for working with SQL identifiers and values:

  • psql.F("field") - Field reference (column name)
  • psql.V("value") - Value literal
  • psql.S("field", "ASC") - Sort field with direction
  • psql.Raw("SQL") - Raw SQL injection (use carefully)
WHERE Conditions

The query builder supports various WHERE condition operators:

// Equality
query := psql.B().Select().From("users").Where(map[string]any{"id": 123})

// Using comparison operators
query := psql.B().Select().From("users").Where(psql.Gte(psql.F("age"), 18))

// LIKE operator
query := psql.B().Select().From("users").Where(&psql.Like{psql.F("name"), "John%"})

// IS NULL / IS NOT NULL
query := psql.B().Select().From("users").Where(map[string]any{"deleted_at": nil})

// Complex conditions with OR
query := psql.B().Select().From("users").Where(map[string]any{
    "status": psql.WhereOR{"active", "pending"},
})

// Multiple conditions (AND)
query := psql.B().Select().From("users").Where(
    psql.Equal(psql.F("status"), "active"),
    psql.Gte(psql.F("age"), 18),
)
Comparison Operators

Available comparison functions:

  • psql.Equal(field, value) - Equality (=)
  • psql.Lt(field, value) - Less than (<)
  • psql.Lte(field, value) - Less than or equal (<=)
  • psql.Gt(field, value) - Greater than (>)
  • psql.Gte(field, value) - Greater than or equal (>=)
  • psql.WhereOR{value1, value2, ...} - OR conditions for the same field
Advanced Features
ORDER BY and LIMIT
query := psql.B().Select().From("users").
    OrderBy(psql.S("created_at", "DESC"), psql.S("name", "ASC")).
    Limit(10, 20) // limit 10, offset 20
// Renders as "LIMIT 10, 20" for MySQL
// Renders as "LIMIT 10 OFFSET 20" for PostgreSQL
Raw SQL

For complex queries, you can inject raw SQL:

query := psql.B().Select(psql.Raw("COUNT(DISTINCT user_id)")).From("orders")
Aggregate Functions
// COUNT
query := psql.B().Select(psql.Raw("COUNT(*)")).From("users")

// GROUP BY with HAVING
query := psql.B().Select("status", psql.Raw("COUNT(*) as count")).
    From("users").
    Where(psql.Raw("created_at > NOW() - INTERVAL '1 day'"))
Executing Queries

The query builder provides several methods to execute the built query:

// Get the SQL string
sql, err := query.Render(ctx)

// Get SQL with placeholders and arguments (for prepared statements)
sql, args, err := query.RenderArgs(ctx)

// Execute a query that returns rows (SELECT)
rows, err := query.RunQuery(ctx)
defer rows.Close()

// Execute a query that doesn't return rows (INSERT, UPDATE, DELETE)
result, err := query.ExecQuery(ctx)

// Prepare a statement for repeated execution
stmt, err := query.Prepare(ctx)
defer stmt.Close()
Complete Examples
// Find active users older than 18, ordered by name
users := psql.B().
    Select("id", "name", "email").
    From("users").
    Where(
        psql.Equal(psql.F("status"), "active"),
        psql.Gt(psql.F("age"), 18),
    ).
    OrderBy(psql.S("name", "ASC")).
    Limit(50)

// Update user's last login time
update := psql.B().
    Update("users").
    Set(map[string]any{
        "last_login": time.Now(),
        "login_count": psql.Raw("login_count + 1"),
    }).
    Where(map[string]any{"id": userID})

// Complex search with LIKE and OR conditions
search := psql.B().
    Select().
    From("products").
    Where(map[string]any{
        "status": "available",
        "name": &psql.Like{psql.F("name"), "%" + searchTerm + "%"},
        "category_id": psql.WhereOR{1, 2, 3},
    }).
    OrderBy(psql.S("price", "ASC"))

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")
	ErrBreakLoop          = errors.New("exiting loop (not an actual error, used to break out of loop callbacks)")
)
View Source
var FetchLock = &FetchOptions{Lock: true}
View Source
var FormatTableName = formatCamelSnakeCase

FormatTableName is a variable that holds the default table name formatter. It defaults to formatCamelSnakeCase but can be overridden. This is kept for backwards compatibility - new code should use Backend.Namer.

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 DefineMagicTypeEngine added in v0.4.1

func DefineMagicTypeEngine(e Engine, 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 deprecated

func Exec(q *SQLQuery) error

Exec simply runs a query against the DefaultBackend

Deprecated: use .Exec() instead

func ExecContext added in v0.4.1

func ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func Factory added in v0.3.6

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

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

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 GenerateEnumCheckSQL added in v0.4.1

func GenerateEnumCheckSQL(constraint *EnumConstraint, tableName string) string

GenerateEnumCheckSQL generates the CHECK constraint SQL for enum columns According to PGSQL.md, it should create a single constraint that validates all columns with the same enum values This is exported for testing purposes

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 GetEnumConstraintName added in v0.4.1

func GetEnumConstraintName(values string) string

GetEnumConstraintName generates a deduplicated constraint name based on the hash of the values It is exported for testing purposes but should generally not be used directly

func GetEnumTypeName added in v0.4.1

func GetEnumTypeName(values string) string

GetEnumTypeName is kept for backward compatibility but returns the constraint name

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 Iter added in v0.4.1

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

func Query deprecated

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 { ... })

Deprecated: use .Each() instead

func QueryContext deprecated

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

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

Deprecated: use .Each() instead

func QuoteName

func QuoteName(v string) string

quote a name (field, etc) This doesn't use the Namer since this is just for escaping a name that's already been formatted

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 slog package:

psql.SetLogger(slog.Default())

Or a better option:

psql.SetLogger(slog.Default().With("backend", "psql")) etc...

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 LocalTestServer added in v0.4.1

func LocalTestServer() (*Backend, error)

LocalTestServer returns a backend that can be used for local tests, especially suitable for Go unit tests

This requires having cockroach or apkg installed in order to run, and will start a local database with in-memory storage that will shutdown at the end of the tests. The database will always start in an empty state, and all data written to it will be lost once the execution completes.

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) Engine added in v0.4.1

func (be *Backend) Engine() Engine

func (*Backend) Namer added in v0.4.1

func (be *Backend) Namer() Namer

Namer returns the configured naming strategy

func (*Backend) Plug added in v0.4.0

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

func (*Backend) SetNamer added in v0.4.1

func (be *Backend) SetNamer(n Namer)

SetNamer allows changing the naming strategy Use DefaultNamer to keep names exactly as defined in structs (e.g., "HelloWorld" stays "HelloWorld") Use LegacyNamer (default) for backward compatibility (e.g., "HelloWorld" becomes "Hello_World") Use CamelSnakeNamer to convert all names to Camel_Snake_Case

type CamelSnakeNamer added in v0.4.1

type CamelSnakeNamer struct{}

CamelSnakeNamer is a namer that converts names to Camel_Snake_Case

func (CamelSnakeNamer) CheckerName added in v0.4.1

func (CamelSnakeNamer) CheckerName(table, column string) string

CheckerName returns the checker name with table and column in Camel_Snake_Case format

func (CamelSnakeNamer) ColumnName added in v0.4.1

func (CamelSnakeNamer) ColumnName(table, column string) string

ColumnName returns the column name in Camel_Snake_Case format

func (CamelSnakeNamer) EnumTypeName added in v0.4.1

func (CamelSnakeNamer) EnumTypeName(table, column string) string

EnumTypeName returns the enum type name with table and column in Camel_Snake_Case format

func (CamelSnakeNamer) IndexName added in v0.4.1

func (CamelSnakeNamer) IndexName(table, column string) string

IndexName returns the index name with table and column in Camel_Snake_Case format

func (CamelSnakeNamer) JoinTableName added in v0.4.1

func (CamelSnakeNamer) JoinTableName(joinTable string) string

JoinTableName returns the join table name in Camel_Snake_Case format

func (CamelSnakeNamer) SchemaName added in v0.4.1

func (CamelSnakeNamer) SchemaName(table string) string

SchemaName returns the schema name in Camel_Snake_Case format

func (CamelSnakeNamer) TableName added in v0.4.1

func (CamelSnakeNamer) TableName(table string) string

TableName returns the table name in Camel_Snake_Case format

func (CamelSnakeNamer) UniqueName added in v0.4.1

func (CamelSnakeNamer) UniqueName(table, column string) string

UniqueName returns the unique constraint name with table and column in Camel_Snake_Case format

type Comparison

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

func (*Comparison) EscapeValue

func (c *Comparison) EscapeValue() string

type DefaultNamer added in v0.4.1

type DefaultNamer struct{}

DefaultNamer is a namer that returns names as they are provided

func (DefaultNamer) CheckerName added in v0.4.1

func (DefaultNamer) CheckerName(table, column string) string

CheckerName returns the checker name as is

func (DefaultNamer) ColumnName added in v0.4.1

func (DefaultNamer) ColumnName(table, column string) string

ColumnName returns the column name as is

func (DefaultNamer) EnumTypeName added in v0.4.1

func (DefaultNamer) EnumTypeName(table, column string) string

EnumTypeName returns the enum type name using original table and column names

func (DefaultNamer) IndexName added in v0.4.1

func (DefaultNamer) IndexName(table, column string) string

IndexName returns the index name as is

func (DefaultNamer) JoinTableName added in v0.4.1

func (DefaultNamer) JoinTableName(joinTable string) string

JoinTableName returns the join table name as is

func (DefaultNamer) SchemaName added in v0.4.1

func (DefaultNamer) SchemaName(table string) string

SchemaName returns the schema name as is

func (DefaultNamer) TableName added in v0.4.1

func (DefaultNamer) TableName(table string) string

TableName returns the table name as is

func (DefaultNamer) UniqueName added in v0.4.1

func (DefaultNamer) UniqueName(table, column string) string

UniqueName returns the unique constraint name as is

type Engine added in v0.4.0

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

func (Engine) String added in v0.4.1

func (e Engine) String() string

type EnumConstraint added in v0.4.1

type EnumConstraint struct {
	Name    string              // Constraint name (chk_enum_XXXXXXXX)
	Values  []string            // Allowed enum values
	Columns map[string][]string // Map of table -> columns using this constraint
}

EnumConstraint represents a CHECK constraint for enum columns

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 Join added in v0.4.1

type Join struct {
	Table     string
	Condition string // condition for join
	Type      string // LEFT|INNER|RIGHT
	Alias     string // if any
}

func (*Join) JoinTable added in v0.4.1

func (j *Join) JoinTable(ctx context.Context) string

JoinTable returns the formatted table name using the namer if available

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 LegacyNamer added in v0.4.1

type LegacyNamer struct{}

LegacyNamer reproduces the behavior of the original implementation: - Table names use CamelSnakeCase - Column names are kept as is (no transformation) - Other names use standard prefixes with the original names

func (LegacyNamer) CheckerName added in v0.4.1

func (LegacyNamer) CheckerName(table, column string) string

CheckerName returns the checker name with table in Camel_Snake_Case format and original column name

func (LegacyNamer) ColumnName added in v0.4.1

func (LegacyNamer) ColumnName(table, column string) string

ColumnName returns the column name as is (no transformation)

func (LegacyNamer) EnumTypeName added in v0.4.1

func (LegacyNamer) EnumTypeName(table, column string) string

EnumTypeName returns the enum type name with table in Camel_Snake_Case format and original column name

func (LegacyNamer) IndexName added in v0.4.1

func (LegacyNamer) IndexName(table, column string) string

IndexName returns the index name with table in Camel_Snake_Case format and original column name

func (LegacyNamer) JoinTableName added in v0.4.1

func (LegacyNamer) JoinTableName(joinTable string) string

JoinTableName returns the join table name in Camel_Snake_Case format

func (LegacyNamer) SchemaName added in v0.4.1

func (LegacyNamer) SchemaName(table string) string

SchemaName returns the schema name in Camel_Snake_Case format

func (LegacyNamer) TableName added in v0.4.1

func (LegacyNamer) TableName(table string) string

TableName returns the table name in Camel_Snake_Case format (original behavior)

func (LegacyNamer) UniqueName added in v0.4.1

func (LegacyNamer) UniqueName(table, column string) string

UniqueName returns the unique constraint name with table in Camel_Snake_Case format and original column name

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 Namer added in v0.4.1

type Namer interface {
	TableName(table string) string
	SchemaName(table string) string
	ColumnName(table, column string) string
	JoinTableName(joinTable string) string
	CheckerName(table, column string) string
	IndexName(table, column string) string
	UniqueName(table, column string) string
	EnumTypeName(table, column string) string // For PostgreSQL ENUM types
}

Namer is an object that provides names to functions. This is based on gorm

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 PGYesOrNo added in v0.4.1

type PGYesOrNo string

func (PGYesOrNo) V added in v0.4.1

func (p PGYesOrNo) V() bool

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(ctx context.Context) (string, error)

func (*QueryBuilder) RenderArgs added in v0.2.0

func (q *QueryBuilder) RenderArgs(ctx context.Context) (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

func (*SQLQuery) Each added in v0.4.1

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

Each will execute the query and call cb for each row, so you do not need to call .Next() or .Close() on the object.

Example use: err := psql.Q("SELECT ...").Each(ctx, func(row *sql.Rows) error { ... })

func (*SQLQuery) Exec added in v0.4.1

func (q *SQLQuery) Exec(ctx context.Context) error

Exec simply executes the query and returns any error that could have happened

type SQLQueryT added in v0.4.1

type SQLQueryT[T any] struct {
	Query string
	Args  []any
}

func QT added in v0.4.1

func QT[T any](q string, args ...any) *SQLQueryT[T]

QT is a short hand to create a Query object against a specific table

func (*SQLQueryT[T]) All added in v0.4.1

func (q *SQLQueryT[T]) All(ctx context.Context) ([]*T, error)

All will execute the query and return all the results

func (*SQLQueryT[T]) Each added in v0.4.1

func (q *SQLQueryT[T]) Each(ctx context.Context, cb func(*T) error) error

Each will execute the query and call cb for each row

func (*SQLQueryT[T]) Single added in v0.4.1

func (q *SQLQueryT[T]) Single(ctx context.Context) (*T, error)

Single will execute the query and fetch a single result

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 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]() *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(ctx context.Context) *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]) FormattedName added in v0.4.1

func (t *TableMeta[T]) FormattedName(be *Backend) string

FormattedName returns the table name, applying the namer transformation if needed

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]) Iter added in v0.4.1

func (t *TableMeta[T]) Iter(ctx context.Context, where any, opts ...*FetchOptions) (func(func(v *T) bool), 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