-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlParser.cs
More file actions
197 lines (183 loc) · 6.78 KB
/
Copy pathSqlParser.cs
File metadata and controls
197 lines (183 loc) · 6.78 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System.Globalization;
using System.Text;
using KeyLoad.Core;
using KeyLoad.Query.Features.QueryExecution;
namespace KeyLoad.Query;
/// <summary>A bounded Q1 parser. Unsupported syntax is rejected, never passed through to storage.</summary>
public sealed class SqlParser
{
private readonly SqlTokenCursor cursor;
private readonly DatabaseLimits limits;
private string? alias;
/// <summary>Creates a parser with the configured SQL byte and token limits.</summary>
/// <param name="sql">Q1 SQL text.</param>
/// <param name="limits">Database query limits.</param>
public SqlParser(string sql, DatabaseLimits limits)
: this(sql, limits, null)
{
}
internal SqlParser(string sql, DatabaseLimits limits, ReadExecutionBudget? budget)
{
ArgumentNullException.ThrowIfNull(sql);
ArgumentNullException.ThrowIfNull(limits);
this.limits = limits;
if (sql.Length > limits.MaxQueryBytes || Encoding.UTF8.GetByteCount(sql) > limits.MaxQueryBytes)
{
throw Errors.Fail(ErrorCode.BudgetExceeded, SqlSyntax.ByteBudgetDetail);
}
cursor = new(SqlTokenizer.Lex(sql, limits.MaxQueryTokens, limits.MaxQueryDepth, budget));
}
/// <summary>Parses the SQL text into a typed, bounded query.</summary>
/// <returns>A select query with immutable projection and ordering.</returns>
public SelectQuery Parse()
{
var explain = cursor.Eat(SqlSyntax.Explain);
cursor.Need(SqlSyntax.Select);
var projection = ReadProjection();
cursor.Need(SqlSyntax.From);
var (collection, modelSource) = ReadSource();
ReadAlias();
projection = projection.Select(p => p with { Path = BoundPath(p.Path) }).ToList();
var filter = cursor.Eat(SqlSyntax.Where) ? new SqlExpressionParser(cursor, limits, alias).Parse() : null;
var order = ReadOrder();
var limit = ReadLimit();
cursor.Eat(SqlSyntax.Semicolon);
if (cursor.Current.Kind != SqlTokenKind.End)
{
throw Errors.Fail(ErrorCode.UnsupportedCapability, SqlSyntax.UnsupportedSyntaxDetail);
}
if (limit < 1 || limit > limits.MaxResults || projection.Count > SqlSyntax.MaximumProjection || order.Count > SqlSyntax.MaximumOrdering
|| projection.Select(p => p.Alias).Distinct(StringComparer.Ordinal).Count() != projection.Count)
{
throw SqlSyntax.Invalid();
}
return new(collection, alias, [.. projection], filter, [.. order], limit, explain, modelSource);
}
private (string Collection, ModelQuerySource? Source) ReadSource()
{
if (!cursor.Current.Quoted && cursor.Is(SqlSyntax.Events))
{
var collection = cursor.Current.Text;
cursor.Advance();
if (!cursor.Eat(SqlSyntax.OpenParen))
{
return (collection, null);
}
var streamSet = StringArgument();
cursor.Need(SqlSyntax.Comma);
var streamId = StringArgument();
var generation = 1L;
if (cursor.Eat(SqlSyntax.Comma))
{
if (cursor.Current.Kind != SqlTokenKind.Number
|| !long.TryParse(cursor.Current.Text, NumberStyles.None, CultureInfo.InvariantCulture, out generation)
|| generation < 1)
{
throw SqlSyntax.Invalid();
}
cursor.Advance();
}
cursor.Need(SqlSyntax.CloseParen);
return (streamSet, new(ModelQuerySourceKind.Events, streamId, generation));
}
if (!cursor.Current.Quoted && cursor.Is(SqlSyntax.QueueMessages))
{
var collection = cursor.Current.Text;
cursor.Advance();
if (!cursor.Eat(SqlSyntax.OpenParen))
{
return (collection, null);
}
var queue = StringArgument();
cursor.Need(SqlSyntax.CloseParen);
return (queue, new(ModelQuerySourceKind.QueueMessages, queue));
}
return (cursor.Identifier(), null);
}
private string StringArgument()
{
if (cursor.Current.Kind != SqlTokenKind.String)
{
throw SqlSyntax.Invalid();
}
var value = cursor.Current.Text;
cursor.Advance();
JsonData.Identifier(value);
return value;
}
private List<Selection> ReadProjection()
{
var projection = new List<Selection>();
if (cursor.Eat(SqlSyntax.Star))
{
projection.Add(new(SqlSyntax.Star, SqlSyntax.Star));
}
else
{
do
{
var path = cursor.Path();
var output = cursor.Eat(SqlSyntax.As) ? cursor.Identifier() : path.Last();
projection.Add(new(JsonData.Path(path.ToArray()), output));
} while (cursor.Eat(SqlSyntax.Comma));
}
return projection;
}
private void ReadAlias()
{
if (cursor.Eat(SqlSyntax.As))
{
alias = cursor.Identifier();
}
else if (cursor.Current.Kind == SqlTokenKind.Identifier && !cursor.Is(SqlSyntax.Where) && !cursor.Is(SqlSyntax.Order) && !cursor.Is(SqlSyntax.Limit))
{
alias = cursor.Identifier();
}
}
private string BoundPath(string path)
{
if (path == SqlSyntax.Star)
{
return path;
}
var parts = JsonData.PathSegments(path).ToList();
if (alias is not null && parts.Count > 1 && parts[0] == alias)
{
parts.RemoveAt(0);
}
return parts.Count == 1 && parts[0] is SqlSyntax.MetadataId or SqlSyntax.MetadataRevision ? SqlSyntax.MetadataPrefix + parts[0] : JsonData.Path(parts.ToArray());
}
private List<Ordering> ReadOrder()
{
var order = new List<Ordering>();
if (cursor.Eat(SqlSyntax.Order))
{
cursor.Need(SqlSyntax.By);
do
{
var field = BoundPath(JsonData.Path(cursor.Path().ToArray()));
var descending = cursor.Eat(SqlSyntax.Desc);
if (!descending)
{
cursor.Eat(SqlSyntax.Asc);
}
order.Add(new(field, descending));
} while (cursor.Eat(SqlSyntax.Comma));
}
return order;
}
private int ReadLimit()
{
var limit = SqlSyntax.DefaultLimit;
if (cursor.Eat(SqlSyntax.Limit))
{
if (cursor.Current.Kind != SqlTokenKind.Number
|| !int.TryParse(cursor.Current.Text, NumberStyles.None, CultureInfo.InvariantCulture, out limit))
{
throw SqlSyntax.Invalid();
}
cursor.Advance();
}
return limit;
}
}