sq

package
v0.0.17 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2024 License: MIT Imports: 17 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DialectSQLite    = "sqlite"
	DialectPostgres  = "postgres"
	DialectMySQL     = "mysql"
	DialectSQLServer = "sqlserver"
)

Dialects supported.

Variables

This section is empty.

Functions

func EscapeQuote

func EscapeQuote(str string, quote byte) string

EscapeQuote will escape the relevant quote in a string by doubling up on it (as per SQL rules).

func FetchAll

func FetchAll[T any](ctx context.Context, db DB, query Query, rowmapper func(*Row) T) ([]T, error)

FetchAll returns all results from running the given Query on the given DB.

func FetchExists

func FetchExists(ctx context.Context, db DB, query Query) (exists bool, err error)

FetchExists returns a boolean indicating if running the given Query on the given DB returned any results.

func FetchOne

func FetchOne[T any](ctx context.Context, db DB, query Query, rowmapper func(*Row) T) (T, error)

FetchOne returns the first result from running the given Query on the given DB.

func ParseBytes

func ParseBytes(b []byte) (uuid [16]byte, err error)

ParseBytes decodes b into a UUID or returns an error. Both the UUID form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.

func QuoteIdentifier

func QuoteIdentifier(dialect string, identifier string) string

QuoteIdentifier quotes an identifier if necessary using dialect-specific quoting rules.

func Sprint

func Sprint(dialect string, v any) (string, error)

Sprint is the equivalent of Sprintf but for converting a single value into its SQL representation.

func Sprintf

func Sprintf(dialect string, query string, args []any) (string, error)

Sprintf will interpolate SQL args into a query string containing prepared statement parameters. It returns an error if an argument cannot be properly represented in SQL.

func UUID

func UUID(value [16]byte) driver.Valuer

UUIDValue takes in a type whose underlying type must be a [16]byte and returns a driver.Valuer.

func WriteValue

func WriteValue(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, value any) error

WriteValue is the equivalent of Writef but for writing a single value into the Output.

func Writef

func Writef(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, format string, values []any) error

Writef is a fmt.Sprintf-style function that will write a format string and values slice into an Output. The only recognized placeholder is '{}'. Placeholders can be anonymous (e.g. {}), ordinal (e.g. {1}, {2}, {3}) or named (e.g. {name}, {email}, {age}).

- Anonymous placeholders refer to successive values in the values slice. Anonymous placeholders are treated like a series of incrementing ordinal placeholders.

- Ordinal placeholders refer to a specific value in the values slice using 1-based indexing.

- Named placeholders refer to their corresponding sql.NamedArg value in the values slice. If there are multiple sql.NamedArg values with the same name, the last one wins.

If a value is an SQLWriter, its WriteSQL method will be called. Else if a value is a slice, it will undergo slice expansion (https://bokwoon.neocities.org/sq.html#value-expansion). Otherwise, the value is added to the query args slice.

Types

type Cursor

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

A Cursor represents a database cursor.

func FetchCursor

func FetchCursor[T any](ctx context.Context, db DB, query Query, rowmapper func(*Row) T) (cursor *Cursor[T], err error)

FetchCursor returns a new cursor.

func (*Cursor[T]) Close

func (cursor *Cursor[T]) Close() error

Close closes the cursor.

func (*Cursor[T]) Next

func (cursor *Cursor[T]) Next() bool

Next advances the cursor to the next result.

func (*Cursor[T]) Result

func (cursor *Cursor[T]) Result() (result T, err error)

Result returns the cursor result.

type DB

type DB interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

DB is a database/sql abstraction that can query the database. *sql.Conn, *sql.DB and *sql.Tx all implement DB.

type DialectCase

type DialectCase struct {
	Dialect string
	Result  any
}

type DialectExpression

type DialectExpression struct {
	Default any
	Cases   []DialectCase
}

func (DialectExpression) WriteSQL

func (e DialectExpression) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error

WriteSQL implements the SQLWriter interface.

type DialectValuer

type DialectValuer interface {
	DialectValuer(dialect string) (driver.Valuer, error)
}

DialectValuer is any type that will yield a different driver.Valuer depending on the SQL dialect.

type Expression

type Expression struct {
	Format string
	Values []any
}

Expression represents an SQL expression.

func Expr

func Expr(format string, values ...any) Expression

Expr creates a new Expression using Writef syntax.

func (Expression) Append

func (expr Expression) Append(format string, values ...any) Expression

func (Expression) WriteSQL

func (expr Expression) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error

WriteSQL implements the SQLWriter interface.

type Parameter

type Parameter sql.NamedArg

Parameter is identical to sql.NamedArg, but implements the Field interface.

func BoolParam

func BoolParam(name string, b bool) Parameter

BoolParam creates a new Parameter from a bool value.

func BytesParam

func BytesParam(name string, b []byte) Parameter

BytesParam creates a new Parameter using a []byte value.

func Float64Param

func Float64Param(name string, num float64) Parameter

Float64Param creates a new NumberParameter from an float64 value.

func Int64Param

func Int64Param(name string, num int64) Parameter

Int64Param creates a new Parameter from an int64 value.

func IntParam

func IntParam(name string, num int) Parameter

IntParam creates a new Parameter from an int value.

func Param

func Param(name string, value any) Parameter

Param creates a new Parameter.

func StringParam

func StringParam(name string, s string) Parameter

StringParam creates a new Parameter from a string value.

func TimeParam

func TimeParam(name string, t time.Time) Parameter

TimeParam creates a new Parameter from a time.Time value.

func UUIDParam

func UUIDParam(name string, value [16]byte) Parameter

UUIDParam creates a new Parameter. It wraps the value with UUID().

func (Parameter) WriteSQL

func (p Parameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error

WriteSQL implements the SQLWriter interface.

type PreparedExec

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

PreparedExec represents a exec query that wraps an explicitly-prepared *sql.Stmt. Such a query can be run for different prepared statement parameters without having to re-prepare the query in the database.

func PrepareExec

func PrepareExec(ctx context.Context, db DB, query Query) (*PreparedExec, error)

PrepareExec takes a database instance + query and converts it to a PreparedExec.

func (*PreparedExec) Close

func (preparedExec *PreparedExec) Close() error

Close closes the PreparedExec.

func (*PreparedExec) Exec

func (preparedExec *PreparedExec) Exec(ctx context.Context, params ...Parameter) (Result, error)

Exec executes the PreparedExec with the given params.

type PreparedFetch

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

PreparedFetch represents a fetch query that wraps an explicitly-prepared *sql.Stmt. Such a query can be run for different prepared statement parameters without having to re-prepare the query in the database.

func PrepareFetch

func PrepareFetch[T any](ctx context.Context, db DB, query Query, rowmapper func(*Row) T) (preparedFetch *PreparedFetch[T], err error)

PrepareFetch takes a database instance + query + rowmapper and converts it to a PreparedFetch.

func (*PreparedFetch[T]) Close

func (preparedFetch *PreparedFetch[T]) Close() error

Close closes the PreparedFetch.

func (*PreparedFetch[T]) FetchAll

func (preparedFetch *PreparedFetch[T]) FetchAll(ctx context.Context, params ...Parameter) ([]T, error)

FetchAll returns all the results from running the PreparedFetch with the given params.

func (*PreparedFetch[T]) FetchCursor

func (preparedFetch *PreparedFetch[T]) FetchCursor(ctx context.Context, params ...Parameter) (cursor *Cursor[T], err error)

FetchCursor fetches runs the PreparedFetch with the given params and returns a database cursor.

func (*PreparedFetch[T]) FetchOne

func (preparedFetch *PreparedFetch[T]) FetchOne(ctx context.Context, params ...Parameter) (T, error)

FetchOne returns the first result from running the PreparedFetch with the given params.

type Query

type Query struct {
	Dialect string // Database dialect.
	Format  string // Query format string.
	Values  []any  // Query values.
	Debug   bool   // If Debug is true, the query is logged to console.
}

Query represents a database query.

func (Query) Append

func (query Query) Append(format string, values ...any) Query

Append appends the format string and values slice to the query.

type Result

type Result struct {
	LastInsertId int64
	RowsAffected int64
}

Result is the result of an Exec command.

func Exec

func Exec(ctx context.Context, db DB, query Query) (Result, error)

Exec executes the given Query on the given DB.

type Row

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

Row represents the state of a row after a call to rows.Next().

func (*Row) Bool

func (row *Row) Bool(format string, values ...any) bool

Bool returns the bool value of the expression.

func (*Row) Bytes

func (row *Row) Bytes(b []byte, format string, values ...any) []byte

Bytes returns the []byte value of the expression.

If an existing byte slice is provided, it appends into to that slice (allowing for byte slices to be reused). It returns a nil slice if the expression is NULL, unless a byte slice was provided in which case it returns the same byte slice but with its length truncated to 0.

func (*Row) Float64

func (row *Row) Float64(format string, values ...any) float64

Float64 returns the float64 value of the expression.

func (*Row) Int

func (row *Row) Int(format string, values ...any) int

Int returns the int value of the expression.

func (*Row) Int64

func (row *Row) Int64(format string, values ...any) int64

Int64 returns the int64 value of the expression.

func (*Row) NullBool

func (row *Row) NullBool(format string, values ...any) sql.NullBool

NullBool returns the sql.NullBool value of the expression.

func (*Row) NullFloat64

func (row *Row) NullFloat64(format string, values ...any) sql.NullFloat64

NullFloat64 returns the sql.NullFloat64 valye of the expression.

func (*Row) NullInt64

func (row *Row) NullInt64(format string, values ...any) sql.NullInt64

NullInt64 returns the sql.NullInt64 value of the expression.

func (*Row) NullString

func (row *Row) NullString(format string, values ...any) sql.NullString

NullString returns the sql.NullString value of the expression.

func (*Row) NullTime

func (row *Row) NullTime(format string, values ...any) sql.NullTime

NullTime returns the sql.NullTime value of the expression.

func (*Row) Scan

func (row *Row) Scan(destPtr any, format string, values ...any)

Scan scans the expression into destPtr.

func (*Row) String

func (row *Row) String(format string, values ...any) string

String returns the string value of the expression.

func (*Row) Time

func (row *Row) Time(format string, values ...any) time.Time

Time returns the time.Time value of the expression.

func (*Row) UUID

func (row *Row) UUID(format string, values ...any) [16]byte

UUID scans the UUID expression into destPtr.

type SQLWriter

type SQLWriter interface {
	// WriteSQL writes the SQL representation of the SQLWriter into the query
	// string (*bytes.Buffer) and args slice (*[]any).
	//
	// The params map is used to hold the mappings between named parameters in
	// the query to the corresponding index in the args slice and is used for
	// rebinding args by their parameter name. The params map may be nil, check
	// first before writing to it.
	WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error
}

SQLWriter is anything that can be converted to SQL.

type Timestamp

type Timestamp struct {
	time.Time
	Valid bool
	// contains filtered or unexported fields
}

Timestamp is as a replacement for sql.NullTime but with the following enhancements:

1. Timestamp.Value() returns an int64 unix timestamp if the dialect is SQLite, otherwise it returns a time.Time (similar to sql.NullTime).

2. Timestamp.Scan() additionally supports scanning from int64 and text (string/[]byte) values on top of what sql.NullTime already supports. The following text timestamp formats are supported:

var timestampFormats = []string{
	"2006-01-02 15:04:05.999999999-07:00",
	"2006-01-02T15:04:05.999999999-07:00",
	"2006-01-02 15:04:05.999999999",
	"2006-01-02T15:04:05.999999999",
	"2006-01-02 15:04:05",
	"2006-01-02T15:04:05",
	"2006-01-02 15:04",
	"2006-01-02T15:04",
	"2006-01-02",
}

func NewTimestamp

func NewTimestamp(t time.Time) *Timestamp

func (*Timestamp) DialectValuer

func (ts *Timestamp) DialectValuer(dialect string) (driver.Valuer, error)

DialectValuer implements the DialectValuer interface.

func (*Timestamp) Scan

func (ts *Timestamp) Scan(value any) error

Scan implements the sql.Scanner interface. It additionally supports scanning from int64 and text (string/[]byte) values on top of what sql.NullTime already supports. The following text timestamp formats are supported:

var timestampFormats = []string{
	"2006-01-02 15:04:05.999999999-07:00",
	"2006-01-02T15:04:05.999999999-07:00",
	"2006-01-02 15:04:05.999999999",
	"2006-01-02T15:04:05.999999999",
	"2006-01-02 15:04:05",
	"2006-01-02T15:04:05",
	"2006-01-02 15:04",
	"2006-01-02T15:04",
	"2006-01-02",
}

func (*Timestamp) Value

func (ts *Timestamp) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns an int64 unix timestamp if the dialect is SQLite, otherwise it returns a time.Time (similar to sql.NullTime).

Jump to

Keyboard shortcuts

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