diff --git a/fbconn/array.go b/fbconn/array.go index 435c95b..aea97ef 100644 --- a/fbconn/array.go +++ b/fbconn/array.go @@ -218,25 +218,14 @@ func putArray(fbConn *FbConn, ctx context.Context, tx *FBTransaction, arrayData return id, nil } -func getArray(fbConn *FbConn, ctx context.Context, tx *FBTransaction, arrayData *Array, arrId []byte) ([]byte, error) { - if len(arrId) == 0 { - return nil, nil - } - - arrayId := int64(binary.BigEndian.Uint64(arrId)) - +func getArray(fbConn *FbConn, ctx context.Context, tx *FBTransaction, arrayData *Array, arrayID int64) ([]byte, error) { length, err := arrayData.getSliceLength(arrayData.Dimensions) if err != nil { return nil, err } sdl := arrayData.generateSDL(arrayData.Dimensions) - array, err := fbConn.getArray(ctx, tx, arrayId, arrayData.BlrTypeId, length, int(arrayData.Length), sdl) - if err != nil { - return nil, err - } - - return array, err + return fbConn.getArray(ctx, tx, arrayID, arrayData.BlrTypeId, length, int(arrayData.Length), sdl) } func getSqlTypeFromBlr(datatype uint32) (uint32, error) { diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index e55a22e..92266e6 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -2462,6 +2462,15 @@ type bufferedCol struct { length int } +func (rr *ResultReader) storeValue(value []byte) bufferedCol { + if value == nil { + return bufferedCol{length: bufferedColNullLength} + } + col := bufferedCol{start: len(rr.bufferedArena), length: len(value)} + rr.bufferedArena = append(rr.bufferedArena, value...) + return col +} + // Result is the saved query response that is returned by calling Read on a ResultReader. type Result struct { FieldDescriptions []FieldDescription @@ -2745,12 +2754,15 @@ func (rr *ResultReader) popBufferedRow() bool { func (rr *ResultReader) bufferCurrentFetchRows() bool { rr.clearBufferedFetch() - colCount := len(rr.fieldDescriptions) - - var rowsBuf [][][]byte + // ARRAY reads use the same connection and must wait for the full Fetch response. + type pendingArray struct { + col int + metadata *Array + id int64 + } + var arrays []pendingArray for rr.fetchResp.MoreRows() { - rowBuf := [][]byte{} row, msg, err := rr.fbConn.receiveSQLData(rr.statementDescription.StatementInfo.FieldDescriptors) if err != nil { rr.fbConn.asyncCloseAfterRead(err) @@ -2768,44 +2780,29 @@ func (rr *ResultReader) bufferCurrentFetchRows() bool { } rr.rowsFetched++ - for i := 0; i < colCount; i++ { - col := make([]byte, 0) - if row.RowData[i] == nil { - rowBuf = append(rowBuf, nil) - continue + rr.bufferedRows = append(rr.bufferedRows, bufferedRow{colStart: len(rr.bufferedCols)}) + for i := range rr.fieldDescriptions { + value := row.RowData[i] + field := &rr.fieldDescriptions[i] + if IsArrayType(field.Type) { + if len(value) > 0 { + id := int64(binary.BigEndian.Uint64(value)) + arrays = append(arrays, pendingArray{len(rr.bufferedCols), field.ArrayData, id}) + } + value = nil } - col = append(col, row.RowData[i]...) - rowBuf = append(rowBuf, col) - } - rowsBuf = append(rowsBuf, rowBuf) - - if rr.fetchResp.EndOfCursor() { - rr.eoc = true + rr.bufferedCols = append(rr.bufferedCols, rr.storeValue(value)) } } - if rr.fetchResp.EndOfCursor() { - rr.eoc = true - } - for _, row := range rowsBuf { - rowStart := len(rr.bufferedCols) - for j, elem := range row { - if IsArrayType(uint32(rr.fieldDescriptions[j].Type)) { - array, err := getArray(rr.fbConn, rr.ctx, rr.boundTransaction, rr.fieldDescriptions[j].ArrayData, elem) - if err != nil { - rr.concludeCommand(QueryStatus{}, err) - return false - } - elem = array - } - if elem == nil { - rr.bufferedCols = append(rr.bufferedCols, bufferedCol{length: bufferedColNullLength}) - continue - } - start := len(rr.bufferedArena) - rr.bufferedArena = append(rr.bufferedArena, elem...) - rr.bufferedCols = append(rr.bufferedCols, bufferedCol{start: start, length: len(elem)}) + rr.eoc = rr.fetchResp.EndOfCursor() + + for _, pending := range arrays { + value, err := getArray(rr.fbConn, rr.ctx, rr.boundTransaction, pending.metadata, pending.id) + if err != nil { + rr.concludeCommand(QueryStatus{}, err) + return false } - rr.bufferedRows = append(rr.bufferedRows, bufferedRow{colStart: rowStart}) + rr.bufferedCols[pending.col] = rr.storeValue(value) } return true } @@ -3028,6 +3025,9 @@ func (rr *ResultReader) concludeCommand(queryStatus QueryStatus, err error) { rr.queryStatus = queryStatus rr.rowValues = nil + rr.bufferedRows = nil + rr.bufferedCols = nil + rr.bufferedArena = nil rr.commandConcluded = true } diff --git a/fbconn/fetch_arena_test.go b/fbconn/fetch_arena_test.go new file mode 100644 index 0000000..11c27e7 --- /dev/null +++ b/fbconn/fetch_arena_test.go @@ -0,0 +1,102 @@ +package fbconn + +import ( + "bytes" + "encoding/binary" + "io" + "testing" + + "github.com/firebirdsql/fbx/fbproto" + "github.com/stretchr/testify/require" +) + +func newFetchTestReader(t *testing.T, fields []fbproto.FieldDescriptor, responses io.Reader, requests io.Writer) *ResultReader { + conn := newDetachTestConn(&noopConn{}) + conn.client.Rebind(responses, requests) + return &ResultReader{ + fbConn: conn, ctx: t.Context(), cursorOpened: true, + boundTransaction: &FBTransaction{Handle: 1}, + fieldDescriptions: conn.convertRowDescription(fields), + statementDescription: &StatementDescription{StatementInfo: &StatementInfo{FieldDescriptors: fields}}, + } +} + +func TestFetchBuffersRowsBeforeReadingArrays(t *testing.T) { + fields := []fbproto.FieldDescriptor{ + {Type: fbproto.SQL_TYPE_VARYING}, {Type: fbproto.SQL_TYPE_ARRAY}, + {Type: fbproto.SQL_TYPE_VARYING}, {Type: fbproto.SQL_TYPE_ARRAY}, + } + var wire bytes.Buffer + w := fbproto.NewXDRWriter(&wire) + writeInts := func(values ...int) { + for _, v := range values { + require.NoError(t, w.WriteInt32(v)) + } + } + writeRow := func(values ...[]byte) { require.NoError(t, fbproto.WriteRowData(w, fields, values)) } + id := func(n uint64) []byte { return binary.BigEndian.AppendUint64(nil, n) } + long := bytes.Repeat([]byte("x"), 1024) + + writeInts(fbproto.Op_fetch_response, 0, 1) + writeRow([]byte("first"), id(1), []byte{}, id(2)) + writeInts(fbproto.Op_fetch_response, 0, 1) + writeRow(long, id(3), []byte("second"), nil) + writeInts(fbproto.Op_fetch_response, 0, 0) + for _, v := range []int{11, 22, 33} { + writeInts(fbproto.Op_slice_response, 8, 8, v, v+1) + } + writeInts(fbproto.Op_fetch_response, 0, 1) + writeRow(nil, nil, []byte("third"), id(4)) + writeInts(fbproto.Op_fetch_response, 100, 0) + writeInts(fbproto.Op_slice_response, 8, 8, 44, 45) + + var requests bytes.Buffer + rr := newFetchTestReader(t, fields, &wire, &requests) + array := &Array{TypeId: fbproto.SQL_TYPE_LONG, BlrTypeId: fbproto.Isc_blr_long, Length: 4, Dimensions: []map[string]int{{"Lower": 1, "Upper": 2}}} + rr.fieldDescriptions[1].ArrayData, rr.fieldDescriptions[3].ArrayData = array, array + + for _, want := range [][][]byte{ + {[]byte("first"), {0, 0, 0, 11, 0, 0, 0, 12}, {}, {0, 0, 0, 22, 0, 0, 0, 23}}, + {long, {0, 0, 0, 33, 0, 0, 0, 34}, []byte("second"), nil}, + {nil, nil, []byte("third"), {0, 0, 0, 44, 0, 0, 0, 45}}, + } { + require.True(t, rr.NextRow(), "fetch error: %v", rr.err) + require.Equal(t, want, rr.Values()) + } + require.False(t, rr.NextRow()) + require.NoError(t, rr.err) + require.EqualValues(t, 3, rr.rowsFetched) + + slice := fbproto.OpGetSlice{TransactionHandle: 1, SliceLength: 8, SliceDescriptor: array.generateSDL(array.Dimensions)} + remaining := requests.Bytes() + for handle := int64(1); handle <= 4; handle++ { + var expected bytes.Buffer + slice.ArrayHandle = handle + require.NoError(t, slice.Write(fbproto.NewXDRWriter(&expected))) + _, tail, found := bytes.Cut(remaining, expected.Bytes()) + require.True(t, found, "missing or out-of-order GetSlice for ARRAY %d", handle) + remaining = tail + } +} + +func TestFetchDiscardsPartialBatchOnError(t *testing.T) { + fields := []fbproto.FieldDescriptor{{Type: fbproto.SQL_TYPE_VARYING}} + var wire bytes.Buffer + w := fbproto.NewXDRWriter(&wire) + for range 2 { + for _, v := range []int{fbproto.Op_fetch_response, 0, 1} { + require.NoError(t, w.WriteInt32(v)) + } + require.NoError(t, fbproto.WriteRowData(w, fields, [][]byte{[]byte("partial")})) + } + require.NoError(t, retryTestResponse(w, fbproto.Isc_dsql_error)) + + rr := newFetchTestReader(t, fields, &wire, io.Discard) + require.False(t, rr.NextRow()) + var fbErr *FbError + require.ErrorAs(t, rr.err, &fbErr) + require.Nil(t, rr.Values()) + require.Nil(t, rr.bufferedRows) + require.Nil(t, rr.bufferedCols) + require.Nil(t, rr.bufferedArena) +}