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
use alloc::{boxed::Box, vec::Vec};
use crate::{
Begin, Identifier, Span, Spanned, Statement,
keywords::Keyword,
lexer::Token,
parser::{ParseError, Parser},
statement::parse_statement,
};
/// PostgreSQL CTE materialization hint
#[derive(Clone, Debug)]
pub enum MaterializedHint {
Materialized(Span),
NotMaterialized(Span),
}
impl Spanned for MaterializedHint {
fn span(&self) -> Span {
match self {
MaterializedHint::Materialized(s) => s.span(),
MaterializedHint::NotMaterialized(s) => s.span(),
}
}
}
#[derive(Clone, Debug)]
pub struct WithBlock<'a> {
/// Identifier for the with block
pub identifier: Identifier<'a>,
/// Span of AS
pub as_span: Span,
/// Optional PostgreSQL MATERIALIZED / NOT MATERIALIZED hint
pub materialized: Option<MaterializedHint>,
/// Span of (
pub lparen_span: Span,
/// The statement within the with block, will be one of select, update, insert or delete
pub statement: Statement<'a>,
/// Span of )
pub rparen_span: Span,
}
impl<'a> Spanned for WithBlock<'a> {
fn span(&self) -> Span {
self.identifier
.span()
.join_span(&self.as_span)
.join_span(&self.materialized)
.join_span(&self.lparen_span)
.join_span(&self.statement)
.join_span(&self.rparen_span)
}
}
/// Represent a with query statement
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, WithQuery, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::PostgreSQL);
/// #
/// let sql = "WITH ids AS (DELETE FROM things WHERE number=42) INSERT INTO deleted (id) SELECT id FROM ids;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
///
/// # assert!(issues.is_ok());
/// #
/// let delete: WithQuery = match stmts.pop() {
/// Some(Statement::WithQuery(d)) => *d,
/// _ => panic!("We should get a with statement")
/// };
///
/// assert!(delete.with_blocks[0].identifier.as_str() == "ids");
/// ```
#[derive(Clone, Debug)]
pub struct WithQuery<'a> {
/// Span of WITH
pub with_span: Span,
/// Optional span of RECURSIVE (PostgreSQL)
pub recursive_span: Option<Span>,
/// The comma seperated with blocks
pub with_blocks: Vec<WithBlock<'a>>,
/// The final statement of the with query, will be one of select, update, insert, delete or merge
pub statement: Box<Statement<'a>>,
}
impl<'a> Spanned for WithQuery<'a> {
fn span(&self) -> Span {
self.with_span
.join_span(&self.recursive_span)
.join_span(&self.with_blocks)
.join_span(&self.statement)
}
}
pub(crate) fn parse_with_query<'a>(
parser: &mut Parser<'a, '_>,
) -> Result<WithQuery<'a>, ParseError> {
let with_span = parser.consume_keyword(Keyword::WITH)?;
let recursive_span = parser.skip_keyword(Keyword::RECURSIVE);
let mut with_blocks = Vec::new();
loop {
let identifier = parser.consume_plain_identifier_unreserved()?;
let as_span = parser.consume_keyword(Keyword::AS)?;
// Optional PostgreSQL [NOT] MATERIALIZED hint
let materialized = if let Some(not_span) = parser.skip_keyword(Keyword::NOT) {
let mat_span = parser.consume_keyword(Keyword::MATERIALIZED)?;
parser.postgres_only(&mat_span);
Some(MaterializedHint::NotMaterialized(
not_span.join_span(&mat_span),
))
} else if let Some(mat_span) = parser.skip_keyword(Keyword::MATERIALIZED) {
parser.postgres_only(&mat_span);
Some(MaterializedHint::Materialized(mat_span))
} else {
None
};
let lparen_span = parser.consume_token(Token::LParen)?;
let statement =
parser.recovered(
"')'",
&|t| t == &Token::RParen,
|parser| match parse_statement(parser)? {
Some(v) => Ok(Some(v)),
None => {
parser.expected_error("Statement");
Ok(None)
}
},
)?;
let rparen_span = parser.consume_token(Token::RParen)?;
let statement = match statement {
Some(v) => {
if !matches!(
&v,
Statement::Select(_)
| Statement::CompoundQuery(_)
| Statement::InsertReplace(_)
| Statement::Update(_)
| Statement::Delete(_)
) {
parser.err(
"Only SELECT, INSERT, UPDATE or DELETE allowed within WITH query",
&v.span(),
);
}
v
}
None => Statement::Begin(Box::new(Begin {
span: lparen_span.clone(),
})),
};
with_blocks.push(WithBlock {
identifier,
as_span,
materialized,
lparen_span,
statement,
rparen_span,
});
if parser.skip_token(Token::Comma).is_none() {
break;
}
}
let statement = match parse_statement(parser)? {
Some(v) => {
// TODO merge statements are also allowed here
if !matches!(
&v,
Statement::Select(_)
| Statement::CompoundQuery(_)
| Statement::InsertReplace(_)
| Statement::Update(_)
| Statement::Delete(_)
) {
parser.err(
"Only SELECT, INSERT, UPDATE or DELETE allowed as WITH query",
&v.span(),
);
}
Box::new(v)
}
None => parser.expected_failure("Statement")?,
};
let res = WithQuery {
with_span,
recursive_span,
with_blocks,
statement,
};
Ok(res)
}