Schemas in ADO.NET 2.0

xiaoxiao2021-03-06  104

An in-depth look at the New Common Metadata API

Download The Associated Schemassample.exe Sample Code.

In my previous article, I pointed out that Visual Studio 2005 Server Explorer now uses a dialog box containing a list of .NET data providers (rather than OLE DB providers) to prompt for connection information. When you decide on a connection string and add a Data Connection, each Data Connection also displays a tree of information about the database objects (like tables, views, and stored procedures) visible directly through the connection. But where does this information come from? Is Visual Studio hard-coded to produce this information only for certain data providers, leaving me with an empty node if I write my own data provider or buy one from a third party? No, not in Visual Studio 2005. All of this good information is brought to you courtesy of the new Schema API IN ADO.NET 2.0. I don't know IF this Is How Visual Studio Does It, But Here Is Code To Get A List of Tables IN A DATABASE Using The New Apis.

// Uses a ADO.NET 2.0 Named Connection String In Config File

// Uses ADO.NET 2.0 ProviderFactory and Base Classes

// See Previous Article

Public Static Void getListoft Ables (String ConnectString_name)

{

ConnectionstringSettingS s =

ConfigurationSettings.connectionstrings [ConnectString_name];

DBProviderFactory f = dbProviderfactories.getFactory (S.ProviderName);

Using (dbconnection conn = f.createConnection ())

{

Conn.connectionstring = S.Connectionstring;

Cn.open ();

DataTable t = conn.getschema ("Tables");

T.WriteXML ("Tables.xml");

}

}

Who Needs metadata, Anyway?

Metadata is a part of every data access API. Although the primary consumers of metadata are tools like Visual Studio or code generators like DeKlarit, they are not the only users. Application package designers may allow end-users to customize an application by adding new tables or new columns to existing tables. When end-users change the database schema like this, a general-purpose query and modification tool can use metadata to include the users' new tables in maintenance, backup, and other application functions just like they were built -in tables that ship with the application. Programmers can use metadata to write their own custom classes that derive from System.Data.Common.DbCommandBuilder and build insert, update, and delete commands for use with the DataSet. Builders of multi-database applications (That IS, Applications Designed to Run on the user's cho3tain a common code base as much as possible, Optimizing the data access code by .It's better to expose the metadata through a generic metadata API than to have each consumer use the database-specific API. That way, tool writers can maintain a more manageable code base. Such an API must be very flexible as well, because there are Four Obstacles to consider when Writing a generic api to evpose metadata.

The metadata collections and information differ between databases. For example, SQL Server users might want to expose a collection of Linked Servers, whereas Oracle users might be interested in information about Oracle Sequences. The underlying system tables in which common database metadata is stored is different , not only in different database products, but even in different versions of the same database. for example, SQL Server 2005 exposes its metadata using new tables under a "sys" schema (for example, sys.tables) while previous versions of SQL Server use metadata tables, such as sysobjects, to store the same data. Different programs may have different views of metadata. As an example, many programmers complain about long lists of tables in an Oracle database because most metadata APIs mix "system" tables with user Tables. TheY'd Like to Have A Short List That Consists Only OR NOT To Support Metadata At All, And How Much Metadata To Provide, Should be entirely up to the provider writer.Most database APIs provide a standard set of metadata that all providers must support and allow provider writers to add new metadata tables. This is consistent with the approach taken by ANSI SQL standard. The part of the standard that addresses this is the Schema Schemata (INFORMATION_SCHEMA and DEFINITION_SCHEMA), part 11. The ANSI SQL INFORMATION_SCHEMA defines of standard set of metadata views to be supported by a compliant database. But even the spec needs to have a way to address the points above. It States:

"Implementers are Free to Add Additional Tables to the information_schema or additional columns to the pre-defined information_schema tables."

As an example of a data access API consistent in concept with the ANSI SQL standard, OLE DB defined a series of metadata that it called "Schema Rowsets". It started with a predefined set that roughly followed the INFORMATION_SCHEMA and added OLE DB-specific columns TO Each One. ADO.NET 2.0 Province An Even More Powerful and Flexible Mechanism To Expose Metadata.What metadata can I get?

