Ejemplo n.º 1
0
        public async Task <IEnumerable <T> > QueryAsync <T>(RequestContext context, DataSourceType sourceType = DataSourceType.Read)
        {
            #region Read Cache
            var cache = CacheManager[context, typeof(IEnumerable <T>)];
            if (cache != null)
            {
                return((IEnumerable <T>)cache);
            }
            #endregion
            IDbConnectionSession session = SessionStore.LocalSession;
            if (session == null)
            {
                session = CreateDbSession(sourceType);
            }
            string sqlStr = SqlBuilder.BuildSql(context);
            try
            {
                var result = await session.Connection.QueryAsync <T>(sqlStr, context.DapperDynamicParams, session.DbTransaction);

                CacheManager[context, typeof(IEnumerable <T>)] = result;
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 2
0
 public Task <DbDataReader> ExecuteReaderAsync(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarpAsync((dbCommand) =>
     {
         return dbCommand.ExecuteReaderAsync();
     }, dbSession, context));
 }
Ejemplo n.º 3
0
        public async Task <T> RunAsync <T>(RequestContext context, DataSourceChoice sourceChoice, Func <String, IDbConnectionSession, Task <T> > runSql)
        {
            IDbConnectionSession session = SmartSqlMapper.SessionStore.LocalSession;

            if (session == null)
            {
                session = SmartSqlMapper.CreateDbSession(sourceChoice);
            }

            string sqlStr = SqlBuilder.BuildSql(context);

            try
            {
                T result = await runSql(sqlStr, session);

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 4
0
        public void RequestExecuted(IDbConnectionSession dbSession, RequestContext context)
        {
            var sessionId = dbSession.Id;

            if (dbSession.Transaction == null)
            {
                FlushOnExecute(context);
            }
            else
            {
                if (_cachedSessionRequest.TryGetValue(sessionId, out SessionRequest sessionRequest))
                {
                    sessionRequest.Requests.Add(context);
                }
                else
                {
                    sessionRequest = new SessionRequest
                    {
                        SessionId = sessionId,
                        Requests  = new List <RequestContext> {
                            context
                        }
                    };
                    _cachedSessionRequest.Add(sessionId, sessionRequest);
                }
            }
        }
Ejemplo n.º 5
0
        public IDataReader ExecuteReader(string sqlStr, object reqParams, DataSourceType sourceType = DataSourceType.Read)
        {
            IDbConnectionSession session = SessionStore.LocalSession;

            if (session == null)
            {
                session = CreateDbSession(sourceType);
            }
            try
            {
                var result = session.Connection.ExecuteReader(sqlStr, reqParams);
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 6
0
        public IEnumerable <T> Query <T>(RequestContext context, DataSourceChoice sourceChoice)
        {
            var cache = CacheManager[context, typeof(IEnumerable <T>)];

            if (cache != null)
            {
                return((IEnumerable <T>)cache);
            }

            IDbConnectionSession session = SessionStore.LocalSession;

            if (session == null)
            {
                session = CreateDbSession(sourceChoice);
            }
            string sqlStr = SqlBuilder.BuildSql(context);

            try
            {
                var result = session.Connection.Query <T>(sqlStr, context.DapperParameters, session.Transaction);
                CacheManager[context, typeof(IEnumerable <T>)] = result;
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 7
0
 public Task <object> ExecuteScalarAsync(IDbConnectionSession dbSession, RequestContext context, CancellationToken cancellationToken)
 {
     return(ExecuteWarpAsync((dbCommand) =>
     {
         return dbCommand.ExecuteScalarAsync(cancellationToken);
     }, dbSession, context));
 }
Ejemplo n.º 8
0
 public object ExecuteScalar(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarp((dbCommand) =>
     {
         return dbCommand.ExecuteScalar();
     }, dbSession, context));
 }
Ejemplo n.º 9
0
        public async Task <T> ExecuteAsync <T>(RequestContext context, DataSourceType dataSourceType, Func <string, IDbConnectionSession, Task <T> > executeSql)
        {
            IDbConnectionSession session = _baraMapper.SessionStore.LocalSession;

            if (session == null)
            {
                session = _baraMapper.CreateDbSession(dataSourceType);
            }
            try
            {
                var strSql = _sqlBuilder.BuildSql(context);
                return(await executeSql(strSql, session));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 10
0
 public int ExecuteNonQuery(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarp((dbCommand) =>
     {
         return dbCommand.ExecuteNonQuery();
     }, dbSession, context));
 }
Ejemplo n.º 11
0
 public IDataReader ExecuteReader(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarp((dbCommand) =>
     {
         return dbCommand.ExecuteReader();
     }, dbSession, context));
 }
Ejemplo n.º 12
0
 public Task <int> ExecuteNonQueryAsync(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarpAsync((dbCommand) =>
     {
         return dbCommand.ExecuteNonQueryAsync();
     }, dbSession, context));
 }
Ejemplo n.º 13
0
 public void Store(IDbConnectionSession session)
 {
     if (_staticSession.Value == null)
     {
         _staticSession.Value = session;
     }
 }
Ejemplo n.º 14
0
        public IEnumerable <dynamic> QueryBySql(String sqlStr, object reqParams, DataSourceType sourceType = DataSourceType.Read)
        {
            IDbConnectionSession session = SessionStore.LocalSession;

            if (session == null)
            {
                session = CreateDbSession(sourceType);
            }
            try
            {
                var result = session.Connection.Query(sqlStr, reqParams, session.DbTransaction);
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (session.LifeCycle == DbSessionLifeCycle.Transient)
                {
                    session.CloseConnection();
                }
            }
        }
Ejemplo n.º 15
0
 public Task <IDataReaderWrapper> ExecuteReaderAsync(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarpAsync <IDataReaderWrapper>(async(dbCommand) =>
     {
         var dataReader = await dbCommand.ExecuteReaderAsync();
         return new DataReaderWrapper(dataReader);
     }, dbSession, context));
 }
Ejemplo n.º 16
0
 public Task <object> ExecuteScalarAsync(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarpAsync((dbCommand) =>
     {
         dbCommand.CommandTimeout = 0;
         return dbCommand.ExecuteScalarAsync();
     }, dbSession, context));
 }
Ejemplo n.º 17
0
 public Task <int> ExecuteNonQueryAsync(IDbConnectionSession dbSession, RequestContext context, CancellationToken cancellationToken)
 {
     return(ExecuteWarpAsync((dbCommand) =>
     {
         dbCommand.CommandTimeout = 0;
         return dbCommand.ExecuteNonQueryAsync(cancellationToken);
     }, dbSession, context));
 }
Ejemplo n.º 18
0
 public void Store(IDbConnectionSession session)
 {
     if (staticSessions.Value == null)
     {
         staticSessions.Value = new Dictionary <String, IDbConnectionSession>();
     }
     staticSessions.Value[sessionName] = session;
 }
Ejemplo n.º 19
0
 public IDataReaderWrapper ExecuteReader(IDbConnectionSession dbSession, RequestContext context)
 {
     return(ExecuteWarp((dbCommand) =>
     {
         var dataReader = dbCommand.ExecuteReader();
         return new DataReaderWrapper(dataReader);
     }, dbSession, context));
 }
Ejemplo n.º 20
0
        public void RequestCommitted(IDbConnectionSession dbSession)
        {
            var sessionId = dbSession.Id;

            if (_cachedSessionRequest.TryGetValue(sessionId, out SessionRequest sessionRequest))
            {
                foreach (var context in sessionRequest.Requests)
                {
                    FlushOnExecute(context);
                }
                _cachedSessionRequest.Remove(sessionId);
            }
        }
Ejemplo n.º 21
0
        public IDataReader ExecuteReader(IDbConnectionSession dbSession, RequestContext context)
        {
            return(ExecuteWarp((dbCommand) =>
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug(dbCommand.CommandText);
                }

                IDataReader reader = dbCommand.ExecuteReader();

                return reader;
            }, dbSession, context));
        }
Ejemplo n.º 22
0
        private T ExecuteWarp <T>(Func <IDbCommand, T> excute, IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = _preparedCommand.Prepare(dbSession, context);

            dbSession.OpenConnection();
            T result = excute(dbCommand);

            OnExecuted?.Invoke(this, new OnExecutedEventArgs
            {
                DbSession      = dbSession,
                RequestContext = context
            });
            return(result);
        }
Ejemplo n.º 23
0
 public void RequestCommitted(IDbConnectionSession dbSession)
 {
 }
Ejemplo n.º 24
0
 public void RequestExecuted(IDbConnectionSession dbSession, RequestContext context)
 {
 }
Ejemplo n.º 25
0
        public IDbCommand Prepare(IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = dbSession.Connection.CreateCommand();

            dbCommand.CommandType = context.CommandType;
            dbCommand.Transaction = dbSession.Transaction;
            switch (dbCommand.CommandType)
            {
            case CommandType.Text:
            {
                string sql = context.RealSql;
                if (_sqlParamsTokens.IsMatch(sql))
                {
                    HashSet <string> parameters = new HashSet <string>();
                    sql = _sqlParamsTokens.Replace(sql, match =>
                        {
                            string paramName    = match.Groups[1].Value;
                            Parameter paramMap  = ParseParameter(context, paramName);
                            string propertyName = paramName;
                            string dbParamName  = regDbParamName.Replace(paramName, "$2_");

                            if (context.RequestParameters == null)
                            {
                                return($"{_smartSqlContext.DbPrefix}{dbParamName}");
                            }

                            object paramVal;
                            if (propertyName.Contains("."))
                            {
                                paramVal = ExpressionEvaluator.GetValue(context.RequestParameters, propertyName);
                            }
                            else
                            {
                                context.RequestParameters.TryGetValue(propertyName, out paramVal);
                            }

                            ITypeHandler typeHandler = paramMap?.Handler;
                            if (typeHandler != null)
                            {
                                AddParameterIfNotExists(dbCommand, dbParamName, paramVal, ref parameters, typeHandler);
                                return($"{_smartSqlContext.DbPrefix}{dbParamName}");
                            }
                            bool isString = paramVal is String;
                            if (paramVal is IEnumerable && !isString)
                            {
                                var enumParams           = paramVal as IEnumerable;
                                StringBuilder inParamSql = new StringBuilder();
                                inParamSql.Append("(");
                                int item_Index = 0;
                                foreach (var itemVal in enumParams)
                                {
                                    string itemParamName = $"{_smartSqlContext.DbPrefix}{dbParamName}_{item_Index}";
                                    inParamSql.AppendFormat("{0},", itemParamName);
                                    AddParameterIfNotExists(dbCommand, itemParamName, itemVal, ref parameters);
                                    item_Index++;
                                }
                                inParamSql.Remove(inParamSql.Length - 1, 1);
                                inParamSql.Append(")");
                                return(inParamSql.ToString());
                            }
                            else
                            {
                                if (new Regex("\\#{" + dbParamName + "}\\s*\\${wildcardEscapeClause}").IsMatch(context.Sql.ToString()))
                                {
                                    paramVal = $"%{paramVal}%";
                                }

                                AddParameterIfNotExists(dbCommand, dbParamName, paramVal, ref parameters);
                                return($"{_smartSqlContext.DbPrefix}{dbParamName}");
                            }
                        });
                }
                dbCommand.CommandText = sql;
                break;
            }

            case CommandType.StoredProcedure:
            {
                if (context.Request is IDataParameterCollection reqParams)
                {
                    foreach (var reqParam in reqParams)
                    {
                        dbCommand.Parameters.Add(reqParam);
                    }
                }
                dbCommand.CommandText = context.SqlId;
                break;
            }
            }
            OnPrepared?.Invoke(this, new OnPreparedEventArgs
            {
                RequestContext = context,
                DbSession      = dbSession,
                DbCommand      = dbCommand
            });
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                StringBuilder dbParameterStr = new StringBuilder();
                foreach (IDbDataParameter dbParameter in dbCommand.Parameters)
                {
                    dbParameterStr.AppendFormat("{0}={1},", dbParameter.ParameterName, dbParameter.Value);
                }
                _logger.LogDebug($"PreparedCommand.Prepare->Statement.Id:[{context.FullSqlId}],Sql:[{dbCommand.CommandText}],Parameters:[{dbParameterStr}]");
            }
            return(dbCommand);
        }
Ejemplo n.º 26
0
        public IDbCommand Prepare(IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = dbSession.Connection.CreateCommand();

            dbCommand.CommandType = context.CommandType;
            dbCommand.Transaction = dbSession.Transaction;
            switch (dbCommand.CommandType)
            {
            case CommandType.Text:
            {
                string sql = context.RealSql;
                if (_sqlParamsTokens.IsMatch(sql))
                {
                    sql = _sqlParamsTokens.Replace(sql, match =>
                        {
                            string paramName = match.Groups[1].Value;
                            var paramMap     = context.Statement?.ParameterMap?.Parameters?.FirstOrDefault(p => p.Name == paramName);
                            var propertyName = paramMap != null ? paramMap.Property : paramName;

                            if (!context.RequestParameters.Contains(propertyName))
                            {
                                if (_logger.IsEnabled(LogLevel.Warning))
                                {
                                    _logger.LogWarning($"PreparedCommand.Prepare:StatementKey:{context.StatementKey}:can not find ParamterName:{propertyName}!");
                                }
                                return(GetParameterName(match.Value));
                            }
                            var dbParameter          = context.RequestParameters.Get(propertyName);
                            ITypeHandler typeHandler = dbParameter.TypeHandler ?? paramMap?.Handler;
                            if (typeHandler != null)
                            {
                                AddDbParameter(dbCommand, dbParameter, typeHandler);
                                return(GetParameterName(match.Value));
                            }
                            var paramVal  = dbParameter.Value;
                            bool isString = paramVal is String;
                            if (paramVal is IEnumerable && !isString)
                            {
                                var enumParams           = paramVal as IEnumerable;
                                StringBuilder inParamSql = new StringBuilder();
                                inParamSql.Append("(");
                                int item_Index = 0;
                                foreach (var itemVal in enumParams)
                                {
                                    string itemParamName = $"{paramName}_{item_Index}";
                                    inParamSql.AppendFormat("{0}{1},", _smartSqlContext.DbPrefix, itemParamName);
                                    AddDbParameter(dbCommand, new DbParameter
                                    {
                                        Name  = itemParamName,
                                        Value = itemVal
                                    }, typeHandler);
                                    item_Index++;
                                }
                                if (_logger.IsEnabled(LogLevel.Warning))
                                {
                                    if (item_Index == 0)
                                    {
                                        _logger.LogWarning($"PreparedCommand.Prepare:StatementKey:{context.StatementKey}:ParamterName:{propertyName} no element For [In] Tag!");
                                    }
                                }
                                if (item_Index > 0)
                                {
                                    inParamSql.Remove(inParamSql.Length - 1, 1);
                                }
                                inParamSql.Append(")");
                                return(inParamSql.ToString());
                            }
                            else
                            {
                                AddDbParameter(dbCommand, dbParameter);
                                return(GetParameterName(match.Value));
                            }
                        });
                }
                dbCommand.CommandText = sql;
                break;
            }

            case CommandType.StoredProcedure:
            {
                AddDbParameterCollection(dbCommand, context.RequestParameters);
                dbCommand.CommandText = context.RealSql;
                break;
            }
            }
            OnPrepared?.Invoke(this, new OnPreparedEventArgs
            {
                RequestContext = context,
                DbSession      = dbSession,
                DbCommand      = dbCommand
            });
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                string dbParameterStr = string.Join(",", dbCommand.Parameters.Cast <IDbDataParameter>().Select(p => $"{p.ParameterName}={p.Value}"));

                string realSql = _sqlParamsTokens.Replace(dbCommand.CommandText, (match) =>
                {
                    string paramName     = match.Groups[1].Value;
                    var paramNameCompare = _smartSqlContext.IgnoreParameterCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
                    var dbParam          = dbCommand.Parameters.Cast <IDbDataParameter>().FirstOrDefault(m => String.Equals(m.ParameterName, paramName, paramNameCompare));
                    if (dbParam == null)
                    {
                        return(match.Value);
                    }
                    if (dbParam.Value == DBNull.Value)
                    {
                        return("NULL");
                    }
                    switch (dbParam.DbType)
                    {
                    case DbType.AnsiString:
                    case DbType.AnsiStringFixedLength:
                    case DbType.DateTime:
                    case DbType.DateTime2:
                    case DbType.DateTimeOffset:
                    case DbType.Guid:
                    case DbType.String:
                    case DbType.StringFixedLength:
                    case DbType.Time:
                    case DbType.Xml:
                        { return($"'{dbParam.Value}'"); }

                    case DbType.Boolean:
                        {
                            return(((bool)dbParam.Value) ? "1" : "0");
                        }
                    }
                    return(dbParam.Value.ToString());
                });
                _logger.LogDebug($"PreparedCommand.Prepare->Statement.Id:[{context.FullSqlId}],Sql:{Environment.NewLine}{dbCommand.CommandText}{Environment.NewLine}Parameters:[{dbParameterStr}]{Environment.NewLine}Sql with parameter value: {Environment.NewLine}{realSql}");
            }
            return(dbCommand);
        }
Ejemplo n.º 27
0
        public IDbCommand Prepare(IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = dbSession.Connection.CreateCommand();

            dbCommand.CommandType = context.CommandType;
            dbCommand.Transaction = dbSession.Transaction;
            switch (dbCommand.CommandType)
            {
            case CommandType.Text:
            {
                string sql = context.RealSql;
                if (_sqlParamsTokens.IsMatch(sql))
                {
                    sql = _sqlParamsTokens.Replace(sql, match =>
                        {
                            string paramName = match.Groups[1].Value;
                            var paramMap     = context.Statement?.ParameterMap?.Parameters?.FirstOrDefault(p => p.Name == paramName);
                            var propertyName = paramMap != null ? paramMap.Property : paramName;

                            if (context.RequestParameters == null
                                ||
                                !context.RequestParameters.TryGetValue(propertyName, out object paramVal))
                            {
                                return(match.Value);
                            }

                            ITypeHandler typeHandler = paramMap?.Handler;
                            if (typeHandler != null)
                            {
                                AddParameterIfNotExists(context, dbCommand, paramName, paramVal, typeHandler);
                                return(match.Value);
                            }
                            bool isString = paramVal is String;
                            if (paramVal is IEnumerable && !isString)
                            {
                                var enumParams           = paramVal as IEnumerable;
                                StringBuilder inParamSql = new StringBuilder();
                                inParamSql.Append("(");
                                int item_Index = 0;
                                foreach (var itemVal in enumParams)
                                {
                                    string itemParamName = $"{_smartSqlContext.DbPrefix}{paramName}_{item_Index}";
                                    inParamSql.AppendFormat("{0},", itemParamName);
                                    AddParameterIfNotExists(context, dbCommand, itemParamName, itemVal);
                                    item_Index++;
                                }
                                inParamSql.Remove(inParamSql.Length - 1, 1);
                                inParamSql.Append(")");
                                return(inParamSql.ToString());
                            }
                            else
                            {
                                AddParameterIfNotExists(context, dbCommand, paramName, paramVal);
                                return(match.Value);
                            }
                        });
                }
                dbCommand.CommandText = sql;
                break;
            }

            case CommandType.StoredProcedure:
            {
                if (context.Request is IDataParameterCollection reqParams)
                {
                    foreach (var reqParam in reqParams)
                    {
                        dbCommand.Parameters.Add(reqParam);
                    }
                }
                dbCommand.CommandText = context.SqlId;
                break;
            }
            }
            OnPrepared?.Invoke(this, new OnPreparedEventArgs
            {
                RequestContext = context,
                DbSession      = dbSession,
                DbCommand      = dbCommand
            });
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                StringBuilder dbParameterStr = new StringBuilder();
                foreach (IDbDataParameter dbParameter in dbCommand.Parameters)
                {
                    dbParameterStr.AppendFormat("{0}={1},", dbParameter.ParameterName, dbParameter.Value);
                }
                _logger.LogDebug($"PreparedCommand.Prepare->Statement.Id:[{context.FullSqlId}],Sql:[{dbCommand.CommandText}],Parameters:[{dbParameterStr}]");
            }
            return(dbCommand);
        }
