https://github.com/goapt/scan
Tiny lib to scan SQL rows directly to structs, slices, and primitive types
https://github.com/goapt/scan
Last synced: 5 months ago
JSON representation
Tiny lib to scan SQL rows directly to structs, slices, and primitive types
- Host: GitHub
- URL: https://github.com/goapt/scan
- Owner: goapt
- License: mit
- Created: 2024-12-02T06:30:11.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2025-12-24T10:39:08.000Z (6 months ago)
- Last Synced: 2025-12-25T17:06:44.454Z (6 months ago)
- Language: Go
- Homepage:
- Size: 3.88 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Scan
[](https://godoc.org/github.com/goapt/scan)
[](https://github.com/goapt/scan/actions)
[](https://coveralls.io/github/goapt/scan?branch=master)
Scan is a Go package for scanning database rows into structs or slices of primitive types.
> This project is forked from [https://github.com/blockloop/scan](https://github.com/blockloop/scan) and adjusted to be generic, while all dependencies are removed.
## Installation
```sh
go get github.com/goapt/scan
```
## Usage
```go
import "github.com/goapt/scan"
```
## Examples
### Multiple Rows
```go
type Person struct {
ID int `db:"id"`
Name string
}
db, err := sql.Open("sqlite3", "database.sqlite")
rows, err := db.Query("SELECT * FROM persons")
defer rows.Close()
persons, err := scan.Rows[Person](rows)
fmt.Printf("%#v", persons)
// []Person{
// {ID: 1, Name: "brett"},
// {ID: 2, Name: "fred"},
// {ID: 3, Name: "stacy"},
// }
```
### Multiple rows of primitive type
```go
rows, err := db.Query("SELECT name FROM persons")
defer rows.Close()
names, err := scan.Rows[string](rows)
fmt.Printf("%#v", names)
// []string{
// "brett",
// "fred",
// "stacy",
// }
```
### Single row
```go
rows, err := db.Query("SELECT * FROM persons where name = 'brett' LIMIT 1")
person, err := scan.Row[Person](rows)
defer rows.Close()
fmt.Printf("%#v", person)
// Person{ ID: 1, Name: "brett" }
```
### Scalar value
```go
rows, err := db.Query("SELECT age FROM persons where name = 'brett' LIMIT 1")
defer rows.Close()
age, err := scan.Row[int8](rows)
fmt.Printf("%d", age)
// 100
```
### Custom Column Mapping
By default, column names are mapped to and from database column names using basic title case conversion. You can override this behavior by setting `ScannerMapper` to custom functions.
```go
scan.ScannerMapper = func(columnName string) string {
return strings.ToLower(columnName)
}
```
## Why
While many other projects support similar features (i.e. [sqlx](https://github.com/jmoiron/sqlx)) scan allows you to use any database lib such as the stdlib to write fluent SQL statements and pass the resulting `rows` to `scan` for scanning.