ADO.NET 2.0 permits a provider writer to expose five different types of metadata. These main metadata "meta-collections" or "categories" are enumerated in the class System.Data.Common.DbMetaDataCollectionNames.

MetaDataCollections-A list of metadata collections available. Restrictions-For each metadata collection, an array of qualifiers that can be used to restrict the scope of the schema information requested. DataSourceInformation-Information about the instance of the database the data provider references. DataTypes- A Set of Information About Each Data Type The Database Supports. RESERVEDWORDS-Reserved Words for That Database's Query Language. Usually "Query Language" Equates to a SQL DIALECT.

MetaDataCollections is the name for the INFORMATION_SCHEMA collections, like "Tables", "Columns", or "PrimaryKeys". Using DbConnection.GetSchema, however, these metadata categories are also considered metadata. What this means in terms of code is that these collections can Be obtained like Ordinary Metadata.

// Gets Information About Database Views

Table t1 = conn.getschema ("views");

// Gets Information About Collections Exposed by this provider

// this incrudes the FIVE "Meta-Collection" Described Above

Table t2 = conn.getschema (dbmetadatacolectionnames.metadatacollections); // Gets Information About The Restrictions Meta-Collection

Table T3 = conn.getschema (dbmetadatacolectionnames.restrictions);

// no argument overload is Same as asking for metadatacollections

Table T4 = conn.getschema ();

Two of the FIVE META-Collections Deserve Further Explanation.

Restrictions

Restrictions can be used to limit the amount of metadata returned. If you are familiar with OLE DB or ADO, the term "restriction" means the same thing in those APIs. As an example, let's use the MetaDataCollection "Columns", which is the set of Column names in tables. This collection can be used to get all of the Columns in all tables. However, the set of columns requested can be restricted by database name, by owner / schema, or by table. Each metadata collection can have A Different Number of Possible Restrictions and Each Restriction Can Have A Default. Following Along with Our Example, Here's An XML Representation of The Restrictions for the Column Metadata:

Listing 1. Restrictions on The Column Collection (XML Format)

Column

Catalog

Table_catalog

1

Column

Owner

Table_Schema

2

Column Table

Table_Name

3

Column

Column

Column_name

4

Restrictions are specified using an overload of DbConnection.GetSchema. The restrictions are specified as an array. You can specify an array as large as the entire restrictions collections or a subset array, because "RestrictionNumbers" usually progress from least restrictive to most restrictive. Use A Null Value (NOT DATABASE NULL, But .Net Null, or Nothing In Visual Basic .NET) for Restriction Values ​​You Want To Leave Out. for Example:

// restriction string array

String [] res = new string [4];

// All columns, all Tables OWNED by dbo

RES [1] = "dbo";

DataTable T1 = Conn.getschema ("Column", RES);

// Clear Collection

For (int i = 0; i <4; i ) RES [i] = null;

// all column, all tables named "authors", Any Owner / Schema

RES [2] = "authors";

DataTable T2 = Conn.getschema ("Column", RES);

// Clear Collection

For (int i = 0; i <4; i ) RES [i] = null;

// columns named au_lname

// All Tables named "authors", Any Owner / Schema

RES [2] = "authors"; res [3] = "au_lname";

DataTable T3 = Conn.getschema ("Column", RES);

// Clear Collection

For (int i = 0; i <4; i ) RES [i] = null; // columns named au_lname

// any Tables, ANY OWNER / Schema

RES [3] = "name";

DataTable T4 = Conn.getschema ("Column", RES);

You need not specify the entire array of restrictions. In the case above, where you'd like to see only columns in tables owned by "dbo", you can specify an array with only two members instead of all four. Note also that specifying an empty string as a restriction is different than specifying a null (Nothing in Visual Basic .NET) value you do not need to memorize the restrictions;. you can always query for them, just like any other collection The "Restrictions" collection itself. Does Not Allow Restrictions, But Because The Information Is Fetched Into A DataTable, You Can Use A DataView To Provide Similar FunctionAlity, AS Shown Below.

