nexql-tools 0.2.3

MCP tool registry, JSON schemas, executors
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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 NexQL-OSS Team

//! Tool descriptors for the active MCP surface (Phase 2–4).

use serde_json::{Value, json};

use crate::registry::{ToolName, ToolProfile};

#[derive(Debug, Clone)]
pub struct ToolSpec {
    pub name: ToolName,
    pub description: &'static str,
    pub input_schema: Value,
}

/// Tools filtered by the requested `ToolProfile`.
pub fn tools_for_profile(profile: ToolProfile) -> Vec<ToolSpec> {
    let names = ToolName::for_profile(profile);
    active_tools()
        .into_iter()
        .filter(|spec| names.contains(&spec.name))
        .collect()
}

/// Generate a formatted Mermaid ERD snippet for an object's column & key structure.
pub fn generate_mermaid_erd_for_object(obj: &serde_json::Map<String, Value>) -> Option<String> {
    let ref_name = obj.get("ref").and_then(|v| v.as_str()).unwrap_or("table");
    let safe_table_name = ref_name.replace(['.', '-'], "_");
    let mut diagram = String::from("erDiagram\n");
    diagram.push_str(&format!("    {safe_table_name} {{\n"));
    if let Some(columns) = obj.get("columns").and_then(|v| v.as_array()) {
        for col in columns {
            let name = col.get("name").and_then(|v| v.as_str()).unwrap_or("col");
            let data_type = col.get("type").and_then(|v| v.as_str()).unwrap_or("string");
            let pk = col.get("is_pk").and_then(|v| v.as_bool()).unwrap_or(false);
            let fk = col.get("is_fk").and_then(|v| v.as_bool()).unwrap_or(false);
            let key_str = match (pk, fk) {
                (true, true) => " PK,FK",
                (true, false) => " PK",
                (false, true) => " FK",
                _ => "",
            };
            diagram.push_str(&format!(
                "        {} {}{}\n",
                data_type.replace(' ', "_"),
                name,
                key_str
            ));
        }
    }
    diagram.push_str("    }\n");
    Some(diagram)
}

/// Generate a formatted Mermaid ERD diagram snippet for a FK join path.
pub fn generate_mermaid_diagram_for_path(path_val: &Value) -> Option<String> {
    let edges = path_val
        .as_array()
        .or_else(|| path_val.get("path").and_then(|v| v.as_array()))?;
    if edges.is_empty() {
        return None;
    }
    let mut diagram = String::from("erDiagram\n");
    for edge in edges {
        let from = edge
            .get("from")
            .and_then(|v| v.as_str())
            .unwrap_or("A")
            .replace(['.', '-'], "_");
        let to = edge
            .get("to")
            .and_then(|v| v.as_str())
            .unwrap_or("B")
            .replace(['.', '-'], "_");
        let from_col = edge.get("from_col").and_then(|v| v.as_str()).unwrap_or("");
        let to_col = edge.get("to_col").and_then(|v| v.as_str()).unwrap_or("");
        diagram.push_str(&format!(
            "    {from} }}|--|| {to} : \"{from_col} -> {to_col}\"\n"
        ));
    }
    Some(diagram)
}

