//long iterations = 0L;

        public override void DeliverMessage(IEntityDescriptor destination, IMessage message)
        {
            //Logger.Instance.Log(string.Format("Delivering {0} to {1}...", message, destination));
            //this.MessageCount++;
            //var t = new Task(() =>
            //{
            //    var messageAndDestination = new MessageWithDestination
            //    {
            //        //Source = message.Source,
            //        Destination = destination,
            //        Message = message
            //    };
            //    var entityProcessor = GetEntityWithProcessor(messageAndDestination.Destination);
            //    if (entityProcessor != null)
            //    {
            //        entityProcessor.ReceiveMessage(messageAndDestination.Message.Source, messageAndDestination.Message);
            //    }
            //    //Console.WriteLine("Enqueueing {0}", messageAndDestination);
            //    //lock (this.Queue)
            //    //{
            //    //    this.Queue.Enqueue(messageAndDestination);
            //    //}
            //    //entity.ReceiveMessage(message.Source, message);
            //    //}
            //    Logger.Instance.Log(string.Format("Delivered {0} to {1}", message, destination));
            //});
            //lock (this.Tasks)
            //{
            //    this.Tasks.Add(t);
            //}
            //t.Start();
            throw new NotImplementedException();
        }
        internal MethodEntityProcessor(MethodEntity methodEntity, 
            IDispatcher dispatcher, ICodeProvider codeProvider, IEntityDescriptor entityDescriptor = null,
            bool verbose = false)
            : base(methodEntity, entityDescriptor, dispatcher)
        {
            Contract.Assert(methodEntity != null);

            this.MethodEntity = methodEntity;
            this.EntityDescriptor = entityDescriptor==null?methodEntity.EntityDescriptor
                                                          :entityDescriptor;
            this.Verbose = true; // verbose;
            // It gets a code provider for the method.
            if (codeProvider!=null || dispatcher is OrleansDispatcher)
            {
                this.codeProvider = codeProvider;
                 //this.codeProvider = ProjectGrainWrapper.CreateProjectGrainWrapperAsync(methodEntity.MethodDescriptor).Result;
                //SetCodeProviderAsync(methodEntity.MethodDescriptor);
            }
            else
            {
                var pair = ProjectCodeProvider.GetProjectProviderAndSyntaxAsync(methodEntity.MethodDescriptor).Result;
                if (pair != null)
                {
                    this.codeProvider = pair.Item1;
                }
            }
            // We use the codeProvider for Propagation and HandleCall and ReturnEvents (in the method DiffProp that uses IsAssignable)
            // We can get rid of this by passing codeProvider as parameter in this 3 methods
            this.MethodEntity.PropGraph.SetCodeProvider(this.codeProvider);
        }
        public virtual Task<IEntity> GetEntityAsync(IEntityDescriptor entityDesc)
        {
            IEntity entity;
            entityMapping.TryGetValue(entityDesc, out entity);

			return Task.FromResult(entity);
        }
 public EntityProcessor(IEntity entity, 
                         IEntityDescriptor entityDescriptor,
                         IDispatcher dispatcher)
 {
     this.Entity = entity;
     this.EntityDescriptor = entityDescriptor;
     this.dispatcher = dispatcher;
 }
 public async virtual Task<IEntityProcessor> GetEntityWithProcessorAsync(IEntityDescriptor entityDesc)
 {
     var entity = (Analysis.MethodEntity)await GetEntityAsync(entityDesc);
     if (entity != null)
     {
         return new ReachingTypeAnalysis.Analysis.MethodEntityProcessor(entity, this);
         //return entity.GetEntityProcessor(this);
     }
     return null;
 }
 public  virtual IEntityProcessor GetEntityWithProcessor(IEntityDescriptor entityDesc)
 {
     var entity = (Analysis.MethodEntity)GetEntity(entityDesc);
     if (entity != null)
     {
         return new ReachingTypeAnalysis.Analysis.MethodEntityProcessor(entity, this);
         //return entity.GetEntityProcessor(this);
     }
     return null;
 }
		public async Task DeliverMessageAsync(IEntityDescriptor destination, IMessage message)
		{
            // Option 1: Using directly the grain
            var destinationEntity = await GetEntityAsync(destination);
            var destinationGrain = (IMethodEntityGrain)destinationEntity;
            await destinationGrain.ProcessMessaggeAsync(message.Source, message);

            // Option 2: Using a MethoProcessor created by the grain.
            // This option requires the processor to be serializable
            //var methodEntityProcessor = (MethodEntityProcessor)await GetEntityWithProcessorAsync(destination);
            //await methodEntityProcessor.ProcessMessageAsync(message.Source, message);
		}
        /// <summary>
        /// This dispacher tries to find and load methods on the fly
        /// </summary>
        /// <param name="entityDesc"></param>
        /// <returns></returns>
        public async override Task<IEntity> GetEntityAsync(IEntityDescriptor entityDesc)
        {
            IEntity entity = await base.GetEntityAsync(entityDesc);
            if (entity == null)
            {
                MethodDescriptor methodDescriptor = GetMethodDescriptor(entityDesc);
                var methodEntity = await ProjectCodeProvider.FindProviderAndCreateMethodEntityAsync(methodDescriptor);
                this.RegisterEntity(methodEntity.EntityDescriptor, methodEntity);
                entity = methodEntity;
            }

            return entity;
        }
        void CheckEntityID(EGID entityID, IEntityDescriptor descriptorEntity)
        {
            Dictionary <Type, ITypeSafeDictionary> @group;
            var descriptorEntitiesToBuild = descriptorEntity.entitiesToBuild;

            if (_groupEntityDB.TryGetValue(entityID.groupID, out @group) == true)
            {
                for (int i = 0; i < descriptorEntitiesToBuild.Length; i++)
                {
                    CheckEntityID(entityID, descriptorEntitiesToBuild[i].GetEntityType(), @group, descriptorEntity.ToString());
                }
            }
        }
