Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/taleeus/sqld
A Go library to build and manage dynamic queries
https://github.com/taleeus/sqld
database go query-builder sql
Last synced: 2 days ago
JSON representation
A Go library to build and manage dynamic queries
- Host: GitHub
- URL: https://github.com/taleeus/sqld
- Owner: taleeus
- License: mit
- Created: 2024-01-04T16:09:10.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2024-10-24T15:15:03.000Z (22 days ago)
- Last Synced: 2024-10-25T20:16:28.165Z (21 days ago)
- Topics: database, go, query-builder, sql
- Language: Go
- Homepage:
- Size: 62.5 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# sqld
A Go library to build and manage dynamic queries.
It tries to remain as simple as possible, leveraging [sqlx](https://github.com/jmoiron/sqlx) parameter annotation.## Legazy version
See the `legacy` module and the corresponding [README](legacy/README.md).## Scope of the project
The scope of `sqld` is to provide an easy way to organize your dynamic queries, not to validate said queries.
I suggest to use other tools like [SQLParser](https://github.com/blastrain/vitess-sqlparser) and a lot of e2e tests!# Usage
```go
func testQuery(db sqlx.ExtContext, args QueryArgs) ([]TestModel, error) {
dynquery := `
SELECT *
FROM table
`params := make(slqd.Params) // it's just a map
dynquery += sqld.Where( // returns empty string if all predicates don't evaluate
sqld.IfNotNil(args.Name, params, sqld.Contains("table.name"))
)
dynquery += sqld.IfNotNil(args.Limit, params, sqld.Limit)
dynquery += sqld.IfNotNil(args.Offset, params, sqld.Offset)query, args, err := sqlx.Named(dynquery, params)
if err != nil {
return nil, err
}rows, err := db.QueryxContext(ctx, db.Rebind(query), args...) // use Rebind() with postgres
if err != nil {
return nil, err
}
defer rows.Close()var items []TestModel
for rows.Next() {
var item TestModel
if err := rows.StructScan(&item); err != nil {
return nil, err
}items = append(items, item)
}return items, nil
}
```