graphdblite 0.1.2

Embedded graph database with Cypher support. SQLite-grade simplicity, graph-native performance.
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 ds7n

use std::io::{self, BufRead, Write};

use graphdblite::{Database, Edge, Node, PathValue, Value};

#[derive(Clone, Copy, PartialEq, Eq)]
enum OutputMode {
    Table,
    Json,
}

fn main() {
    let args: Vec<String> = std::env::args().collect();

    let opts = parse_args(&args);

    let mut db = match &opts.db_path {
        Some(path) => Database::open(path).unwrap_or_else(|e| {
            eprintln!("error: failed to open {path}: {e}");
            std::process::exit(1);
        }),
        None => {
            eprintln!("error: database path required");
            eprintln!();
            print_usage();
            std::process::exit(1);
        }
    };

    match opts.query {
        Some(q) => run_query(&mut db, &q, opts.mode),
        None => run_repl(&mut db, opts.mode),
    }
}

struct Opts {
    db_path: Option<String>,
    query: Option<String>,
    mode: OutputMode,
}

fn parse_args(args: &[String]) -> Opts {
    let mut opts = Opts {
        db_path: None,
        query: None,
        mode: OutputMode::Table,
    };
    let mut i = 1;

    while i < args.len() {
        match args[i].as_str() {
            "-h" | "--help" => {
                print_usage();
                std::process::exit(0);
            }
            "-V" | "--version" => {
                println!("graphdblite {}", env!("CARGO_PKG_VERSION"));
                std::process::exit(0);
            }
            "-q" | "--query" => {
                i += 1;
                if i < args.len() {
                    opts.query = Some(args[i].clone());
                } else {
                    eprintln!("error: -q requires a query string");
                    std::process::exit(1);
                }
            }
            "-j" | "--json" => {
                opts.mode = OutputMode::Json;
            }
            arg if arg.starts_with('-') => {
                eprintln!("error: unknown flag: {arg}");
                std::process::exit(1);
            }
            _ => {
                if opts.db_path.is_none() {
                    opts.db_path = Some(args[i].clone());
                } else {
                    eprintln!("error: unexpected argument: {}", args[i]);
                    std::process::exit(1);
                }
            }
        }
        i += 1;
    }

    opts
}

fn print_usage() {
    eprintln!("graphdblite — embedded graph database CLI");
    eprintln!();
    eprintln!("Usage:");
    eprintln!("  graphdblite <db-path>                  Interactive REPL");
    eprintln!("  graphdblite <db-path> -q <cypher>      Run a single query");
    eprintln!();
    eprintln!("Flags:");
    eprintln!("  -h, --help     Show this help");
    eprintln!("  -V, --version  Print version and exit");
    eprintln!("  -q, --query    Execute a single Cypher query and exit");
    eprintln!("  -j, --json     Output NDJSON (one JSON object per row)");
    eprintln!();
    eprintln!("Examples:");
    eprintln!("  graphdblite my.db");
    eprintln!("  graphdblite my.db -q \"MATCH (n:Person) RETURN n.name\"");
    eprintln!("  graphdblite my.db -j -q \"MATCH (n:Person) RETURN n.name\"");
    eprintln!();
    eprintln!("REPL commands:");
    eprintln!("  .help              Show REPL help");
    eprintln!("  .mode table|json   Switch output mode");
    eprintln!("  .quit / .exit      Exit");
}

fn run_query(db: &mut Database, cypher: &str, mode: OutputMode) {
    // Always use a write transaction. The CLI is single-threaded and runs one
    // query per invocation, so any "read-only" optimization to acquire a
    // deferred txn is not worth dragging the parser into this binary.
    let tx = db.write_tx().unwrap_or_else(|e| {
        eprintln!("error: {e}");
        std::process::exit(1);
    });
    match tx.query(cypher) {
        Ok(records) => {
            print_records(&records, mode);
            tx.commit().unwrap_or_else(|e| {
                eprintln!("error committing: {e}");
                std::process::exit(1);
            });
        }
        Err(e) => {
            eprintln!("error: {e}");
            let _ = tx.rollback();
        }
    }
}

