Skip to content

Cannot populate TVP containing lob fields, from a streamed content #1143

Open

Description

@jimbobmcgee

There appears to be some...glue...missing to allow streaming content into a table valued parameter. Consider the following extremely contrived scenario:

CREATE TABLE dbo.test (clob VARCHAR(MAX), blob VARBINARY(MAX));
CREATE TYPE dbo.test_tt AS TABLE(clob VARCHAR(MAX), blob VARBINARY(MAX));
// works...
using (var stream1 = IO.File.OpenRead("x:\\foo.bin"))
using (var stream2 = IO.File.OpenRead("x:\\bar.bin"))
using (var reader1 = IO.File.OpenText("x:\\foo.txt"))
using (var reader2 = IO.File.OpenText("x:\\bar.txt"))
{
  var cmd1 = sqlconn.CreateCommand();
  cmd1.CommandType = CommandType.Text;
  cmd1.CommandText = "INSERT INTO dbo.test(clob, blob) VALUES (@pclob, @pblob);"
  cmd1.Parameters.Add("@pblob", SqlDbType.VarBinary, -1);
  cmd1.Parameters.Add("@pclob", SqlDbType.VarChar, -1);

  cmd1.Parameters["@pblob"].Value = stream1;
  cmd1.Parameters["@pclob"].Value = reader1;
  cmd1.ExecuteNonQuery();

  cmd1.Parameters["@pblob"].Value = stream2;
  cmd1.Parameters["@pclob"].Value = reader2;
  cmd1.ExecuteNonQuery();
}

