stmt.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. stmt, err := format(q, args...)
  12. if err != nil {
  13. return nil, err
  14. }
  15. startTime := timex.Now()
  16. result, err := conn.Exec(q, args...)
  17. duration := timex.Since(startTime)
  18. if duration > slowThreshold {
  19. logx.WithDuration(duration).Slowf("[SQL] exec: slowcall - %s", stmt)
  20. } else {
  21. logx.WithDuration(duration).Infof("sql exec: %s", stmt)
  22. }
  23. if err != nil {
  24. logSqlError(stmt, err)
  25. }
  26. return result, err
  27. }
  28. func execStmt(conn stmtConn, args ...interface{}) (sql.Result, error) {
  29. stmt := fmt.Sprint(args...)
  30. startTime := timex.Now()
  31. result, err := conn.Exec(args...)
  32. duration := timex.Since(startTime)
  33. if duration > slowThreshold {
  34. logx.WithDuration(duration).Slowf("[SQL] execStmt: slowcall - %s", stmt)
  35. } else {
  36. logx.WithDuration(duration).Infof("sql execStmt: %s", stmt)
  37. }
  38. if err != nil {
  39. logSqlError(stmt, err)
  40. }
  41. return result, err
  42. }
  43. func query(conn sessionConn, scanner func(*sql.Rows) error, q string, args ...interface{}) error {
  44. stmt, err := format(q, args...)
  45. if err != nil {
  46. return err
  47. }
  48. startTime := timex.Now()
  49. rows, err := conn.Query(q, args...)
  50. duration := timex.Since(startTime)
  51. if duration > slowThreshold {
  52. logx.WithDuration(duration).Slowf("[SQL] query: slowcall - %s", stmt)
  53. } else {
  54. logx.WithDuration(duration).Infof("sql query: %s", stmt)
  55. }
  56. if err != nil {
  57. logSqlError(stmt, err)
  58. return err
  59. }
  60. defer rows.Close()
  61. return scanner(rows)
  62. }
  63. func queryStmt(conn stmtConn, scanner func(*sql.Rows) error, args ...interface{}) error {
  64. stmt := fmt.Sprint(args...)
  65. startTime := timex.Now()
  66. rows, err := conn.Query(args...)
  67. duration := timex.Since(startTime)
  68. if duration > slowThreshold {
  69. logx.WithDuration(duration).Slowf("[SQL] queryStmt: slowcall - %s", stmt)
  70. } else {
  71. logx.WithDuration(duration).Infof("sql queryStmt: %s", stmt)
  72. }
  73. if err != nil {
  74. logSqlError(stmt, err)
  75. return err
  76. }
  77. defer rows.Close()
  78. return scanner(rows)
  79. }