Skip to main content

sqlitegraph_cli/
cli.rs

1#[derive(Clone, Debug, PartialEq, Eq)]
2pub struct CommandLineConfig {
3    pub backend: String,
4    pub database: String,
5    pub command: String,
6    pub command_args: Vec<String>,
7}
8
9impl CommandLineConfig {
10    pub fn from_args(args: &[&str]) -> Result<Self, String> {
11        let mut backend = String::from("sqlite");
12        let mut database = String::from("memory");
13        let mut command = String::from("status");
14        let mut command_args = Vec::new();
15        let mut command_set = false;
16        let mut iter = args.iter().skip(1);
17        while let Some(arg) = iter.next() {
18            if command_set {
19                command_args.push(arg.to_string());
20                continue;
21            }
22            match *arg {
23                "--backend" => {
24                    backend = iter
25                        .next()
26                        .ok_or_else(|| "--backend requires a value".to_string())?
27                        .to_string();
28                }
29                "--db" | "--database" => {
30                    database = iter
31                        .next()
32                        .ok_or_else(|| "--db requires a value".to_string())?
33                        .to_string();
34                }
35                "--command" => {
36                    command = iter
37                        .next()
38                        .ok_or_else(|| "--command requires a value".to_string())?
39                        .to_string();
40                    command_set = true;
41                }
42                other if other.starts_with('-') => {
43                    return Err(format!("unknown flag {other}"));
44                }
45                _ => {
46                    command = arg.to_string();
47                    command_set = true;
48                }
49            }
50        }
51        Ok(Self {
52            backend,
53            database,
54            command,
55            command_args,
56        })
57    }
58
59    pub fn help() -> &'static str {
60        r#"Usage: sqlitegraph [--backend sqlite|native] [--db memory|PATH] [command] [args]
61
62Commands:
63  status                    Show database status and statistics
64  list                      List all entities in the graph
65  kv-scan --prefix PREFIX   Scan KV store by key prefix (native-v2 only)
66  nodes-by-kind --kind KIND Find all nodes with given kind
67  nodes-by-name --pattern PATTERN  Find nodes matching name pattern (*, ? wildcards)
68  migrate [--dry-run]       Run pending schema migrations
69  dump-graph --output PATH  Dump graph data to file
70  load-graph --input PATH   Load graph data from file
71  bulk-insert-entities --input FILE  Bulk insert entities from JSON
72  bulk-insert-edges --input FILE    Bulk insert edges from JSON
73  bfs --start ID --max-depth N    Breadth-first search traversal
74  k-hop --start ID --depth N [--direction incoming|outgoing]  K-hop neighbor query
75  shortest-path --from ID --to ID    Find shortest path between nodes
76  neighbors --id ID [--direction incoming|outgoing]  Direct neighbor query
77  pattern-match --edge-type TYPE [--start-label LABEL] [--end-label LABEL] [--direction incoming|outgoing] [--start-prop KEY:VAL] [--end-prop KEY:VAL]  Match triple patterns
78  pattern-match-fast --edge-type TYPE [--start-label LABEL] [--end-label LABEL] [--direction incoming|outgoing] [--start-prop KEY:VAL] [--end-prop KEY:VAL]  Fast-path pattern match
79  forward-reachability --start ID    Find all nodes reachable from start node
80  backward-reachability --target ID  Find all nodes that can reach target node
81  can-reach --from ID --to ID        Check if from node can reach to node
82  unreachable-nodes --entry ID       Find nodes unreachable from entry point
83  hnsw-create --dimension N --m M --ef-construction N --distance-metric TYPE [--index-name NAME]  Create HNSW index
84  hnsw-insert --input FILE [--name NAME]  Insert vectors into HNSW index
85  hnsw-search --input FILE --k N [--name NAME]  Search HNSW index
86  hnsw-stats [--name NAME]                Show HNSW index statistics
87  hnsw-list                               List all HNSW indexes in database
88  hnsw-delete --index-name NAME           Delete HNSW index and all vectors
89  hnsw-info [--index-name NAME]           Show detailed HNSW index information
90  wal-checkpoint            Trigger WAL checkpoint operation
91  wal-metrics                Show WAL performance metrics and file sizes
92  wal-config                 Show WAL configuration settings
93  wal-stats                  Show detailed WAL statistics with derived metrics
94  snapshot-create --dir DIR  Create database snapshot
95  snapshot-load --dir DIR     Load database snapshot
96  debug-stats                Show graph introspection data (JSON)
97  debug-dump --output PATH   Export graph structure for debugging
98  debug-trace COMMAND [...]  Enable trace logging for specific operation
99  pagerank --iterations N [--damping-factor F]   PageRank centrality algorithm
100  betweenness                Betweenness centrality algorithm
101  louvain [--max-iterations N]    Louvain community detection algorithm
102  enumerate-paths --start ID [--max-depth N] [--max-paths N]  Enumerate execution paths with bounds
103  enumerate-paths-constrained --start ID [--enable-dominance] [--enable-cd] [--enable-loops]  Path enumeration with pruning
104  critical-path              Longest weighted path in DAG (bottleneck identification)
105  cycle-basis [--max-cycles N] [--max-cycle-length N]  Minimal cycle basis for cycle explanation
106  wcc                       Weakly Connected Components (undirected connectivity)
107  scc                       Strongly Connected Components (Tarjan's algorithm)
108  transitive-closure [--max-depth N] [--max-sources N] [--max-pairs N]  All-pairs reachability
109  transitive-reduction      Remove redundant edges while preserving reachability
110  topological-sort          Topological ordering of nodes in DAGs
111  structural-similarity --graph1 ID --graph2 ID  Structural similarity using isomorphism and MCS
112  graph-diff --before PATH --after PATH  Structural graph delta between two snapshots
113  validate-refactor --before PATH --after PATH  Refactor validation with safety heuristics
114  taint-forward --sources-file FILE    Forward taint propagation from sources to sinks
115  taint-backward --sink ID --sources-file FILE  Backward taint propagation from sink to sources
116  sink-analysis --sources-file FILE --sinks-file FILE  Full vulnerability detection (all sinks)
117  discover-sources-sinks             Discover sources/sinks using metadata-based detectors
118  backward-slice --target ID         Backward program slicing (what affects this node?)
119  forward-slice --source ID          Forward program slicing (what does this affect?)
120  collapse-scc                       Collapse SCCs into supernodes for call graph analysis
121  min-cut --source ID --sink ID      Minimum s-t edge cut for fault tolerance analysis
122  min-vertex-cut --source ID --sink ID  Minimum vertex cut for critical node identification
123  dominators --entry ID              Compute dominators and immediate dominator tree
124  post-dominators [--exit ID]        Compute post-dominators (auto-detects exit if omitted)
125  control-dependence [--exit ID]     Compute Control Dependence Graph
126  dominance-frontiers --entry ID     Compute dominance frontiers for SSA phi-placement
127  natural-loops --entry ID           Detect natural loops using back-edge dominance
128  happens-before --events-file FILE  Event ordering analysis for concurrent traces
129  impact-radius --start ID [--max-distance N]  Blast zone computation using bounded reachability
130  partition --k N [--max-size N]      Size-bounded k-way graph partitioning
131  subgraph-isomorphism --pattern-file FILE  Bounded subgraph isomorphism for pattern matching
132  graph-rewrite --rules-file FILE    DPO-style graph rewriting for pattern transformation
133
134Traversal Options:
135  --start                   Starting node ID for traversal
136  --max-depth                Maximum depth for BFS (default: 3)
137  --depth                    Hop depth for k-hop (default: 2)
138  --direction               Traversal direction: incoming|outgoing (default: outgoing)
139  --from                     Source node ID for shortest path or can-reach
140  --to                       Target node ID for shortest path or can-reach
141  --id                       Node ID for neighbors query
142  --target                   Target node ID for backward reachability or backward-slice
143  --entry                    Entry node ID for unreachable nodes
144  --source                   Source node ID for forward-slice, min-cut, or min-vertex-cut
145  --sink                     Sink node ID for min-cut or min-vertex-cut
146
147Pattern Options:
148  --edge-type                Edge type to match (required)
149  --start-label              Start node label filter
150  --end-label                End node label filter
151  --start-prop               Start node property filter (format: key:value)
152  --end-prop                 End node property filter (format: key:value)
153
154HNSW Options:
155  --dimension               Vector dimension (e.g., 768)
156  --m                       Number of bi-directional links (default: 16)
157  --ef-construction         HNSW ef_construction parameter (default: 200)
158  --distance-metric         Distance metric: cosine|euclidean|dot|manhattan
159  --index-name              Index name for create (default: "default")
160  --name                    Index name for insert/search/stats (default: "default")
161  --k                       Number of nearest neighbors to return
162
163Examples:
164  sqlitegraph status
165  sqlitegraph --db /path/to/graph.db list
166  sqlitegraph bfs --start 123 --max-depth 3
167  sqlitegraph k-hop --start 123 --depth 2 --direction outgoing
168  sqlitegraph shortest-path --from 123 --to 456
169  sqlitegraph neighbors --id 123 --direction incoming
170  sqlitegraph forward-reachability --start 123
171  sqlitegraph backward-reachability --target 456
172  sqlitegraph can-reach --from 123 --to 456
173  sqlitegraph unreachable-nodes --entry 1
174  sqlitegraph bulk-insert-entities --input entities.json
175  sqlitegraph pattern-match --edge-type DEPENDS_ON --start-label "Function" --end-label "Module"
176  sqlitegraph pattern-match-fast --edge-type CALLS --direction outgoing
177  sqlitegraph hnsw-create --dimension 768 --m 16 --ef-construction 200 --distance-metric cosine
178  sqlitegraph migrate --dry-run
179  sqlitegraph backward-slice --target 456
180  sqlitegraph forward-slice --source 123
181  sqlitegraph collapse-scc
182  sqlitegraph min-cut --source 1 --sink 10
183  sqlitegraph min-vertex-cut --source 1 --sink 10
184"#
185    }
186}