Documentation
¶
Overview ¶
Package xdb provides the building blocks of SQL services on database/sql.
- Provider: a connection opened by NewProvider, which can run the migrations first, with transactions (BeginTx) and snowflake IDs (NextID).
- Value types whose zero value is SQL NULL: ID, ID32, Int64, Int32, Float, Bool, NULLString, UUID, Time, Metadata, KVSet and Strings.
- QueryParams: the variant name and positional arguments of a query whose SQL is built once with xsql and cached under that name.
- QueryRow, QueryRows, ExecuteQuery, ExecuteQueryWithPagination and ExecuteQueryWithCursor: run SQL into the models that xdbcli generates.
- Cursor: the opaque token of keyset pagination, built with NewCursor from the sort key of the last row and read back with ParseCursor.
In a service, with the generated model and schema packages and a query package of SQL functions:
p, err := xdb.NewProvider("postgres://u:p@localhost:5432?sslmode=disable", "mydb", nil, nil)
if err != nil {
return err
}
defer p.Close()
q, _ := query.GetUserByID()
u, err := xdb.QueryRow[model.User](ctx, p, q, id)
if err != nil {
return xdb.CheckNotFoundError(err, schema.UserTableInfo.Name, id)
}
Documentation/design/QUERYBUILDER.md describes the query patterns and Documentation/design/SCHEMA_GENERATOR.md the generator.
Index ¶
- Constants
- Variables
- func CheckNotFoundError(err error, table string, id any) error
- func DecodeCursor(cursor string) (values.MapAny, error)deprecated
- func EncodeCursor(val values.MapAny) stringdeprecated
- func ExecuteListQuery[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) ([]TPointer, error)
- func ExecuteQuery[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, res Result[T, TPointer], query string, ...) error
- func ExecuteQueryWithCursor[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, cursor SetCursor[T, TPointer], ...) error
- func ExecuteQueryWithPagination[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, res Result[T, TPointer], query string, ...) error
- func IDString(id uint64) string
- func Int32Array[E Enum](list []E) pq.Int32Array
- func Int64Array(list []uint64) pq.Int64Array
- func IsNotFoundError(err error) bool
- func Merge(dst any, src any) error
- func NewErrorNotFound(err error, table string, id any) error
- func NullTime(val *time.Time) sql.NullTime
- func Open(dataSource, database string) (*sql.DB, string, string, error)
- func PageParam(p any) uint32
- func ParseUint(id string) (uint64, error)
- func QueryRow[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) (TPointer, error)
- func QueryRows[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) iter.Seq2[TPointer, error]
- func QuotedIDString(id uint64) string
- func QuotedString(val *string) string
- func String(val *string) string
- func TimePtr(val Time) *time.Time
- func Validate(m any) error
- type Bool
- type Cursor
- type DB
- type Enum
- type ErrorNotFound
- type Float
- type HasQueryParams
- type ID
- func (v ID) Invalid() bool
- func (v ID) IsZero() bool
- func (v ID) MarshalJSON() ([]byte, error)
- func (v ID) MarshalYAML() (any, error)
- func (v ID) QuotedString() string
- func (v *ID) Reset()
- func (v *ID) Scan(value any) error
- func (v *ID) Set(val string) error
- func (v ID) String() string
- func (v ID) UInt64() uint64
- func (v ID) UnderscoreString() string
- func (v *ID) UnmarshalJSON(data []byte) error
- func (v *ID) UnmarshalYAML(unmarshal func(any) error) error
- func (v ID) Valid() bool
- func (v ID) Value() (driver.Value, error)
- type ID32
- type IDArray
- func (n IDArray) Add(id ID) IDArray
- func (n IDArray) Concat(other IDArray) IDArray
- func (n IDArray) Contains(id ID) bool
- func (n IDArray) Int64Array() pq.Int64Array
- func (n IDArray) List() []uint64
- func (n IDArray) Overlaps(other IDArray) bool
- func (n *IDArray) Scan(value any) error
- func (n IDArray) Sort() IDArray
- func (n IDArray) String() string
- func (n IDArray) Strings() []string
- func (n IDArray) Value() (driver.Value, error)
- type IDGenerator
- type Int32
- type Int64
- type KVSet
- type Metadata
- func (n Metadata) Keys() []string
- func (n *Metadata) Merge(m Metadata) *Metadata
- func (n Metadata) OrderedKeys() []string
- func (n Metadata) OrderedPairs() []string
- func (n Metadata) Range(f func(k string, v string) bool)
- func (n Metadata) RangeOrdered(f func(k string, v string) bool)
- func (n *Metadata) Scan(value any) error
- func (n Metadata) Value() (driver.Value, error)
- type MigrationConfig
- type NULLString
- type PageableByCursor
- type PageableByOffset
- type Provider
- type QueryParams
- type QueryParamsBuilder
- func (b *QueryParamsBuilder) AddArgs(v ...any) *QueryParamsBuilder
- func (b *QueryParamsBuilder) Args() []any
- func (b *QueryParamsBuilder) Cursor() (limit uint32, cursor any)
- func (b *QueryParamsBuilder) GetEnum(pos uint32) (int32, bool)
- func (b *QueryParamsBuilder) GetFlags() []int32
- func (b *QueryParamsBuilder) GetNullColumns() []string
- func (b *QueryParamsBuilder) IsSet(pos uint32) bool
- func (b *QueryParamsBuilder) Name() string
- func (b *QueryParamsBuilder) Page() (limit uint32, offset uint32)
- func (b *QueryParamsBuilder) Reset()
- func (b *QueryParamsBuilder) Set(pos uint32, v any) *QueryParamsBuilder
- func (b *QueryParamsBuilder) SetCursor(limit uint32, pos uint32, key ...any) *QueryParamsBuilder
- func (b *QueryParamsBuilder) SetEnum(pos uint32, v int32) *QueryParamsBuilder
- func (b *QueryParamsBuilder) SetFlags(v ...int32) *QueryParamsBuilder
- func (b *QueryParamsBuilder) SetNullColums(nullColumns []string) *QueryParamsBuilder
- func (b *QueryParamsBuilder) SetPage(limit, offset uint32) *QueryParamsBuilder
- type Result
- type ResultWithCursor
- type Row
- type RowPointer
- type RowScanner
- type Rows
- type SQLProvider
- func (p *SQLProvider) BeginTx(ctx context.Context, opts *sql.TxOptions) (Provider, error)
- func (p *SQLProvider) Close() (err error)
- func (p *SQLProvider) Commit() error
- func (p *SQLProvider) ConnectionString() string
- func (p *SQLProvider) DB() DB
- func (p *SQLProvider) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (p *SQLProvider) IDTime(id uint64) time.Time
- func (p *SQLProvider) Name() string
- func (p *SQLProvider) NextID() ID
- func (p *SQLProvider) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (p *SQLProvider) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (p *SQLProvider) Rollback() error
- func (p *SQLProvider) Tx() Tx
- func (p *SQLProvider) WithConnectionString(connstr string) *SQLProvider
- type SetCursor
- type Source
- type Strings
- type Time
- func (ns Time) Add(after time.Duration) Time
- func (ns Time) IsNil() bool
- func (ns Time) IsZero() bool
- func (ns Time) MarshalJSON() ([]byte, error)
- func (ns Time) Ptr() *time.Time
- func (ns *Time) Scan(value any) error
- func (ns Time) String() string
- func (ns Time) UTC() time.Time
- func (ns Time) UnixMilli() int64
- func (ns *Time) UnmarshalJSON(data []byte) error
- func (ns Time) Value() (driver.Value, error)
- type Tx
- type UUID
- type Validator
Constants ¶
const ( MaxLenForName = 64 MaxLenForEmail = 160 MaxLenForShortURL = 256 )
Max values, common for strings
const DefaultPageSize = 500
DefaultPageSize is the default page size
Variables ¶
var DefaultTimeFormat = "2006-01-02T15:04:05.999Z07:00"
DefaultTimeFormat is the default format for Time.String()
var DefaultTrucate = time.Millisecond
DefaultTrucate is the default time to truncate as Postgres time precision is default to 6 However, JavaScript and AWS accept time milliseconds only, 3 digits, so we truncate to 3
var MergeOpts = mergo.WithTransformers(transformers{})
MergeOpts is a mergo option to merge structs
Functions ¶
func CheckNotFoundError ¶ added in v0.23.108
func DecodeCursor
deprecated
added in
v0.17.76
func EncodeCursor
deprecated
added in
v0.17.76
func ExecuteListQuery ¶ added in v0.7.0
func ExecuteListQuery[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) ([]TPointer, error)
ExecuteListQuery runs a query and returns a list of models
func ExecuteQuery ¶ added in v0.16.72
func ExecuteQuery[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, res Result[T, TPointer], query string, args ...any) error
ExecuteQuery runs a query and populates the result with a list of models. args can be a QueryParams or a list of arguments
func ExecuteQueryWithCursor ¶ added in v0.17.76
func ExecuteQueryWithCursor[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, cursor SetCursor[T, TPointer], res ResultWithCursor[T, TPointer], query string, args ...any) error
ExecuteQueryWithCursor runs a query and populates the result with a list of models and the next cursor, if there are more rows to fetch. args can be a QueryParams or a list of arguments followed by the limit, with at least one argument before it; a query whose only argument is the limit passes QueryParams, such as NewQueryParams(name).SetCursor(limit, pos). The query runs with limit+1 bound in place of the limit, and the extra row, which is not returned, tells whether a next page exists; the LIMIT must therefore apply to the final, ordered result. A zero limit reports no next page.
func ExecuteQueryWithPagination ¶ added in v0.16.72
func ExecuteQueryWithPagination[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, res Result[T, TPointer], query string, args ...any) error
ExecuteQueryWithPagination runs a query and populates the result with a list of models and the next offset, if there are more rows to fetch. args can be a QueryParams or a list of arguments followed by the limit and offset. The query runs with limit+1 bound in place of the limit, and the extra row, which is not returned, tells whether a next page exists; the LIMIT must therefore apply to the final, ordered result. A zero limit reports no next page.
func Int32Array ¶ added in v0.23.116
func Int32Array[E Enum](list []E) pq.Int32Array
Int32Array returns pq.Int32Array
func Int64Array ¶ added in v0.17.77
func Int64Array(list []uint64) pq.Int64Array
Int64Array returns pq.Int64Array
func IsNotFoundError ¶
IsNotFoundError returns true, if error is NotFound
func NewErrorNotFound ¶ added in v0.23.108
func QueryRow ¶ added in v0.6.0
func QueryRow[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) (TPointer, error)
QueryRow runs a query and returns a single model
func QueryRows ¶ added in v1.0.166
func QueryRows[T any, TPointer RowPointer[T]](ctx context.Context, sql DB, query string, args ...any) iter.Seq2[TPointer, error]
QueryRows runs a query and yields its rows one at a time, each scanned into a new model, without collecting them in a slice:
for m, err := range xdb.QueryRows[model.Event](ctx, db, query, args...) {
if err != nil {
return err
}
...
}
The rows are closed when the loop ends, also on break. A query, scan or iteration error is yielded once, with a nil model, and ends the sequence.
func QuotedIDString ¶ added in v0.24.141
QuotedIDString returns string id
func QuotedString ¶ added in v0.24.141
QuotedString returns string
Types ¶
type Bool ¶ added in v0.8.0
type Bool bool
Bool represents SQL bool NULL
func (Bool) MarshalJSON ¶ added in v0.8.0
MarshalJSON implements json.Marshaler interface
func (*Bool) UnmarshalJSON ¶ added in v0.8.0
UnmarshalJSON implements the json.Unmarshaler interface.
type Cursor ¶ added in v1.0.166
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is the position of a keyset (seek) page: the sort key of the last row of the previous page, in ORDER BY order. Its String form is an opaque, URL-safe token for API clients; ParseCursor reads it back and Scan returns the typed key values, which the next page binds in its WHERE clause:
// ORDER BY created_at DESC, id DESC c, err := xdb.NewCursor(last.CreatedAt, last.ID) next := c.String() c, err = xdb.ParseCursor(next) var at xdb.Time var id xdb.ID err = c.Scan(&at, &id) // WHERE (created_at, id) < (?, ?)
The key keeps full precision: integers as decimal digits and times as RFC 3339 with nanoseconds, so rows that differ only in microseconds are not skipped. The zero Cursor is the first page.
func NewCursor ¶ added in v1.0.166
NewCursor returns the cursor that continues after a row with the given sort key values, in ORDER BY order. A key value is a Time, time.Time, an encoding.TextMarshaler (by value or pointer receiver), a type with an integer, unsigned, float, bool or string kind (ID, enums, NULLString, ...), or a pointer to one of them. A key type with custom text methods implements both MarshalText and UnmarshalText. NewCursor fails when MarshalText fails or a value has another type, so no token is issued that Scan cannot read back; keys of Time, integer and string types never fail.
func ParseCursor ¶ added in v1.0.166
ParseCursor decodes the String form of a cursor. An empty string is the zero cursor, which starts at the first page.
func (Cursor) IsZero ¶ added in v1.0.166
IsZero returns true for the zero cursor, which starts at the first page.
func (Cursor) Scan ¶ added in v1.0.166
Scan copies the sort key into dest, which must match it in number and order. A destination is a non-nil pointer to Time, time.Time, an encoding.TextUnmarshaler, or a type with an integer, unsigned, float, bool or string kind; text methods take precedence over the kind. A cursor that does not decode into dest returns an error, which a service reports as an invalid argument.
type DB ¶
type DB interface {
// QueryContext executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// QueryRowContext executes a query that is expected to return at most one row.
// QueryRowContext always returns a non-nil value. Errors are deferred until
// Row's Scan method is called.
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
// Otherwise, the *Row's Scan scans the first selected row and discards
// the rest.
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
// ExecContext executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
DB provides interface for Db operations It's an interface accepted by Query, QueryRow and Exec methods. Both sql.DB, sql.Conn and sql.Tx can be passed as DB interface.
type ErrorNotFound ¶ added in v0.23.108
func (*ErrorNotFound) Error ¶ added in v0.23.108
func (e *ErrorNotFound) Error() string
func (*ErrorNotFound) Is ¶ added in v0.23.108
func (e *ErrorNotFound) Is(target error) bool
Is implements the errors.Is interface to properly compare ErrorNotFound instances
func (*ErrorNotFound) Unwrap ¶ added in v0.23.108
func (e *ErrorNotFound) Unwrap() error
type Float ¶ added in v0.8.0
type Float float64
Float represents SQL float64 NULL
func (Float) MarshalJSON ¶ added in v0.8.0
MarshalJSON implements json.Marshaler interface
func (*Float) UnmarshalJSON ¶ added in v0.8.0
UnmarshalJSON implements the json.Unmarshaler interface.
type HasQueryParams ¶ added in v0.16.72
type HasQueryParams interface {
QueryParams() QueryParams
}
HasQueryParams is an interface for objects with query parameters.
type ID ¶
type ID uint64
ID defines a type to convert between internal uint64 and external string representations of ID. ID is a plain value type: copies are independent, safe for concurrent use, comparable with == and ordered with <. The zero value is invalid ID, and is stored as NULL in DB.
func TryParseID ¶ added in v0.8.0
TryParseID returns ID or empty if val is not valid ID
func (ID) MarshalJSON ¶
MarshalJSON implements json.Marshaler interface
func (ID) MarshalYAML ¶ added in v0.20.82
func (ID) QuotedString ¶ added in v0.24.141
QuotedString returns string
func (ID) UnderscoreString ¶ added in v0.24.141
UnderscoreString returns string with underscore prefix. This is useful for logs and metrics, where JS can't handle 64-bit numbers.
func (*ID) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
func (*ID) UnmarshalYAML ¶ added in v0.20.82
type ID32 ¶ added in v0.8.0
type ID32 uint32
ID32 defines a type to convert between internal uint32 and NULL values in DB
func (ID32) MarshalJSON ¶ added in v0.8.0
MarshalJSON implements json.Marshaler interface
func (*ID32) UnmarshalJSON ¶ added in v0.8.0
UnmarshalJSON implements the json.Unmarshaler interface.
type IDArray ¶
type IDArray []ID
IDArray defines a list of IDArray
func IDArrayFromStrings ¶ added in v0.20.86
IDArray returns IDArray
func NewIDArray ¶ added in v0.13.1
NewIDArray returns IDArray
func (IDArray) Int64Array ¶ added in v0.17.77
func (n IDArray) Int64Array() pq.Int64Array
Int64Array returns pq.Int64Array
func (IDArray) Overlaps ¶ added in v0.19.80
Overlaps returns true if any of the IDs in the list is in the other list
func (IDArray) String ¶ added in v0.16.75
String returns string representation of IDs, concatenated with comma
type IDGenerator ¶
type IDGenerator interface {
// NextID generates a next unique ID.
NextID() ID
IDTime(id uint64) time.Time
}
IDGenerator defines an interface to generate unique ID across the cluster
type Int32 ¶ added in v0.8.0
type Int32 int32
Int32 represents SQL int NULL
func (Int32) MarshalJSON ¶ added in v0.8.0
MarshalJSON implements json.Marshaler interface
func (*Int32) UnmarshalJSON ¶ added in v0.8.0
UnmarshalJSON implements the json.Unmarshaler interface.
type Int64 ¶ added in v0.8.1
type Int64 int64
Int64 represents SQL int64 NULL
func (Int64) MarshalJSON ¶ added in v0.8.1
MarshalJSON implements json.Marshaler interface
func (Int64) QuotedString ¶ added in v0.24.141
QuotedString returns string
func (*Int64) UnmarshalJSON ¶ added in v0.8.1
UnmarshalJSON implements the json.Unmarshaler interface.
type KVSet ¶ added in v0.22.91
KVSet de/encodes the string map to/from a SQL string.
type Metadata ¶
Metadata de/encodes the string map to/from a SQL string.
func (Metadata) OrderedKeys ¶ added in v0.24.143
func (Metadata) OrderedPairs ¶ added in v0.24.143
OrderedPairs returns a slice of key-value pairs in the order of keys.
func (Metadata) RangeOrdered ¶ added in v0.24.143
type MigrationConfig ¶
MigrationConfig defines migration configuration
type NULLString ¶
type NULLString string
NULLString de/encodes the string a SQL string.
func (*NULLString) Scan ¶
func (ns *NULLString) Scan(value any) error
Scan implements the Scanner interface.
func (NULLString) String ¶ added in v0.13.1
func (ns NULLString) String() string
String returns string
type PageableByCursor ¶ added in v0.17.76
type PageableByCursor interface {
// Cursor returns the limit and the cursor for pagination: nil without a
// cursor, the value of a single-column key, or []any for a multi-column key.
Cursor() (limit uint32, cursor any)
}
PageableByCursor is an interface for pagination. The cursor values and the limit are the last arguments. The cursor values are before limit because they are used in WHERE clause.
type PageableByOffset ¶ added in v0.17.76
type PageableByOffset interface {
// Page returns the limit and offset for pagination.
Page() (limit uint32, offset uint32)
}
PageableByOffset is an interface for pagination. The limit and offset are the last two arguments.
type Provider ¶
type Provider interface {
IDGenerator
DB
Tx
// Name returns provider name: postgres, sqlserver, etc
Name() string
ConnectionString() string
// DB returns underlying DB connection
DB() DB
// Tx returns underlying DB transaction
Tx() Tx
// Close connection and release resources
Close() (err error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (Provider, error)
}
Provider provides complete DB access
func NewProvider ¶
func NewProvider(dataSource, dbName string, idGen flake.IDGenerator, migrateCfg *MigrationConfig) (Provider, error)
NewProvider creates a Provider instance. It runs the migrations of migrateCfg first, when migrateCfg.Source is set. A nil idGen uses flake.DefaultIDGenerator; any type with NextID() uint64, such as a github.com/effective-security/x/flake generator, also works.
type QueryParams ¶ added in v0.16.72
type QueryParams interface {
PageableByOffset
PageableByCursor
Name() string
Args() []any
// IsSet checks if a positional query parameter is set.
IsSet(pos uint32) bool
// GetEnum checks if an enum query parameter is set.
GetEnum(pos uint32) (int32, bool)
// GetFlags returns additional flags for query parameter.
GetFlags() []int32
// GetNullColumns returns a list of columns that should be replaced with NULL.
GetNullColumns() []string
}
QueryParams is an interface for query parameters.
func GetQueryParams ¶ added in v0.16.72
func GetQueryParams(args ...any) QueryParams
GetQueryParams returns query parameters from an object.
type QueryParamsBuilder ¶ added in v0.16.72
type QueryParamsBuilder struct {
// contains filtered or unexported fields
}
QueryParams is a placeholder for query parameters.
func NewQueryParams ¶ added in v0.16.72
func NewQueryParams(queryName string) *QueryParamsBuilder
NewQueryParams creates a new query parameters builder.
func (*QueryParamsBuilder) AddArgs ¶ added in v0.16.72
func (b *QueryParamsBuilder) AddArgs(v ...any) *QueryParamsBuilder
AddArgs adds an additional query arguments, such as Limit or Offset
func (*QueryParamsBuilder) Args ¶ added in v0.16.72
func (b *QueryParamsBuilder) Args() []any
Args returns a list of query arguments.
func (*QueryParamsBuilder) Cursor ¶ added in v0.17.76
func (b *QueryParamsBuilder) Cursor() (limit uint32, cursor any)
Cursor returns the limit and cursor for pagination, if supported
func (*QueryParamsBuilder) GetEnum ¶ added in v0.16.72
func (b *QueryParamsBuilder) GetEnum(pos uint32) (int32, bool)
GetEnum checks if an enum query parameter is set.
func (*QueryParamsBuilder) GetFlags ¶ added in v0.16.72
func (b *QueryParamsBuilder) GetFlags() []int32
GetFlags returns additional flags for query parameter.
func (*QueryParamsBuilder) GetNullColumns ¶ added in v0.22.99
func (b *QueryParamsBuilder) GetNullColumns() []string
GetNullColumns returns the sorted list of columns that should be replaced with NULL.
func (*QueryParamsBuilder) IsSet ¶ added in v0.16.72
func (b *QueryParamsBuilder) IsSet(pos uint32) bool
IsSet checks if a positional query parameter is set.
func (*QueryParamsBuilder) Name ¶ added in v0.16.72
func (b *QueryParamsBuilder) Name() string
Name returns a hash of the query parameters. It changes with every parameter that changes the SQL: positions, enums, flags, null columns and the pagination mode.
func (*QueryParamsBuilder) Page ¶ added in v0.16.72
func (b *QueryParamsBuilder) Page() (limit uint32, offset uint32)
Page returns the limit and offset for pagination, if supported
func (*QueryParamsBuilder) Reset ¶ added in v0.16.72
func (b *QueryParamsBuilder) Reset()
Reset clears the parameters, keeping the query name.
func (*QueryParamsBuilder) Set ¶ added in v0.16.72
func (b *QueryParamsBuilder) Set(pos uint32, v any) *QueryParamsBuilder
Set sets a positional query parameter, and adds it to the list of arguments.
func (*QueryParamsBuilder) SetCursor ¶ added in v0.17.76
func (b *QueryParamsBuilder) SetCursor(limit uint32, pos uint32, key ...any) *QueryParamsBuilder
SetCursor sets keyset pagination as the last parameters: key is the sort key of the last row of the previous page, in ORDER BY order (for example the values scanned from a Cursor), recorded at position pos and added to the arguments, followed by the limit. The SQL then filters past the key, for example `(created_at, id) < (?, ?)`, and has a LIMIT without OFFSET. Without key values it starts a cursor listing at its first page and is SetPage(limit, 0).
func (*QueryParamsBuilder) SetEnum ¶ added in v0.16.72
func (b *QueryParamsBuilder) SetEnum(pos uint32, v int32) *QueryParamsBuilder
SetEnum sets an enum query parameter, without adding it to the list of arguments.
func (*QueryParamsBuilder) SetFlags ¶ added in v0.16.72
func (b *QueryParamsBuilder) SetFlags(v ...int32) *QueryParamsBuilder
SetFlags sets additional flags for query parameter, replacing the flags set before; add one with SetFlags(append(b.GetFlags(), flag)...).
func (*QueryParamsBuilder) SetNullColums ¶ added in v0.22.99
func (b *QueryParamsBuilder) SetNullColums(nullColumns []string) *QueryParamsBuilder
SetNullColums sets a list of columns that should be replaced with NULL, or filtered with IS NULL. The builder keeps a sorted copy of the list.
func (*QueryParamsBuilder) SetPage ¶ added in v0.16.72
func (b *QueryParamsBuilder) SetPage(limit, offset uint32) *QueryParamsBuilder
SetPage sets the limit for pagination, and adds it to the list of arguments.
type Result ¶
type Result[T any, TPointer RowPointer[T]] interface { SetResult(rows []TPointer, hasNextPage bool, nextOffset uint32) }
Result describes the result of a list query
type ResultWithCursor ¶ added in v0.17.76
type ResultWithCursor[T any, TPointer RowPointer[T]] interface { SetResultWithCursor(rows []TPointer, hasNextPage bool, cursor func(lastRow TPointer) string) }
ResultWithCursor describes the result of a list query with a cursor
type Row ¶
type Row interface {
// Scan copies the columns from the matched row into the values
// pointed at by dest. See the documentation on Rows.Scan for details.
// If more than one row matches the query,
// Scan uses the first row and discards the rest. If no row matches
// the query, Scan returns ErrNoRows.
Scan(dest ...any) error
// Err provides a way for wrapping packages to check for
// query errors without calling Scan.
// Err returns the error, if any, that was encountered while running the query.
// If this error is not nil, this error will also be returned from Scan.
Err() error
}
Row defines an interface for DB row
type RowPointer ¶
type RowPointer[T any] interface { *T RowScanner }
RowPointer defines a generic interface to scan a single row
type RowScanner ¶
RowScanner defines an interface to scan a single row
type Rows ¶
type Rows interface {
io.Closer
Row
// Next prepares the next result row for reading with the Scan method. It
// returns true on success, or false if there is no next result row or an error
// happened while preparing it. Err should be consulted to distinguish between
// the two cases.
//
// Every call to Scan, even the first one, must be preceded by a call to Next.
Next() bool
// NextResultSet prepares the next result set for reading. It reports whether
// there is further result sets, or false if there is no further result set
// or if there is an error advancing to it. The Err method should be consulted
// to distinguish between the two cases.
//
// After calling NextResultSet, the Next method should always be called before
// scanning. If there are further result sets they may not have rows in the result
// set.
NextResultSet() bool
}
Rows defines an interface for DB rows
type SQLProvider ¶
type SQLProvider struct {
// contains filtered or unexported fields
}
SQLProvider represents SQL client instance
func New ¶
func New(name string, db *sql.DB, idGen flake.IDGenerator) (*SQLProvider, error)
New creates a Provider instance
func (*SQLProvider) BeginTx ¶
BeginTx starts a transaction.
The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.
The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.
func (*SQLProvider) Close ¶
func (p *SQLProvider) Close() (err error)
Close connection and release resources
func (*SQLProvider) Commit ¶ added in v0.2.0
func (p *SQLProvider) Commit() error
func (*SQLProvider) ConnectionString ¶ added in v0.18.79
func (p *SQLProvider) ConnectionString() string
func (*SQLProvider) ExecContext ¶ added in v0.2.0
func (p *SQLProvider) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.
func (*SQLProvider) IDTime ¶
func (p *SQLProvider) IDTime(id uint64) time.Time
IDTime returns time when ID was generated
func (*SQLProvider) Name ¶ added in v0.6.0
func (p *SQLProvider) Name() string
Name returns provider name
func (*SQLProvider) QueryContext ¶ added in v0.2.0
func (p *SQLProvider) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.
func (*SQLProvider) QueryRowContext ¶ added in v0.2.0
QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.
func (*SQLProvider) Rollback ¶ added in v0.2.0
func (p *SQLProvider) Rollback() error
func (*SQLProvider) WithConnectionString ¶ added in v0.18.79
func (p *SQLProvider) WithConnectionString(connstr string) *SQLProvider
type SetCursor ¶ added in v0.17.76
type SetCursor[T any, TPointer RowPointer[T]] func(lastRow TPointer) string
SetCursor returns the cursor of the page that follows lastRow, usually NewCursor with the sort key of the row:
func(last *model.Event) string {
// a Time and an ID always encode
c, _ := xdb.NewCursor(last.CreatedAt, last.ID)
return c.String()
}
type Source ¶ added in v0.2.2
type Source struct {
Source string
Driver string
Host string
User string
Password string
Database string
Params map[string]string
}
Source describes connection info
func ParseConnectionString ¶ added in v0.2.2
ParseConnectionString return parsed Source from sqlserver://username:password@host/instance?param1=value¶m2=value
type Strings ¶
type Strings []string
Strings de/encodes the string slice to/from a SQL string.
type Time ¶
Time implements sql.Time functionality and always returns UTC
func FromUnixMilli ¶
FromUnixMilli returns Time from Unix milliseconds elapsed since January 1, 1970 UTC.
func (Time) IsNil ¶
IsNil reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
func (Time) IsZero ¶
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
func (Time) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface. The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (Time) String ¶
String returns string in RFC3339 format, if it's Zero time, an empty string is returned
func (Time) UnixMilli ¶
UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC.
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a quoted string in RFC 3339 format.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
xdbcli
command
|
|
|
internal
|
|
|
cli
Package cli provides CLI app and global flags
|
Package cli provides CLI app and global flags |
|
cli/clisuite
Package clisuite to test CLI commands
|
Package clisuite to test CLI commands |
|
cli/schema
Package schema provides CLI commands
|
Package schema provides CLI commands |
|
mocks
|
|
|
mockschema
Package mockschema is a generated GoMock package.
|
Package mockschema is a generated GoMock package. |
|
mockxdb
Package mockxdb is a generated GoMock package.
|
Package mockxdb is a generated GoMock package. |
|
pkg
|
|
|
flake
Package flake implements Snowflake, a distributed unique ID generator inspired by Twitter's Snowflake.
|
Package flake implements Snowflake, a distributed unique ID generator inspired by Twitter's Snowflake. |
|
print
Package print provides helper package to print objects.
|
Package print provides helper package to print objects. |
|
Package schema provides helper package to generate schema.
|
Package schema provides helper package to generate schema. |
|
Package xsql is a fast SQL statement builder and executor.
|
Package xsql is a fast SQL statement builder and executor. |