reddb-io-server 1.0.7

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
//! Query Mode Detection
//!
//! Automatically detects the query language based on syntax patterns.

/// Supported query modes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryMode {
    /// SQL-style: SELECT ... FROM ... WHERE
    Sql,
    /// Gremlin traversal: g.V().out().has(...)
    Gremlin,
    /// Cypher pattern matching: MATCH (a)-[r]->(b) RETURN
    Cypher,
    /// SPARQL RDF queries: SELECT ?var WHERE { ... }
    Sparql,
    /// Path queries: PATH FROM ... TO ... VIA
    Path,
    /// Natural language queries
    Natural,
    /// Unknown mode
    Unknown,
}

/// Detect the query mode from input string
pub fn detect_mode(input: &str) -> QueryMode {
    let trimmed = input.trim();
    let lower = trimmed.to_lowercase();

    // Check for quoted natural language (starts with quote)
    if trimmed.starts_with('"') || trimmed.starts_with('\'') {
        return QueryMode::Natural;
    }

    // Gremlin: starts with g. or __.
    if lower.starts_with("g.") || lower.starts_with("__.") {
        return QueryMode::Gremlin;
    }

    // Path: PATH or PATHS keyword at start
    if lower.starts_with("path ") || lower.starts_with("paths ") {
        return QueryMode::Path;
    }

    // SPARQL: has ?variable pattern or PREFIX keyword
    if lower.starts_with("prefix ") || has_sparql_pattern(&lower) {
        return QueryMode::Sparql;
    }

    // Cypher: MATCH keyword at start
    if lower.starts_with("match ") || lower.starts_with("match(") {
        return QueryMode::Cypher;
    }

    // SQL: SELECT, FROM, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, GRAPH, SEARCH at start
    // Plus transaction / admin one-word commands that have no trailing
    // clause (BEGIN/COMMIT/ROLLBACK/SAVEPOINT/RELEASE/VACUUM/ANALYZE/
    // RESET/TENANT/etc.) — matched by equality on the trimmed token.
    let first_token = lower.split_whitespace().next().unwrap_or("");
    if matches!(
        first_token,
        "begin"
            | "start"
            | "commit"
            | "rollback"
            | "savepoint"
            | "release"
            | "end"
            | "vacuum"
            | "analyze"
            | "reset"
            | "copy"
            | "refresh"
            | "explain"
            | "grant"
            | "revoke"
            | "attach"
            | "detach"
            | "simulate"
            | "apply"
            | "events"
    ) {
        return QueryMode::Sql;
    }
    if lower.starts_with("select ")
        || lower.starts_with("from ")
        || lower.starts_with("insert ")
        || lower.starts_with("update ")
        || lower.starts_with("delete ")
        || lower.starts_with("truncate ")
        || lower.starts_with("create ")
        || lower.starts_with("drop ")
        || lower.starts_with("alter ")
        || lower.starts_with("vector ")
        || lower.starts_with("hybrid ")
        || lower.starts_with("graph ")
        || lower.starts_with("queue ")
        || lower.starts_with("events ")
        || lower.starts_with("tree ")
        || lower.starts_with("vault ")
        || lower.starts_with("unseal vault ")
        || lower.starts_with("rotate vault ")
        || lower.starts_with("history vault ")
        || lower.starts_with("list vault ")
        || lower.starts_with("watch vault ")
        || lower.starts_with("delete vault ")
        || lower.starts_with("purge vault ")
        || lower.starts_with("search ")
        || lower.starts_with("ask ")
        || lower.starts_with("put config ")
        || lower.starts_with("get config ")
        || lower.starts_with("resolve config ")
        || lower.starts_with("rotate config ")
        || lower.starts_with("delete config ")
        || lower.starts_with("history config ")
        || lower.starts_with("list config ")
        || lower.starts_with("watch config ")
        || lower.starts_with("incr config ")
        || lower.starts_with("decr config ")
        || lower.starts_with("add config ")
        || lower.starts_with("invalidate config ")
        || lower.starts_with("invalidate tags ")
        || lower.starts_with("set config ")
        || lower.starts_with("set secret ")
        || lower.starts_with("set tenant")
        || lower.starts_with("show config")
        || lower.starts_with("show collections")
        || lower.starts_with("show tables")
        || lower.starts_with("show queues")
        || lower.starts_with("show vectors")
        || lower.starts_with("show documents")
        || lower.starts_with("show timeseries")
        || lower.starts_with("show graphs")
        || lower.starts_with("kv ")
        || lower.starts_with("show kv")
        || lower.starts_with("show configs")
        || lower.starts_with("show vaults")
        || lower.starts_with("show schema")
        || lower.starts_with("show indices")
        || lower.starts_with("show sample ")
        || lower.starts_with("show secret")
        || lower.starts_with("show stats")
        || lower.starts_with("show tenant")
        || lower.starts_with("show policies")
        || lower.starts_with("show effective ")
    {
        // But check if it's SPARQL-style SELECT with ?variable
        if lower.starts_with("select ") && lower.contains(" ?") {
            return QueryMode::Sparql;
        }
        return QueryMode::Sql;
    }

    // Natural language detection: common question words and patterns
    if is_natural_language(&lower) {
        return QueryMode::Natural;
    }

    QueryMode::Unknown
}

