From 11192c83f932eb7421ef09e06859a7f171de7803 Mon Sep 17 00:00:00 2001 From: Emanuel Bennici Date: Tue, 28 Feb 2023 14:38:05 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20expose=20Exec(=E2=80=A6)=20method=20for?= =?UTF-8?q?=20RawQuery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Exec(…) method allows to execute raw queries which do not return any data. --- query_base.go | 7 ++++++- query_raw.go | 40 ++++++++++++++++++++++++++++++++++------ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/query_base.go b/query_base.go index 9df70d1f4..e20c809d6 100644 --- a/query_base.go +++ b/query_base.go @@ -1054,7 +1054,12 @@ type customValueQuery struct { func (q *customValueQuery) addValue( table *schema.Table, column string, value string, args []interface{}, ) { - if _, ok := table.FieldMap[column]; ok { + ok := false + if table != nil { + _, ok = table.FieldMap[column] + } + + if ok { if q.modelValues == nil { q.modelValues = make(map[string]schema.QueryWithArgs) } diff --git a/query_raw.go b/query_raw.go index 7afa4d536..fda088a7c 100644 --- a/query_raw.go +++ b/query_raw.go @@ -2,6 +2,7 @@ package bun import ( "context" + "database/sql" "github.com/uptrace/bun/schema" ) @@ -46,19 +47,46 @@ func (q *RawQuery) Err(err error) *RawQuery { return q } +func (q *RawQuery) Exec(ctx context.Context, dest ...interface{}) (sql.Result, error) { + return q.scanOrExec(ctx, dest, len(dest) > 0) +} + func (q *RawQuery) Scan(ctx context.Context, dest ...interface{}) error { + _, err := q.scanOrExec(ctx, dest, true) + return err +} + +func (q *RawQuery) scanOrExec( + ctx context.Context, dest []interface{}, hasDest bool, +) (sql.Result, error) { if q.err != nil { - return q.err + return nil, q.err } - model, err := q.getModel(dest) - if err != nil { - return err + var model Model + var err error + + if hasDest { + model, err = q.getModel(dest) + if err != nil { + return nil, err + } } query := q.db.format(q.query, q.args) - _, err = q.scan(ctx, q, query, model, true) - return err + var res sql.Result + + if hasDest { + res, err = q.scan(ctx, q, query, model, hasDest) + } else { + res, err = q.exec(ctx, q, query) + } + + if err != nil { + return nil, err + } + + return res, nil } func (q *RawQuery) AppendQuery(fmter schema.Formatter, b []byte) ([]byte, error) {