Created
May 2, 2012 18:50
-
-
Save mgroves/2579162 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ParsedSqlSelectQuery | |
| { | |
| public IList<string> SelectElements { get; private set; } | |
| public string WhereClause { get; private set; } | |
| public string FromClause { get; private set; } | |
| public ParsedSqlSelectQuery(string sqlQuery) | |
| { | |
| var parser = new TSql100Parser(false); | |
| IList<ParseError> errors; | |
| var parsedQuery = parser.Parse(new StringReader(sqlQuery), out errors) as TSqlScript; | |
| if (errors.Count > 0) | |
| throw new ArgumentException("Errors in parsing tSQL: " + string.Join("\n", errors.Select(e => e.Message).ToArray())); | |
| if (parsedQuery == null) | |
| throw new ArgumentException("Invalid tSQL script: " + sqlQuery); | |
| if (parsedQuery.Batches.Count != 1) | |
| throw new ArgumentException("Only 1 batch supported"); | |
| if (parsedQuery.Batches[0].Statements.Count != 1) | |
| throw new ArgumentException("Only 1 statement supported"); | |
| var selectQuery = parsedQuery.Batches[0].Statements[0] as SelectStatement; | |
| if(selectQuery == null) | |
| throw new ArgumentException("Only SELECT queries are supported"); | |
| var querySpecification = (QuerySpecification) selectQuery.QueryExpression; | |
| SelectElements = querySpecification.SelectElements.Select(e => GetText(e, sqlQuery)).ToList(); | |
| if(querySpecification.WhereClause != null) | |
| WhereClause = GetText(querySpecification.WhereClause, sqlQuery); | |
| FromClause = string.Join(" ", querySpecification.FromClauses.Select(e => GetText(e, sqlQuery)).ToArray()); | |
| } | |
| string GetText(TSqlFragment fragment, string sqlQuery) | |
| { | |
| var result = sqlQuery.Substring(fragment.StartOffset, fragment.FragmentLength); | |
| return result; | |
| } | |
| } |
Author
It's in these namespaces:
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
Not part of EF as far as I know.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks pretty clean... is TSql100Parser part of EF?