/// Check for SPARQL-specific patterns
fn has_sparql_pattern(lower: &str) -> bool {
    // SPARQL variables start with ? or $
    // SPARQL has WHERE { } with triple patterns

    // Check for ?variable pattern (not after comparison operators)
    let has_var = lower.contains(" ?") && !lower.contains("= ?") && !lower.contains("> ?");

    // Check for typical SPARQL structure
    let has_triple_pattern = lower.contains(" where {") || lower.contains(" where{");

    // Check for RDF predicates (prefixed URIs like :predicate or prefix:pred)
    let has_prefix_pattern = lower.contains(":")
        && (lower.contains(":<")
            || lower.contains("> :")
            || lower.contains(" :") && lower.contains("?"));

    has_var || has_triple_pattern || has_prefix_pattern
}

/// Detect natural language patterns
fn is_natural_language(lower: &str) -> bool {
    // Question words
    let question_starters = [
        "find ", "show ", "list ", "what ", "which ", "where ", "how ", "who ", "get ", "give ",
        "tell ", "display ", "search ", "look ",
    ];

    // Common natural language verbs/phrases
    let nl_patterns = [
        " with ",
        " for ",
        " that ",
        " have ",
        " has ",
        " can ",
        " are ",
        " is ",
        " all ",
        " me ",
        " the ",
        " from ",
        " to ",
        " on ",
        " in ",
        "vulnerable",
        "credential",
        "password",
        "user",
        "host",
        "service",
        "connected",
        "reachable",
        "exposed",
        "critical",
    ];

    // Check starters
    for starter in question_starters.iter() {
        if lower.starts_with(starter) {
            return true;
        }
    }

    // Check for multiple natural language patterns (at least 2)
    let pattern_count = nl_patterns.iter().filter(|p| lower.contains(*p)).count();

    pattern_count >= 2
}

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

    #[test]
    fn test_sql_detection() {
        assert_eq!(
            detect_mode("SELECT * FROM users WHERE id = 1"),
            QueryMode::Sql
        );
        assert_eq!(detect_mode("select name, age from hosts"), QueryMode::Sql);
        assert_eq!(
            detect_mode("FROM hosts h WHERE h.os = 'Linux'"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("INSERT INTO users VALUES (1, 'alice')"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("UPDATE hosts SET status = 'active'"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("DELETE FROM logs WHERE age > 30"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("QUEUE GROUP CREATE tasks workers"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("EVENTS BACKFILL users TO audit"),
            QueryMode::Sql
        );
        assert_eq!(detect_mode("TREE VALIDATE forest.org"), QueryMode::Sql);
        assert_eq!(
            detect_mode("VECTOR SEARCH embeddings SIMILAR TO [1.0, 0.0] LIMIT 5"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("HYBRID FROM hosts VECTOR SEARCH embeddings SIMILAR TO [1.0, 0.0] LIMIT 5"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("ASK 'what happened on host 10.0.0.1?' USING groq"),
            QueryMode::Sql
        );
        assert_eq!(
            detect_mode("SET SECRET red.secret.api = 'x'"),
            QueryMode::Sql
        );
        assert_eq!(detect_mode("SHOW SECRET red.secret"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW SECRETS"), QueryMode::Sql);
        assert_eq!(detect_mode("VAULT PUT secrets.api = 'x'"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW SAMPLE users"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW TABLES"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW QUEUES"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW VECTORS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW DOCUMENTS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW TIMESERIES"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW GRAPHS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW KV"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW KVS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW CONFIGS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW VAULTS"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW SCHEMA users"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW INDICES"), QueryMode::Sql);
        assert_eq!(detect_mode("SHOW STATS users"), QueryMode::Sql);
    }

    #[test]
    fn test_gremlin_detection() {
        assert_eq!(detect_mode("g.V()"), QueryMode::Gremlin);
        assert_eq!(detect_mode("g.V().hasLabel('host')"), QueryMode::Gremlin);
        assert_eq!(
            detect_mode("g.V().out('connects').in('has_service')"),
            QueryMode::Gremlin
        );
        assert_eq!(
            detect_mode("g.E().hasLabel('auth_access')"),
            QueryMode::Gremlin
        );
        assert_eq!(
            detect_mode("__.out('knows').has('name', 'bob')"),
            QueryMode::Gremlin
        );
        assert_eq!(
            detect_mode("g.V('host:10.0.0.1').repeat(out()).times(3)"),
            QueryMode::Gremlin
        );
    }

    #[test]
    fn test_cypher_detection() {
        assert_eq!(
            detect_mode("MATCH (a)-[r]->(b) RETURN a, b"),
            QueryMode::Cypher
        );
        assert_eq!(
            detect_mode("MATCH (h:Host)-[:HAS_SERVICE]->(s:Service)"),
            QueryMode::Cypher
        );
        assert_eq!(
            detect_mode("match (n) where n.ip = '10.0.0.1' return n"),
            QueryMode::Cypher
        );
        assert_eq!(
            detect_mode("MATCH(a:User) RETURN a.name"),
            QueryMode::Cypher
        );
    }

    #[test]
    fn test_sparql_detection() {
        assert_eq!(
            detect_mode("SELECT ?name WHERE { ?s :name ?name }"),
            QueryMode::Sparql
        );
        assert_eq!(
            detect_mode("PREFIX ex: <http://example.org/> SELECT ?x WHERE { ?x ex:type ?t }"),
            QueryMode::Sparql
        );
        assert_eq!(
            detect_mode("SELECT ?host ?ip WHERE { ?host :hasIP ?ip }"),
            QueryMode::Sparql
        );
    }

    #[test]
    fn test_path_detection() {
        assert_eq!(
            detect_mode("PATH FROM host('10.0.0.1') TO host('10.0.0.2')"),
            QueryMode::Path
        );
        assert_eq!(
            detect_mode("PATHS ALL FROM credential('admin') TO host('db')"),
            QueryMode::Path
        );
        assert_eq!(
            detect_mode("path from user('root') to service('ssh') via auth_access"),
            QueryMode::Path
        );
    }

    #[test]
    fn test_natural_detection() {
        assert_eq!(
            detect_mode("find all hosts with ssh open"),
            QueryMode::Natural
        );
        assert_eq!(
            detect_mode("show me vulnerable services"),
            QueryMode::Natural
        );
        assert_eq!(
            detect_mode("what credentials can reach the database?"),
            QueryMode::Natural
        );
        assert_eq!(
            detect_mode("list users with weak passwords"),
            QueryMode::Natural
        );
        assert_eq!(
            detect_mode("\"find hosts connected to 10.0.0.1\""),
            QueryMode::Natural
        );
        assert_eq!(
            detect_mode("which hosts have critical vulnerabilities?"),
            QueryMode::Natural
        );
    }

    #[test]
    fn test_edge_cases() {
        // Empty input
        assert_eq!(detect_mode(""), QueryMode::Unknown);

        // Just whitespace
        assert_eq!(detect_mode("   "), QueryMode::Unknown);

        // Case insensitivity
        assert_eq!(detect_mode("SELECT"), QueryMode::Unknown); // No space after
        assert_eq!(detect_mode("G.V()"), QueryMode::Gremlin);
        assert_eq!(detect_mode("Match (a) RETURN a"), QueryMode::Cypher);
    }
}