public IEnumerable <object> Select(DbConnectionContext dbConnectionContext, SqlCommandDescription sqlCommand, Type entityType)
        {
            DapperParameters parameters = new DapperParameters(sqlCommand);

            return(dbConnectionContext.DbConnection
                   .Query(entityType, sqlCommand.SqlCommand, parameters, transaction: dbConnectionContext.DbTransaction));
        }
Example #2
0
 public ConditionGeneratorContext(ISqlCommandGenerator sqlCommandGenerator, SqlCommandDescription sqlCommandDescription, StringBuilder sqlBuilder, ConditionInfo conditionInfo)
 {
     this.sqlCommandGenerator   = sqlCommandGenerator;
     this.sqlCommandDescription = sqlCommandDescription;
     this.sqlBuilder            = sqlBuilder;
     this.conditionInfo         = conditionInfo;
 }
        public int Execute(DbConnectionContext dbConnectionContext, SqlCommandDescription sqlCommand)
        {
            DapperParameters parameters = new DapperParameters(sqlCommand);

            return(dbConnectionContext.DbConnection
                   .Execute(sqlCommand.SqlCommand, parameters, transaction: dbConnectionContext.DbTransaction));
        }
Example #4
0
 public DapperParameters(SqlCommandDescription description)
 {
     foreach (var p in description.Parameters)
     {
         this[p.Key] = p.Value.Value;
     }
 }
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.Method.Name;

            Type typeofIDao = typeof(INpiDao <>);
            Type entityType = invocation.Method.DeclaringType.GetInterface(typeofIDao.FullName).GetGenericArguments()[0];


            // todo :åƹ其单例化
            ISqlCommandGenerator  g = NpiServicesCollection.GetService <ISqlServerCommandGenerator>();
            SqlCommandDescription d = g.Generate(invocation.Method, invocation.Arguments);

            DebugLogger.Debug(d.ToString());

            DapperParameters dp = new DapperParameters();

            foreach (var p in d.Parameters)
            {
                dp[p.Key] = p.Value.Value;
            }

            object dbReturnedValue = null;
            object handledValue    = null;

            DebugLogger.Debug("å‡†å¤‡ę‰§č”Œ Sql");

            switch (d.Type)
            {
            case SqlCommandTypes.Insert:
            case SqlCommandTypes.Update:
            case SqlCommandTypes.Delete:
            {
                var executor = ServicesCollection.GetService <ISqlCommandExecutor>();
                dbReturnedValue = executor.Execute(d.SqlCommand, dp, dbConnectionContext);
            }
            break;

            case SqlCommandTypes.Select:
            {
                var querier = ServicesCollection.GetService <ISqlCommandQuerier>();
                dbReturnedValue = querier.Select(entityType, d.SqlCommand, dp, dbConnectionContext);
            }
            break;

            default:
                break;
            }
            DebugLogger.Debug("Sql ę‰§č”Œå®Œęƕļ¼Œå¼€å§‹å¤„ē†ē»“ęžœé›†");
            foreach (var handler in dbReturnValueHandlers)
            {
                if (!handler.CanHandle(invocation.Method, entityType))
                {
                    continue;
                }
                handledValue = handler.Handle(invocation.Method, entityType, dbReturnedValue);
            }
            invocation.ReturnValue = handledValue;
            DebugLogger.Debug("ē»“ęžœé›†å¤„ē†å®Œęƕ");
        }
Example #6
0
        public void FillTest()
        {
            Type       type = typeof(IUserDao);
            MethodInfo mi   = type.GetMethod("SelectById");
            DefaultSqlServerCommandGenerator g = new DefaultSqlServerCommandGenerator();
            SqlCommandDescription            d = g.Generate(mi, new object[] { 1 });

            Console.WriteLine(d);
        }
