values.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package pgx
  2. import (
  3. "errors"
  4. "github.com/jackc/pgx/v5/internal/pgio"
  5. "github.com/jackc/pgx/v5/pgtype"
  6. )
  7. // PostgreSQL format codes
  8. const (
  9. TextFormatCode = 0
  10. BinaryFormatCode = 1
  11. )
  12. func convertSimpleArgument(m *pgtype.Map, arg any) (any, error) {
  13. buf, err := m.Encode(0, TextFormatCode, arg, []byte{})
  14. if err != nil {
  15. return nil, err
  16. }
  17. if buf == nil {
  18. return nil, nil
  19. }
  20. return string(buf), nil
  21. }
  22. func encodeCopyValue(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) {
  23. sp := len(buf)
  24. buf = pgio.AppendInt32(buf, -1)
  25. argBuf, err := m.Encode(oid, BinaryFormatCode, arg, buf)
  26. if err != nil {
  27. if argBuf2, err2 := tryScanStringCopyValueThenEncode(m, buf, oid, arg); err2 == nil {
  28. argBuf = argBuf2
  29. } else {
  30. return nil, err
  31. }
  32. }
  33. if argBuf != nil {
  34. buf = argBuf
  35. pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
  36. }
  37. return buf, nil
  38. }
  39. func tryScanStringCopyValueThenEncode(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) {
  40. s, ok := arg.(string)
  41. if !ok {
  42. textBuf, err := m.Encode(oid, TextFormatCode, arg, nil)
  43. if err != nil {
  44. return nil, errors.New("not a string and cannot be encoded as text")
  45. }
  46. s = string(textBuf)
  47. }
  48. var v any
  49. err := m.Scan(oid, TextFormatCode, []byte(s), &v)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return m.Encode(oid, BinaryFormatCode, v, buf)
  54. }