/// Phase 2 catalog tools (live Postgres; no index required).
pub fn phase2_catalog_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ListConnections,
            description: "List configured connection profiles (never includes passwords).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListDatabases,
            description: "List databases available for a connection profile.",
            input_schema: object_schema(&[("connectionId", "string", true)]),
        },
        ToolSpec {
            name: ToolName::ListSchemas,
            description: "List non-system schemas in the currently selected database.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListObjects,
            description: "List objects (tables, views, …) in a schema.",
            input_schema: object_schema(&[("schema", "string", false), ("kind", "string", false)]),
        },
        ToolSpec {
            name: ToolName::GetCurrentContext,
            description: "Return the active profile, database, and access mode.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SwitchConnection,
            description: "Switch the session to another connection profile / database.",
            input_schema: object_schema(&[
                ("connectionId", "string", true),
                ("database", "string", false),
            ]),
        },
        ToolSpec {
            name: ToolName::RunSelect,
            description: "Run a read-only SELECT or WITH query. DML/DDL are rejected. Only reference tables/columns confirmed via list_schemas / list_objects.",
            input_schema: object_schema(&[("sql", "string", true)]),
        },
        ToolSpec {
            name: ToolName::ExplainQuery,
            description: "Run EXPLAIN (no ANALYZE execute) for a SELECT/WITH query.",
            input_schema: object_schema(&[("sql", "string", true)]),
        },
        ToolSpec {
            name: ToolName::DiscoverTools,
            description: "Dynamically discover and inspect specialized MCP database tools by keyword query (e.g., 'locks', 'bloat', 'index') or category ('query', 'dba', 'write'). Use this when you need specialized tools beyond the core surface.",
            input_schema: object_schema(&[
                ("query", "string", false),
                ("category", "string", false),
            ]),
        },
        ToolSpec {
            name: ToolName::RunDoctor,
            description: "Run diagnostic health checks on active database connection, permissions, session guards, and index status.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SetupConnection,
            description: "Automatically detect or configure a database connection. Scans environment variables, workspace files, and local settings, eliciting missing credentials when supported.",
            input_schema: object_schema(&[
                ("name", "string", false),
                ("url", "string", false),
                ("host", "string", false),
                ("port", "number", false),
                ("dbname", "string", false),
                ("user", "string", false),
                ("password", "string", false),
                ("sslmode", "string", false),
                ("interactive", "boolean", false),
            ]),
        },
        ToolSpec {
            name: ToolName::SaveProfile,
            description: "Save or update a database connection profile in user configuration with atomic backup and dynamic session reload.",
            input_schema: object_schema(&[
                ("name", "string", true),
                ("url", "string", false),
                ("host", "string", false),
                ("port", "number", false),
                ("dbname", "string", false),
                ("user", "string", false),
                ("password", "string", false),
                ("sslmode", "string", false),
                ("access_mode", "string", false),
                ("max_rows", "number", false),
            ]),
        },
        ToolSpec {
            name: ToolName::TestProfile,
            description: "Test a database connection profile or inline parameters and return server version, superuser status, and round-trip latency.",
            input_schema: object_schema(&[
                ("name", "string", false),
                ("url", "string", false),
                ("host", "string", false),
                ("port", "number", false),
                ("dbname", "string", false),
                ("user", "string", false),
                ("password", "string", false),
                ("sslmode", "string", false),
            ]),
        },
        ToolSpec {
            name: ToolName::ExportProfile,
            description: "Export a secret-sanitized TOML configuration for team sharing (.nexql/config.toml) with all passwords and credentials stripped.",
            input_schema: object_schema(&[("format", "string", false)]),
        },
        ToolSpec {
            name: ToolName::ImportProfile,
            description: "Import a team configuration file (.nexql/config.toml) or TOML content into local user configuration.",
            input_schema: object_schema(&[("content", "string", false), ("path", "string", false)]),
        },
    ]
}

/// Phase 3 index tools (require `nexql-mcp index build`).
pub fn phase3_index_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ResolveTarget,
            description: "Autonomously find which connection/database matches a user's hint (a database name, environment, host fragment) and/or an object hint (a table/view name), searching across ALL configured connections and their indexed schemas. Call this FIRST whenever the request references a database, environment, or object that is not the current session context — before search_schema, before list_connections. When the match is unambiguous it switches the session context automatically and returns the resolved connection/database; only returns `ambiguous: true` with a candidate list when multiple equally-plausible matches exist, in which case surface those candidates to the user rather than guessing.",
            input_schema: object_schema(&[
                ("hint", "string", false),
                ("objectHint", "string", false),
            ]),
        },
        ToolSpec {
            name: ToolName::SearchSchema,
            description: "Search the live, auto-indexed database schema using natural language or keywords to find tables, views, materialized views, and functions matching the query. Call this FIRST before writing any SQL — do not assume a table exists without finding it here.",
            input_schema: object_schema(&[("query", "string", true)]),
        },
        ToolSpec {
            name: ToolName::DescribeObject,
            description: "Get structural details of a specific database object (table, view, or materialized view) including columns, data types, constraints, and indexes.",
            input_schema: object_schema(&[("ref", "string", true)]),
        },
        ToolSpec {
            name: ToolName::GetJoinPath,
            description: "Find the shortest path of join relationships and foreign keys between two database tables.",
            input_schema: object_schema(&[("a", "string", true), ("b", "string", true)]),
        },
        ToolSpec {
            name: ToolName::SampleValues,
            description: "Retrieve a list of sample values from a specific table column to inspect its contents. Only works on read-only SELECT queries.",
            input_schema: object_schema(&[("ref", "string", true), ("col", "string", true)]),
        },
        ToolSpec {
            name: ToolName::RebuildIndex,
            description: "Rebuild the schema index for the active database connection.",
            input_schema: object_schema(&[("depth", "string", false)]),
        },
        ToolSpec {
            name: ToolName::RefreshIndex,
            description: "Refresh the schema index for the active database connection using previous build scope.",
            input_schema: object_schema(&[]),
        },
    ]
}

