예제 #1
0
 public RequestScope(IBatisNet.DataMapper.DataExchange.DataExchangeFactory dataExchangeFactory, ISqlMapSession session, IStatement statement)
 {
     this._statement           = statement;
     this._parameterMap        = statement.ParameterMap;
     this._session             = session;
     this._dataExchangeFactory = dataExchangeFactory;
     this._id = GetNextId();
 }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RequestScope"/> class.
        /// </summary>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="session">The session.</param>
        /// <param name="statement">The statement</param>
        public RequestScope(
            DataExchangeFactory dataExchangeFactory,
            ISqlMapSession session,
            IStatement statement
            )
        {
            _errorContext = new ErrorContext();

            _statement = statement;
            _parameterMap = statement.ParameterMap;
            _session = session;
            _dataExchangeFactory = dataExchangeFactory;
            _id = GetNextId();
        }
        /// <summary>
        /// Deserialize a ParameterMap object
        /// </summary>
        /// <param name="node"></param>
        /// <param name="configScope"></param>
        /// <returns></returns>
        public static ParameterMap Deserialize(XmlNode node, ConfigurationScope configScope)
        {
            ParameterMap parameterMap = new ParameterMap(configScope.DataExchangeFactory);
            NameValueCollection prop = NodeUtils.ParseAttributes(node, configScope.Properties);

            configScope.ErrorContext.MoreInfo = "ParameterMap DeSerializer";

            parameterMap.ExtendMap = NodeUtils.GetStringAttribute(prop, "extends");
            parameterMap.Id =  NodeUtils.GetStringAttribute(prop, "id");
            parameterMap.ClassName = NodeUtils.GetStringAttribute(prop, "class");

            configScope.ErrorContext.MoreInfo = "Initialize ParameterMap";
            configScope.NodeContext = node;
            parameterMap.Initialize( configScope.DataSource.DbProvider.UsePositionalParameters, configScope );
            parameterMap.BuildProperties(configScope);
            configScope.ErrorContext.MoreInfo = string.Empty;

            return parameterMap;
        }
예제 #4
0
 internal virtual void Initialize(ConfigurationScope configurationScope)
 {
     if (this._resultMapName.Length > 0)
     {
         string[] strArray = this._resultMapName.Split(new char[] { ',' });
         for (int i = 0; i < strArray.Length; i++)
         {
             string name = configurationScope.ApplyNamespace(strArray[i].Trim());
             this._resultsMap.Add(configurationScope.SqlMapper.GetResultMap(name));
         }
     }
     if (this._parameterMapName.Length > 0)
     {
         this._parameterMap = configurationScope.SqlMapper.GetParameterMap(this._parameterMapName);
     }
     if (this._resultClassName.Length > 0)
     {
         string[] strArray2 = this._resultClassName.Split(new char[] { ',' });
         for (int j = 0; j < strArray2.Length; j++)
         {
             this._resultClass = configurationScope.SqlMapper.TypeHandlerFactory.GetType(strArray2[j].Trim());
             IFactory resultClassFactory = null;
             if ((Type.GetTypeCode(this._resultClass) == TypeCode.Object) && !this._resultClass.IsValueType)
             {
                 resultClassFactory = configurationScope.SqlMapper.ObjectFactory.CreateFactory(this._resultClass, Type.EmptyTypes);
             }
             IDataExchange dataExchangeForClass = configurationScope.DataExchangeFactory.GetDataExchangeForClass(this._resultClass);
             IResultMap    map = new AutoResultMap(this._resultClass, resultClassFactory, dataExchangeForClass);
             this._resultsMap.Add(map);
         }
     }
     if (this._parameterClassName.Length > 0)
     {
         this._parameterClass = configurationScope.SqlMapper.TypeHandlerFactory.GetType(this._parameterClassName);
     }
     if (this._listClassName.Length > 0)
     {
         this._listClass        = configurationScope.SqlMapper.TypeHandlerFactory.GetType(this._listClassName);
         this._listClassFactory = configurationScope.SqlMapper.ObjectFactory.CreateFactory(this._listClass, Type.EmptyTypes);
     }
 }
