public void Compile_ShouldReturnFromExames()
        {
            var from = new FromExpression(typeof(ExameMetadata));

            _compiler.CompileFrom(from);
            Assert.AreEqual("FROM EXAMES ", _compiler.Compiled());
        }
Exemple #2
0
 public void Compile(FromExpression query)
 {
     CheckMalformed(query);
     Compile(query.Select);
     CompileFrom(query);
     Compile(query.Joins);
     Compile(query.Where);
 }
        public IList <Tuple <TSource, TTarget> > Retrieve <TSource, TTarget>(FromExpression <TSource> fromCondition, WhereExpression <TSource> whereCondition, TransactionContext transContext)
            where TSource : DatabaseEntity, new()
            where TTarget : DatabaseEntity, new()
        {
            if (whereCondition == null)
            {
                whereCondition = Where <TSource>();
            }

            switch (fromCondition.JoinType)
            {
            case SqlJoinType.LEFT:
                whereCondition.And(t => t.Deleted == false);
                break;

            case SqlJoinType.RIGHT:
                whereCondition.And <TTarget>(t => t.Deleted == false);
                break;

            case SqlJoinType.INNER:
                whereCondition.And(t => t.Deleted == false).And <TTarget>(t => t.Deleted == false);
                break;

            case SqlJoinType.FULL:
                break;

            case SqlJoinType.CROSS:
                whereCondition.And(t => t.Deleted == false).And <TTarget>(t => t.Deleted == false);
                break;
            }

            IList <Tuple <TSource, TTarget> > result = null;
            IDataReader       reader    = null;
            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <TSource>();

            try
            {
                IDbCommand command = _sqlBuilder.CreateRetrieveCommand <TSource, TTarget>(fromCondition, whereCondition);
                reader = _databaseEngine.ExecuteCommandReader(transContext?.Transaction, entityDef.DatabaseName, command, transContext != null);
                result = _modelMapper.ToList <TSource, TTarget>(reader);
            }
            //catch (DbException ex)
            //{
            //    result = new List<Tuple<TSource, TTarget>>();

            //    _logger.LogCritical(ex.Message);
            //}
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }

            return(result);
        }
Exemple #4
0
        /// <summary>
        /// GetByUserGuidAsync
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="transContext"></param>
        /// <returns></returns>
        /// <exception cref="DatabaseException"></exception>
        public Task <IEnumerable <TRole> > GetByUserGuidAsync <TRole, TRoleOfUser>(string userGuid, TransactionContext?transContext = null)
            where TRole : IdentityRole, new()
            where TRoleOfUser : IdentityRoleOfUser, new()
        {
            FromExpression <TRole> from = _database.From <TRole>().RightJoin <TRoleOfUser>((r, ru) => r.Guid == ru.RoleGuid);

            WhereExpression <TRole> where = _database.Where <TRole>().And <IdentityRoleOfUser>(ru => ru.UserGuid == userGuid);

            return(_database.RetrieveAsync(from, where, transContext));
        }
Exemple #5
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = ValueExpression.GetHashCode();
         hashCode = (hashCode * 397) ^ FromExpression.GetHashCode();
         hashCode = (hashCode * 397) ^ ForExpression.GetHashCode();
         return(hashCode);
     }
 }
        public IList <Tuple <TSource, TTarget> > Page <TSource, TTarget>(FromExpression <TSource> fromCondition, WhereExpression <TSource> whereCondition, long pageNumber, long perPageCount, TransactionContext transContext)
            where TSource : DatabaseEntity, new()
            where TTarget : DatabaseEntity, new()
        {
            if (whereCondition == null)
            {
                whereCondition = Where <TSource>();
            }

            whereCondition.Limit((pageNumber - 1) * perPageCount, perPageCount);

            return(Retrieve <TSource, TTarget>(fromCondition, whereCondition, transContext));
        }
Exemple #7
0
        public void GetWhoHasRoles()
        {
            FromExpression <UserRole> from = _db.From <UserRole>().LeftJoin <Role>((ur, r) => ur.RoleGuid == r.Guid).LeftJoin <User>((ur, u) => ur.UserGuid == u.Guid);

            var resultList = _db.RetrieveAsync <UserRole, User, Role>(from, null, null).Result;

            foreach (var item in resultList)
            {
                _output.WriteLine(JsonUtil.ToJson(item));
            }

            Assert.NotEmpty(resultList);
        }
