runtime icon indicating copy to clipboard operation
runtime copied to clipboard

API for retrieving Columns Schema from DbDataReader

Open NickCraver opened this issue 11 years ago • 72 comments

This is to unwrap the specific issue of resultset schemas from the many involved in dotnet/runtime#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 dotnet/runtime#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 dotnet/runtime#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.

NickCraver avatar Sep 24 '15 10:09 NickCraver

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.

FransBouma avatar Sep 24 '15 10:09 FransBouma

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

william-gross avatar Sep 24 '15 20:09 william-gross

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.

NickCraver avatar Sep 25 '15 21:09 NickCraver

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)...

roji avatar Sep 25 '15 21:09 roji

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.

FransBouma avatar Sep 26 '15 08:09 FransBouma

@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?

nvivo avatar Sep 26 '15 13:09 nvivo

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

YoungGah avatar Oct 02 '15 03:10 YoungGah

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.

bricelam avatar Oct 02 '15 17:10 bricelam

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

YoungGah avatar Oct 02 '15 17:10 YoungGah

@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.

roji avatar Oct 03 '15 08:10 roji

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.

roji avatar Oct 07 '15 19:10 roji

cc @jcyang75

saurabh500 avatar Nov 19 '15 21:11 saurabh500

For the schema information return type we are considering adding a List of Dictionaries. The dictionary looks like Dictionary<string, object> The key will represent that column and the object will be the value of the column. Each item in the list will represent an item in the schema.

This data structure can be used for the replacement of the DbConnection.GetSchema() API as well. Let us know what you think.

For the DataReader API we are considering the following names:

  1. GetSchemaDefinition()
  2. GetSchemaInfo()
  3. GetDefinition()

Suggestions, votes?

saurabh500 avatar Dec 15 '15 02:12 saurabh500

@saurabh500 It's a bit hard to picture this in the abstract, can you give us an example of what this would look like? Let's say if it were serialized as JSON for the purposes of discussion.

