You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filter.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. return strings.Replace(sql, "`", dialect.QuoteStr(), -1)
  18. }
  19. // IdFilter filter SQL replace (id) to primary key column name
  20. type IdFilter struct {
  21. }
  22. type Quoter struct {
  23. dialect Dialect
  24. }
  25. func NewQuoter(dialect Dialect) *Quoter {
  26. return &Quoter{dialect}
  27. }
  28. func (q *Quoter) Quote(content string) string {
  29. return q.dialect.QuoteStr() + content + q.dialect.QuoteStr()
  30. }
  31. func (i *IdFilter) Do(sql string, dialect Dialect, table *Table) string {
  32. quoter := NewQuoter(dialect)
  33. if table != nil && len(table.PrimaryKeys) == 1 {
  34. sql = strings.Replace(sql, " `(id)` ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  35. sql = strings.Replace(sql, " "+quoter.Quote("(id)")+" ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  36. return strings.Replace(sql, " (id) ", " "+quoter.Quote(table.PrimaryKeys[0])+" ", -1)
  37. }
  38. return sql
  39. }
  40. // SeqFilter filter SQL replace ?, ? ... to $1, $2 ...
  41. type SeqFilter struct {
  42. Prefix string
  43. Start int
  44. }
  45. func (s *SeqFilter) Do(sql string, dialect Dialect, table *Table) string {
  46. segs := strings.Split(sql, "?")
  47. size := len(segs)
  48. res := ""
  49. for i, c := range segs {
  50. if i < size-1 {
  51. res += c + fmt.Sprintf("%s%v", s.Prefix, i+s.Start)
  52. }
  53. }
  54. res += segs[size-1]
  55. return res
  56. }