Example #10
0
        public EntitySql Build(IEntityDescriptor descriptor)
        {
            var batchInsertColumnList = new List <IColumnDescriptor>();
            var insertSql             = BuildInsertSql(descriptor, batchInsertColumnList, out string batchInsertSql);
            var deleteSql             = BuildDeleteSql(descriptor, out string deleteSingleSql);
            var softDeleteSql         = BuildSoftDeleteSql(descriptor, out string softDeleteSingleSql);
            var updateSql             = BuildUpdateSql(descriptor, out string updateSingleSql);
            var querySql  = BuildQuerySql(descriptor, out string getSql);
            var existsSql = BuildExistsSql(descriptor);

            return(new EntitySql(descriptor, insertSql, batchInsertSql, deleteSingleSql, deleteSql, softDeleteSql,
                                 softDeleteSingleSql, updateSingleSql, updateSql, getSql, querySql, existsSql, batchInsertColumnList));
        }
 public MethodEntity(MethodDescriptor methodDescriptor,
                     MethodInterfaceData mid,
                     PropagationGraph propGraph,
                     IEntityDescriptor descriptor,
                     IEnumerable <TypeDescriptor> instantiatedTypes,
                     IDictionary <AnonymousMethodDescriptor, MethodEntity> anonymousMethods,
                     CodeGraphModel.DeclarationAnnotation declarationInfo,
                     CodeGraphModel.SymbolReference referenceInfo)
     : this(methodDescriptor, mid, propGraph, descriptor, instantiatedTypes)
 {
     this.anonymousMethods = anonymousMethods;
     this.DeclarationInfo  = declarationInfo;
     this.ReferenceInfo    = referenceInfo;
 }
Example #12
0
        public void CreateTable(IDataContext db, IEntityDescriptor model, string label)
        {
            if (db == null)
            {
                throw new ArgumentNullException("session");
            }

            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var tableName = model.TableName.SqlEscape();

            LoggerProvider.EnvironmentLogger.Debug(String.Format("Creating Table [{0}]...", tableName));

            var fieldsWithoutId = model.Fields.Values.Where(f => f.IsColumn);

            var sb = new SqlStringBuilder();

            sb.Add("create table [");
            sb.Add(tableName);
            sb.Add("] (");

            var commaNeeded = false;

            foreach (var f in fieldsWithoutId)
            {
                if (commaNeeded)
                {
                    sb.Add(", ");
                }
                commaNeeded = true;

                sb.Add("[" + f.Name + "]");
                sb.Add(" ");
                var sqlType = MssqlSqlTypeConverter.GetSqlType(f);
                sb.Add(sqlType);
            }

            sb.Add(") ");

            var sql = sb.ToSqlString();

            db.Execute(sql);

            //TODO 支持表注释
            //SetTableComment(db, tableName, label);
        }
