public static string GetTableTemplate(this IDataProviderMetaData @this, ISqlCommandGenerator sqlCommandGenerator)
        {
            var result = "";

            string safe(string value) => sqlCommandGenerator.SafeId(value);

            void addTable(IDataProviderMetaData medaData)
            {
                var baseType = medaData.BaseClassesInOrder.LastOrDefault();

                var alias = safe($"{{0}}{medaData.TableAlias}");

                result += " LEFT OUTER JOIN ".OnlyWhen(result.HasValue()) +
                          $"{medaData.Schema.WithSuffix(".")}{medaData.TableName} AS {alias} " +
                          $"ON {alias}.{safe(medaData.IdColumnName)} = {safe($"{{0}}{baseType?.TableAlias}")}.{safe(baseType?.IdColumnName)}".OnlyWhen(baseType != null);
            }

            foreach (var parent in @this.BaseClassesInOrder)
            {
                addTable(parent);
            }

            addTable(@this);

            foreach (var drived in @this.DrivedClasses)
            {
                addTable(drived);
            }

            return(result);
        }
Esempio n. 2
0
 public ParameterLookupContext(ISqlCommandGenerator sqlCommandGenerator, SqlCommandDescription description, MethodInfo methodInfo, object[] values)
 {
     SqlCommandGenerator = sqlCommandGenerator;
     Description         = description;
     MethodInfo          = methodInfo;
     Values = values;
 }
Esempio n. 3
0
 public ConditionGeneratorContext(ISqlCommandGenerator sqlCommandGenerator, SqlCommandDescription sqlCommandDescription, StringBuilder sqlBuilder, ConditionInfo conditionInfo)
 {
     this.sqlCommandGenerator   = sqlCommandGenerator;
     this.sqlCommandDescription = sqlCommandDescription;
     this.sqlBuilder            = sqlBuilder;
     this.conditionInfo         = conditionInfo;
 }
        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("结果集处理完毕");
        }
Esempio n. 5
0
 // <summary>
 // Registgers a data Data Access instance for a specified provider type.
 // </summary>
 public static void Register(
     Type connectionType,
     ISqlCommandGenerator sqlCommandGenerator,
     IParameterFactory parameterFactory)
 {
     ConnectionTypes[connectionType.Name] = connectionType;
     CommandGenerators[connectionType]    = sqlCommandGenerator;
     ParameterFactories[connectionType]   = parameterFactory;
 }
        private static int AttachParamsAndRun <T>(IDbConnection connection, T t, ISqlCommandGenerator commandGenerator)
            where T : class
        {
            var parameters = commandGenerator
                             .GetColumns()
                             .Select(x => x.ValueAccessor(t))
                             .ToArray();

            return(AttachParamsAndRun(connection, commandGenerator.GetSql(), parameters));
        }
        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 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));
                });
            }
        }
        public static DataProvider Get(Type type, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator)
        {
            lock (Cache)
            {
                if (Cache.ContainsKey(type))
                {
                    return(Cache[type]);
                }

                var result = new DataProvider(type, cache, access, sqlCommandGenerator);
                result.Prepare();
                Cache.Add(type, result);

                return(result);
            }
        }
        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);
        }
Esempio n. 11
0
        internal DataProvider(Type type, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator)
        {
            EntityType          = type;
            SqlCommandGenerator = sqlCommandGenerator;
            Cache  = cache;
            Access = access;

            MetaData = DataProviderMetaDataGenerator.Generate(type);

            DeleteCommand = SqlCommandGenerator.GenerateDeleteCommand(MetaData);
            UpdateCommand = SqlCommandGenerator.GenerateUpdateCommand(MetaData);
            InsertCommand = SqlCommandGenerator.GenerateInsertCommand(MetaData);

            if (UpdateCommand.IsEmpty())
            {
                UpdateSelf = entity => Task.CompletedTask;
            }
            else
            {
                UpdateSelf = UpdateSelfImpl;
            }
        }
 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);
     }
 }
Esempio n. 13
0
 public static void Register <TConnection>(ISqlCommandGenerator sqlCommandGenerator, string dataProviderType)
     where TConnection : DbConnection, new()
 {
     Accessors[dataProviderType] = new DataAccess <TConnection>(sqlCommandGenerator);
 }
Esempio n. 14
0
        public static DataProvider GetOrCreate(Type type, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator)
        {
            lock (ProviderCache)
            {
                if (!ProviderCache.TryGetValue(type, out var result))
                {
                    result = new DataProvider(type, cache, access, sqlCommandGenerator);
                    result.Prepare();
                    ProviderCache.Add(type, result);
                }

                return(result);
            }
        }
Esempio n. 15
0
 public RepositoryClassGenerator(ISqlCommandGenerator sqlCommandGenerator)
 {
     _sqlCommandGenerator = sqlCommandGenerator;
 }
Esempio n. 16
0
        public static void Register(Type connectionType, ISqlCommandGenerator sqlCommandGenerator, string dataProviderType)
        {
            var dataAccessType = typeof(DataAccess <>).MakeGenericType(connectionType);

            Accessors[dataProviderType] = (IDataAccess)Activator.CreateInstance(dataAccessType, sqlCommandGenerator, null);
        }
 public static DataProvider GetProvider(
     this Type @this, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator)
 {
     return(InternalDataProviderFactory.Get(@this, cache, access, sqlCommandGenerator));
 }
Esempio n. 18
0
 public CachedSqlCommandGenerator(ISqlCommandGenerator generator)
 {
     _sql     = generator.GetSql();
     _columns = generator.GetColumns().ToArray();
 }
 public static DataProvider GetProvider(
     this IDataProviderMetaData @this, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator)
 {
     return(GetProvider(@this.Type, cache, access, sqlCommandGenerator));
 }
Esempio n. 20
0
 // <summary>
 // Registgers a data Data Access instance for a specified provider type.
 // </summary>
 public static void Register(Type connectionType, ISqlCommandGenerator sqlCommandGenerator)
 {
     ConnectionTypes[connectionType.Name] = connectionType;
     CommandGenerators[connectionType]    = sqlCommandGenerator;
 }