Skip to main content

sqlrite/ask/
mod.rs

1//! Engine-side glue for the [`sqlrite-ask`](https://crates.io/crates/sqlrite-ask)
2//! crate — natural-language → SQL.
3//!
4//! Compiled only when the `ask` feature is enabled (default-on for
5//! the CLI binary, off for the WASM SDK and any
6//! `default-features = false` library embedding).
7//!
8//! ## Why this lives in the engine, not in `sqlrite-ask`
9//!
10//! Earlier (v0.1.18) `sqlrite-ask` itself owned the `Connection`
11//! integration — it imported `sqlrite-engine` and exposed
12//! `ConnectionAskExt`. That worked for library callers, but when
13//! the engine's REPL binary tried to depend on `sqlrite-ask` to
14//! wire up the `.ask` meta-command we hit a hard cargo error:
15//!
16//! ```text
17//! cyclic package dependency: package `sqlrite-ask` depends on itself.
18//! Cycle: sqlrite-ask → sqlrite-engine → sqlrite-ask
19//! ```
20//!
21//! Optional / feature-gated deps don't escape this — cargo's static
22//! cycle detection counts every potential edge in the graph. The
23//! structural fix was to flip the dep direction: keep `sqlrite-ask`
24//! pure (operates on `&str` schemas), put the engine integration
25//! here. The dep flow is now one-way: `sqlrite-engine[ask]` →
26//! `sqlrite-ask`. No cycle.
27//!
28//! ## What's here
29//!
30//! - [`schema::dump_schema_for_database`] — walks `Database.tables`
31//!   alphabetically, emits `CREATE TABLE … (…);` text the LLM grounds
32//!   on. Determinism matters for prompt caching.
33//! - [`ConnectionAskExt`] — extension trait adding `Connection::ask`
34//!   that handles schema introspection + `sqlrite_ask::ask_with_schema`
35//!   in one call.
36//! - Free functions [`ask`] / [`ask_with_database`] /
37//!   [`ask_with_provider`] / [`ask_with_database_and_provider`] —
38//!   for callers who don't want to bring the trait into scope, or
39//!   who hold a `&Database` directly (the REPL binary does this).
40
41use sqlrite_ask::{ask_with_schema, ask_with_schema_and_provider};
42
43use crate::Connection;
44use crate::sql::db::database::Database;
45
46pub mod schema;
47
48// Re-export the public surface from sqlrite-ask. Lets callers reach
49// these without listing `sqlrite-ask` as a direct dep — convenient
50// for the Tauri desktop app, the SDK adapters, and any Rust embedder
51// who already pulls the engine in. They can keep saying
52// `use sqlrite::ask::AskConfig` instead of dragging the second crate
53// in just for one type.
54pub use sqlrite_ask::{
55    AnthropicProvider, AskConfig, AskError, AskResponse, CacheTtl, Provider, ProviderKind, Request,
56    Response, Usage,
57};
58
59/// Extension trait adding `Connection::ask` to
60/// [`crate::Connection`]. Bring it into scope with
61/// `use sqlrite::ConnectionAskExt;` (the engine re-exports it at
62/// the crate root).
63pub trait ConnectionAskExt {
64    /// Generate SQL from a natural-language question.
65    ///
66    /// Internally: dump the schema, build the cache-friendly prompt,
67    /// POST to the configured LLM provider, parse the JSON-shaped
68    /// reply.
69    ///
70    /// ```no_run
71    /// use sqlrite::{Connection, ConnectionAskExt};
72    /// use sqlrite_ask::AskConfig;
73    ///
74    /// let conn = Connection::open("foo.sqlrite")?;
75    /// let cfg  = AskConfig::from_env()?;          // SQLRITE_LLM_API_KEY etc.
76    /// let resp = conn.ask("how many users are over 30?", &cfg)?;
77    /// println!("{}", resp.sql);
78    /// # Ok::<(), Box<dyn std::error::Error>>(())
79    /// ```
80    fn ask(&self, question: &str, config: &AskConfig) -> Result<AskResponse, AskError>;
81}
82
83impl ConnectionAskExt for Connection {
84    fn ask(&self, question: &str, config: &AskConfig) -> Result<AskResponse, AskError> {
85        ask(self, question, config)
86    }
87}
88
89/// Free-function form of [`ConnectionAskExt::ask`]. Equivalent —
90/// pick whichever shape reads better at the call site.
91pub fn ask(conn: &Connection, question: &str, config: &AskConfig) -> Result<AskResponse, AskError> {
92    ask_with_database(conn.database(), question, config)
93}
94
95/// Same as [`ask`], but takes the engine's `&Database` directly.
96///
97/// Used by the REPL binary's `.ask` meta-command, which holds a
98/// `&mut Database` rather than a `&Connection`.
99pub fn ask_with_database(
100    db: &Database,
101    question: &str,
102    config: &AskConfig,
103) -> Result<AskResponse, AskError> {
104    let schema_dump = schema::dump_schema_for_database(db);
105    ask_with_schema(&schema_dump, question, config)
106}
107
108/// Lower-level entry — same flow as [`ask`] but you supply the
109/// provider. For test harnesses + advanced callers driving custom
110/// backends.
111pub fn ask_with_provider<P: Provider>(
112    conn: &Connection,
113    question: &str,
114    config: &AskConfig,
115    provider: &P,
116) -> Result<AskResponse, AskError> {
117    ask_with_database_and_provider(conn.database(), question, config, provider)
118}
119
120/// Lower-level entry taking `&Database` and a provider. Canonical
121/// inner function — the others reduce to this one.
122pub fn ask_with_database_and_provider<P: Provider>(
123    db: &Database,
124    question: &str,
125    config: &AskConfig,
126    provider: &P,
127) -> Result<AskResponse, AskError> {
128    let schema_dump = schema::dump_schema_for_database(db);
129    ask_with_schema_and_provider(&schema_dump, question, config, provider)
130}