applyToBuffer method

  1. @override
void applyToBuffer(
  1. PgByteDataWriter buffer
)
override

Implementation

@override
void applyToBuffer(PgByteDataWriter buffer) {
  buffer.writeUint8(ClientMessage.BindIdentifier);
  final portalName = buffer.encodeString(_portalName);
  final statementName = buffer.encodeString(_statementName);

  final parameterBytes =
      _parameters.map((p) => p.encodeAsBytes(buffer.encoding)).toList();
  final typeSpecCount = _parameters.where((p) => p.hasKnownType).length;
  var inputParameterElementCount = _parameters.length;
  if (typeSpecCount == _parameters.length || typeSpecCount == 0) {
    inputParameterElementCount = 1;
  }

  var length = 14;
  length += statementName.bytesLength;
  length += portalName.bytesLength;
  length += inputParameterElementCount * 2;
  length += parameterBytes.fold<int>(
      0, (len, bytes) => len + 4 + (bytes?.length ?? 0));

  buffer.writeUint32(length);

  // Name of portal.
  buffer.writeEncodedString(portalName);
  // Name of prepared statement.
  buffer.writeEncodedString(statementName);

  // OK, if we have no specified types at all, we can use 0. If we have all specified types, we can use 1. If we have a mix, we have to individually
  // call out each type.
  if (typeSpecCount == _parameters.length) {
    buffer.writeUint16(1);
    // Apply following format code for all parameters by indicating 1
    buffer.writeUint16(ClientMessage.FormatBinary);
  } else if (typeSpecCount == 0) {
    buffer.writeUint16(1);
    // Apply following format code for all parameters by indicating 1
    buffer.writeUint16(ClientMessage.FormatText);
  } else {
    // Well, we have some text and some binary, so we have to be explicit about each one
    buffer.writeUint16(_parameters.length);
    for (final p in _parameters) {
      buffer.writeUint16(p.hasKnownType
          ? ClientMessage.FormatBinary
          : ClientMessage.FormatText);
    }
  }

  // This must be the number of $n's in the query.
  buffer.writeUint16(_parameters.length);
  for (final bytes in parameterBytes) {
    if (bytes == null) {
      buffer.writeInt32(-1);
    } else {
      buffer.writeInt32(bytes.length);
      buffer.write(bytes);
    }
  }

  // Result columns - we always want binary for all of them, so specify 1:1.
  buffer.writeUint16(1);
  buffer.writeUint16(1);
}