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/// Currently only `multilingual-e5-small` is supported. Additional variants
13/// will be added here as new models are integrated; the `value_enum` derive
14/// ensures the CLI rejects unknown strings at parse time rather than at runtime.
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    /// Embedding model identifier. Currently only `multilingual-e5-small` is supported.
36    /// Reserved for future multi-model support; 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', 'multilingual-e5-small')",
97        [],
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        "Initializing embedding model (may download on first run)...",
123        crate::i18n::validation::runtime_pt::initializing_embedding_model(),
124    );
125
126    let test_emb = crate::embedder::embed_passage_local(&paths.models, "smoke test")?;
127
128    output::emit_json(&InitResponse {
129        db_path: paths.db.display().to_string(),
130        schema_version,
131        model: "multilingual-e5-small".to_string(),
132        dim: test_emb.len(),
133        namespace,
134        status: "ok".to_string(),
135        elapsed_ms: start.elapsed().as_millis() as u64,
136    })?;
137
138    Ok(())
139}
140
141fn latest_schema_version(conn: &rusqlite::Connection) -> Result<u32, AppError> {
142    match conn.query_row(
143        "SELECT version FROM refinery_schema_history ORDER BY version DESC LIMIT 1",
144        [],
145        |row| row.get::<_, i64>(0),
146    ) {
147        Ok(version) => Ok(version.max(0) as u32),
148        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(0),
149        Err(err) => Err(AppError::Database(err)),
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn init_response_serializes_all_fields() {
159        let resp = InitResponse {
160            db_path: "/tmp/test.sqlite".to_string(),
161            schema_version: 6,
162            model: "multilingual-e5-small".to_string(),
163            dim: 384,
164            namespace: "global".to_string(),
165            status: "ok".to_string(),
166            elapsed_ms: 100,
167        };
168        let json = serde_json::to_value(&resp).expect("serialization failed");
169        assert_eq!(json["db_path"], "/tmp/test.sqlite");
170        assert_eq!(json["schema_version"], 6);
171        assert_eq!(json["model"], "multilingual-e5-small");
172        assert_eq!(json["dim"], 384usize);
173        assert_eq!(json["namespace"], "global");
174        assert_eq!(json["status"], "ok");
175        assert!(json["elapsed_ms"].is_number());
176    }
177
178    #[test]
179    fn latest_schema_version_returns_zero_for_empty_db() {
180        let conn = rusqlite::Connection::open_in_memory().expect("failed to open in-memory db");
181        conn.execute_batch("CREATE TABLE refinery_schema_history (version INTEGER NOT NULL);")
182            .expect("failed to create table");
183
184        let version = latest_schema_version(&conn).expect("latest_schema_version failed");
185        assert_eq!(version, 0u32, "empty db must return schema_version 0");
186    }
187
188    #[test]
189    fn latest_schema_version_returns_max_version() {
190        let conn = rusqlite::Connection::open_in_memory().expect("failed to open in-memory db");
191        conn.execute_batch(
192            "CREATE TABLE refinery_schema_history (version INTEGER NOT NULL);
193             INSERT INTO refinery_schema_history VALUES (1);
194             INSERT INTO refinery_schema_history VALUES (3);
195             INSERT INTO refinery_schema_history VALUES (2);",
196        )
197        .expect("failed to populate table");
198
199        let version = latest_schema_version(&conn).expect("latest_schema_version failed");
200        assert_eq!(version, 3u32, "must return the highest version present");
201    }
202
203    #[test]
204    fn init_default_dim_is_64() {
205        // G42/S1 (v1.0.79): the default dimensionality dropped from 384
206        // to 64 (MRL, arXiv 2205.13147). The active dim may differ when
207        // an env override or an existing database sets it.
208        assert_eq!(
209            crate::constants::DEFAULT_EMBEDDING_DIM,
210            64,
211            "default dim must be 64 in the LLM-only build"
212        );
213    }
214
215    #[test]
216    fn init_response_namespace_aligned_with_schema() {
217        // Verify namespace field survives round-trip serialization with correct value.
218        let resp = InitResponse {
219            db_path: "/tmp/x.sqlite".to_string(),
220            schema_version: 6,
221            model: "multilingual-e5-small".to_string(),
222            dim: 384,
223            namespace: "my-project".to_string(),
224            status: "ok".to_string(),
225            elapsed_ms: 0,
226        };
227        let json = serde_json::to_value(&resp).expect("serialization failed");
228        assert_eq!(json["namespace"], "my-project");
229    }
230}