/mcs/class/referencesource/System.Data.Linq/SqlClient/SqlProvider.cs
C# | 2024 lines | 1692 code | 204 blank | 128 comment | 393 complexity | 925ac6166544d3fb2119787e9cbcdd2f MD5 | raw file
Possible License(s): GPL-2.0, CC-BY-SA-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, Unlicense, Apache-2.0
Large files files are truncated, but you can click here to view the full file
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Data;
- using System.Data.Common;
- using System.Data.Linq;
- using System.Data.Linq.Mapping;
- using System.Data.Linq.Provider;
- using System.Data.SqlClient;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Globalization;
- using System.Diagnostics.CodeAnalysis;
- using Me = System.Data.Linq.SqlClient;
- using System.Runtime.Versioning;
- using System.Runtime.CompilerServices;
- namespace System.Data.Linq.SqlClient {
- public sealed class Sql2000Provider : SqlProvider {
- public Sql2000Provider()
- : base(ProviderMode.Sql2000) {
- }
- }
- public sealed class Sql2005Provider : SqlProvider {
- public Sql2005Provider()
- : base(ProviderMode.Sql2005) {
- }
- }
- public sealed class Sql2008Provider : SqlProvider {
- public Sql2008Provider()
- : base(ProviderMode.Sql2008) {
- }
- }
- [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification="Unknown reason.")]
- public class SqlProvider : IReaderProvider, IConnectionUser {
- private IDataServices services;
- private SqlConnectionManager conManager;
- private TypeSystemProvider typeProvider;
- private SqlFactory sqlFactory;
- private Translator translator;
- private IObjectReaderCompiler readerCompiler;
- private bool disposed;
- private int commandTimeout;
- private TextWriter log;
- string dbName = string.Empty;
- // stats and flags
- private int queryCount;
- private bool checkQueries;
- private OptimizationFlags optimizationFlags = OptimizationFlags.All;
- private bool enableCacheLookup = true;
- private ProviderMode mode = ProviderMode.NotYetDecided;
- private bool deleted = false;
- #if PERFORMANCE_BUILD
- private bool collectPerfInfo;
- private bool collectPerfInfoInitialized = false;
- private bool collectQueryPerf;
- internal bool CollectPerfInfo {
- get {
- if (!collectPerfInfoInitialized) {
- string s = System.Environment.GetEnvironmentVariable("CollectDLinqPerfInfo");
- collectPerfInfo = (s != null) && (s == "On");
- collectPerfInfoInitialized = true;
- }
- return this.collectPerfInfo;
- }
- }
- internal bool CollectQueryPerf {
- get { return this.collectQueryPerf; }
- }
- #endif
- internal enum ProviderMode {
- NotYetDecided,
- Sql2000,
- Sql2005,
- Sql2008,
- SqlCE
- }
- const string SqlCeProviderInvariantName = "System.Data.SqlServerCe.3.5";
- const string SqlCeDataReaderTypeName = "System.Data.SqlServerCe.SqlCeDataReader";
- const string SqlCeConnectionTypeName = "System.Data.SqlServerCe.SqlCeConnection";
- const string SqlCeTransactionTypeName = "System.Data.SqlServerCe.SqlCeTransaction";
- internal ProviderMode Mode {
- get {
- this.CheckDispose();
- this.CheckInitialized();
- this.InitializeProviderMode();
- return this.mode;
- }
- }
-
- private void InitializeProviderMode() {
- if (this.mode == ProviderMode.NotYetDecided) {
- if (this.IsSqlCe) {
- this.mode = ProviderMode.SqlCE;
- } else if (this.IsServer2KOrEarlier) {
- this.mode = ProviderMode.Sql2000;
- }
- else if (this.IsServer2005) {
- this.mode = ProviderMode.Sql2005;
- } else {
- this.mode = ProviderMode.Sql2008;
- }
- }
- if (this.typeProvider == null) {
- switch (this.mode) {
- case ProviderMode.Sql2000:
- this.typeProvider = SqlTypeSystem.Create2000Provider();
- break;
- case ProviderMode.Sql2005:
- this.typeProvider = SqlTypeSystem.Create2005Provider();
- break;
- case ProviderMode.Sql2008:
- this.typeProvider = SqlTypeSystem.Create2008Provider();
- break;
- case ProviderMode.SqlCE:
- this.typeProvider = SqlTypeSystem.CreateCEProvider();
- break;
- default:
- System.Diagnostics.Debug.Assert(false);
- break;
- }
- }
- if (this.sqlFactory == null) {
- this.sqlFactory = new SqlFactory(this.typeProvider, this.services.Model);
- this.translator = new Translator(this.services, this.sqlFactory, this.typeProvider);
- }
- }
- /// <summary>
- /// Return true if the current connection is SQLCE.
- /// </summary>
- private bool IsSqlCe {
- get {
- DbConnection con = conManager.UseConnection(this);
- try {
- if (String.CompareOrdinal(con.GetType().FullName, SqlCeConnectionTypeName) == 0) {
- return true;
- }
- } finally {
- conManager.ReleaseConnection(this);
- }
- return false;
- }
- }
-
- /// <summary>
- /// Return true if this is a 2K (or earlier) server. This may be a round trip to the server.
- /// </summary>
- private bool IsServer2KOrEarlier {
- get {
- DbConnection con = conManager.UseConnection(this);
- try {
- string serverVersion = con.ServerVersion;
- if (serverVersion.StartsWith("06.00.", StringComparison.Ordinal)) {
- return true;
- }
- else if (serverVersion.StartsWith("06.50.", StringComparison.Ordinal)) {
- return true;
- }
- else if (serverVersion.StartsWith("07.00.", StringComparison.Ordinal)) {
- return true;
- }
- else if (serverVersion.StartsWith("08.00.", StringComparison.Ordinal)) {
- return true;
- }
- return false;
- }
- finally {
- conManager.ReleaseConnection(this);
- }
- }
- }
- /// <summary>
- /// Return true if this is a SQL 2005 server. This may be a round trip to the server.
- /// </summary>
- private bool IsServer2005 {
- get {
- DbConnection con = conManager.UseConnection(this);
- try {
- string serverVersion = con.ServerVersion;
- if (serverVersion.StartsWith("09.00.", StringComparison.Ordinal)) {
- return true;
- }
- return false;
- }
- finally {
- conManager.ReleaseConnection(this);
- }
- }
- }
- DbConnection IProvider.Connection {
- get {
- this.CheckDispose();
- this.CheckInitialized();
- return this.conManager.Connection;
- }
- }
- TextWriter IProvider.Log {
- get {
- this.CheckDispose();
- this.CheckInitialized();
- return this.log;
- }
- set {
- this.CheckDispose();
- this.CheckInitialized();
- this.log = value;
- }
- }
- DbTransaction IProvider.Transaction {
- get {
- this.CheckDispose();
- this.CheckInitialized();
- return this.conManager.Transaction;
- }
- set {
- this.CheckDispose();
- this.CheckInitialized();
- this.conManager.Transaction = value;
- }
- }
- int IProvider.CommandTimeout {
- get {
- this.CheckDispose();
- return this.commandTimeout;
- }
- set {
- this.CheckDispose();
- this.commandTimeout = value;
- }
- }
- /// <summary>
- /// Expose a test hook which controls which SQL optimizations are executed.
- /// </summary>
- internal OptimizationFlags OptimizationFlags {
- get {
- CheckDispose();
- return this.optimizationFlags;
- }
- set {
- CheckDispose();
- this.optimizationFlags = value;
- }
- }
- /// <summary>
- /// Validate queries as they are generated.
- /// </summary>
- internal bool CheckQueries {
- get {
- CheckDispose();
- return checkQueries;
- }
- set {
- CheckDispose();
- checkQueries = value;
- }
- }
- internal bool EnableCacheLookup {
- get {
- CheckDispose();
- return this.enableCacheLookup;
- }
- set {
- CheckDispose();
- this.enableCacheLookup = value;
- }
- }
- internal int QueryCount {
- get {
- CheckDispose();
- return this.queryCount;
- }
- }
- internal int MaxUsers {
- get {
- CheckDispose();
- return this.conManager.MaxUsers;
- }
- }
- IDataServices IReaderProvider.Services {
- get { return this.services; }
- }
- IConnectionManager IReaderProvider.ConnectionManager {
- get { return this.conManager; }
- }
- public SqlProvider() {
- this.mode = ProviderMode.NotYetDecided;
- }
- internal SqlProvider(ProviderMode mode) {
- this.mode = mode;
- }
- private void CheckInitialized() {
- if (this.services == null) {
- throw Error.ContextNotInitialized();
- }
- }
- private void CheckNotDeleted() {
- if (this.deleted) {
- throw Error.DatabaseDeleteThroughContext();
- }
- }
- [ResourceExposure(ResourceScope.Machine)] // connection parameter may refer to filenames.
- void IProvider.Initialize(IDataServices dataServices, object connection) {
- if (dataServices == null) {
- throw Error.ArgumentNull("dataServices");
- }
- this.services = dataServices;
- DbConnection con;
- DbTransaction tx = null;
- string fileOrServerOrConnectionString = connection as string;
- if (fileOrServerOrConnectionString != null) {
- string connectionString = this.GetConnectionString(fileOrServerOrConnectionString);
- this.dbName = this.GetDatabaseName(connectionString);
- if (this.dbName.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) {
- this.mode = ProviderMode.SqlCE;
- }
- if (this.mode == ProviderMode.SqlCE) {
- DbProviderFactory factory = SqlProvider.GetProvider(SqlCeProviderInvariantName);
- if (factory == null) {
- throw Error.ProviderNotInstalled(this.dbName, SqlCeProviderInvariantName);
- }
- con = factory.CreateConnection();
- }
- else {
- con = new SqlConnection();
- }
- con.ConnectionString = connectionString;
- }
- else {
- // We only support SqlTransaction and SqlCeTransaction
- tx = connection as SqlTransaction;
- if (tx == null) {
- // See if it's a SqlCeTransaction
- if (connection.GetType().FullName == SqlCeTransactionTypeName) {
- tx = connection as DbTransaction;
- }
- }
- if (tx != null) {
- connection = tx.Connection;
- }
- con = connection as DbConnection;
- if (con == null) {
- throw Error.InvalidConnectionArgument("connection");
- }
- if (con.GetType().FullName == SqlCeConnectionTypeName) {
- this.mode = ProviderMode.SqlCE;
- }
- this.dbName = this.GetDatabaseName(con.ConnectionString);
- }
-
- // initialize to the default command timeout
- using (DbCommand c = con.CreateCommand()) {
- this.commandTimeout = c.CommandTimeout;
- }
- int maxUsersPerConnection = 1;
- if (con.ConnectionString.IndexOf("MultipleActiveResultSets", StringComparison.OrdinalIgnoreCase) >= 0) {
- DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
- builder.ConnectionString = con.ConnectionString;
- if (string.Compare((string)builder["MultipleActiveResultSets"], "true", StringComparison.OrdinalIgnoreCase) == 0) {
- maxUsersPerConnection = 10;
- }
- }
- // If fileOrServerOrConnectionString != null, that means we just created the connection instance and we have to tell
- // the SqlConnectionManager that it should dispose the connection when the context is disposed. Otherwise the user owns
- // the connection and should dispose of it themselves.
- this.conManager = new SqlConnectionManager(this, con, maxUsersPerConnection, fileOrServerOrConnectionString != null /*disposeConnection*/);
- if (tx != null) {
- this.conManager.Transaction = tx;
- }
- #if DEBUG
- SqlNode.Formatter = new SqlFormatter();
- #endif
- #if ILGEN
- Type readerType;
- if (this.mode == ProviderMode.SqlCE) {
- readerType = con.GetType().Module.GetType(SqlCeDataReaderTypeName);
- }
- else if (con is SqlConnection) {
- readerType = typeof(SqlDataReader);
- }
- else {
- readerType = typeof(DbDataReader);
- }
- this.readerCompiler = new ObjectReaderCompiler(readerType, this.services);
- #else
- this.readerCompiler = new ObjectReaderBuilder(this, this.services);
- #endif
- }
- private static DbProviderFactory GetProvider(string providerName) {
- bool hasProvider =
- DbProviderFactories.GetFactoryClasses().Rows.OfType<DataRow>()
- .Select(r => (string)r["InvariantName"])
- .Contains(providerName, StringComparer.OrdinalIgnoreCase);
- if (hasProvider) {
- return DbProviderFactories.GetFactory(providerName);
- }
- return null;
- }
- #region Dispose\Finalize
- public void Dispose() {
- this.disposed = true;
- Dispose(true);
- // Technically, calling GC.SuppressFinalize is not required because the class does not
- // have a finalizer, but it does no harm, protects against the case where a finalizer is added
- // in the future, and prevents an FxCop warning.
- GC.SuppressFinalize(this);
- }
- // Not implementing finalizer here because there are no unmanaged resources
- // to release. See http://msdnwiki.microsoft.com/en-us/mtpswiki/12afb1ea-3a17-4a3f-a1f0-fcdb853e2359.aspx
- // The bulk of the clean-up code is implemented in Dispose(bool)
- protected virtual void Dispose(bool disposing) {
- // Implemented but empty so that derived contexts can implement
- // a finalizer that potentially cleans up unmanaged resources.
- if (disposing) {
- this.services = null;
- if (this.conManager != null) {
- this.conManager.DisposeConnection();
- }
- this.conManager = null;
- this.typeProvider = null;
- this.sqlFactory = null;
- this.translator = null;
- this.readerCompiler = null;
- this.log = null;
- }
- }
- internal void CheckDispose() {
- if (this.disposed) {
- throw Error.ProviderCannotBeUsedAfterDispose();
- }
- }
- #endregion
- private string GetConnectionString(string fileOrServerOrConnectionString) {
- if (fileOrServerOrConnectionString.IndexOf('=') >= 0) {
- return fileOrServerOrConnectionString;
- }
- else {
- DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
- if (fileOrServerOrConnectionString.EndsWith(".mdf", StringComparison.OrdinalIgnoreCase)) {
- // if just a database file is specified, default to local SqlExpress instance
- builder.Add("AttachDBFileName", fileOrServerOrConnectionString);
- builder.Add("Server", "localhost\\sqlexpress");
- builder.Add("Integrated Security", "SSPI");
- builder.Add("User Instance", "true");
- builder.Add("MultipleActiveResultSets", "true");
- }
- else if (fileOrServerOrConnectionString.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) {
- // A SqlCE database file has been specified
- builder.Add("Data Source", fileOrServerOrConnectionString);
- }
- else {
- builder.Add("Server", fileOrServerOrConnectionString);
- builder.Add("Database", this.services.Model.DatabaseName);
- builder.Add("Integrated Security", "SSPI");
- }
- return builder.ToString();
- }
- }
- private string GetDatabaseName(string constr) {
- DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
- builder.ConnectionString = constr;
- if (builder.ContainsKey("Initial Catalog")) {
- return (string)builder["Initial Catalog"];
- }
- else if (builder.ContainsKey("Database")) {
- return (string)builder["Database"];
- }
- else if (builder.ContainsKey("AttachDBFileName")) {
- return (string)builder["AttachDBFileName"];
- }
- else if (builder.ContainsKey("Data Source")
- && ((string)builder["Data Source"]).EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) {
- return (string)builder["Data Source"];
- }
- else {
- return this.services.Model.DatabaseName;
- }
- }
- [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")]
- [ResourceExposure(ResourceScope.None)] // Exposure is via other methods that set dbName.
- [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] // File.Exists method call.
- void IProvider.CreateDatabase() {
- this.CheckDispose();
- this.CheckInitialized();
- // Don't need to call CheckNotDeleted() here since we allow CreateDatabase after DeleteDatabase
- // Don't need to call InitializeProviderMode() here since we don't need to know the provider to do this.
- string catalog = null;
- string filename = null;
- DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
- builder.ConnectionString = this.conManager.Connection.ConnectionString;
- if (this.conManager.Connection.State == ConnectionState.Closed) {
- if (this.mode == ProviderMode.SqlCE) {
- if (!File.Exists(this.dbName)) {
- Type engineType = this.conManager.Connection.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine");
- object engine = Activator.CreateInstance(engineType, new object[] { builder.ToString() });
- try {
- engineType.InvokeMember("CreateDatabase", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, engine, new object[] { }, CultureInfo.InvariantCulture);
- }
- catch (TargetInvocationException tie) {
- throw tie.InnerException;
- }
- finally {
- IDisposable disp = engine as IDisposable;
- if (disp != null) {
- disp.Dispose();
- }
- }
- }
- else {
- throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName);
- }
- }
- else {
- // get connection string w/o reference to new catalog
- object val;
- if (builder.TryGetValue("Initial Catalog", out val)) {
- catalog = val.ToString();
- builder.Remove("Initial Catalog");
- }
- if (builder.TryGetValue("Database", out val)) {
- catalog = val.ToString();
- builder.Remove("Database");
- }
- if (builder.TryGetValue("AttachDBFileName", out val)) {
- filename = val.ToString();
- builder.Remove("AttachDBFileName");
- }
- }
- this.conManager.Connection.ConnectionString = builder.ToString();
- }
- else {
- if (this.mode == ProviderMode.SqlCE) {
- if (File.Exists(this.dbName)) {
- throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName);
- }
- }
- object val;
- if (builder.TryGetValue("Initial Catalog", out val)) {
- catalog = val.ToString();
- }
- if (builder.TryGetValue("Database", out val)) {
- catalog = val.ToString();
- }
- if (builder.TryGetValue("AttachDBFileName", out val)) {
- filename = val.ToString();
- }
- }
- if (String.IsNullOrEmpty(catalog)) {
- if (!String.IsNullOrEmpty(filename)) {
- catalog = Path.GetFullPath(filename);
- }
- else if (!String.IsNullOrEmpty(this.dbName)) {
- catalog = this.dbName;
- }
- else {
- throw Error.CouldNotDetermineCatalogName();
- }
- }
- this.conManager.UseConnection(this);
- this.conManager.AutoClose = false;
- try {
- if (this.services.Model.GetTables().FirstOrDefault() == null) {
- // we have no tables to create
- throw Error.CreateDatabaseFailedBecauseOfContextWithNoTables(this.services.Model.DatabaseName);
- }
- this.deleted = false;
- // create database
- if (this.mode == ProviderMode.SqlCE) {
- // create tables
- foreach (MetaTable table in this.services.Model.GetTables()) {
- string command = SqlBuilder.GetCreateTableCommand(table);
- if (!String.IsNullOrEmpty(command)) {
- this.ExecuteCommand(command);
- }
- }
- // create all foreign keys after all tables are defined
- foreach (MetaTable table in this.services.Model.GetTables()) {
- foreach (string command in SqlBuilder.GetCreateForeignKeyCommands(table)) {
- if (!String.IsNullOrEmpty(command)) {
- this.ExecuteCommand(command);
- }
- }
- }
- }
- else {
- string createdb = SqlBuilder.GetCreateDatabaseCommand(catalog, filename, Path.ChangeExtension(filename, ".ldf"));
- this.ExecuteCommand(createdb);
- this.conManager.Connection.ChangeDatabase(catalog);
- // create the schemas that our tables will need
- // cannot be batched together with the rest of the CREATE TABLES
- if (this.mode == ProviderMode.Sql2005 || this.mode == ProviderMode.Sql2008) {
- HashSet<string> schemaCommands = new HashSet<string>();
- foreach (MetaTable table in this.services.Model.GetTables()) {
- string schemaCommand = SqlBuilder.GetCreateSchemaForTableCommand(table);
- if (!string.IsNullOrEmpty(schemaCommand)) {
- schemaCommands.Add(schemaCommand);
- }
- }
- foreach (string schemaCommand in schemaCommands) {
- this.ExecuteCommand(schemaCommand);
- }
- }
- StringBuilder sb = new StringBuilder();
- // create tables
- foreach (MetaTable table in this.services.Model.GetTables()) {
- string createTable = SqlBuilder.GetCreateTableCommand(table);
- if (!string.IsNullOrEmpty(createTable)) {
- sb.AppendLine(createTable);
- }
- }
- // create all foreign keys after all tables are defined
- foreach (MetaTable table in this.services.Model.GetTables()) {
- foreach (string createFK in SqlBuilder.GetCreateForeignKeyCommands(table)) {
- if (!string.IsNullOrEmpty(createFK)) {
- sb.AppendLine(createFK);
- }
- }
- }
- if (sb.Length > 0) {
- // must be on when creating indexes on computed columns
- sb.Insert(0, "SET ARITHABORT ON" + Environment.NewLine);
- this.ExecuteCommand(sb.ToString());
- }
- }
- }
- finally {
- this.conManager.ReleaseConnection(this);
- if (this.conManager.Connection is SqlConnection) {
- SqlConnection.ClearAllPools();
- }
- }
- }
- [ResourceExposure(ResourceScope.None)] // Exposure is via other methods that set dbName.
- [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] // File.Delete method call.
- void IProvider.DeleteDatabase() {
- this.CheckDispose();
- this.CheckInitialized();
- // Don't need to call InitializeProviderMode() here since we don't need to know the provider to do this.
- if (this.deleted) {
- // 2nd delete is no-op.
- return;
- }
- if (this.mode == ProviderMode.SqlCE) {
- ((IProvider)this).ClearConnection();
- System.Diagnostics.Debug.Assert(this.conManager.Connection.State == ConnectionState.Closed);
- File.Delete(this.dbName);
- this.deleted = true;
- }
- else {
- string holdConnStr = conManager.Connection.ConnectionString;
- DbConnection con = this.conManager.UseConnection(this);
- try {
- con.ChangeDatabase("master");
- if (con is SqlConnection) {
- SqlConnection.ClearAllPools();
- }
- if (this.log != null) {
- this.log.WriteLine(Strings.LogAttemptingToDeleteDatabase(this.dbName));
- }
- this.ExecuteCommand(SqlBuilder.GetDropDatabaseCommand(this.dbName));
- this.deleted = true;
- }
- finally {
- this.conManager.ReleaseConnection(this);
- if (conManager.Connection.State == ConnectionState.Closed &&
- string.Compare(conManager.Connection.ConnectionString, holdConnStr, StringComparison.Ordinal) != 0) {
- // Credential information may have been stripped from the connection
- // string as a result of opening the connection. Restore the full
- // connection string.
- conManager.Connection.ConnectionString = holdConnStr;
- }
- }
- }
- }
- [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification="Microsoft: Code needs to return false regarless of exception.")]
- [ResourceExposure(ResourceScope.None)] // Exposure is via other methods that set dbName.
- [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] // File.Exists method call.
- bool IProvider.DatabaseExists() {
- this.CheckDispose();
- this.CheckInitialized();
- if (this.deleted) {
- return false;
- }
- // Don't need to call InitializeProviderMode() here since we don't need to know the provider to do this.
- bool exists = false;
- if (this.mode == ProviderMode.SqlCE) {
- exists = File.Exists(this.dbName);
- }
- else {
- string holdConnStr = conManager.Connection.ConnectionString;
- try {
- // If no database name is explicitly specified on the connection,
- // UseConnection will connect to 'Master', which is why after connecting
- // we call ChangeDatabase to verify that the database actually exists.
- this.conManager.UseConnection(this);
- this.conManager.Connection.ChangeDatabase(this.dbName);
- this.conManager.ReleaseConnection(this);
- exists = true;
- } catch (Exception) {
- } finally {
- if (conManager.Connection.State == ConnectionState.Closed &&
- string.Compare(conManager.Connection.ConnectionString, holdConnStr, StringComparison.Ordinal) != 0) {
- // Credential information may have been stripped from the connection
- // string as a result of opening the connection. Restore the full
- // connection string.
- conManager.Connection.ConnectionString = holdConnStr;
- }
- }
- }
- return exists;
- }
- void IConnectionUser.CompleteUse() {
- }
- void IProvider.ClearConnection() {
- this.CheckDispose();
- this.CheckInitialized();
- this.conManager.ClearConnection();
- }
- private void ExecuteCommand(string command) {
- if (this.log != null) {
- this.log.WriteLine(command);
- this.log.WriteLine();
- }
- IDbCommand cmd = this.conManager.Connection.CreateCommand();
- cmd.CommandTimeout = this.commandTimeout;
- cmd.Transaction = this.conManager.Transaction;
- cmd.CommandText = command;
- cmd.ExecuteNonQuery();
- }
- ICompiledQuery IProvider.Compile(Expression query) {
- this.CheckDispose();
- this.CheckInitialized();
- if (query == null) {
- throw Error.ArgumentNull("query");
- }
- this.InitializeProviderMode();
- SqlNodeAnnotations annotations = new SqlNodeAnnotations();
- QueryInfo[] qis = this.BuildQuery(query, annotations);
- CheckSqlCompatibility(qis, annotations);
-
- LambdaExpression lambda = query as LambdaExpression;
- if (lambda != null) {
- query = lambda.Body;
- }
- IObjectReaderFactory factory = null;
- ICompiledSubQuery[] subQueries = null;
- QueryInfo qi = qis[qis.Length - 1];
- if (qi.ResultShape == ResultShape.Singleton) {
- subQueries = this.CompileSubQueries(qi.Query);
- factory = this.GetReaderFactory(qi.Query, qi.ResultType);
- }
- else if (qi.ResultShape == ResultShape.Sequence) {
- subQueries = this.CompileSubQueries(qi.Query);
- factory = this.GetReaderFactory(qi.Query, TypeSystem.GetElementType(qi.ResultType));
- }
- return new CompiledQuery(this, query, qis, factory, subQueries);
- }
- private ICompiledSubQuery CompileSubQuery(SqlNode query, Type elementType, ReadOnlyCollection<Me.SqlParameter> parameters) {
- query = SqlDuplicator.Copy(query);
- SqlNodeAnnotations annotations = new SqlNodeAnnotations();
- QueryInfo[] qis = this.BuildQuery(ResultShape.Sequence, TypeSystem.GetSequenceType(elementType), query, parameters, annotations);
- System.Diagnostics.Debug.Assert(qis.Length == 1);
- QueryInfo qi = qis[0];
- ICompiledSubQuery[] subQueries = this.CompileSubQueries(qi.Query);
- IObjectReaderFactory factory = this.GetReaderFactory(qi.Query, elementType);
- CheckSqlCompatibility(qis, annotations);
- return new CompiledSubQuery(qi, factory, parameters, subQueries);
- }
- IExecuteResult IProvider.Execute(Expression query) {
- this.CheckDispose();
- this.CheckInitialized();
- this.CheckNotDeleted();
- if (query == null) {
- throw Error.ArgumentNull("query");
- }
- this.InitializeProviderMode();
- #if PERFORMANCE_BUILD
- PerformanceCounter pcBuildQuery = null, bpcBuildQuery = null, pcExecQuery = null, bpcExecQuery = null,
- pcSession = null, bpcSession = null;
- PerfTimer timerAll = null, timer = null;
- if (this.CollectPerfInfo) {
- string s = System.Environment.GetEnvironmentVariable("EnableDLinqQueryPerf");
- collectQueryPerf = (s != null && s == "On");
- }
- if (collectQueryPerf) {
- pcBuildQuery = new PerformanceCounter("DLinq", "BuildQueryElapsedTime", false);
- bpcBuildQuery = new PerformanceCounter("DLinq", "BuildQueryElapsedTimeBase", false);
- pcExecQuery = new PerformanceCounter("DLinq", "ExecuteQueryElapsedTime", false);
- bpcExecQuery = new PerformanceCounter("DLinq", "ExecuteQueryElapsedTimeBase", false);
- pcSession = new PerformanceCounter("DLinq", "SessionExecuteQueryElapsedTime", false);
- bpcSession = new PerformanceCounter("DLinq", "SessionExecuteQueryElapsedTimeBase", false);
- timerAll = new PerfTimer();
- timer = new PerfTimer();
- timerAll.Start();
- }
- #endif
- query = Funcletizer.Funcletize(query);
- if (this.EnableCacheLookup) {
- IExecuteResult cached = this.GetCachedResult(query);
- if (cached != null) {
- return cached;
- }
- }
- #if PERFORMANCE_BUILD
- if (collectQueryPerf) {
- timer.Start();
- }
- #endif
- SqlNodeAnnotations annotations = new SqlNodeAnnotations();
- QueryInfo[] qis = this.BuildQuery(query, annotations);
- CheckSqlCompatibility(qis, annotations);
- LambdaExpression lambda = query as LambdaExpression;
- if (lambda != null) {
- query = lambda.Body;
- }
- IObjectReaderFactory factory = null;
- ICompiledSubQuery[] subQueries = null;
- QueryInfo qi = qis[qis.Length - 1];
- if (qi.ResultShape == ResultShape.Singleton) {
- subQueries = this.CompileSubQueries(qi.Query);
- factory = this.GetReaderFactory(qi.Query, qi.ResultType);
- }
- else if (qi.ResultShape == ResultShape.Sequence) {
- subQueries = this.CompileSubQueries(qi.Query);
- factory = this.GetReaderFactory(qi.Query, TypeSystem.GetElementType(qi.ResultType));
- }
- #if PERFORMANCE_BUILD
- if (collectQueryPerf) {
- timer.Stop();
- pcBuildQuery.IncrementBy(timer.Duration);
- bpcBuildQuery.Increment();
- }
- #endif
- #if PERFORMANCE_BUILD
- if (collectQueryPerf) {
- timer.Start();
- }
- #endif
- IExecuteResult result = this.ExecuteAll(query, qis, factory, null, subQueries);
- #if PERFORMANCE_BUILD
- if (collectQueryPerf) {
- timer.Stop();
- pcSession.IncrementBy(timer.Duration);
- bpcSession.Increment();
- timerAll.Stop();
- pcExecQuery.IncrementBy(timerAll.Duration);
- bpcExecQuery.Increment();
- }
- #endif
- return result;
- }
- private ICompiledSubQuery[] CompileSubQueries(SqlNode query) {
- return new SubQueryCompiler(this).Compile(query);
- }
- class SubQueryCompiler : SqlVisitor {
- SqlProvider provider;
- List<ICompiledSubQuery> subQueries;
- internal SubQueryCompiler(SqlProvider provider) {
- this.provider = provider;
- }
- internal ICompiledSubQuery[] Compile(SqlNode node) {
- this.subQueries = new List<ICompiledSubQuery>();
- this.Visit(node);
- return this.subQueries.ToArray();
- }
- internal override SqlSelect VisitSelect(SqlSelect select) {
- this.Visit(select.Selection);
- return select;
- }
- internal override SqlExpression VisitSubSelect(SqlSubSelect ss) {
- return ss;
- }
- internal override SqlExpression VisitClientQuery(SqlClientQuery cq) {
- Type clientElementType = cq.Query.NodeType == SqlNodeType.Multiset ? TypeSystem.GetElementType(cq.ClrType) : cq.ClrType;
- ICompiledSubQuery c = this.provider.CompileSubQuery(cq.Query.Select, clientElementType, cq.Parameters.AsReadOnly());
- cq.Ordinal = this.subQueries.Count;
- this.subQueries.Add(c);
- return cq;
- }
- }
- /// <summary>
- /// Look for compatibility annotations for the set of providers we
- /// add annotations for.
- /// </summary>
- private void CheckSqlCompatibility(QueryInfo[] queries, SqlNodeAnnotations annotations) {
- if (this.Mode == ProviderMode.Sql2000 ||
- this.Mode == ProviderMode.SqlCE) {
- for (int i = 0, n = queries.Length; i < n; i++) {
- SqlServerCompatibilityCheck.ThrowIfUnsupported(queries[i].Query, annotations, this.Mode);
- }
- }
- }
- private IExecuteResult ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, object[] userArguments, ICompiledSubQuery[] subQueries) {
- IExecuteResult result = null;
- object lastResult = null;
- for (int i = 0, n = queryInfos.Length; i < n; i++) {
- if (i < n - 1) {
- result = this.Execute(query, queryInfos[i], null, null, userArguments, subQueries, lastResult);
- }
- else {
- result = this.Execute(query, queryInfos[i], factory, null, userArguments, subQueries, lastResult);
- }
- if (queryInfos[i].ResultShape == ResultShape.Return) {
- lastResult = result.ReturnValue;
- }
- }
- return result;
- }
- [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
- private IExecuteResult GetCachedResult(Expression query) {
- object obj = this.services.GetCachedObject(query);
- if (obj != null) {
- switch (this.GetResultShape(query)) {
- case ResultShape.Singleton:
- return new ExecuteResult(null, null, null, obj);
- case ResultShape.Sequence:
- return new ExecuteResult(null, null, null,
- Activator.CreateInstance(
- typeof(SequenceOfOne<>).MakeGenericType(TypeSystem.GetElementType(this.GetResultType(query))),
- BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { obj }, null
- ));
- }
- }
- return null;
- }
- [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification="Unknown reason.")]
- [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
- private IExecuteResult Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, object[] parentArgs, object[] userArgs, ICompiledSubQuery[] subQueries, object lastResult) {
- this.InitializeProviderMode();
- DbConnection con = this.conManager.UseConnection(this);
- try {
- DbCommand cmd = con.CreateCommand();
- cmd.CommandText = queryInfo.CommandText;
- cmd.Transaction = this.conManager.Transaction;
- cmd.CommandTimeout = this.commandTimeout;
- AssignParameters(cmd, queryInfo.Parameters, userArgs, lastResult);
- LogCommand(this.log, cmd);
- this.queryCount += 1;
- switch (queryInfo.ResultShape) {
- default:
- case ResultShape.Return: {
- return new ExecuteResult(cmd, queryInfo.Parameters, null, cmd.ExecuteNonQuery(), true);
- }
- case ResultShape.Singleton: {
- DbDataReader reader = cmd.ExecuteReader();
- IObjectReader objReader = factory.Create(reader, true, this, parentArgs, userArgs, subQueries);
- this.conManager.UseConnection(objReader.Session);
- try {
- IEnumerable sequence = (IEnumerable)Activator.CreateInstance(
- typeof(OneTimeEnumerable<>).MakeGenericType(queryInfo.ResultType),
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
- new object[] { objReader }, null
- );
- object value = null;
- MethodCallExpression mce = query as MethodCallExpression;
- MethodInfo sequenceMethod = null;
- if (mce != null && (
- mce.Method.DeclaringType == typeof(Queryable) ||
- mce.Method.DeclaringType == typeof(Enumerable))
- ) {
- switch (mce.Method.Name) {
- case "First":
- case "FirstOrDefault":
- case "SingleOrDefault":
- sequenceMethod = TypeSystem.FindSequenceMethod(mce.Method.Name, sequence);
- break;
- case "Single":
- default:
- sequenceMethod = TypeSystem.FindSequenceMethod("Single", sequence);
- break;
- }
- }
- else {
- sequenceMethod = TypeSystem.FindSequenceMethod("SingleOrDefault", sequence);
- }
- // When dynamically invoking the sequence method, we want to
- // return the inner exception if the invocation fails
- if (sequenceMethod != null) {
- try {
- value = sequenceMethod.Invoke(null, new object[] { sequence });
- }
- catch (TargetInvocationException tie) {
- if (tie.InnerException != null) {
- throw tie.InnerException;
- }
- throw;
- }
- }
- return new ExecuteResult(cmd, queryInfo.Parameters, objReader.Session, value);
- }
- finally {
- objReader.Dispose();
- }
- }
- case ResultShape.Sequence: {
- DbDataReader reader = cmd.ExecuteReader();
- IObjectReader objReader = factory.Create(reader, true, this, parentArgs, userArgs, subQueries);
- this.conManager.UseConnection(objReader.Session);
- IEnumerable sequence = (IEnumerable)Activator.CreateInstance(
- typeof(OneTimeEnumerable<>).MakeGenericType(TypeSystem.GetElementType(queryInfo.ResultType)),
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
- new object[] { objReader }, null
- );
- if (typeof(IQueryable).IsAssignableFrom(queryInfo.ResultType)) {
- sequence = sequence.AsQueryable();
- }
- ExecuteResult result = new ExecuteResult(cmd, queryInfo.Parameters, objReader.Session);
- MetaFunction function = this.GetFunction(query);
- if (function != null && !function.IsComposable) {
- sequence = (IEnumerable)Activator.CreateInstance(
- typeof(SingleResult<>).MakeGenericType(TypeSystem.GetElementType(queryInfo.ResultType)),
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
- new object[] { sequence, result, this.services.Context }, null
- );
- }
- result.ReturnValue = sequence;
- return result;
- }
- case ResultShape.MultipleResults: {
- DbDataReader reader = cmd.ExecuteReader();
- IObjectReaderSession session = this.readerCompiler.CreateSession(reader, this, parentArgs, userArgs, subQueries);
- this.conManager.UseConnection(session);
- MetaFunction function = this.GetFunction(query);
- ExecuteResult result = new ExecuteResult(cmd, queryInfo.Parameters, session);
- result.ReturnValue = new MultipleResults(this, function, session, result);
- return result;
- }
- }
- }
- finally {
- this.conManager.ReleaseConnection(this);
- }
- }
- private MetaFunction GetFunction(Expression query) {
- LambdaExpression lambda = query as LambdaExpression;
- if (lambda != null) {
- query = lambda.Body;
- }
- MethodCallExpression mc = query as MethodCallExpression;
- if (mc != null && typeof(DataContext).IsAssignableFrom(mc.Method.DeclaringType)) {
- return this.services.Model.GetF…
Large files files are truncated, but you can click here to view the full file