/// Phase 4 monitoring / DDL tools (descriptions from ToolSpec.ts where available).
pub fn phase4_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::GetDdl,
            description: "Get the DDL / definition of a database object. Views, materialized views, functions, and indexes return their CREATE statement; tables return structured DDL (columns, constraints, indexes).",
            input_schema: object_schema(&[("ref", "string", true), ("kind", "string", false)]),
        },
        ToolSpec {
            name: ToolName::TableStats,
            description: "Get size, row-count, activity (scans, inserts/updates/deletes, dead tuples, vacuum/analyze times) and per-column statistics for a specific table.",
            input_schema: object_schema(&[("ref", "string", true)]),
        },
        ToolSpec {
            name: ToolName::IndexUsage,
            description: "Get index usage statistics (scan counts, size, definition, type) for a specific table's indexes. Useful for finding unused or missing indexes.",
            input_schema: object_schema(&[("ref", "string", true)]),
        },
        ToolSpec {
            name: ToolName::ListRunningQueries,
            description: "List currently executing (non-idle) queries in the connected database with pid, user, state, wait events, and duration.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::FindBlockingLocks,
            description: "Find lock contention: which queries are blocked waiting on locks and which pids/queries are blocking them.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SlowQueries,
            description: "List the slowest statements by mean execution time from pg_stat_statements (requires the extension; returns a hint if not installed).",
            input_schema: object_schema(&[("limit", "number", false)]),
        },
        ToolSpec {
            name: ToolName::DbHealthCheck,
            description: "Run a database health overview: size/connection stats, cache hit ratio, tables with dead tuples needing vacuum, active connections, and blocking-lock count. Sections that fail are reported individually; partial results are still returned.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ExplainAnalyze,
            description: "Run EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on a SELECT/WITH query inside a read-only transaction that is always rolled back. WARNING: the query actually executes (volatile functions run), so expect real query runtime.",
            input_schema: object_schema(&[("sql", "string", true)]),
        },
        ToolSpec {
            name: ToolName::AnalyzeQueryPlan,
            description: "Run EXPLAIN (FORMAT JSON) on a SELECT/WITH query and return parsed plan metrics (scan counts, bottlenecks, buffer stats) plus performance recommendations. Set analyze=true to also execute the query for actual timings.",
            input_schema: object_schema(&[("sql", "string", true), ("analyze", "boolean", false)]),
        },
        ToolSpec {
            name: ToolName::GetIndexStatus,
            description: "Return schema-index status for the active connection/database: indexed_at, fingerprint, object counts, and optional live fingerprint drift.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListExtensions,
            description: "List installed PostgreSQL extensions (name, version, schema).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ServerSettings,
            description: "Return key PostgreSQL server settings from pg_settings (memory, connections, timeouts, autovacuum, version).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SuggestIndexes,
            description: "Suggest indexes from high sequential-scan tables, unindexed FK columns, and optional pg_stat_statements / EXPLAIN plan heuristics. Pass sql to analyze a specific query plan.",
            input_schema: object_schema(&[("limit", "number", false), ("sql", "string", false)]),
        },
        ToolSpec {
            name: ToolName::FindUnusedIndexes,
            description: "List indexes with idx_scan = 0 (never used since stats reset), excluding primary keys, unique indexes, and constraint-backed indexes.",
            input_schema: object_schema(&[("limit", "number", false)]),
        },
        ToolSpec {
            name: ToolName::BloatReport,
            description: "Approximate table bloat via dead-tuple ratio from pg_stat_user_tables (simplified estimate — not physical page bloat). Tables with >1000 dead tuples, ordered by bloat %.",
            input_schema: object_schema(&[("limit", "number", false)]),
        },
        ToolSpec {
            name: ToolName::FindMissingFks,
            description: "Find likely missing foreign keys: prefers schema-index join-graph inferred edges; falls back to catalog naming (*_id columns without an FK matching a PK).",
            input_schema: object_schema(&[("limit", "number", false)]),
        },
    ]
}

