Пример #1
0
        public void Test()
        {
            var db = new TranslateContext()
            {
                Log = System.Console.Out
            };

            db.Users.ToList();
            db.Users.Insert(new User {
                Name = "User", ID = db.Users.Max(o => o.ID) + 1
            });
            var q       = db.Users.Where(o => o.ID < 10);
            var command = db.GetCommand(q);

            Console.WriteLine(command.CommandText);
            db.Connection.Open();
            try
            {
                var reader = command.ExecuteReader();
                var items  = db.Translate <T>(reader);
                foreach (var item in items)
                {
                    Console.Write(item.Name);
                }
            }
            finally
            {
                db.Connection.Close();
            }
        }
Пример #2
0
	public static void Main(string[] args){
		InitConsole();

		string srcfile=checkArgument(args);
		if(srcfile==null)return;

		FileInfo info=new FileInfo();
		info.filename=_args.option_filename??srcfile;
		System.Console.WriteLine("file '{0}' を処理します",srcfile);
		string content=System.IO.File.ReadAllText(srcfile,enc);

		content=Preprocessor.Process(content,info);
    content=RegExp.JsConvertAtStrings(content); // @"" @'' の処理
		content=TranslateContext.Translate(_args,content);
		if(_args.option_compress)
			content=RegExp.CutComment(content);
		else
			content=RegExp.CanonicalizeLine(content);

    if(!_args.option_partial){
      content=string.Format(
        FRAME,
        info.filename,
        enc.WebName,
        System.DateTime.Now,
        srcfile,
        content,
        info.GetMwgScriptsRequirement()
      );
    }
		System.IO.File.WriteAllText(info.filename+".js",content);

		System.Console.WriteLine("file '{0}.js' に書き込みました",info.filename);
	}
 public PropertyFieldExpressionVisitor(TranslateContext context)
     : base(context)
 {
     // TODO: Complete member initialization
     this._joins   = context.Joins;
     this._columns = context.Columns;
 }
Пример #4
0
 public async Task Apply(TResult entity, TranslateContext <TInput, TSchema> context)
 {
     foreach (var translater in _translaters)
     {
         await translater.Apply(entity, context).ConfigureAwait(false);
     }
 }
 public PropertyFieldExpressionVisitor(TranslateContext context)
     : base(context)
 {
     // TODO: Complete member initialization
     this._joins = context.Joins;
     this._columns = context.Columns;
 }
Пример #6
0
        async Task <TranslateResult <TSchema> > TranslateEntity(TranslateContext <TSchema> context, TSchema entity)
        {
            var entityType = entity.GetType();

            var interfaceTypes = entityType.GetTypeInfo().GetInterfaces();

            if (interfaceTypes.Length == 0)
            {
                return(context.Result(entity, entityType));
            }

            foreach (var interfaceType in interfaceTypes)
            {
                IEntityTranslator <TSchema> entityTranslator;
                if (_entityTranslators.TryGetValue(interfaceType, out entityTranslator))
                {
                    var translateResult = await entityTranslator.Translate(context, entity).ConfigureAwait(false);

                    if (translateResult.IsTranslated)
                    {
                        return(translateResult);
                    }
                }
            }

            return(context.Result(entity));
        }
Пример #7
0
        public CompositeTranslateResult(TranslateContext <TSchema> context, IReadOnlyList <TranslateResult <TSchema> > results)
        {
            _context = context;
            _results = results;

            _positions = new List <IndexPosition>(_results.Count);
        }
Пример #8
0
        private void ControllerOnTranslateProviderChanged(bool fromView, string provider, string apiKey,
                                                          string langFrom,
                                                          string langTo)
        {
            if (!fromView)
            {
                return;
            }

            TranslateProvider = provider;
            TranslateApiKey   = apiKey;
            TranslateLangFrom = langFrom;
            TranslateLangTo   = langTo;

            var factory = AllProviders.First(it => it.ProviderId == provider);
            var lF      = langFrom == LanguageDef.CodeAuto
                ? null
                : factory.SupportedSrcLanguages.First(it => it.LangCode == langFrom);
            var lT      = factory.GetSupportedDestLanguages(lF).First(it => it.LangCode == langTo);
            var context = new TranslateContext
            {
                Service  = this,
                Provider = factory.CreateProvider(apiKey, lF, lT)
            };

            _controller.NotifyLegalInfoChanged(false, factory.LegalInfo);
            _workingThread.StartWorkingThread(context);
        }
