linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! User Management Statement Parsing Module
//!
//! Responsible for parsing statements related to user management, including CREATE USER, ALTER USER, DROP USER, CHANGE PASSWORD, etc.

use crate::parser::ast::stmt::*;
use crate::parser::ast::types::Span;
use crate::parser::core::error::{ParseError, ParseErrorKind};
use crate::parser::parsing::parse_context::ParseContext;
use crate::parser::TokenKind;

/// User Management Parser
pub struct UserParser;

impl UserParser {
    pub fn new() -> Self {
        Self
    }

    /// Analysis of the CREATE USER statement
    pub fn parse_create_user_statement(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::CreateUser)?;
        self.parse_create_user_internal(ctx, start_span)
    }

    /// Analysis of the CREATE USER statement (the CREATE token has already been consumed)
    pub fn parse_create_user_statement_after_create(
        &mut self,
        ctx: &mut ParseContext,
        start_span: Span,
    ) -> Result<Stmt, ParseError> {
        ctx.expect_token(TokenKind::User)?;
        self.parse_create_user_internal(ctx, start_span)
    }

    /// Analyzing the internal implementation of the CREATE USER statement
    fn parse_create_user_internal(
        &mut self,
        ctx: &mut ParseContext,
        start_span: Span,
    ) -> Result<Stmt, ParseError> {
        let mut if_not_exists = false;
        if ctx.match_token(TokenKind::If) {
            ctx.expect_token(TokenKind::Not)?;
            ctx.expect_token(TokenKind::Exists)?;
            if_not_exists = true;
        }

        let username = ctx.expect_dcl_name()?;

        // Password is optional for Nebula compatibility; when omitted it
        // defaults to an empty password that still has to pass the password
        // policy at execution time.
        let mut password = String::new();
        if ctx.match_token(TokenKind::With) {
            // Nebula writes `WITH PASSWORD '...'`; the PASSWORD keyword is
            // accepted but optional so both spellings parse.
            ctx.match_token(TokenKind::Password);
            password = ctx.expect_string_literal()?;
        } else if ctx.match_token(TokenKind::Password) {
            password = ctx.expect_string_literal()?;
        } else if matches!(ctx.current_token().kind, TokenKind::StringLiteral(_)) {
            // Bare `CREATE USER name 'password'` is also accepted.
            password = ctx.expect_string_literal()?;
        }

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::CreateUser(CreateUserStmt {
            span,
            username,
            password,
            if_not_exists,
        }))
    }

    /// Analysis of the ALTER USER statement
    pub fn parse_alter_user_statement(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::AlterUser)?;
        self.parse_alter_user_internal(ctx, start_span)
    }

    /// Analysis of the internal implementation of the ALTER USER command
    pub fn parse_alter_user_internal(
        &mut self,
        ctx: &mut ParseContext,
        start_span: Span,
    ) -> Result<Stmt, ParseError> {
        ctx.expect_token(TokenKind::User)?;

        let username = ctx.expect_dcl_name()?;

        let mut password = None;
        let mut is_locked = None;

        // Analyzing the WITH PASSWORD clause
        if ctx.match_token(TokenKind::With) {
            ctx.expect_token(TokenKind::Password)?;
            password = Some(ctx.expect_string_literal()?);
        }

        // The SET LOCKED = <true|false> syntax is also supported.
        while ctx.match_token(TokenKind::Set) {
            if ctx.match_token(TokenKind::Locked) {
                ctx.expect_token(TokenKind::Assign)?;
                is_locked = Some(ctx.expect_boolean_literal()?);
            } else {
                return Err(ParseError::new(
                    ParseErrorKind::SyntaxError,
                    "Expected LOCKED after SET in ALTER USER".to_string(),
                    ctx.current_position(),
                ));
            }
        }

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::AlterUser(AlterUserStmt {
            span,
            username,
            password,
            is_locked,
        }))
    }

    /// Analysis of the DROP USER statement
    pub fn parse_drop_user_statement(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::DropUser)?;

        let mut if_exists = false;
        if ctx.match_token(TokenKind::If) {
            ctx.expect_token(TokenKind::Exists)?;
            if_exists = true;
        }

        let username = ctx.expect_dcl_name()?;

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::DropUser(DropUserStmt {
            span,
            username,
            if_exists,
        }))
    }

    /// Analysis of the CHANGE PASSWORD statement
    pub fn parse_change_password_statement(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::ChangePassword)?;

        self.parse_change_password_internal(ctx, start_span)
    }

    /// Analysis of the internal implementation of the “CHANGE PASSWORD” command
    pub fn parse_change_password_internal(
        &mut self,
        ctx: &mut ParseContext,
        start_span: Span,
    ) -> Result<Stmt, ParseError> {
        // Parse the optional username. A username is present only when the next
        // token is not the old password literal and not the Nebula `FROM`
        // keyword that introduces the old password.
        let username = if matches!(ctx.current_token().kind, TokenKind::StringLiteral(_))
            || ctx.check_token(TokenKind::From)
        {
            None
        } else {
            Some(ctx.expect_dcl_name()?)
        };

        // Nebula spells `CHANGE PASSWORD name FROM 'old' TO 'new'`; both that
        // form and the shorter positional form are accepted here.
        ctx.match_token(TokenKind::From);

        let old_password = ctx.expect_string_literal()?;
        ctx.expect_token(TokenKind::To)?;
        let new_password = ctx.expect_string_literal()?;

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::ChangePassword(ChangePasswordStmt {
            span,
            username,
            old_password,
            new_password,
        }))
    }

    /// Analysis of the CHANGE statement (currently only CHANGE PASSWORD is supported)
    pub fn parse_change_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Change)?;

        // Check whether it is “CHANGE PASSWORD”.
        if ctx.match_token(TokenKind::Password) {
            return self.parse_change_password_internal(ctx, start_span);
        }

        Err(ParseError::new(
            ParseErrorKind::UnexpectedToken,
            "Expected PASSWORD after CHANGE".to_string(),
            ctx.current_position(),
        ))
    }

    /// Analyzing character types (supporting keyword-based searches)
    fn parse_role_type(&mut self, ctx: &mut ParseContext) -> Result<RoleType, ParseError> {
        let token = ctx.current_token();
        let role_str = match token.kind {
            TokenKind::God => {
                ctx.next_token();
                "GOD".to_string()
            }
            TokenKind::Admin => {
                ctx.next_token();
                "ADMIN".to_string()
            }
            TokenKind::Dba => {
                ctx.next_token();
                "DBA".to_string()
            }
            TokenKind::Guest => {
                ctx.next_token();
                "GUEST".to_string()
            }
            TokenKind::User => {
                ctx.next_token();
                "USER".to_string()
            }
            _ => ctx.expect_identifier()?,
        };

        role_str
            .parse::<RoleType>()
            .map_err(|e| ParseError::new(ParseErrorKind::SyntaxError, e, ctx.current_position()))
    }

    /// Analysis of the GRANT statement
    /// Syntax:  `GRANT ROLE <role_type> ON <space_name> TO <username>`
    pub fn parse_grant_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Grant)?;

        // Analyzing the ROLE keyword (optional)
        let _ = ctx.match_token(TokenKind::Role);

        // Analyzing character types
        let role = self.parse_role_type(ctx)?;

        // Analysis of the ON keyword
        ctx.expect_token(TokenKind::On)?;

        // Analysis of the Space name
        let space_name = ctx.expect_dcl_name()?;

        // Analysis of the TO keyword
        ctx.expect_token(TokenKind::To)?;

        // Analyzing the username
        let username = ctx.expect_dcl_name()?;

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::Grant(GrantStmt {
            span,
            role,
            space_name,
            username,
        }))
    }

    /// Analysis of the REVOKE statement
    /// Syntax: `REVOKE ROLE <role_type> ON <space_name> FROM <username>`
    pub fn parse_revoke_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Revoke)?;

        // Analysis of the ROLE keyword (optional)
        let _ = ctx.match_token(TokenKind::Role);

        // Analyzing character types
        let role = self.parse_role_type(ctx)?;

        // Analysis of the ON keyword
        ctx.expect_token(TokenKind::On)?;

        // Analyzing the name “Space”
        let space_name = ctx.expect_dcl_name()?;

        // Analysis of the FROM keyword
        ctx.expect_token(TokenKind::From)?;

        // Analyzing the username
        let username = ctx.expect_dcl_name()?;

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::Revoke(RevokeStmt {
            span,
            role,
            space_name,
            username,
        }))
    }
}

impl Default for UserParser {
    fn default() -> Self {
        Self::new()
    }
}

// ==================== Unit Tests ====================

#[cfg(test)]
mod tests {
    use crate::parser::Parser;

    #[test]
    fn test_parse_create_user_unicode_username() {
        let query = "CREATE USER ユーザー WITH PASSWORD 'password'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Unicode username should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_unicode_password() {
        let query = "CREATE USER testuser WITH PASSWORD 'パスワード123'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Unicode password should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_special_chars_username() {
        let query = "CREATE USER user_123_test WITH PASSWORD 'password'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Username with numbers and underscores should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_special_chars_password() {
        let query = "CREATE USER user WITH PASSWORD 'P@$$w0rd!#%&*'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Password with special chars should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_rejects_with_role() {
        let query = "CREATE USER testuser WITH PASSWORD 'pass' WITH ROLE ADMIN";
        let mut parser = Parser::new(query);
        assert!(
            parser.parse().is_err(),
            "WITH ROLE is no longer part of CREATE USER syntax"
        );
    }

    #[test]
    fn test_parse_alter_user_set_locked() {
        for (value, expected) in [("true", true), ("false", false)] {
            let query = format!("ALTER USER testuser SET LOCKED = {}", value);
            let mut parser = Parser::new(&query);
            let result = parser.parse();
            assert!(
                result.is_ok(),
                "SET LOCKED = {} should parse: {:?}",
                value,
                result.err()
            );
            match result.expect("parsed").ast.stmt() {
                crate::parser::ast::Stmt::AlterUser(stmt) => {
                    assert_eq!(stmt.is_locked, Some(expected))
                }
                other => panic!("expected AlterUser, got {:?}", other),
            }
        }
    }

