gdb_result.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright GoFrame Author(https://goframe.org). 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. // RowsAffected returns the number of rows affected by an
  31. // update, insert, or delete. Not every database or database
  32. // driver may support this.
  33. // Also See sql.Result.
  34. func (r *SqlResult) RowsAffected() (int64, error) {
  35. if r.affected > 0 {
  36. return r.affected, nil
  37. }
  38. if r.result == nil {
  39. return 0, nil
  40. }
  41. return r.result.RowsAffected()
  42. }
  43. // LastInsertId returns the integer generated by the database
  44. // in response to a command. Typically this will be from an
  45. // "auto increment" column when inserting a new row. Not all
  46. // databases support this feature, and the syntax of such
  47. // statements varies.
  48. // Also See sql.Result.
  49. func (r *SqlResult) LastInsertId() (int64, error) {
  50. if r.result == nil {
  51. return 0, nil
  52. }
  53. return r.result.LastInsertId()
  54. }