예제 #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        private string Process(RequestScope request, object parameterObject)
        {
            SqlTagContext ctx = new SqlTagContext();
            IList localChildren = _children;

            ProcessBodyChildren(request, ctx, parameterObject, localChildren);

            // Builds a 'dynamic' ParameterMap
            ParameterMap map = new ParameterMap(request.DataExchangeFactory);
            map.Id = _statement.Id + "-InlineParameterMap";
            map.Initialize(_usePositionalParameters, request);
            map.Class = _statement.ParameterClass;

            // Adds 'dynamic' ParameterProperty
            IList parameters = ctx.GetParameterMappings();
            int count = parameters.Count;
            for(int i=0;i<count;i++)
            {
                map.AddParameterProperty( (ParameterProperty)parameters[i] );
            }
            request.ParameterMap = map;

            string dynSql = ctx.BodyText;

            // Processes $substitutions$ after DynamicSql
            if ( SimpleDynamicSql.IsSimpleDynamicSql(dynSql) )
            {
                dynSql = new SimpleDynamicSql(request, dynSql, _statement).GetSql(parameterObject);
            }
            return dynSql;
        }
예제 #6
0
        /// <summary>
        /// Apply inline paremeterMap
        /// </summary>
        /// <param name="statement"></param>
        /// <param name="sqlStatement"></param>
        private void ApplyInlineParemeterMap( IStatement statement, string sqlStatement)
        {
            string newSql = sqlStatement;

            _configScope.ErrorContext.MoreInfo = "apply inline parameterMap";

            // Check the inline parameter
            if (statement.ParameterMap == null)
            {
                // Build a Parametermap with the inline parameters.
                // if they exist. Then delete inline infos from sqltext.

                SqlText sqlText = _paramParser.ParseInlineParameterMap(_configScope,  statement, newSql );

                if (sqlText.Parameters.Length > 0)
                {
                    ParameterMap map = new ParameterMap(_configScope.DataExchangeFactory);
                    map.Id = statement.Id + "-InLineParameterMap";
                    if (statement.ParameterClass!=null)
                    {
                        map.Class = statement.ParameterClass;
                    }
                    map.Initialize(_configScope.DataSource.DbProvider.UsePositionalParameters,_configScope);
                    if (statement.ParameterClass==null &&
                        sqlText.Parameters.Length==1 && sqlText.Parameters[0].PropertyName=="value")//#value# parameter with no parameterClass attribut
                    {
                        map.DataExchange = _configScope.DataExchangeFactory.GetDataExchangeForClass( typeof(int) );//Get the primitiveDataExchange
                    }
                    statement.ParameterMap = map;

                    int lenght = sqlText.Parameters.Length;
                    for(int index=0;index<lenght;index++)
                    {
                        map.AddParameterProperty( sqlText.Parameters[index] );
                    }
                }
                newSql = sqlText.Text;
            }

            ISql sql = null;

            newSql = newSql.Trim();

            if (SimpleDynamicSql.IsSimpleDynamicSql(newSql))
            {
                sql = new SimpleDynamicSql(_configScope, newSql, statement);
            }
            else
            {
                if (statement is Procedure)
                {
                    sql = new ProcedureSql(_configScope, newSql, statement);
                    // Could not call BuildPreparedStatement for procedure because when NUnit Test
                    // the database is not here (but in theory procedure must be prepared like statement)
                    // It's even better as we can then switch DataSource.
                }
                else if (statement is Statement)
                {
                    sql = new StaticSql(_configScope, statement);
                    ISqlMapSession session = new SqlMapSession(_configScope.SqlMapper);

                    ((StaticSql)sql).BuildPreparedStatement( session, newSql );
                }
            }
            statement.Sql = sql;
        }
