Skip to content

API for retrieving Columns Schema from DbDataReader #15269

Closed

Description

@NickCraver

This is to unwrap the specific issue of resultset schemas from the many involved in #14302.
Back on May 5th @davkean noted:

We want GetSchemaTable in some form (we should get a separate bug filed on that, however, as you could imagine bringing that back with a different design that doesn't pull in DataSet/DataTable).

While it doesn't seem that anyone cares what method exists for of getting the schema of a resultset, we seem to agree on needing a method of doing it in .Net Core. For example, if a user runs a simple query such as:

SELECT 'bob' Name, 1 Id

Then there's no way to see what the types are. While getting the .Net type (via .GetFieldType(), e.g. DateTime) is possible and getting part the SQL type (via .GetDataTypeName(), e.g. NVARCHAR) is possible, other vital attributes of the schema shape currently aren't possible. For example there's no way to distinguish a varchar(20) from a varchar(max). There's also no way to tell if the column was nullable. Previously, this functionality was provided by .GetSchemaTable() which returned a DataTable class.

Currently I have a very simple use case: query data here, create a table with that data elsewhere. The query can be something like: SELECT * FROM sys.database_files. I point this out to illustrate that INFORMATION_SCHEMA (as proposed by some in #14302 as an alternative) is not a viable option. The same issue presents on any stored procedure which can also return any result set shape depending on the code paths. We need a way to see the scheme of a result set, these database-query alternatives are both expensive and non-covering.

This is a hard blocker for projects of myself and others. I have uses in both one-off projects as well as Opserver (which monitors SQL) and Dapper.Net. I know from #14302 that I'm not alone on this block. The portability of .Net core is extremely appealing for certain projects, especially those where we need to monitor the innards of SQL without depending on a .Net install (many if not most existing SQL servers only have .Net 3.5). Unfortunately though, this one missing piece of the puzzle may prevent using it altogether, forcing full CLR installs.

While SqlClient specifically serves my blocking use case, it's important to point out as @FransBouma notes in the other issue: this needs to be in the base API, not specifically up in SqlClient. For example, I also need this for Dapper features and it works across many providers - it is not at all SQL Server specific.

So how about it, can we please get an API for result set schemas added back? I'm happy to contribute to designing and provide feedback on a new API here if that's the best route. I know many others are as well.

Activity

  1. FransBouma commented on Sep 24, 2015

    @FransBouma
    Contributor

    Additionally: DbConnection.GetSchema(). This too relies currently on DataTable and should get a proper alternative in .NET core going forward. There are no alternatives for some schemas retrievable through this method, for some providers. If there's no alternative in .NET core, there's no way to write generic code to obtain metadata about a schema aspect. E.g. on Firebird, some metadata is very hard to retrieve from the schema (read: very complex metadata queries) and the schemas provided by this method are very helpful. I think the solution chosen for DbDataReader.GetSchemaTable should also be applied to DbConnection.GetSchema as it too simply has to return a datatype with tabular data which is only known at runtime.

  2. william-gross commented on Sep 24, 2015

    @william-gross

    This is a blocker for me as well, as I commented in #14302.

  3. NickCraver commented on Sep 25, 2015

    @NickCraver
    MemberAuthor

    Responding to @YoungGah's note above:

    Absolutely! We are tossing around ideas of the API returning schema in JSON format. Any opinions?

    Given that JSON serialization is not included in core, wouldn't it be a bit odd to have libraries implementing DataReader taking dependencies to support it? I wouldn't need JSON serialization in several apps aside from this. I'd love to hear what others hear, but from the SQL side, this option isn't very appealing. That being said, I certainly see why it's being discussed for other providers.

    With tabular data it can usually be expressed by positional or named arguments (e.g. a dictionary, list of an interface, etc.). I think that's a better approach for SQL, but I also recognize how that doesn't really work for a document type data store.

  4. roji commented on Sep 25, 2015

    @roji
    Member

    Am the maintainer of Npgsql, this is definitely a very important discussion, and it seems important to have this for .NET Core RTM.

    Here are some thoughts:

    • It definitely seems that dropping DataTable/View/Set is a good approach as long as an alternative schema-fetching mechanism is provided.
    • Re resultset metadata, as has been mentioned before a limited subset is available via GetFieldType, GetDataTypeName. Although this API approach could be extended (e.g. IsNullable), this doesn't seems like an optimal API for getting the results. It would also probably be different from whatever new API will replace DbConnection.GetSchema. If so, you may consider removing GetFieldType, GetDataTypeName from .NET Core as well as these will be a subset of whatever full new metadata API will be introduced.
    • Re JSON, I agree with @NickCraver that it seems a bit out place in the ADO.NET API:
      • It would force a particular JSON API (Newtonsoft?) on all ADO.NET consumers (and producers).
      • It would be a weakly-typed API
      • It is somewhat cumbersome for provider writers, since relational databases typically don't communicate schema information in JSON.
    • Why not introduce a simple .NET object-based model, e.g. DbColumn, DbTable? Providers could extend these as usual in ADO.NET for provider-specific metadata attributes (e.g. SqlDbColumn)...
  5. FransBouma commented on Sep 26, 2015

    @FransBouma
    Contributor

    JSON is a silly format in this context, it's an untyped text blob that needs deserializing using an external library. So -1 for JSON. The main issue is besides the external library needed that it's weakly typed: a piece of code calling GetDbSchema has to be sure the data it receives back is of the same type and the elements embedded inside it is stored in the same types. Always. With JSON that's up in the air, hence: bad choice.

  6. nvivo commented on Sep 26, 2015

    @nvivo

    @YoungGah

    We are tossing around ideas of the API returning schema in JSON format. Any opinions?

    I'm not sure about the idea of json for this. What would be the advantage over a simple object that can be easily serialized if needed? This is supposed to be used in the context of .NET calls, there is hardly a need for this information to be that interoperable to require a json blob.

    On https://github.com/dotnet/corefx/issues/1039#issuecomment-142271673 I proposed a very a simple interface that has the basic information that have been proven to be needed, and a dictionary for additional data.

    interface IColumnSchema {
        int ColumnOrder;
        string ColumnName;
        string ProviderDataType;
        Type ClrMappedType;
        int MaxLength;
        bool CanBeNull;
        IReadOnlyDictionary<string, object> CustomProviderData;
    }
    
    interface IReaderSchema()
    {
         IReadOnlyList<IColumnSchema> Columns { get; }
    }

    This is supposed to be used as:

    var command = CreateDbCommand("select 1 from bob");
    var reader = command.ExecuteReader();
    
    var schema = reader.GetResultSchema(); // returns IReaderSchema
    
    foreach (var c in schema.Columns) {
        ....
    }

    I'm not proposing this exact api, but something along the lines of this idea, with interfaces describing this data instead of the datatable.

    @YoungGah and others, what do you think?

  7. YoungGah commented on Oct 2, 2015

    @YoungGah

    Thanks for all your feedbacks and JSON is out, then. We will get back to you with another proposal.

  8. bricelam commented on Oct 2, 2015

    @bricelam
    Contributor

    In case it's useful, I did an EF feature spec on a new Schema Information API a few years ago. We never got around to implementing it, and it was definitely skewed toward EF6, but it may be interesting to look at in the context of this issue.

  9. YoungGah commented on Oct 2, 2015

    @YoungGah

    @bricelam Thanks for the spec! We will look into it.

  10. roji commented on Oct 3, 2015

    @roji
    Member

    @bricelam, @YoungGah, this Schema Information definitely seems like a step in the right direction! Some immediate points that come to mind:

    • The proposal handles schema table/view metadata, but not resultset metadata (i.e. from a DbDataReader). Of course it would be pretty trivial to extend the proposal for that.
    • It's worth thinking about allowing providers to extend these classes to provide provider-specific information
    • At least in PostgreSQL there are function features not covered (e.g. variadic)
    • Unique constraint is missing

    But I'm guessing this is just a starting point, I'll be glad to provide more feedback on an up-to-date proposal.

  11. roji commented on Oct 7, 2015

    @roji
    Member

    Note the current effort in EF7 to define a relational model produced by a reverse engineering provider. Ideally this could be the same model returned by an ADO.NET provider.

  12. saurabh500 commented on Nov 19, 2015

    @saurabh500
    Contributor
  13. 50 remaining items

  14. NickCraver commented on Jan 22, 2016

    @NickCraver
    MemberAuthor

    Linking initial PR discussion here: dotnet/corefx#5609

  15. terrajobst commented on Feb 3, 2016

    @terrajobst
    Contributor

    We discussed this today. We believe the current proposal isn't ready yet.

    @saurabh500: once you updated the proposal, please edit the description of the issue and copy & paste it there. Also, remove the api-needs-work label and add the api-ready-for-review label. Thanks!

  16. changed the title [-]A replacement API for DataReader.GetSchemaTable()[/-] [+]API for retrieving Columns Schema from DbDataReader[/+] on Feb 4, 2016
  17. saurabh500 commented on Feb 4, 2016

    @saurabh500
    Contributor
  18. saurabh500 commented on Feb 4, 2016

    @saurabh500
    Contributor

    API for GetColumnSchema

    Problem

    DbDataReader on .Net Framework, provides an API called DataTable GetSchemaTable() which was returns the metadata of the columns
    being read using the DbDataReader object. Because of the removal of DataTable in .Net Core this API had to be removed.
    DbDataReader.GetSchemaTable() needs a replacement in .Net core.

    Progress

    The data structure DbColumn along with the necessary attributes which should be present
    for the various ADO.Net providers to effectively provide the metadata for the columns is provided in the issue.

    namespace System.Data.Common
    {
       // DbColumn contains the base attributes that are common to most Database columns. An indexer 
      // has been provided in case a property added by a provider needs to be accessed without a dependency on the provider implementation. 
        public class DbColumn
        {
            public virtual bool AllowDBNull { get; set; }
            public virtual string BaseCatalogName { get; set; }
            public virtual string BaseColumnName { get; set; }
            public virtual string BaseSchemaName { get; set; }
            public virtual string BaseServerName { get; set; }
            public virtual string BaseTableName { get; set; }
            public virtual string ColumnName { get; set; }
            public virtual int ColumnOrdinal { get; set; }
            public virtual int ColumnSize { get; set; }
            public virtual bool IsAliased { get; set; }
            public virtual bool IsAutoIncrement { get; set; }
            public virtual bool IsExpression { get; set; }
            public virtual bool IsHidden { get; set; }
            public virtual bool IsIdentity { get; set; }
            public virtual bool IsKey { get; set; }
            public virtual bool IsLong { get; set; }
            public virtual bool IsReadOnly { get; set; }
            public virtual bool IsUnique { get; set; }
            public virtual int NumericPrecision { get; set; }
            public virtual int NumericScale { get; set; }
            public virtual string UdtAssemblyQualifiedName { get; set; }
            public virtual Type DataType { get; set; }
            public virtual string DataTypeName { get; set; }
    
            public virtual object this[string property] {} 
    
    
        }
    }

    The next part of the API is to expose a ReadOnlyCollection from the DbDataReader

    The right way of exposing the API would be to add an API in the DbDataReader class called
    ReadOnlyCollection<DbColumn> DbDataReader.GetColumnSchema()

    This is however not possible in .Net Core current version as it would hinder portability of apps created on .Net core with .Net framework.

    https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/breaking-change-rules.md

    Based on the contents of the link above, the following rule is allowed
    Adding an abstract member to a public type when there are no accessible (public or protected) constructors, or the type is sealed

    The restriction is due to type forwarding, which needs the calls to DbDataReader to be forwarded to the .Net framework's DbDataReader.

    Proposal

    We introduce an interface called IDbColumnSchemaGenerator, in .Net core which can be implemented by a type which can provide the Column Metadata.
    For DbDataReader, this interface needs to be implemented by the subclasses of the DbDataReader to provide the Column metadata provided by the DbDataReader

    namespace System.Data.Common
    {
        public interface IDbColumnSchemaGenerator
        {
            System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema();
        }
    }

    The subclasses of DbDataReader in the ADO.Net providers implement this interface.

    public class SqlDataReader : DbDataReader, IDbColumnSchemaGenerator 
    {
      public ReadOnlyCollection<DbColumn> GetColumnSchema(){
          return ... ; 
      }
    }

    In .Net core, to allow the Column Metadata to be exposed from the DbDataReader, an extension to the DbDataReader will be provided. This extension has the same signature as the interface method.

    using System.Collections.ObjectModel;
    
    namespace System.Data.Common
    {
        public static class DbDataReaderExtension
        {
            public static System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema(this DbDataReader reader)
            {
                if(reader is IDbColumnSchemaGenerator)
                {
                    return ((IDbColumnSchemaGenerator)reader).GetColumnSchema();
                }
                throw new NotImplementedException());
            }
        }
    }

    It is recommended that the extension be used by consumers, for compatibility with .Net Framework. The details are mentioned in the compatibility section below.

    Producer

    The ADO.Net providers are the producers of the Column Schema. The interface will be implemented by the sub-classes of DbDataReader in the ADO.Net providers.

    E.g.

    class SqlDataReader : DbDataReader, IDbColumnSchemaGenerator
    {
        ...
    
            public ReadOnlyCollection<DbColumn> GetDbColumnSchema()
            {
                ReadOnlyCollection<DbColumn> metadata = ... ; 
                // Build the list of columns metadata. Each columns metadata is represented by the DbColumn
                return metadata; // 
            }
        ...
    }

    Consumer

    The consumers can retrieve the column metadata using an extension method on the DbDataReader. This extension will be provided in System.Data.Common

    For a library consuming the DbDataReader the code will look like the following:

    using System.Data.Common;
    
    namespace org.example.my
    {
            ...
                public void ProcessMetadata(DbDataReader reader)
                {
                    ICollection<DbColumn> columnMetadata = reader.GetColumnSchema();
                }
            ...
    }

    Compatibility of libraries written on .Net Core with .Net Framework

    The extension method will have a different implementation in the partial facade to get the Schema. The implementation will use the DbDataReader.GetSchemaTable() api which returns the schema as a Datatable.
    This Datatable will be mapped to a ReadOnlyCollection and returned by the implementation of the extension in the partial facade.

    vNext

    Change in .Net Framework (Desktop)

    In the next version of .Net Framework we add a virtual method on the DbDataReader to allow access to schema using ReadOnlyCollection<DbColumn>
    The method will have the same signature as the extension method.

    namespace System.Data.Common
    {
        public abstract class DbDataReader : ... 
        {
            ...
            public virtual ReadOnlyCollection<DbColumn> GetColumnSchema()
            {
                // Map Datatable to the DbColumn as default implementation
                // Providers can override the implementation for their requirement.
                // The implementation will be similar to the implementation in 
                // partial facade implementation for .Net core v1.0 
            }
        }
    
    }

    .Net Core: vNext

    For a vNext of .Net core which targets .Net Framework with the API added to it, we can introduce the same API on .Net core with a default implementation in the base class DbDataReader. At this point the providers have the option of providing the metadata either by overriding the method in the base class or by implementing the interface.
    The base class implementation would check if the interface is implemented by the subclass and will provide the interface implementation while querying the base class API. The providers which do not implement the interface will have the option of overriding the base class method or implementing the interface.

    The base class virtual function will have the same signature as the interface.

    namespace System.Data.Common
    {
        public abstract class DbDataReader : ... 
        {
            ...
            public virtual ReadOnlyCollection<DbColumn> GetColumnSchema()
            {
                if(this is IDbColumnSchemaGenerator)
                {
                    return ((IDBColumnSchemaGenerator)this).GetColumnSchema();
                }
                throw new NotImplementedException();
            }
        }
    
    }

    The vNext of .Net core will have a changed implementation of the Extension method where the extension method will call the base class function to retrieve the schema. This will allow consumer DLL compiled on .Net core v1.0 to be able to run on vNext without any changes.

    Any code compiled on .Net Core vNext will compile against the base class function as the member methods get precedence over the extensino method.

    Examples

    Consumers

    A consumer written on .Net Core on v1.0

    In this case, the code will be compiled with the Extension method.

    using System.Data.Common;
    
    namespace org.example.my
    {
            ...
                public void ProcessMetadata(DbDataReader reader)
                {
                    ICollection<DbColumn> columnMetadata = reader.GetColumnSchema();
                }
            ...
    }

    In vNext of .Net core

    If the consumer is recompiled, the code will be compiled with the base class DbDataReader which has the virtual method added to it. The base class virtual method takes precedence

    using System.Data.Common;
    
    namespace org.example.my
    {
            ...
                public void ProcessMetadata(DbDataReader reader)
                {
                    ICollection<DbColumn> columnMetadata = reader.GetColumnSchema();
                }
            ...
    }

    Producers

    The producers in the .Net Core v1.0 don't have to implement the interface IDbColumnSchemaGenerator in v1.0

    In vNext, they can continue to implement the interface and not change any code. However, they can choose to override the base class method to provide the Column Schema as well. Either ways the consumer will not need to change their code to consume the Schema

    For new provider implementation, it is however recommended that they override the base class virtual method in DbDataReader for Columns Metadata.

  19. NickCraver commented on Feb 4, 2016

    @NickCraver
    MemberAuthor

    @saurabh500 Thanks for writing all this up. Just a few minor improvements I see:
    I think the .Net desktop version is missing the conversion bits from the proposal, specifically this example both now (extension) and vNext (virtual):

    namespace System.Data.Common
    {
        public abstract class DbDataReader : ... 
        {
            public virtual ReadOnlyCollection<DbColumn> GetColumnSchema()
            {
                throw new NotImplementedException();
            }
        }
    }

    I think it'd be better to put a comment (rather than the throw) about converting the existing GetSchemaTable() to ReadOnlyCollection<DbColumn> in these examples to be more accurate and convey the providers-need-to-do-nothing to get the benefits of today's interfaces, but they can to add more detail later if they choose to override. It's correct in this section of the notes, but the code doesn't align:

    The extension method will have a different implementation in the partial facade to get the Schema. The implementation will use the DbDataReader.GetSchemaTable() api which returns the schema as a Datatable. This Datatable will be mapped to a ReadOnlyCollection and returned by the implementation of the extension in the partial facade.

    One other item: I'd use something along the lines of IDbDataReaderSchemaGenerator for the interface name, I think IDbColumnSchemaGenerator is too generic/confusing when factoring in the entire-database schema getter that may have a similar interface approach.

  20. saurabh500 commented on Feb 4, 2016

    @saurabh500
    Contributor

    @NickCraver
    For the first part. Thanks for pointing it out. I will make changes to align the code with the description using comments.

    The second part about the name of the interface
    IDbColumnSchemaGenerator: I chose the name because I wanted to convey that the implementing class is a Column Schema Generator and a ProviderDbReader can implement this class to become a Column Schema Generator.

    In case another class is internally created by the provider to generate Column Schema, this interface can be used by them. E.g. If there is an class or technique which generates the schema for the database this interface can be used to populate the columns using a different implementation than the DbDataReader.

    This was the thought process behind the name and mapping it to DbColumn Schema rather than the interface.

    IDbDataReaderSchemaGenerator gives the sense that the object should be a reader and can apply to this usecase.
    I did think about calling the interface IDbDataReaderSchemaGenerator but chose IDbColumnSchemaGenerator so that the concept of DbColumn schema generation can be decoupled from a reader and can be used in a more generic manner.

    Thoughts?

  21. terrajobst commented on Feb 5, 2016

    @terrajobst
    Contributor

    @saurabh500

    Thanks for writing this up. In order to keep things organized I propose that:

    • We close this issue.
    • @saurabh500 creates a new issue and copy as pastes the above write up in there.

    As refinements are made, we update the description. The reason I say this is because finding the latest version of a proposal is otherwise a daunting task.

  22. saurabh500 commented on Feb 5, 2016

    @saurabh500
    Contributor

    @terrajobst I have opened issue dotnet/corefx#5915 for API review
    That would help track feedback for the API.

    @NickCraver Can you close this issue? We can follow this up on dotnet/corefx#5915

  23. terrajobst commented on Feb 5, 2016

    @terrajobst
    Contributor

    Thanks!

  24. werddomain commented on May 29, 2016

    @werddomain

    where i can download this api?
    Im translating my mcv 5 app and this block me, i cant finish the conversion :(

        `public static List<string> GetColumnList(DbDataReader reader)
        {
    
            List<string> columnList = new List<string>();
    
            DataTable readerSchema = reader.GetSchemaTable();
    
            for (int i = 0; i < readerSchema.Rows.Count; i++)
    
                columnList.Add(readerSchema.Rows[i]["ColumnName"].ToString());
    
            return columnList;
    
        }`
    
  25. transferred this issue fromdotnet/corefxon Jan 31, 2020
  26. added this to the 1.0.0-rtm milestone on Jan 31, 2020
  27. ghost locked as resolved and limited conversation to collaborators on Jan 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions