jet/statement.go

80 lines
1.7 KiB
Go
Raw Normal View History

2019-06-21 13:56:57 +02:00
package jet
import (
2019-06-20 12:22:19 +02:00
"context"
"database/sql"
2019-06-21 13:56:57 +02:00
"github.com/go-jet/jet/execution"
2019-05-12 18:15:23 +02:00
"strconv"
"strings"
)
2019-05-12 18:15:23 +02:00
type Statement interface {
// String returns generated SQL as string.
Sql() (query string, args []interface{}, err error)
2019-05-12 18:15:23 +02:00
DebugSql() (query string, err error)
Query(db execution.Db, destination interface{}) error
2019-06-20 12:22:19 +02:00
QueryContext(db execution.Db, context context.Context, destination interface{}) error
Exec(db execution.Db) (sql.Result, error)
2019-06-20 12:22:19 +02:00
ExecContext(db execution.Db, context context.Context) (sql.Result, error)
}
2019-05-12 18:15:23 +02:00
func DebugSql(statement Statement) (string, error) {
2019-06-21 13:56:57 +02:00
sqlQuery, args, err := statement.Sql()
2019-05-12 18:15:23 +02:00
if err != nil {
return "", err
}
2019-06-21 13:56:57 +02:00
debugSqlQuery := sqlQuery
2019-05-12 18:15:23 +02:00
for i, arg := range args {
argPlaceholder := "$" + strconv.Itoa(i+1)
2019-06-21 13:56:57 +02:00
debugSqlQuery = strings.Replace(debugSqlQuery, argPlaceholder, ArgToString(arg), 1)
2019-05-12 18:15:23 +02:00
}
2019-06-21 13:56:57 +02:00
return debugSqlQuery, nil
2019-05-12 18:15:23 +02:00
}
2019-06-20 12:22:19 +02:00
func Query(statement Statement, db execution.Db, destination interface{}) error {
query, args, err := statement.Sql()
if err != nil {
return err
}
return execution.Query(db, context.Background(), query, args, destination)
}
func QueryContext(statement Statement, db execution.Db, context context.Context, destination interface{}) error {
query, args, err := statement.Sql()
if err != nil {
return err
}
return execution.Query(db, context, query, args, destination)
}
func Exec(statement Statement, db execution.Db) (res sql.Result, err error) {
query, args, err := statement.Sql()
if err != nil {
return
}
return db.Exec(query, args...)
}
func ExecContext(statement Statement, db execution.Db, context context.Context) (res sql.Result, err error) {
query, args, err := statement.Sql()
if err != nil {
return
}
return db.ExecContext(context, query, args...)
}