예제 #7
0
        /// <summary>
        /// Intialize the internal ISqlMapper instance.
        /// </summary>
        private void Initialize()
        {
            Reset();

            #region Load Global Properties
            if (_configScope.IsCallFromDao == false)
            {
                _configScope.NodeContext = _configScope.SqlMapConfigDocument.SelectSingleNode( ApplyDataMapperNamespacePrefix(XML_DATAMAPPER_CONFIG_ROOT), _configScope.XmlNamespaceManager);

                ParseGlobalProperties();
            }
            #endregion

            #region Load settings

            _configScope.ErrorContext.Activity = "loading global settings";

            XmlNodeList settings = _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_CONFIG_SETTINGS), _configScope.XmlNamespaceManager);

            if (settings!=null)
            {
                foreach (XmlNode setting in settings)
                {
                    if (setting.Attributes[ATR_USE_STATEMENT_NAMESPACES] != null )
                    {
                        string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_USE_STATEMENT_NAMESPACES].Value, _configScope.Properties);
                        _configScope.UseStatementNamespaces =  Convert.ToBoolean( value );
                    }
                    if (setting.Attributes[ATR_CACHE_MODELS_ENABLED] != null )
                    {
                        string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_CACHE_MODELS_ENABLED].Value, _configScope.Properties);
                        _configScope.IsCacheModelsEnabled =  Convert.ToBoolean( value );
                    }
                    if (setting.Attributes[ATR_USE_REFLECTION_OPTIMIZER] != null )
                    {
                        string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_USE_REFLECTION_OPTIMIZER].Value, _configScope.Properties);
                        _configScope.UseReflectionOptimizer =  Convert.ToBoolean( value );
                    }
                    if (setting.Attributes[ATR_VALIDATE_SQLMAP] != null )
                    {
                        string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_VALIDATE_SQLMAP].Value, _configScope.Properties);
                        _configScope.ValidateSqlMap =  Convert.ToBoolean( value );
                    }
                }
            }

            #endregion

            if (_objectFactory == null)
            {
                _objectFactory = new ObjectFactory(_configScope.UseReflectionOptimizer);
            }
            if (_setAccessorFactory == null)
            {
                _setAccessorFactory = new SetAccessorFactory(_configScope.UseReflectionOptimizer);
            }
            if (_getAccessorFactory == null)
            {
                _getAccessorFactory = new GetAccessorFactory(_configScope.UseReflectionOptimizer);
            }
            if (_sqlMapper == null)
            {
                AccessorFactory accessorFactory = new AccessorFactory(_setAccessorFactory, _getAccessorFactory);
                _configScope.SqlMapper = new SqlMapper(_objectFactory, accessorFactory);
            }
            else
            {
                _configScope.SqlMapper = _sqlMapper;
            }

            ParameterMap emptyParameterMap = new ParameterMap(_configScope.DataExchangeFactory);
            emptyParameterMap.Id = ConfigurationScope.EMPTY_PARAMETER_MAP;
            _configScope.SqlMapper.AddParameterMap( emptyParameterMap );

            _configScope.SqlMapper.IsCacheModelsEnabled = _configScope.IsCacheModelsEnabled;

            #region Cache Alias

            TypeAlias cacheAlias = new TypeAlias(typeof(MemoryCacheControler));
            cacheAlias.Name = "MEMORY";
            _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias);
            cacheAlias = new TypeAlias(typeof(LruCacheController));
            cacheAlias.Name = "LRU";
            _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias);
            cacheAlias = new TypeAlias(typeof(FifoCacheController));
            cacheAlias.Name = "FIFO";
            _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias);
            cacheAlias = new TypeAlias(typeof(AnsiStringTypeHandler));
            cacheAlias.Name = "AnsiStringTypeHandler";
            _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias);

            #endregion

            #region Load providers
            if (_configScope.IsCallFromDao == false)
            {
                GetProviders();
            }
            #endregion

            #region Load DataBase
            #region Choose the  provider
            IDbProvider provider = null;
            if ( _configScope.IsCallFromDao==false )
            {
                provider = ParseProvider();
                _configScope.ErrorContext.Reset();
            }
            #endregion

            #region Load the DataSources

            _configScope.ErrorContext.Activity = "loading Database DataSource";
            XmlNode nodeDataSource = _configScope.SqlMapConfigDocument.SelectSingleNode( ApplyDataMapperNamespacePrefix(XML_DATABASE_DATASOURCE), _configScope.XmlNamespaceManager );

            if (nodeDataSource == null)
            {
                if (_configScope.IsCallFromDao == false)
                {
                    throw new ConfigurationException("There's no dataSource tag in SqlMap.config.");
                }
                else  // patch from Luke Yang
                {
                    _configScope.SqlMapper.DataSource = _configScope.DataSource;
                }
            }
            else
            {
                if (_configScope.IsCallFromDao == false)
                {
                    _configScope.ErrorContext.Resource = nodeDataSource.OuterXml.ToString();
                    _configScope.ErrorContext.MoreInfo = "parse DataSource";

                    DataSource dataSource = DataSourceDeSerializer.Deserialize( nodeDataSource );

                    dataSource.DbProvider = provider;
                    dataSource.ConnectionString = NodeUtils.ParsePropertyTokens(dataSource.ConnectionString, _configScope.Properties);

                    _configScope.DataSource = dataSource;
                    _configScope.SqlMapper.DataSource = _configScope.DataSource;
                }
                else
                {
                    _configScope.SqlMapper.DataSource = _configScope.DataSource;
                }
                _configScope.ErrorContext.Reset();
            }
            #endregion
            #endregion

            #region Load Global TypeAlias
            foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_GLOBAL_TYPEALIAS), _configScope.XmlNamespaceManager))
            {
                _configScope.ErrorContext.Activity = "loading global Type alias";
                TypeAliasDeSerializer.Deserialize(xmlNode, _configScope);
            }
            _configScope.ErrorContext.Reset();
            #endregion

            #region Load TypeHandlers
            foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_GLOBAL_TYPEHANDLER), _configScope.XmlNamespaceManager))
            {
                try
                {
                    _configScope.ErrorContext.Activity = "loading typeHandler";
                    TypeHandlerDeSerializer.Deserialize( xmlNode, _configScope );
                }
                catch (Exception e)
                {
                    NameValueCollection prop = NodeUtils.ParseAttributes(xmlNode, _configScope.Properties);

                    throw new ConfigurationException(
                        String.Format("Error registering TypeHandler class \"{0}\" for handling .Net type \"{1}\" and dbType \"{2}\". Cause: {3}",
                        NodeUtils.GetStringAttribute(prop, "callback"),
                        NodeUtils.GetStringAttribute(prop, "type"),
                        NodeUtils.GetStringAttribute(prop, "dbType"),
                        e.Message), e);
                }
            }
            _configScope.ErrorContext.Reset();
            #endregion

            #region Load sqlMap mapping files

            foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_SQLMAP), _configScope.XmlNamespaceManager))
            {
                _configScope.NodeContext = xmlNode;
                ConfigureSqlMap();
            }

            #endregion

            #region Attach CacheModel to statement

            if (_configScope.IsCacheModelsEnabled)
            {
                foreach(DictionaryEntry entry in _configScope.SqlMapper.MappedStatements)
                {
                    _configScope.ErrorContext.Activity = "Set CacheModel to statement";

                    IMappedStatement mappedStatement = (IMappedStatement)entry.Value;
                    if (mappedStatement.Statement.CacheModelName.Length >0)
                    {
                        _configScope.ErrorContext.MoreInfo = "statement : "+mappedStatement.Statement.Id;
                        _configScope.ErrorContext.Resource = "cacheModel : " +mappedStatement.Statement.CacheModelName;
                        mappedStatement.Statement.CacheModel = _configScope.SqlMapper.GetCache(mappedStatement.Statement.CacheModelName);
                    }
                }
            }
            _configScope.ErrorContext.Reset();
            #endregion

            #region Register Trigger Statements for Cache Models
            foreach (DictionaryEntry entry in _configScope.CacheModelFlushOnExecuteStatements)
            {
                string cacheModelId = (string)entry.Key;
                IList statementsToRegister = (IList)entry.Value;

                if (statementsToRegister != null && statementsToRegister.Count > 0)
                {
                    foreach (string statementName in statementsToRegister)
                    {
                        IMappedStatement mappedStatement = _configScope.SqlMapper.MappedStatements[statementName] as IMappedStatement;

                        if (mappedStatement != null)
                        {
                            CacheModel cacheModel = _configScope.SqlMapper.GetCache(cacheModelId);

                            if (_logger.IsDebugEnabled)
                            {
                                _logger.Debug("Registering trigger statement [" + mappedStatement.Id + "] to cache model [" + cacheModel.Id + "]");
                            }

                            cacheModel.RegisterTriggerStatement(mappedStatement);
                        }
                        else
                        {
                            if (_logger.IsWarnEnabled)
                            {
                                _logger.Warn("Unable to register trigger statement [" + statementName + "] to cache model [" + cacheModelId + "]. Statement does not exist.");
                            }
                        }
                    }
                }
            }
            #endregion

            #region Resolve resultMap / Discriminator / PropertyStategy attributes on Result/Argument Property

            foreach(DictionaryEntry entry in _configScope.SqlMapper.ResultMaps)
            {
                _configScope.ErrorContext.Activity = "Resolve 'resultMap' attribute on Result Property";

                ResultMap resultMap = (ResultMap)entry.Value;
                for(int index=0; index< resultMap.Properties.Count; index++)
                {
                    ResultProperty result = resultMap.Properties[index];
                    if(result.NestedResultMapName.Length >0)
                    {
                        result.NestedResultMap = _configScope.SqlMapper.GetResultMap(result.NestedResultMapName);
                    }
                    result.PropertyStrategy = PropertyStrategyFactory.Get(result);
                }
                for(int index=0; index< resultMap.Parameters.Count; index++)
                {
                    ResultProperty result = resultMap.Parameters[index];
                    if(result.NestedResultMapName.Length >0)
                    {
                        result.NestedResultMap = _configScope.SqlMapper.GetResultMap(result.NestedResultMapName);
                    }
                    result.ArgumentStrategy = ArgumentStrategyFactory.Get( (ArgumentProperty)result );
                }
                if (resultMap.Discriminator != null)
                {
                    resultMap.Discriminator.Initialize(_configScope);
                }
            }

            _configScope.ErrorContext.Reset();

            #endregion
        }