Example #7
0
        protected override SqlCommandDescription GenerateSelect(SqlCommandGenerateContext context)
        {
            SelectInfo selectInfo = (SelectInfo)context.CommandInfo;
            string     tableName  = context.TableName;

            StringBuilder         sqlBuilder = new StringBuilder();
            SqlCommandDescription result     = new SqlCommandDescription();
            var generateContext = new GenerateContext(result, sqlBuilder);

            sqlBuilder.Append("SELECT ");

            if (!selectInfo.Fields.Any())
            {
                sqlBuilder.Append("*");
            }
            else
            {
                sqlBuilder.Append(selectInfo.Fields.Join(",", x => $"[{x}]"));
            }

            sqlBuilder.Append($" FROM [{tableName}]");

            GenerateByConditions(ref generateContext, selectInfo.Conditions);

            if (!selectInfo.Paging)
            {
                GenerateSqlByOrders(ref generateContext, selectInfo.Orders);
                result.SqlCommand = sqlBuilder.ToString();
                return(result);
            }

            if (!selectInfo.Orders.Any())
            {
                throw new NotImplementedException("åˆ†é”µęŸ„čÆ¢åæ…é”»å…·ęœ‰ęŽ’åŗå­—ꮵ");
            }

            StringBuilder shellBuilder = new StringBuilder();

            shellBuilder.Append("SELECT * FROM ( SELECT *,ROW_NUMBER() OVER (");
            generateContext.StringBuilder = shellBuilder;
            GenerateSqlByOrders(ref generateContext, selectInfo.Orders);
            shellBuilder.Append(" ) AS __RN__ FROM ( ");
            shellBuilder.Append(sqlBuilder.ToString());
            shellBuilder.Append($") t ) t WHERE t.__RN__ > @{Constant.PARAMETER_NAME_BEGIN_ROW_NUMBER} AND t.__RN__ <= @{Constant.PARAMETER_NAME_END_ROW_NUMBER}");
            result.AddParameter(new SqlParameterInfo()
            {
                Name = Constant.PARAMETER_NAME_BEGIN_ROW_NUMBER
            });
            result.AddParameter(new SqlParameterInfo()
            {
                Name = Constant.PARAMETER_NAME_END_ROW_NUMBER
            });
            result.SqlCommand = shellBuilder.ToString();
            return(result);
        }
        public override void Intercept(InterfaceInvocationInfo info)
        {
            this.AssertProviderIsValid();
            Type typeOfIDao = typeof(INpiDao <>);

            ISqlCommandGenerator  g = NpiServicesCollection.GetService <ISqlServerCommandGenerator>();
            SqlCommandDescription d = g.Generate(info.Method, info.Arguments);

            this.EventBus.Publish(new SqlCommandDescriptionGeneratedEvent(this, d));

            if (info.Method.ReturnType == typeof(void))
            {
                d.Mode = SqlCommandExecuteModes.Execute;
            }

            switch (d.Mode)
            {
            case SqlCommandExecuteModes.Execute:
                int i = this.Executor.Execute(this.Provider.Provide(), d);
                foreach (var handler in this.ExecuteResultHandlers)
                {
                    if (!handler.CanHandle(info.Method))
                    {
                        continue;
                    }
                    info.ReturnValue = handler.Handle(info.Method, i);
                }
                break;

            case SqlCommandExecuteModes.Query:
            {
                Type returnType = info.Method.ReturnType;
                Type itemType;
                if (TryGetIEnumerableItemType(returnType, out itemType))
                {
                    returnType = itemType;
                }

                IEnumerable <object> list = this.Executor.Select(this.Provider.Provide(), d, returnType);
                foreach (var handler in this.SelectResultHandlers)
                {
                    if (!handler.CanHandle(info.Method, returnType))
                    {
                        continue;
                    }
                    info.ReturnValue = handler.Handle(info.Method, returnType, list);
                }
            }
            break;

            default:
                break;
            }
        }
        private void FillWithBaseType(SqlCommandDescription description, string parameterName, Func <object> valueGetter)
        {
            var parameter = description.Parameters.Values
                            .Where(x => x.Name.ToLower() == parameterName.ToLower())
                            .FirstOrDefault();

            if (parameter == null)
            {
                return;
            }
            parameter.Value = valueGetter();
        }
        private void FillWithObjectType(ISqlCommandGenerator generator, SqlCommandDescription description, Type valueType, Func <object> valueGetter)
        {
            var propertyInfos = valueType.GetProperties();

            foreach (var propertyInfo in propertyInfos)
            {
                string parameterNameOnProperty = GetParameterName(propertyInfo);
                this.Fill(generator, description, parameterNameOnProperty, propertyInfo.PropertyType, () =>
                {
                    return(propertyInfo.GetValue(valueGetter(), null));
                });
            }
        }
