Пример #1
0
        public SqlString ToSqlString(bool isCount = false)
        {
            var dataProvider = SlipstreamEnvironment.RootContainer.Resolve <IDataProvider>();
            var qs           = new QuerySelect(dataProvider.Dialect);

            SqlString columnsFragment = null;

            if (isCount)
            {
                columnsFragment = new SqlString("count(", MainTableAlias + '.' + AbstractModel.IdFieldName, ")");
            }
            else
            {
                columnsFragment = new SqlString(MainTableAlias + '.' + AbstractModel.IdFieldName);
            }
            qs.AddSelectFragmentString(columnsFragment);
            qs.Distinct = false;

            var fromClauseBuilder = new SqlStringBuilder();

            for (int i = 0; i < this.fromJoins.Count; i++)
            {
                if (this.fromJoins.Count > 1 && i > 0)
                {
                    fromClauseBuilder.Add(", ");
                }
                else
                {
                    fromClauseBuilder.Add(" ");
                }
                fromClauseBuilder.Add(this.fromJoins[i]);
                fromClauseBuilder.Add(" ");
            }
            var fromClause = fromClauseBuilder.ToSqlString();

            qs.JoinFragment.AddJoins(fromClause, SqlString.Empty);

            foreach (var innerJoin in this.innerJoins)
            {
                qs.JoinFragment.AddJoin(
                    innerJoin.Table, innerJoin.Alias,
                    new string[] { innerJoin.FkColumn },
                    new string[] { innerJoin.PkColumn }, JoinType.InnerJoin);
            }

            foreach (var outerJoin in this.outerJoins)
            {
                qs.JoinFragment.AddJoin(
                    outerJoin.Table, outerJoin.Alias,
                    new string[] { outerJoin.FkColumn },
                    new string[] { outerJoin.PkColumn }, JoinType.LeftOuterJoin);
            }

            if (this.whereRestrictions.Count > 0)
            {
                var whereTokens = new SqlString[] { this.whereRestrictions.ToSqlString() };
                qs.SetWhereTokens((ICollection)whereTokens);
            }

            if (!isCount)
            {
                foreach (var o in this.orders)
                {
                    var orderBySql = ' ' + MainTableAlias + '.' + o.Field + ' ' + o.Order.ToSql();
                    qs.AddOrderBy(orderBySql);
                }
            }

            return(qs.ToQuerySqlString());
        }