Skip to content

Commit

Permalink
Query Row, Rows inside RowQuery callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jan 15, 2017
1 parent 97949fd commit c62e9bc
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
30 changes: 30 additions & 0 deletions callback_row_query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package gorm

import "database/sql"

// 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 rowResult, ok := result.(*RowQueryResult); ok {
rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)
} else if rowsResult, ok := result.(*RowsQueryResult); ok {
rowsResult.Rows, rowsResult.Error = scope.SQLDB().Query(scope.SQL, scope.SQLVars...)
}
}
}
14 changes: 10 additions & 4 deletions scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -886,16 +886,22 @@ func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[strin

func (scope *Scope) row() *sql.Row {
defer scope.trace(NowFunc())

result := &RowQueryResult{}
scope.InstanceSet("row_query_result", result)
scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
scope.prepareQuerySQL()
return scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)

return result.Row
}

func (scope *Scope) rows() (*sql.Rows, error) {
defer scope.trace(NowFunc())

result := &RowsQueryResult{}
scope.InstanceSet("row_query_result", result)
scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
scope.prepareQuerySQL()
return scope.SQLDB().Query(scope.SQL, scope.SQLVars...)

return result.Rows, result.Error
}

func (scope *Scope) initialize() *Scope {
Expand Down

0 comments on commit c62e9bc

Please sign in to comment.