query_raw.go (1740B)
1 package bun 2 3 import ( 4 "context" 5 "database/sql" 6 7 "github.com/uptrace/bun/schema" 8 ) 9 10 type RawQuery struct { 11 baseQuery 12 13 query string 14 args []interface{} 15 } 16 17 // Deprecated: Use NewRaw instead. When add it to IDB, it conflicts with the sql.Conn#Raw 18 func (db *DB) Raw(query string, args ...interface{}) *RawQuery { 19 return &RawQuery{ 20 baseQuery: baseQuery{ 21 db: db, 22 conn: db.DB, 23 }, 24 query: query, 25 args: args, 26 } 27 } 28 29 func NewRawQuery(db *DB, query string, args ...interface{}) *RawQuery { 30 return &RawQuery{ 31 baseQuery: baseQuery{ 32 db: db, 33 conn: db.DB, 34 }, 35 query: query, 36 args: args, 37 } 38 } 39 40 func (q *RawQuery) Conn(db IConn) *RawQuery { 41 q.setConn(db) 42 return q 43 } 44 45 func (q *RawQuery) Err(err error) *RawQuery { 46 q.setErr(err) 47 return q 48 } 49 50 func (q *RawQuery) Exec(ctx context.Context, dest ...interface{}) (sql.Result, error) { 51 return q.scanOrExec(ctx, dest, len(dest) > 0) 52 } 53 54 func (q *RawQuery) Scan(ctx context.Context, dest ...interface{}) error { 55 _, err := q.scanOrExec(ctx, dest, true) 56 return err 57 } 58 59 func (q *RawQuery) scanOrExec( 60 ctx context.Context, dest []interface{}, hasDest bool, 61 ) (sql.Result, error) { 62 if q.err != nil { 63 return nil, q.err 64 } 65 66 var model Model 67 var err error 68 69 if hasDest { 70 model, err = q.getModel(dest) 71 if err != nil { 72 return nil, err 73 } 74 } 75 76 query := q.db.format(q.query, q.args) 77 var res sql.Result 78 79 if hasDest { 80 res, err = q.scan(ctx, q, query, model, hasDest) 81 } else { 82 res, err = q.exec(ctx, q, query) 83 } 84 85 if err != nil { 86 return nil, err 87 } 88 89 return res, nil 90 } 91 92 func (q *RawQuery) AppendQuery(fmter schema.Formatter, b []byte) ([]byte, error) { 93 return fmter.AppendQuery(b, q.query, q.args...), nil 94 } 95 96 func (q *RawQuery) Operation() string { 97 return "SELECT" 98 }