utils.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package sqlx
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/core/mapping"
  7. )
  8. func desensitize(datasource string) string {
  9. // remove account
  10. pos := strings.LastIndex(datasource, "@")
  11. if 0 <= pos && pos+1 < len(datasource) {
  12. datasource = datasource[pos+1:]
  13. }
  14. return datasource
  15. }
  16. func escape(input string) string {
  17. var b strings.Builder
  18. for _, ch := range input {
  19. switch ch {
  20. case '\x00':
  21. b.WriteString(`\x00`)
  22. case '\r':
  23. b.WriteString(`\r`)
  24. case '\n':
  25. b.WriteString(`\n`)
  26. case '\\':
  27. b.WriteString(`\\`)
  28. case '\'':
  29. b.WriteString(`\'`)
  30. case '"':
  31. b.WriteString(`\"`)
  32. case '\x1a':
  33. b.WriteString(`\x1a`)
  34. default:
  35. b.WriteRune(ch)
  36. }
  37. }
  38. return b.String()
  39. }
  40. func format(query string, args ...interface{}) (string, error) {
  41. numArgs := len(args)
  42. if numArgs == 0 {
  43. return query, nil
  44. }
  45. var b strings.Builder
  46. argIndex := 0
  47. for _, ch := range query {
  48. if ch == '?' {
  49. if argIndex >= numArgs {
  50. return "", fmt.Errorf("error: %d ? in sql, but less arguments provided", argIndex)
  51. }
  52. arg := args[argIndex]
  53. argIndex++
  54. switch v := arg.(type) {
  55. case bool:
  56. if v {
  57. b.WriteByte('1')
  58. } else {
  59. b.WriteByte('0')
  60. }
  61. case string:
  62. b.WriteByte('\'')
  63. b.WriteString(escape(v))
  64. b.WriteByte('\'')
  65. default:
  66. b.WriteString(mapping.Repr(v))
  67. }
  68. } else {
  69. b.WriteRune(ch)
  70. }
  71. }
  72. if argIndex < numArgs {
  73. return "", fmt.Errorf("error: %d ? in sql, but more arguments provided", argIndex)
  74. }
  75. return b.String(), nil
  76. }
  77. func logInstanceError(datasource string, err error) {
  78. datasource = desensitize(datasource)
  79. logx.Errorf("Error on getting sql instance of %s: %v", datasource, err)
  80. }
  81. func logSqlError(stmt string, err error) {
  82. if err != nil && err != ErrNotFound {
  83. logx.Errorf("stmt: %s, error: %s", stmt, err.Error())
  84. }
  85. }