/// Phase 4b read-only breadth (export / role introspection).
pub fn phase4b_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ExportQuery,
            description: "Run a read-only SELECT/WITH and format results as CSV, JSON, or SQL INSERT statements. Honors max-row / max-char caps. For sqlinsert, pass table as schema.name.",
            input_schema: object_schema(&[
                ("sql", "string", true),
                ("format", "string", false),
                ("table", "string", false),
            ]),
        },
        ToolSpec {
            name: ToolName::ListRoles,
            description: "List PostgreSQL roles (attributes). Pass role to get memberships and table privileges for one role.",
            input_schema: object_schema(&[("role", "string", false)]),
        },
        ToolSpec {
            name: ToolName::DbDashboard,
            description: "One-shot live metrics bundle: DB size/owner, connection-state breakdown, top tables by size, object counts, active queries, and blocking locks. Soft-fails per section.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::DeepPlanAnalysis,
            description: "Run EXPLAIN (ANALYZE by default) and return severity-graded findings: estimate skew, expensive function/CTE/subquery nodes, and recommendations. Set analyze=false for plan-only (no execution).",
            input_schema: object_schema(&[("sql", "string", true), ("analyze", "boolean", false)]),
        },
        ToolSpec {
            name: ToolName::SchemaDiff,
            description: "Compare two schemas in the current database (or sourceSchema vs targetSchema). Returns structured table/column/constraint/index diffs. Read-only — does not apply changes.",
            input_schema: object_schema(&[
                ("sourceSchema", "string", true),
                ("targetSchema", "string", true),
            ]),
        },
        ToolSpec {
            name: ToolName::GenerateMigration,
            description: "Emit migration SQL to evolve sourceSchema toward targetSchema (from a live schema_diff). Read-only — returns SQL text, never executes it. Destructive drops are commented out.",
            input_schema: object_schema(&[
                ("sourceSchema", "string", true),
                ("targetSchema", "string", true),
            ]),
        },
        ToolSpec {
            name: ToolName::AutoTuneQuery,
            description: "Autonomous query tuner: executes EXPLAIN ANALYZE, checks table statistics, evaluates missing indexes, and outputs step-by-step performance tuning recommendations.",
            input_schema: object_schema(&[("sql", "string", true)]),
        },
        ToolSpec {
            name: ToolName::CheckDdlSafety,
            description: "Safety guard for migration DDL: inspects SQL for dangerous exclusive locks (e.g. non-concurrent index builds, column drops, table rewrites) and outputs risk scores and safe zero-downtime alternatives.",
            input_schema: object_schema(&[("ddl", "string", true)]),
        },
    ]
}

/// Phase 9 write/admin tools (always listed; access-gated at dispatch).
pub fn phase9_write_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ExecuteSql,
            description: "Execute DML (and DDL in admin mode) inside an explicit transaction. Set dry_run=true to roll back after execution. Errors always roll back.",
            input_schema: object_schema(&[("sql", "string", true), ("dry_run", "boolean", false)]),
        },
        ToolSpec {
            name: ToolName::EditRow,
            description: "Structured insert, update, or delete by primary key. The server builds parameterized SQL — pass table (schema.name), action, values, and pk for update/delete.",
            input_schema: object_schema(&[
                ("table", "string", true),
                ("action", "string", true),
                ("values", "object", false),
                ("pk", "object", false),
            ]),
        },
        ToolSpec {
            name: ToolName::ImportData,
            description: "Batch INSERT rows from a JSON array of objects into a table. Optional columns array fixes column order; otherwise keys from the first row are used.",
            input_schema: object_schema(&[
                ("table", "string", true),
                ("rows", "array", true),
                ("columns", "array", false),
            ]),
        },
        ToolSpec {
            name: ToolName::ApplyDdl,
            description: "Apply a DDL statement (CREATE, ALTER, DROP, TRUNCATE, …) in admin mode inside a transaction. Set dry_run=true to roll back.",
            input_schema: object_schema(&[("sql", "string", true), ("dry_run", "boolean", false)]),
        },
        ToolSpec {
            name: ToolName::CreateIndexConcurrently,
            description: "Run CREATE INDEX CONCURRENTLY outside a transaction (non-blocking index build). Admin mode only.",
            input_schema: object_schema(&[("sql", "string", true)]),
        },
        ToolSpec {
            name: ToolName::RunMaintenance,
            description: "Run VACUUM, ANALYZE, or REINDEX outside a transaction. Admin mode only. Optional table (schema.name); vacuum supports full=true.",
            input_schema: object_schema(&[
                ("action", "string", true),
                ("table", "string", false),
                ("full", "boolean", false),
            ]),
        },
        ToolSpec {
            name: ToolName::TerminateQuery,
            description: "Cancel (pg_cancel_backend) or force-terminate (pg_terminate_backend) a backend by pid. Admin mode only. Refuses superuser targets and the current session.",
            input_schema: object_schema(&[("pid", "number", true), ("force", "boolean", false)]),
        },
    ]
}