Example #11
0
        protected override SqlCommandDescription GenerateCount(SqlCommandGenerateContext context)
        {
            string                tableName       = context.TableName;
            CountInfo             deleteInfo      = (CountInfo)context.CommandInfo;
            StringBuilder         sqlBuilder      = new StringBuilder();
            SqlCommandDescription description     = new SqlCommandDescription();
            GenerateContext       generateContext = new GenerateContext(description, sqlBuilder);

            sqlBuilder.Append($"SELECT COUNT(*) AS [{Constant.RESULT_FIELD_NAME_COUNT}] FROM [{tableName}]");
            GenerateByConditions(ref generateContext, deleteInfo.ConditionInfos);

            description.SqlCommand = sqlBuilder.ToString();
            return(description);
        }
Example #12
0
        protected override SqlCommandDescription GenerateDelete(SqlCommandGenerateContext context)
        {
            string                tableName       = context.TableName;
            DeleteInfo            deleteInfo      = (DeleteInfo)context.CommandInfo;
            StringBuilder         sqlBuilder      = new StringBuilder();
            SqlCommandDescription description     = new SqlCommandDescription();
            GenerateContext       generateContext = new GenerateContext(description, sqlBuilder);

            sqlBuilder.Append($"DELETE FROM [{tableName}]");
            GenerateByConditions(ref generateContext, deleteInfo.ConditionInfos);

            description.SqlCommand = sqlBuilder.ToString();
            return(description);
        }
        public void Lookup(ParameterLookupContext context)
        {
            SqlCommandDescription description = context.Description;
            MethodInfo            methodInfo  = context.MethodInfo;

            object[] values         = context.Values;
            var      parameterInfos = methodInfo.GetParameters();
            int      length         = parameterInfos.Length;

            for (int i = 0; i < length; i++)
            {
                var parameterInfo = parameterInfos[i];
                var value         = values[i];
                this.Fill(context.SqlCommandGenerator, description, GetParameterName(parameterInfo), parameterInfo.ParameterType, () => value);
            }
        }
Example #14
0
        public IEnumerable <object> Select(DbConnectionContext dbConnectionContext, SqlCommandDescription sqlCommand, Type entityType)
        {
            if (sqlCommand.SqlCommand.Contains("COUNT"))
            {
                return new List <object>()
                       {
                           100
                       }
            }
            ;


            return(new List <object>()
            {
                Activator.CreateInstance(entityType), Activator.CreateInstance(entityType)
            });
        }
    }
        private void FillWithCollectionType(ISqlCommandGenerator generator, SqlCommandDescription description, string parameterName, Func <object> valueGetter)
        {
            var parameter = description.Parameters.Values
                            .Where(x => x.Name.ToLower() == parameterName.ToLower())
                            .FirstOrDefault();

            if (parameter == null)
            {
                return;
            }
            IEnumerable   collection           = (IEnumerable)valueGetter();
            Type          itemType             = GetCollectionItemType(collection);
            int           i                    = 0;
            List <string> newParameterNameList = new List <string>();
            bool          isCollectionEmpty    = true;

            foreach (object item in collection)
            {
                isCollectionEmpty = false;
                if (!IsBaseType(itemType))
                {
                    throw new MustBeBaseTypeException(itemType);
                }

                var itemSqlParameter = new SqlParameterInfo()
                {
                    Name  = $"{parameter.Name}{i++}",
                    Value = item
                };
                description.AddParameter(itemSqlParameter);
                newParameterNameList.Add(generator.GenerateParameterName(itemSqlParameter.Name));
            }
            if (isCollectionEmpty)
            {
                throw new EmptyCollectionException(parameterName);
            }
            string newParameterNameSql = newParameterNameList.Join(",", x => x);

            description.SqlCommand = description.SqlCommand.Replace(generator.GenerateParameterName(parameter.Name), $"({newParameterNameSql})");

            description.Parameters.Remove(parameter.Name);
        }
