result_binary.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. bits := math.Float32bits(float32(f))
  136. return append(dst, byte(bits>>24), byte(bits>>16), byte(bits>>8), byte(bits)), nil
  137. case 701: // float8
  138. f, err := binaryFloat64(value)
  139. if err != nil {
  140. return dst, err
  141. }
  142. return appendUint64(dst, math.Float64bits(f)), nil
  143. case 1700: // numeric
  144. return appendNumericValue(dst, value)
  145. case 3802: // jsonb: version byte plus canonical JSON text
  146. dst = append(dst, 1)
  147. return append(dst, binaryJSONText(value)...), nil
  148. default:
  149. return dst, binaryEncodeErrorf("binary result format is not supported for OID %d", oid)
  150. }
  151. }
  152. // appendBinaryArray appends a one-dimensional binary array. The stored value is
  153. // the canonical PostgreSQL array text, so parsing it yields the same elements
  154. // the text format carries; NULL elements keep their -1 length and an empty
  155. // array has no dimension header, as array_recv expects.
  156. func appendBinaryArray(dst []byte, elementOID int32, value interface{}) ([]byte, error) {
  157. text := binaryJSONText(value)
  158. elements, err := executor.ParseArrayText(text)
  159. if err != nil {
  160. return dst, binaryEncodeErrorf("invalid array value %q: %v", text, err)
  161. }
  162. hasNull := false
  163. for _, element := range elements {
  164. if element == nil {
  165. hasNull = true
  166. break
  167. }
  168. }
  169. dimensions := int32(1)
  170. if len(elements) == 0 {
  171. dimensions = 0
  172. }
  173. dst = appendUint32(dst, uint32(dimensions))
  174. if hasNull {
  175. dst = appendUint32(dst, 1)
  176. } else {
  177. dst = appendUint32(dst, 0)
  178. }
  179. dst = appendUint32(dst, uint32(elementOID))
  180. if dimensions == 0 {
  181. return dst, nil
  182. }
  183. dst = appendUint32(dst, uint32(len(elements)))
  184. dst = appendUint32(dst, 1) // lower bound
  185. for _, element := range elements {
  186. if element == nil {
  187. dst = appendUint32(dst, math.MaxUint32) // -1: NULL element
  188. continue
  189. }
  190. start := len(dst)
  191. dst = appendUint32(dst, 0)
  192. dst, err = appendBinaryResultValue(dst, elementOID, *element)
  193. if err != nil {
  194. return dst, err
  195. }
  196. binary.BigEndian.PutUint32(dst[start:start+4], uint32(len(dst)-start-4))
  197. }
  198. return dst, nil
  199. }
  200. func appendUint32(dst []byte, n uint32) []byte {
  201. return append(dst, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  202. }
  203. func appendUint64(dst []byte, n uint64) []byte {
  204. 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))
  205. }
  206. // binaryInt64 converts an engine value to an integer result of the given OID.
  207. // Text is accepted because SQLite affinity can leave a text value in an integer
  208. // column; a value that does not fit the reported OID is an encoding error
  209. // instead of a silently truncated one.
  210. func binaryInt64(value interface{}, oid int32) (int64, error) {
  211. var n int64
  212. switch v := value.(type) {
  213. case int64:
  214. n = v
  215. case int:
  216. n = int64(v)
  217. case int32:
  218. n = int64(v)
  219. case int16:
  220. n = int64(v)
  221. case int8:
  222. n = int64(v)
  223. case float64:
  224. if math.Trunc(v) != v || v < math.MinInt64 || v > math.MaxInt64 {
  225. return 0, binaryEncodeErrorf("value %v is not an integer", v)
  226. }
  227. n = int64(v)
  228. case string:
  229. parsed, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
  230. if err != nil {
  231. return 0, binaryEncodeErrorf("value %q is not an integer", v)
  232. }
  233. n = parsed
  234. case []byte:
  235. parsed, err := strconv.ParseInt(strings.TrimSpace(string(v)), 10, 64)
  236. if err != nil {
  237. return 0, binaryEncodeErrorf("value %q is not an integer", v)
  238. }
  239. n = parsed
  240. default:
  241. return 0, binaryEncodeErrorf("value of type %T is not an integer", value)
  242. }
  243. switch oid {
  244. case 21:
  245. if n < math.MinInt16 || n > math.MaxInt16 {
  246. return 0, binaryEncodeErrorf("value %d does not fit int2", n)
  247. }
  248. case 23:
  249. if n < math.MinInt32 || n > math.MaxInt32 {
  250. return 0, binaryEncodeErrorf("value %d does not fit int4", n)
  251. }
  252. }
  253. return n, nil
  254. }
  255. // binaryFloat64 converts an engine value to a floating-point result.
  256. func binaryFloat64(value interface{}) (float64, error) {
  257. switch v := value.(type) {
  258. case float64:
  259. return v, nil
  260. case float32:
  261. return float64(v), nil
  262. case int64:
  263. return float64(v), nil
  264. case int:
  265. return float64(v), nil
  266. case int32:
  267. return float64(v), nil
  268. case int16:
  269. return float64(v), nil
  270. case string:
  271. parsed, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
  272. if err != nil {
  273. return 0, binaryEncodeErrorf("value %q is not a floating-point number", v)
  274. }
  275. return parsed, nil
  276. case []byte:
  277. parsed, err := strconv.ParseFloat(strings.TrimSpace(string(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. default:
  283. return 0, binaryEncodeErrorf("value of type %T is not a floating-point number", value)
  284. }
  285. }
  286. // binaryBool converts an engine value to a boolean result. Boolean columns hold
  287. // int64 0/1 from storage, bool from expressions, and text when the inserted
  288. // literal did not convert.
  289. func binaryBool(value interface{}) (bool, error) {
  290. switch v := value.(type) {
  291. case bool:
  292. return v, nil
  293. case int64:
  294. return v != 0, nil
  295. case int:
  296. return v != 0, nil
  297. case int32:
  298. return v != 0, nil
  299. case int16:
  300. return v != 0, nil
  301. case float64:
  302. return v != 0, nil
  303. case string:
  304. return boolText(v)
  305. case []byte:
  306. return boolText(string(v))
  307. default:
  308. return false, binaryEncodeErrorf("value of type %T is not a boolean", value)
  309. }
  310. }
  311. func boolText(text string) (bool, error) {
  312. switch strings.ToLower(strings.TrimSpace(text)) {
  313. case "t", "true", "1", "y", "yes", "on":
  314. return true, nil
  315. case "f", "false", "0", "n", "no", "off":
  316. return false, nil
  317. default:
  318. return false, binaryEncodeErrorf("value %q is not a boolean", text)
  319. }
  320. }
  321. // binaryBytes returns the bytes a binary bytea result carries. A non-[]byte
  322. // value uses the same text the bytea text format would send, which is the
  323. // escape-format interpretation of the value's spelling.
  324. func binaryBytes(value interface{}) []byte {
  325. if b, ok := value.([]byte); ok {
  326. return b
  327. }
  328. return []byte(textValueString(value))
  329. }
  330. // binaryJSONText returns the JSON text a jsonb result carries.
  331. func binaryJSONText(value interface{}) string {
  332. switch v := value.(type) {
  333. case string:
  334. return v
  335. case []byte:
  336. return string(v)
  337. default:
  338. return textValueString(value)
  339. }
  340. }
  341. // appendNumericValue appends a PostgreSQL binary numeric value. Numeric values
  342. // are stored as exact decimal text, so they are encoded digit by digit into
  343. // base-10000 groups; converting through float64 would round digits above 2^53
  344. // and lose the display scale (1.10 would become 1.1).
  345. func appendNumericValue(dst []byte, value interface{}) ([]byte, error) {
  346. var text string
  347. switch v := value.(type) {
  348. case string:
  349. text = v
  350. case []byte:
  351. text = string(v)
  352. case int64:
  353. text = strconv.FormatInt(v, 10)
  354. case int:
  355. text = strconv.FormatInt(int64(v), 10)
  356. case float64:
  357. text = strconv.FormatFloat(v, 'g', -1, 64)
  358. default:
  359. return dst, binaryEncodeErrorf("value of type %T is not numeric", value)
  360. }
  361. return appendNumericText(dst, text)
  362. }
  363. // appendNumericText encodes exact decimal text as a PostgreSQL numeric: ndigits,
  364. // weight, sign, dscale, then base-10000 groups. Exponents are applied to the
  365. // decimal point, trailing fraction zeros only affect dscale, and leading zero
  366. // groups are dropped while adjusting weight.
  367. func appendNumericText(dst []byte, text string) ([]byte, error) {
  368. invalid := func() ([]byte, error) {
  369. return dst, binaryEncodeErrorf("invalid numeric value %q", text)
  370. }
  371. s := strings.TrimSpace(text)
  372. if s == "" {
  373. return invalid()
  374. }
  375. negative := false
  376. if s[0] == '+' || s[0] == '-' {
  377. negative = s[0] == '-'
  378. s = s[1:]
  379. }
  380. if s == "" {
  381. return invalid()
  382. }
  383. exponent := 0
  384. if index := strings.IndexAny(s, "eE"); index >= 0 {
  385. parsed, err := strconv.Atoi(s[index+1:])
  386. if err != nil {
  387. return invalid()
  388. }
  389. if parsed > math.MaxInt16*4 || parsed < math.MinInt16*4 {
  390. return dst, binaryEncodeErrorf("numeric exponent %d is out of range", parsed)
  391. }
  392. exponent = parsed
  393. s = s[:index]
  394. }
  395. point := strings.IndexByte(s, '.')
  396. var digits string
  397. if point < 0 {
  398. point = len(s)
  399. digits = s
  400. } else {
  401. digits = s[:point] + s[point+1:]
  402. }
  403. if digits == "" {
  404. return invalid()
  405. }
  406. for i := 0; i < len(digits); i++ {
  407. if digits[i] < '0' || digits[i] > '9' {
  408. return invalid()
  409. }
  410. }
  411. point += exponent
  412. if point > math.MaxInt16*4 || point < math.MinInt16*4 {
  413. return dst, binaryEncodeErrorf("numeric exponent is out of range in %q", text)
  414. }
  415. // The display scale is the number of fraction digits after the exponent,
  416. // including zeros this encoder drops from the base-10000 groups (1.10 keeps
  417. // dscale 2).
  418. dscale := len(digits) - point
  419. if dscale < 0 {
  420. dscale = 0
  421. }
  422. if dscale > math.MaxInt16 {
  423. return dst, binaryEncodeErrorf("numeric scale %d is out of range", dscale)
  424. }
  425. integerDigits := ""
  426. if point >= len(digits) {
  427. integerDigits = digits + strings.Repeat("0", point-len(digits))
  428. } else if point > 0 {
  429. integerDigits = digits[:point]
  430. }
  431. fractionDigits := ""
  432. if point < 0 {
  433. fractionDigits = strings.Repeat("0", -point) + digits
  434. } else if point < len(digits) {
  435. fractionDigits = digits[point:]
  436. }
  437. var groups []uint16
  438. weight := 0
  439. if trimmed := strings.TrimLeft(integerDigits, "0"); trimmed != "" {
  440. padding := (4 - len(trimmed)%4) % 4
  441. padded := strings.Repeat("0", padding) + trimmed
  442. weight = len(padded)/4 - 1
  443. for i := 0; i < len(padded); i += 4 {
  444. groups = append(groups, uint16(decimalGroup(padded[i:i+4])))
  445. }
  446. }
  447. if trimmed := strings.TrimRight(fractionDigits, "0"); trimmed != "" {
  448. padding := (4 - len(trimmed)%4) % 4
  449. padded := trimmed + strings.Repeat("0", padding)
  450. if len(groups) == 0 {
  451. weight = -1
  452. }
  453. for i := 0; i < len(padded); i += 4 {
  454. groups = append(groups, uint16(decimalGroup(padded[i:i+4])))
  455. }
  456. }
  457. leading := 0
  458. for leading < len(groups) && groups[leading] == 0 {
  459. leading++
  460. }
  461. if leading == len(groups) {
  462. groups = nil
  463. weight = 0
  464. } else {
  465. groups = groups[leading:]
  466. weight -= leading
  467. }
  468. for len(groups) > 0 && groups[len(groups)-1] == 0 {
  469. groups = groups[:len(groups)-1]
  470. }
  471. if weight < math.MinInt16 || weight > math.MaxInt16 {
  472. return dst, binaryEncodeErrorf("numeric weight %d is out of range", weight)
  473. }
  474. if len(groups) > math.MaxUint16 {
  475. return dst, binaryEncodeErrorf("numeric has %d base-10000 groups, out of range", len(groups))
  476. }
  477. dst = append(dst, byte(len(groups)>>8), byte(len(groups)))
  478. dst = append(dst, byte(weight>>8), byte(weight))
  479. sign := 0
  480. if negative && len(groups) > 0 {
  481. sign = 0x4000
  482. }
  483. dst = append(dst, byte(sign>>8), byte(sign))
  484. dst = append(dst, byte(dscale>>8), byte(dscale))
  485. for _, group := range groups {
  486. dst = append(dst, byte(group>>8), byte(group))
  487. }
  488. return dst, nil
  489. }
  490. // decimalGroup parses four decimal digits, which are always in 0000-9999.
  491. func decimalGroup(digits string) int {
  492. n := 0
  493. for i := 0; i < len(digits); i++ {
  494. n = n*10 + int(digits[i]-'0')
  495. }
  496. return n
  497. }