Пример #9
0
        /// <summary>
        /// 构造最终执行的表达式。
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="translator">翻译器。</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static Expression Build(TranslateContext transContext, Expression expression, BuildOptions options)
        {
            var builder = new ExecutionBuilder()
            {
                _transContext = transContext,
                _executor     = Expression.Parameter(typeof(IDatabase), "db"),
                _translator   = transContext.Translator
            };

            if (options.IsAsync != null)
            {
                builder._isAsync = (bool)options.IsAsync;
            }

            if (options.IsNoTracking == true)
            {
                builder._isNoTracking = true;
            }

            var newExpression = builder.Bind(expression);

            if (builder._isAsync)
            {
                var cancelToken = builder._cancelToken ?? Expression.Parameter(typeof(CancellationToken), "token");
                return(Expression.Lambda(newExpression, builder._executor, cancelToken));
            }

            return(Expression.Lambda(newExpression, builder._executor));
        }
Пример #10
0
        public async Task <TranslateResult <TSchema> > Translate(TranslateContext <TSchema> context, TSchema entity)
        {
            if (entity is TEntity)
            {
                var input = (TEntity)entity;

                var entityContext = context.CreateContext(input);

                if (_observers.Count > 0)
                {
                    await _observers.PreTranslateEntity(input, entityContext).ConfigureAwait(false);
                }

                TranslateResult <TSchema> translateResult;
                if (_filter != null)
                {
                    translateResult = await GetFilteredResult(entityContext, input).ConfigureAwait(false);
                }
                else
                {
                    translateResult = context.Empty <TEntity>();
                }

                if (_observers.Count > 0)
                {
                    await _observers.PostTranslateEntity(translateResult, entityContext);
                }

                return(translateResult);
            }

            return(context.NotTranslated <TEntity>());
        }
Пример #11
0
 public SelectExpressionVisitor(TranslateContext context)
     : base(context)
 {
     // TODO: Complete member initialization
     this._elementType = context.EntityType;
     this._Joins       = context.Joins;
     Columns           = new List <Column>();
 }
 public SelectExpressionVisitor(TranslateContext context)
     : base(context)
 {
     // TODO: Complete member initialization
     this._elementType = context.EntityType;
     this._Joins = context.Joins;
     Columns = new List<Column>();
 }
Пример #13
0
 public void Dispose()
 {
     if (parent != null)
     {
         parent.prefixGenerator = null;
         parent = null;
     }
 }
Пример #14
0
        public Task Apply(TResult entity, TranslateContext <TInput, TSchema> context)
        {
            var inputValue = _inputProperty.Get(context.Input) ?? ValueList.Missing <TValue>();

            _property.Set(entity, inputValue);

            return(TaskUtil.Completed);
        }
Пример #15
0
        public Task <TranslateResult <TSchema> > Translate(TranslateContext <TSchema> context, TSchema entity)
        {
            if (entity is TInput input)
            {
                return(Translate(context.CreateContext(input)));
            }

            return(Task.FromResult(context.Empty <TSchema>()));
        }
Пример #16
0
        public Task <Value <TValue> > GetProperty(TranslateContext <TInput, TSchema> context)
        {
            if (context.HasInput)
            {
                return(Task.FromResult(_property.Get(context.Input)));
            }

            return(Task.FromResult(Value.Missing <TValue>()));
        }
Пример #17
0
        public Task <TranslateResult <TSchema> > Translate(TranslateContext <TEntity, TSchema> context)
        {
            if (context.HasInput && _filter != null)
            {
                return(GetFilteredResult(context, context.Input));
            }

            return(Task.FromResult(context.Empty <TEntity>()));
        }