Exemple #8
0
        public void GetWhoHasClaims()
        {
            FromExpression <UserClaim> from = _db.From <UserClaim>().LeftJoin <User>((uc, u) => uc.UserGuid == u.Guid);


            var resultList = _db.RetrieveAsync <UserClaim, User>(from, null, null).Result;

            foreach (var item in resultList)
            {
                _output.WriteLine(JsonUtil.ToJson(item));
            }

            Assert.NotEmpty(resultList);
        }
Exemple #9
0
        public string BuildExpression(Dictionary <string, Expression> selectExpressions)
        {
            var anonymousTypeCreateExpression = new AnonymousTypeCreateExpression();
            var crrv = new ChangeRootReferenceVisitor(FromIdentifier);

            foreach (var curExpr in selectExpressions.OrderBy(x => x.Key))
            {
                curExpr.Value.AcceptVisitor(crrv);
                anonymousTypeCreateExpression.Initializers.Add(
                    new AssignmentExpression(new IdentifierExpression(curExpr.Key), curExpr.Value.Clone()));
            }
            if (FromExpression == null)
            {
                FromExpression = new IdentifierExpression();
            }

            var queryExpr = new QueryExpression
            {
                Clauses =
                {
                    new QueryFromClause
                    {
                        Identifier = "doc",
                        Expression = FromExpression.Clone()
                    },
                    new QuerySelectClause
                    {
                        Expression = anonymousTypeCreateExpression.Clone()
                    }
                }
            };

            FromIdentifier = "doc";

            var printer        = new StringWriter();
            var printerVisitor = new CSharpOutputVisitor(printer, FormattingOptionsFactory.CreateSharpDevelop());

            queryExpr.AcceptVisitor(printerVisitor);

            var format = printer.GetStringBuilder().ToString();

            if (format.Substring(0, 3) == "\r\n\t")
            {
                format = format.Remove(0, 3);
            }
            format = format.Replace("\r\n\t", "\n");
            return(format);
        }
        public IList <T> Retrieve <T>(SelectExpression <T> selectCondition, FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
            where T : DatabaseEntity, new()
        {
            #region Argument Adjusting

            if (selectCondition != null)
            {
                selectCondition.Select(t => t.Id).Select(t => t.Deleted).Select(t => t.LastTime).Select(t => t.LastUser).Select(t => t.Version);
            }

            if (whereCondition == null)
            {
                whereCondition = Where <T>();
            }

            whereCondition.And(t => t.Deleted == false);

            #endregion

            IList <T>         result    = null;
            IDataReader       reader    = null;
            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            try
            {
                IDbCommand command = _sqlBuilder.CreateRetrieveCommand <T>(selectCondition, fromCondition, whereCondition);
                reader = _databaseEngine.ExecuteCommandReader(transContext?.Transaction, entityDef.DatabaseName, command, transContext != null);
                result = _modelMapper.ToList <T>(reader);
            }
            //catch (DbException ex)
            //{
            //    result = new List<T>();
            //    _logger.LogCritical(ex.Message);
            //}
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }

            return(result);
        }
        public T Scalar <T>(SelectExpression <T> selectCondition, FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
            where T : DatabaseEntity, new()
        {
            IList <T> result = Retrieve <T>(selectCondition, fromCondition, whereCondition, transContext);

            if (result == null || result.Count == 0)
            {
                return(null);
            }

            if (result.Count > 1)
            {
                //_logger.LogCritical(0, "retrieve result not one, but many." + typeof(T).FullName, null);

                throw new DatabaseException($"Scalar retrieve return more than one result. Select:{selectCondition.ToString()}, From:{fromCondition.ToString()}, Where:{whereCondition.ToString()}");
            }

            return(result[0]);
        }
        public override void CheckSemantics(TigerScope scope, Report report)
        {
            ContainingScope = scope;

            //Check children
            IdNode.CheckSemantics(scope, report);
            FromExpression.CheckSemantics(scope, report);
            ToExpression.CheckSemantics(scope, report);

            if (!IdNode.IsOK || !FromExpression.IsOK || !ToExpression.IsOK)
            {
                return;
            }

            //Check loop bounds type
            if (!TigerType.AreCompatible(FromExpression.TigerType, TigerType.Int) || !TigerType.AreCompatible(ToExpression.TigerType, TigerType.Int))
            {
                report.AddError(!TigerType.AreCompatible(FromExpression.TigerType, TigerType.Int)
                    ? SemanticErrors.InvalidForBoundType(FromExpression, FromExpression.TigerType)
                    : SemanticErrors.InvalidForBoundType(ToExpression, ToExpression.TigerType));
                return;
            }

            IsOK = true;

            //Define new scope
            TigerScope childScope = new TigerScope(scope, "For");

            VariableInfo = childScope.DefineVariable(IdNode.Name, TigerType.Int, ContainingScope, false);

            DoInstruction.CheckSemantics(childScope, report);

            if (!DoInstruction.IsOK)
            {
                return;
            }

            if (!TigerType.AreCompatible(DoInstruction.TigerType, TigerType.Void))
            {
                report.AddError(SemanticErrors.InvalidForBodyType(DoInstruction));
                IsOK = false;
            }
        }
        public Tuple <TSource, TTarget> Scalar <TSource, TTarget>(FromExpression <TSource> fromCondition, WhereExpression <TSource> whereCondition, TransactionContext transContext)
            where TSource : DatabaseEntity, new()
            where TTarget : DatabaseEntity, new()
        {
            IList <Tuple <TSource, TTarget> > result = Retrieve <TSource, TTarget>(fromCondition, whereCondition, transContext);

            if (result == null || result.Count == 0)
            {
                return(null);
            }

            if (result.Count > 1)
            {
                throw new DatabaseException($"Scalar retrieve return more than one result. From:{fromCondition.ToString()}, Where:{whereCondition.ToString()}");
                //_logger.LogCritical(0, "retrieve result not one, but many." + typeof(TSource).FullName, null);
                //return null;
            }

            return(result[0]);
        }
Exemple #14
0
        public Task <T> ScalarAsync <T>(SelectExpression <T> selectCondition, FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
            where T : DatabaseEntity, new()
        {
            return(RetrieveAsync <T>(selectCondition, fromCondition, whereCondition, transContext)
                   .ContinueWith(t => {
                IList <T> lst = t.Result;

                if (lst == null || lst.Count == 0)
                {
                    return default;
                }

                if (lst.Count > 1)
                {
                    throw new DatabaseException($"Scalar retrieve return more than one result. Select:{selectCondition.ToString()}, From:{fromCondition.ToString()}, Where:{whereCondition.ToString()}");
                    //_logger.LogCritical(0, "retrieve result not one, but many." + typeof(T).FullName, null);
                    //return default;
                }

                return lst[0];
            }, TaskScheduler.Default));
        }
        public IList <T> Page <T>(SelectExpression <T> selectCondition, FromExpression <T> fromCondition, WhereExpression <T> whereCondition, long pageNumber, long perPageCount, TransactionContext transContext)
            where T : DatabaseEntity, new()
        {
            #region Argument Adjusting

            if (selectCondition != null)
            {
                selectCondition.Select(t => t.Id).Select(t => t.Deleted).Select(t => t.LastTime).Select(t => t.LastUser).Select(t => t.Version);
            }

            if (whereCondition == null)
            {
                whereCondition = Where <T>();
            }

            whereCondition.And(t => t.Deleted == false);

            #endregion

            whereCondition.Limit((pageNumber - 1) * perPageCount, perPageCount);

            return(Retrieve <T>(selectCondition, fromCondition, whereCondition, transContext));
        }
Exemple #16
0
        public Task <Tuple <TSource, TTarget> > ScalarAsync <TSource, TTarget>(FromExpression <TSource> fromCondition, WhereExpression <TSource> whereCondition, TransactionContext transContext)
            where TSource : DatabaseEntity, new()
            where TTarget : DatabaseEntity, new()
        {
            return(RetrieveAsync <TSource, TTarget>(fromCondition, whereCondition, transContext)
                   .ContinueWith(t =>
            {
                IList <Tuple <TSource, TTarget> > lst = t.Result;

                if (lst == null || lst.Count == 0)
                {
                    return null;
                }

                if (lst.Count > 1)
                {
                    throw new DatabaseException($"Scalar retrieve return more than one result. From:{fromCondition.ToString()}, Where:{whereCondition.ToString()}");
                    //_logger.LogCritical(0, "retrieve result not one, but many." + typeof(TSource).FullName, null);
                    //return null;
                }

                return lst[0];
            }, TaskScheduler.Default));
        }
Exemple #17
0
 public QueryBuilder From(FromExpression from)
 {
     entityMap[nameof(From)] = from;
     return(this);
 }
 public string ToString(string db, int index) => $"{JoinType.ToString().ToUpper()} JOIN {FromExpression.GetText(db)} AS t{index} ON {JoinExpression.Text}";
Exemple #19
0
 public void CompileFrom(FromExpression from)
 => _builder.Append(FromExpression.FROM).AppendFormat(" {0} ", GetTableName(from.Table));
Exemple #20
0
        public async Task <long> CountAsync <T>(SelectExpression <T> selectCondition, FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
            where T : DatabaseEntity, new()
        {
            #region Argument Adjusting

            if (selectCondition != null)
            {
                selectCondition.Select(t => t.Id).Select(t => t.Deleted).Select(t => t.LastTime).Select(t => t.LastUser).Select(t => t.Version);
            }

            if (whereCondition == null)
            {
                whereCondition = Where <T>();
            }

            whereCondition.And(t => t.Deleted == false);

            #endregion

            long count = -1;

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();
            try
            {
                IDbCommand command  = _sqlBuilder.CreateCountCommand(fromCondition, whereCondition);
                object     countObj = await _databaseEngine.ExecuteCommandScalarAsync(transContext?.Transaction, entityDef.DatabaseName, command, transContext != null).ConfigureAwait(false);

                count = Convert.ToInt32(countObj, GlobalSettings.Culture);
            }
            catch (DbException ex)
            {
                throw ex;// _logger.LogCritical(ex.Message);
            }

            return(count);
        }
Exemple #21
0
 public Task <T> ScalarAsync <T>(FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
     where T : DatabaseEntity, new()
 {
     return(ScalarAsync(null, fromCondition, whereCondition, transContext));
 }
 public long Count <T>(FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
     where T : DatabaseEntity, new()
 {
     return(Count(null, fromCondition, whereCondition, transContext));
 }
 public IList <T> Page <T>(FromExpression <T> fromCondition, WhereExpression <T> whereCondition, long pageNumber, long perPageCount, TransactionContext transContext)
     where T : DatabaseEntity, new()
 {
     return(Page(null, fromCondition, whereCondition, pageNumber, perPageCount, transContext));
 }
 public IList <T> Retrieve <T>(FromExpression <T> fromCondition, WhereExpression <T> whereCondition, TransactionContext transContext)
     where T : DatabaseEntity, new()
 {
     return(Retrieve(null, fromCondition, whereCondition, transContext));
 }
Exemple #25
0
 static _Nullable()
 {
     _Nullable <T> .HasValue = FromExpression.ToProperty <T?, bool>(nullable => nullable.HasValue);
     _Nullable <T> .Value    = FromExpression.ToProperty <T?, T>(nullable => nullable.Value);
 }
        public IList <TSelect> Retrieve <TSelect, TFrom, TWhere>(SelectExpression <TSelect> selectCondition, FromExpression <TFrom> fromCondition, WhereExpression <TWhere> whereCondition, TransactionContext transContext = null)
            where TSelect : DatabaseEntity, new()
            where TFrom : DatabaseEntity, new()
            where TWhere : DatabaseEntity, new()
        {
            #region Argument Adjusting

            if (selectCondition != null)
            {
                selectCondition.Select(t => t.Id).Select(t => t.Deleted).Select(t => t.LastTime).Select(t => t.LastUser).Select(t => t.Version);
            }

            if (whereCondition == null)
            {
                whereCondition = Where <TWhere>();
            }

            whereCondition.And(t => t.Deleted == false).And <TSelect>(ts => ts.Deleted == false).And <TFrom>(tf => tf.Deleted == false);

            #endregion

            IList <TSelect>   result    = null;
            IDataReader       reader    = null;
            DatabaseEntityDef selectDef = _entityDefFactory.GetDef <TSelect>();

            try
            {
                IDbCommand command = _sqlBuilder.CreateRetrieveCommand(selectCondition, fromCondition, whereCondition);
                reader = _databaseEngine.ExecuteCommandReader(transContext?.Transaction, selectDef.DatabaseName, command, transContext != null);
                result = _modelMapper.ToList <TSelect>(reader);
            }
            //catch (DbException ex)
            //{
            //    throw ex;
            //}
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }

            return(result);
        }
 static _KeyValuePair()
 {
     _KeyValuePair <TKey, TValue> .Key   = FromExpression.ToProperty <KeyValuePair <TKey, TValue>, TKey>(entry => entry.Key);
     _KeyValuePair <TKey, TValue> .Value = FromExpression.ToProperty <KeyValuePair <TKey, TValue>, TValue>(entry => entry.Value);
     _KeyValuePair <TKey, TValue> .Ctor  = FromExpression.ToConstructor <TKey, TValue, KeyValuePair <TKey, TValue> >((key, value) => new KeyValuePair <TKey, TValue>(key, value));
 }