Skip to content

Commit be26d11

Browse files
authored
Merge pull request #58 from FirebirdSQL/38_fix_batch_char_encoding
Use declared char lengths when encoding batch rows to keep following parameters aligned. Add input validation and regression tests, release temporary buffers on encoding errors, and reduce padding allocations.
2 parents a98cdaa + a78cdbe commit be26d11

8 files changed

Lines changed: 353 additions & 22 deletions

File tree

‎batch.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,11 +257,13 @@ func (b *PreparedBatch) Add(args ...any) error {
257257
}
258258

259259
if err := b.eqb.Build(context.Background(), b.conn, b.tx, b.conn.typeMap, sd, args); err != nil {
260+
b.eqb = ExtendedQueryBuilder{}
260261
return err
261262
}
262263

263264
row, err := sd.EncodeBatchRow(b.eqb.ParamValues)
264265
if err != nil {
266+
b.eqb = ExtendedQueryBuilder{}
265267
return err
266268
}
267269

‎batch_internal_test.go‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package fbx
22

33
import (
4+
"bytes"
45
"context"
56
"errors"
67
"math"
@@ -804,6 +805,52 @@ func TestTxCommitCanceledPreservesPreparedBatch(t *testing.T) {
804805
require.Equal(t, 1, count)
805806
}
806807

808+
func TestPreparedBatchAddEncodingErrorReleasesParameters(t *testing.T) {
809+
ctx := context.Background()
810+
conn := mustConnect(t, mustParseConfig(t, os.Getenv("FBX_TEST_DATABASE")))
811+
defer func() { require.NoError(t, conn.Close(ctx)) }()
812+
skipIfBatchUnsupported(ctx, t, conn)
813+
814+
_, err := conn.Exec(ctx, "recreate table batch_char_encode_error (v char(5) character set octets, id integer)")
815+
require.NoError(t, err)
816+
defer func() {
817+
require.NoError(t, conn.DeallocateAll(ctx))
818+
_, err := conn.Exec(ctx, "drop table batch_char_encode_error")
819+
require.NoError(t, err)
820+
}()
821+
b, err := conn.PrepareBatch(ctx, "insert into batch_char_encode_error values (?, ?)")
822+
require.NoError(t, err)
823+
defer func() { require.NoError(t, b.Close(ctx)) }()
824+
825+
require.NoError(t, b.Add([]byte{1, 0, 2}, 1))
826+
queuedRow := bytes.Clone(b.encodedRows[0])
827+
pending := b.PendingBytes()
828+
829+
large := make([]byte, 16<<20)
830+
for _, tc := range []struct {
831+
name string
832+
id any
833+
wantErr string
834+
}{
835+
{"row encoding", 2, "exceeds declared length"},
836+
{"parameter encoding", struct{}{}, "failed to encode args[1]"},
837+
} {
838+
t.Run(tc.name, func(t *testing.T) {
839+
err := b.Add(large, tc.id)
840+
require.ErrorContains(t, err, tc.wantErr)
841+
require.Nil(t, b.eqb.ParamValues)
842+
require.Nil(t, b.eqb.paramValueBytes)
843+
require.Equal(t, [][]byte{queuedRow}, b.encodedRows)
844+
require.Equal(t, pending, b.PendingBytes())
845+
})
846+
}
847+
848+
require.NoError(t, b.Add([]byte{3, 0, 4}, 2))
849+
result, err := b.Exec(ctx)
850+
require.NoError(t, err)
851+
require.EqualValues(t, 2, result.Affected)
852+
}
853+
807854
func TestPreparedBatchClearPendingClearsBufferedRows(t *testing.T) {
808855
row1 := []byte("row-one")
809856
row2 := []byte("row-two")

‎batch_test.go‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,77 @@ import (
1212
"github.com/stretchr/testify/require"
1313
)
1414

15+
func TestPreparedBatchFixedChar(t *testing.T) {
16+
for _, tc := range []struct {
17+
charset string
18+
length string
19+
full string
20+
}{
21+
{"UTF8", "3", "😀😁😂"},
22+
{"ASCII", "5", "abcde"},
23+
} {
24+
t.Run(tc.charset, func(t *testing.T) {
25+
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
26+
defer cancel()
27+
config := defaultConnTestRunner.CreateConfig(ctx, t)
28+
config.Encoding = tc.charset
29+
conn := mustConnect(t, config)
30+
defer closeConn(t, conn)
31+
skipIfBatchUnsupported(ctx, t, conn)
32+
table := "batch_fixed_char_" + strings.ToLower(tc.charset)
33+
_, 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)")
34+
require.NoError(t, err)
35+
defer func() {
36+
require.NoError(t, conn.DeallocateAll(context.Background()))
37+
_, err := conn.Exec(context.Background(), "drop table "+table)
38+
require.NoError(t, err)
39+
}()
40+
query := "insert into " + table + " (v, b, id) values (?, ?, ?)"
41+
batch, err := conn.PrepareBatch(ctx, query)
42+
require.NoError(t, err)
43+
defer func() { require.NoError(t, batch.Close(context.Background())) }()
44+
45+
require.ErrorContains(t, batch.Add("abc", []byte{1, 2, 3, 4, 5, 6}, 0), "exceeds declared length")
46+
require.Zero(t, batch.PendingBytes())
47+
values := [][]any{
48+
{"abc", []byte{1, 0, 2}, 1},
49+
{"", []byte{}, 2},
50+
{nil, nil, 3},
51+
{tc.full, []byte{1, 2, 3, 4, 5}, 4},
52+
}
53+
for _, row := range values {
54+
require.NoError(t, batch.Add(row...))
55+
}
56+
require.NoError(t, batch.Flush(ctx))
57+
result, err := batch.Exec(ctx)
58+
require.NoError(t, err)
59+
require.EqualValues(t, len(values), result.Affected)
60+
61+
ordinary := []any{"xy", []byte{0xff}, 5}
62+
_, err = conn.Exec(ctx, query, ordinary...)
63+
require.NoError(t, err)
64+
for _, row := range append(values, ordinary) {
65+
var text *string
66+
var binary []byte
67+
var id int
68+
err := conn.QueryRow(ctx, "select trim(v), b, id from "+table+" where id = ?", row[2]).Scan(&text, &binary, &id)
69+
require.NoError(t, err)
70+
require.Equal(t, row[2], id)
71+
if row[0] == nil {
72+
require.Nil(t, text)
73+
require.Nil(t, binary)
74+
} else {
75+
require.NotNil(t, text)
76+
require.Equal(t, row[0], *text)
77+
wantBinary := make([]byte, 5)
78+
copy(wantBinary, row[1].([]byte))
79+
require.Equal(t, wantBinary, binary)
80+
}
81+
}
82+
})
83+
}
84+
}
85+
1586
func TestExecBatchRows(t *testing.T) {
1687
ctx := context.Background()
1788
fbxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *fbx.Conn) {

‎fbconn/statement.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (sd *StatementDescription) EncodeBatchRow(values [][]byte) ([]byte, error)
8989
var buf bytes.Buffer
9090
x := fbproto.NewXDRWriter(&buf)
9191

92-
if err := fbproto.WriteRowData(x, sd.StatementInfo.ParametersDescriptors, values); err != nil {
92+
if err := fbproto.WriteBatchRowData(x, sd.StatementInfo.ParametersDescriptors, values); err != nil {
9393
return nil, err
9494
}
9595

‎fbconn/statement_internal_test.go‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,94 @@ import (
1010
"github.com/stretchr/testify/require"
1111
)
1212

13+
func TestEncodeBatchRowFixedChar(t *testing.T) {
14+
for _, tc := range []struct {
15+
name string
16+
charset int
17+
length int
18+
value []byte
19+
want []byte
20+
wantErr bool
21+
}{
22+
{"utf8", 4, 12, []byte("abc"), []byte("abc "), false},
23+
{"ascii with padding", 2, 5, []byte("abc"), []byte("abc "), false},
24+
{"full text with padding", 2, 5, []byte("abcde"), []byte("abcde "), false},
25+
{"full aligned text", 2, 4, []byte("abcd"), []byte("abcd"), false},
26+
{"text across padding blocks", 2, 2049, []byte("abc"), append([]byte("abc"), bytes.Repeat([]byte{' '}, 2049)...), false},
27+
{"empty text", 2, 5, []byte{}, []byte(" "), false},
28+
{"null", 4, 12, nil, nil, false},
29+
{"octets", fbproto.CS_BINARY, 5, []byte{1, 0, 2}, []byte{1, 0, 2, 0, 0, 0, 0, 0}, false},
30+
{"empty octets", fbproto.CS_BINARY, 5, []byte{}, make([]byte, 8), false},
31+
{"text too long", 4, 2, []byte("abc"), nil, true},
32+
{"octets too long", fbproto.CS_BINARY, 2, []byte{1, 2, 3}, nil, true},
33+
} {
34+
t.Run(tc.name, func(t *testing.T) {
35+
sd := &StatementDescription{StatementInfo: &StatementInfo{
36+
ParametersDescriptors: []fbproto.FieldDescriptor{
37+
{Type: fbproto.SQL_TYPE_TEXT, Subtype: tc.charset, Length: tc.length},
38+
{Type: fbproto.SQL_TYPE_LONG, Length: 4},
39+
},
40+
}}
41+
row, err := sd.EncodeBatchRow([][]byte{tc.value, {0, 0, 0, 42}})
42+
if tc.wantErr {
43+
require.ErrorContains(t, err, "exceeds declared length")
44+
require.Nil(t, row)
45+
return
46+
}
47+
require.NoError(t, err)
48+
want := []byte{0, 0, 0, 0}
49+
if tc.value == nil {
50+
want[0] = 1
51+
}
52+
want = append(want, tc.want...)
53+
want = append(want, 0, 0, 0, 42)
54+
require.Equal(t, want, row, "CHAR padding must preserve the following parameter")
55+
})
56+
}
57+
}
58+
59+
func BenchmarkEncodeBatchRowPadding(b *testing.B) {
60+
for _, tc := range []struct {
61+
name string
62+
fields []fbproto.FieldDescriptor
63+
values [][]byte
64+
}{
65+
{"ascii_country_char2", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 2}}, [][]byte{[]byte("DE")}},
66+
{"ascii_code_char8", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 8}}, [][]byte{[]byte("AB-1042")}},
67+
{"ascii_uuid_char36", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 36}}, [][]byte{[]byte("550e8400-e29b-41d4-a716-446655440000")}},
68+
{"ascii_label_char32", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 32}}, [][]byte{[]byte("North warehouse")}},
69+
{"utf8_name_char32", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 4, Length: 32 * 4}}, [][]byte{[]byte("Иван Петров")}},
70+
{"utf8_label_char64", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: 4, Length: 64 * 4}}, [][]byte{[]byte("Основной склад в Москве")}},
71+
{"octets_id_char16", []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_TEXT, Subtype: fbproto.CS_BINARY, Length: 16}}, [][]byte{{0x55, 0x0e, 0x84, 0, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44, 0, 0}}},
72+
{
73+
"mixed_row",
74+
[]fbproto.FieldDescriptor{
75+
{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 2},
76+
{Type: fbproto.SQL_TYPE_TEXT, Subtype: 2, Length: 8},
77+
{Type: fbproto.SQL_TYPE_TEXT, Subtype: 4, Length: 32 * 4},
78+
{Type: fbproto.SQL_TYPE_TEXT, Subtype: fbproto.CS_BINARY, Length: 16},
79+
},
80+
[][]byte{[]byte("DE"), []byte("AB-1042"), []byte("Иван Петров"), {0x55, 0x0e, 0x84, 0, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44, 0, 0}},
81+
},
82+
} {
83+
b.Run(tc.name, func(b *testing.B) {
84+
fields := []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_LONG, Length: 4}}
85+
fields = append(fields, tc.fields...)
86+
fields = append(fields, fbproto.FieldDescriptor{Type: fbproto.SQL_TYPE_LONG, Length: 4})
87+
values := [][]byte{{0, 0, 0, 42}}
88+
values = append(values, tc.values...)
89+
values = append(values, []byte{0, 0, 0, 7})
90+
sd := &StatementDescription{StatementInfo: &StatementInfo{ParametersDescriptors: fields}}
91+
b.ReportAllocs()
92+
for b.Loop() {
93+
if _, err := sd.EncodeBatchRow(values); err != nil {
94+
b.Fatal(err)
95+
}
96+
}
97+
})
98+
}
99+
}
100+
13101
type prepareCleanupTestConn struct {
14102
noopConn
15103
written bytes.Buffer

‎fbproto/client_test.go‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package fbproto
22

33
import (
44
"bytes"
5+
"fmt"
56
"io"
67
"math"
78
"testing"
@@ -92,6 +93,81 @@ func TestXDRReaderBufferLengths(t *testing.T) {
9293
}
9394
}
9495

96+
func TestWriteCustomPadding(t *testing.T) {
97+
for _, tc := range []struct {
98+
length int
99+
value byte
100+
}{
101+
{0, ' '},
102+
{17, ' '},
103+
{17, 0},
104+
{17, 'x'},
105+
{paddingBlockSize, ' '},
106+
{2*paddingBlockSize + 3, 0},
107+
} {
108+
t.Run(fmt.Sprintf("length=%d/byte=%d", tc.length, tc.value), func(t *testing.T) {
109+
t.Parallel()
110+
var buf bytes.Buffer
111+
err := NewXDRWriter(&buf).WriteCustomPadding(tc.length, tc.value)
112+
require.NoError(t, err)
113+
require.True(t, bytes.Equal(bytes.Repeat([]byte{tc.value}, tc.length), buf.Bytes()), "unexpected padding bytes")
114+
})
115+
}
116+
}
117+
118+
type paddingErrorWriter struct {
119+
calls int
120+
}
121+
122+
func (w *paddingErrorWriter) Write(p []byte) (int, error) {
123+
w.calls++
124+
if w.calls == 2 {
125+
return 0, io.ErrClosedPipe
126+
}
127+
return len(p), nil
128+
}
129+
130+
func TestWriteCustomPaddingStopsOnWriteError(t *testing.T) {
131+
w := &paddingErrorWriter{}
132+
err := NewXDRWriter(w).WriteCustomPadding(3*paddingBlockSize, ' ')
133+
require.ErrorIs(t, err, io.ErrClosedPipe)
134+
require.Equal(t, 2, w.calls)
135+
}
136+
137+
func TestWriteRowDataUsesActualCharLength(t *testing.T) {
138+
fields := []FieldDescriptor{
139+
{Type: SQL_TYPE_TEXT, Subtype: 4, Length: 12},
140+
{Type: SQL_TYPE_LONG, Length: 4},
141+
}
142+
var buf bytes.Buffer
143+
require.NoError(t, WriteRowData(NewXDRWriter(&buf), fields, [][]byte{[]byte("abc"), {0, 0, 0, 42}}))
144+
require.Equal(t, []byte{
145+
0, 0, 0, 0,
146+
'a', 'b', 'c', ' ',
147+
0, 0, 0, 42,
148+
}, buf.Bytes())
149+
}
150+
151+
func TestWriteBatchRowDataValueCount(t *testing.T) {
152+
fields := []FieldDescriptor{{Type: SQL_TYPE_TEXT, Subtype: CS_BINARY, Length: 5}}
153+
for _, tc := range []struct {
154+
name string
155+
values [][]byte
156+
}{
157+
{"missing", nil},
158+
{"empty", [][]byte{}},
159+
{"extra", [][]byte{[]byte("abc"), []byte("extra")}},
160+
{"extra null", [][]byte{[]byte("abc"), nil}},
161+
} {
162+
t.Run(tc.name, func(t *testing.T) {
163+
buf := bytes.NewBufferString("prefix")
164+
err := WriteBatchRowData(NewXDRWriter(buf), fields, tc.values)
165+
require.ErrorContains(t, err, "batch values count mismatch")
166+
require.Equal(t, "prefix", buf.String(), "invalid value count must not write row data")
167+
})
168+
}
169+
}
170+
95171
func TestReadRowDataVaryingLength(t *testing.T) {
96172
fields := []FieldDescriptor{{Type: SQL_TYPE_VARYING, Length: 8}, {Type: SQL_TYPE_LONG}}
97173
var scratch rowScratch

0 commit comments

Comments
 (0)