Example #13
0
        /// <summary>
        /// 设置删除语句
        /// </summary>
        private string BuildDeleteSql(IEntityDescriptor descriptor, out string deleteSingleSql)
        {
            var deleteSql = $"DELETE FROM {descriptor.SqlAdapter.AppendQuote(descriptor.TableName)} ";

            if (!descriptor.PrimaryKey.IsNo())
            {
                deleteSingleSql = $"{deleteSql} WHERE {descriptor.SqlAdapter.AppendQuote(descriptor.PrimaryKey.Name)}={descriptor.SqlAdapter.AppendParameter(descriptor.PrimaryKey.PropertyInfo.Name)};";
            }
            else
            {
                deleteSingleSql = "";
            }

            return(deleteSql);
        }
        /// <summary>
        /// This method should not exists. Because the IEntityDescriptor should have a MethdodDescriptor 
        /// and Orleans entities should not appear here
        /// </summary>
        /// <param name="entityDesc"></param>
        /// <returns></returns>
        private MethodDescriptor GetMethodDescriptor(IEntityDescriptor entityDesc)
        {
            if(entityDesc is MethodEntityDescriptor)
            {
                return ((MethodEntityDescriptor)entityDesc).MethodDescriptor;
            }
            if (entityDesc is OrleansEntityDescriptor)
            {
                var grainDesc = (OrleansEntityDescriptor)entityDesc;
    			Contract.Assert(grainDesc != null);
	
                return grainDesc.MethodDescriptor;
            }
            throw new NotImplementedException("We shouldn't reach this place");
        }
        /// <summary>
        /// We use this mapping as a cache of already computed callees info
        /// </summary>
        //public MethodEntityProcessor EntityProcessor { get; private set; }

        //public ISet<E> NodesProcessing = new HashSet<E>();
        //public ISet<CallConext<M,E>> NodesProcessing = new HashSet<CallConext<M,E>>();

        /// <summary>
        /// A method entity is built using the methods interface (params, return) and the propagation graph that is
        /// initially populated with the variables, parameters and calls of the method
        /// </summary>
        /// <param name="methodDescriptor"></param>
        /// <param name="mid"></param>
        /// <param name="propGraph"></param>
        /// <param name="instantiatedTypes"></param>
        public MethodEntity(MethodDescriptor methodDescriptor,
                            MethodInterfaceData mid,
                            PropagationGraph propGraph,
                            IEntityDescriptor descriptor,
                            IEnumerable <TypeDescriptor> instantiatedTypes,
                            bool canBeAnalyzed = true)
        {
            this.MethodDescriptor    = methodDescriptor;
            this.EntityDescriptor    = descriptor; // EntityFactory.Create(methodDescriptor);
            this.MethodInterfaceData = mid;

            this.propGraph         = propGraph;
            this.CanBeAnalized     = canBeAnalyzed;
            this.InstantiatedTypes = new HashSet <TypeDescriptor>(instantiatedTypes);
            this.anonymousMethods  = new Dictionary <AnonymousMethodDescriptor, MethodEntity>();
        }
        public ListEntitiesGraphQLType(
            IEntityDescriptor descriptor,
            IIndex <IEntityDescriptor, EntityGraphQLType> entityTypesByDescriptor,
            IIndex <IEntityDescriptor, IRepository> repositoriesByDescriptor)
        {
            Name         = descriptor.Name.Pluralize().Camelize();
            Description  = $"Query all {descriptor.Name.Pluralize().Humanize(LetterCasing.LowerCase)}";
            ResolvedType = new ListGraphType(new NonNullGraphType(entityTypesByDescriptor[descriptor]));

            var repository = repositoriesByDescriptor[descriptor];

            Resolver = new AsyncFieldResolver <IEnumerable <IEntity> >(resolveContext =>
            {
                return(repository.__UNSAFE__ListAsync(resolveContext.CancellationToken));
            });
        }
        /// <summary>
        /// We use this mapping as a cache of already computed callees info
        /// </summary>
        //public MethodEntityProcessor EntityProcessor { get; private set; }
        //public ISet<E> NodesProcessing = new HashSet<E>();
        //public ISet<CallConext<M,E>> NodesProcessing = new HashSet<CallConext<M,E>>();
        /// <summary>
        /// A method entity is built using the methods interface (params, return) and the propagation graph that is 
        /// initially populated with the variables, parameters and calls of the method 
        /// </summary>
        /// <param name="methodDescriptor"></param>
        /// <param name="mid"></param>
        /// <param name="propGraph"></param>
        /// <param name="instantiatedTypes"></param>
        public MethodEntity(MethodDescriptor methodDescriptor,
            MethodInterfaceData mid,
            PropagationGraph propGraph,
            IEntityDescriptor descriptor,
            IEnumerable<TypeDescriptor> instantiatedTypes,
            bool canBeAnalyzed = true)
            : base()
        {
            this.MethodDescriptor = methodDescriptor;
            this.EntityDescriptor = descriptor; // EntityFactory.Create(methodDescriptor);
            this.MethodInterfaceData = mid;

            this.propGraph = propGraph;
            this.InstantiatedTypes = new HashSet<TypeDescriptor>(instantiatedTypes);
            this.CanBeAnalized = canBeAnalyzed;
        }
Example #18
0
        private void RegisterEntityType <TEntity>(IEntityDescriptor descriptor, ContainerBuilder builder)
            where TEntity : Entity <TEntity>
        {
            builder
            .RegisterType <TransientRepository>()
            .Keyed <IRepository>(descriptor)
            .SingleInstance();

            builder
            .Register(ctx =>
            {
                var repository = ctx.ResolveKeyed <IRepository>(descriptor);
                return(new TypesafeRepository <TEntity>(repository));
            })
            .As <IRepository <TEntity> >()
            .SingleInstance();
        }