fn run_repl(db: &mut Database, initial_mode: OutputMode) {
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    let mut mode = initial_mode;

    eprintln!("graphdblite v{}", env!("CARGO_PKG_VERSION"));
    eprintln!("Type Cypher queries. Press Ctrl-D to exit. Type .help for commands.");
    eprintln!();

    loop {
        print!("cypher> ");
        stdout.flush().unwrap();

        let mut line = String::new();
        match stdin.lock().read_line(&mut line) {
            Ok(0) => break, // EOF
            Ok(_) => {}
            Err(e) => {
                eprintln!("read error: {e}");
                break;
            }
        }

        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        if trimmed == ".quit" || trimmed == ".exit" {
            break;
        }

        if trimmed == ".help" {
            eprintln!("Commands:");
            eprintln!("  .help              Show this help");
            eprintln!(
                "  .mode table|json   Switch output mode (current: {})",
                mode_name(mode)
            );
            eprintln!("  .quit / .exit      Exit the REPL");
            eprintln!();
            eprintln!("Enter any Cypher query to execute it.");
            continue;
        }

        if let Some(rest) = trimmed.strip_prefix(".mode") {
            match rest.trim() {
                "table" => {
                    mode = OutputMode::Table;
                    eprintln!("output mode: table");
                }
                "json" => {
                    mode = OutputMode::Json;
                    eprintln!("output mode: json");
                }
                "" => eprintln!(
                    "current mode: {} (use .mode table | .mode json)",
                    mode_name(mode)
                ),
                other => eprintln!("error: unknown mode '{other}' (expected: table, json)"),
            }
            continue;
        }

        if trimmed.starts_with('.') {
            eprintln!("error: unknown command '{trimmed}' (try .help)");
            continue;
        }

        run_query(db, trimmed, mode);
    }
}

fn mode_name(mode: OutputMode) -> &'static str {
    match mode {
        OutputMode::Table => "table",
        OutputMode::Json => "json",
    }
}

fn visible_columns(rec: &graphdblite::Record) -> Vec<&String> {
    let mut cols: Vec<&String> = rec.keys().filter(|k| !k.contains(".__")).collect();
    cols.sort();
    cols
}

fn print_records(records: &[graphdblite::Record], mode: OutputMode) {
    match mode {
        OutputMode::Table => print_records_table(records),
        OutputMode::Json => print_records_json(records),
    }
}

fn print_records_json(records: &[graphdblite::Record]) {
    let stdout = io::stdout();
    let mut out = stdout.lock();
    for rec in records {
        let cols = visible_columns(rec);
        let mut s = String::from("{");
        for (i, col) in cols.iter().enumerate() {
            if i > 0 {
                s.push(',');
            }
            json_escape_into(col, &mut s);
            s.push(':');
            value_to_json(rec.get(col).unwrap_or(&Value::Null), &mut s);
        }
        s.push('}');
        let _ = writeln!(out, "{s}");
    }
}

fn print_records_table(records: &[graphdblite::Record]) {
    if records.is_empty() {
        println!("(no results)");
        return;
    }

    let columns = visible_columns(&records[0]);

    if columns.is_empty() {
        println!("(empty record)");
        return;
    }

    // Compute column widths.
    let mut widths: Vec<usize> = columns.iter().map(|c| c.len()).collect();
    for rec in records {
        for (i, col) in columns.iter().enumerate() {
            let val_str = format_value(rec.get(col));
            widths[i] = widths[i].max(val_str.len());
        }
    }

    // Print header.
    let header: String = columns
        .iter()
        .enumerate()
        .map(|(i, c)| format!("{:width$}", c, width = widths[i]))
        .collect::<Vec<_>>()
        .join(" | ");
    println!("{header}");

    // Separator.
    let sep: String = widths
        .iter()
        .map(|w| "-".repeat(*w))
        .collect::<Vec<_>>()
        .join("-+-");
    println!("{sep}");

    // Print rows.
    for rec in records {
        let row: String = columns
            .iter()
            .enumerate()
            .map(|(i, col)| {
                let val_str = format_value(rec.get(col));
                format!("{:width$}", val_str, width = widths[i])
            })
            .collect::<Vec<_>>()
            .join(" | ");
        println!("{row}");
    }

    println!();
    println!("{} row(s)", records.len());
}

