Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .github/workflows/docs-deploy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: docs-deploy

on:
push:
branches: [master]
paths: [docs/**]

# Allows to run this workflow manually from the Actions tab
workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow one concurrent deployment
concurrency:
group: "pages"
cancel-in-progress: true

jobs:
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
defaults:
run:
working-directory: docs
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
cache: 'npm'
- run: npm ci
- run: npm run build
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
path: '.vitepress/dist'
- id: deployment
uses: actions/deploy-pages@v4
15 changes: 6 additions & 9 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
name: Test
name: test

on:
push:
paths-ignore: [benchmarks/**]
paths-ignore: [benchmarks/**, docs/**]
branches: [master]
pull_request:
paths-ignore: [benchmarks/**]
paths-ignore: [benchmarks/**, docs/**]
branches: [master]

jobs:
Expand Down Expand Up @@ -45,16 +45,13 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v4
- uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go-version }}

- name: Vet
run: go vet ./...
- run: go vet ./...

- name: Test
- run: go test -v -race ./...
env:
MYSQL_DSN: root:root@tcp(127.0.0.1:3306)/mysql?parseTime=True
POSTGRES_DSN: postgres://postgres:root@127.0.0.1:5432/postgres?sslmode=disable
run: go test -v -race ./...
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@ go.work.sum

# env files
.env

# docs
docs/node_modules
docs/.vitepress/dist
docs/.vitepress/cache
96 changes: 23 additions & 73 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

**sqlz** is a lightweight, dependency-free Go library that extends the standard [database/sql](https://pkg.go.dev/database/sql) package with named queries, scanning, and batch operations with a simple API.

> Guide documentation: https://rfberaldo.github.io/sqlz/.

## Getting started

### Install
Expand All @@ -14,7 +16,7 @@
go get github.com/rfberaldo/sqlz
```

### Connect to database
### Setup

There are two ways to use it:

Expand All @@ -27,97 +29,45 @@ pool, err := sql.Open("sqlite3", ":memory:")
db := sqlz.New("sqlite3", pool, nil)
```

## Querying

**sqlz** has three main methods:

```go
Query(ctx context.Context, query string, args ...any) *Scanner
QueryRow(ctx context.Context, query string, args ...any) *Scanner
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
```
## Examples

> [!NOTE]
> Error handling is omitted for brevity of these examples.

### Query / QueryRow
> Error handling is omitted for brevity of the examples.

They both query from database and returns a Scanner object that can automatically scan rows into structs, maps, slices, etc. `QueryRow` query for one row.
Errors are deferred to scanner for easy chaining, until `Err` or `Scan` is called.
### Standard query

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

```go
// struct or map args are treated as a named query
loc := Location{Country: "Brazil"}
var names []string
db.Query(ctx, "SELECT name FROM user WHERE country = :country", loc).Scan(&names)
```
### Named query

```go
// also works with 'IN' clause out of the box
args := []int{4, 8, 16}
loc := Location{Country: "Brazil"}
var users []User
db.Query(ctx, "SELECT * FROM user WHERE id IN (?)", args).Scan(&users)
// executed as:
// SELECT * FROM user WHERE id IN (?,?,?)
db.Query(ctx, "SELECT * FROM user WHERE country = :country", loc).Scan(&users)
// users variable now contains data from query
```

### Exec

Exec is very similar to standard library, with added support for named queries and batch inserts.

```go
// named query
args := map[string]any{"id": 42}
db.Exec(ctx, "DELETE FROM user WHERE id = :id", args)
user := User{Name: "Alice", Email: "alice@wonderland.com"}
db.Exec(ctx, "INSERT INTO user (name, email) VALUES (:name, :email)", user)
```

```go
// slice arg is treated as a named batch insert
users := []User{
{Id: 1, Name: "Alice", Email: "alice@example.com"},
{Id: 2, Name: "Rob", Email: "rob@example.com"},
{Id: 3, Name: "John", Email: "john@example.com"},
}
query := "INSERT INTO user (id, name, email) VALUES (:id, :name, :email)"
db.Exec(ctx, query, users)
// executed as:
// INSERT INTO user (id, name, email) VALUES (?,?,?), (?,?,?), (?,?,?)
```

### Transactions

Transactions have the methods, and it's also similar to standard library.
### Batch insert

```go
tx := db.Begin(ctx)

// Rollback will be ignored if tx has been committed later in the function
defer tx.Rollback()

user := User{Id: 42}
tx.Exec(ctx, "DELETE FROM user_permission WHERE user_id = :id", user)
tx.Exec(ctx, "DELETE FROM user WHERE id = :id", user)

// Commit may fail, and nothing will have been committed
tx.Commit()
```

### Struct fields

To find the key of a struct field, by default it first try to find the `db` tag,
if it's not present, it then transforms the field's name to snake case.

```go
type User struct {
Id int `db:"user_id"` // mapped as 'user_id'
Name string // mapped as 'name'
CreatedAt time.Time // mapped as 'created_at'
users := []User{
{Name: "Alice", Email: "alice@example.com"},
{Name: "Rob", Email: "rob@example.com"},
{Name: "John", Email: "john@example.com"},
}
db.Exec(ctx, "INSERT INTO user (name, email) VALUES (:name, :email)", users)
// executed as "INSERT INTO user (name, email) VALUES (?, ?), (?, ?), (?, ?)"
```

## Dependencies
Expand All @@ -127,7 +77,7 @@ type User struct {
## Comparison with [sqlx](https://github.com/jmoiron/sqlx)

- It was designed with a simpler API for everyday use, with fewer concepts and less verbose.
- It supports non-english utf-8 characters in named queries.
- It has full support for UTF-8 in named queries.

### Performance

Expand Down
45 changes: 45 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { defineConfig } from 'vitepress'

// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "sqlz",
description: "sqlz is a lightweight, dependency-free Go library that extends the standard database/sql package with named queries, scanning, and batch operations with a simple API",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Guide', link: '/' },
{ text: 'Reference', link: 'https://pkg.go.dev/github.com/rfberaldo/sqlz' },
],

sidebar: [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/' },
{ text: 'Getting started', link: '/getting-started' },
{ text: 'Querying', link: '/querying' },
{ text: 'Scanning', link: '/scanning' },
{ text: 'Transactions', link: '/transactions' },
{ text: 'Custom options', link: '/custom-options' },
{ text: 'Connection pool', link: '/connection-pool' },
],
},
],

socialLinks: [
{ icon: 'github', link: 'https://github.com/rfberaldo/sqlz' },
{
icon: { svg: '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32.000001"><g transform="translate(0 -1020.3622)"><ellipse cx="-907.35657" cy="479.90009" fill="#384e54" color="#000" overflow="visible" rx="3.5793996" ry="3.8207953" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1" transform="scale(-1 1) rotate(-60.548)"/><ellipse cx="-891.57654" cy="507.8461" fill="#384e54" color="#000" overflow="visible" rx="3.5793996" ry="3.8207953" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1" transform="rotate(-60.548)"/><path fill="#384e54" d="M16.091693 1021.3642c-1.105749.01-2.210341.049-3.31609.09C6.8422558 1021.6738 2 1026.3942 2 1032.3622v20h28v-20c0-5.9683-4.667345-10.4912-10.59023-10.908-1.10575-.078-2.212328-.099-3.318077-.09z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill="#76e1fe" d="M4.6078867 1025.0462c.459564.2595 1.818262 1.2013 1.980983 1.648.183401.5035.159385 1.0657-.114614 1.551-.346627.6138-1.005341.9487-1.696421.9365-.339886-.01-1.720283-.6372-2.042561-.8192-.97754-.5519-1.350795-1.7418-.833686-2.6576.517109-.9158 1.728749-1.2107 2.706299-.6587z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><rect width="3.0866659" height="3.5313663" x="14.406213" y="1035.6842" fill-opacity=".32850246" color="#000" overflow="visible" ry=".62426329" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill="#76e1fe" d="M16 1023.3622c-9 0-12 3.7153-12 9v20h24c-.04889-7.3562 0-18 0-20 0-5.2848-3-9-12-9z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill="#76e1fe" d="M27.074073 1025.0462c-.45957.2595-1.818257 1.2013-1.980979 1.648-.183401.5035-.159384 1.0657.114614 1.551.346627.6138 1.005335.9487 1.696415.9365.33988-.01 1.72029-.6372 2.04256-.8192.97754-.5519 1.35079-1.7418.83369-2.6576-.51711-.9158-1.72876-1.2107-2.7063-.6587z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><circle cx="21.175734" cy="1030.3542" r="4.6537542" fill="#fff" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><circle cx="10.339486" cy="1030.3542" r="4.8316345" fill="#fff" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><rect width="3.6673687" height="4.1063409" x="14.115863" y="1035.9174" fill-opacity=".32941176" color="#000" overflow="visible" ry=".72590536" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><rect width="3.6673687" height="4.1063409" x="14.115863" y="1035.2253" fill="#fffcfb" color="#000" overflow="visible" ry=".72590536" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill-opacity=".32941176" d="M19.999735 1036.5289c0 .838-.871228 1.2682-2.144766 1.1659-.02366 0-.04795-.6004-.254147-.5832-.503669.042-1.095902-.02-1.685964-.02-.612939 0-1.206342.1826-1.68549.017-.110233-.038-.178298.5838-.261532.5816-1.243685-.033-2.078803-.3383-2.078803-1.1618 0-1.2118 1.815635-2.1941 4.055351-2.1941 2.239704 0 4.055351.9823 4.055351 2.1941z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill="#c38c74" d="M19.977414 1035.7004c0 .5685-.433659.8554-1.138091 1.0001-.291933.06-.630371.096-1.003719.1166-.56405.032-1.207782.031-1.89122.031-.672834 0-1.307182 0-1.864904-.029-.306268-.017-.589429-.043-.843164-.084-.813833-.1318-1.324962-.417-1.324962-1.0344 0-1.1601 1.805642-2.1006 4.03303-2.1006 2.227377 0 4.03303.9405 4.03303 2.1006z" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><ellipse cx="15.944382" cy="1033.8501" fill="#23201f" color="#000" overflow="visible" rx="2.0801733" ry="1.343747" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><circle cx="12.414201" cy="1030.3542" r="1.9630634" fill="#171311" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><circle cx="23.110121" cy="1030.3542" r="1.9630634" fill="#171311" color="#000" overflow="visible" style="isolation:auto;mix-blend-mode:normal;solid-color:#000;solid-opacity:1"/><path fill="none" stroke="#384e54" stroke-linecap="round" stroke-width=".39730874" d="M5.0055377 1027.2727c-1.170435-1.0835-2.026973-.7721-2.044172-.7463"/><path fill="none" stroke="#384e54" stroke-linecap="round" stroke-width=".39730874" d="M4.3852457 1026.9152c-1.158557.036-1.346704.6303-1.33881.6523m23.5840973-.3951c1.17043-1.0835 2.02697-.7721 2.04417-.7463"/><path fill="none" stroke="#384e54" stroke-linecap="round" stroke-width=".39730874" d="M27.321773 1026.673c1.15856.036 1.3467.6302 1.3388.6522"/></g></svg>' },
link: 'https://pkg.go.dev/github.com/rfberaldo/sqlz',
},
],

editLink: {
pattern: 'https://github.com/rfberaldo/sqlz/edit/master/docs/:path',
},

search: {
provider: 'local',
},
},
})
5 changes: 5 additions & 0 deletions docs/.vitepress/theme/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// https://vitepress.dev/guide/custom-theme
import DefaultTheme from 'vitepress/theme'
import './style.css'

export default DefaultTheme
113 changes: 113 additions & 0 deletions docs/.vitepress/theme/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* Customize default theme styling by overriding CSS variables:
* https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css
*/

/**
* Colors
*
* Each colors have exact same color scale system with 3 levels of solid
* colors with different brightness, and 1 soft color.
*
* - `XXX-1`: The most solid color used mainly for colored text. It must
* satisfy the contrast ratio against when used on top of `XXX-soft`.
*
* - `XXX-2`: The color used mainly for hover state of the button.
*
* - `XXX-3`: The color for solid background, such as bg color of the button.
* It must satisfy the contrast ratio with pure white (#ffffff) text on
* top of it.
*
* - `XXX-soft`: The color used for subtle background such as custom container
* or badges. It must satisfy the contrast ratio when putting `XXX-1` colors
* on top of it.
*
* The soft color must be semi transparent alpha channel. This is crucial
* because it allows adding multiple "soft" colors on top of each other
* to create an accent, such as when having inline code block inside
* custom containers.
*
* - `default`: The color used purely for subtle indication without any
* special meanings attached to it such as bg color for menu hover state.
*
* - `brand`: Used for primary brand colors, such as link text, button with
* brand theme, etc.
*
* - `tip`: Used to indicate useful information. The default theme uses the
* brand color for this by default.
*
* - `warning`: Used to indicate warning to the users. Used in custom
* container, badges, etc.
*
* - `danger`: Used to show error, or dangerous message to the users. Used
* in custom container, badges, etc.
* -------------------------------------------------------------------------- */

:root {
--vp-c-default-1: var(--vp-c-gray-1);
--vp-c-default-2: var(--vp-c-gray-2);
--vp-c-default-3: var(--vp-c-gray-3);
--vp-c-default-soft: var(--vp-c-gray-soft);

--vp-c-brand-1: hsl(214, 100%, 50%);
--vp-c-brand-2: hsl(214, 100%, 60%);
--vp-c-brand-3: hsl(214, 100%, 40%);
--vp-c-brand-soft: hsla(214, 100%, 55%, 0.12);

--vp-c-tip-1: var(--vp-c-green-1);
--vp-c-tip-2: var(--vp-c-green-2);
--vp-c-tip-3: var(--vp-c-green-3);
--vp-c-tip-soft: var(--vp-c-green-soft);

--vp-c-warning-1: var(--vp-c-yellow-1);
--vp-c-warning-2: var(--vp-c-yellow-2);
--vp-c-warning-3: var(--vp-c-yellow-3);
--vp-c-warning-soft: var(--vp-c-yellow-soft);

--vp-c-danger-1: var(--vp-c-red-1);
--vp-c-danger-2: var(--vp-c-red-2);
--vp-c-danger-3: var(--vp-c-red-3);
--vp-c-danger-soft: var(--vp-c-red-soft);

--vp-code-color: var(--vp-c-red-1);
}

/**
* Component: Button
* -------------------------------------------------------------------------- */

:root {
--vp-button-brand-border: transparent;
--vp-button-brand-text: var(--vp-c-white);
--vp-button-brand-bg: var(--vp-c-brand-3);
--vp-button-brand-hover-border: transparent;
--vp-button-brand-hover-text: var(--vp-c-white);
--vp-button-brand-hover-bg: var(--vp-c-brand-2);
--vp-button-brand-active-border: transparent;
--vp-button-brand-active-text: var(--vp-c-white);
--vp-button-brand-active-bg: var(--vp-c-brand-1);
}

/**
* Component: Custom Block
* -------------------------------------------------------------------------- */

:root {
--vp-custom-block-note-border: transparent;
--vp-custom-block-note-text: var(--vp-c-text-1);
--vp-custom-block-note-bg: var(--vp-c-brand-soft);
--vp-custom-block-note-code-bg: var(--vp-c-brand-soft);

--vp-custom-block-tip-border: transparent;
--vp-custom-block-tip-text: var(--vp-c-text-1);
--vp-custom-block-tip-bg: var(--vp-c-tip-soft);
--vp-custom-block-tip-code-bg: var(--vp-c-tip-soft);
}

/**
* Component: Algolia
* -------------------------------------------------------------------------- */

.DocSearch {
--docsearch-primary-color: var(--vp-c-brand-1) !important;
}
Loading