Example #19
0
 public EntitySql(IEntityDescriptor descriptor, string insert, string batchInsert, string deleteSingle, string delete, string softDelete, string softDeleteSingle, string updateSingle, string update, string get, string query, string exists, List <IColumnDescriptor> batchInsertColumnList)
 {
     _descriptor       = descriptor;
     _adapter          = _descriptor.SqlAdapter;
     _insert           = insert;
     _batchInsert      = batchInsert;
     _deleteSingle     = deleteSingle;
     _delete           = delete;
     _softDelete       = softDelete;
     _softDeleteSingle = softDeleteSingle;
     _updateSingle     = updateSingle;
     _update           = update;
     _get    = get;
     _query  = query;
     _exists = exists;
     BatchInsertColumnList = batchInsertColumnList;
 }
        private string CreateTableSql(IEntityDescriptor entityDescriptor)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE IF NOT EXISTS {0}(", AppendQuote(entityDescriptor.TableName));

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("`{0}` ", column.Name);
                sql.AppendFormat("{0} ", Property2Column(column, out string def));

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");

                    if (entityDescriptor.PrimaryKey.IsInt() || entityDescriptor.PrimaryKey.IsLong())
                    {
                        sql.Append("AUTO_INCREMENT ");
                    }

                    def = string.Empty;
                }

                if (!column.Nullable)
                {
                    sql.Append("NOT NULL ");
                }

                if (def.NotNull())
                {
                    sql.Append(def);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;");

            return(sql.ToString());
        }
Example #21
0
        private string CreateTableSql(IEntityDescriptor entityDescriptor)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE [{0}](", entityDescriptor.TableName);

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("[{0}] ", column.Name);
                sql.AppendFormat("{0} ", Property2Column(column, out string def));

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");

                    if (entityDescriptor.PrimaryKey.IsInt() || entityDescriptor.PrimaryKey.IsLong())
                    {
                        sql.Append("IDENTITY(1,1) ");
                    }

                    def = string.Empty;
                }

                if (!column.Nullable)
                {
                    sql.Append("NOT NULL ");
                }

                if (def.NotNull())
                {
                    sql.Append(def);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(");");

            return(sql.ToString());
        }
Example #22
0
        /// <summary>
        /// 覆盖指定类型或继承类型的实体解释器。
        /// </summary>
        /// <typeparam name="T">实体类型。</typeparam>
        /// <param name="descriptor">实体解释器。</param>
        public static void OverrideDescriptor <T>(IEntityDescriptor descriptor)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException(nameof(descriptor));
            }
            Type type = typeof(T);

            if (_TargetedDescriptor.ContainsKey(type))
            {
                _TargetedDescriptor[type] = descriptor;
            }
            else
            {
                _TargetedDescriptor.Add(type, descriptor);
            }
        }
Example #23
0
        /// <summary>
        /// 设置查询语句
        /// </summary>
        private string BuildQuerySql(IEntityDescriptor descriptor, out string getSql, out string getAndRowLockSql)
        {
            var sb = new StringBuilder("SELECT ");

            for (var i = 0; i < descriptor.Columns.Count; i++)
            {
                var col = descriptor.Columns[i];
                sb.AppendFormat("{0} AS '{1}'", descriptor.SqlAdapter.AppendQuote(col.Name), col.PropertyInfo.Name);

                if (i != descriptor.Columns.Count - 1)
                {
                    sb.Append(",");
                }
            }
            sb.Append(" FROM {0} ");

            var querySql = sb.ToString();

            getSql           = querySql;
            getAndRowLockSql = querySql;
            // SqlServer行锁
            if (descriptor.SqlAdapter.SqlDialect == Abstractions.Enums.SqlDialect.SqlServer)
            {
                getAndRowLockSql += " WITH (ROWLOCK, UPDLOCK) ";
            }

            if (!descriptor.PrimaryKey.IsNo())
            {
                getSql           += $" WHERE {descriptor.SqlAdapter.AppendQuote(descriptor.PrimaryKey.Name)}={descriptor.SqlAdapter.AppendParameter(descriptor.PrimaryKey.PropertyInfo.Name)} ";
                getAndRowLockSql += $" WHERE {descriptor.SqlAdapter.AppendQuote(descriptor.PrimaryKey.Name)}={descriptor.SqlAdapter.AppendParameter(descriptor.PrimaryKey.PropertyInfo.Name)} ";

                if (descriptor.SoftDelete)
                {
                    getSql           += $" AND {descriptor.SqlAdapter.AppendQuote("Deleted")}=0 ";
                    getAndRowLockSql += $" AND {descriptor.SqlAdapter.AppendQuote("Deleted")}=0 ";
                }

                //MySql行锁
                if (descriptor.SqlAdapter.SqlDialect == Abstractions.Enums.SqlDialect.MySql)
                {
                    getAndRowLockSql += " FOR UPDATE;";
                }
            }

            return(querySql);
        }
