stmt.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package sqlx
  2. import (
  3. "database/sql"
  4. "time"
  5. "git.i2edu.net/i2/go-zero/core/logx"
  6. "git.i2edu.net/i2/go-zero/core/timex"
  7. )
  8. const slowThreshold = time.Millisecond * 500
  9. func exec(conn sessionConn, q string, args ...interface{}) (sql.Result, error) {
  10. stmt, err := format(q, args...)
  11. if err != nil {
  12. return nil, err
  13. }
  14. startTime := timex.Now()
  15. result, err := conn.Exec(q, args...)
  16. duration := timex.Since(startTime)
  17. if duration > slowThreshold {
  18. logx.WithDuration(duration).Slowf("[SQL] exec: slowcall - %s", stmt)
  19. } else {
  20. logx.WithDuration(duration).Infof("sql exec: %s", stmt)
  21. }
  22. if err != nil {
  23. logSqlError(stmt, err)
  24. }
  25. return result, err
  26. }
  27. func execStmt(conn stmtConn, q string, args ...interface{}) (sql.Result, error) {
  28. stmt, err := format(q, args...)
  29. if err != nil {
  30. return nil, err
  31. }
  32. startTime := timex.Now()
  33. result, err := conn.Exec(args...)
  34. duration := timex.Since(startTime)
  35. if duration > slowThreshold {
  36. logx.WithDuration(duration).Slowf("[SQL] execStmt: slowcall - %s", stmt)
  37. } else {
  38. logx.WithDuration(duration).Infof("sql execStmt: %s", stmt)
  39. }
  40. if err != nil {
  41. logSqlError(stmt, err)
  42. }
  43. return result, err
  44. }
  45. func query(conn sessionConn, scanner func(*sql.Rows) error, q string, args ...interface{}) error {
  46. stmt, err := format(q, args...)
  47. if err != nil {
  48. return err
  49. }
  50. startTime := timex.Now()
  51. rows, err := conn.Query(q, args...)
  52. duration := timex.Since(startTime)
  53. if duration > slowThreshold {
  54. logx.WithDuration(duration).Slowf("[SQL] query: slowcall - %s", stmt)
  55. } else {
  56. logx.WithDuration(duration).Infof("sql query: %s", stmt)
  57. }
  58. if err != nil {
  59. logSqlError(stmt, err)
  60. return err
  61. }
  62. defer rows.Close()
  63. return scanner(rows)
  64. }
  65. func queryStmt(conn stmtConn, scanner func(*sql.Rows) error, q string, args ...interface{}) error {
  66. stmt, err := format(q, args...)
  67. if err != nil {
  68. return err
  69. }
  70. startTime := timex.Now()
  71. rows, err := conn.Query(args...)
  72. duration := timex.Since(startTime)
  73. if duration > slowThreshold {
  74. logx.WithDuration(duration).Slowf("[SQL] queryStmt: slowcall - %s", stmt)
  75. } else {
  76. logx.WithDuration(duration).Infof("sql queryStmt: %s", stmt)
  77. }
  78. if err != nil {
  79. logSqlError(stmt, err)
  80. return err
  81. }
  82. defer rows.Close()
  83. return scanner(rows)
  84. }