Thoughts without the layout example for discussion: I would want constants for the known things such as size, type, etc. (as opposed to magical matching strings on every consumer's side), but the lack of strong typing by the nature of the API is a pretty significant downside. We're talking about shifting to runtime breaks rather than compile time breaks on an API that differs between CLR vs. CoreCLR. Every consumer would be casting object to the string, int, Type, etc. (and causing a lot of boxing in the process, though to be fair: that's not a major concern here I think).

While GetSchemaTable() isn't the best option, it is typed and most issues are compile time rather than runtime. I wouldn't want to lose this ease of use (and safety) vs. a very generic dictionary approach. There should be a more strongly typed API. If this is an attempt to describe both document and tabular data in the same APIs, I think that's a bad approach. There is a fundamental disconnect even at the "number of levels" definition, and those should be distinct APIs. The tabular schema definitions can then be much more strongly typed, and I can certainly see a string indexer on that description class/type for providers to add any additional properties they want above and beyond the base, strongly typed set.

NickCraver avatar Dec 15 '15 02:12 NickCraver

I second @NickCraver here, if you're doing a new schema API, there's no reason whatsoever not to have it typed. Why not create classes such as DbSchemaTable, DbSchemaColumn, DbSchemaFunction and include simple strongly-typed properties exposing relevant information (e.g. Precision, Scale)? Specific providers could extend these (e.g. SqlSchemaColumn) to add provider-specific properties, as is already done with other areas of the ADO.NET API...

roji avatar Dec 15 '15 07:12 roji

Also, as I mentioned above, note the EF7 reverse-engineering effort currently underway, which does exactly this: represent a database schema in a strongly-typed way. Any chance the ADO.NET and EF7 teams could get together and see if a single API could be used here?

roji avatar Dec 15 '15 07:12 roji

Agree with @roji's example and @NickCraver 's points. An untyped Dictionary bucket is useless. I also wonder how much time has been put into this on MS' side. We're debating this since May this year and the most naive approach is to use an untyped Dictionary and MS comes up after all this time with exactly that.

Not a good show, people.

FransBouma avatar Dec 15 '15 07:12 FransBouma

@FransBouma, @roji, @NickCraver Thanks for the feedback.

While proposing the loosely typed Dictionary there were 3 considerations:

  1. Allowing schema to be returned by DataReader
  2. Allowing DbConnection.GetSchema(), DbConnection.GetSchema(String), DbConnection.GetSchema(String, String[]) to return a schema in a manner similar to point 1.
  3. Allowing another provider to provide the schema using the same API

The DataReader's GetSchemaTable API provided the same Column Names every time it is used. However the DbConnection's GetSchema() and the overloads provide different Column Names based on what is being queried.

If the DbConnection.GetSchema is called, then the Columns returned are CollectionName, NumberOfRestrictions, NumberOfIdentifierParts If the schema information of the Databases is queried, then the returned columns are database_name, dbid, create_date In case the schema information of all Tables is queried then the columns are TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE

The column names are different based on different contexts in which the Schema is being retrieved.

In the interest of keeping the Data Structure same for DbConnection and DataReader, I recommended an untyped Dictionary with relevant information present in it. The providers can also provide their own Keys if they choose to use constants that System.Data.Common exposes.

@NickCraver following is a close JSON representation of what I was recommending:

[{
    ColumnName : "CourseID",
    ColumnOrdinal : "0",
    ColumnSize : "10",
    NumericPrecision : "255",
    NumericScale : "255",
    IsUnique : "False",
    BaseColumnName : "CourseID",
    DataType : "System.String",
    AllowDBNull : "False",
    ProviderType : "12",
    IsAliased : "",
    IsExpression : "",
    IsIdentity : "False",
    IsAutoIncrement : "False",
    IsRowVersion : "False",
    IsLong : "False",
    IsReadOnly : "False",
    ProviderSpecificDataType : "System.Data.SqlTypes.SqlString",
    DataTypeName : "nvarchar",
    ...
},
{
    ColumnName : "Year",
    ColumnOrdinal : "1",
    ColumnSize : "2",
    NumericPrecision : "5",
    NumericScale : "255",
    IsUnique : "False",
    BaseColumnName : "Year",
    DataType : "System.Int16",
    AllowDBNull : "False",
    ProviderType : "16",
    IsAliased : "",
    IsExpression : "",
    IsIdentity : "False",
    IsAutoIncrement : "False",
    IsRowVersion : "False",
    IsLong : "False",
    ProviderSpecificDataType : "System.Data.SqlTypes.SqlInt16",
    DataTypeName : "smallint",
    ...
}]

Having explained this, the consensus is definitely towards having a strongly typed API

Requests / Questions If the same return type is to be used for the Schema APIs of DbConnection and DataReader, what are the relevant set of strongly typed properties that should be included? Are you recommending adding different data structures for schema API for the DbConnection and DataReader? If the schema returned by DbConnection and DataReader, then there is hardly any overlap in the strongly typed properties.

This issue was opened for DataReader. @FransBouma has mentioned the DbConnection.GetSchema(...) API. It will be a good idea to discuss both DbConnection and DataReader on this thread.

The schema returned by the DataReader is the Column schema however the DbConnection covers a much wider range of schema at different levels.

saurabh500 avatar Dec 15 '15 09:12 saurabh500

@saurabh500, I understand the motivation for weakly-typed results you explain above. If a single API method (i.e. DbConnection.GetSchema()) needs to return different results based on the query its given, then there's indeed a problem with strongly-typed results.

I think the answer is to replace the single, multi-result GetSchema() with multiple methods, each of which returns a single result type. In other words, instead of having one method returning different things based on its input (the query), have several methods which each return only one thing. So you would have GetDatabaseSchema, GetTableSchema, and so on. Note the JDBC approach of retrieving a DatabaseMetadata object from the connection, which you can then query with specific methods; this has the advantage of concentrating all the schema-related methods in a single place that's separate from DbConnection (however, note that in JDBC these methods return a weakly-typed ResultSet which isn't good).

Regarding an overlap between DbConnection.GetSchema() and DbDataReader.GetSchema()... IMHO, an overlap isn't necessary related to making the API strongly-typed or not - even if there isn't any overlap anywhere a strongly-typed API is still preferable to a weakly-typed one. I think still there's some potential for overlap, e.g. with DbSchemaColumn with may be returned from both.

Finally, the JSON representation seems good in principle (assuming it gets translated to a strongly-typed API). However, please consider a clean distinction between SqlServer properties and general properties which make sense for all relational database. So DataTypeName and AllowDBNull make sense for all databases, but IsIdentity and IsRowVersion are entirely SqlServer-specific. The latter probably belong in an Sql* subclass, much like SqlConnection is a subclass of DbConnection.

roji avatar Dec 15 '15 13:12 roji

I am all for: 1: 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)... 2: And corresponding methods to replace the magic "GetSchema" - So you would have GetDatabaseSchema, GetTableSchema

The challenge being of course to agree on what belongs in the "general" model

ErikEJ avatar Dec 15 '15 13:12 ErikEJ