sqlite_graphrag/commands/
init.rs1use 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#[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 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
34 pub db: Option<String>,
35 #[arg(long, value_enum)]
38 pub model: Option<EmbeddingModelChoice>,
39 #[arg(long)]
42 pub force: bool,
43 #[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 schema_version: u32,
57 model: String,
58 dim: usize,
59 namespace: String,
61 status: String,
62 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 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 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 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 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 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}