gdb_result.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import "database/sql"
  8. // SqlResult is execution result for sql operations.
  9. // It also supports batch operation result for rowsAffected.
  10. type SqlResult struct {
  11. result sql.Result
  12. affected int64
  13. }
  14. // MustGetAffected returns the affected rows count, if any error occurs, it panics.
  15. func (r *SqlResult) MustGetAffected() int64 {
  16. rows, err := r.RowsAffected()
  17. if err != nil {
  18. panic(err)
  19. }
  20. return rows
  21. }
  22. // MustGetInsertId returns the last insert id, if any error occurs, it panics.
  23. func (r *SqlResult) MustGetInsertId() int64 {
  24. id, err := r.LastInsertId()
  25. if err != nil {
  26. panic(err)
  27. }
  28. return id
  29. }
  30. // see sql.Result.RowsAffected
  31. func (r *SqlResult) RowsAffected() (int64, error) {
  32. if r.affected > 0 {
  33. return r.affected, nil
  34. }
  35. if r.result == nil {
  36. return 0, nil
  37. }
  38. return r.result.RowsAffected()
  39. }
  40. // see sql.Result.LastInsertId
  41. func (r *SqlResult) LastInsertId() (int64, error) {
  42. if r.result == nil {
  43. return 0, nil
  44. }
  45. return r.result.LastInsertId()
  46. }