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
// SPDX-License-Identifier: Apache-2.0
//! Parse CREATE/DROP/SHOW RLS POLICY.
use super::helpers::{extract_after_keyword, extract_name_after_if_exists};
use crate::ddl_ast::statement::NodedbStatement;
use crate::error::SqlError;
pub(super) fn try_parse(
upper: &str,
parts: &[&str],
trimmed: &str,
) -> Option<Result<NodedbStatement, SqlError>> {
(|| -> Result<Option<NodedbStatement>, SqlError> {
if upper.starts_with("CREATE RLS POLICY ") {
return Ok(Some(parse_create_rls_policy(upper, parts, trimmed)));
}
if upper.starts_with("DROP RLS POLICY ") {
let if_exists = upper.contains("IF EXISTS");
let name = match extract_name_after_if_exists(parts, "POLICY") {
None => return Ok(None),
Some(r) => r?,
};
let collection = extract_after_keyword(parts, "ON").unwrap_or_default();
return Ok(Some(NodedbStatement::DropRlsPolicy {
name,
collection,
if_exists,
}));
}
if upper.starts_with("SHOW RLS POLI") {
let collection = parts.get(3).map(|s| s.to_string());
return Ok(Some(NodedbStatement::ShowRlsPolicies { collection }));
}
Ok(None)
})()
.transpose()
}
/// `CREATE RLS POLICY <name> ON <collection> FOR <type> USING (<predicate>)
/// [RESTRICTIVE] [TENANT <id>] [ON DENY ...]`
///
/// Extracts all token-level fields. Predicate compilation (AST parse,
/// auth-ref validation, ScanFilter serialization) is left to the
/// handler in `nodedb` which has access to the required security types.
fn parse_create_rls_policy(upper: &str, parts: &[&str], _trimmed: &str) -> NodedbStatement {
// parts: CREATE RLS POLICY <name> ON <collection> FOR <type> USING (<pred>) ...
// Indices (0-based): 0 1 2 3 4 5 6 7 8 9+
let name = parts.get(3).unwrap_or(&"").to_lowercase();
let collection = parts
.iter()
.position(|p| p.to_uppercase() == "ON")
.and_then(|i| parts.get(i + 1))
.map(|s| s.to_lowercase())
.unwrap_or_default();
// FOR keyword → next token is the policy type.
let policy_type = parts
.iter()
.position(|p| p.to_uppercase() == "FOR")
.and_then(|i| parts.get(i + 1))
.map(|s| s.to_uppercase())
.unwrap_or_else(|| "ALL".to_string());
// USING keyword → everything up to the next keyword (RESTRICTIVE/TENANT/ON)
// is the predicate (including its outer parentheses which we strip).
let predicate_raw =
if let Some(using_idx) = parts.iter().position(|p| p.to_uppercase() == "USING") {
let end = parts[using_idx + 1..]
.iter()
.position(|p| {
let u = p.to_uppercase();
u == "RESTRICTIVE" || u == "TENANT" || u == "ON"
})
.map(|i| using_idx + 1 + i)
.unwrap_or(parts.len());
strip_outer_parens(&parts[using_idx + 1..end].join(" "))
} else {
// Fall back: look in the upper string between USING( and ) for simple cases.
extract_using_from_upper(upper)
};
let is_restrictive = upper.contains("RESTRICTIVE");
// ON DENY <...> — everything after "ON DENY" up to RESTRICTIVE/TENANT/end.
let on_deny_raw = {
// Find "ON" followed by "DENY" in parts (not the "ON <collection>" earlier).
let deny_pos = parts
.windows(2)
.position(|w| w[0].to_uppercase() == "ON" && w[1].to_uppercase() == "DENY");
deny_pos.map(|pos| {
// Collect tokens after DENY until RESTRICTIVE or TENANT.
parts[pos + 2..]
.iter()
.take_while(|p| {
let u = p.to_uppercase();
u != "RESTRICTIVE" && u != "TENANT"
})
.copied()
.collect::<Vec<_>>()
.join(" ")
})
};
let tenant_id_override = parts
.iter()
.position(|p| p.to_uppercase() == "TENANT")
.and_then(|i| parts.get(i + 1))
.and_then(|s| s.parse::<u64>().ok());
NodedbStatement::CreateRlsPolicy {
name,
collection,
policy_type,
predicate_raw,
is_restrictive,
on_deny_raw,
tenant_id_override,
}
}
/// Strip at most one matched pair of outer parentheses.
fn strip_outer_parens(s: &str) -> String {
let trimmed = s.trim();
if trimmed.starts_with('(') && trimmed.ends_with(')') {
let inner = &trimmed[1..trimmed.len() - 1];
let mut depth = 0i32;
let mut balanced = true;
for ch in inner.chars() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth < 0 {
balanced = false;
break;
}
}
_ => {}
}
}
if balanced && depth == 0 {
return inner.trim().to_string();
}
}
trimmed.to_string()
}
/// Fallback: extract predicate text from the uppercased SQL string when
/// USING appears without space-separated parts matching (e.g. `USING(x=1)`).
fn extract_using_from_upper(upper: &str) -> String {
let Some(start) = upper.find("USING") else {
return String::new();
};
let after = &upper[start + 5..].trim_start();
if after.starts_with('(') {
let mut depth = 0usize;
let mut end = 0;
for (i, ch) in after.char_indices() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = i;
break;
}
}
_ => {}
}
}
after[1..end].trim().to_string()
} else {
String::new()
}
}