prepared_statement.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package gorqlite
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // EscapeString sql-escapes a string.
  7. func EscapeString(value string) string {
  8. replace := [][2]string{
  9. {`\`, `\\`},
  10. {`\0`, `\\0`},
  11. {`\n`, `\\n`},
  12. {`\r`, `\\r`},
  13. {`'`, `''`},
  14. }
  15. for _, val := range replace {
  16. value = strings.Replace(value, val[0], val[1], -1)
  17. }
  18. return value
  19. }
  20. // PreparedStatement is a simple wrapper around fmt.Sprintf for prepared SQL
  21. // statements.
  22. type PreparedStatement struct {
  23. body string
  24. }
  25. // NewPreparedStatement takes a sprintf syntax SQL query for later binding of
  26. // parameters.
  27. func NewPreparedStatement(body string) PreparedStatement {
  28. return PreparedStatement{body: body}
  29. }
  30. // Bind takes arguments and SQL-escapes them, then calling fmt.Sprintf.
  31. func (p PreparedStatement) Bind(args ...interface{}) string {
  32. var spargs []interface{}
  33. for _, arg := range args {
  34. switch arg.(type) {
  35. case string:
  36. spargs = append(spargs, `'`+EscapeString(arg.(string))+`'`)
  37. case fmt.Stringer:
  38. spargs = append(spargs, `'`+EscapeString(arg.(fmt.Stringer).String())+`'`)
  39. default:
  40. spargs = append(spargs, arg)
  41. }
  42. }
  43. return fmt.Sprintf(p.body, spargs...)
  44. }