Example #24
0
        /// <summary>
        /// 设置是否存在语句
        /// </summary>
        /// <param name="descriptor"></param>
        /// <returns></returns>
        private string BuildExistsSql(IEntityDescriptor descriptor)
        {
            //没有主键,无法使用该方法
            if (descriptor.PrimaryKey.IsNo())
            {
                return(string.Empty);
            }

            var sql = $"SELECT COUNT(0) FROM {{0}} WHERE {descriptor.SqlAdapter.AppendQuote(descriptor.PrimaryKey.Name)}={descriptor.SqlAdapter.AppendParameter(descriptor.PrimaryKey.PropertyInfo.Name)}";

            if (descriptor.SoftDelete)
            {
                sql += $" AND {descriptor.SqlAdapter.AppendQuote("Deleted")}=0 ";
            }

            return(sql);
        }
Example #25
0
        /// <summary>
        /// 设置插入语句
        /// </summary>
        private string BuildInsertSql(IEntityDescriptor descriptor, List <IColumnDescriptor> batchInsertColumnList, out string batchInsertSql)
        {
            var sb = new StringBuilder();

            sb.Append("INSERT INTO {0} ");
            sb.Append("(");

            var valuesSql = new StringBuilder();

            foreach (var col in descriptor.Columns)
            {
                //排除自增主键
                if (col.IsPrimaryKey && (descriptor.PrimaryKey.IsInt() || descriptor.PrimaryKey.IsLong()))
                {
                    continue;
                }

                descriptor.SqlAdapter.AppendQuote(sb, col.Name);
                sb.Append(",");

                descriptor.SqlAdapter.AppendParameter(valuesSql, col.PropertyInfo.Name);
                valuesSql.Append(",");

                batchInsertColumnList.Add(col);
            }

            //删除最后一个","
            sb.Remove(sb.Length - 1, 1);

            sb.Append(") VALUES");

            batchInsertSql = sb.ToString();

            sb.Append("(");

            //删除最后一个","
            if (valuesSql.Length > 0)
            {
                valuesSql.Remove(valuesSql.Length - 1, 1);
            }

            sb.Append(valuesSql);
            sb.Append(");");

            return(sb.ToString());
        }
        EntityStructInitializer BuildEntity(EGID entityID,
                                            IEntityDescriptor entityDescriptor,
                                            object[] implementors)
        {
            var descriptorEntitiesToBuild = entityDescriptor.entitiesToBuild;

#if DEBUG && !PROFILER
            CheckEntityID(entityID, entityDescriptor);
#endif
            var dic = EntityFactory.BuildGroupedEntityViews(entityID,
                                                            _groupedEntityToAdd.current,
                                                            descriptorEntitiesToBuild,
                                                            implementors);

            _newEntitiesBuiltToProcess++;

            return(new EntityStructInitializer(entityID, dic));
        }
Example #27
0
        public EntityGraphQLType(
            IEntityDescriptor descriptor,
            IGraphQLMapper mapper)
        {
            _mapper     = mapper;
            _properties = descriptor.Properties;

            Name        = descriptor.Name;
            Description = XmlDoc.ReadSummary(descriptor.EntityType);

            AddField(new FieldType
            {
                Name         = "id",
                Description  = $"The ID of the {descriptor.Name.Humanize(LetterCasing.LowerCase)}.",
                ResolvedType = new NonNullGraphType(new IdGraphType()),
                Resolver     = new FuncFieldResolver <IEntity, Guid>(resolveContext => resolveContext.Source.Id),
            });
        }
Example #28
0
        public override string GetCreateTableSql(IEntityDescriptor entityDescriptor, string tableName = null)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE [{0}](", tableName ?? entityDescriptor.TableName);

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("[{0}] ", column.Name);
                sql.AppendFormat("{0} ", column.TypeName);

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");

                    if (entityDescriptor.PrimaryKey.IsInt() || entityDescriptor.PrimaryKey.IsLong())
                    {
                        sql.Append("IDENTITY(1,1) ");
                    }
                }

                if (!column.Nullable)
                {
                    sql.Append("NOT NULL ");
                }

                if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
                {
                    sql.Append(column.DefaultValue);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(");");

            return(sql.ToString());
        }
Example #29
0
        public override string GetCreateTableSql(IEntityDescriptor entityDescriptor, string tableName = null)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE IF NOT EXISTS {0}(", AppendQuote(tableName ?? entityDescriptor.TableName));

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("`{0}` ", column.Name);
                sql.AppendFormat("{0} ", column.TypeName);

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");

                    if (entityDescriptor.PrimaryKey.IsInt() || entityDescriptor.PrimaryKey.IsLong())
                    {
                        sql.Append("AUTO_INCREMENT ");
                    }
                }

                if (!column.Nullable)
                {
                    sql.Append("NOT NULL ");
                }

                if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
                {
                    sql.Append(column.DefaultValue);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;");

            return(sql.ToString());
        }
		/// <summary>
		/// Asynv version of ProcessMessage
		/// </summary>
		/// <param name="source"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		public async override Task ProcessMessageAsync(IEntityDescriptor source, IMessage message)
		{
			//lock (this.Entity)
			{
				if (message is CallerMessage)
				{
					await ProcessCallMessageAsync(message as CallerMessage);
				}
				else
				if (message is ReturnMessage)
				{
					await ProcessReturnMessageAsync(message as ReturnMessage);
				}
				else
				{
					Contract.Assert(false, "Unexpected message: " + message);
				}
			}
		}
