callback_row_query.go 953 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package gorm
  2. import (
  3. "database/sql"
  4. "fmt"
  5. )
  6. // Define callbacks for row query
  7. func init() {
  8. DefaultCallback.RowQuery().Register("gorm:row_query", rowQueryCallback)
  9. }
  10. type RowQueryResult struct {
  11. Row *sql.Row
  12. }
  13. type RowsQueryResult struct {
  14. Rows *sql.Rows
  15. Error error
  16. }
  17. // queryCallback used to query data from database
  18. func rowQueryCallback(scope *Scope) {
  19. if result, ok := scope.InstanceGet("row_query_result"); ok {
  20. scope.prepareQuerySQL()
  21. if str, ok := scope.Get("gorm:query_hint"); ok {
  22. scope.SQL = fmt.Sprint(str) + scope.SQL
  23. }
  24. if str, ok := scope.Get("gorm:query_option"); ok {
  25. scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
  26. }
  27. if rowResult, ok := result.(*RowQueryResult); ok {
  28. rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)
  29. } else if rowsResult, ok := result.(*RowsQueryResult); ok {
  30. rowsResult.Rows, rowsResult.Error = scope.SQLDB().Query(scope.SQL, scope.SQLVars...)
  31. }
  32. }
  33. }