builder_insert.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 Eq) *Builder {
  11. builder := &Builder{cond: NewCond()}
  12. return builder.Insert(eq)
  13. }
  14. func (b *Builder) insertWriteTo(w Writer) error {
  15. if len(b.tableName) <= 0 {
  16. return ErrNoTableName
  17. }
  18. if len(b.inserts) <= 0 {
  19. return ErrNoColumnToInsert
  20. }
  21. if _, err := fmt.Fprintf(w, "INSERT INTO %s (", b.tableName); err != nil {
  22. return err
  23. }
  24. var args = make([]interface{}, 0)
  25. var bs []byte
  26. var valBuffer = bytes.NewBuffer(bs)
  27. var i = 0
  28. for _, col := range b.inserts.sortedKeys() {
  29. value := b.inserts[col]
  30. fmt.Fprint(w, col)
  31. if e, ok := value.(expr); ok {
  32. fmt.Fprintf(valBuffer, "(%s)", e.sql)
  33. args = append(args, e.args...)
  34. } else {
  35. fmt.Fprint(valBuffer, "?")
  36. args = append(args, value)
  37. }
  38. if i != len(b.inserts)-1 {
  39. if _, err := fmt.Fprint(w, ","); err != nil {
  40. return err
  41. }
  42. if _, err := fmt.Fprint(valBuffer, ","); err != nil {
  43. return err
  44. }
  45. }
  46. i = i + 1
  47. }
  48. if _, err := fmt.Fprint(w, ") Values ("); err != nil {
  49. return err
  50. }
  51. if _, err := w.Write(valBuffer.Bytes()); err != nil {
  52. return err
  53. }
  54. if _, err := fmt.Fprint(w, ")"); err != nil {
  55. return err
  56. }
  57. w.Append(args...)
  58. return nil
  59. }