Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/knadh/goyesql
Parse SQL files with multiple named queries and automatically prepare and scan them into structs.
https://github.com/knadh/goyesql
mysql postgresql prepared-statements sql sql-files
Last synced: 10 days ago
JSON representation
Parse SQL files with multiple named queries and automatically prepare and scan them into structs.
- Host: GitHub
- URL: https://github.com/knadh/goyesql
- Owner: knadh
- License: bsd-2-clause
- Created: 2019-06-27T07:35:54.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-12-06T10:58:58.000Z (almost 2 years ago)
- Last Synced: 2024-08-23T10:42:33.931Z (3 months ago)
- Topics: mysql, postgresql, prepared-statements, sql, sql-files
- Language: Go
- Homepage:
- Size: 26.4 KB
- Stars: 53
- Watchers: 3
- Forks: 12
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# goyesql
> This package is based on [nleof/goyesql](https://github.com/nleof/goyesql) but is not compatible with it any more. This package introduces support for arbitrary tag types and changes structs and error types.
Parses a file and associate SQL queries to a map. Useful for separating SQL from code logic.
# Installation
```
$ go get -u github.com/knadh/goyesql/v2
```## Usage
Create a file containing your SQL queries
```sql
-- queries.sql-- name: list
-- some: param
-- some_other: param
SELECT *
FROM foo;-- name: get
SELECT *
FROM foo
WHERE bar = $1;
```And just call them in your code!
```go
queries := goyesql.MustParseFile("queries.sql")
// use queries["list"] with sql/database, sqlx ...
// queries["list"].Query is the parsed SQL query string
// queries["list"].Tags is the list of arbitrary tags (some=param, some_other=param)
```## Scanning
Often, it's necessary to scan multiple queries from a SQL file, prepare them into \*sql.Stmt and use them throught the application. goyesql comes with a helper function that helps with this. Given a goyesql map of queries, it can turn the queries into prepared statements and scan them into a struct that can be passed around.
```go
type MySQLQueries struct {
// This will be prepared.
List *sql.Stmt `query:"list"`// This will not be prepared.
Get string `query:"get"`
}type MySQLxQueries struct {
// These will be prepared.
List *sqlx.Stmt `query:"list"`
NamedList *sqlx.NamedStmt `query:"named_list"`// This will not be prepared.
Get string `query:"get"`
}var (
q MySQLQueries
qx MySQLxQueries
)// Here, db (*sql.DB) is your live DB connection.
err := goyesql.ScanToStruct(&q, queries, db)
if err != nil {
log.Fatal(err)
}// Here, db (*sqlx.DB) is your live DB connection.
err := goyesqlx.ScanToStruct(&qx, queries, db)
if err != nil {
log.Fatal(err)
}// Then, q.Exec(), q.QueryRow() etc.
```
## Embedding
You can use [stuffbin](https://github.com/knadh/stuffbin) and `ParseBytes()` for embedding SQL queries in your binary.