Skip to content

Commit c10242e

Browse files
committed
code fmt and schema discovery doc
1 parent 8ce1d4d commit c10242e

10 files changed

Lines changed: 175 additions & 63 deletions

File tree

clickgraph-embedded/src/database.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,20 @@ impl Database {
163163
let view_count = clickgraph::executor::data_loader::load_schema_sources(&executor, &schema)
164164
.map_err(|e| EmbeddedError::Executor(e.to_string()))?;
165165
if view_count > 0 {
166-
log::info!("Created {} chdb VIEW(s) from schema source: entries", view_count);
166+
log::info!(
167+
"Created {} chdb VIEW(s) from schema source: entries",
168+
view_count
169+
);
167170
}
168171

169172
let table_count =
170173
clickgraph::executor::data_loader::create_writable_tables(&executor, &schema)
171174
.map_err(|e| EmbeddedError::Executor(e.to_string()))?;
172175
if table_count > 0 {
173-
log::info!("Created {} writable ReplacingMergeTree table(s)", table_count);
176+
log::info!(
177+
"Created {} writable ReplacingMergeTree table(s)",
178+
table_count
179+
);
174180
}
175181

176182
let remote_executor = Self::build_remote_executor(&runtime, config.remote.as_ref())?;
@@ -194,8 +200,9 @@ impl Database {
194200
let graph_schema = load_graph_schema(schema_path.as_ref())?;
195201
let runtime = build_runtime()?;
196202
let remote_executor =
197-
Self::build_remote_executor(&runtime, Some(&remote))?
198-
.ok_or_else(|| EmbeddedError::Executor("Failed to connect to remote ClickHouse".to_string()))?;
203+
Self::build_remote_executor(&runtime, Some(&remote))?.ok_or_else(|| {
204+
EmbeddedError::Executor("Failed to connect to remote ClickHouse".to_string())
205+
})?;
199206
Ok(Database {
200207
executor: Arc::new(NullExecutor),
201208
remote_executor: Some(remote_executor),
@@ -223,7 +230,9 @@ impl Database {
223230
))
224231
.map_err(EmbeddedError::Executor)?;
225232
log::info!("Remote ClickHouse executor initialized: {}", remote.url);
226-
Ok(Some(Arc::new(RemoteClickHouseExecutor::new(Arc::new(pool))) as Arc<dyn QueryExecutor>))
233+
Ok(Some(
234+
Arc::new(RemoteClickHouseExecutor::new(Arc::new(pool))) as Arc<dyn QueryExecutor>,
235+
))
227236
}
228237

229238
/// Return a reference to the graph schema.

clickgraph-embedded/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ pub(crate) mod write_helpers;
4848

4949
pub use connection::Connection;
5050
pub use cypher_loader::LoadStats;
51-
pub use database::{Database, RemoteConfig, SystemConfig};
5251
#[cfg(feature = "embedded")]
5352
pub use database::StorageCredentials;
53+
pub use database::{Database, RemoteConfig, SystemConfig};
5454
pub use error::EmbeddedError;
5555
pub use export::{ExportFormat, ExportOptions};
5656
pub use graph_result::{GraphEdge, GraphNode, GraphResult, GraphResultBuilder, StoreStats};

clickgraph-tool/src/commands/nl.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ pub async fn run_nl(description: &str, execute: bool, format: &str, cfg: &CgConf
3030
"No schema loaded. Generate a general Cypher query.".to_string()
3131
};
3232

33-
let user_prompt = format!("{}\n\nNatural language query: {}", schema_context, description);
33+
let user_prompt = format!(
34+
"{}\n\nNatural language query: {}",
35+
schema_context, description
36+
);
3437

3538
eprintln!("Calling {} ({})...", llm.model, provider_name(&llm));
3639
let response = llm.call(NL_SYSTEM_PROMPT, &user_prompt).await?;

clickgraph-tool/src/commands/query.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,17 +87,33 @@ fn print_table(cols: &[String], rows: &[Vec<Value>]) {
8787
}
8888
}
8989

90-
let sep: String = widths.iter().map(|w| "-".repeat(w + 2)).collect::<Vec<_>>().join("+");
90+
let sep: String = widths
91+
.iter()
92+
.map(|w| "-".repeat(w + 2))
93+
.collect::<Vec<_>>()
94+
.join("+");
9195
println!("+{}+", sep);
92-
let header: Vec<String> = cols.iter().zip(&widths).map(|(c, w)| format!(" {:w$} ", c, w = w)).collect();
96+
let header: Vec<String> = cols
97+
.iter()
98+
.zip(&widths)
99+
.map(|(c, w)| format!(" {:w$} ", c, w = w))
100+
.collect();
93101
println!("|{}|", header.join("|"));
94102
println!("+{}+", sep);
95103
for row in rows {
96-
let cells: Vec<String> = row.iter().zip(&widths).map(|(v, w)| format!(" {:w$} ", value_str(v), w = w)).collect();
104+
let cells: Vec<String> = row
105+
.iter()
106+
.zip(&widths)
107+
.map(|(v, w)| format!(" {:w$} ", value_str(v), w = w))
108+
.collect();
97109
println!("|{}|", cells.join("|"));
98110
}
99111
println!("+{}+", sep);
100-
println!("({} row{})", rows.len(), if rows.len() == 1 { "" } else { "s" });
112+
println!(
113+
"({} row{})",
114+
rows.len(),
115+
if rows.len() == 1 { "" } else { "s" }
116+
);
101117
}
102118

