builder_insert.go 1.3 KB

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