stmt.go 2.0 KB

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