You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.1 KiB

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