Skip to content

rfberaldo/sqlz

Repository files navigation

sqlz

Test Status Go Report Card Codecov Go Reference Mentioned in Awesome Go

sqlz is a lightweight, dependency-free Go library that extends the standard database/sql package, adding support for named queries, struct scanning, and batch operations, while having a clean, minimal API.

It's designed to feel familiar to anyone using database/sql, while removing repetitive boilerplate code. It can scan directly into structs, maps, or slices, and run named queries with full UTF-8/multilingual support.

Documentation: https://rfberaldo.github.io/sqlz/.

Features

  • Named queries for structs and maps.
  • Automatic scanning into primitives, structs, maps and slices.
  • Automatic expanding "IN" clauses.
  • Automatic expanding batch inserts.
  • Automatic prepared statement caching.

Getting started

Install

go get github.com/rfberaldo/sqlz

Setup

There are two ways to use it:

// 1. using [sqlz.Connect]
db, err := sqlz.Connect("sqlite3", ":memory:")

// 2. using [sqlz.New] with a current connection
pool, err := sql.Open("sqlite3", ":memory:")
db := sqlz.New("sqlite3", pool, nil)

Examples

Note

For brevity of the examples, error handling is omitted.

Standard query

var users []User
db.Query(ctx, "SELECT * FROM user WHERE active = ?", true).Scan(&users)
// users variable now contains data from query

Named query

loc := Location{Country: "Brazil"}
var users []User
db.Query(ctx, "SELECT * FROM user WHERE country = :country", loc).Scan(&users)
// users variable now contains data from query

Exec

user := User{Name: "Alice", Email: "[email protected]"}
db.Exec(ctx, "INSERT INTO user (name, email) VALUES (:name, :email)", user)

Batch insert

users := []User{
  {Name: "Alice", Email: "[email protected]"},
  {Name: "Rob", Email: "[email protected]"},
  {Name: "John", Email: "[email protected]"},
}
db.Exec(ctx, "INSERT INTO user (name, email) VALUES (:name, :email)", users)
// executed as "INSERT INTO user (name, email) VALUES (?, ?), (?, ?), (?, ?)"

Dependencies

sqlz has no dependencies, only testing/dev deps.

Comparison with sqlx

  • It was designed with a simpler API for everyday use, with fewer concepts and less verbose.
  • It has full support for UTF-8/multilingual named queries.
  • It's more performant in most cases, take a look at the benchmarks for comparison.

About

Extensions for Golang's database/sql

Topics

Resources

License

Stars

Watchers

Forks