Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added raw query calls #596

Merged
merged 3 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
}