From 1a6db23b67dc3ace35953b0f8fb4cbd3ec22ad75 Mon Sep 17 00:00:00 2001 From: RozmiDan Date: Tue, 24 Nov 2026 11:01:53 +0300 Subject: [PATCH] Fix fixed-length CHAR encoding in batches --- batch_test.go | 71 +++++++++++++++++++++++++++++++ fbconn/statement.go | 2 +- fbconn/statement_internal_test.go | 43 +++++++++++++++++++ fbproto/client_test.go | 14 ++++++ fbproto/sqldata.go | 20 ++++++++- 5 files changed, 147 insertions(+), 3 deletions(-) diff --git a/batch_test.go b/batch_test.go index 016437cc..74d002c5 100644 --- a/batch_test.go +++ b/batch_test.go @@ -12,6 +12,77 @@ import ( "github.com/stretchr/testify/require" ) +func TestPreparedBatchFixedChar(t *testing.T) { + for _, tc := range []struct { + charset string + length string + full string + }{ + {"UTF8", "3", "😀😁😂"}, + {"ASCII", "5", "abcde"}, + } { + t.Run(tc.charset, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + config := defaultConnTestRunner.CreateConfig(ctx, t) + config.Encoding = tc.charset + conn := mustConnect(t, config) + defer closeConn(t, conn) + skipIfBatchUnsupported(ctx, t, conn) + table := "batch_fixed_char_" + strings.ToLower(tc.charset) + _, err := conn.Exec(ctx, "recreate table "+table+" (v char("+tc.length+") character set "+tc.charset+", b char(5) character set OCTETS, id integer primary key)") + require.NoError(t, err) + defer func() { + require.NoError(t, conn.DeallocateAll(context.Background())) + _, err := conn.Exec(context.Background(), "drop table "+table) + require.NoError(t, err) + }() + query := "insert into " + table + " (v, b, id) values (?, ?, ?)" + batch, err := conn.PrepareBatch(ctx, query) + require.NoError(t, err) + defer func() { require.NoError(t, batch.Close(context.Background())) }() + + require.ErrorContains(t, batch.Add("abc", []byte{1, 2, 3, 4, 5, 6}, 0), "exceeds declared length") + require.Zero(t, batch.PendingBytes()) + values := [][]any{ + {"abc", []byte{1, 0, 2}, 1}, + {"", []byte{}, 2}, + {nil, nil, 3}, + {tc.full, []byte{1, 2, 3, 4, 5}, 4}, + } + for _, row := range values { + require.NoError(t, batch.Add(row...)) + } + require.NoError(t, batch.Flush(ctx)) + result, err := batch.Exec(ctx) + require.NoError(t, err) + require.EqualValues(t, len(values), result.Affected) + + ordinary := []any{"xy", []byte{0xff}, 5} + _, err = conn.Exec(ctx, query, ordinary...) + require.NoError(t, err) + for _, row := range append(values, ordinary) { + var text *string + var binary []byte + var id int + err := conn.QueryRow(ctx, "select trim(v), b, id from "+table+" where id = ?", row[2]).Scan(&text, &binary, &id) + require.NoError(t, err) + require.Equal(t, row[2], id) + if row[0] == nil { + require.Nil(t, text) + require.Nil(t, binary) + } else { + require.NotNil(t, text) + require.Equal(t, row[0], *text) + wantBinary := make([]byte, 5) + copy(wantBinary, row[1].([]byte)) + require.Equal(t, wantBinary, binary) + } + } + }) + } +} + func TestExecBatchRows(t *testing.T) { ctx := context.Background() fbxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *fbx.Conn) { diff --git a/fbconn/statement.go b/fbconn/statement.go index 243cb7f9..d0fdd637 100644 --- a/fbconn/statement.go +++ b/fbconn/statement.go @@ -89,7 +89,7 @@ func (sd *StatementDescription) EncodeBatchRow(values [][]byte) ([]byte, error) var buf bytes.Buffer x := fbproto.NewXDRWriter(&buf) - if err := fbproto.WriteRowData(x, sd.StatementInfo.ParametersDescriptors, values); err != nil { + if err := fbproto.WriteBatchRowData(x, sd.StatementInfo.ParametersDescriptors, values); err != nil { return nil, err } diff --git a/fbconn/statement_internal_test.go b/fbconn/statement_internal_test.go index 5ab632bb..bfddea8d 100644 --- a/fbconn/statement_internal_test.go +++ b/fbconn/statement_internal_test.go @@ -10,6 +10,49 @@ import ( "github.com/stretchr/testify/require" ) +func TestEncodeBatchRowFixedChar(t *testing.T) { + for _, tc := range []struct { + name string + charset int + length int + value []byte + want []byte + wantErr bool + }{ + {"utf8", 4, 12, []byte("abc"), []byte("abc "), false}, + {"ascii with padding", 2, 5, []byte("abc"), []byte("abc "), false}, + {"empty text", 2, 5, []byte{}, []byte(" "), false}, + {"null", 4, 12, nil, nil, false}, + {"octets", fbproto.CS_BINARY, 5, []byte{1, 0, 2}, []byte{1, 0, 2, 0, 0, 0, 0, 0}, false}, + {"empty octets", fbproto.CS_BINARY, 5, []byte{}, make([]byte, 8), false}, + {"text too long", 4, 2, []byte("abc"), nil, true}, + {"octets too long", fbproto.CS_BINARY, 2, []byte{1, 2, 3}, nil, true}, + } { + t.Run(tc.name, func(t *testing.T) { + sd := &StatementDescription{StatementInfo: &StatementInfo{ + ParametersDescriptors: []fbproto.FieldDescriptor{ + {Type: fbproto.SQL_TYPE_TEXT, Subtype: tc.charset, Length: tc.length}, + {Type: fbproto.SQL_TYPE_LONG, Length: 4}, + }, + }} + row, err := sd.EncodeBatchRow([][]byte{tc.value, {0, 0, 0, 42}}) + if tc.wantErr { + require.ErrorContains(t, err, "exceeds declared length") + require.Nil(t, row) + return + } + require.NoError(t, err) + want := []byte{0, 0, 0, 0} + if tc.value == nil { + want[0] = 1 + } + want = append(want, tc.want...) + want = append(want, 0, 0, 0, 42) + require.Equal(t, want, row, "CHAR padding must preserve the following parameter") + }) + } +} + type prepareCleanupTestConn struct { noopConn written bytes.Buffer diff --git a/fbproto/client_test.go b/fbproto/client_test.go index febbd86b..029b5fc9 100644 --- a/fbproto/client_test.go +++ b/fbproto/client_test.go @@ -92,6 +92,20 @@ func TestXDRReaderBufferLengths(t *testing.T) { } } +func TestWriteRowDataUsesActualCharLength(t *testing.T) { + fields := []FieldDescriptor{ + {Type: SQL_TYPE_TEXT, Subtype: 4, Length: 12}, + {Type: SQL_TYPE_LONG, Length: 4}, + } + var buf bytes.Buffer + require.NoError(t, WriteRowData(NewXDRWriter(&buf), fields, [][]byte{[]byte("abc"), {0, 0, 0, 42}})) + require.Equal(t, []byte{ + 0, 0, 0, 0, + 'a', 'b', 'c', ' ', + 0, 0, 0, 42, + }, buf.Bytes()) +} + func TestReadRowDataVaryingLength(t *testing.T) { fields := []FieldDescriptor{{Type: SQL_TYPE_VARYING, Length: 8}, {Type: SQL_TYPE_LONG}} var scratch rowScratch diff --git a/fbproto/sqldata.go b/fbproto/sqldata.go index 082e396c..b93e2c3e 100644 --- a/fbproto/sqldata.go +++ b/fbproto/sqldata.go @@ -123,9 +123,19 @@ func ReadRowData(x *XDRReader, rowDescriptor []FieldDescriptor, scratch *rowScra return &SQLData{Nulls: nullsBitset, RowData: scratch.data, RowDescriptor: rowDescriptor}, nil } -// WriteRowData - write fields null-bitset and data in 13+ protocol version +// WriteRowData writes the null-bitset and values in protocol 13+ format. // https://firebirdsql.org/file/documentation/html/en/firebirddocs/wireprotocol/firebird-wire-protocol.html#wireprotocol-row-data-format func WriteRowData(x *XDRWriter, rowDescriptor []FieldDescriptor, values [][]byte) error { + return writeRowData(x, rowDescriptor, values, false) +} + +// WriteBatchRowData writes rows using the declared CHAR lengths, matching +// the batch BLR generated by CalculateBLR(rowDescriptor, nil). +func WriteBatchRowData(x *XDRWriter, rowDescriptor []FieldDescriptor, values [][]byte) error { + return writeRowData(x, rowDescriptor, values, true) +} + +func writeRowData(x *XDRWriter, rowDescriptor []FieldDescriptor, values [][]byte, useDeclaredTextLength bool) error { var err error nulls := NewBitSet(len(rowDescriptor)) for n, value := range values { @@ -144,7 +154,13 @@ func WriteRowData(x *XDRWriter, rowDescriptor []FieldDescriptor, values [][]byte } valueBuf := values[n] valueBufLen := len(valueBuf) - l := field.CalculateIoLength(values[n]) + l := field.CalculateIoLength(valueBuf) + if useDeclaredTextLength && field.Type == SQL_TYPE_TEXT { + if valueBufLen > field.Length { + return fmt.Errorf("batch CHAR parameter %d: value length %d exceeds declared length %d", n, valueBufLen, field.Length) + } + l = field.GetIOLength() + } if l == 0 { if err = x.WriteInt32(valueBufLen); err != nil { return err