103119
fn print_json(cols: &[String], rows: &[Vec<Value>]) -> Result<()> {

clickgraph-tool/src/commands/schema.rs

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
use anyhow::{anyhow, Result};
2-
use clickgraph::{
3-
graph_catalog::{
4-
config::GraphSchemaConfig,
5-
llm_prompt,
6-
schema_discovery::SchemaDiscovery,
7-
},
2+
use clickgraph::graph_catalog::{
3+
config::GraphSchemaConfig, llm_prompt, schema_discovery::SchemaDiscovery,
84
};
95

106
use crate::{
@@ -133,10 +129,18 @@ pub fn run_diff(old_path: &str, new_path: &str) -> Result<()> {
133129
let new_cfg = GraphSchemaConfig::from_yaml_file(new_path)
134130
.map_err(|e| anyhow!("Failed to load '{}': {}", new_path, e))?;
135131

136-
let old_nodes: std::collections::BTreeSet<String> =
137-
old_cfg.graph_schema.nodes.iter().map(|n| n.label.clone()).collect();
138-
let new_nodes: std::collections::BTreeSet<String> =
139-
new_cfg.graph_schema.nodes.iter().map(|n| n.label.clone()).collect();
132+
let old_nodes: std::collections::BTreeSet<String> = old_cfg
133+
.graph_schema
134+
.nodes
135+
.iter()
136+
.map(|n| n.label.clone())
137+
.collect();
138+
let new_nodes: std::collections::BTreeSet<String> = new_cfg
139+
.graph_schema
140+
.nodes
141+
.iter()
142+
.map(|n| n.label.clone())
143+
.collect();
140144

141145
let old_rels: std::collections::BTreeSet<String> = old_cfg
142146
.graph_schema
@@ -174,8 +178,16 @@ pub fn run_diff(old_path: &str, new_path: &str) -> Result<()> {
174178

175179
// Property-level diff for nodes present in both
176180
for label in old_nodes.intersection(&new_nodes) {
177-
let old_node = old_cfg.graph_schema.nodes.iter().find(|n| &n.label == label);
178-
let new_node = new_cfg.graph_schema.nodes.iter().find(|n| &n.label == label);
181+
let old_node = old_cfg
182+
.graph_schema
183+
.nodes
184+
.iter()
185+
.find(|n| &n.label == label);
186+
let new_node = new_cfg
187+
.graph_schema
188+
.nodes
189+
.iter()
190+
.find(|n| &n.label == label);
179191
if let (Some(old), Some(new)) = (old_node, new_node) {
180192
let old_props: std::collections::BTreeSet<String> =
181193
old.properties.keys().cloned().collect();
@@ -208,7 +220,10 @@ fn merge_batch_yaml(base: &str, continuation: &str) -> String {
208220
let mut result = base.trim_end().to_string();
209221

210222
if !cont_nodes.is_empty() {
211-
if let Some(pos) = result.find("\n edges:").or_else(|| result.find("\nedges:")) {
223+
if let Some(pos) = result
224+
.find("\n edges:")
225+
.or_else(|| result.find("\nedges:"))
226+
{
212227
result.insert_str(pos, &format!("\n{}", cont_nodes));
213228
} else {
214229
result.push('\n');

clickgraph-tool/src/config.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,7 @@ impl CgConfig {
6868
let file_cfg = load_file_config();
6969

7070
// Schema path: CLI flag > env (already handled by clap) > config file
71-
let schema_path = schema
72-
.clone()
73-
.or_else(|| file_cfg.schema.path.clone());
71+
let schema_path = schema.clone().or_else(|| file_cfg.schema.path.clone());
7472

7573
// ClickHouse URL: CLI flag > env > config file
7674
let clickhouse_url = clickhouse
@@ -81,7 +79,11 @@ impl CgConfig {
8179
let ch_user = if ch_user != "default" {
8280
ch_user.to_string()
8381
} else {
84-
file_cfg.clickhouse.user.clone().unwrap_or_else(|| "default".to_string())
82+
file_cfg
83+
.clickhouse
84+
.user
85+
.clone()
86+
.unwrap_or_else(|| "default".to_string())
8587
};
8688

8789
let ch_password = if !ch_password.is_empty() {
@@ -129,9 +131,11 @@ impl CgConfig {
129131

130132
/// Resolve the schema path, returning an error if not set
131133
pub fn require_schema(&self) -> Result<&str> {
132-
self.schema_path
133-
.as_deref()
134-
.ok_or_else(|| anyhow::anyhow!("No schema file specified. Use --schema <file> or set CG_SCHEMA env var."))
134+
self.schema_path.as_deref().ok_or_else(|| {
135+
anyhow::anyhow!(
136+
"No schema file specified. Use --schema <file> or set CG_SCHEMA env var."
137+
)
138+
})
135139
}
136140
}
137141

clickgraph-tool/src/llm.rs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ impl LlmClient {
6464
.api_key
6565
.clone()
6666
.or_else(|| std::env::var("ANTHROPIC_API_KEY").ok())
67-
.ok_or_else(|| anyhow!("No API key found. Set CG_LLM_API_KEY or ANTHROPIC_API_KEY."))?;
67+
.ok_or_else(|| {
68+
anyhow!("No API key found. Set CG_LLM_API_KEY or ANTHROPIC_API_KEY.")
69+
})?;
6870
(
6971
LlmProvider::Anthropic,
7072
key,
@@ -78,11 +80,16 @@ impl LlmClient {
7880
let api_url = cfg.base_url.clone().unwrap_or(default_url);
7981
let max_tokens = cfg.max_tokens.unwrap_or(8192);
8082

81-
let client = Client::builder()
82-
.timeout(LLM_REQUEST_TIMEOUT)
83-
.build()?;
83+
let client = Client::builder().timeout(LLM_REQUEST_TIMEOUT).build()?;
8484

85-
Ok(LlmClient { api_key, model, api_url, max_tokens, provider, client })
85+
Ok(LlmClient {
86+
api_key,
87+
model,
88+
api_url,
89+
max_tokens,
90+
provider,
91+
client,
92+
})
8693
}
8794

8895
/// Call the LLM with a system prompt and user message, return the text response.
@@ -119,10 +126,14 @@ impl LlmClient {
119126
model: &self.model,
120127
max_tokens: self.max_tokens,
121128
system: system_prompt,
122-
messages: vec![Msg { role: "user", content: user_prompt }],
129+
messages: vec![Msg {
130+
role: "user",
131+
content: user_prompt,
132+
}],
123133
};
124134

125-
let resp = self.client
135+
let resp = self
136+
.client
126137
.post(&self.api_url)
127138
.header("x-api-key", &self.api_key)
128139
.header("anthropic-version", "2023-06-01")
@@ -172,12 +183,19 @@ impl LlmClient {
172183
model: &self.model,
173184
max_tokens: self.max_tokens,
174185
messages: vec![
175-
Msg { role: "system", content: system_prompt },
176-
Msg { role: "user", content: user_prompt },
186+
Msg {
187+
role: "system",
188+
content: system_prompt,
189+
},
190+
Msg {
191+
role: "user",
192+
content: user_prompt,
193+
},
177194
],
178195
};
179196

180-
let resp = self.client
197+
let resp = self
198+
.client
181199
.post(&self.api_url)
182200
.bearer_auth(&self.api_key)
183201
.json(&body)

clickgraph-tool/src/main.rs

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,21 @@ struct Cli {
2424
clickhouse: Option<String>,
2525

2626
/// ClickHouse user
27-
#[arg(long, env = "CG_CLICKHOUSE_USER", global = true, default_value = "default")]
27+
#[arg(
28+
long,
29+
env = "CG_CLICKHOUSE_USER",
30+
global = true,
31+
default_value = "default"
32+
)]
2833
ch_user: String,
2934

3035
/// ClickHouse password
31-
#[arg(long, env = "CG_CLICKHOUSE_PASSWORD", global = true, default_value = "")]
36+
#[arg(
37+
long,
38+
env = "CG_CLICKHOUSE_PASSWORD",
39+
global = true,
40+
default_value = ""
41+
)]
3242
ch_password: String,
3343

3444
/// ClickHouse database to query
@@ -139,7 +149,13 @@ enum SchemaCommands {
139149
#[tokio::main]
140150
async fn main() -> Result<()> {
141151
let cli = Cli::parse();
142-
let cfg = CgConfig::load(&cli.schema, &cli.clickhouse, &cli.ch_user, &cli.ch_password, &cli.ch_database)?;
152+
let cfg = CgConfig::load(
153+
&cli.schema,
154+
&cli.clickhouse,
155+
&cli.ch_user,
156+
&cli.ch_password,
157+
&cli.ch_database,
158+
)?;
143159

144160
match cli.command {
145161
Commands::Sql { query } => {
@@ -150,11 +166,19 @@ async fn main() -> Result<()> {
150166
commands::query::run_validate(&query, &cfg)?;
151167
}
152168

153-
Commands::Query { query, sql_only, format } => {
169+
Commands::Query {
170+
query,
171+
sql_only,
172+
format,
173+
} => {
154174
commands::query::run_query(&query, sql_only, &format, &cfg).await?;
155175
}
156176

157-
Commands::Nl { description, execute, format } => {
177+
Commands::Nl {
178+
description,
179+
execute,
180+
format,
181+
} => {
158182
commands::nl::run_nl(&description, execute, &format, &cfg).await?;
159183
}
160184

@@ -163,16 +187,34 @@ async fn main() -> Result<()> {
163187
commands::schema::run_show(&format, &cfg)?;
164188
}
165189
SchemaCommands::Validate { file } => {
166-
let path = file
167-
.or_else(|| cfg.schema_path.clone())
168-
.ok_or_else(|| anyhow::anyhow!("No schema file specified. Use --schema or provide a file argument."))?;
190+
let path = file.or_else(|| cfg.schema_path.clone()).ok_or_else(|| {
191+
anyhow::anyhow!(
192+
"No schema file specified. Use --schema or provide a file argument."
193+
)
194+
})?;
169195
commands::schema::run_validate_schema(&path)?;
170196
}
171-
SchemaCommands::Discover { database, clickhouse, user, password, out } => {
197+
SchemaCommands::Discover {
198+
database,
199+
clickhouse,
200+
user,
201+
password,
202+
out,
203+
} => {
172204
let ch_url = clickhouse
173205
.or_else(|| cfg.clickhouse_url.clone())
174-
.ok_or_else(|| anyhow::anyhow!("No ClickHouse URL. Use --clickhouse or CG_CLICKHOUSE_URL."))?;
175-
commands::schema::run_discover(&database, &ch_url, &user, &password, out.as_deref(), &cfg).await?;
206+
.ok_or_else(|| {
207+
anyhow::anyhow!("No ClickHouse URL. Use --clickhouse or CG_CLICKHOUSE_URL.")
208+
})?;
209+
commands::schema::run_discover(
210+
&database,
211+
&ch_url,
212+
&user,
213+
&password,
214+
out.as_deref(),
215+
&cfg,
216+
)
217+
.await?;
176218
}
177219
SchemaCommands::Diff { old, new } => {
178220
commands::schema::run_diff(&old, &new)?;

0 commit comments

Comments
 (0)