-
Notifications
You must be signed in to change notification settings - Fork 1
/
SqlLexer.cs
131 lines (105 loc) · 3.49 KB
/
SqlLexer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System;
using System.IO;
using System.Text;
namespace SqlGadgetry
{
public class SqlLexer : IDisposable
{
private readonly StringReader _reader;
private readonly SqlLexerOptions _options;
private SqlLexerState _state = SqlLexerState.None;
private bool _disposed;
public SqlLexer(string sql)
: this(sql, new SqlLexerOptions { IgnoreCase = true })
{
_reader = new StringReader(sql);
}
public SqlLexer(string sql, SqlLexerOptions options)
{
_reader = new StringReader(sql);
_options = options;
}
public SqlLexerState State
{
get { return _state; }
}
public SqlToken Next()
{
if (_disposed)
{
throw new ObjectDisposedException("SqlLexer");
}
switch (_state)
{
case SqlLexerState.None:
string keyword = ReadWord();
if (string.Equals(keyword, "SELECT",
_options.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
_state = SqlLexerState.SelectList;
return new SqlToken(SqlTokenType.SelectKeyword, keyword);
}
throw new NotSupportedException();
case SqlLexerState.SelectList:
string column = ReadColumnTable();
if (string.Equals(column, "FROM",
_options.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
_state = SqlLexerState.TableSource;
return new SqlToken(SqlTokenType.FromKeyword, column);
}
return new SqlToken(SqlTokenType.SelectListColumn, column);
case SqlLexerState.TableSource:
string table = ReadColumnTable();
_state = SqlLexerState.End;
return new SqlToken(SqlTokenType.TableSource, table);
default:
return null;
}
}
private string ReadColumnTable()
{
int ch = _reader.Peek();
if (ch != '[')
{
while ((ch = _reader.Peek()) != -1 && "\r\n\t ,".IndexOf((char)ch) != -1)
{
_reader.Read();
}
return ReadWord();
}
var sb = new StringBuilder();
while ((ch = _reader.Read()) != -1 && (char)ch != ']')
{
sb.Append((char)ch);
}
while ((ch = _reader.Peek()) != -1 && "\r\n\t ,".IndexOf((char)ch) != -1)
{
_reader.Read();
}
return sb.ToString();
}
private string ReadWord()
{
var sb = new StringBuilder();
int ch;
while ((ch = _reader.Read()) != -1 && "\r\n\t ,".IndexOf((char)ch) == -1)
{
sb.Append((char)ch);
}
return sb.ToString();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_reader.Dispose();
_disposed = true;
}
}
}
}