/vendor/gopkg.in/src-d/go-vitess.v1/vt/sqlparser/encodable.go

https://github.com/campoy/justforfunc · Go · 99 lines · 63 code · 11 blank · 25 comment · 17 complexity · fe4f15c22d0dc58674bbb33951c19bfe MD5 · raw file

  1. /*
  2. Copyright 2017 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package sqlparser
  14. import (
  15. "bytes"
  16. "gopkg.in/src-d/go-vitess.v1/sqltypes"
  17. )
  18. // This file contains types that are 'Encodable'.
  19. // Encodable defines the interface for types that can
  20. // be custom-encoded into SQL.
  21. type Encodable interface {
  22. EncodeSQL(buf *bytes.Buffer)
  23. }
  24. // InsertValues is a custom SQL encoder for the values of
  25. // an insert statement.
  26. type InsertValues [][]sqltypes.Value
  27. // EncodeSQL performs the SQL encoding for InsertValues.
  28. func (iv InsertValues) EncodeSQL(buf *bytes.Buffer) {
  29. for i, rows := range iv {
  30. if i != 0 {
  31. buf.WriteString(", ")
  32. }
  33. buf.WriteByte('(')
  34. for j, bv := range rows {
  35. if j != 0 {
  36. buf.WriteString(", ")
  37. }
  38. bv.EncodeSQL(buf)
  39. }
  40. buf.WriteByte(')')
  41. }
  42. }
  43. // TupleEqualityList is for generating equality constraints
  44. // for tables that have composite primary keys.
  45. type TupleEqualityList struct {
  46. Columns []ColIdent
  47. Rows [][]sqltypes.Value
  48. }
  49. // EncodeSQL generates the where clause constraints for the tuple
  50. // equality.
  51. func (tpl *TupleEqualityList) EncodeSQL(buf *bytes.Buffer) {
  52. if len(tpl.Columns) == 1 {
  53. tpl.encodeAsIn(buf)
  54. return
  55. }
  56. tpl.encodeAsEquality(buf)
  57. }
  58. func (tpl *TupleEqualityList) encodeAsIn(buf *bytes.Buffer) {
  59. Append(buf, tpl.Columns[0])
  60. buf.WriteString(" in (")
  61. for i, r := range tpl.Rows {
  62. if i != 0 {
  63. buf.WriteString(", ")
  64. }
  65. r[0].EncodeSQL(buf)
  66. }
  67. buf.WriteByte(')')
  68. }
  69. func (tpl *TupleEqualityList) encodeAsEquality(buf *bytes.Buffer) {
  70. for i, r := range tpl.Rows {
  71. if i != 0 {
  72. buf.WriteString(" or ")
  73. }
  74. buf.WriteString("(")
  75. for j, c := range tpl.Columns {
  76. if j != 0 {
  77. buf.WriteString(" and ")
  78. }
  79. Append(buf, c)
  80. buf.WriteString(" = ")
  81. r[j].EncodeSQL(buf)
  82. }
  83. buf.WriteByte(')')
  84. }
  85. }