An open API service indexing awesome lists of open source software.

https://github.com/deadblue/sqlfunc

A SQL framework for Golang.
https://github.com/deadblue/sqlfunc

database golang

Last synced: 2 months ago
JSON representation

A SQL framework for Golang.

Awesome Lists containing this project

README

          

# SQL-Function

Run your SQL as function.

## Example

```golang
import (
"context"
"database/sql"
"log"

"github.com/deadblue/sqlfunc"
)

type (
QueryParams struct {
UserId string
Status int
}

UserResult struct {
UserId string
FirstName string
// sql.NullXXX types are supported.
LastName sql.NullString
// Mapping "sex" column to [Gender] field.
Gender int `sql:"sex"`
}
)

func main() {
// Make SQL function
queryUser, err := sqlfunc.MakeQueryFunc[QueryParams, UserResult](
"SELECT user_id, first_name, last_name, sex",
"FROM tbl_user",
"WHERE user_id = {{ .UserID }} AND status = {{ .Status }}",
)
if err != nil {
panic(err)
}

// Connect to database
db, err := sql.Open("driver", "DSN")
if err != nil {
panic(err)
}
// Put DB to context
ctx := sqlfunc.NewContext(context.TODO(), db)

// Execute query
result, err := queryUser(ctx, QueryParams{
UserId: "123",
Status: 1,
})
if err != nil {
panic(err)
}
// Process result
if result.Valid {
user := result.V
if user.LastName.Valid {
log.Printf("Found user: %s-%s", user.FirstName, user.LastName.String)
} else {
log.Printf("Found user: %s", user.FirstName)
}
}
}
```

## License

MIT