Пример #18
0
        async Task <TranslateResult <TSchema> > GetFilteredResult(TranslateContext <TEntity, TSchema> entityContext, TEntity input)
        {
            if (await _filter(entityContext).ConfigureAwait(false))
            {
                return(entityContext.Empty <TEntity>());
            }

            return(entityContext.Result(input));
        }
Пример #19
0
        public Task <TranslateResult <TSchema> > Translate(TranslateContext <TSchema> context, TSchema entity)
        {
            if (entity is TEntity input)
            {
                return(Translate(context.CreateContext(input)));
            }

            return(Task.FromResult(context.NotTranslated <TEntity>()));
        }
Пример #20
0
        public ResultTranslateResult(TranslateContext <TSchema> context, bool isTranslated = true)
        {
            _result     = default(TResult);
            _resultType = typeof(TResult);

            IsTranslated = isTranslated;

            _context         = context;
            _contextSnapshot = context.CurrentContext;
        }
Пример #21
0
        public ResultTranslateResult(TranslateContext <TSchema> context, TResult result, Type resultType, bool isTranslated = true)
        {
            _result     = result;
            _resultType = resultType;

            IsTranslated = isTranslated;

            _context         = context;
            _contextSnapshot = context.CurrentContext;
        }
Пример #22
0
        public Task Apply(TEntity entity, TranslateContext <TInput, TSchema> context)
        {
            var existing = _readProperty.Get(entity);

            if (existing == null)
            {
                _property.Set(entity, ValueList.Missing <TPropertyEntity>());
            }

            return(TaskUtil.Completed);
        }
Пример #23
0
        public Task <TranslateResult <TSchema> > Translate(TranslateContext <TEntity, TSchema> context)
        {
            if (context.HasInput)
            {
                return(_filter != null
                    ? GetFilteredResult(context)
                    : GetResult(context));
            }

            return(Task.FromResult(context.NotTranslated <TEntity>()));
        }
Пример #24
0
        bool TranslateContext <TInput, TSchema> .TryGetContext <T>(out TranslateContext <T, TSchema> context)
        {
            if (HasInput)
            {
                context = new EntityTranslateContext <T, TSchema>(_context, Source, (T)Input, true, Index);
                return(true);
            }

            context = new EntityTranslateContext <T, TSchema>(_context, Source, default(T), false, Index);
            return(false);
        }
Пример #25
0
        public Task Apply(TEntity entity, TranslateContext <TInput, TSchema> context)
        {
            var inputValue = context.HasInput ? _inputProperty.Get(context.Input) : Value.Missing <TPropertyEntity>();

            var subContext = context.CreateValueContext(inputValue);

            var resultValue = _valueProvider(subContext) ?? Value.Missing <TPropertyEntity>();

            _property.Set(entity, resultValue);

            return(TaskUtil.Completed);
        }
        /// <summary>
        /// 访问 IDbQueryable.Contains 方法
        /// </summary>
        /// <param name="m">方法表达式</param>
        protected override Expression VisitQueryableContains(MethodCallExpression m)
        {
            ITranslateContext context = _builder.TranslateContext;
            var subquery = m.Arguments[0].Evaluate().Value as DbQueryable;

            subquery.Parameterized = _builder.Parameterized;

            // 可能会有几级嵌套,这里用 Builder.Ident 标记是第几层级
            string[] subs       = new[] { "p", "u", "v", "w", "x" };
            var      newContext = context != null?TranslateContext.Copy(context, subs[_builder.Indent]) : null;

            var  cmd      = subquery.Translate(_builder.Indent + 1, false, newContext) as DbSelectCommand;
            bool isDelete = context != null && ((MySqlTranslateContext)context).IsDelete;

            if (this.NotOperands != null && this.NotOperands.Contains(m))
            {
                _builder.Append("NOT ");
            }
            _builder.Append("EXISTS(");

            if (isDelete)
            {
                _builder.Append("SELECT 1 FROM(");
                _builder.Append(cmd.CommandText);
                _builder.Append(string.Format(") {0}0 WHERE ", subs[_builder.Indent]));

                _builder.Append(cmd.SelectedColumnText);
                _builder.Append(" = ");
                _visitor.Visit(m.Arguments[1]);
                _builder.Append(")");
            }
            else
            {
                _builder.Append(cmd.CommandText);

                if (cmd.WhereFragment.Length > 0)
                {
                    _builder.Append(" AND ");
                }
                else
                {
                    _builder.Append("WHERE ");
                }

                _builder.Append(cmd.SelectedColumnText);
                _builder.Append(" = ");
                _visitor.Visit(m.Arguments[1]);
                _builder.Append(")");
            }

            return(m);
        }