Example #31
0
        /// <summary>
        /// 设置软删除
        /// </summary>
        private string BuildSoftDeleteSql(IEntityDescriptor descriptor, out string softDeleteSingleSql)
        {
            var sb = new StringBuilder($"UPDATE {descriptor.SqlAdapter.AppendQuote(descriptor.TableName)} SET ");

            sb.AppendFormat("{0}=1,", descriptor.SqlAdapter.AppendQuote("IsDeleted"));
            sb.AppendFormat("{0}={1},", descriptor.SqlAdapter.AppendQuote("DeletedTime"), descriptor.SqlAdapter.AppendParameter("DeletedTime"));
            sb.AppendFormat("{0}={1} ", descriptor.SqlAdapter.AppendQuote("Deleter"), descriptor.SqlAdapter.AppendParameter("Deleter"));

            var softDeleteSql = sb.ToString();

            softDeleteSingleSql = "";
            if (descriptor.SoftDelete)
            {
                sb.AppendFormat(" WHERE {0}={1};", descriptor.SqlAdapter.AppendQuote(descriptor.PrimaryKey.Name), descriptor.SqlAdapter.AppendParameter(descriptor.PrimaryKey.PropertyInfo.Name));
                softDeleteSingleSql = sb.ToString();
            }

            return(softDeleteSql);
        }
        void CheckRemoveEntityID(EGID entityID, IEntityDescriptor descriptorEntity)
        {
            var descriptorEntitiesToBuild = descriptorEntity.entitiesToBuild;

            if (_groupEntityDB.TryGetValue(entityID.groupID, out var @group))
            {
                for (int i = 0; i < descriptorEntitiesToBuild.Length; i++)
                {
                    CheckRemoveEntityID(entityID, descriptorEntitiesToBuild[i].GetEntityType(), group, descriptorEntity.ToString());
                }
            }
            else
            {
                Console.LogError("Entity with not found ID is about to be removed: id: "
                                 .FastConcat(entityID.entityID)
                                 .FastConcat(" groupid: ")
                                 .FastConcat(entityID.groupID));
            }
        }
        public override async Task DeliverMessageAsync(IEntityDescriptor destination, IMessage message)
        {
            Logger.Instance.Log("AsyncDispatcher", "DeliverMessageAsync", "Delivering {0} to {1}", message, destination);
            this.MessageCount++;
            var messageAndDestination = new MessageWithDestination
            {
                //Source = message.Source,
                Destination = destination,
                Message = message
            };
            var entityProcessor = await GetEntityWithProcessorAsync(messageAndDestination.Destination);
                        
            if (entityProcessor != null)
            {
                await entityProcessor.ReceiveMessageAsync(
                    messageAndDestination.Message.Source, 
					messageAndDestination.Message);
            }
        }
        void CheckRemoveEntityID(EGID entityID, IEntityDescriptor descriptorEntity)
        {
            Dictionary <Type, ITypeSafeDictionary> @group;
            var descriptorEntitiesToBuild = descriptorEntity.entitiesToBuild;

            if (_groupEntityDB.TryGetValue(entityID.groupID, out @group) == true)
            {
                for (int i = 0; i < descriptorEntitiesToBuild.Length; i++)
                {
                    CheckRemoveEntityID(entityID, descriptorEntitiesToBuild[i].GetEntityType(), @group, descriptorEntity.ToString());
                }
            }
            else
            {
                Console.LogError("Entity ".FastConcat(" with not found ID is about to be removed: ")
                                 .FastConcat(" id: ")
                                 .FastConcat(entityID.entityID)
                                 .FastConcat(" groupid: ")
                                 .FastConcat(entityID.groupID));
            }
        }
        private string CreateTableSql(IEntityDescriptor entityDescriptor)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE IF NOT EXISTS {0}.{1}(", AppendQuote(Options.Database), AppendQuote(entityDescriptor.TableName.ToLower()));

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("{0} ", AppendQuote(column.Name.ToLower()));
                sql.AppendFormat("{0} ", Property2Column(column, out string def));

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");
                }

                if (!column.Nullable && !column.IsPrimaryKey)
                {
                    sql.Append("NOT NULL ");
                }

                if (def.NotNull())
                {
                    sql.Append(def);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(");");

            return(sql.ToString());
        }
        private string CreateTableSql(IEntityDescriptor entityDescriptor)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE {0}(", AppendQuote(entityDescriptor.TableName));

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("`{0}` ", column.Name);
                sql.AppendFormat("{0} ", Property2Column(column));

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");

                    if (entityDescriptor.PrimaryKey.IsInt() || entityDescriptor.PrimaryKey.IsLong())
                    {
                        sql.Append("AUTOINCREMENT ");
                    }
                }

                if (!column.Nullable)
                {
                    sql.Append("NOT NULL ");
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(")");

            return(sql.ToString());
        }