/// Full tools/list surface for the current phase (catalog + index + Phase 4 + 4b + 9).
pub fn active_tools() -> Vec<ToolSpec> {
    let mut specs = phase2_catalog_tools();
    specs.extend(phase3_index_tools());
    specs.extend(phase4_tools());
    specs.extend(phase4b_tools());
    specs.extend(phase9_write_tools());
    specs
}

fn object_schema(props: &[(&str, &str, bool)]) -> Value {
    let mut properties = serde_json::Map::new();
    let mut required = Vec::new();
    for (name, ty, req) in props {
        let prop_val = match *ty {
            "array" => match *name {
                "columns" => json!({ "type": "array", "items": { "type": "string" } }),
                "rows" => json!({ "type": "array", "items": { "type": "object" } }),
                _ => json!({ "type": "array", "items": {} }),
            },
            _ => json!({ "type": *ty }),
        };
        properties.insert((*name).into(), prop_val);
        if *req {
            required.push(json!(*name));
        }
    }
    json!({
        "type": "object",
        "properties": properties,
        "required": required
    })
}

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

    #[test]
    fn active_tools_lists_fifty_three() {
        let specs = active_tools();
        assert_eq!(specs.len(), 53);
        assert_eq!(specs.len(), ToolName::ACTIVE.len());
        for (spec, name) in specs.iter().zip(ToolName::ACTIVE.iter()) {
            assert_eq!(spec.name, *name);
        }
    }

    #[test]
    fn phase9_write_tools_count() {
        assert_eq!(phase9_write_tools().len(), ToolName::PHASE9.len());
    }

    #[test]
    fn array_properties_have_items() {
        for tool in active_tools() {
            if let Some(props) = tool
                .input_schema
                .get("properties")
                .and_then(|p| p.as_object())
            {
                for (prop_name, prop_val) in props {
                    if prop_val.get("type").and_then(|t| t.as_str()) == Some("array") {
                        assert!(
                            prop_val.get("items").is_some(),
                            "Tool '{}' parameter '{}' is array type but missing 'items'",
                            tool.name.as_str(),
                            prop_name
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn profile_tools_filtering() {
        let query_specs = tools_for_profile(ToolProfile::Query);
        assert_eq!(query_specs.len(), 18);

        let dba_specs = tools_for_profile(ToolProfile::Dba);
        assert_eq!(dba_specs.len(), 28);

        let meta_specs = tools_for_profile(ToolProfile::Meta);
        assert_eq!(meta_specs.len(), 10);

        let full_specs = tools_for_profile(ToolProfile::Full);
        assert_eq!(full_specs.len(), 53);
    }

    #[test]
    fn generate_mermaid_erd_test() {
        let obj = json!({
            "ref": "public.users",
            "columns": [
                { "name": "id", "type": "uuid", "is_pk": true, "is_fk": false },
                { "name": "email", "type": "varchar", "is_pk": false, "is_fk": false },
                { "name": "org_id", "type": "uuid", "is_pk": false, "is_fk": true }
            ]
        });
        let diagram = generate_mermaid_erd_for_object(obj.as_object().unwrap()).unwrap();
        assert!(diagram.contains("erDiagram"));
        assert!(diagram.contains("public_users"));
        assert!(diagram.contains("uuid id PK"));
        assert!(diagram.contains("uuid org_id FK"));
    }

    #[test]
    fn generate_mermaid_diagram_for_path_test() {
        let path = json!([
            { "from": "public.orders", "to": "public.users", "from_col": "user_id", "to_col": "id" }
        ]);
        let diagram = generate_mermaid_diagram_for_path(&path).unwrap();
        assert!(diagram.contains("erDiagram"));
        assert!(diagram.contains("public_orders }|--|| public_users : \"user_id -> id\""));
    }
}