forked from jinzhu/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback_row_query.go
47 lines (39 loc) · 1.04 KB
/
callback_row_query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package gorm
import (
"database/sql"
"fmt"
)
// Define callbacks for row query
func init() {
DefaultCallback.RowQuery().Register("gorm:row_query", rowQueryCallback)
}
type RowQueryResult struct {
Row *sql.Row
}
type RowsQueryResult struct {
Rows *sql.Rows
Error error
}
// queryCallback used to query data from database
func rowQueryCallback(scope *Scope) {
if result, ok := scope.InstanceGet("row_query_result"); ok {
scope.prepareQuerySQL()
if scope.DB() != nil {
scope.DB().SQL = FormatSQL(scope.SQL, scope.SQLVars...)
}
if str, ok := scope.Get("gorm:query_hint"); ok {
scope.SQL = fmt.Sprint(str) + scope.SQL
}
if rowResult, ok := result.(*RowQueryResult); ok {
rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)
} else if rowsResult, ok := result.(*RowsQueryResult); ok {
rows, err := scope.SQLDB().Query(scope.SQL, scope.SQLVars...)
rowsResult.Rows = rows
if rowsResult.Error != nil {
rowsResult.Error = NewGormError(err, scope.SQL)
} else {
rowsResult.Error = err
}
}
}
}