https://github.com/emanuel-skrenkovic/tql
Generics around database/sql with an api for simple use-cases.
https://github.com/emanuel-skrenkovic/tql
generics go golang sql
Last synced: 4 months ago
JSON representation
Generics around database/sql with an api for simple use-cases.
- Host: GitHub
- URL: https://github.com/emanuel-skrenkovic/tql
- Owner: emanuel-skrenkovic
- License: mit
- Created: 2023-05-06T09:17:37.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2024-10-19T08:42:10.000Z (over 1 year ago)
- Last Synced: 2024-10-30T22:38:29.153Z (over 1 year ago)
- Topics: generics, go, golang, sql
- Language: Go
- Homepage:
- Size: 292 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# tql
Simple convenience functions (with generics) around `database/sql`.
Designed to be used with existing `sql.DB`, `sql.Tx` types.
Marshals rows into structs using the `db` tag. For the struct field to be marshalled, it needs to contain the `db` tag.
### Example usage:
```go
type Foo struct {
ID string `db:"id"`
Value string `db:"value"`
}
const query = "SELECT * FROM foo WHERE value = $1;"
foos, err := tql.Query[Foo](context.Background(), db, query, "bar")
if err != nil {
// error handling
}
// do stuff with foos
```
### Supports named parameters:
```go
type Foo struct {
ID string `db:"id"`
Value string `db:"value"`
}
foo := Foo {
ID: "foo",
Value: "bar",
}
const stmt = "INSERT INTO foo (id, value) VALUES (:id, :value);"
result, err := tql.Exec(context.Background(), db, stmt, foo)
if err != nil {
// error handling
}
// do stuff with result
```
## API
```go
QuerySingle[T any](ctx context.Context, q Querier, query string, params ...any) (T, error)
QuerySingleOrDefault[T any](ctx context.Context, q Querier, def T, query string, params ...any) (T, error)
QueryFirst[T any](ctx context.Context, q Querier, query string, params ...any) (T, error)
QueryFirstOrDefault[T any](ctx context.Context, q Querier, def T, query string, params ...any) (T, error)
Query[T any](ctx context.Context, q Querier, query string, params ...any) ([]T, error)
Exec(ctx context.Context, e Executor, query string, params ...any) (sql.Result, error)
```
## Interfaces used
```go
type Executor interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
type Querier interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
```