Skip to main content

sqlite_graphrag/commands/
init.rs

1//! Handler for the `init` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::output;
5use crate::paths::AppPaths;
6use crate::pragmas::{apply_init_pragmas, ensure_wal_mode};
7use crate::storage::connection::open_rw;
8use serde::Serialize;
9
10/// Embedding model choices exposed through `--model`.
11///
12/// Legacy flag kept for CLI compatibility only: since v1.0.76 the build is
13/// LLM-only and no local model is downloaded. The value is accepted and
14/// ignored; `schema_meta.model` records the CLI version (G46).
15#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
16pub enum EmbeddingModelChoice {
17    #[value(name = "multilingual-e5-small")]
18    MultilingualE5Small,
19}
20
21#[derive(clap::Args)]
22#[command(after_long_help = "EXAMPLES:\n  \
23    # Initialize a new database in the current directory\n  \
24    sqlite-graphrag init\n\n  \
25    # Initialize with a specific namespace\n  \
26    sqlite-graphrag init --namespace my-project\n\n  \
27    # Initialize at a custom database path\n  \
28    sqlite-graphrag init --db /path/to/graphrag.sqlite")]
29pub struct InitArgs {
30    /// Path to graphrag.sqlite. Defaults to `./graphrag.sqlite` in the current directory.
31    /// Resolution precedence (highest to lowest): `--db` flag > `SQLITE_GRAPHRAG_DB_PATH` env >
32    /// `SQLITE_GRAPHRAG_HOME` env (used as base directory) > cwd.
33    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
34    pub db: Option<String>,
35    /// Legacy embedding model identifier (accepted and ignored since the
36    /// v1.0.76 LLM-only build; kept for CLI compatibility). Safe to omit.
37    #[arg(long, value_enum)]
38    pub model: Option<EmbeddingModelChoice>,
39    /// Force re-initialization, overwriting any existing schema metadata.
40    /// Use only when the schema is corrupted; loses configuration but preserves data.
41    #[arg(long)]
42    pub force: bool,
43    /// Initial namespace to resolve. Aligned with bilingual docs that mention `init --namespace`.
44    /// When provided, overrides `SQLITE_GRAPHRAG_NAMESPACE`; otherwise resolves via env or fallback `global`.
45    #[arg(long)]
46    pub namespace: Option<String>,
47    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
48    pub json: bool,
49}
50
51#[derive(Serialize)]
52struct InitResponse {
53    db_path: String,
54    /// Latest applied migration number from `refinery_schema_history`.
55    /// Emitted as a JSON number for cross-command consistency with `health` and `stats` (since v1.0.35).
56    schema_version: u32,
57    model: String,
58    dim: usize,
59    /// Active namespace resolved during initialisation, aligned with the bilingual docs.
60    namespace: String,
61    status: String,
62    /// Total execution time in milliseconds from handler start to serialisation.
63    elapsed_ms: u64,
64}
65
66pub fn run(args: InitArgs) -> Result<(), AppError> {
67    let start = std::time::Instant::now();
68    let paths = AppPaths::resolve(args.db.as_deref())?;
69    paths.ensure_dirs()?;
70
71    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
72
73    let mut conn = open_rw(&paths.db)?;
74
75    apply_init_pragmas(&conn)?;
76
77    crate::migrations::runner()
78        .run(&mut conn)
79        .map_err(|e| AppError::Internal(anyhow::anyhow!("migration failed: {e}")))?;
80
81    conn.execute_batch(&format!(
82        "PRAGMA user_version = {};",
83        crate::constants::SCHEMA_USER_VERSION
84    ))?;
85
86    // Defensive re-assertion: refinery may revert journal_mode during migrations.
87    ensure_wal_mode(&conn)?;
88
89    let schema_version = latest_schema_version(&conn)?;
90
91    conn.execute(
92        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('schema_version', ?1)",
93        rusqlite::params![schema_version],
94    )?;
95    conn.execute(
96        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('model', ?1)",
97        rusqlite::params![crate::constants::SQLITE_GRAPHRAG_VERSION],
98    )?;
99    // G43: pre-v1.0.79 this hardcoded '384', stamping NEW databases with a
100    // dimensionality that contradicts the active default (64 since G42/S1).
101    // INSERT OR IGNORE preserves the recorded dim on re-init of an existing
102    // database; the active dim (env > database > default) fills new ones.
103    conn.execute(
104        "INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('dim', ?1)",
105        rusqlite::params![crate::constants::embedding_dim().to_string()],
106    )?;
107    conn.execute(
108        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('created_at', CAST(unixepoch() AS TEXT))",
109        [],
110    )?;
111    conn.execute(
112        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('sqlite-graphrag_version', ?1)",
113        rusqlite::params![crate::constants::SQLITE_GRAPHRAG_VERSION],
114    )?;
115    // Persist the resolved namespace so downstream tools can inspect it without re-resolving.
116    conn.execute(
117        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('namespace_initial', ?1)",
118        rusqlite::params![namespace],
119    )?;
120
121    output::emit_progress_i18n(
122        "Validating embedding backend...",
123        "Validando backend de embedding...",
124    );
125
126    // GAP-INIT-EMBEDDING-001 FIX (v1.0.89): init must succeed without LLM.
127    // Schema, tables and FTS5 are created above; the smoke test only validates
128    // that the embedding subprocess is reachable. When it is not (OAuth expired,
129    // CLI missing), init still succeeds with dim from the database or default.
130    // ADR-0011: Validation errors (OAuth-only enforcement) are FATAL — propagate.
131    // v1.0.89 (GAP-EMBED-PROPAGATION): honour --llm-backend via embed_passage_with_choice.
132    let (dim, status) = match crate::embedder::embed_passage_with_choice(
133        &paths.models,
134        "smoke test",
135        None,
136    ) {
137        Ok((v, _backend)) => (v.len(), "ok"),
138        Err(crate::errors::AppError::Validation(msg)) => {
139            return Err(crate::errors::AppError::Validation(msg))
140        }
141        Err(e) => {
142            tracing::warn!(target: "init", error = %e, "embedding smoke test failed; init continues without LLM validation");
143            (crate::constants::embedding_dim(), "ok_no_embedding")
144        }
145    };
146
147    output::emit_json(&InitResponse {
148        db_path: paths.db.display().to_string(),
149        schema_version,
150        model: crate::constants::SQLITE_GRAPHRAG_VERSION.to_string(),
151        dim,
152        namespace,
153        status: status.to_string(),
154        elapsed_ms: start.elapsed().as_millis() as u64,
155    })?;
156
157    Ok(())
158}
159
160fn latest_schema_version(conn: &rusqlite::Connection) -> Result<u32, AppError> {
161    match conn.query_row(
162        "SELECT version FROM refinery_schema_history ORDER BY version DESC LIMIT 1",
163        [],
164        |row| row.get::<_, i64>(0),
165    ) {
166        Ok(version) => Ok(version.max(0) as u32),
167        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(0),
168        Err(err) => Err(AppError::Database(err)),
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn init_response_serializes_all_fields() {
178        let resp = InitResponse {
179            db_path: "/tmp/test.sqlite".to_string(),
180            schema_version: 6,
181            model: crate::constants::SQLITE_GRAPHRAG_VERSION.to_string(),
182            dim: 384,
183            namespace: "global".to_string(),
184            status: "ok".to_string(),
185            elapsed_ms: 100,
186        };
187        let json = serde_json::to_value(&resp).expect("serialization failed");
188        assert_eq!(json["db_path"], "/tmp/test.sqlite");
189        assert_eq!(json["schema_version"], 6);
190        assert_eq!(json["model"], crate::constants::SQLITE_GRAPHRAG_VERSION);
191        assert_eq!(json["dim"], 384usize);
192        assert_eq!(json["namespace"], "global");
193        assert_eq!(json["status"], "ok");
194        assert!(json["elapsed_ms"].is_number());
195    }
196
197    #[test]
198    fn latest_schema_version_returns_zero_for_empty_db() {
199        let conn = rusqlite::Connection::open_in_memory().expect("failed to open in-memory db");
200        conn.execute_batch("CREATE TABLE refinery_schema_history (version INTEGER NOT NULL);")
201            .expect("failed to create table");
202
203        let version = latest_schema_version(&conn).expect("latest_schema_version failed");
204        assert_eq!(version, 0u32, "empty db must return schema_version 0");
205    }
206
207    #[test]
208    fn latest_schema_version_returns_max_version() {
209        let conn = rusqlite::Connection::open_in_memory().expect("failed to open in-memory db");
210        conn.execute_batch(
211            "CREATE TABLE refinery_schema_history (version INTEGER NOT NULL);
212             INSERT INTO refinery_schema_history VALUES (1);
213             INSERT INTO refinery_schema_history VALUES (3);
214             INSERT INTO refinery_schema_history VALUES (2);",
215        )
216        .expect("failed to populate table");
217
218        let version = latest_schema_version(&conn).expect("latest_schema_version failed");
219        assert_eq!(version, 3u32, "must return the highest version present");
220    }
221
222    #[test]
223    fn init_default_dim_is_64() {
224        // G42/S1 (v1.0.79): the default dimensionality dropped from 384
225        // to 64 (MRL, arXiv 2205.13147). The active dim may differ when
226        // an env override or an existing database sets it.
227        assert_eq!(
228            crate::constants::DEFAULT_EMBEDDING_DIM,
229            64,
230            "default dim must be 64 in the LLM-only build"
231        );
232    }
233
234    #[test]
235    fn init_response_namespace_aligned_with_schema() {
236        // Verify namespace field survives round-trip serialization with correct value.
237        let resp = InitResponse {
238            db_path: "/tmp/x.sqlite".to_string(),
239            schema_version: 6,
240            model: crate::constants::SQLITE_GRAPHRAG_VERSION.to_string(),
241            dim: 384,
242            namespace: "my-project".to_string(),
243            status: "ok".to_string(),
244            elapsed_ms: 0,
245        };
246        let json = serde_json::to_value(&resp).expect("serialization failed");
247        assert_eq!(json["namespace"], "my-project");
248    }
249}