// fails...
using (var stream1 = IO.File.OpenRead("x:\\foo.bin"))
using (var stream2 = IO.File.OpenRead("x:\\bar.bin"))
using (var reader1 = IO.File.OpenText("x:\\foo.txt"))
using (var reader2 = IO.File.OpenText("x:\\bar.txt"))
{
  var meta = new[] {
    new SqlMetaData("clob", SqlDbType.VarChar, -1),
    new SqlMetaData("blob", SqlDbType.VarBinary, -1)
  };
  var records = new List<SqlDataRecord>();
  records.Add(new SqlDataRecord(meta);
  records.Add(new SqlDataRecord(meta);
  records[0].SetValue(0, reader1);
  records[0].SetValue(1, stream1);
  records[1].SetValue(0, reader2);
  records[1].SetValue(1, stream2);

  var cmd2 = sqlconn.CreateCommand();
  cmd2.CommandType = CommandType.Text;
  cmd2.CommandText = "INSERT INTO dbo.test(clob, blob) SELECT clob, blob FROM @test_tt;"
  var par = cmd2.Parameters.Add("@test_tt", SqlDbType.Structured, -1)'
  par.TypeName = "dbo.test_tt";
  par.Value = records;  
  cmd2.ExecuteNonQuery();
}

(Assuming I've written the example code above correctly, or at least its intent can be reasonably inferred), cmd1 should execute successfully twice, loading each row one-by-one. cmd2 will never run, as the calls to SqlDataRecord.SetValue don't accept either the Stream or TextReader objects, and throw an Invalid cast exception.

To that end, it does not appear that I can support both streaming multiple rows via TVP and streaming lobs via Stream and/or TextReader. I either have to load row-by-row (foregoing any decent set-based logic I might have in the SQL); or I have to load the whole content into memory (e.g. as String and Byte[]), to pass them. Neither approach seems particularly suitable for lots of input rows.

It's possible that Stream support might already come via SqlTypes.SqlBytes, which has a constructor which takes a Stream (I haven't tried); but the equivalent SqlTypes.SqlChars does not offer a constructor which takes TextReader. I'm not entirely convinced the SqlTypes don't automatically load the streamed data into contiguous memory, beforehand, anyway.

Is there anything specific preventing either SqlDataRecord accepting Stream and TextReader, or for SqlChars to accept TextReader, so there is at least some combination that would accept populating a TVP via entirely streamed data?

I suppose IDisposable lifetime has to be considered. Even though the above is contrived, I would expect that you would have to Close/Dispose each lob source only after each row was streamed in. I imagine normally streaming each row via a yield-based IEnumerable<SqlDataRecord> method, e.g.

private IEnumerable<SqlDataRecord> GetFileLobRecords()
{
  var meta = new[] {
    new SqlMetaData("clob", SqlDbType.VarChar, -1),
    new SqlMetaData("blob", SqlDbType.VarBinary, -1)
  };
  var files = IO.Directory.EnumerateFiles("X:\\");
  foreach (var f in files)
  {
    using (var s1 = IO.File.Open(f, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
    using (var s2 = IO.File.Open(f, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
    using (var t = new IO.StreamReader(s2))
    {
       var record = new SqlDataRecord(meta);
       record.SetValue(0, t);
       record.SetValue(0, s1);
       yield return record;
    }
  }
}

...which, on the surface, at least looks like it would behave, with ExecuteNonQuery streaming each TVP row up to the server in turn, and then cleaning up the lob source after each row has been streamed.

(I note I haven't made any async considerations -- the old-style, non-async pattern is fine for my immediate needs, but others' expectations that it might also work in those situations as well may not be unreasonable).

Anyone with some deeper knowledge of the internals care to comment?

(Possibly related: #982)

Activity

  1. johnnypham commented on Jun 30, 2021

    @johnnypham
    Contributor

    From what I've seen, the value of a SqlDataRecord column must be a compatible SQL DB type. I couldn't find a reason as to why that's the case. Maybe someone else can elaborate.

  2. jimbobmcgee commented on Jul 4, 2021

    @jimbobmcgee
    Author

    From my recent experience, I believe you can call SqlDataRecord.SetValue() with SqlDbTypes and the reasonable native types (string for SqlDbString, etc). It also allows anything IConvertible, if it can be converted to the reasonable native type.

    For LOB types, SqlChars, SqlBytes, byte[], char[] and string seem to be the common types; and SqlParameter.Value can also take a Stream (where CanRead is true) and a TextReader, but SqlDataRecord.SetValue() cannot.

    The perceived "contract" of SqlDataRecord.SetValue() and SqlParameter.Value are so close to each other -- both appear to make use of the same internal classes (StreamDataField, TextDataField) to handle reading the data -- so it feels like an oversight not to include support for Stream and TextReader in SqlDataRecord.

  3. cheenamalhotra commented on Jul 7, 2021

    @cheenamalhotra
    Member

    @jimbobmcgee

    Could you provide me complete repro in zip please? I'd like to test with some recent changes we are making internally.

  4. jimbobmcgee commented on Jul 8, 2021

    @jimbobmcgee
    Author

    @cheenamalhotra - I think the attached is self-contained and repeatable enough. It's written for LINQPad which is an interactive scratchpad for C# code, which lets me download the MDS package via NuGet. The principle should be sound in a csproj, but I don't have a working VS with .NET Core support at the moment.

    It contains four tests, which are run against both System.Data.SqlClient and Microsoft.Data.SqlClient:

    1. Test1: Inserting row-by-row, setting scalar parameter values to in-memory types (byte[] or string)
    2. Test2: Inserting row-by-row, setting scalar parameter values to streamable types (Stream or TextReader)
    3. Test3: Inserting as a set, setting a TVP value to IEnumerable<SqlDataRecord>, where each SqlDataRecord is loaded from the in-memory types
    4. Test4: Inserting as a set, setting a TVP value to IEnumerable<SqlDataRecord>, where each SqlDataRecord is loaded from streamable types

    Consts at the top of the LobStreamTest.linq file specify DB connection string and a local path for files to read. There's also a random seed, but it only keeps the binary/text content consistent across runs.

    Interestingly, I notice that, when performing these tests against both System.Data.SqlClient and Microsoft.Data.SqlClient, MDS fails both my TVP tests (Test3 and Test4), while SDS only fails the streaming one (Test4). Is MDS using a different SqlDataRecord to SDS?

    If I have done something wrong here, please advise.

  5. cheenamalhotra commented on Jul 26, 2021

    @cheenamalhotra
    Member

    Is MDS using a different SqlDataRecord to SDS?

    Yes, MDS changed to Microsoft.Data.SqlClient.Server namespace from Microsoft.SqlServer.Server namespace for all applicable classes. Ref: Porting Cheat Sheet.

    After changing to the new namespace I get only 4th test failing with MDS.

  6. jimbobmcgee commented on Jul 27, 2021

    @jimbobmcgee
    Author

    Thanks @cheenamalhotra, for the clarification regarding SqlDataRecord. I actually still get a failure in Test 3, when using Microsoft.Data.SqlClient.Server.SqlDataRecord (i.e. find/replace s/Microsoft.SqlServer.Server/Microsoft.Data.SqlClient.Server/), but I haven't spent any real time diagnosing yet -- I'll check and come back.

    To be clear, though, some approach for making Test 4 work is the functionality I was looking for when I raised the issue. It should be possible to load a TVP containing varbinary(max), varchar(max) or nvarchar(max), using an IEnumerable<SqlDataRecord>, without having to load the binary/string data into memory first.

  7. JRahnama commented on Aug 5, 2021

    @JRahnama
    Contributor

    Hi @jimbobmcgee,

    Regarding Test3:
    It is working fine. No exception captured. I got 6 rows affected by that test.

    Test4:
    The exception happens at record.SetValue(0, bytes); Simply we cannot cast Stream/FileStream to VARBINARY as you have defined in MetaData for the SqlDataRecord. The approach should be the same as you have used for textData by using a StreamReader. BinaryReader could solve your issue.

    If I have managed to answer all your questions and there is nothing more to add to this thread please feel free to close the issue, otherwise if you are still getting failures with Test3 provide me the stack trace and exception message.

  8. cheenamalhotra commented on Jan 6, 2026

    @cheenamalhotra
    Member

    Closing as stale

  9. moved this from To triage to Done in SqlClient Boardon Jan 6, 2026
  10. jimbobmcgee commented on Jan 7, 2026

    @jimbobmcgee
    Author

    @cheenamalhotra :: apologies for letting this one go (very) stale.

    The exception happens at record.SetValue(0, bytes); Simply we cannot cast Stream/FileStream to VARBINARY as you have defined in MetaData for the SqlDataRecord. The approach should be the same as you have used for textData by using a StreamReader. BinaryReader could solve your issue.

    It still appears to be the case that it is not possible to populate a SqlDataRecord with either a TextReader or Stream and -- assuming I have not missed a method for doing so -- I perceive this to be an oversight in the overall API.

    i.e. it should be functionally possible to pass either TextReader or Stream to the second parameter of SqlDataRecord.SetValue(int, object), such that a table-type of VARBINARY(MAX) or VARCHAR(MAX) can be spooled, without requiring pre-loading into contiguous memory (via a string, char[] or byte[]).

    At first glance, the internals appear to be able to handle both types, either wrapped as a TextDataFeed, StreamDataFeed, but all the constructors/methods where one might create one of those wrappers are all marked internal.

    (Similarly, it does not appear to be possible to create SqlBytes or SqlChars from either type -- constructors for these are also internal.)

    The similar (in principle) object SqlParameter.Value setter does not exhibit this restriction -- it accepts both TextReader and Stream and creates the relevant TextDataFeed or StreamDataFeed wrapper behind the scenes, using the internal methods.

    My suggestion (i.e. the reason for the issue) is that an equivalent behind-the-scenes conversion should also be possible when using SqlDataRecord.SetValue(...).

  11. cheenamalhotra commented on Jan 7, 2026

    @cheenamalhotra
    Member

    @jimbobmcgee I'm going to re-open to re-assess the scenario closely, as I believe streaming is supported for TVPs as per documentation: https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/table-valued-parameters?view=sql-server-ver17#streaming-rows-with-a-datareader

    However, I need to understand your case closely to respond better regarding SqlDataRecord API streaming support.

  12. moved this from Backlog to Investigating in SqlClient Boardon Jan 7, 2026
  13. jimbobmcgee commented on Jan 7, 2026

    @jimbobmcgee
    Author

    Thanks @cheenamalhotra.

    I'll admit, I get a little lost when trying to follow the logic in Github/code-review alone, but I think the exception is thrown by SqlDataRecord.SetValue() because MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType() has no branch which explicitly matches types Stream or TextReader. By default, without a matching branch, this method returns the Invalid enum value, which results in the exception.

    That method would match on the internal StreamDataFeed or TextDataFeed wrapper types and return Stream or TextReader enum values as appropriate.

    For SqlParameter, it appears objects passed to Value are first wrapped to the internal types using the static SqlParameter.CoerceValue() function. For SqlDataRecord, this coercion is not done ahead of time, so the default Invalid result remains.

    If SqlDataRecord.SetValue() did not throw at this point, it's next operation would be to call into a decorated chain of ValueUtilsSmi.SetCompatibleValue(...) which does have branches that deliberately handle DataFeed-derived types and does have setters to explicitly deal with Stream and TextReader.

    I lose track after reviewing after that, so I can't tell if there is a legitimate reason why the same branches cannot reasonably be followed in both SqlParameter and SqlDataRecord cases.

    (That said, I also can't work out whether the existing API actually streams in the first place, or whether it later turns everything into a contiguous array or string anyway. If it does materialise the stream before sending it onto the server, then the whole purpose of streaming LOBs is somewhat lost, and this issue becomes moot.)

  14. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  15. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug (API design gap)
    Environment ⚠️ Missing: SqlClient version, .NET target framework, SQL Server version, OS (issue predates template; behavior described is version-independent internal API design, not environment-specific)
    Area Area\Sql Bulk Copy (closest match — TVP/SqlDataRecord streaming; no dedicated TVP label exists)
    Duplicates Potentially related: #982 (already linked by reporter), #732 ("Allow TVPs to be populated via asynchronous data sources & add a new field to SqlDbType")
    Regression Not indicated — this is a longstanding API limitation, not a regression

    Analysis

    The reporter demonstrates that SqlDataRecord.SetValue() cannot accept a Stream or TextReader for LOB columns (VARCHAR(MAX)/VARBINARY(MAX)) when populating a table-valued parameter (TVP) row-by-row, whereas SqlParameter.Value supports both via internal StreamDataFeed/TextDataFeed wrapping (through SqlParameter.CoerceValue()). This forces callers to fully materialize LOB content into string/byte[] before adding rows to a TVP IEnumerable<SqlDataRecord>, defeating the purpose of streaming for large object data. Root cause appears to be that MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType() has no branch recognizing Stream/TextReader types the way SqlParameter's coercion path does. This is a legitimate API/feature gap (not a crash or data-corruption bug), affecting the Microsoft.Data.SqlClient.Server.SqlDataRecord TVP streaming path. Severity: P3 (feature enhancement / API completeness — long-standing, no urgent regression, but has multi-year community interest).

    Next Steps

    • Since this is a well-understood, reproducible API gap (confirmed by a maintainer and root-caused by the reporter down to MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType and the missing CoerceValue-equivalent step for SqlDataRecord), recommend assigning to Copilot coding agent to investigate adding Stream/TextReader support to SqlDataRecord.SetValue()/SetBytes()/SetChars() (or equivalent), mirroring the coercion behavior in SqlParameter.CoerceValue(), and update MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType() to recognize these types.
    • Review linked issue Allow Stream and TextReader to be retrieved by GetFieldValue and GetFieldValueAsync #732 (async TVP population) and Allow TVPs to be populated via asynchronous data sources & add a new field to SqlDbType #982 for overlapping design considerations before implementation, to ensure a consistent approach across sync/async TVP streaming.
    • If implemented, ensure both Microsoft.Data.SqlClient.Server.SqlDataRecord (MDS) and any shared TDS streaming (StreamDataFeed/TextDataFeed) code paths are covered by new unit/manual tests validating true streaming (not full in-memory materialization) for both sync and async TVP execution.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #1143 · copilot · auto · 57.3 AIC · ⌖ 13.2 AIC · ⊞ 11.9K · ◷

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions