nodedb-sql 0.3.0

SQL parser, planner, and optimizer for NodeDB
Documentation
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// SPDX-License-Identifier: Apache-2.0

//! Parse top-level `GRANT` / `REVOKE` statements.
//!
//! Disambiguation follows the SQL standard: a `GRANT`/`REVOKE` with **no
//! `ON` clause** is a role-membership grant; one **with an `ON` clause** is
//! an object-permission grant. The `ROLE` keyword (`GRANT ROLE r TO u`) is
//! accepted as an optional alias for the no-`ON` form — it is not required.
//!
//! Both the role list and the permission list may be comma-separated.
//!
//! `SCOPE` / `DELEGATION` / `API KEY` grants belong to the admin router —
//! this family returns `None` for them so they fall through.

use crate::ddl_ast::statement::{AuthStmt, NodedbStatement};
use crate::error::SqlError;

pub(super) fn try_parse(
    upper: &str,
    parts: &[&str],
    _trimmed: &str,
) -> Option<Result<NodedbStatement, SqlError>> {
    if upper.starts_with("GRANT ") {
        if upper.starts_with("GRANT SCOPE ") {
            return None;
        }
        return Some(parse_grant_revoke(parts, true));
    }
    if upper.starts_with("REVOKE ")
        && !upper.starts_with("REVOKE SCOPE ")
        && !upper.starts_with("REVOKE DELEGATION ")
        && !upper.starts_with("REVOKE API KEY ")
    {
        return Some(parse_grant_revoke(parts, false));
    }
    None
}

/// Classify the object clause of a `GRANT/REVOKE ... ON ...` statement.
///
/// `after` is the token immediately following `ON`; `name_after` is the
/// token after that (consulted only when `after` is an explicit
/// object-type keyword). Returns `(target_type, target_name)`.
///
/// Object-type keywords (`FUNCTION`, `PROCEDURE`, `COLLECTION`, `TABLE`)
/// are matched explicitly so they can never be silently consumed as the
/// object name. `COLLECTION` and `TABLE` are accepted as the explicit
/// spelling of the default (collection) object type; a bare token with
/// no keyword is still treated as a collection name directly.
///
/// `DATABASE` and `TENANT` are not handled here — the caller intercepts
/// them first because they need different statement shapes.
pub(super) fn classify_object_clause(after: &str, name_after: Option<&str>) -> (String, String) {
    if after.eq_ignore_ascii_case("FUNCTION") {
        (
            "FUNCTION".to_string(),
            name_after.map(|s| s.to_lowercase()).unwrap_or_default(),
        )
    } else if after.eq_ignore_ascii_case("PROCEDURE") {
        (
            "PROCEDURE".to_string(),
            name_after.map(|s| s.to_lowercase()).unwrap_or_default(),
        )
    } else if after.eq_ignore_ascii_case("COLLECTION") || after.eq_ignore_ascii_case("TABLE") {
        (
            "COLLECTION".to_string(),
            name_after.map(|s| s.to_string()).unwrap_or_default(),
        )
    } else {
        ("COLLECTION".to_string(), after.to_string())
    }
}

/// Split a run of whitespace-separated tokens into a comma-separated list,
/// trimming each item. `["READ,", "WRITE"]` → `["READ", "WRITE"]`,
/// `["CREATE", "COLLECTION"]` → `["CREATE COLLECTION"]`.
fn split_list(tokens: &[&str]) -> Vec<String> {
    tokens
        .join(" ")
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}

fn parse_grant_revoke(parts: &[&str], is_grant: bool) -> Result<NodedbStatement, SqlError> {
    let pivot = if is_grant { "TO" } else { "FROM" };
    let kw = if is_grant { "GRANT" } else { "REVOKE" };

    let pivot_pos = parts
        .iter()
        .position(|p| p.eq_ignore_ascii_case(pivot))
        .ok_or_else(|| SqlError::Parse {
            detail: format!(
                "syntax: {kw} <role>[, ...] {pivot} <grantee> | \
                 {kw} <perm>[, ...] ON <object> {pivot} <grantee>"
            ),
        })?;

    let grantee = parts
        .get(pivot_pos + 1)
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| SqlError::Parse {
            detail: format!("{kw}: missing grantee after {pivot}"),
        })?;

    let on_pos = parts.iter().position(|p| p.eq_ignore_ascii_case("ON"));

    match on_pos {
        // Object-permission grant: an `ON` clause sits before the pivot.
        Some(on) if on < pivot_pos => {
            let permissions = split_list(&parts[1..on]);
            if permissions.is_empty() {
                return Err(SqlError::Parse {
                    detail: format!("{kw}: missing permission before ON"),
                });
            }
            let after = parts.get(on + 1).copied().unwrap_or_default();

            if after.eq_ignore_ascii_case("DATABASE") {
                // Database grants carry a single (possibly multi-word) privilege.
                let permission = parts[1..on].join(" ");
                let db_name = parts.get(on + 2).map(|s| s.to_string()).unwrap_or_default();
                return Ok(NodedbStatement::Auth(if is_grant {
                    AuthStmt::GrantDatabasePermission {
                        permission,
                        db_name,
                        grantee,
                    }
                } else {
                    AuthStmt::RevokeDatabasePermission {
                        permission,
                        db_name,
                        grantee,
                    }
                }));
            }

            if after.eq_ignore_ascii_case("TENANT") {
                // Tenant-scoped grant: the permission applies to every
                // collection in the named tenant. The handler resolves the
                // tenant name to its id.
                let tenant_name = parts
                    .get(on + 2)
                    .filter(|_| on + 2 < pivot_pos)
                    .map(|s| s.to_string())
                    .filter(|s| !s.is_empty())
                    .ok_or_else(|| SqlError::Parse {
                        detail: format!("{kw}: missing tenant name after ON TENANT"),
                    })?;
                return Ok(NodedbStatement::Auth(if is_grant {
                    AuthStmt::GrantPermission {
                        permissions,
                        target_type: "TENANT".to_string(),
                        target_name: tenant_name,
                        grantee,
                    }
                } else {
                    AuthStmt::RevokePermission {
                        permissions,
                        target_type: "TENANT".to_string(),
                        target_name: tenant_name,
                        grantee,
                    }
                }));
            }

            let (target_type, target_name) =
                classify_object_clause(after, parts.get(on + 2).copied());

            Ok(NodedbStatement::Auth(if is_grant {
                AuthStmt::GrantPermission {
                    permissions,
                    target_type,
                    target_name,
                    grantee,
                }
            } else {
                AuthStmt::RevokePermission {
                    permissions,
                    target_type,
                    target_name,
                    grantee,
                }
            }))
        }

        // Role-membership grant: no `ON` clause.
        _ => {
            // Accept a leading `ROLE` keyword as an optional alias.
            let start = if parts
                .get(1)
                .map(|s| s.eq_ignore_ascii_case("ROLE"))
                .unwrap_or(false)
            {
                2
            } else {
                1
            };
            let roles = split_list(&parts[start.min(pivot_pos)..pivot_pos]);
            if roles.is_empty() {
                return Err(SqlError::Parse {
                    detail: format!("{kw}: missing role name before {pivot}"),
                });
            }
            Ok(NodedbStatement::Auth(if is_grant {
                AuthStmt::GrantRole { roles, grantee }
            } else {
                AuthStmt::RevokeRole { roles, grantee }
            }))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(sql: &str) -> NodedbStatement {
        let upper = sql.to_uppercase();
        let parts: Vec<&str> = sql.split_whitespace().collect();
        try_parse(&upper, &parts, sql)
            .expect("expected Some")
            .expect("expected Ok")
    }

    #[test]
    fn grant_role_without_keyword() {
        match parse("GRANT tenant_admin TO eman") {
            NodedbStatement::Auth(AuthStmt::GrantRole { roles, grantee }) => {
                assert_eq!(roles, vec!["tenant_admin"]);
                assert_eq!(grantee, "eman");
            }
            other => panic!("expected GrantRole, got {other:?}"),
        }
    }

    #[test]
    fn grant_role_with_keyword_alias() {
        match parse("GRANT ROLE readwrite TO grace") {
            NodedbStatement::Auth(AuthStmt::GrantRole { roles, grantee }) => {
                assert_eq!(roles, vec!["readwrite"]);
                assert_eq!(grantee, "grace");
            }
            other => panic!("expected GrantRole, got {other:?}"),
        }
    }

    #[test]
    fn grant_comma_separated_roles() {
        match parse("GRANT readonly, readwrite TO multi") {
            NodedbStatement::Auth(AuthStmt::GrantRole { roles, .. }) => {
                assert_eq!(roles, vec!["readonly", "readwrite"]);
            }
            other => panic!("expected GrantRole, got {other:?}"),
        }
    }

    #[test]
    fn grant_comma_separated_permissions() {
        match parse("GRANT SELECT, INSERT ON orders TO analyst") {
            NodedbStatement::Auth(AuthStmt::GrantPermission {
                permissions,
                target_type,
                target_name,
                grantee,
            }) => {
                assert_eq!(permissions, vec!["SELECT", "INSERT"]);
                assert_eq!(target_type, "COLLECTION");
                assert_eq!(target_name, "orders");
                assert_eq!(grantee, "analyst");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_procedure() {
        match parse("GRANT EXECUTE ON PROCEDURE transfer_funds TO data_engineer") {
            NodedbStatement::Auth(AuthStmt::GrantPermission {
                target_type,
                target_name,
                ..
            }) => {
                assert_eq!(target_type, "PROCEDURE");
                assert_eq!(target_name, "transfer_funds");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_function() {
        match parse("GRANT EXECUTE ON FUNCTION full_name TO analyst") {
            NodedbStatement::Auth(AuthStmt::GrantPermission { target_type, .. }) => {
                assert_eq!(target_type, "FUNCTION");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_database_multiword_privilege() {
        match parse("GRANT CREATE COLLECTION ON DATABASE prod TO alice") {
            NodedbStatement::Auth(AuthStmt::GrantDatabasePermission {
                permission,
                db_name,
                grantee,
            }) => {
                assert_eq!(permission, "CREATE COLLECTION");
                assert_eq!(db_name, "prod");
                assert_eq!(grantee, "alice");
            }
            other => panic!("expected GrantDatabasePermission, got {other:?}"),
        }
    }

    #[test]
    fn revoke_role_without_keyword() {
        match parse("REVOKE tenant_admin FROM demoter") {
            NodedbStatement::Auth(AuthStmt::RevokeRole { roles, grantee }) => {
                assert_eq!(roles, vec!["tenant_admin"]);
                assert_eq!(grantee, "demoter");
            }
            other => panic!("expected RevokeRole, got {other:?}"),
        }
    }

    #[test]
    fn revoke_permission_on_collection() {
        match parse("REVOKE INSERT ON orders FROM analyst") {
            NodedbStatement::Auth(AuthStmt::RevokePermission {
                permissions,
                target_name,
                ..
            }) => {
                assert_eq!(permissions, vec!["INSERT"]);
                assert_eq!(target_name, "orders");
            }
            other => panic!("expected RevokePermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_scope_falls_through() {
        let upper = "GRANT SCOPE 'pro:all' TO ORG 'acme'".to_uppercase();
        let parts: Vec<&str> = "GRANT SCOPE 'pro:all' TO ORG 'acme'"
            .split_whitespace()
            .collect();
        assert!(try_parse(&upper, &parts, "").is_none());
    }

    #[test]
    fn grant_on_collection_keyword() {
        match parse("GRANT SELECT, INSERT ON COLLECTION chunks TO some_role") {
            NodedbStatement::Auth(AuthStmt::GrantPermission {
                permissions,
                target_type,
                target_name,
                grantee,
            }) => {
                assert_eq!(permissions, vec!["SELECT", "INSERT"]);
                assert_eq!(target_type, "COLLECTION");
                // The explicit `COLLECTION` object-type keyword must be
                // recognized, not consumed as the collection name itself.
                assert_ne!(target_name, "COLLECTION");
                assert_eq!(target_name, "chunks");
                assert_eq!(grantee, "some_role");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_table_keyword() {
        match parse("GRANT SELECT ON TABLE orders TO analyst") {
            NodedbStatement::Auth(AuthStmt::GrantPermission {
                target_type,
                target_name,
                ..
            }) => {
                assert_eq!(target_type, "COLLECTION");
                assert_ne!(target_name, "TABLE");
                assert_eq!(target_name, "orders");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn revoke_on_collection_keyword() {
        match parse("REVOKE INSERT ON COLLECTION orders FROM analyst") {
            NodedbStatement::Auth(AuthStmt::RevokePermission {
                target_type,
                target_name,
                ..
            }) => {
                assert_eq!(target_type, "COLLECTION");
                assert_ne!(target_name, "COLLECTION");
                assert_eq!(target_name, "orders");
            }
            other => panic!("expected RevokePermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_tenant_keyword() {
        match parse("GRANT BACKUP ON TENANT acme TO ops_user") {
            NodedbStatement::Auth(AuthStmt::GrantPermission {
                permissions,
                target_type,
                target_name,
                grantee,
            }) => {
                assert_eq!(permissions, vec!["BACKUP"]);
                assert_eq!(target_type, "TENANT");
                // The tenant name must be captured, not the `TENANT` keyword.
                assert_eq!(target_name, "acme");
                assert_eq!(grantee, "ops_user");
            }
            other => panic!("expected GrantPermission, got {other:?}"),
        }
    }

    #[test]
    fn revoke_on_tenant_keyword() {
        match parse("REVOKE SELECT, INSERT ON TENANT acme FROM ops_user") {
            NodedbStatement::Auth(AuthStmt::RevokePermission {
                permissions,
                target_type,
                target_name,
                ..
            }) => {
                assert_eq!(permissions, vec!["SELECT", "INSERT"]);
                assert_eq!(target_type, "TENANT");
                assert_eq!(target_name, "acme");
            }
            other => panic!("expected RevokePermission, got {other:?}"),
        }
    }

    #[test]
    fn grant_on_tenant_missing_name_is_error() {
        let sql = "GRANT BACKUP ON TENANT TO ops_user";
        let parts: Vec<&str> = sql.split_whitespace().collect();
        // `TO` is the token after `TENANT`; with no name the pivot still
        // parses, so the tenant name resolves empty → explicit error.
        assert!(matches!(
            try_parse(&sql.to_uppercase(), &parts, sql),
            Some(Err(SqlError::Parse { .. }))
        ));
    }

    #[test]
    fn grant_missing_pivot_is_error() {
        let upper = "GRANT readonly".to_uppercase();
        let parts: Vec<&str> = "GRANT readonly".split_whitespace().collect();
        assert!(matches!(
            try_parse(&upper, &parts, ""),
            Some(Err(SqlError::Parse { .. }))
        ));
    }
}