public MemoryDbDataReader.ResultBatch Execute(Dictionary <string, Table> tables, RawData rawData, SqlQuerySpecification sqlQuery, SqlOrderByClause orderByClause = null) { if (sqlQuery.FromClause != null) { rawData.AddTablesFromClause(sqlQuery.FromClause, tables); if (sqlQuery.WhereClause != null) { rawData.ExecuteWhereClause(sqlQuery.WhereClause); } } else { // We do not select data from any table, so we insert an empty row to trigger a result in AddData(). rawData.RawRowList.Add(new RawTableJoinRow()); } var batch = InitializeBatch(rawData, sqlQuery); if (sqlQuery.GroupByClause != null) { rawData.AddGroupByClause(sqlQuery.GroupByClause); } rawData.HavingClause = sqlQuery.HavingClause?.Expression; rawData.SortOrder = GetSortOrder(orderByClause, sqlQuery); new QueryResultBuilder(rawData, sqlQuery.SelectClause.IsDistinct).AddData(batch); if (sqlQuery.IntoClause != null) { InsertIntoTable(sqlQuery.IntoClause, tables, batch); } return(batch); }
public virtual void Visiting(SqlOrderByClause orderByClause) { if (orderByClause.SqlOrderByItems.Count > 0) { sqlBuilder.Append(" Order By "); } }
private SqlOrderByClause Substitute(SqlSelectSpec spec, SqlIdentifier inputParam, SqlOrderByClause orderByClause) { if (orderByClause == null) { return(null); } if (spec is SqlSelectStarSpec) { return(orderByClause); } SqlSelectValueSpec selValue = spec as SqlSelectValueSpec; if (selValue != null) { SqlScalarExpression replaced = selValue.Expression; SqlOrderByItem[] substitutedItems = new SqlOrderByItem[orderByClause.OrderByItems.Length]; for (int i = 0; i < substitutedItems.Length; ++i) { SqlScalarExpression substituted = SqlExpressionManipulation.Substitute(replaced, inputParam, orderByClause.OrderByItems[i].Expression); substitutedItems[i] = SqlOrderByItem.Create(substituted, orderByClause.OrderByItems[i].IsDescending); } SqlOrderByClause result = SqlOrderByClause.Create(substitutedItems); return(result); } throw new DocumentQueryException("Unexpected SQL select clause type: " + spec.GetType()); }
public MemoryDbDataReader.ResultBatch Execute(RawData rawData, Dictionary <string, Table> tables, SqlQueryExpression expression, SqlOrderByClause orderByClause = null) { switch (expression) { case SqlBinaryQueryExpression binaryQueryExpression: { var commandLeft = new MemoryDbCommand(_Command); var rawDataLeft = new RawData(commandLeft); var batchLeft = Execute(rawDataLeft, tables, binaryQueryExpression.Left); var commandRight = new MemoryDbCommand(_Command); var rawDataRight = new RawData(commandRight); var batchRight = Execute(rawDataRight, tables, binaryQueryExpression.Right); var batch = MergeBatches(batchLeft, batchRight, binaryQueryExpression.Operator); if (orderByClause != null) { var resultRawData = new RawData(_Command, batch); new QueryResultBuilder(resultRawData).AddOrderedResultRows(batch, orderByClause.Items); } return(batch); } case SqlQuerySpecification sqlQuery: { return(Execute(tables, rawData, sqlQuery, orderByClause)); } default: throw new NotImplementedException($"Query expressions of type {expression} are currently not implemented."); } }
public virtual void Visited(SqlOrderByClause orderByClause) { if (orderByClause.SqlOrderByItems.Count > 0) { sqlBuilder.Length -= 2; } }
public override SqlObject Visit(SqlOrderByClause sqlOrderByClause) { SqlOrderByItem[] items = new SqlOrderByItem[sqlOrderByClause.OrderByItems.Length]; for (int i = 0; i < sqlOrderByClause.OrderByItems.Length; i++) { items[i] = sqlOrderByClause.OrderByItems[i].Accept(this) as SqlOrderByItem; } return(SqlOrderByClause.Create(items)); }
public override int Visit(SqlOrderByClause sqlOrderByClause) { int hashCode = SqlOrderbyClauseHashCode; for (int i = 0; i < sqlOrderByClause.OrderByItems.Length; i++) { hashCode = CombineHashes(hashCode, sqlOrderByClause.OrderByItems[i].Accept(this)); } return(hashCode); }
public SqlSelectQuery <T> OrderBy(Expression <Func <T, object> > columns) { if (columns == null) { return(this); } var clause = new SqlOrderByClause(columns); Clauses.Add(clause); return(this); }
public override void Visit(SqlOrderByClause sqlOrderByClause) { this.writer.Write("ORDER BY "); sqlOrderByClause.OrderByItems[0].Accept(this); for (int i = 1; i < sqlOrderByClause.OrderByItems.Length; i++) { this.writer.Write(", "); sqlOrderByClause.OrderByItems[i].Accept(this); } }
public QueryUnderConstruction AddOrderByClause(SqlOrderByClause orderBy, TranslationContext context) { QueryUnderConstruction result = context.PackageCurrentQueryIfNeccessary(); result.orderByClause = orderBy; foreach (Binding binding in context.CurrentSubqueryBinding.TakeBindings()) { result.AddBinding(binding); } return(result); }
public SqlSelectQuery <T> OrderBy(string columns) { if (columns == null) { return(this); } var exp = Expression.Constant(columns); var clause = new SqlOrderByClause(exp); Clauses.Add(clause); return(this); }
private static SqlOrderByItemCollection GetSortOrder(SqlOrderByClause orderByClause, SqlQuerySpecification sqlQuery) { if (sqlQuery.OrderByClause != null && orderByClause == null) { orderByClause = sqlQuery.OrderByClause; if (IsPartialQuery(sqlQuery.Parent) && IsMissingTopOffsetOrForXml(sqlQuery)) { throw new SqlOrderByException( ); } } return(orderByClause?.Items); }
public QueryUnderConstruction UpdateOrderByClause(SqlOrderByClause thenBy, TranslationContext context) { List <SqlOrderByItem> items = new List <SqlOrderByItem>(context.currentQuery.orderByClause.OrderByItems); items.AddRange(thenBy.OrderByItems); context.currentQuery.orderByClause = SqlOrderByClause.Create(items.ToImmutableArray()); foreach (Binding binding in context.CurrentSubqueryBinding.TakeBindings()) { context.currentQuery.AddBinding(binding); } return(context.currentQuery); }
public override SqlObject VisitOrder_by_clause([NotNull] sqlParser.Order_by_clauseContext context) { Contract.Requires(context != null); List <SqlOrderByItem> orderByItems = new List <SqlOrderByItem>(); foreach (sqlParser.Order_by_itemContext orderByItemContext in context.order_by_items().order_by_item()) { SqlOrderByItem orderByItem = (SqlOrderByItem)this.VisitOrder_by_item(orderByItemContext); orderByItems.Add(orderByItem); } return(SqlOrderByClause.Create(orderByItems.ToImmutableArray())); }
public override bool Visit(SqlOrderByClause first, SqlObject secondAsObject) { if (!(secondAsObject is SqlOrderByClause second)) { return(false); } if (!SequenceEquals(first.OrderByItems, second.OrderByItems)) { return(false); } return(true); }
public override string ToString() { var strSql = new StringBuilder(); var select = Clauses.FirstOrDefault(c => c is SqlSelectClause <T>); var where = Clauses.FirstOrDefault(c => c is SqlWhereClause); var groupBy = Clauses.FirstOrDefault(c => c is SqlGroupByClause); var having = Clauses.FirstOrDefault(c => c is SqlHavingClause); var orderBy = Clauses.FirstOrDefault(c => c is SqlOrderByClause); var offset = Clauses.FirstOrDefault(c => c is SqlRowOffsetClause); var fetch = Clauses.FirstOrDefault(c => c is SqlRowFetchNextClause); if (select != null) { strSql.Append($"{select}"); } if (where != null) { strSql.Append($" {where}"); } if (groupBy != null) { strSql.Append($" {groupBy}"); if (having != null) { strSql.Append($" {having}"); } } if (orderBy == null) { orderBy = new SqlOrderByClause(Expression.Constant(1)); } strSql.Append($" {orderBy}"); if (offset != null) { strSql.Append($" {offset}"); if (fetch != null) { strSql.Append($" {fetch}"); } } return(strSql.ToString()); }
public override void Visit(SqlOrderByClause codeObject) { _stringBuilder.Append("ORDER BY"); using (_stringBuilder.CreateIndentationContext()) { for (var i = 0; i < codeObject.Items.Count; i++) { if (i > 0) { _stringBuilder.Append(","); } _stringBuilder.AppendIndentedLine(); codeObject.Items[i] .Accept(this); } } }
public abstract TResult Visit(SqlOrderByClause sqlObject);
/// <summary> /// Flatten subqueries into a single query by substituting their expressions in the current query. /// </summary> /// <returns>A flattened query.</returns> private QueryUnderConstruction Flatten() { // SELECT fo(y) FROM y IN (SELECT fi(x) FROM x WHERE gi(x)) WHERE go(y) // is translated by substituting fi(x) for y in the outer query // producing // SELECT fo(fi(x)) FROM x WHERE gi(x) AND (go(fi(x)) if (this.inputQuery == null) { // we are flat already if (this.selectClause == null) { // If selectClause doesn't exists, use SELECT v0 where v0 is the input parameter, instead of SELECT *. string parameterName = this.fromParameters.GetInputParameter().Name; SqlScalarExpression parameterExpression = SqlPropertyRefScalarExpression.Create(null, SqlIdentifier.Create(parameterName)); this.selectClause = SqlSelectClause.Create(SqlSelectValueSpec.Create(parameterExpression)); } else { this.selectClause = SqlSelectClause.Create(this.selectClause.SelectSpec, this.topSpec, this.selectClause.HasDistinct); } return(this); } QueryUnderConstruction flatInput = this.inputQuery.Flatten(); SqlSelectClause inputSelect = flatInput.selectClause; SqlWhereClause inputwhere = flatInput.whereClause; // Determine the paramName to be replaced in the current query // It should be the top input parameter name which is not binded in this collection. // That is because if it has been binded before, it has global scope and should not be replaced. string paramName = null; HashSet <string> inputQueryParams = new HashSet <string>(); foreach (Binding binding in this.inputQuery.fromParameters.GetBindings()) { inputQueryParams.Add(binding.Parameter.Name); } foreach (Binding binding in this.fromParameters.GetBindings()) { if (binding.ParameterDefinition == null || inputQueryParams.Contains(binding.Parameter.Name)) { paramName = binding.Parameter.Name; } } SqlIdentifier replacement = SqlIdentifier.Create(paramName); SqlSelectClause composedSelect = this.Substitute(inputSelect, inputSelect.TopSpec ?? this.topSpec, replacement, this.selectClause); SqlWhereClause composedWhere = this.Substitute(inputSelect.SelectSpec, replacement, this.whereClause); SqlOrderByClause composedOrderBy = this.Substitute(inputSelect.SelectSpec, replacement, this.orderByClause); SqlWhereClause and = QueryUnderConstruction.CombineWithConjunction(inputwhere, composedWhere); FromParameterBindings fromParams = QueryUnderConstruction.CombineInputParameters(flatInput.fromParameters, this.fromParameters); SqlOffsetSpec offsetSpec; SqlLimitSpec limitSpec; if (flatInput.offsetSpec != null) { offsetSpec = flatInput.offsetSpec; limitSpec = flatInput.limitSpec; } else { offsetSpec = this.offsetSpec; limitSpec = this.limitSpec; } QueryUnderConstruction result = new QueryUnderConstruction(this.aliasCreatorFunc) { selectClause = composedSelect, whereClause = and, inputQuery = null, fromParameters = flatInput.fromParameters, orderByClause = composedOrderBy ?? this.inputQuery.orderByClause, offsetSpec = offsetSpec, limitSpec = limitSpec, alias = new Lazy <ParameterExpression>(() => this.Alias) }; return(result); }
private static IEnumerable <CosmosElement> ExecuteOrderByClause( IEnumerable <CosmosElement> dataSource, SqlOrderByClause sqlOrderByClause, IReadOnlyDictionary <string, PartitionKeyRange> ridToPartitionKeyRange) { // Sort by the columns left to right SqlOrderByItem firstItem = sqlOrderByClause.OrderByItems[0]; // Since we don't supply an explicit index on the policy undefined items don't show up in the sort order if (sqlOrderByClause.OrderByItems.Length == 1) { dataSource = dataSource.Where(element => firstItem.Expression.Accept( ScalarExpressionEvaluator.Singleton, element) != Undefined); } IOrderedEnumerable <CosmosElement> orderedDataSource; if (firstItem.IsDescending) { orderedDataSource = dataSource.OrderByDescending( element => firstItem.Expression.Accept( ScalarExpressionEvaluator.Singleton, element)); } else { orderedDataSource = dataSource.OrderBy( element => firstItem.Expression.Accept( ScalarExpressionEvaluator.Singleton, element)); } foreach (SqlOrderByItem sqlOrderByItem in sqlOrderByClause.OrderByItems.Skip(1)) { if (sqlOrderByItem.IsDescending) { orderedDataSource = orderedDataSource.ThenByDescending( element => sqlOrderByItem.Expression.Accept( ScalarExpressionEvaluator.Singleton, element)); } else { orderedDataSource = orderedDataSource.ThenBy( element => sqlOrderByItem.Expression.Accept( ScalarExpressionEvaluator.Singleton, element)); } } // Grab from the left most partition first orderedDataSource = orderedDataSource .ThenBy((element) => { string rid = ((CosmosString)((CosmosObject)element)["_rid"]).Value; PartitionKeyRange partitionKeyRange = ridToPartitionKeyRange[rid]; return(partitionKeyRange.MinInclusive); }, StringComparer.Ordinal); // Break all final ties within partition by document id if (firstItem.IsDescending) { orderedDataSource = orderedDataSource .ThenByDescending(element => ResourceId.Parse(((CosmosString)((CosmosObject)element)["_rid"]).Value).Document); } else { orderedDataSource = orderedDataSource .ThenBy(element => ResourceId.Parse(((CosmosString)((CosmosObject)element)["_rid"]).Value).Document); } return(orderedDataSource); }
public abstract void Visit(SqlOrderByClause sqlObject);
public abstract TOutput Visit(SqlOrderByClause sqlObject, TArg input);
public override void Visit(SqlOrderByClause codeObject) { Format(codeObject); }