DataTable TV = conn.getschema (dbmetadatacolectionnames.restrictions);

DataView v = tv.defaultview;

// Show Restrictions on the "columns" Collection, sorted by Number

v.rowfilter = "collectname = 'color";

v.sort = "restrictionnumber";

For (int i = 0; i

Console.writeline ("{0} (default) {1}",

TV.Rows [i] ["restrictionname"],

TV.Rows [i] ["restrictionDefault"]);

DataSourceInformation

The DataSourceInformation collection provides information about the current instance of the database (data source) for query builders. Although this collection can contain anything the provider desires, in the Microsoft providers (SqlClient, OracleClient, OleDb, Odbc) this collection contains similar information. Here's The information you get by default.

Table 1. DataSourceInformation in Microsoft providersValueFormat / MeaningCompositeIdentifierSeparatorPatternSeparator for multipart names, (eg, the dot in pubs.dbo.authors) DataSourceProductNameDatabase nameDataSourceProductVersionDatabase version. Note that this is the version of the database instance currently being accessed by the DbConnection.DataSourceProductVersionNormalized GroupByBehaviorEnumeration, System .Data.Common.GroupByBehaviorIdentifierPatternRegular expression stringIdentifierCaseEnumeration, System.Data.Common.IdentifierCaseOrderByColumnsInSelectBoolean, should you ORDER bY the columns in a SELECT statement by defaultParameterMarkerFormatIndicates whether parameter markers begin with a special character (eg, @ for T-SQL) ParameterMarkerPatternRegular expression string, Used to create parametersparameternameTernameMaxlengththmaximum length of a parameterparameterNamePatternRegular Expression String, Used to create ParametersquotedIndiDentifierPatternRegular Expression String d to quote identifiersQuotedIdentifierCaseEnumeration, System.Data.Common.IdentifierCaseStatementSeparatorPatternRegular expression stringStringLiteralPatternRegular expression stringSupportedJoinOperatorsEnumeration, System.Data.Common.SupportedJoinOperators

More than enough information to produce SQL for a particular database dialect, do not you think? There is just one more piece of information I'd like, and that's whether the provider uses named parameters or positional parameters in parameterized queries. I mentioned named And Positional Parameters As Two Ways to Write Parameterized Commands in My Last Article About Writing Provider-Independent Code.

Customizing and extending the metadata

Now that we've seen the base metadata that is provided and can find our way around DbConnection.GetSchema (), let's look at the ways provider writers can customize metadata using a simple declarative format, and how programmers can hook into that format. This discussion ties back to our metadata complications at the beginning of the article: how to provide database-version-independent metadata and how to deal with the fact different customers may want different views of the same metadata.First, let's point out that metadata support that is completely optional Providers do not have to support DbConnection.GetSchema;.. this method can throw a NotSupportedException In addition, only the MetaDataCollections category is required if the provider writer chooses to support DbConnection.GetSchema Providers can choose not to supply any or all. Other four categories of information.

Next, each provider can expose different information for the same metadata collection The structure of the Tables collection, for example, is entirely up to the provider writer As an example, the SqlClient provider exposes four information items in the Tables collection:.. Table_catalog, table_schema, table_name and table_type. The OracleClient provider exposes only three information items (OWNER, tABLE_NAME, and TYPE) because Oracle databases do not contain multiple catalogs. The number of restrictions and restriction items can be different for each provider. Using the case of Tables again, the SqlClient provider supports four restrictions, and the OracleClient provider supports two. The restrictions also need not occur in any specific order. So there is no mandated metadata structure, amount of metadata, or order of metadata, as there is in the OLE DB and ODBC APIS. The Provider is Free to Expose Whate Metadata IS Pertinent. However, IF A Specific Application (LIKE Visual Studio) desires that the metadata be consistent among all .NET data providers used in an application, it can obtain this behavior, too, by overriding the provider's normal behavior. We'll discuss this further in the User Customization section.

Provider writers can hard-code metadata logic directly into their providers, with each provider-writer using a potentially different internal algorithm for obtaining similar metadata. This is the way it's been done in the past, for example, in implementing the OLE DB ISchemaRowset method . in ADO.NET 2.0, however, there are some base classes available for provider writers in the System.Data.ProviderBase namespace. The four available Microsoft providers use these base classes, so they all implement schemas similarly. I'll use this implementation for exposition, hoping that major provider-writing players like DataDirect Technologies and other provider-writers will use it, too.The base class for exposing metadata is DbMetaDataFactory. Providers that implement a subclass of it use an XML file to define their metadata-fetching Behavior. Thase Files Are Embedded Resources In System.data.dll and System.data.OracleClient.dll; You CAN Look At the Raw Xml Files by Running Ildasm.exe from the CommM And line.

> ildasm.exe system.data.dll /out:dummy.il

Looking at the XML resource files produces from ILDASM peels another layer off the onion. The file enumerates the collections that are supported and the information contained in each meta-collection (through the schema) and appears to be the output of the DataSet.WriteXml method using the DataSet.WriteXml (XmlWriteMode.WriteSchema) overload. The most interesting bits are the MinimumVersion / MaximumVersion elements in all the meta-collections except DataSourceInformation and the PopulationMechanism / PopulationString subelements in the MetaDataCollections elements.

Using MinimumVersion / MaximumVersion allows the provider writer to specify which metadata queries to execute for different versions of the database. By using multiple elements for a single MetaDataCollection, you can make GetSchema act differently for different versions of the database. As an obvious example, you could use different versions for SQL Server 2005 than for previous versions of SQL Server Here's an example of using MinimumVersion from the SQL Server metadata resource, System.Data.SqlClient.SqlMetaData:. Listing 2. Metadata Entry for Data Type XML in Data Types Collection

XML

25

2147483647

System.String

false

false

false

false

True

True

True

false

09.00.000.0

false

This defines information about the SQL Server data type XML. The MinimumVersion indicates that this data type is only available when using SQL Server 2005. If you ask SqlConnection.GetSchema for a list of data types that the database supports, only SQL Server 2005 databases ( SQL Server 2005 is version 9, the current beta 2 version is 09.00.852.2) will report that they support the XML data type.For collections usually exposed by the INFORMATION_SCHEMA (like Tables, Views, or Stored Procedures), PopulationMechanism and PopulationString are where things get started There are three PopulationMechanisms used in this implementation:... DataTable, SQLCommand, and PrepareCollection DataTable is used to populate the meta-collections Using DataTable means that the information used to populate the collection is in the XML resource file itself in. Each Case, The PopulationString Is The Name of The DataTable Product. SqlCommand Means That Thim E Provider Will Use a dbcommand instance to issesue The Command Against The Database. if You Look At One of The PopulationStrings of a Collection Product PROPUCED by a SqlCommand:

Listing 3. Entry for Databases (Catalogs) in SQL Server - Metadatacollection

Databases

1

1

SQLCommand

Select Name As Database_name, DBID, CRDATE AS

Create_date from master..sysdatabases where name = {0}

It's fairly easy to deduce that String substitution will be applied to the "base query" when restrictions are used in DbConnection.GetSchema. If no restrictions are specified that predicate will effectively be stripped out of the query.The provider writer can use a custom mechanism when the value of PopulationMechanism is PrepareCommand. There is a PrepareCommand method of DbMetaDataFactory that, if overridden by the provider writer, can be coded to use whatever custom semantics the provider chooses. This mechanism is used in SqlClient to produce the DataTypes meta-collection. The SqlMetaDataFactory subclass implementation of PrepareCommand first reads the built-in data types supported by SQL Server from the DataTable, as with other meta-collections, and then uses custom logic to add user-defined types to the collection if the database is SQL Server 2005 (NOTE: SQL Server 2005 CAN Expose .NET CLASS AS User-Defined Types. See Chapter 5 of a First Look At SQL Server 2005 For Developer S for more information.)

User Customization

In addition to the provider customization mechanism, there is also a hook that allows programmers to customize schema information on a per-application basis! Before loading the embedded resource, the DbConnectionFactory CreateMetaDataFactory will consult the application configuration file. Each provider can implement CreateMetaDataFactory to retrieve the XML stream for its DbMetaDataFactory in whatever way it chooses, but the four Microsoft providers follow a common pattern. Each Microsoft provider will look for an application configuration setting named after the provider itself (eg, system.data.sqlclient). in this setting element you can add or remove name-value pairs. DbMetaDataFactory looks for a name "MetaDataXml". The value corresponding to the special name is the name of a file. This is a simple file name-the file must exist in the CONFIG subdirectory of The location where .net is installed. this is the directory where machine.config and the security configuration settings LIV e. This file must contain the entire set of schema configuration information, not just the change.

You can use this mechanism, for providers that support it, for many reasons. For example, you could change the schema queries in the OracleClient provider to use the USER catalog views rather than the ALL catalog views. Because the USER views do not contain information about internal database tables, the list of Tables, for example, will be much shorter and easier to work with. Another example might consist of coding out metadata XML files for all .NET data providers that give you a consistent standard set of metadata, possibly one that corresponds exactly to the SQL-99 INFORMATION_SCHEMA views. This might be just right for your application.A more concrete example would be if I wanted to expose information about SQL Server Service Broker metadata collections in SQL Server 2005. These collections might include Queues, Services, Contracts, And Message Types. I Would Start with The Embedded XML Resource File and Embellish It With Information On My New Collections. If The File Name WAS SQLB Rokeraware.xml, I Would Install The File and My Application Configuration File Would Look Like this:

That's all there is to it! Using what setup, I Could Write Code In Which Service Broker Metadata IS Part of The Built-in metadata available to the client. The code might look like this for all of the queues:

Using (SqlConnection Conn = New SqlConnection (ConnString))

{

Cn.open ();

// this include Service Broker Metadata CollectionStable T = Conn.getschema (DBMetAdatacollectionNames.Metadatacollections);

// get all the queues in My Database

Table queues = conn.getschema ("queues");

}

Very cool indeed! A code sample that adds Service Broker metadata is included with this article. Although this is a very powerful feature, it does have the capability to be abused. Remember that you'll need to distribute the metadata XML file with every application that uses it and convince the System Administrator to install it in the CONFIG directory for you. and you'll need to maintain it with each new version of the provider that ships. Because one of the reasons for generic metadata APIs is to have consistent metadata Across Databases and Applications, this Feature Should Not Be used graturely. Note Also That You Cannot Provide A Custom Implementation of PrepareCommand At this Time.

As a final remark on customization, you might have guessed that customization and resources work differently with the bridge providers for OLE DB and ODBC. When you use these providers, the default Odbc or OleDb XML resource files are used, and you can customize not only the main Odbc or OleDb schema behaviors, but also customize the behavior on a per-provider basis. If you want to specify your own providers or drivers, the name attribute used in adding / removing settings subelements would not be MetaDataXml, but instead would be .

Conclusion: Final Fragments of Metadata Support

In closing, I'd just like to mention two other metadata extensions that are not exposed through DbConnection.GetSchema. The DbCommandBuilder includes two properties, QuoteIdentifier and UnquoteIdentifier, which permit you to customize identifiers in commands that the CommandBuilder builds. As an example, in SQL Server you can use double-quote ( ") or brackets ( '[' and ']') to quote identifiers, depending on your session settings. Finally, the class SqlMetaData in the System.Data.Sql namespace is used to expose the metadata in SQL Server DataReaders and allows you to set this metadata in Parameters used by SqlCommand. This metadata is similar in concept to, though not anywhere near as detailed as, the metadata exposed in the DataTypes meta-collection. SqlMetaData is useable by both the SqlClient data provider and the in-database SqlServer data provider included with SQL Server 2005. SqlMetaData augments the rowset metadata exposed currently by the method SqlDataReader.GetSchemaTable (). At this point you'll likely agree that the ADO.NET 2.0 metadata infrastructure is the most powerful, flexible, and customizable you've seen. It expands the picture of ADO.NET as a complete object-oriented database API. Tool vendors, provider Writers, And Users of Visual Studio Data Tools Will Be dancing in the streets-see you there.

转载请注明原文地址:https://www.9cbs.com/read-124243.html

New Post(0)