Example #37
0
        public override string GetCreateTableSql(IEntityDescriptor entityDescriptor, string tableName = null)
        {
            var columns = entityDescriptor.Columns;
            var sql     = new StringBuilder();

            sql.AppendFormat("CREATE TABLE IF NOT EXISTS {0}.{1}(", AppendQuote(Options.Database), AppendQuote(tableName ?? entityDescriptor.TableName.ToLower()));

            for (int i = 0; i < columns.Count; i++)
            {
                var column = columns[i];

                sql.AppendFormat("{0} ", AppendQuote(column.Name.ToLower()));
                sql.AppendFormat("{0} ", column.TypeName);

                if (column.IsPrimaryKey)
                {
                    sql.Append("PRIMARY KEY ");
                }

                if (!column.Nullable && !column.IsPrimaryKey)
                {
                    sql.Append("NOT NULL ");
                }

                if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
                {
                    sql.Append(column.DefaultValue);
                }

                if (i < columns.Count - 1)
                {
                    sql.Append(",");
                }
            }

            sql.Append(");");

            return(sql.ToString());
        }
 public override void DeliverMessage(IEntityDescriptor destination, IMessage message)
 {
     this.MessageCount++;
     Task.Factory.StartNew(() =>
     {
         var messageAndDestination = new MessageWithDestination
         {
             //Source = message.Source,
             Destination = destination,
             Message = message
         };
         Console.WriteLine("Enqueueing {0}", messageAndDestination);
         lock (this.Queue)
         {
             this.Queue.Enqueue(messageAndDestination);
         }
         //entity.ReceiveMessage(message.Source, message);
         //}
         //return messageAndDestination;
     });
     //.ContinueWith((mad) => ProcessNext(mad.Result));
 }
Example #39
0
        public EntityMapper(IEntityDescriptor <TEntity> descriptor)
        {
            this.Descriptor = descriptor;

            var identityCount = descriptor.Properties.Count(d => d.IsIdentity);

            if (identityCount <= 0)
            {
                throw new ArgumentException("No identity specified.");
            }
            else
            {
                this.m_allProperties = descriptor.Properties.ToDictionary(
                    d => d.Property,
                    d => new PropertyMapper(d, d.IsIdentity ? (identityCount == 1) : false));
            }

            this.m_identities = this.m_allProperties.Values
                                .Where(m => m.Descriptor.IsIdentity)
                                .ToDictionary(p => p.Descriptor.Property);

            this.m_version = this.m_allProperties.Values.SingleOrDefault(p => p.Descriptor.IsVersion);
        }
Example #40
0
        public EntitySql Build(IEntityDescriptor descriptor)
        {
            var batchInsertColumnList = new List <IColumnDescriptor>();
            var insertSql             = BuildInsertSql(descriptor, batchInsertColumnList, out string batchInsertSql);
            var deleteSql             = BuildDeleteSql(descriptor, out string deleteSingleSql);
            var softDeleteSql         = BuildSoftDeleteSql(descriptor, out string softDeleteSingleSql);
            var updateSql             = BuildUpdateSql(descriptor, out string updateSingleSql);
            var querySql = BuildQuerySql(descriptor, out string getSql);

            return(new EntitySql
            {
                Insert = insertSql,
                BatchInsert = batchInsertSql,
                BatchInsertColumnList = batchInsertColumnList,
                Delete = deleteSql,
                DeleteSingle = deleteSingleSql,
                SoftDelete = softDeleteSql,
                SoftDeleteSingle = softDeleteSingleSql,
                Update = updateSql,
                UpdateSingle = updateSingleSql,
                Query = querySql,
                Get = getSql
            });
        }
        /// <summary>
        /// Recupera as informações dos valores de uma lista de propriedades.
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="entityDescriptor"></param>
        /// <param name="record"></param>
        /// <returns></returns>
        private IEnumerable <object> Merge(string[] properties, IEntityDescriptor entityDescriptor, Query.IRecord record)
        {
            var entityDescriptorStateble = entityDescriptor as IEntityDescriptorStateble;

            foreach (var p in properties)
            {
                var index = record.Descriptor.GetFieldPosition(p);
                if (index >= 0)
                {
                    yield return(record.GetValue(record.Descriptor.GetFieldPosition(p)));
                }
                else
                {
                    if (entityDescriptorStateble != null && entityDescriptorStateble.Contains(p))
                    {
                        yield return(entityDescriptorStateble[p]);
                    }
                    else
                    {
                        yield return(null);
                    }
                }
            }
        }
        public override void DeliverMessage(IEntityDescriptor destination, IMessage message)
        {
            // We can put the message in the destination queue
            //var entity = GetEntity(destination);
            var entityProcessor = GetEntityWithProcessorAsync(destination).Result;

            if (entityProcessor != null)
            {
                // We really need to fix this.
                // TO-DO Remove this: add the check in the HandleCallEvent method (as I did with async)
                Contract.Assert(activeEntities.Occurrences(destination) < 5);
                //if (activeEntities.Occurrences(destination) > 5)
                //{
                //    Console.Error.WriteLine("Occurs check on {0}", destination);
                //}
                //else
                {
                    activeEntities.Add(destination);
                    entityProcessor.ReceiveMessage(message.Source, message);
                    activeEntities.Remove(destination);
                }
            }
            this.MessageCount++;
        }
		public void RegisterEntity(IEntityDescriptor entityDesc, IEntity entity)
		{
			//var descriptor = (OrleansEntityDescriptor)entityDesc;
			//this.entities.Add(descriptor.MethodDescriptor);
 		}
 public IEntity GetEntity(IEntityDescriptor entityDesc)
 {
     throw new NotImplementedException();
 }
 public IEntityProcessor GetEntityWithProcessor(IEntityDescriptor entityDesc)
 {
     //throw new NotImplementedException();
     return GetEntityWithProcessorAsync(entityDesc).Result;
 }