    #[test]
    fn test_parse_alter_user_set_locked_rejects_non_boolean() {
        for query in [
            "ALTER USER testuser SET LOCKED = yes",
            "ALTER USER testuser SET LOCKED = 1",
        ] {
            let mut parser = Parser::new(query);
            assert!(
                parser.parse().is_err(),
                "{} should be rejected, not silently treated as false",
                query
            );
        }
    }

    #[test]
    fn test_parse_alter_user_set_role_rejected() {
        let mut parser = Parser::new("ALTER USER testuser SET ROLE = DBA");
        assert!(
            parser.parse().is_err(),
            "SET ROLE is no longer part of ALTER USER syntax"
        );
    }

    #[test]
    fn test_parse_create_user_case_insensitive_keywords() {
        let query = "create user testuser with password 'pass'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Lowercase keywords should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_alter_user_unicode() {
        let query = "ALTER USER ユーザー WITH PASSWORD 'ニューパスワード'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "ALTER USER with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_drop_user_unicode() {
        let query = "DROP USER ユーザー";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "DROP USER with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_change_password_unicode() {
        let query = "CHANGE PASSWORD ユーザー 'オールドパスワード' TO 'ニューパスワード'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "CHANGE PASSWORD with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_grant_unicode() {
        let query = "GRANT ADMIN ON スペース TO ユーザー";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "GRANT with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_revoke_unicode() {
        let query = "REVOKE ADMIN ON スペース FROM ユーザー";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "REVOKE with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_describe_user_unicode() {
        let query = "DESCRIBE USER ユーザー";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "DESCRIBE USER with unicode should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_show_roles_with_unicode_space() {
        let query = "SHOW ROLES IN スペース";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "SHOW ROLES IN with unicode space should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_long_username() {
        let long_username = "a".repeat(255);
        let query = format!("CREATE USER {} WITH PASSWORD 'pass'", long_username);
        let mut parser = Parser::new(&query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Long username should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_long_password() {
        let long_password = "a".repeat(1000);
        let query = format!("CREATE USER user WITH PASSWORD '{}'", long_password);
        let mut parser = Parser::new(&query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Long password should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_create_user_empty_like_password() {
        let query = "CREATE USER user WITH PASSWORD 'a'";
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Single char password should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_grant_case_insensitive_role() {
        for role_case in ["ADMIN", "Admin", "admin"] {
            let query = format!("GRANT {} ON space TO user", role_case);
            let mut parser = Parser::new(&query);
            let result = parser.parse();
            assert!(
                result.is_ok(),
                "GRANT with role case {} should parse: {:?}",
                role_case,
                result.err()
            );
        }
    }

    #[test]
    fn test_parse_show_roles_with_and_without_space() {
        let query1 = "SHOW ROLES";
        let query2 = "SHOW ROLES IN myspace";

        let mut parser1 = Parser::new(query1);
        let result1 = parser1.parse();
        assert!(
            result1.is_ok(),
            "SHOW ROLES without space should parse: {:?}",
            result1.err()
        );

        let mut parser2 = Parser::new(query2);
        let result2 = parser2.parse();
        assert!(
            result2.is_ok(),
            "SHOW ROLES with space should parse: {:?}",
            result2.err()
        );
    }

    #[test]
    fn test_parse_whitespace_handling() {
        let queries = vec![
            "CREATE  USER  user  WITH  PASSWORD  'pass'",
            "CREATE\tUSER\tuser\tWITH\tPASSWORD\t'pass'",
            "CREATE\nUSER\nuser\nWITH\nPASSWORD\n'pass'",
        ];

        for query in queries {
            let mut parser = Parser::new(query);
            let result = parser.parse();
            assert!(
                result.is_ok(),
                "Query with extra whitespace should parse: {:?}",
                result.err()
            );
        }
    }
}