public SelectStatement ApplyCondition(SelectStatement statement) { var extractor = new CriteriaOperatorExtractor(); extractor.Extract(statement.Condition); traceStatement(statement, "ApplyCondition"); foreach (FilterProviderBase provider in FilterProviderManager.Providers) { FilterProviderBase providerBase = FilterProviderManager.GetFilterProvider(provider.FilterMemberName); if (providerBase!= null) { Tracing.Tracer.LogVerboseValue("providerName", providerBase.Name); IEnumerable<BinaryOperator> binaryOperators = extractor.BinaryOperators.Where( @operator => @operator.RightOperand is OperandValue && ReferenceEquals(((OperandValue) @operator.RightOperand).Value, providerBase.FilterMemberName)); if (!FilterIsShared(statement.TableName,providerBase.Name) && binaryOperators.Count() == 0&&!IsSystemTable(statement.TableName)) { string s = providerBase.FilterValue== null? null:providerBase.FilterValue.ToString(); string nodeAlias = statement.Operands.OfType<QueryOperand>().Where( operand => operand.ColumnName == providerBase.FilterMemberName).Select( operand => operand.NodeAlias).FirstOrDefault() ?? statement.Alias; statement.Condition &= new QueryOperand(providerBase.FilterMemberName, nodeAlias) ==s; Tracing.Tracer.LogVerboseValue("new_statement", statement); } } } return statement; }
private static SelectStatement CreateSelectFromLevelQuery(IEntity rootEntity, DbRelation recursiveRelation, SearchCondition leafFilter, int level, LevelQuerySelectList itemsToSelect) { if (level > Settings.GenericHierarchicalQueryExecutorMaxLevel) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Messages.GenericHierarchicalQueryExecutor_MaxLevelReachedFormat, Settings.GenericHierarchicalQueryExecutorMaxLevel)); // Target level table must be child table because that is the table which is used in leafFilter. // If leaf filter is used then the we must ensure that proper table name is used for target table. IDbTable targetLevelTable; if (leafFilter != null && !leafFilter.IsEmpty) targetLevelTable = recursiveRelation.Child; else targetLevelTable = rootEntity.Table.Clone("L" + level); SelectStatement selectFromTargetLevel = new SelectStatement(targetLevelTable); CreateSelectListItems(itemsToSelect, targetLevelTable, selectFromTargetLevel); if (leafFilter != null && !leafFilter.IsEmpty) selectFromTargetLevel.Where.Add(leafFilter); IDbTable prevLevel = targetLevelTable; for (int parentLevel = level - 1; parentLevel >= 0; parentLevel--) { IDbTable nextLevel = rootEntity.Table.Clone("L" + parentLevel); DbRelation joinLevels = JoinLevelsInSubTree(prevLevel, nextLevel, recursiveRelation); selectFromTargetLevel.Relations.Add(joinLevels, false, false); prevLevel = nextLevel; } IDbTable subTreeRoot = prevLevel; foreach (IDbColumn rootPkPart in subTreeRoot.PrimaryKey) selectFromTargetLevel.Where.Add(rootPkPart, rootEntity.GetField(rootPkPart)); return selectFromTargetLevel; }
public void Visit(SelectStatement select_statement) { _Query.Append("SELECT "); if (select_statement.IsDistinct) _Query.Append("DISTINCT "); if (select_statement.SelectedAllColumns) _Query.Append("* "); if (select_statement.SelectedAllColumns && select_statement.SelectList.Count != 0) _Query.Append(", "); foreach(ISQLExpression item in select_statement.SelectList) { item.Accept(this); if ( select_statement.SelectList.IndexOf(item) != select_statement.SelectList.Count - 1 ) _Query.Append(", "); } select_statement.FromClause.Accept(this); if (select_statement.WhereClause != null) select_statement.WhereClause.Accept(this); if( select_statement.OrderByClause != null) select_statement.OrderByClause.Accept(this); }
private static void RenderSingleQuery(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // Either TOP or ORDER BY is used; but not both. // SELECT ... FROM ... // WHERE (ROWNUM <= @top) AND (@this.filter) // GROUP BY ... HAVING ... ORDER BY ... AppendSelectAndDistinctKeyWords(select, output); AppendSelectList(select, dbms, output, parameters); AppendFromClause(select, dbms, output); // WHERE. We have made sure that if TOP is used then ORDER BY is not used. if (select.Top > 0) { // WHERE ROWNUM <= this.top AND (this.filter). output.Append(" WHERE ROWNUM <= " + select.Top.ToString(CultureInfo.InvariantCulture)); if (select.Where != null && !select.Where.IsEmpty) { output.Append(" AND ("); select.Where.Render(dbms, output, parameters); output.Append(")"); } } else { AppenWhereWoRownum(select, dbms, output, parameters); } AppendGroupByClause(select, dbms, output, parameters); AppendHavingClause(select, dbms, output, parameters); AppendOrderByClause(select, dbms, output, parameters); }
private static void AppendSelectAndDistinctKeyWords(SelectStatement select, StringBuilder output) { // SELECT. output.Append("SELECT "); if (select.Distinct) output.Append("DISTINCT "); }
public static Predicate NotExists(SelectStatement subQuery) { if (subQuery == null) { throw new ArgumentNullException("subQuery"); } return new NotExistsPredicate(subQuery); }
private static void AppendSelectList(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // Select list. if (select.SelectList != null && select.SelectList.Count > 0) select.SelectList.Render(dbms, output, parameters); else output.Append("*"); }
internal ExistsPredicate(SelectStatement subQuery) { if (subQuery == null) { throw new ArgumentNullException("subQuery"); } this.SubQuery = subQuery; }
public SubQuery(SelectStatement select) { mySelect = select.Clone(); Name = Naming.NewTableName(); foreach (Expression column in mySelect.Columns) { column.VisitAll<BindExpression>(x => x.BindColumn.Table = this); } }
private void ProcessOptimizerHints(IList<OptimizerHint> OptimizerHints, SelectStatement SelStatement) { /* OptimizerHints is not a decendant of TSQLFragment */ foreach (OptimizerHint Hint in OptimizerHints) { ProcessHint(Hint, SelStatement); } }
private static void AppendHavingClause(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // HAVING. if (select.Having != null && !select.Having.IsEmpty) { output.Append(" HAVING "); select.Having.Render(dbms, output, parameters); } }
private static void AppendGroupByClause(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // GROUP BY. if (select.GroupBy != null && select.GroupBy.Fields.Count > 0) { output.Append(" "); select.GroupBy.Render(dbms, output, parameters); } }
private static void AppendWhereClause(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // WHERE. if (select.Where != null && !select.Where.IsEmpty) { output.Append(" WHERE "); select.Where.Render(dbms, output, parameters); } }
private static void CreateSelectListItems(LevelQuerySelectList itemsToSelect, IDbTable targetLevelTable, SelectStatement selectFromTargetLevel) { if (itemsToSelect == LevelQuerySelectList.AllColumns) selectFromTargetLevel.SelectList.Add(targetLevelTable.Columns); else if (itemsToSelect == LevelQuerySelectList.Count) selectFromTargetLevel.SelectList.Add(AggregateFunctionFactory.Count("nodeCount")); else if (itemsToSelect == LevelQuerySelectList.PrimaryKey) selectFromTargetLevel.SelectList.Add(targetLevelTable.PrimaryKey); }
public void Render(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // Uses ROWNUM instead of TOP. If ORDER BY is used then current SELECT statement is rendered // using sub-queries. ROWNUM is used in outer query. bool orderByIsUsed = (select.OrderBy != null && select.OrderBy.Count > 0); if (select.Top > 0 && orderByIsUsed) RenderOrderByInSubQueryAndRownumInOuterQuery(select, dbms, output, parameters); else RenderSingleQuery(select, dbms, output, parameters); }
private static void AppendTopExpression(SelectStatement select, StringBuilder output) { // TOP - only SQL Server. if (select.Top > 0) { output.Append("TOP "); output.Append(select.Top.ToString(CultureInfo.InvariantCulture)); output.Append(" "); } }
public void Process(SelectStatement SelStatement, string ParentType, bool TestTop = false, WithCtesAndXmlNamespaces Cte = null) { if (Cte == null && SelStatement.WithCtesAndXmlNamespaces != null) { Cte = SelStatement.WithCtesAndXmlNamespaces; if (Cte != null) _smells.InsertProcessor.ProcessWithCtesAndXmlNamespaces(Cte); } _smells.ProcessQueryExpression(SelStatement.QueryExpression, ParentType, false, Cte); ProcessOptimizerHints(SelStatement.OptimizerHints, SelStatement); }
public void Render(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { AppendSelectAndDistinctKeyWords(select, output); AppendTopExpression(select, output); AppendSelectList(select, dbms, output, parameters); AppendFromClause(select, dbms, output); AppendWhereClause(select, dbms, output, parameters); AppendGroupByClause(select, dbms, output, parameters); AppendHavingClause(select, dbms, output, parameters); AppendOrderByClause(select, dbms, output, parameters); }
private string GetCallingCode(CreateFunctionStatement function) { var callingSelect = new SelectStatement(); var spec = (callingSelect.QueryExpression = new QuerySpecification()) as QuerySpecification; spec.FromClause = new FromClause(); spec.FromClause.TableReferences.Add(new SchemaObjectFunctionTableReference() { SchemaObject = function.Name }); spec.SelectElements.Add(new SelectStarExpression()); return ScriptDom.GenerateTSql(spec); }
public IEnumerable<SqlStatement> Build() { if (queryExpression == null) throw new InvalidOperationException("The query expression is required"); var statement = new SelectStatement(queryExpression); if (sortColumns.Count > 0) statement.OrderBy = sortColumns.AsReadOnly(); if (queryLimit != null) statement.Limit = queryLimit; return new[] {statement}; }
private void ProcessHint(OptimizerHint Hint, SelectStatement SelStatement) { switch (Hint.HintKind) { case OptimizerHintKind.OrderGroup: case OptimizerHintKind.MergeJoin: case OptimizerHintKind.HashJoin: case OptimizerHintKind.LoopJoin: case OptimizerHintKind.ConcatUnion: case OptimizerHintKind.HashUnion: case OptimizerHintKind.MergeUnion: case OptimizerHintKind.KeepUnion: _smells.SendFeedBack(4, SelStatement); break; } }
public void When_Statement_Has_ObjectType_Condtion() { var selectStatement = new SelectStatement { Condition = new BinaryOperator { LeftOperand = new QueryOperand("ObjectType", "N0", DBColumnType.Int32), RightOperand = new ParameterValue { Value = 14 } } }; var baseStatements = new BaseStatement[]{selectStatement}; var objectMerger = new ObjectMerger(baseStatements); objectMerger.Merge(14, 2); Assert.AreEqual("N0.{ObjectType,Int32} = 2 Or N0.{ObjectType,Int32} = 14", baseStatements[0].Condition.ToString()); }
private static void RenderOrderByInSubQueryAndRownumInOuterQuery(SelectStatement select, DbmsType dbms, StringBuilder output, DbParameterCollection parameters) { // ROWNUM must be placed in outer query when ORDER BY is used. // SELECT * // FROM (SELECT ...) subquery // WHERE ROWNUM <= this.top output.Append("SELECT * FROM ("); AppendSelectAndDistinctKeyWords(select, output); AppendSelectList(select, dbms, output, parameters); AppendFromClause(select, dbms, output); AppenWhereWoRownum(select, dbms, output, parameters); AppendGroupByClause(select, dbms, output, parameters); AppendHavingClause(select, dbms, output, parameters); AppendOrderByClause(select, dbms, output, parameters); // ROWNUM. output.Append(") subquery WHERE ROWNUM <= "); output.Append(select.Top.ToString(CultureInfo.InvariantCulture)); }
private static void AppendFromClause(SelectStatement select, DbmsType dbms, StringBuilder output) { // FROM. output.Append(" "); if (select.Relations != null) { select.Relations.RenderFromClause(select.FromTable, dbms, output); } else { // If no relations have been specified. output.Append("FROM "); select.FromTable.RenderTableName(dbms, output); // AS may not be used between table name and alias because Oracle doesn't that syntax. if (select.FromTable.Alias != select.FromTable.TableName) { output.Append(" "); select.FromTable.RenderAlias(dbms, output); } } }
private static void AppendFromClause(SelectStatement select, DbmsType dbms, StringBuilder output) { // FROM. output.Append(" "); if (select.Relations != null) { select.Relations.RenderFromClause(select.FromTable, dbms, output); } else { // If no relations have been specified. output.Append("FROM "); select.FromTable.RenderTableName(dbms, output); // AS is not used because some DBMSs don't support that syntax. if (select.FromTable.Alias != select.FromTable.TableName) { output.Append(" "); select.FromTable.RenderAlias(dbms, output); } } }
public void Should_Fail_With_ExpectedSyntaxError_When_Using_Reserved_Word_As_Alias() { // Exercise SelectStatement statement = ParserFactory.Execute <SelectStatement>("select * from table select").First(); }
/// <summary> /// Initializes a new instance of the <see cref="SelectUnionStatement"/> class. /// </summary> /// <param name="first"> /// The first. /// </param> /// <param name="second"> /// The second. /// </param> public SelectUnionStatement(SelectStatement first, SelectStatement second) { this.First = first; this.Second = second; }
public DataStoreSelectDataEventArgs(SelectStatement[] selects) { SelectStatements = selects; }
private void ParseSqlSelectStatement(TSqlStatement sqlStatement) { if (sqlStatement.GetType() == typeof(SelectStatement)) { SelectStatement aSelectStatement = (SelectStatement)sqlStatement; QueryExpression aQueryExpression = aSelectStatement.QueryExpression; if (aQueryExpression.GetType() == typeof(QuerySpecification)) { QuerySpecification aQuerySpecification = (QuerySpecification)aQueryExpression; if (aQuerySpecification.FromClause == null) { return; //'select *' is valid query, but not of our interest } //tables NamedTableReferenceVisitor ntVisitor = new NamedTableReferenceVisitor(Context); aQuerySpecification.FromClause.Accept(ntVisitor); TablesReferred = ntVisitor.Tables; //columns ScalarExpressionVisitor seVisitor = null; foreach (SelectElement selectStatement in aQuerySpecification.SelectElements) { seVisitor = new ScalarExpressionVisitor(Context, TablesReferred[0]); selectStatement.Accept(seVisitor); Columns.AddRange(seVisitor.Columns); } if (!string.IsNullOrEmpty(seVisitor.ParsedQuery)) { ParsedQuery = seVisitor.ParsedQuery; //todo } //else // ParsedQuery = Columns.GetParsedQuery(ParsedQuery); UpdateReferredTables(Columns); //ensure unique tables TablesReferred = new List <RbacTable>(TablesReferred.DistinctBy(t => t.Name)); //joins JoinClauseVisitor jcVisitor = new JoinClauseVisitor(Context); aQueryExpression.AcceptChildren(jcVisitor); JoinClauses = jcVisitor.JoinClauses; //where clause if (aQuerySpecification.WhereClause != null) { EqualVisitor cidv = new EqualVisitor(ParsedQuery); InPredicateVisitor inpv = new InPredicateVisitor(ParsedQuery); aQuerySpecification.WhereClause.AcceptChildren(cidv); aQuerySpecification.WhereClause.AcceptChildren(inpv); WhereClauses.AddRange(cidv.WhereClauses); WhereClauses.AddRange(inpv.WhereClauses); WhereClauses.ParseReferenceTableNames(JoinClauses); } } } else { Errors.Add("Not a select statement!"); } }
public void TestExpectedError() { // Exercise SelectStatement statement = ParserFactory.Execute <SelectStatement>("select * from table order field").First(); }
public void TestNoParserException() { // Exercise SelectStatement statement = ParserFactory.Execute <SelectStatement>("merge from table").First(); }
internal JoinClause(SelectStatement parentStatement, Table joinedTable, JoinType joinType) { this.ParentStatement = parentStatement; this.JoinedTable = joinedTable; this.JoinType = joinType; }
/// <summary> /// Converts a FetchXML query to SQL /// </summary> /// <param name="metadata">The metadata cache to use for the conversion</param> /// <param name="fetch">The query object to convert</param> /// <returns>The converted SQL query</returns> public static string Convert(IAttributeMetadataCache metadata, FetchXml.FetchType fetch) { var select = new SelectStatement(); var query = new QuerySpecification(); select.QueryExpression = query; if (fetch.top != null) { query.TopRowFilter = new TopRowFilter { Expression = new IntegerLiteral { Value = fetch.top } } } ; if (fetch.distinct) { query.UniqueRowFilter = UniqueRowFilter.Distinct; } // SELECT (columns from first table) var entity = fetch.Items.OfType <FetchEntityType>().SingleOrDefault(); AddSelectElements(query, entity.Items, entity?.name); // FROM var aliasToLogicalName = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (entity != null) { query.FromClause = new FromClause { TableReferences = { new NamedTableReference { SchemaObject = new SchemaObjectName { Identifiers = { new Identifier { Value = entity.name } } } } } }; if (fetch.nolock) { ((NamedTableReference)query.FromClause.TableReferences[0]).TableHints.Add(new TableHint { HintKind = TableHintKind.NoLock }); } // Recurse into link-entities to build joins query.FromClause.TableReferences[0] = BuildJoins(metadata, query.FromClause.TableReferences[0], (NamedTableReference)query.FromClause.TableReferences[0], entity.Items, query, aliasToLogicalName, fetch.nolock); } // OFFSET if (!String.IsNullOrEmpty(fetch.page) && fetch.page != "1") { var page = Int32.Parse(fetch.page); var pageSize = Int32.Parse(fetch.count); query.OffsetClause = new OffsetClause { OffsetExpression = new IntegerLiteral { Value = ((page - 1) * pageSize).ToString() }, FetchExpression = new IntegerLiteral { Value = fetch.count } }; } // WHERE var filter = GetFilter(metadata, entity.Items, entity.name, aliasToLogicalName); if (filter != null) { query.WhereClause = new WhereClause { SearchCondition = filter }; } // ORDER BY AddOrderBy(entity.name, entity.Items, query); // For single-table queries, don't bother qualifying the column names to make the query easier to read if (query.FromClause.TableReferences[0] is NamedTableReference) { select.Accept(new SimplifyMultiPartIdentifierVisitor(entity.name)); } // Check whether each identifier needs to be quoted so we have minimal quoting to make the query easier to read select.Accept(new QuoteIdentifiersVisitor()); new Sql150ScriptGenerator().GenerateScript(select, out var sql); return(sql); }
/// <summary> /// Returns collection of the select statement alias /// </summary> /// <param name="select"></param> /// <returns></returns> private IEnumerable <SelectAlias> BuildSelectList(SelectStatement select, List <FromAlias> aliasList) { var analyzer = new SelectExpressionAnalyzer(_formatter, select.SelectExpression as LambdaExpression, FilterExpressionAliasList(aliasList, select.ExpressionBoundClauses)); return((List <SelectAlias>)analyzer.Sql()); }
CriteriaOperator CreateOperand(IMemberInfo memberInfo, SelectStatement selectStatement) { var referenceInfoAttribute = memberInfo.FindAttribute<ReferenceInfoAttribute>(); return new QueryOperand(GetColumnName(memberInfo, referenceInfoAttribute), GetAlias(referenceInfoAttribute, selectStatement)); }
public void Select_Top_Missing_Top_Param_StarField() { // Exercise SelectStatement statement = ParserFactory.Execute <SelectStatement>("select top * from table").First(); }
public void Select_With_Inner_Join_Condition_With_Complex_Expressions() { // Exercise SelectStatement statement = ParserFactory.Execute <SelectStatement>(@" select fielda from table1 t1 join table2 as t2 on (t1.field1 + 150) / 12 = ( t2.field2 + t1.fielda ) " ).First(); // Verify outcome Assert.IsNotNull(statement); // Test From Assert.AreEqual(1, statement.From.Count); Assert.AreEqual("table1", statement.From[0].Name); Assert.AreEqual("t1", statement.From[0].Alias.Name); // Test Join Assert.AreEqual(1, statement.From[0].Joins.Count); Join join = statement.From[0].Joins[0]; Assert.AreEqual("table2", join.Name); Assert.AreEqual("t2", join.Alias.Name); Assert.AreEqual(JoinType.Join, join.Type); CriteriaExpression expr = join.Condition as CriteriaExpression; Assert.AreEqual("=", expr.Operator); Assert.IsTrue(expr.Left is OperatorExpression); var leftExpression = ( OperatorExpression )expr.Left; Assert.AreEqual("/", leftExpression.Operator); Assert.IsTrue(leftExpression.Left is NestedExpression); var leftLeftExpression = ( NestedExpression )leftExpression.Left; Assert.IsTrue(leftLeftExpression.Expression is OperatorExpression); OperatorExpression leftOperatorExpression = ( OperatorExpression )leftLeftExpression.Expression; Assert.AreEqual("t1.field1", leftOperatorExpression.Left.Value); Assert.AreEqual("+", leftOperatorExpression.Operator); Assert.AreEqual("150", leftOperatorExpression.Right.Value); IdentifierExpression rightIdentifierExpression = ( IdentifierExpression )leftExpression.Right; Assert.AreEqual("12", rightIdentifierExpression.Value); //var rightExpression = ( NestedExpression )expr.Right; //Assert.AreEqual( "t2", rightExpression.Parts[ 0 ] ); //Assert.AreEqual( "field2", rightExpression.Parts[ 1 ] ); //Assert.AreEqual( "t2.field2", expr.Right.Value ); }
protected override void VisitLimitAtEnd(SelectStatement select) { this.CommandText.Append(" LIMIT "); this.CommandText.Append(select.Limit); }
string GetNodeAlias(SelectStatement statement, string filterMemberName) { if (!_tablesDictionary.ContainsKey(statement.TableName)) { var classInfo = Application.Model.BOModel.Select(mclass => XafTypesInfo.XpoTypeInfoSource.XPDictionary.QueryClassInfo(mclass.TypeInfo.Type)).Where(info => info != null && info.TableName == statement.TableName).FirstOrDefault(); if (classInfo != null) _tablesDictionary.Add(classInfo.TableName, classInfo.ClassType); else throw new ArgumentException(statement.TableName); } var fullName = _tablesDictionary[statement.TableName].FullName; if (XafTypesInfo.Instance.FindTypeInfo(fullName).OwnMembers.Where(member => member.Name == filterMemberName).FirstOrDefault() == null) { return statement.SubNodes[0].Alias; } return statement.Alias; }
public SelectStatement ParseSelect(string input, int offset, Context context, SelectFlags flags, SelectStatement parent) { int originalOffset = offset; var statement = new SelectStatement(); if (parent != null) { statement.Parent = parent; } statement.UsedFlags = flags; Token next = NextToken(input, offset); if (next.Kind != TokenKind.Keyword || next.KeywordValue != Keyword.Select) { throw new Exception("Failed initial check"); } offset += next.InputLength; var exprFlags = new ExpressionFlags { GeneralWildcardAllowed = true, IdentifierAllowed = true, WildcardAllowed = true, SingleValueSubSelectAllowed = true }; do { next = NextToken(input, offset); if (next.Kind == TokenKind.Keyword && next.KeywordValue == Keyword.From) { offset += next.InputLength; break; } else if (next.Kind == TokenKind.None) { throw new Exception("Unexpected end of input"); } else if (next.Kind == TokenKind.Comma) { offset += next.InputLength; } var expr = ParseExpression(input, offset, context, statement, exprFlags, false, false); if (statement.OutputColumns.Count > 0 && expr.IsWildcard() && !expr.IsOnlyReference()) { throw new Exception("Unexpected token *"); } statement.OutputColumns.Add(expr); offset += expr.FullText.Length; // Disallow general wildflags after first column exprFlags.GeneralWildcardAllowed = false; } while (true); var source = ParseReference(input, offset, context, statement, new ReferenceFlags() { TableOnly = true }); statement.MainSource = source; offset += source.InputLength; // If we have a parent, they're going to resolve our references for us if (parent == null) { ResolveSelectReferences(statement, context); } // Prepare flags for WHERE and ORDER BY expressions exprFlags.GeneralWildcardAllowed = false; exprFlags.WildcardAllowed = false; exprFlags.IdentifierAllowed = false; do { next = NextToken(input, offset); offset += next.InputLength; if (next.Kind == TokenKind.Keyword) { if (next.KeywordValue == Keyword.Where) { if (statement.FilterConditions != null) { throw new Exception("Unexpected WHERE when filter has already been set"); } statement.FilterConditions = ParseExpression(input, offset, context, statement, exprFlags, parent == null, false); offset += statement.FilterConditions.FullText.Length; } else if (next.KeywordValue == Keyword.Order) { next = NextToken(input, offset); if (next.Kind != TokenKind.Keyword || next.KeywordValue != Keyword.By) { throw new Exception("Unexpected token after ORDER"); } offset += next.InputLength; bool firstOrder = true; while (true) { next = NextToken(input, offset); if (next.Kind == TokenKind.Comma) { if (!firstOrder) { offset += next.InputLength; } else { throw new Exception("Order by clause cannot start with a comma"); } } else if (next.Kind == TokenKind.Operator && next.OperatorValue == Operator.ParenthesisRight) { if (flags.StopOnUnmatchedParenthesis) { offset += next.InputLength; break; } else { throw new Exception("Missing left parenthesis"); } } else if (next.Kind == TokenKind.Keyword || next.Kind == TokenKind.None) { break; } firstOrder = false; var ordering = new Ordering { OrderExpression = ParseExpression(input, offset, context, statement, exprFlags, parent == null, false) }; offset += ordering.OrderExpression.FullText.Length; next = NextToken(input, offset); if (next.Kind == TokenKind.Keyword && (next.KeywordValue == Keyword.Asc || next.KeywordValue == Keyword.Desc)) { ordering.Kind = next.KeywordValue == Keyword.Asc ? OrderingKind.Ascending : OrderingKind.Descending; offset += next.InputLength; } statement.OutputOrder.Add(ordering); } } } else if (next.Kind == TokenKind.Operator && next.OperatorValue == Operator.ParenthesisRight) { if (!flags.StopOnUnmatchedParenthesis) { offset += next.InputLength; break; } else { throw new Exception("Missing left parenthesis"); } } else if (next.Kind != TokenKind.None) { throw new Exception($"Unexpected token in query at offset {offset}"); } } while (next.Kind != TokenKind.None && next.Kind != TokenKind.SemiColon); offset = Math.Min(input.Length, offset); statement.OriginalText = input[originalOffset..offset];
public override SelectedData SelectData(params SelectStatement[] selects) { var selectStatement = selects.FirstOrDefault(statement => statement.TableName == ObjectClassInfo.TableName); if (selectStatement != null) { var systemMembers = new[] { GCRecordField.StaticName, ObjectClassInfo.OptimisticLockFieldName, ObjectClassInfo.OptimisticLockFieldInDataLayerName }; var memberInfos = DynamicTypeInfo.OwnMembers.Where(info => info.IsPublic && !systemMembers.Contains(info.Name)); var operands = memberInfos.Select(info => CreateOperand(info, selectStatement)).ToList(); selectStatement.Operands.Clear(); selectStatement.Operands.AddRange(operands); _selectStatement = selectStatement; } return base.SelectData(selects); }
/// <summary> /// Appends the select. /// </summary> /// <param name="builder">The builder.</param> /// <param name="select">The select.</param> public virtual void AppendSelect(StringBuilder builder, SelectStatement select) { builder.AppendLine("SELECT"); builder.AppendLine(Indentation + this.Columns(select.ColumnsList)); }
string GetAlias(ReferenceInfoAttribute referenceInfoAttribute, SelectStatement selectStatement) { if (referenceInfoAttribute != null) { var joinNode = selectStatement.SubNodes.GetItems<JoinNode>(node => node.SubNodes).FirstOrDefault( node => node.TableName == referenceInfoAttribute.TableName); if (joinNode != null) { return joinNode.Alias; } } return "N0"; }
private void ProcessViewStatementBody(TSqlStatement sqlStatement) { if ((sqlStatement.GetType() == typeof(CreateViewStatement)) || (sqlStatement.GetType() == typeof(AlterViewStatement))) { ViewStatementBody aViewStatementBody = (ViewStatementBody)sqlStatement; AddLogText("Columns meta data:"); foreach (Identifier aColumnIdentifier in aViewStatementBody.Columns) { AddLogText(string.Format("Column:{0}", aColumnIdentifier.Value)); ColumnList.Add(new ColumnInfo { Alias = aColumnIdentifier.Value }); } AddLogText(""); AddLogText("QueryExpression SelectElements:"); SelectStatement aSelectStatement = aViewStatementBody.SelectStatement; QueryExpression aQueryExpression = aSelectStatement.QueryExpression; if (aQueryExpression.GetType() == typeof(QuerySpecification)) { QuerySpecification aQuerySpecification = (QuerySpecification)aQueryExpression; int aSelectElementID = 0; foreach (SelectElement aSelectElement in aQuerySpecification.SelectElements) { if (aSelectElement.GetType() == typeof(SelectScalarExpression)) { SelectScalarExpression aSelectScalarExpression = (SelectScalarExpression)aSelectElement; string identStr = string.Empty; IdentifierOrValueExpression aIdentifierOrValueExpression = aSelectScalarExpression.ColumnName; if (aIdentifierOrValueExpression != null) { if (aIdentifierOrValueExpression.ValueExpression == null) { AddLogText(string.Format("Identifier={0}", aIdentifierOrValueExpression.Identifier.Value)); identStr = aIdentifierOrValueExpression.Identifier.Value; } else { AddLogText("Value Expression found!"); } } AddColumnIfNeeded(aSelectElementID, identStr); ScalarExpression aScalarExpression = aSelectScalarExpression.Expression; PrintSelectScalarExperssionRecurse(aSelectElementID, aScalarExpression); } else { AddColumnIfNeeded(aSelectElementID, "Error, something else than SelectScalarExpression found"); AddLogText("We only support SelectScalarExpression."); } aSelectElementID = aSelectElementID + 1; AddLogText(""); } AddLogText(""); AddLogText("Table References:"); FromClause aFromClause = aQuerySpecification.FromClause; foreach (TableReference aTableReference in aFromClause.TableReferences) { PrintTableReferenceRecurse(aTableReference); } } FillEmptyAlias(); } else { AddLogText("This is not a view statement, but a:" + sqlStatement.ToString()); } }