Ejemplo n.º 28
0
        public IDbCommand Prepare(IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = dbSession.Connection.CreateCommand();

            dbCommand.CommandType = context.CommandType;
            dbCommand.Transaction = dbSession.Transaction;
            switch (dbCommand.CommandType)
            {
            case CommandType.Text:
            {
                string sql = SqlParamAnalyzer.Replace(context.RealSql, (paramName, nameWithPrefix) =>
                    {
                        var paramMap     = context.GetParameterMap(paramName);
                        var propertyName = paramMap != null ? paramMap.Property : paramName;
                        var dbParameter  = context.RequestParameters.Get(propertyName);
                        if (dbParameter == null)
                        {
                            if (_logger.IsEnabled(LogLevel.Warning))
                            {
                                _logger.LogWarning($"PreparedCommand.Prepare:StatementKey:{context.StatementKey}:can not find ParamterName:{propertyName}!");
                            }
                            return(GetParameterName(nameWithPrefix));
                        }

                        ITypeHandler typeHandler = dbParameter.TypeHandler ?? paramMap?.Handler;
                        AddDbParameter(dbCommand, dbParameter, typeHandler);
                        return(GetParameterName(nameWithPrefix));
                    });
                dbCommand.CommandText = sql;
                break;
            }

            case CommandType.StoredProcedure:
            {
                AddDbParameterCollection(dbCommand, context.RequestParameters);
                dbCommand.CommandText = context.RealSql;
                break;
            }
            }
            OnPrepared?.Invoke(this, new OnPreparedEventArgs
            {
                RequestContext = context,
                DbSession      = dbSession,
                DbCommand      = dbCommand
            });
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                string dbParameterStr = string.Join(",", dbCommand.Parameters.Cast <IDbDataParameter>().Select(p => $"{p.ParameterName}={p.Value}"));

                string realSql = SqlParamAnalyzer.Replace(dbCommand.CommandText, (paramName, nameWithPrefix) =>
                {
                    var paramNameCompare = _smartSqlContext.IgnoreParameterCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
                    var dbParam          = dbCommand.Parameters.Cast <IDbDataParameter>().FirstOrDefault(m => String.Equals(m.ParameterName, paramName, paramNameCompare));
                    if (dbParam == null)
                    {
                        return(nameWithPrefix);
                    }
                    if (dbParam.Value == DBNull.Value)
                    {
                        return("NULL");
                    }
                    switch (dbParam.DbType)
                    {
                    case DbType.AnsiString:
                    case DbType.AnsiStringFixedLength:
                    case DbType.DateTime:
                    case DbType.DateTime2:
                    case DbType.DateTimeOffset:
                    case DbType.Guid:
                    case DbType.String:
                    case DbType.StringFixedLength:
                    case DbType.Time:
                    case DbType.Xml:
                        { return($"'{dbParam.Value}'"); }

                    case DbType.Boolean:
                        {
                            return(((bool)dbParam.Value) ? "1" : "0");
                        }
                    }
                    return(dbParam.Value.ToString());
                });
                _logger.LogDebug($"PreparedCommand.Prepare->Statement.Id:[{context.FullSqlId}],Sql:{Environment.NewLine}{dbCommand.CommandText}{Environment.NewLine}Parameters:[{dbParameterStr}]{Environment.NewLine}Sql with parameter value: {Environment.NewLine}{realSql}");
            }
            return(dbCommand);
        }
