builder_insert.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 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 builder
  5. import (
  6. "bytes"
  7. "fmt"
  8. )
  9. // Insert creates an insert Builder
  10. func Insert(eq ...interface{}) *Builder {
  11. builder := &Builder{cond: NewCond()}
  12. return builder.Insert(eq...)
  13. }
  14. func (b *Builder) insertSelectWriteTo(w Writer) error {
  15. if _, err := fmt.Fprintf(w, "INSERT INTO %s ", b.into); err != nil {
  16. return err
  17. }
  18. if len(b.insertCols) > 0 {
  19. fmt.Fprintf(w, "(")
  20. for _, col := range b.insertCols {
  21. fmt.Fprintf(w, col)
  22. }
  23. fmt.Fprintf(w, ") ")
  24. }
  25. return b.selectWriteTo(w)
  26. }
  27. func (b *Builder) insertWriteTo(w Writer) error {
  28. if len(b.into) <= 0 {
  29. return ErrNoTableName
  30. }
  31. if len(b.insertCols) <= 0 && b.from == "" {
  32. return ErrNoColumnToInsert
  33. }
  34. if b.into != "" && b.from != "" {
  35. return b.insertSelectWriteTo(w)
  36. }
  37. if _, err := fmt.Fprintf(w, "INSERT INTO %s (", b.into); err != nil {
  38. return err
  39. }
  40. var args = make([]interface{}, 0)
  41. var bs []byte
  42. var valBuffer = bytes.NewBuffer(bs)
  43. for i, col := range b.insertCols {
  44. value := b.insertVals[i]
  45. fmt.Fprint(w, col)
  46. if e, ok := value.(expr); ok {
  47. fmt.Fprintf(valBuffer, "(%s)", e.sql)
  48. args = append(args, e.args...)
  49. } else {
  50. fmt.Fprint(valBuffer, "?")
  51. args = append(args, value)
  52. }
  53. if i != len(b.insertCols)-1 {
  54. if _, err := fmt.Fprint(w, ","); err != nil {
  55. return err
  56. }
  57. if _, err := fmt.Fprint(valBuffer, ","); err != nil {
  58. return err
  59. }
  60. }
  61. }
  62. if _, err := fmt.Fprint(w, ") Values ("); err != nil {
  63. return err
  64. }
  65. if _, err := w.Write(valBuffer.Bytes()); err != nil {
  66. return err
  67. }
  68. if _, err := fmt.Fprint(w, ")"); err != nil {
  69. return err
  70. }
  71. w.Append(args...)
  72. return nil
  73. }