DecodeRawBytesToByteArray converts raw bytes to a SQL-level byte array according to the encoding specification in "be". When using the Hex format, the caller is responsible for skipping the "\x" prefix, if any. See DecodeRawBytesToByteArrayAuto() below for an alternative.
(data string, be sessiondata.BytesEncodeFormat)
| 290 | // "\x" prefix, if any. See DecodeRawBytesToByteArrayAuto() below for |
| 291 | // an alternative. |
| 292 | func DecodeRawBytesToByteArray(data string, be sessiondata.BytesEncodeFormat) ([]byte, error) { |
| 293 | switch be { |
| 294 | case sessiondata.BytesEncodeHex: |
| 295 | return hex.DecodeString(data) |
| 296 | |
| 297 | case sessiondata.BytesEncodeEscape: |
| 298 | // PostgreSQL does not allow all the escapes formats recognized by |
| 299 | // CockroachDB's scanner. It only recognizes octal and \\ for the |
| 300 | // backslash itself. |
| 301 | // See https://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667 |
| 302 | res := make([]byte, 0, len(data)) |
| 303 | for i := 0; i < len(data); i++ { |
| 304 | ch := data[i] |
| 305 | if ch != '\\' { |
| 306 | res = append(res, ch) |
| 307 | continue |
| 308 | } |
| 309 | if i >= len(data)-1 { |
| 310 | return nil, pgerror.New(pgcode.InvalidEscapeSequence, |
| 311 | "bytea encoded value ends with escape character") |
| 312 | } |
| 313 | if data[i+1] == '\\' { |
| 314 | res = append(res, '\\') |
| 315 | i++ |
| 316 | continue |
| 317 | } |
| 318 | if i+3 >= len(data) { |
| 319 | return nil, pgerror.New(pgcode.InvalidEscapeSequence, |
| 320 | "bytea encoded value ends with incomplete escape sequence") |
| 321 | } |
| 322 | b := byte(0) |
| 323 | for j := 1; j <= 3; j++ { |
| 324 | octDigit := data[i+j] |
| 325 | if octDigit < '0' || octDigit > '7' || (j == 1 && octDigit > '3') { |
| 326 | return nil, pgerror.New(pgcode.InvalidEscapeSequence, |
| 327 | "invalid bytea escape sequence") |
| 328 | } |
| 329 | b = (b << 3) | (octDigit - '0') |
| 330 | } |
| 331 | res = append(res, b) |
| 332 | i += 3 |
| 333 | } |
| 334 | return res, nil |
| 335 | |
| 336 | case sessiondata.BytesEncodeBase64: |
| 337 | return base64.StdEncoding.DecodeString(data) |
| 338 | |
| 339 | default: |
| 340 | return nil, errors.AssertionFailedf("unhandled format: %s", be) |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // DecodeRawBytesToByteArrayAuto detects which format to use with |
| 345 | // DecodeRawBytesToByteArray(). It only supports hex ("\x" prefix) |
no test coverage detected
searching dependent graphs…