Ejemplo n.º 29
0
        public IDbCommand Prepare(IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = dbSession.Connection.CreateCommand();

            dbCommand.CommandType = context.CommandType;
            dbCommand.Transaction = dbSession.Transaction;
            switch (dbCommand.CommandType)
            {
            case CommandType.Text:
            {
                string sql = context.RealSql;
                if (_sqlParamsTokens.IsMatch(sql))
                {
                    sql = _sqlParamsTokens.Replace(sql, match =>
                        {
                            string paramName = match.Groups[1].Value;
                            var paramMap     = context.Statement?.ParameterMap?.Parameters?.FirstOrDefault(p => p.Name == paramName);
                            var propertyName = paramMap != null ? paramMap.Property : paramName;

                            if (!context.RequestParameters.Contains(propertyName))
                            {
                                if (_logger.IsEnabled(LogLevel.Warning))
                                {
                                    _logger.LogWarning($"PreparedCommand.Prepare:StatementKey:{context.StatementKey}:can not find ParamterName:{propertyName}!");
                                }
                                return(match.Value);
                            }
                            var dbParameter          = context.RequestParameters.Get(propertyName);
                            ITypeHandler typeHandler = paramMap?.Handler;
                            if (typeHandler != null)
                            {
                                AddDbParameter(dbCommand, dbParameter, typeHandler);
                                return(match.Value);
                            }
                            var paramVal  = dbParameter.Value;
                            bool isString = paramVal is String;
                            if (paramVal is IEnumerable && !isString)
                            {
                                var enumParams           = paramVal as IEnumerable;
                                StringBuilder inParamSql = new StringBuilder();
                                inParamSql.Append("(");
                                int item_Index = 0;
                                foreach (var itemVal in enumParams)
                                {
                                    string itemParamName = $"{_smartSqlContext.DbPrefix}{paramName}_{item_Index}";
                                    inParamSql.AppendFormat("{0},", itemParamName);
                                    AddDbParameter(dbCommand, new DbParameter
                                    {
                                        Name  = itemParamName,
                                        Value = itemVal
                                    }, typeHandler);
                                    item_Index++;
                                }
                                inParamSql.Remove(inParamSql.Length - 1, 1);
                                inParamSql.Append(")");
                                return(inParamSql.ToString());
                            }
                            else
                            {
                                AddDbParameter(dbCommand, dbParameter);
                                return(match.Value);
                            }
                        });
                }
                dbCommand.CommandText = sql;
                break;
            }

            case CommandType.StoredProcedure:
            {
                AddDbParameterCollection(dbCommand, context.RequestParameters);
                dbCommand.CommandText = context.RealSql;
                break;
            }
            }
            OnPrepared?.Invoke(this, new OnPreparedEventArgs
            {
                RequestContext = context,
                DbSession      = dbSession,
                DbCommand      = dbCommand
            });
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                string dbParameterStr = string.Join(",", dbCommand.Parameters.Cast <IDbDataParameter>().Select(p => $"{p.ParameterName}={p.Value}"));
                _logger.LogDebug($"PreparedCommand.Prepare->Statement.Id:[{context.FullSqlId}],Sql:[{dbCommand.CommandText}],Parameters:[{dbParameterStr}]");
            }
            return(dbCommand);
        }
Ejemplo n.º 30
0
        private async Task <T> ExecuteWarpAsync <T>(Func <DbCommand, Task <T> > excute, IDbConnectionSession dbSession, RequestContext context)
        {
            var dbCommand = _preparedCommand.Prepare(dbSession, context);
            await dbSession.OpenConnectionAsync();

            var dbCommandAsync = dbCommand as DbCommand;
            T   result         = await excute(dbCommandAsync);

            OnExecuted?.Invoke(this, new OnExecutedEventArgs
            {
                DbSession      = dbSession,
                RequestContext = context
            });
            return(result);
        }