Example #46
0
 public EntitySqlBuilder(IEntityDescriptor descriptor)
 {
     _descriptor = descriptor;
     _primaryKey = descriptor.PrimaryKey;
 }
        public async Task<IEntity> GetEntityAsync(IEntityDescriptor entityDesc)
        {
			if(entityDesc.Equals(self))
			{
				return entity;
			}
            Contract.Assert(entityDesc != null);
            var grainDesc = (OrleansEntityDescriptor)entityDesc;
            Contract.Assert(grainDesc != null);

            //var guid = ((OrleansEntityDescriptor)grainDesc).Guid;
			return await CreateMethodEntityGrain(grainDesc);
        }
 public virtual IEntity GetEntity(IEntityDescriptor entityDesc)
 {
     IEntity entity;
     entityMapping.TryGetValue(entityDesc, out entity);
     return entity;
 }
 internal MethodEntityProcessor(MethodEntity methodEntity,
     IDispatcher dispatcher, IEntityDescriptor entityDescriptor = null,
     bool verbose = false)
     : this(methodEntity, dispatcher, null, entityDescriptor, verbose)
 {
 }
 public void RegisterEntity(IEntityDescriptor entityDesc, IEntity entity)
 {
     entityMapping[entityDesc] = entity;
 }
		public async Task<IEntityProcessor> GetEntityWithProcessorAsync(IEntityDescriptor entityDesc)
		{
			Contract.Assert(entityDesc != null);
			var entity = (IMethodEntityGrain)await GetEntityAsync(entityDesc);
            return await entity.GetEntityWithProcessorAsync();
            //Contract.Assert(entity != null);
            //var methodEntity = (MethodEntity) await entity.GetMethodEntity();
            //var codeProvider = await ProjectGrainWrapper.CreateProjectGrainWrapperAsync(methodEntity.MethodDescriptor);
            //return new MethodEntityProcessor(methodEntity, this, codeProvider, entityDesc, true);
		}
 public async Task<MethodEntity> GetMethodEntityAsync(IEntityDescriptor entityDesc)
 {
     var grainDesc = (OrleansEntityDescriptor)entityDesc;
     //Contract.Assert(grainDesc != null);
     Contract.Assert(grainDesc.MethodDescriptor != null);
     return await ProjectCodeProvider.FindProviderAndCreateMethodEntityAsync(grainDesc.MethodDescriptor);
 }
		public void DeliverMessage(IEntityDescriptor destination, IMessage message)
		{
			throw new NotImplementedException();
		}
 /// <summary>
 /// This is the main responsibility of the class. Essentially to anwser messagages sent to the entity
 /// </summary>
 /// <param name="source"></param>
 /// <param name="message"></param>
 public override void ProcessMessage(IEntityDescriptor source, IMessage message)
 {
     lock (this.Entity)
     {
         if (message is CallerMessage)
         {
             ProcessCallMessage(message as CallerMessage);
         }
         else if (message is ReturnMessage)
         {
             ProcessReturnMessage(message as ReturnMessage);
         }
     }
 }
 internal EntityDescriptorInfo(IEntityDescriptor descriptor)
 {
     name = descriptor.ToString();
     entityViewsToBuild = descriptor.entityViewsToBuild;
 }
        /// <summary>
        /// We use this constructor in the case we use one dispatcher per grain
        /// </summary>
        /// <param name="self"></param>
        /// <param name="entity"></param>
		public OrleansDispatcher(IEntityDescriptor self, IEntity entity)
		{
			this.self = self;
			this.entity = entity;
		}
 public abstract void DeliverMessage(IEntityDescriptor destination, IMessage message);
 public abstract Task DeliverMessageAsync(IEntityDescriptor destination, IMessage message);
 public override Task DeliverMessageAsync(IEntityDescriptor destination, IMessage message)
 {
     throw new NotImplementedException();
 }
 internal ReturnMessage(IEntityDescriptor source, ReturnMessageInfo messageInfo)
     : base(source)
 {
     this.ReturnMessageInfo = messageInfo;
 }