Skip to content

Commit

Permalink
feat: added raw query calls (#596)
Browse files Browse the repository at this point in the history
* feat: added raw query calls
  • Loading branch information
josearomeroj committed Jul 1, 2022
1 parent f2bef6c commit 127644d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
9 changes: 9 additions & 0 deletions internal/dbtest/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ func TestDB(t *testing.T) {
{testJSONInterface},
{testJSONValuer},
{testSelectBool},
{testRawQuery},
{testFKViolation},
{testWithForeignKeysAndRules},
{testWithForeignKeys},
Expand Down Expand Up @@ -820,6 +821,14 @@ func testSelectBool(t *testing.T, db *bun.DB) {
require.False(t, flag)
}

func testRawQuery(t *testing.T, db *bun.DB) {
var num int
err := db.Raw("SELECT ?", 123).Scan(ctx, &num)

require.NoError(t, err)
require.Equal(t, 123, num)
}

func testFKViolation(t *testing.T, db *bun.DB) {
type Deck struct {
ID int `bun:",pk,autoincrement"`
Expand Down
47 changes: 47 additions & 0 deletions query_raw.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package bun

import (
"context"
"github.com/uptrace/bun/schema"
)

type RawQuery struct {
baseQuery

query string
args []interface{}
}

func (db *DB) Raw(query string, args ...interface{}) *RawQuery {
return &RawQuery{
baseQuery: baseQuery{
db: db,
conn: db.DB,
},
query: query,
args: args,
}
}

func (q *RawQuery) Scan(ctx context.Context, dest ...interface{}) error {
if q.err != nil {
return q.err
}

model, err := q.getModel(dest)
if err != nil {
return err
}

query := q.db.format(q.query, q.args)
_, err = q.scan(ctx, q, query, model, true)
return err
}

func (q *RawQuery) AppendQuery(fmter schema.Formatter, b []byte) ([]byte, error) {
return fmter.AppendQuery(b, q.query, q.args), nil
}

func (q *RawQuery) Operation() string {
return "SELECT"
}

0 comments on commit 127644d

Please sign in to comment.