Repository navigation
Expand file tree
/
Copy pathSqlParser.cs
More file actions
158 lines (148 loc) · 6.38 KB
/
Copy pathSqlParser.cs
File metadata and controls
158 lines (148 loc) · 6.38 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
using System.Globalization;
using System.Text;
using KeyLoad.Core;
using KeyLoad.Query.Features.QueryExecution;
using Microsoft.Extensions.Options;
namespace KeyLoad.Query;
/// <summary>A bounded Q1/Q2 parser. Unsupported syntax is rejected, never passed through to storage.</summary>
public sealed class SqlParser
{
private const int MinimumPositiveCount = 1;
private const int DefaultDialectVersion = 1;
private const int JoinDialectVersion = 2;
private readonly SqlTokenCursor cursor;
private readonly DatabaseLimits limits;
private readonly QueryExecutionOptions execution;
private readonly IOptions<DatabaseLimits> operationLimitsOptions;
private readonly int dialectVersion;
private string? alias;
/// <summary>Creates a parser with the configured SQL byte and token limits.</summary>
/// <param name="sql">SQL text in the selected bounded query dialect.</param>
/// <param name="limitsOptions">Centrally validated database query limits.</param>
/// <param name="executionOptions">Centrally validated query structure limits.</param>
public SqlParser(string sql, IOptions<DatabaseLimits> limitsOptions, IOptions<QueryExecutionOptions> executionOptions)
: this(sql, limitsOptions, executionOptions, null, DefaultDialectVersion)
{
}
internal SqlParser(string sql, IOptions<DatabaseLimits> limitsOptions, IOptions<QueryExecutionOptions> executionOptions,
ReadExecutionBudget? budget, int dialectVersion = DefaultDialectVersion)
{
ArgumentNullException.ThrowIfNull(sql);
ArgumentNullException.ThrowIfNull(limitsOptions);
ArgumentNullException.ThrowIfNull(executionOptions);
limits = limitsOptions.Value;
limits.Validate();
execution = executionOptions.Value;
execution.Validate();
operationLimitsOptions = limitsOptions;
if (dialectVersion is not (DefaultDialectVersion or JoinDialectVersion))
{
throw Errors.Fail(ErrorCode.UnsupportedCapability, SqlSyntax.UnsupportedDialectDetail);
}
this.dialectVersion = dialectVersion;
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, execution.SqlBudgetCheckInterval, 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) = new ModelSqlSourceParser(cursor).Read();
ReadAlias();
var joinSyntax = new SqlJoinSyntax(cursor, dialectVersion);
var join = joinSyntax.ReadJoin(alias);
if (join is not null && StringComparer.Ordinal.Equals(join.Collection, collection))
{
throw SqlSyntax.Invalid();
}
projection = projection.Select(p => join is null
? p with { Path = SqlJoinSyntax.BoundPath(p.Path, alias), SourceAlias = null }
: SqlJoinSyntax.BindProjection(p, alias, join)).ToList();
var filter = cursor.Eat(SqlSyntax.Where) ? new SqlExpressionParser(cursor, operationLimitsOptions, execution.MaximumInValues, alias).Parse() : null;
var order = ReadOrder(join);
var limit = ReadLimit();
cursor.Eat(SqlSyntax.Semicolon);
if (cursor.Current.Kind != SqlTokenKind.End)
{
throw Errors.Fail(ErrorCode.UnsupportedCapability, SqlSyntax.UnsupportedSyntaxDetail);
}
if (limit < MinimumPositiveCount || limit > limits.MaxResults || projection.Count > execution.MaximumProjection || order.Count > execution.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, join);
}
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) && (!cursor.Is(SqlSyntax.Inner) || !cursor.IsNext(SqlSyntax.Join)))
{
alias = cursor.Identifier();
}
}
private List<Ordering> ReadOrder(InnerJoinClause? join)
{
var order = new List<Ordering>();
if (cursor.Eat(SqlSyntax.Order))
{
cursor.Need(SqlSyntax.By);
do
{
var raw = cursor.Path();
var field = join is null ? SqlJoinSyntax.BoundPath(JsonData.Path(raw.ToArray()), alias)
: SqlJoinSyntax.BoundOrderPath(raw, alias);
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;
}
}