Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion fbconn/statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
43 changes: 43 additions & 0 deletions fbconn/statement_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions fbproto/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 18 additions & 2 deletions fbproto/sqldata.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could WriteBatchRowData check that len(values) == len(rowDescriptor) before writing the NULL bitmap? With one CHAR descriptor and no values, it writes four bytes and then panics at values[0]. An extra non-nil value is silently dropped. Returning an error in both cases would match CalculateBLR and leave the writer untouched.

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 {
Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When this length check fails, PreparedBatch.Add returns before clearing b.eqb. Passing a 16 MiB byte slice to CHAR(5) CHARACTER SET OCTETS leaves the batch holding the entire copy even after Cancel and Close. Could we set b.eqb = ExtendedQueryBuilder{} on the EncodeBatchRow error path? Previously accepted rows are already in b.encodedRows, so they stay queued.

}
l = field.GetIOLength()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WriteCustomPadding allocates a temporary slice the size of the padding. For CHAR(32767) CHARACTER SET ASCII, both a one-byte value and a full-width value produce the same number of encoded bytes. In a WriteBatchRowData benchmark writing to io.Discard, "x" allocated 32,784 B/op and the full-width value allocated 16 B/op. Could we write the padding in chunks from reusable blocks of spaces and zero bytes? That would avoid the per-row padding allocation for wide columns.

}
if l == 0 {
if err = x.WriteInt32(valueBufLen); err != nil {
return err
Expand Down
Loading