builder_insert.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 update")
  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, value := range b.inserts {
  25. fmt.Fprint(w, col)
  26. if e, ok := value.(expr); ok {
  27. fmt.Fprint(valBuffer, e.sql)
  28. args = append(args, e.args...)
  29. } else {
  30. fmt.Fprint(valBuffer, "?")
  31. args = append(args, value)
  32. }
  33. if i != len(b.inserts)-1 {
  34. if _, err := fmt.Fprint(w, ","); err != nil {
  35. return err
  36. }
  37. if _, err := fmt.Fprint(valBuffer, ","); err != nil {
  38. return err
  39. }
  40. }
  41. i = i + 1
  42. }
  43. if _, err := fmt.Fprint(w, ") Values ("); err != nil {
  44. return err
  45. }
  46. if _, err := w.Write(valBuffer.Bytes()); err != nil {
  47. return err
  48. }
  49. if _, err := fmt.Fprint(w, ")"); err != nil {
  50. return err
  51. }
  52. w.Append(args...)
  53. return nil
  54. }