orm

package
v1.6.6 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: GPL-3.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	TagUnixNano          = "unixnano"
	TagPrimaryKey        = "primary"
	TagAutoIncrement     = "autoincrement"
	TagTime              = "time"
	TagNotNull           = "not-null"
	TagNullable          = "nullable"
	TagTypeInt           = "integer"
	TagTypeText          = "text"
	TagTypePrefixVarchar = "varchar"
	TagTypeBlob          = "blob"
	TagTypeFloat         = "float"
	TagTypePrefixDefault = "default="
)

Struct Tags.

View Source
var DefaultDecodeConfig = DecodeConfig{
	DecodeHooks: []DecodeFunc{
		DatetimeDecoder(time.UTC),
	},
}

DefaultDecodeConfig holds the default decoding configuration.

View Source
var DefaultEncodeConfig = EncodeConfig{
	EncodeHooks: []EncodeFunc{
		DatetimeEncoder(time.UTC),
	},
}

DefaultEncodeConfig holds the default encoding configuration.

View Source
var (
	// sqliteTimeFromat defines the string representation that is
	// expected by SQLite DATETIME functions.
	// Note that SQLite itself does not include support for a DATETIME
	// column type. Instead, dates and times are stored either as INTEGER,
	// TEXT or REAL.
	// This package provides support for time.Time being stored as TEXT (using a
	// preconfigured timezone; UTC by default) or as INTEGER (the user can choose between
	// unixepoch and unixnano-epoch where the nano variant is not officially supported by
	// SQLITE).
	SqliteTimeFormat = "2006-01-02 15:04:05"
)

constants used when transforming data to and from sqlite.

Functions

func DecodeStmt

func DecodeStmt(ctx context.Context, schema *TableSchema, stmt Stmt, result interface{}, cfg DecodeConfig) error

DecodeStmt decodes the current result row loaded in Stmt into the struct or map type result. Decoding hooks configured in cfg are executed before trying to decode basic types and may be specified to provide support for special types. See DatetimeDecoder() for an example of a DecodeHook that handles graceful time.Time conversion.

func EncodeValue

func EncodeValue(ctx context.Context, colDef *ColumnDef, val interface{}, cfg EncodeConfig) (interface{}, error)

EncodeValue encodes the given value.

func NormalizeKind

func NormalizeKind(kind reflect.Kind) reflect.Kind

NormalizeKind returns a normalized kind of the given kind.

func RunQuery

func RunQuery(ctx context.Context, conn *sqlite.Conn, sql string, modifiers ...QueryOption) error

RunQuery executes the query stored in sql against the databased opened in conn. Please refer to the documentation of QueryOption, especially WithResult() for more information on how to retrieve the resulting rows.

Example:

var result []struct{
	Count int `sqlite:"rowCount"`
}

err := RunQuery(ctx, conn, "SELECT COUNT(*) AS rowCount FROM table", WithResult(&result))
fmt.Println(result[0].Count)

func ToParamMap

func ToParamMap(ctx context.Context, r interface{}, keyPrefix string, cfg EncodeConfig, skipFields []string) (map[string]interface{}, error)

ToParamMap returns a map that contains the sqlite compatible value of each struct field of r using the sqlite column name as a map key. It either uses the name of the exported struct field or the value of the "sqlite" tag.

Types

type ColumnDef

type ColumnDef struct {
	Name          string
	Nullable      bool
	Type          sqlite.ColumnType
	GoType        reflect.Type
	Length        int
	PrimaryKey    bool
	AutoIncrement bool
	UnixNano      bool
	IsTime        bool
	Default       any
}

ColumnDef defines a SQL column.

func (ColumnDef) AsSQL

func (def ColumnDef) AsSQL() string

AsSQL builds the SQL column definition.

type DecodeConfig

type DecodeConfig struct {
	DecodeHooks []DecodeFunc
}

DecodeConfig holds decoding functions.

type DecodeFunc

type DecodeFunc func(colIdx int, colDef *ColumnDef, stmt Stmt, fieldDef reflect.StructField, outval reflect.Value) (interface{}, bool, error)

DecodeFunc is called for each non-basic type during decoding.

func DatetimeDecoder

func DatetimeDecoder(loc *time.Location) DecodeFunc

DatetimeDecoder is capable of decoding sqlite INTEGER or TEXT storage classes into time.Time. For INTEGER storage classes, it supports 'unixnano' struct tag value to decide between Unix or UnixNano epoch timestamps.

TODO(ppacher): update comment about loc parameter and TEXT storage class parsing.

type EncodeConfig

type EncodeConfig struct {
	EncodeHooks []EncodeFunc
}

EncodeConfig holds encoding functions.

type EncodeFunc

type EncodeFunc func(col *ColumnDef, valType reflect.Type, val reflect.Value) (interface{}, bool, error)

EncodeFunc is called for each non-basic type during encoding.

func DatetimeEncoder

func DatetimeEncoder(loc *time.Location) EncodeFunc

DatetimeEncoder returns a new datetime encoder for the given time zone.

type QueryOption

type QueryOption func(opts *queryOpts)

QueryOption can be specified at RunQuery to alter the behavior of the executed query.

func WithArgs

func WithArgs(args ...interface{}) QueryOption

WithArgs adds a list of arguments for the query. Arguments are applied in order.

See SQL Language Expression documentation of SQLite for details: https://sqlite.org/lang_expr.html

func WithDecodeConfig

func WithDecodeConfig(cfg DecodeConfig) QueryOption

WithDecodeConfig configures the DecodeConfig to use when calling DecodeStmt to decode each row into the result slice.

If not specified, DefaultDecodeConfig will be used.

func WithNamedArgs

func WithNamedArgs(args map[string]interface{}) QueryOption

WithNamedArgs adds args to the query. The query must used named argument placeholders. According to the SQLite spec, arguments must either start with ':', '@' or '$'.

See SQL Language Expression documentation of SQLite for details: https://sqlite.org/lang_expr.html

func WithResult

func WithResult(result interface{}) QueryOption

WithResult sets the result receiver. result is expected to be a pointer to a slice of struct or map types.

For decoding DecodeStmt is used to decode each row into a new slice element. It thus supports special values like time.Time. See DecodeStmt() and WithDecodeConfig() for more information.

func WithSchema

func WithSchema(tbl TableSchema) QueryOption

WithSchema returns a query option that adds the given table schema to the query.

func WithTransient

func WithTransient() QueryOption

WithTransient marks the query as transient.

Transient queries will not be cached for later re-use after they have been prepared.

type Stmt

type Stmt interface {
	ColumnCount() int
	ColumnName(col int) string
	ColumnType(col int) sqlite.ColumnType
	ColumnText(col int) string
	ColumnBool(col int) bool
	ColumnFloat(col int) float64
	ColumnInt(col int) int
	ColumnReader(col int) *bytes.Reader
}

Stmt describes the interface that must be implemented in order to be decodable to a struct type using DecodeStmt. This interface is implemented by *sqlite.Stmt.

type TableSchema

type TableSchema struct {
	Name    string
	Columns []ColumnDef
}

TableSchema defines a SQL table schema.

func GenerateTableSchema

func GenerateTableSchema(name string, d interface{}) (*TableSchema, error)

GenerateTableSchema generates a table schema from the given struct.

func (TableSchema) CreateStatement

func (ts TableSchema) CreateStatement(databaseName string, ifNotExists bool) string

CreateStatement build the CREATE SQL statement for the table.

func (TableSchema) GetColumnDef

func (ts TableSchema) GetColumnDef(name string) *ColumnDef

GetColumnDef returns the column definition with the given name.

Jump to

Keyboard shortcuts

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