Пример #27
0
        public void CreateDatabase()
        {
            var db = new TranslateContext()
            {
                Log = Console.Out,
            };

            if (db.DatabaseExists())
            {
                db.DeleteDatabase();
            }
            db.CreateDatabase();
        }
Пример #28
0
        public async Task <Entity <TEntity> > GetProperty(TranslateContext <TInput, TSchema> context)
        {
            var entity = await _provider.GetProperty(context).ConfigureAwait(false);

            var entityContext = context.CreateContext(entity.Value);

            var result = await _translator.Translate(entityContext).ConfigureAwait(false);

            if (result.TryGetEntity <TEntity>(0, out var entityResult))
            {
                return(new EntityProperty <TEntity>(entityResult));
            }

            return(new EntityProperty <TEntity>());
        }
Пример #29
0
        async Task <TranslateResult <TSchema> > GetResult(TranslateContext <TEntity, TSchema> entityContext)
        {
            if (_observers.Count > 0)
            {
                await _observers.PreTranslateEntity(entityContext.Input, entityContext).ConfigureAwait(false);
            }

            var translateResult = entityContext.Result(entityContext.Input);

            if (_observers.Count > 0)
            {
                await _observers.PostTranslateEntity(translateResult, entityContext).ConfigureAwait(false);
            }

            return(translateResult);
        }
Пример #30
0
        public async Task Apply(TResult entity, TranslateContext <TInput, TSchema> context)
        {
            var inputValue = _inputProperty.Get(context.Input) ?? Value.Missing <TEntity>();

            TranslateContext <TEntity, TSchema> inputContext = context.CreateContext(inputValue.Value);

            var result = await _entityTranslator.Translate(inputContext).ConfigureAwait(false);

            if (result.HasResult && result.TryGetEntity(0, out TEntity resultEntity))
            {
                _property.Set(entity, new ConstantValue <TEntity>(resultEntity));
            }
            else
            {
                _property.Set(entity, Value.Missing <TEntity>());
            }
        }
Пример #31
0
        public async Task <TranslateResult <TSchema> > Translate(TranslateContext <TSchema> context)
        {
            var results = context.CreateResultCollection();

            var index = 0;

            while (context.Source.TryGetEntity(index, out TSchema entity))
            {
                var entityResult = await TranslateEntity(context, entity).ConfigureAwait(false);

                results.Add(entityResult);

                index++;
            }

            return(results.ToResult());
        }
Пример #32
0
        /// <summary>
        /// 访问 IDbQueryable.Contains 方法
        /// </summary>
        /// <param name="m">字段或属性表达式</param>
        protected override Expression VisitQueryableContains(MethodCallExpression m)
        {
            ITranslateContext context  = _builder.TranslateContext;
            DbQueryable       subquery = m.Arguments[0].Evaluate().Value as DbQueryable;

            subquery.Parameterized = _builder.Parameterized;

            // 可能会有几级嵌套,这里用 Builder.Ident 标记是第几层级
            string[] subs       = new[] { "p", "u", "v", "w", "x" };
            var      newContext = context != null?TranslateContext.Copy(context, subs[_builder.Indent]) : null;

            bool isDelete = context != null && ((SQLiteTranslateContext)context).IsDelete;
            var  cmd      = subquery.Translate(_builder.Indent + 1, false, newContext) as DbSelectCommand;

            if (this.NotOperands != null && this.NotOperands.Contains(m))
            {
                _builder.Append("NOT ");
            }
            _builder.Append("EXISTS(");
            _builder.Append(cmd.CommandText);

            if (((DbSelectCommand)cmd).WhereFragment.Length > 0)
            {
                _builder.Append(" AND ");
            }
            else
            {
                _builder.Append("WHERE ");
            }
            _builder.Append(cmd.SelectedColumnText);
            _builder.Append(" = ");

            // exists 不能用别名
            if (isDelete)
            {
                var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(((MemberExpression)m.Arguments[1]).Expression.Type);
                _builder.AppendTable(typeRuntime.TableSchema, typeRuntime.TableName, typeRuntime.IsTemporary);
                _builder.Append('.');
            }

            _visitor.Visit(m.Arguments[1]);
            _builder.Append(")");

            return(m);
        }
        public NoLockExpressionVisitor(TranslateContext context):base(context)
        {

        }
