#region Apache Notice /***************************************************************************** * $Revision$ * $LastChangedDate$ * $LastChangedBy$ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Using using System; using System.Data; using System.Reflection; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Utilities; #endregion namespace IBatisNet.Common { /// /// Information about a data provider. /// [Serializable] [XmlRoot("provider", Namespace="http://ibatis.apache.org/providers")] public class DbProvider : IDbProvider { private const string SQLPARAMETER = "?"; #region Fields [NonSerialized] private string _assemblyName = string.Empty; [NonSerialized] private string _connectionClass = string.Empty; [NonSerialized] private string _commandClass = string.Empty; [NonSerialized] private string _parameterDbTypeClass = string.Empty; [NonSerialized] private Type _parameterDbType = null; [NonSerialized] private string _parameterDbTypeProperty = string.Empty; [NonSerialized] private string _dataAdapterClass = string.Empty; [NonSerialized] private string _commandBuilderClass = string.Empty; [NonSerialized] private string _name = string.Empty; [NonSerialized] private string _description = string.Empty; [NonSerialized] private bool _isDefault = false; [NonSerialized] private bool _isEnabled = true; [NonSerialized] private IDbConnection _templateConnection = null; [NonSerialized] private IDbDataAdapter _templateDataAdapter= null; [NonSerialized] private Type _commandBuilderType = null; [NonSerialized] private string _parameterPrefix = string.Empty; [NonSerialized] private bool _useParameterPrefixInSql = true; [NonSerialized] private bool _useParameterPrefixInParameter = true; [NonSerialized] private bool _usePositionalParameters = false; [NonSerialized] private bool _templateConnectionIsICloneable = false; [NonSerialized] private bool _templateDataAdapterIsICloneable = false; [NonSerialized] private bool _setDbParameterSize = true; [NonSerialized] private bool _setDbParameterPrecision = true; [NonSerialized] private bool _setDbParameterScale = true; [NonSerialized] private bool _useDeriveParameters = true; [NonSerialized] private bool _allowMARS = false; // private static readonly ILog _connectionLogger = LogManager.GetLogger("System.Data.IDbConnection"); #endregion #region Properties /// /// The name of the assembly which conatins the definition of the provider. /// /// Examples : "System.Data", "Microsoft.Data.Odbc" [XmlAttribute("assemblyName")] public string AssemblyName { get { return _assemblyName; } set { CheckPropertyString("AssemblyName", value); _assemblyName = value; } } /// /// Tell us if it is the default data source. /// Default false. /// [XmlAttribute("default")] public bool IsDefault { get { return _isDefault; } set {_isDefault = value;} } /// /// Tell us if this provider is enabled. /// Default true. /// [XmlAttribute("enabled")] public bool IsEnabled { get { return _isEnabled; } set {_isEnabled = value;} } /// /// Tell us if this provider allows having multiple open with /// the same . /// /// /// It's a new feature in ADO.NET 2.0 and Sql Server 2005 that allows for multiple forward only read only result sets (MARS). /// Some databases have supported this functionality for a long time : /// Not Supported : DB2, MySql.Data, OLE DB provider [except Sql Server 2005 when using MDAC 9], SQLite, Obdc /// Supported : Sql Server 2005, Npgsql /// [XmlAttribute("allowMARS")] public bool AllowMARS { get { return _allowMARS; } set {_allowMARS = value;} } /// /// The connection class name to use. /// /// /// "System.Data.OleDb.OleDbConnection", /// "System.Data.SqlClient.SqlConnection", /// "Microsoft.Data.Odbc.OdbcConnection" /// [XmlAttribute("connectionClass")] public string DbConnectionClass { get { return _connectionClass; } set { CheckPropertyString("DbConnectionClass", value); _connectionClass = value; } } /// /// Does this ConnectionProvider require the use of a Named Prefix in the SQL /// statement. /// /// /// The OLE DB/ODBC .NET Provider does not support named parameters for /// passing parameters to an SQL Statement or a stored procedure called /// by an IDbCommand when CommandType is set to Text. /// /// For example, SqlClient requires select * from simple where simple_id = @simple_id /// If this is false, like with the OleDb or Obdc provider, then it is assumed that /// the ? can be a placeholder for the parameter in the SQL statement when CommandType /// is set to Text. /// [XmlAttribute("useParameterPrefixInSql")] public bool UseParameterPrefixInSql { get { return _useParameterPrefixInSql; } set { _useParameterPrefixInSql = value;} } /// /// Does this ConnectionProvider require the use of the Named Prefix when trying /// to reference the Parameter in the Command's Parameter collection. /// /// /// This is really only useful when the UseParameterPrefixInSql = true. /// When this is true the code will look like IDbParameter param = cmd.Parameters["@paramName"], /// if this is false the code will be IDbParameter param = cmd.Parameters["paramName"] - ie - Oracle. /// [XmlAttribute("useParameterPrefixInParameter")] public bool UseParameterPrefixInParameter { get { return _useParameterPrefixInParameter; } set { _useParameterPrefixInParameter = value; } } /// /// The OLE DB/OBDC .NET Provider uses positional parameters that are marked with a /// question mark (?) instead of named parameters. /// [XmlAttribute("usePositionalParameters")] public bool UsePositionalParameters { get { return _usePositionalParameters; } set { _usePositionalParameters = value; } } /// /// Used to indicate whether or not the provider /// supports parameter size. /// /// /// See JIRA-49 about SQLite.Net provider not supporting parameter size. /// [XmlAttribute("setDbParameterSize")] public bool SetDbParameterSize { get { return _setDbParameterSize; } set { _setDbParameterSize = value; } } /// /// Used to indicate whether or not the provider /// supports parameter precision. /// /// /// See JIRA-49 about SQLite.Net provider not supporting parameter precision. /// [XmlAttribute("setDbParameterPrecision")] public bool SetDbParameterPrecision { get { return _setDbParameterPrecision; } set { _setDbParameterPrecision = value; } } /// /// Used to indicate whether or not the provider /// supports a parameter scale. /// /// /// See JIRA-49 about SQLite.Net provider not supporting parameter scale. /// [XmlAttribute("setDbParameterScale")] public bool SetDbParameterScale { get { return _setDbParameterScale; } set { _setDbParameterScale = value; } } /// /// Used to indicate whether or not the provider /// supports DeriveParameters method for procedure. /// [XmlAttribute("useDeriveParameters")] public bool UseDeriveParameters { get { return _useDeriveParameters; } set { _useDeriveParameters = value; } } /// /// The command class name to use. /// /// /// "System.Data.SqlClient.SqlCommand" /// [XmlAttribute("commandClass")] public string DbCommandClass { get { return _commandClass; } set { CheckPropertyString("DbCommandClass", value); _commandClass = value; } } /// /// The ParameterDbType class name to use. /// /// /// "System.Data.SqlDbType" /// [XmlAttribute("parameterDbTypeClass")] public string ParameterDbTypeClass { get { return _parameterDbTypeClass; } set { CheckPropertyString("ParameterDbTypeClass", value); _parameterDbTypeClass = value; } } /// /// The ParameterDbTypeProperty class name to use. /// /// /// SqlDbType in SqlParamater.SqlDbType, /// OracleType in OracleParameter.OracleType. /// [XmlAttribute("parameterDbTypeProperty")] public string ParameterDbTypeProperty { get { return _parameterDbTypeProperty; } set { CheckPropertyString("ParameterDbTypeProperty", value); _parameterDbTypeProperty = value; } } /// /// The dataAdapter class name to use. /// /// /// "System.Data.SqlDbType" /// [XmlAttribute("dataAdapterClass")] public string DataAdapterClass { get { return _dataAdapterClass; } set { CheckPropertyString("DataAdapterClass", value); _dataAdapterClass = value; } } /// /// The commandBuilder class name to use. /// /// /// "System.Data.OleDb.OleDbCommandBuilder", /// "System.Data.SqlClient.SqlCommandBuilder", /// "Microsoft.Data.Odbc.OdbcCommandBuilder" /// [XmlAttribute("commandBuilderClass")] public string CommandBuilderClass { get { return _commandBuilderClass; } set { CheckPropertyString("CommandBuilderClass", value); _commandBuilderClass = value; } } /// /// Name used to identify the provider amongst the others. /// [XmlAttribute("name")] public string Name { get { return _name; } set { CheckPropertyString("Name", value); _name = value; } } /// /// Description. /// [XmlAttribute("description")] public string Description { get { return _description; } set { _description = value;} } /// /// Parameter prefix use in store procedure. /// /// @ for Sql Server. [XmlAttribute("parameterPrefix")] public string ParameterPrefix { get { return _parameterPrefix; } set { if ((value == null) || (value.Length < 1)) { _parameterPrefix = ""; } else { _parameterPrefix = value; } } } /// /// Check if this provider is Odbc ? /// [XmlIgnore] public bool IsObdc { get { return (_connectionClass.IndexOf(".Odbc.")>0); } } /// /// Get the CommandBuilder Type for this provider. /// /// An object. public Type CommandBuilderType { get {return _commandBuilderType;} } /// /// Get the ParameterDb Type for this provider. /// /// An object. [XmlIgnore] public Type ParameterDbType { get { return _parameterDbType; } } #endregion #region Constructor (s) / Destructor /// /// Do not use direclty, only for serialization. /// public DbProvider() { } #endregion #region Methods /// /// Init the provider. /// public void Initialize() { Assembly assembly = null; Type type = null; try { assembly = Assembly.Load(_assemblyName); // Build the DataAdapter template type = assembly.GetType(_dataAdapterClass, true); CheckPropertyType("DataAdapterClass", typeof(IDbDataAdapter), type); _templateDataAdapter = (IDbDataAdapter)type.GetConstructor(Type.EmptyTypes).Invoke(null); // Build the connection template type = assembly.GetType(_connectionClass, true); CheckPropertyType("DbConnectionClass", typeof(IDbConnection), type); _templateConnection = (IDbConnection)type.GetConstructor(Type.EmptyTypes).Invoke(null); // Get the CommandBuilder Type _commandBuilderType = assembly.GetType(_commandBuilderClass, true); if (_parameterDbTypeClass.IndexOf(',')>0) { _parameterDbType = TypeUtils.ResolveType(_parameterDbTypeClass); } else { _parameterDbType = assembly.GetType(_parameterDbTypeClass, true); } _templateConnectionIsICloneable = _templateConnection is ICloneable; _templateDataAdapterIsICloneable = _templateDataAdapter is ICloneable; } catch(Exception e) { throw new ConfigurationException( string.Format("Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}", _name, e.Message), e ); } } /// /// Create a connection object for this provider. /// /// An 'IDbConnection' object. public virtual IDbConnection CreateConnection() { // Cannot do that because on // IDbCommand.Connection = cmdConnection // .NET cast the cmdConnection to the real type (as SqlConnection) // and we pass a proxy --> exception invalid cast ! // if (_connectionLogger.IsDebugEnabled) // { // connection = (IDbConnection)IDbConnectionProxy.NewInstance(connection, this); // } if (_templateConnectionIsICloneable) { return (IDbConnection) ((ICloneable)_templateConnection).Clone(); } else { return (IDbConnection) Activator.CreateInstance(_templateConnection.GetType()); } } /// /// Create a command object for this provider. /// /// An 'IDbCommand' object. public virtual IDbCommand CreateCommand() { return _templateConnection.CreateCommand(); } /// /// Create a dataAdapter object for this provider. /// /// An 'IDbDataAdapter' object. public virtual IDbDataAdapter CreateDataAdapter() { if (_templateDataAdapterIsICloneable) { return (IDbDataAdapter) ((ICloneable)_templateDataAdapter).Clone(); } else { return (IDbDataAdapter) Activator.CreateInstance(_templateDataAdapter.GetType()); } } /// /// Create a IDbDataParameter object for this provider. /// /// An 'IDbDataParameter' object. public virtual IDbDataParameter CreateDataParameter() { return _templateConnection.CreateCommand().CreateParameter(); } /// /// Change the parameterName into the correct format IDbCommand.CommandText /// for the ConnectionProvider /// /// The unformatted name of the parameter /// A parameter formatted for an IDbCommand.CommandText public virtual string FormatNameForSql(string parameterName) { return _useParameterPrefixInSql ? (_parameterPrefix + parameterName) : SQLPARAMETER; } /// /// Changes the parameterName into the correct format for an IDbParameter /// for the Driver. /// /// /// For SqlServerConnectionProvider it will change id to @id /// /// The unformatted name of the parameter /// A parameter formatted for an IDbParameter. public virtual string FormatNameForParameter(string parameterName) { return _useParameterPrefixInParameter ? (_parameterPrefix + parameterName) : parameterName; } /// /// Equals implemantation. /// /// The test object. /// A boolean. public override bool Equals(object obj) { if ((obj != null) && (obj is IDbProvider)) { IDbProvider that = (IDbProvider) obj; return ((this._name == that.Name) && (this._assemblyName == that.AssemblyName) && (this._connectionClass == that.DbConnectionClass)); } return false; } /// /// A hashcode for the provider. /// /// An integer. public override int GetHashCode() { return (_name.GetHashCode() ^ _assemblyName.GetHashCode() ^ _connectionClass.GetHashCode()); } /// /// ToString implementation. /// /// A string that describes the provider. public override string ToString() { return "Provider " + _name; } private void CheckPropertyString(string propertyName, string value) { if (value == null || value.Trim().Length == 0) { throw new ArgumentException( "The "+propertyName+" property cannot be " + "set to a null or empty string value.", propertyName); } } private void CheckPropertyType(string propertyName,Type expectedType, Type value) { if (value == null) { throw new ArgumentNullException( propertyName, "The "+propertyName+" property cannot be null."); } if (!expectedType.IsAssignableFrom(value)) { throw new ArgumentException( "The Type passed to the "+propertyName+" property must be an "+expectedType.Name+" implementation."); } } #endregion } }