Skip to content

Repository files navigation

yesql

Write SQL. Skip the plumbing.

yesql is a lightweight layer over Go's database/sql for writing raw SQL with named parameters, cached templates, structured logging, and struct scanning.

database/sql meets text/template—with less query plumbing.

Quick start

Open a database connection with your usual driver:

package main
import (
"github.com/izolate/yesql"
_ "github.com/lib/pq"
)
funcmain() {
db, err:=yesql.Open("postgres", "host=localhost user=foo sslmode=disable")
iferr!=nil {
panic(err)
}
deferdb.Close()
}

Then keep the query in SQL. Named parameters bind values safely, templates add optional clauses, and ScanStruct maps result columns to db tags:

typeBookstruct {
IDstring`db:"id"`Titlestring`db:"title"`Authorstring`db:"author"`Genrestring`db:"genre"`
}
typeBookSearchstruct {
AuthorstringTitlestringGenrestring
}
constsearchBooksSQL=`SELECT id, title, author, genreFROM booksWHERE author = @Author{{if .Title}}AND title ILIKE @Title{{end}}{{if .Genre}}AND genre = @Genre{{end}}`funcSearchBooks(db*yesql.DB, searchBookSearch) ([]Book, error) {
rows, err:=db.Query(searchBooksSQL, search)
iferr!=nil {
returnnil, err
}
deferrows.Close()
varbooks []Bookforrows.Next() {
varbookBookiferr:=rows.ScanStruct(&book); err!=nil {
returnnil, err
}
books=append(books, book)
}
returnbooks, rows.Err()
}

Named parameters can bind from maps or exported struct fields.

Configuration

yesql accepts functional options at setup. For example, OptQuiet disables statement logging:

db, err:=yesql.Open(
"postgres",
"host=localhost user=foo sslmode=disable",
yesql.OptQuiet(),
)

Use OptQuietIf(!debugSQL) when the setting is conditional. Passing false explicitly enables logging, so the last logging option wins.

Status

yesql is a work in progress.

Available today:

  • Templated SQL statements
  • Named parameters
  • Structured statement logging
  • Struct scanning
  • Unicode support
  • PostgreSQL support

Planned:

  • Query tracing
  • Prepared statements

About

Write raw SQL in Go—with named parameters, templates, structured logging, and struct scanning.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages