filter.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2019 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package core
  5. import (
  6. "fmt"
  7. "strings"
  8. )
  9. // Filter is an interface to filter SQL
  10. type Filter interface {
  11. Do(sql string, dialect Dialect, table *Table) string
  12. }
  13. // QuoteFilter filter SQL replace ` to database's own quote character
  14. type QuoteFilter struct {
  15. }
  16. func (s *QuoteFilter) Do(sql string, dialect Dialect, table *Table) string {
  17. dummy := dialect.Quote("")
  18. if len(dummy) != 2 {
  19. return sql
  20. }
  21. prefix, suffix := dummy[0], dummy[1]
  22. raw := []byte(sql)
  23. for i, cnt := 0, 0; i < len(raw); i = i + 1 {
  24. if raw[i] == '`' {
  25. if cnt%2 == 0 {
  26. raw[i] = prefix
  27. } else {
  28. raw[i] = suffix
  29. }
  30. cnt++
  31. }
  32. }
  33. return string(raw)
  34. }
  35. // IdFilter filter SQL replace (id) to primary key column name
  36. type IdFilter struct {
  37. }
  38. type Quoter struct {
  39. dialect Dialect
  40. }
  41. func NewQuoter(dialect Dialect) *Quoter {
  42. return &Quoter{dialect}
  43. }
  44. func (q *Quoter) Quote(content string) string {
  45. return q.dialect.Quote(content)
  46. }
  47. func (i *IdFilter) Do(sql string, dialect Dialect, table *Table) string {
  48. quoter := NewQuoter(dialect)
  49. if table != nil && len(table.PrimaryKeys) == 1 {
  50. sql = strings.Replace(sql, " `(id)` ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  51. sql = strings.Replace(sql, " "+quoter.Quote("(id)")+" ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  52. return strings.Replace(sql, " (id) ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  53. }
  54. return sql
  55. }
  56. // SeqFilter filter SQL replace ?, ? ... to $1, $2 ...
  57. type SeqFilter struct {
  58. Prefix string
  59. Start int
  60. }
  61. func (s *SeqFilter) Do(sql string, dialect Dialect, table *Table) string {
  62. segs := strings.Split(sql, "?")
  63. size := len(segs)
  64. res := ""
  65. for i, c := range segs {
  66. if i < size-1 {
  67. res += c + fmt.Sprintf("%s%v", s.Prefix, i+s.Start)
  68. }
  69. }
  70. res += segs[size-1]
  71. return res
  72. }