result_binary.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. package pgserver
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "strconv"
  8. "strings"
  9. "github.com/danfragoso/pizzasql-next/pkg/executor"
  10. )
  11. // Binary result encoding.
  12. //
  13. // DataRow values are normally sent in the PostgreSQL text format. A client that
  14. // asks for a binary result column (Bind result format code 1) gets the same
  15. // value in PostgreSQL's binary representation for the OID RowDescription
  16. // reports. Values are appended directly into the DataRow buffer, and a value
  17. // that cannot be represented fails the row before it is written.
  18. //
  19. // The supported OIDs are the ones this engine reports (see getOIDForType) plus
  20. // the array element types that appear in binary array headers. Types without a
  21. // binary representation here (timestamptz 1184, date 1082) are rejected at
  22. // execution time with 0A000 rather than being sent as text.
  23. // canEncodeBinaryResult reports whether the wire layer can encode a result
  24. // column of this OID in the binary format.
  25. func canEncodeBinaryResult(oid int32) bool {
  26. switch oid {
  27. case 16, // bool
  28. 17, // bytea
  29. 20, // int8
  30. 21, // int2
  31. 23, // int4
  32. 25, // text
  33. 700, // float4
  34. 701, // float8
  35. 1043, // varchar
  36. 1700, // numeric
  37. 3802: // jsonb
  38. return true
  39. }
  40. _, ok := binaryResultElementOID(oid)
  41. return ok
  42. }
  43. // binaryResultElementOID maps a one-dimensional array OID to the element OID its
  44. // binary envelope must carry.
  45. func binaryResultElementOID(arrayOID int32) (int32, bool) {
  46. switch arrayOID {
  47. case 1000: // bool[]
  48. return 16, true
  49. case 1005: // int2[]
  50. return 21, true
  51. case 1007: // int4[]
  52. return 23, true
  53. case 1009: // text[]
  54. return 25, true
  55. case 1015: // varchar[]
  56. return 1043, true
  57. case 1016: // int8[]
  58. return 20, true
  59. case 1021: // float4[]
  60. return 700, true
  61. case 1022: // float8[]
  62. return 701, true
  63. case 1231: // numeric[]
  64. return 1700, true
  65. default:
  66. return 0, false
  67. }
  68. }
  69. // binaryResultEncodeError reports a value the requested binary format cannot
  70. // represent, such as text left in an INTEGER column by SQLite affinity. The
  71. // connection reports it as invalid text input and sends no further rows.
  72. type binaryResultEncodeError struct {
  73. err error
  74. }
  75. func (e *binaryResultEncodeError) Error() string { return e.err.Error() }
  76. func (e *binaryResultEncodeError) Unwrap() error { return e.err }
  77. func binaryEncodeErrorf(format string, args ...interface{}) error {
  78. return &binaryResultEncodeError{err: fmt.Errorf(format, args...)}
  79. }
  80. // failBinaryEncode reports a value the requested binary format cannot represent.
  81. // Rows already written stay written (an error discards the rest of the result),
  82. // but the failing DataRow is never emitted.
  83. func (c *Connection) failBinaryEncode(err error) error {
  84. var encodeErr *binaryResultEncodeError
  85. if errors.As(err, &encodeErr) {
  86. return c.failExtended(ErrCodeInvalidText, err)
  87. }
  88. return err
  89. }
  90. // appendBinaryResultValue appends the PostgreSQL binary representation of value
  91. // for oid.
  92. func appendBinaryResultValue(dst []byte, oid int32, value interface{}) ([]byte, error) {
  93. if elementOID, ok := binaryResultElementOID(oid); ok {
  94. return appendBinaryArray(dst, elementOID, value)
  95. }
  96. switch oid {
  97. case 16: // bool
  98. flag, err := binaryBool(value)
  99. if err != nil {
  100. return dst, err
  101. }
  102. if flag {
  103. return append(dst, 1), nil
  104. }
  105. return append(dst, 0), nil
  106. case 17: // bytea
  107. return append(dst, binaryBytes(value)...), nil
  108. case 20, 21, 23: // int8, int2, int4
  109. width := 8
  110. switch oid {
  111. case 21:
  112. width = 2
  113. case 23:
  114. width = 4
  115. }
  116. n, err := binaryInt64(value, oid)
  117. if err != nil {
  118. return dst, err
  119. }
  120. switch width {
  121. case 2:
  122. return append(dst, byte(n>>8), byte(n)), nil
  123. case 4:
  124. return append(dst, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)), nil
  125. default:
  126. return appendUint64(dst, uint64(n)), nil
  127. }
  128. case 25, 1043: // text, varchar
  129. return append(dst, textValueString(value)...), nil
  130. case 700: // float4
  131. f, err := binaryFloat64(value)
  132. if err != nil {
  133. return dst, err
  134. }
  135. // A value beyond float4's range would otherwise convert to ±Inf and be
  136. // decoded as infinity instead of the stored value. NaN compares false
  137. // here and stays NaN, which float4 can represent.
  138. if math.Abs(f) > math.MaxFloat32 {
  139. return dst, binaryEncodeErrorf("value %v does not fit float4", f)
  140. }
  141. bits := math.Float32bits(float32(f))
  142. return append(dst, byte(bits>>24), byte(bits>>16), byte(bits>>8), byte(bits)), nil
  143. case 701: // float8
  144. f, err := binaryFloat64(value)
  145. if err != nil {
  146. return dst, err
  147. }
  148. return appendUint64(dst, math.Float64bits(f)), nil
  149. case 1700: // numeric
  150. return appendNumericValue(dst, value)
  151. case 3802: // jsonb: version byte plus canonical JSON text
  152. dst = append(dst, 1)
  153. return append(dst, binaryJSONText(value)...), nil
  154. default:
  155. return dst, binaryEncodeErrorf("binary result format is not supported for OID %d", oid)
  156. }
  157. }
  158. // appendBinaryArray appends a one-dimensional binary array. The stored value is
  159. // the canonical PostgreSQL array text, so parsing it yields the same elements
  160. // the text format carries; NULL elements keep their -1 length and an empty
  161. // array has no dimension header, as array_recv expects.
  162. func appendBinaryArray(dst []byte, elementOID int32, value interface{}) ([]byte, error) {
  163. text := binaryJSONText(value)
  164. elements, err := executor.ParseArrayText(text)
  165. if err != nil {
  166. return dst, binaryEncodeErrorf("invalid array value %q: %v", text, err)
  167. }
  168. hasNull := false
  169. for _, element := range elements {
  170. if element == nil {
  171. hasNull = true
  172. break
  173. }
  174. }
  175. dimensions := int32(1)
  176. if len(elements) == 0 {
  177. dimensions = 0
  178. }
  179. dst = appendUint32(dst, uint32(dimensions))
  180. if hasNull {
  181. dst = appendUint32(dst, 1)
  182. } else {
  183. dst = appendUint32(dst, 0)
  184. }
  185. dst = appendUint32(dst, uint32(elementOID))
  186. if dimensions == 0 {
  187. return dst, nil
  188. }
  189. dst = appendUint32(dst, uint32(len(elements)))
  190. dst = appendUint32(dst, 1) // lower bound
  191. for _, element := range elements {
  192. if element == nil {
  193. dst = appendUint32(dst, math.MaxUint32) // -1: NULL element
  194. continue
  195. }
  196. start := len(dst)
  197. dst = appendUint32(dst, 0)
  198. dst, err = appendBinaryResultValue(dst, elementOID, *element)
  199. if err != nil {
  200. return dst, err
  201. }
  202. binary.BigEndian.PutUint32(dst[start:start+4], uint32(len(dst)-start-4))
  203. }
  204. return dst, nil
  205. }
  206. func appendUint32(dst []byte, n uint32) []byte {
  207. return append(dst, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  208. }
  209. func appendUint64(dst []byte, n uint64) []byte {
  210. return append(dst, byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32), byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  211. }
  212. // binaryInt64 converts an engine value to an integer result of the given OID.
  213. // Text is accepted because SQLite affinity can leave a text value in an integer
  214. // column; a value that does not fit the reported OID is an encoding error
  215. // instead of a silently truncated one.
  216. func binaryInt64(value interface{}, oid int32) (int64, error) {
  217. var n int64
  218. switch v := value.(type) {
  219. case int64:
  220. n = v
  221. case int:
  222. n = int64(v)
  223. case int32:
  224. n = int64(v)
  225. case int16:
  226. n = int64(v)
  227. case int8:
  228. n = int64(v)
  229. case float64:
  230. if math.Trunc(v) != v || v < math.MinInt64 || v >= math.MaxInt64 {
  231. return 0, binaryEncodeErrorf("value %v is not an integer", v)
  232. }
  233. n = int64(v)
  234. case string:
  235. parsed, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
  236. if err != nil {
  237. return 0, binaryEncodeErrorf("value %q is not an integer", v)
  238. }
  239. n = parsed
  240. case []byte:
  241. parsed, err := strconv.ParseInt(strings.TrimSpace(string(v)), 10, 64)
  242. if err != nil {
  243. return 0, binaryEncodeErrorf("value %q is not an integer", v)
  244. }
  245. n = parsed
  246. default:
  247. return 0, binaryEncodeErrorf("value of type %T is not an integer", value)
  248. }
  249. switch oid {
  250. case 21:
  251. if n < math.MinInt16 || n > math.MaxInt16 {
  252. return 0, binaryEncodeErrorf("value %d does not fit int2", n)
  253. }
  254. case 23:
  255. if n < math.MinInt32 || n > math.MaxInt32 {
  256. return 0, binaryEncodeErrorf("value %d does not fit int4", n)
  257. }
  258. }
  259. return n, nil
  260. }
  261. // binaryFloat64 converts an engine value to a floating-point result.
  262. func binaryFloat64(value interface{}) (float64, error) {
  263. switch v := value.(type) {
  264. case float64:
  265. return v, nil
  266. case float32:
  267. return float64(v), nil
  268. case int64:
  269. return float64(v), nil
  270. case int:
  271. return float64(v), nil
  272. case int32:
  273. return float64(v), nil
  274. case int16:
  275. return float64(v), nil
  276. case string:
  277. parsed, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
  278. if err != nil {
  279. return 0, binaryEncodeErrorf("value %q is not a floating-point number", v)
  280. }
  281. return parsed, nil
  282. case []byte:
  283. parsed, err := strconv.ParseFloat(strings.TrimSpace(string(v)), 64)
  284. if err != nil {
  285. return 0, binaryEncodeErrorf("value %q is not a floating-point number", v)
  286. }
  287. return parsed, nil
  288. default:
  289. return 0, binaryEncodeErrorf("value of type %T is not a floating-point number", value)
  290. }
  291. }
  292. // binaryBool converts an engine value to a boolean result. Boolean columns hold
  293. // int64 0/1 from storage, bool from expressions, and text when the inserted
  294. // literal did not convert.
  295. func binaryBool(value interface{}) (bool, error) {
  296. switch v := value.(type) {
  297. case bool:
  298. return v, nil
  299. case int64:
  300. return v != 0, nil
  301. case int:
  302. return v != 0, nil
  303. case int32:
  304. return v != 0, nil
  305. case int16:
  306. return v != 0, nil
  307. case float64:
  308. return v != 0, nil
  309. case string:
  310. return boolText(v)
  311. case []byte:
  312. return boolText(string(v))
  313. default:
  314. return false, binaryEncodeErrorf("value of type %T is not a boolean", value)
  315. }
  316. }
  317. func boolText(text string) (bool, error) {
  318. switch strings.ToLower(strings.TrimSpace(text)) {
  319. case "t", "true", "1", "y", "yes", "on":
  320. return true, nil
  321. case "f", "false", "0", "n", "no", "off":
  322. return false, nil
  323. default:
  324. return false, binaryEncodeErrorf("value %q is not a boolean", text)
  325. }
  326. }
  327. // binaryBytes returns the bytes a binary bytea result carries. A non-[]byte
  328. // value uses the same text the bytea text format would send, which is the
  329. // escape-format interpretation of the value's spelling.
  330. func binaryBytes(value interface{}) []byte {
  331. if b, ok := value.([]byte); ok {
  332. return b
  333. }
  334. return []byte(textValueString(value))
  335. }
  336. // binaryJSONText returns the JSON text a jsonb result carries.
  337. func binaryJSONText(value interface{}) string {
  338. switch v := value.(type) {
  339. case string:
  340. return v
  341. case []byte:
  342. return string(v)
  343. default:
  344. return textValueString(value)
  345. }
  346. }
  347. // appendNumericValue appends a PostgreSQL binary numeric value. Numeric values
  348. // are stored as exact decimal text, so they are encoded digit by digit into
  349. // base-10000 groups; converting through float64 would round digits above 2^53
  350. // and lose the display scale (1.10 would become 1.1).
  351. func appendNumericValue(dst []byte, value interface{}) ([]byte, error) {
  352. var text string
  353. switch v := value.(type) {
  354. case string:
  355. text = v
  356. case []byte:
  357. text = string(v)
  358. case int64:
  359. text = strconv.FormatInt(v, 10)
  360. case int:
  361. text = strconv.FormatInt(int64(v), 10)
  362. case float64:
  363. text = strconv.FormatFloat(v, 'g', -1, 64)
  364. default:
  365. return dst, binaryEncodeErrorf("value of type %T is not numeric", value)
  366. }
  367. return appendNumericText(dst, text)
  368. }
  369. // appendNumericText encodes exact decimal text as a PostgreSQL numeric: ndigits,
  370. // weight, sign, dscale, then base-10000 groups. Exponents are applied to the
  371. // decimal point, trailing fraction zeros only affect dscale, and leading zero
  372. // groups are dropped while adjusting weight.
  373. func appendNumericText(dst []byte, text string) ([]byte, error) {
  374. invalid := func() ([]byte, error) {
  375. return dst, binaryEncodeErrorf("invalid numeric value %q", text)
  376. }
  377. s := strings.TrimSpace(text)
  378. if s == "" {
  379. return invalid()
  380. }
  381. negative := false
  382. if s[0] == '+' || s[0] == '-' {
  383. negative = s[0] == '-'
  384. s = s[1:]
  385. }
  386. if s == "" {
  387. return invalid()
  388. }
  389. exponent := 0
  390. if index := strings.IndexAny(s, "eE"); index >= 0 {
  391. parsed, err := strconv.Atoi(s[index+1:])
  392. if err != nil {
  393. return invalid()
  394. }
  395. if parsed > math.MaxInt16*4 || parsed < math.MinInt16*4 {
  396. return dst, binaryEncodeErrorf("numeric exponent %d is out of range", parsed)
  397. }
  398. exponent = parsed
  399. s = s[:index]
  400. }
  401. point := strings.IndexByte(s, '.')
  402. var digits string
  403. if point < 0 {
  404. point = len(s)
  405. digits = s
  406. } else {
  407. digits = s[:point] + s[point+1:]
  408. }
  409. if digits == "" {
  410. return invalid()
  411. }
  412. for i := 0; i < len(digits); i++ {
  413. if digits[i] < '0' || digits[i] > '9' {
  414. return invalid()
  415. }
  416. }
  417. point += exponent
  418. if point > math.MaxInt16*4 || point < math.MinInt16*4 {
  419. return dst, binaryEncodeErrorf("numeric exponent is out of range in %q", text)
  420. }
  421. // The display scale is the number of fraction digits after the exponent,
  422. // including zeros this encoder drops from the base-10000 groups (1.10 keeps
  423. // dscale 2).
  424. dscale := len(digits) - point
  425. if dscale < 0 {
  426. dscale = 0
  427. }
  428. if dscale > math.MaxInt16 {
  429. return dst, binaryEncodeErrorf("numeric scale %d is out of range", dscale)
  430. }
  431. integerDigits := ""
  432. if point >= len(digits) {
  433. integerDigits = digits + strings.Repeat("0", point-len(digits))
  434. } else if point > 0 {
  435. integerDigits = digits[:point]
  436. }
  437. fractionDigits := ""
  438. if point < 0 {
  439. fractionDigits = strings.Repeat("0", -point) + digits
  440. } else if point < len(digits) {
  441. fractionDigits = digits[point:]
  442. }
  443. var groups []uint16
  444. weight := 0
  445. if trimmed := strings.TrimLeft(integerDigits, "0"); trimmed != "" {
  446. padding := (4 - len(trimmed)%4) % 4
  447. padded := strings.Repeat("0", padding) + trimmed
  448. weight = len(padded)/4 - 1
  449. for i := 0; i < len(padded); i += 4 {
  450. groups = append(groups, uint16(decimalGroup(padded[i:i+4])))
  451. }
  452. }
  453. if trimmed := strings.TrimRight(fractionDigits, "0"); trimmed != "" {
  454. padding := (4 - len(trimmed)%4) % 4
  455. padded := trimmed + strings.Repeat("0", padding)
  456. if len(groups) == 0 {
  457. weight = -1
  458. }
  459. for i := 0; i < len(padded); i += 4 {
  460. groups = append(groups, uint16(decimalGroup(padded[i:i+4])))
  461. }
  462. }
  463. leading := 0
  464. for leading < len(groups) && groups[leading] == 0 {
  465. leading++
  466. }
  467. if leading == len(groups) {
  468. groups = nil
  469. weight = 0
  470. } else {
  471. groups = groups[leading:]
  472. weight -= leading
  473. }
  474. for len(groups) > 0 && groups[len(groups)-1] == 0 {
  475. groups = groups[:len(groups)-1]
  476. }
  477. if weight < math.MinInt16 || weight > math.MaxInt16 {
  478. return dst, binaryEncodeErrorf("numeric weight %d is out of range", weight)
  479. }
  480. if len(groups) > math.MaxInt16 {
  481. return dst, binaryEncodeErrorf("numeric has %d base-10000 groups, out of range", len(groups))
  482. }
  483. dst = append(dst, byte(len(groups)>>8), byte(len(groups)))
  484. dst = append(dst, byte(weight>>8), byte(weight))
  485. sign := 0
  486. if negative && len(groups) > 0 {
  487. sign = 0x4000
  488. }
  489. dst = append(dst, byte(sign>>8), byte(sign))
  490. dst = append(dst, byte(dscale>>8), byte(dscale))
  491. for _, group := range groups {
  492. dst = append(dst, byte(group>>8), byte(group))
  493. }
  494. return dst, nil
  495. }
  496. // decimalGroup parses four decimal digits, which are always in 0000-9999.
  497. func decimalGroup(digits string) int {
  498. n := 0
  499. for i := 0; i < len(digits); i++ {
  500. n = n*10 + int(digits[i]-'0')
  501. }
  502. return n
  503. }