You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SqlDataRecord.SetBytes fails to set length, incorrectly preserving data from a previous call #3957
Suppose you are using IEnumerable<SqlDataRecord> as the value of a table-valued SqlParameter and re-using the same SqlDataRecord instance for each item. One of the fields is type VARBINARY(MAX), and you use the SetBytes method to copy data into the field. After the first call to SetBytes, a subsequent call that copies fewer bytes will write to the existing buffer without setting the field's length, causing the remaining stale buffered bytes from the first call to get copied to the server, too.
To reproduce
#!/usr/bin/env dotnet run
#:package Microsoft.Data.SqlClient@6.*usingMicrosoft.Data.SqlClient.Server;usingSystem.Data;usingSystem.Data.SqlTypes;usingSystem.Text;varcolumns=newSqlMetaData[]{new("Data",SqlDbType.VarBinary,SqlMetaData.Max),};varrec=newSqlDataRecord(columns);varbuffer=newbyte[4096];// write first record valueSetBytes(rec,0,buffer,"Two Words");ReadBytesToConsole(rec,0,buffer);// writes "Two Words"// write second record valueSetBytes(rec,0,buffer,"One");ReadBytesToConsole(rec,0,buffer);// writes "One Words"// write third record value using SqlBytes, which avoids the bugvarsqlBytes=newSqlBytes(Encoding.UTF8.GetBytes("Three"));rec.SetSqlBytes(0,sqlBytes);ReadBytesToConsole(rec,0,buffer);// writes "Three"staticvoidSetBytes(SqlDataRecordrec,intordinal,byte[]buffer,stringvalue){intlength=Encoding.UTF8.GetBytes(value,buffer);rec.SetBytes(ordinal,0,buffer,0,length);}staticvoidReadBytesToConsole(SqlDataRecordrec,intordinal,byte[]buffer){varlength=rec.GetBytes(ordinal,0,buffer,0,buffer.Length);vars=Encoding.UTF8.GetString(buffer,0,int.CreateChecked(length));Console.WriteLine(s);}
Expected behavior
The program should output:
Two Words
One
Three
Further technical details
Microsoft.Data.SqlClient version: 6.1.4
.NET target: .NET 10.0
SQL Server version: N/A
Operating system: Windows 11 Pro 26200.7840
The internal byte array is only allocated on the first SetBytes call. Subsequent calls copy into that existing internal array. The internal array is only modified if it needs to be expanded to fit the new data.
Can you tell me more about the type of API you're looking for? It would be pretty expensive for us to implicitly allocate a new byte array on each SetBytes call and I wouldn't want to force that on others who rely on the existing behavior. What about something like a Clear() method?
(I also reopened #1805 as we need improved guidelines around SqlDataRecord reuse)
It's worth noting that the same problem likely occurs in SetChars.
One option which would have some symmetry with SqlDataReader.GetBytes might be to allow SqlDataRecord.SetBytes(ordinal, fieldOffset, buffer: null, bufferOffset: offset, length: length) to reallocate the underlying buffer.
Can you tell me more about the type of API you're looking for?
I don't want it to allocate a new byte array on every call; that would defeat the benefit of re-using the same instance. I think it should set length when you call SetBytes, the same as SetSqlBytes does here:
The current behavior produces corrupted data. It copies extra, stale bytes to the server because it doesn't remember the length of the buffered data unless it resizes its buffer.
The trouble with that approach is that there's a legitimate use case for calling SetBytes() multiple times. Because the existing API allows you to specify an offset within the destination buffer, others may be using that to iteratively populate the field. For backwards compatibility reasons, we won't be able to assume that the length should be reset.
The trouble with that approach is that there's a legitimate use case for calling SetBytes() multiple times
I don't think that's a problem. You can set BytesLength to fieldOffset + length. That's already how SqlRecordBuffer.SetBytes calculates the new length. It handles the non-zero fieldOffset case by checking the offset is not greater than BytesLength (no gap in copied data), then ensuring the buffer is big enough to fit the additional data.
I'd argue that this is where the bug is: it only sets BytesLength in the buffer-resize case. Either that last line should be moved down, outside the if statement, so it always sets BytesLength, or SqlRecordBuffer should never set BytesLength (deferring to ValueUtilsSmi, which calls SetBytesLength in many other cases).
I think your suggestion of always setting BytesLength makes sense, so let's call it the plan of record. Let me chat with my team and see if there are any other backwards compatibility concerns. This code is probably over a decade old, so we need to tread carefully with any changes that may impact the public surface.
For the record, using SqlBytes as a surrogate is an effective work-around! You can see the basic idea in my repro code, but it's worth mentioning you can re-use one SqlBytes instance, too, with e.g. a MemoryStream as the backing store.
Activity
mdaigle commentedon Feb 17, 2026
The internal byte array is only allocated on the first SetBytes call. Subsequent calls copy into that existing internal array. The internal array is only modified if it needs to be expanded to fit the new data.
SqlClient/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs
Lines 527 to 528 in 5d2d5f4
Can you tell me more about the type of API you're looking for? It would be pretty expensive for us to implicitly allocate a new byte array on each SetBytes call and I wouldn't want to force that on others who rely on the existing behavior. What about something like a Clear() method?
(I also reopened #1805 as we need improved guidelines around SqlDataRecord reuse)
edwardneal commentedon Feb 17, 2026
It's worth noting that the same problem likely occurs in
SetChars.One option which would have some symmetry with
SqlDataReader.GetBytesmight be to allowSqlDataRecord.SetBytes(ordinal, fieldOffset, buffer: null, bufferOffset: offset, length: length)to reallocate the underlying buffer.wjrogers commentedon Feb 17, 2026
I don't want it to allocate a new byte array on every call; that would defeat the benefit of re-using the same instance. I think it should set length when you call
SetBytes, the same asSetSqlBytesdoes here:SqlClient/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.cs
Lines 3265 to 3266 in d96eb70
The current behavior produces corrupted data. It copies extra, stale bytes to the server because it doesn't remember the length of the buffered data unless it resizes its buffer.
mdaigle commentedon Feb 17, 2026
The trouble with that approach is that there's a legitimate use case for calling SetBytes() multiple times. Because the existing API allows you to specify an offset within the destination buffer, others may be using that to iteratively populate the field. For backwards compatibility reasons, we won't be able to assume that the length should be reset.
wjrogers commentedon Feb 17, 2026
I don't think that's a problem. You can set
BytesLengthtofieldOffset + length. That's already howSqlRecordBuffer.SetBytescalculates the new length. It handles the non-zerofieldOffsetcase by checking the offset is not greater thanBytesLength(no gap in copied data), then ensuring the buffer is big enough to fit the additional data.SqlClient/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs
Lines 534 to 549 in 5332da3
I'd argue that this is where the bug is: it only sets
BytesLengthin the buffer-resize case. Either that last line should be moved down, outside theifstatement, so it always setsBytesLength, orSqlRecordBuffershould never setBytesLength(deferring toValueUtilsSmi, which callsSetBytesLengthin many other cases).mdaigle commentedon Feb 17, 2026
I think your suggestion of always setting BytesLength makes sense, so let's call it the plan of record. Let me chat with my team and see if there are any other backwards compatibility concerns. This code is probably over a decade old, so we need to tread carefully with any changes that may impact the public surface.
wjrogers commentedon Feb 17, 2026
For the record, using
SqlBytesas a surrogate is an effective work-around! You can see the basic idea in my repro code, but it's worth mentioning you can re-use oneSqlBytesinstance, too, with e.g. aMemoryStreamas the backing store.priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
test simple body