sqlutil

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MPL-2.0 Imports: 4 Imported by: 0

README

sqliteutil

sqliteutil provides utility functions to work with the standard database/sql package in golang.

Example

type Car struct {
	ID    int64  `db:"id,select"`
	Make  string `db:"make,select,insert,update"`
	Model string `db:"model,select,insert,update"`
	Year  int64  `db:"year,select,insert,update"`
	Color string `db:"color,select,insert,update"`
}

func InsertCar(tx *sql.Tx, c *Car) (int64, error) {
	// extract all columns with the "insert" tag
	cols := sqlutil.Cols(c, "", "insert")
	vals := sqlutil.Vals(c, "insert")

	// create a Builder for sqlite (using the ? placeholder)
	// and write the query. It will end up looking like
	// INSERT INTO car (make, model, year, color) VALUES (?, ?, ?, ?)
	b := sqliteutil.Builder()
	b.Printf("INSERT INTO car (%s) VALUES (%s)", cols, vals)

	// execute the query using the (matching) number of arguments
	res, err := tx.Exec(b.String(), b.Args...)
	if err != nil {
		return 0, err
	}
	return res.LastInsertId()
}

func SelectCars(tx *sql.Tx) ([]Car, error) {
	// extract all columns with the "select" tag
	cols := sqlutil.Cols(Car{}, "", "select")

	// build the query only using the "select" cols
	query := fmt.Sprintf("SELECT %s FROM car", cols)

	// execute the query
	cars, err := sqlutil.Query[Car](tx, "select", query)
	return cars, err
}

func UpdateCar(tx *sql.Tx, c *Car) error {
	// extract all columns with the "update" tag
	cols := sqlutil.Cols(c, "", "update")
	vals := sqlutil.Vals(c, "update")

	// create a Builder for sqlite (using the ? placeholder)
	// and use it to format the update statement. FieldList
	// is used to create the col = ...  part.
	b := sqliteutil.Builder()
	fields := sqlutil.FieldList{
		Cols: cols,
		Vals: vals,
		OP:   "=",
	}
	b.Printf("UPDATE car SET %v WHERE id = %v", &fields, c.ID)
	_, err := tx.Exec(b.String(), b.Args...)
	return err
}

Struct Tags

The function Cols and Vals work using struct tags. Each field that should be retrievable must contain a struct tag named db.

The tag value consists of a field name, and optional "tags". The empty tag is implicitly given to all struct fields.

Licensing

sqlutil is released under the MPL v2.0 license

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Query

func Query[T any](q Queryer, tag, query string, a ...any) ([]T, error)

func QueryRow

func QueryRow[T any](q RowQueryer, tag, query string, a ...any) (T, error)

func ScanRows

func ScanRows[T any](rows *sql.Rows, tag string) ([]T, error)

func ScriptMigration

func ScriptMigration(script string) func(*sql.Tx) error

Types

type Builder

type Builder struct {
	Param ParamFunc
	Args  []any
	// contains filtered or unexported fields
}

func (*Builder) Printf

func (b *Builder) Printf(format string, a ...any)

func (*Builder) String

func (b *Builder) String() string

type FieldList

type FieldList struct {
	Cols []string
	Vals []any
	OP   string
}

func (*FieldList) RawString

func (l *FieldList) RawString(b RawBuilder) string

type Migration

type Migration struct {
	Version int64
	Migrate func(tx *sql.Tx) error
}

type ParamFunc

type ParamFunc = func(n int) string

type Queryer

type Queryer interface {
	Query(query string, a ...any) (*sql.Rows, error)
}

type Raw

type Raw string

Raw will be formatted as raw SQL

type RawBuilder

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

func (RawBuilder) Param

func (b RawBuilder) Param(val any) string

Param converts val to a value safe to use in SQL. if it is Raw, the value will be returned. In any other case a parameter will be created

type RawList

type RawList []string

RawList is a string slice that will be used as a comma seperated list of raw strings.

func Cols

func Cols(t any, prefix string, tag string) RawList

func (RawList) RawString

func (s RawList) RawString(b RawBuilder) string

func (RawList) String

func (s RawList) String() string

type RawStringer

type RawStringer interface {
	RawString(b RawBuilder) string
}

type RowQueryer

type RowQueryer interface {
	QueryRow(query string, a ...any) *sql.Row
}

type ValList

type ValList []any

func Vals

func Vals(t any, tag string) ValList

Vals gets the field values of the struct in t if t is a pointer, pointers to the fields are returned

func (ValList) RawString

func (s ValList) RawString(b RawBuilder) string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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