gdb_result.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 (
  8. "database/sql"
  9. "github.com/gogf/gf/v2/errors/gerror"
  10. )
  11. // SqlResult is execution result for sql operations.
  12. // It also supports batch operation result for rowsAffected.
  13. type SqlResult struct {
  14. Result sql.Result
  15. Affected int64
  16. }
  17. // MustGetAffected returns the affected rows count, if any error occurs, it panics.
  18. func (r *SqlResult) MustGetAffected() int64 {
  19. rows, err := r.RowsAffected()
  20. if err != nil {
  21. err = gerror.Wrap(err, `sql.Result.RowsAffected failed`)
  22. panic(err)
  23. }
  24. return rows
  25. }
  26. // MustGetInsertId returns the last insert id, if any error occurs, it panics.
  27. func (r *SqlResult) MustGetInsertId() int64 {
  28. id, err := r.LastInsertId()
  29. if err != nil {
  30. err = gerror.Wrap(err, `sql.Result.LastInsertId failed`)
  31. panic(err)
  32. }
  33. return id
  34. }
  35. // RowsAffected returns the number of rows affected by an
  36. // update, insert, or delete. Not every database or database
  37. // driver may support this.
  38. // Also, See sql.Result.
  39. func (r *SqlResult) RowsAffected() (int64, error) {
  40. if r.Result == nil {
  41. return 0, nil
  42. }
  43. if r.Affected > 0 {
  44. return r.Affected, nil
  45. }
  46. if r.Result == nil {
  47. return 0, nil
  48. }
  49. return r.Result.RowsAffected()
  50. }
  51. // LastInsertId returns the integer generated by the database
  52. // in response to a command. Typically, this will be from an
  53. // "auto increment" column when inserting a new row. Not all
  54. // databases support this feature, and the syntax of such
  55. // statements varies.
  56. // Also, See sql.Result.
  57. func (r *SqlResult) LastInsertId() (int64, error) {
  58. if r.Result == nil {
  59. return 0, nil
  60. }
  61. return r.Result.LastInsertId()
  62. }