fn format_value(val: Option<&Value>) -> String {
    match val {
        None | Some(Value::Null) => "null".to_string(),
        Some(Value::Bool(b)) => b.to_string(),
        Some(Value::I64(n)) => n.to_string(),
        Some(Value::F64(n)) => format!("{n:.6}"),
        Some(Value::String(s)) => s.clone(),
        Some(Value::List(items)) => format!("{}", Value::List(items.clone())),
        Some(p @ Value::Path(_)) => format!("{p}"),
        Some(m @ Value::Map(_)) => format!("{m}"),
        Some(n @ Value::Node(_)) => format!("{n}"),
        Some(e @ Value::Edge(_)) => format!("{e}"),
        Some(other) => format!("{other}"),
    }
}

// --- minimal JSON serialization (avoids pulling serde_json into the lib) ---

fn value_to_json(v: &Value, out: &mut String) {
    match v {
        Value::Null => out.push_str("null"),
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::I64(n) => out.push_str(&n.to_string()),
        Value::F64(n) => {
            // JSON has no NaN/Infinity — coerce to null per common convention.
            if n.is_finite() {
                out.push_str(&format!("{n}"));
            } else {
                out.push_str("null");
            }
        }
        Value::String(s) => json_escape_into(s, out),
        Value::List(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                value_to_json(item, out);
            }
            out.push(']');
        }
        Value::Map(map) => {
            out.push('{');
            for (i, (k, val)) in map.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                json_escape_into(k, out);
                out.push(':');
                value_to_json(val, out);
            }
            out.push('}');
        }
        Value::Node(n) => node_to_json(n, out),
        Value::Edge(e) => edge_to_json(e, out),
        Value::Path(p) => path_to_json(p, out),
        // Temporal types: ISO-8601 strings via Display.
        Value::Date(d) => json_escape_into(&d.to_string(), out),
        Value::LocalTime(t) => json_escape_into(&t.to_string(), out),
        Value::Time(t) => json_escape_into(&t.to_string(), out),
        Value::LocalDateTime(dt) => json_escape_into(&dt.to_string(), out),
        Value::DateTime(dt) => json_escape_into(&dt.to_string(), out),
        Value::Duration(d) => json_escape_into(&d.to_string(), out),
    }
}

fn node_to_json(n: &Node, out: &mut String) {
    out.push_str("{\"__type\":\"node\",\"id\":");
    out.push_str(&n.id.0.to_string());
    out.push_str(",\"labels\":[");
    for (i, l) in n.labels.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_escape_into(l, out);
    }
    out.push_str("],\"properties\":");
    properties_to_json(&n.properties, out);
    out.push('}');
}

fn edge_to_json(e: &Edge, out: &mut String) {
    out.push_str("{\"__type\":\"edge\",\"src\":");
    out.push_str(&e.src.0.to_string());
    out.push_str(",\"dst\":");
    out.push_str(&e.dst.0.to_string());
    out.push_str(",\"label\":");
    json_escape_into(&e.label, out);
    out.push_str(",\"properties\":");
    properties_to_json(&e.properties, out);
    out.push('}');
}

fn path_to_json(p: &PathValue, out: &mut String) {
    out.push_str("{\"__type\":\"path\",\"nodes\":[");
    for (i, n) in p.nodes.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        node_to_json(n, out);
    }
    out.push_str("],\"edges\":[");
    for (i, e) in p.edges.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        edge_to_json(e, out);
    }
    out.push_str("]}");
}

fn properties_to_json(props: &graphdblite::Properties, out: &mut String) {
    let mut keys: Vec<&String> = props.keys().collect();
    keys.sort();
    out.push('{');
    for (i, k) in keys.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_escape_into(k, out);
        out.push(':');
        value_to_json(&props[*k], out);
    }
    out.push('}');
}

fn json_escape_into(s: &str, out: &mut String) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\x08' => out.push_str("\\b"),
            '\x0c' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out.push('"');
}