Пример #34
0
 public JoinExpressionVisitor(TranslateContext context)
     : base(context)
 {
     Joins = context.Joins;
     ExtraObject = new List<string>();
 }
 public MethodCallExpressionVisitor(TranslateContext context)
     : base(context)
 {
     // TODO: Complete member initialization
     this._joins = context.Joins;
 }
 public MemberExpressionVisitor(TranslateContext context)
     : base(context)
 {
     _Joins = context.Joins;
     SelectedColumn = new Column();
 }
 public BinaryExpressionVisitor(TranslateContext context)
     : base(context)
 {
     this._joins = context.Joins;
 }
Пример #38
0
        internal void Parse(Expression expression)
        {
            _distinct = false;
            _isCallAny = false;
            _isDelete = false;
            _isUpdate = false;
            UpdateResult = new Dictionary<string, object>();
            _aggregationExpressions = new Dictionary<string, Expression>();
            Conditions = new List<Token>();
            _nolockExpressions = new List<Expression>();
            NoLockTables = new List<string>();
            _aggregationColumns = new Dictionary<string, Column>();
            _sortExpressions = new List<KeyValuePair<string, Expression>>();
            _sortColumns = new List<KeyValuePair<string, Column>>();
            _context = new TranslateContext();
            _take = -1;
            _skip = -1;
            _context.EntityType = ElementType;
            Visit(expression);
            if (_aggregationColumns.Count > 1)
            {
                throw new Exception();
            }
            if (_skip != -1 && _take != -1 && !_sortExpressions.Any())
            {
                throw new Exception("分页必须进行排序");
            }

            #region 解析Join子句
            foreach (MethodCallExpression node in _joinExpressions)
            {
                VisitJoinExpression(node);
                break;
            }
            #endregion

            #region 解析Select子句
            if (_selectExpression != null)
            {
                var unary = _selectExpression as UnaryExpression;
                var lambdaExp = unary.Operand as LambdaExpression;
                //var newExp = lambdaExp.Body as NewExpression;
                //if (newExp == null)
                //{
                //    throw new NotSupportedException("Select子句中只能使用new表达式");
                //}
                VisitSelectExpression(lambdaExp.Body);
            }
            else
            {
                VisitSelectExpression(null);
            }
            #endregion


            #region 解析Where子句
            foreach (MethodCallExpression node in _whereExpressions)
            {
                var unary = node.Arguments[1] as UnaryExpression;
                var operand = unary.Operand as LambdaExpression;
                var body = operand.Body;
                if (body is ConstantExpression)
                {
                    var constExp = body as ConstantExpression;
                    if ((bool)constExp.Value == false)
                    {
                        Conditions.Add(Token.Create(false));
                    }
                }
                else
                {
                    VisitWhereExpression(body);
                }
            }
            #endregion

            #region 解析Lock子句
            foreach (var nolockExpression in _nolockExpressions)
            {
                VisitNoLockExpression(nolockExpression);
            }
            #endregion

            #region 解析Sum、Avg等子句
            foreach (var aggreationExpression in _aggregationExpressions)
            {
                VisitAggreationExpression(aggreationExpression);
            }
            #endregion

            #region 解析Order By子句
            foreach (var sortExpression in _sortExpressions)
            {
                VisitSortExpression(sortExpression);
            }
            #endregion

            VisitUpdateExpression(_updateExpression);
        }
Пример #39
0
 public ExpressionVisitorBase(TranslateContext context)
 {
     _context = context;
 }