Example #16
0
        protected override SqlCommandDescription GenerateUpdate(SqlCommandGenerateContext context)
        {
            string     tableName  = context.TableName;
            UpdateInfo updateInfo = (UpdateInfo)context.CommandInfo;

            StringBuilder         sqlBuilder      = new StringBuilder();
            SqlCommandDescription result          = new SqlCommandDescription();
            GenerateContext       generateContext = new GenerateContext(result, sqlBuilder);

            sqlBuilder.Append($"UPDATE [{tableName}] SET ");
            string setCommand;

            if (updateInfo.SetFields.Any())
            {
                setCommand = updateInfo.SetFields.Join(",", x =>
                {
                    result.AddParameter(new SqlParameterInfo(x.Parameter));
                    return($"[{x.Field}] = @{x.Parameter}");
                });
            }
            else
            {
                HashSet <string> conditionField         = new HashSet <string>(updateInfo.Conditions.Select(x => x.Field));
                HashSet <string> lowerCaseWithoutFields = new HashSet <string>(updateInfo.WithoutFields.Select(x => x.ToLower()));
                setCommand = GetColumnNames(context)
                             .Where(x => !conditionField.Contains(x))
                             .Where(x => !lowerCaseWithoutFields.Contains(x.ToLower()))
                             .Join(",", x =>
                {
                    result.AddParameter(new SqlParameterInfo(x));
                    return($"[{x}] = @{x}");
                });
            }

            sqlBuilder.Append(setCommand);

            GenerateByConditions(ref generateContext, updateInfo.Conditions);

            result.SqlCommand = sqlBuilder.ToString();
            return(result);
        }
Example #17
0
        protected override SqlCommandDescription GenerateInsert(SqlCommandGenerateContext context)
        {
            SqlCommandDescription description = new SqlCommandDescription();

            InsertInfo info = (InsertInfo)context.CommandInfo;

            HashSet <string> lowerCaseWithoutFields = new HashSet <string>
                                                      (
                info.WithoutFields.Select(x => x.ToLower())
                                                      );

            IEnumerable <string> columnNames = GetColumnNames(context)
                                               .Where(x => !lowerCaseWithoutFields.Contains(x.ToLower()));
            string fields = columnNames.Join(",", x => $"[{x}]");
            string values = columnNames.Join(",", x => $"@{x}");

            foreach (var columnName in columnNames)
            {
                description.AddParameter(new SqlParameterInfo(columnName));
            }
            description.SqlCommand = $"INSERT INTO [{context.TableName}]({fields})VALUES({values});SELECT ISNULL(SCOPE_IDENTITY(),0) AS [Id]";
            return(description);
        }
 private void Fill(ISqlCommandGenerator generator, SqlCommandDescription description, string parameterName, Type valueType, Func <object> valueGetter)
 {
     if (IsBaseType(valueType))
     {
         FillWithBaseType(description, parameterName, valueGetter);
     }
     else if (IsCollectionType(valueType))
     {
         FillWithCollectionType(generator, description, parameterName, valueGetter);
     }
     else if (IsObject(valueType))
     {
         FillWithObjectType(generator, description, valueType, valueGetter);
     }
     else if (IsEnum(valueType))
     {
         FillWithBaseType(description, parameterName, () => Convert.ToInt32(valueGetter()));
     }
     else
     {
         throw new CanNotConvertToSqlParameterException(valueType);
     }
 }
 public GenerateContext(SqlCommandDescription sqlCommandDescription, StringBuilder stringBuilder)
 {
     SqlCommandDescription = sqlCommandDescription;
     StringBuilder         = stringBuilder;
 }
Example #20
0
 public SqlCommandDescriptionGeneratedEvent(object source, SqlCommandDescription sqlCommandDescription) : base(source)
 {
     this.SqlCommandDescription = sqlCommandDescription;
 }
Example #21
0
 public int Execute(DbConnectionContext dbConnectionContext, SqlCommandDescription sqlCommand)
 {
     Console.WriteLine(sqlCommand.ToString());
     return(10);
 }