agent-source-repository 0.1.0

Agent Source Repository local context registry for coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::collections::BTreeMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::path::Path;
use std::ptr;
use std::slice;

use serde::{Deserialize, Serialize};

use crate::model::Chunk;

use super::{path_string, AsrError, AsrResult};

pub(crate) const INDEX_STATUS_READY: &str = "ready";
pub(crate) const INDEX_STATUS_FAILED: &str = "failed";

const SQLITE_OK: c_int = 0;
const SQLITE_ROW: c_int = 100;
const SQLITE_DONE: c_int = 101;

#[repr(C)]
struct sqlite3 {
    _private: [u8; 0],
}

#[repr(C)]
struct sqlite3_stmt {
    _private: [u8; 0],
}

#[link(name = "sqlite3")]
extern "C" {
    fn sqlite3_open(filename: *const c_char, pp_db: *mut *mut sqlite3) -> c_int;
    fn sqlite3_close(db: *mut sqlite3) -> c_int;
    // sqlite3_close_v2 finalizes all outstanding prepared statements before
    // closing, making it safe to call even when statements are still live.
    fn sqlite3_close_v2(db: *mut sqlite3) -> c_int;
    fn sqlite3_errmsg(db: *mut sqlite3) -> *const c_char;
    fn sqlite3_exec(
        db: *mut sqlite3,
        sql: *const c_char,
        callback: Option<
            unsafe extern "C" fn(*mut c_void, c_int, *mut *mut c_char, *mut *mut c_char) -> c_int,
        >,
        arg: *mut c_void,
        errmsg: *mut *mut c_char,
    ) -> c_int;
    fn sqlite3_prepare_v2(
        db: *mut sqlite3,
        sql: *const c_char,
        n_byte: c_int,
        pp_stmt: *mut *mut sqlite3_stmt,
        pz_tail: *mut *const c_char,
    ) -> c_int;
    fn sqlite3_finalize(stmt: *mut sqlite3_stmt) -> c_int;
    fn sqlite3_step(stmt: *mut sqlite3_stmt) -> c_int;
    fn sqlite3_reset(stmt: *mut sqlite3_stmt) -> c_int;
    fn sqlite3_clear_bindings(stmt: *mut sqlite3_stmt) -> c_int;
    fn sqlite3_bind_text(
        stmt: *mut sqlite3_stmt,
        index: c_int,
        value: *const c_char,
        n: c_int,
        destructor: Option<unsafe extern "C" fn(*mut c_void)>,
    ) -> c_int;
    fn sqlite3_bind_null(stmt: *mut sqlite3_stmt, index: c_int) -> c_int;
    fn sqlite3_column_text(stmt: *mut sqlite3_stmt, index: c_int) -> *const c_uchar;
    fn sqlite3_column_bytes(stmt: *mut sqlite3_stmt, index: c_int) -> c_int;
    fn sqlite3_column_int64(stmt: *mut sqlite3_stmt, index: c_int) -> i64;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoRecord {
    pub name: String,
    pub source_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_url: Option<String>,
    pub local_path: String,
    pub git_root: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_branch: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head_commit: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexStateRecord {
    pub repo_name: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head_commit: Option<String>,
    pub dirty: bool,
    pub untracked: bool,
    pub modified: bool,
    pub worktree_fingerprint: String,
    pub indexed_files: usize,
    pub total_chunks: usize,
    pub languages: BTreeMap<String, usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub indexed_at: String,
}

/// Schema version stored in `PRAGMA user_version`. Bump when DDL changes;
/// `init_schema` skips the DDL block when the version already matches.
const SCHEMA_VERSION: i64 = 2;

pub(crate) struct Store {
    db: Database,
}

impl Store {
    pub(crate) fn open(db_path: &Path) -> AsrResult<Self> {
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent).map_err(|err| {
                AsrError::with_path(
                    "asr_home_create_failed",
                    format!("Failed to create database parent directory: {err}"),
                    path_string(parent),
                )
            })?;
        }
        Ok(Self {
            db: Database::open(db_path)?,
        })
    }

    pub(crate) fn init_schema(&self) -> AsrResult<()> {
        // Skip DDL if the schema is already at the expected version.
        if self.db.user_version()? == SCHEMA_VERSION {
            return Ok(());
        }

        self.db.exec(
            r#"
            PRAGMA journal_mode = WAL;
            CREATE TABLE IF NOT EXISTS repos (
              id INTEGER PRIMARY KEY,
              name TEXT NOT NULL UNIQUE,
              source_type TEXT NOT NULL,
              remote_url TEXT,
              local_path TEXT NOT NULL,
              git_root TEXT NOT NULL,
              default_branch TEXT,
              head_commit TEXT,
              created_at TEXT NOT NULL,
              updated_at TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS repos_name_idx ON repos(name);
            CREATE INDEX IF NOT EXISTS repos_source_type_idx ON repos(source_type);

            CREATE TABLE IF NOT EXISTS index_state (
              repo_name TEXT PRIMARY KEY,
              status TEXT NOT NULL,
              head_commit TEXT,
              dirty TEXT NOT NULL,
              untracked TEXT NOT NULL,
              modified TEXT NOT NULL,
              worktree_fingerprint TEXT NOT NULL,
              indexed_files TEXT NOT NULL,
              total_chunks TEXT NOT NULL,
              languages_json TEXT NOT NULL,
              content_hash TEXT,
              error TEXT,
              indexed_at TEXT NOT NULL,
              FOREIGN KEY(repo_name) REFERENCES repos(name) ON DELETE CASCADE
            );
            CREATE INDEX IF NOT EXISTS index_state_status_idx ON index_state(status);
            CREATE INDEX IF NOT EXISTS index_state_head_idx ON index_state(head_commit);

            CREATE TABLE IF NOT EXISTS chunks (
              repo_name TEXT NOT NULL,
              head_commit TEXT,
              path TEXT NOT NULL,
              start_line TEXT NOT NULL,
              end_line TEXT NOT NULL,
              language TEXT,
              content TEXT NOT NULL,
              FOREIGN KEY(repo_name) REFERENCES repos(name) ON DELETE CASCADE
            );
            CREATE INDEX IF NOT EXISTS chunks_repo_idx ON chunks(repo_name);
            CREATE INDEX IF NOT EXISTS chunks_repo_head_idx ON chunks(repo_name, head_commit);
            CREATE INDEX IF NOT EXISTS chunks_path_idx ON chunks(repo_name, path);
            "#,
        )?;

        // Compatibility migration for ASR_HOME directories created by earlier
        // registry-only builds that lack the worktree_fingerprint column.
        // Duplicate-column errors are expected on fresh databases and intentionally
        // ignored; stale rows will be detected via the default empty fingerprint.
        if let Err(err) = self.db.exec(
            "ALTER TABLE index_state ADD COLUMN worktree_fingerprint TEXT NOT NULL DEFAULT ''",
        ) {
            log::debug!("Schema migration (worktree_fingerprint): {}", err.message);
        }

        // Record the schema version so subsequent open_store calls skip DDL.
        self.db
            .exec(&format!("PRAGMA user_version = {SCHEMA_VERSION}"))?;

        Ok(())
    }

    pub(crate) fn insert_repo(&self, repo: &RepoRecord) -> AsrResult<()> {
        let mut stmt = self.db.prepare(
            "INSERT INTO repos (name, source_type, remote_url, local_path, git_root, default_branch, head_commit, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )?;
        stmt.bind_text(1, &repo.name)?;
        stmt.bind_text(2, &repo.source_type)?;
        stmt.bind_optional_text(3, repo.remote_url.as_deref())?;
        stmt.bind_text(4, &repo.local_path)?;
        stmt.bind_text(5, &repo.git_root)?;
        stmt.bind_optional_text(6, repo.default_branch.as_deref())?;
        stmt.bind_optional_text(7, repo.head_commit.as_deref())?;
        stmt.bind_text(8, &repo.created_at)?;
        stmt.bind_text(9, &repo.updated_at)?;
        expect_done(stmt.step()?, "Unexpected row while inserting repository")
    }

    pub(crate) fn update_repo_head(
        &self,
        name: &str,
        branch: Option<&str>,
        head_commit: Option<&str>,
        updated_at: &str,
    ) -> AsrResult<()> {
        let mut stmt = self.db.prepare(
            "UPDATE repos SET default_branch = ?, head_commit = ?, updated_at = ? WHERE name = ?",
        )?;
        stmt.bind_optional_text(1, branch)?;
        stmt.bind_optional_text(2, head_commit)?;
        stmt.bind_text(3, updated_at)?;
        stmt.bind_text(4, name)?;
        expect_done(
            stmt.step()?,
            "Unexpected row while updating repository head",
        )
    }

    pub(crate) fn get_repo(&self, name: &str) -> AsrResult<Option<RepoRecord>> {
        let mut stmt = self.db.prepare(
            "SELECT name, source_type, remote_url, local_path, git_root, default_branch, head_commit, created_at, updated_at FROM repos WHERE name = ? LIMIT 1",
        )?;
        stmt.bind_text(1, name)?;
        match stmt.step()? {
            Step::Row => Ok(Some(repo_from_statement(&stmt))),
            Step::Done => Ok(None),
        }
    }

    pub(crate) fn list_repos(&self) -> AsrResult<Vec<RepoRecord>> {
        let mut stmt = self.db.prepare(
            "SELECT name, source_type, remote_url, local_path, git_root, default_branch, head_commit, created_at, updated_at FROM repos ORDER BY name COLLATE BINARY ASC",
        )?;
        let mut repos = Vec::new();
        while let Step::Row = stmt.step()? {
            repos.push(repo_from_statement(&stmt));
        }
        Ok(repos)
    }

    pub(crate) fn put_index_state(&self, state: &IndexStateRecord) -> AsrResult<()> {
        self.write_index_state(state)
    }

    pub(crate) fn replace_index(
        &self,
        repo_name: &str,
        state: &IndexStateRecord,
        chunks: &[Chunk],
    ) -> AsrResult<()> {
        self.db.exec("BEGIN IMMEDIATE")?;
        let result = (|| -> AsrResult<()> {
            self.delete_chunks(repo_name)?;
            self.write_index_state(state)?;
            self.insert_chunks(repo_name, state.head_commit.as_deref(), chunks)?;
            Ok(())
        })();

        match result {
            Ok(()) => self.db.exec("COMMIT"),
            Err(err) => {
                // ROLLBACK failure is extremely rare (e.g., disk I/O error on WAL).
                // Log it but still return the original error; the connection will
                // auto-rollback when it is dropped.
                if let Err(rb_err) = self.db.exec("ROLLBACK") {
                    log::warn!(
                        "SQLite ROLLBACK failed: {}; connection will rollback on close",
                        rb_err.message
                    );
                }
                Err(err)
            }
        }
    }

    pub(crate) fn get_index_state(&self, repo_name: &str) -> AsrResult<Option<IndexStateRecord>> {
        let mut stmt = self.db.prepare(
            "SELECT repo_name, status, head_commit, dirty, untracked, modified, worktree_fingerprint, indexed_files, total_chunks, languages_json, content_hash, error, indexed_at FROM index_state WHERE repo_name = ? LIMIT 1",
        )?;
        stmt.bind_text(1, repo_name)?;
        match stmt.step()? {
            Step::Row => Ok(Some(index_state_from_statement(&stmt))),
            Step::Done => Ok(None),
        }
    }

    pub(crate) fn list_chunks(&self, repo_name: &str) -> AsrResult<Vec<Chunk>> {
        let mut stmt = self.db.prepare(
            "SELECT content, path, start_line, end_line, language FROM chunks WHERE repo_name = ? ORDER BY path COLLATE BINARY ASC, CAST(start_line AS INTEGER) ASC, CAST(end_line AS INTEGER) ASC",
        )?;
        stmt.bind_text(1, repo_name)?;
        let mut chunks = Vec::new();
        while let Step::Row = stmt.step()? {
            chunks.push(chunk_from_statement(&stmt));
        }
        Ok(chunks)
    }

    fn delete_chunks(&self, repo_name: &str) -> AsrResult<()> {
        let mut stmt = self.db.prepare("DELETE FROM chunks WHERE repo_name = ?")?;
        stmt.bind_text(1, repo_name)?;
        expect_done(stmt.step()?, "Unexpected row while deleting chunks")
    }

    fn insert_chunks(
        &self,
        repo_name: &str,
        head_commit: Option<&str>,
        chunks: &[Chunk],
    ) -> AsrResult<()> {
        let mut stmt = self.db.prepare(
            "INSERT INTO chunks (repo_name, head_commit, path, start_line, end_line, language, content) VALUES (?, ?, ?, ?, ?, ?, ?)",
        )?;
        for chunk in chunks {
            stmt.bind_text(1, repo_name)?;
            stmt.bind_optional_text(2, head_commit)?;
            stmt.bind_text(3, &chunk.file_path)?;
            stmt.bind_text(4, &chunk.start_line.to_string())?;
            stmt.bind_text(5, &chunk.end_line.to_string())?;
            stmt.bind_optional_text(6, chunk.language.as_deref())?;
            stmt.bind_text(7, &chunk.content)?;
            expect_done(stmt.step()?, "Unexpected row while inserting chunk")?;
            stmt.reset()?;
        }
        Ok(())
    }

    fn write_index_state(&self, state: &IndexStateRecord) -> AsrResult<()> {
        let languages_json = serde_json::to_string(&state.languages).map_err(|err| {
            AsrError::new(
                "store_error",
                format!("Failed to serialize index language metadata: {err}"),
            )
        })?;
        let mut stmt = self.db.prepare(
            "INSERT OR REPLACE INTO index_state (repo_name, status, head_commit, dirty, untracked, modified, worktree_fingerprint, indexed_files, total_chunks, languages_json, content_hash, error, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )?;
        stmt.bind_text(1, &state.repo_name)?;
        stmt.bind_text(2, &state.status)?;
        stmt.bind_optional_text(3, state.head_commit.as_deref())?;
        stmt.bind_text(4, bool_text(state.dirty))?;
        stmt.bind_text(5, bool_text(state.untracked))?;
        stmt.bind_text(6, bool_text(state.modified))?;
        stmt.bind_text(7, &state.worktree_fingerprint)?;
        stmt.bind_text(8, &state.indexed_files.to_string())?;
        stmt.bind_text(9, &state.total_chunks.to_string())?;
        stmt.bind_text(10, &languages_json)?;
        stmt.bind_optional_text(11, state.content_hash.as_deref())?;
        stmt.bind_optional_text(12, state.error.as_deref())?;
        stmt.bind_text(13, &state.indexed_at)?;
        expect_done(stmt.step()?, "Unexpected row while writing index state")
    }
}

fn repo_from_statement(stmt: &Statement<'_>) -> RepoRecord {
    RepoRecord {
        name: stmt.column_text(0).unwrap_or_default(),
        source_type: stmt.column_text(1).unwrap_or_default(),
        remote_url: stmt.column_text(2),
        local_path: stmt.column_text(3).unwrap_or_default(),
        git_root: stmt.column_text(4).unwrap_or_default(),
        default_branch: stmt.column_text(5),
        head_commit: stmt.column_text(6),
        created_at: stmt.column_text(7).unwrap_or_default(),
        updated_at: stmt.column_text(8).unwrap_or_default(),
    }
}

fn index_state_from_statement(stmt: &Statement<'_>) -> IndexStateRecord {
    let languages_json = stmt.column_text(9).unwrap_or_else(|| "{}".to_string());
    let languages = serde_json::from_str(&languages_json).unwrap_or_default();
    IndexStateRecord {
        repo_name: stmt.column_text(0).unwrap_or_default(),
        status: stmt.column_text(1).unwrap_or_default(),
        head_commit: stmt.column_text(2),
        dirty: parse_bool(stmt.column_text(3)),
        untracked: parse_bool(stmt.column_text(4)),
        modified: parse_bool(stmt.column_text(5)),
        worktree_fingerprint: stmt.column_text(6).unwrap_or_default(),
        indexed_files: parse_usize(stmt.column_text(7)),
        total_chunks: parse_usize(stmt.column_text(8)),
        languages,
        content_hash: stmt.column_text(10),
        error: stmt.column_text(11),
        indexed_at: stmt.column_text(12).unwrap_or_default(),
    }
}

fn chunk_from_statement(stmt: &Statement<'_>) -> Chunk {
    Chunk::new(
        stmt.column_text(0).unwrap_or_default(),
        stmt.column_text(1).unwrap_or_default(),
        parse_usize(stmt.column_text(2)).max(1),
        parse_usize(stmt.column_text(3)).max(1),
        stmt.column_text(4),
    )
}

fn bool_text(value: bool) -> &'static str {
    if value {
        "1"
    } else {
        "0"
    }
}

fn parse_bool(value: Option<String>) -> bool {
    matches!(value.as_deref(), Some("1") | Some("true") | Some("TRUE"))
}

fn parse_usize(value: Option<String>) -> usize {
    value
        .and_then(|text| text.parse::<usize>().ok())
        .unwrap_or_default()
}

fn expect_done(step: Step, message: &'static str) -> AsrResult<()> {
    match step {
        Step::Done => Ok(()),
        Step::Row => Err(AsrError::new("store_error", message)),
    }
}

struct Database {
    handle: *mut sqlite3,
}

impl Database {
    fn open(path: &Path) -> AsrResult<Self> {
        let c_path = cstring(path_string(path), "db_path")?;
        let mut handle: *mut sqlite3 = ptr::null_mut();
        let rc = unsafe { sqlite3_open(c_path.as_ptr(), &mut handle) };
        if rc != SQLITE_OK || handle.is_null() {
            let message = if handle.is_null() {
                "SQLite open failed".to_string()
            } else {
                unsafe { sqlite_error(handle) }
            };
            if !handle.is_null() {
                unsafe {
                    sqlite3_close(handle);
                }
            }
            return Err(AsrError::with_path(
                "sqlite_open_failed",
                message,
                path_string(path),
            ));
        }
        let db = Self { handle };
        db.exec("PRAGMA busy_timeout = 5000")?;
        db.exec("PRAGMA foreign_keys = ON")?;
        Ok(db)
    }

    fn user_version(&self) -> AsrResult<i64> {
        let mut stmt = self.prepare("PRAGMA user_version")?;
        match stmt.step()? {
            Step::Row => Ok(stmt.column_i64(0)),
            Step::Done => Ok(0),
        }
    }

    fn exec(&self, sql: &str) -> AsrResult<()> {
        let c_sql = cstring(sql, "sql")?;
        let rc = unsafe {
            sqlite3_exec(
                self.handle,
                c_sql.as_ptr(),
                None,
                ptr::null_mut(),
                ptr::null_mut(),
            )
        };
        if rc != SQLITE_OK {
            return Err(AsrError::new("sqlite_exec_failed", unsafe {
                sqlite_error(self.handle)
            }));
        }
        Ok(())
    }

    fn prepare(&self, sql: &str) -> AsrResult<Statement<'_>> {
        let c_sql = cstring(sql, "sql")?;
        let mut stmt: *mut sqlite3_stmt = ptr::null_mut();
        let rc = unsafe {
            sqlite3_prepare_v2(self.handle, c_sql.as_ptr(), -1, &mut stmt, ptr::null_mut())
        };
        if rc != SQLITE_OK || stmt.is_null() {
            return Err(AsrError::new("sqlite_prepare_failed", unsafe {
                sqlite_error(self.handle)
            }));
        }
        Ok(Statement {
            db: self,
            stmt,
            bindings: Vec::new(),
        })
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            // sqlite3_close_v2 finalizes any remaining prepared statements
            // before closing, so it is safe even if a Statement outlives this
            // Database in a future refactor.
            unsafe {
                sqlite3_close_v2(self.handle);
            }
        }
    }
}

struct Statement<'db> {
    db: &'db Database,
    stmt: *mut sqlite3_stmt,
    bindings: Vec<CString>,
}

impl Statement<'_> {
    fn bind_text(&mut self, index: c_int, value: &str) -> AsrResult<()> {
        let value = cstring(value, "bind_value")?;
        let ptr = value.as_ptr();
        self.bindings.push(value);
        let rc = unsafe { sqlite3_bind_text(self.stmt, index, ptr, -1, None) };
        if rc != SQLITE_OK {
            return Err(AsrError::new("sqlite_bind_failed", unsafe {
                sqlite_error(self.db.handle)
            }));
        }
        Ok(())
    }

    fn bind_optional_text(&mut self, index: c_int, value: Option<&str>) -> AsrResult<()> {
        match value {
            Some(value) => self.bind_text(index, value),
            None => {
                let rc = unsafe { sqlite3_bind_null(self.stmt, index) };
                if rc != SQLITE_OK {
                    return Err(AsrError::new("sqlite_bind_failed", unsafe {
                        sqlite_error(self.db.handle)
                    }));
                }
                Ok(())
            }
        }
    }

    fn step(&mut self) -> AsrResult<Step> {
        match unsafe { sqlite3_step(self.stmt) } {
            SQLITE_ROW => Ok(Step::Row),
            SQLITE_DONE => Ok(Step::Done),
            _ => Err(AsrError::new("sqlite_step_failed", unsafe {
                sqlite_error(self.db.handle)
            })),
        }
    }

    fn reset(&mut self) -> AsrResult<()> {
        let reset_rc = unsafe { sqlite3_reset(self.stmt) };
        if reset_rc != SQLITE_OK {
            return Err(AsrError::new("sqlite_reset_failed", unsafe {
                sqlite_error(self.db.handle)
            }));
        }
        let clear_rc = unsafe { sqlite3_clear_bindings(self.stmt) };
        if clear_rc != SQLITE_OK {
            return Err(AsrError::new("sqlite_clear_bindings_failed", unsafe {
                sqlite_error(self.db.handle)
            }));
        }
        self.bindings.clear();
        Ok(())
    }

    fn column_i64(&self, index: c_int) -> i64 {
        unsafe { sqlite3_column_int64(self.stmt, index) }
    }

    fn column_text(&self, index: c_int) -> Option<String> {
        let ptr = unsafe { sqlite3_column_text(self.stmt, index) };
        if ptr.is_null() {
            return None;
        }
        let len = unsafe { sqlite3_column_bytes(self.stmt, index) };
        if len < 0 {
            return None;
        }
        let bytes = unsafe { slice::from_raw_parts(ptr, len as usize) };
        Some(String::from_utf8_lossy(bytes).to_string())
    }
}

impl Drop for Statement<'_> {
    fn drop(&mut self) {
        if !self.stmt.is_null() {
            unsafe {
                sqlite3_finalize(self.stmt);
            }
        }
    }
}

enum Step {
    Row,
    Done,
}

fn cstring(value: impl AsRef<str>, field: &'static str) -> AsrResult<CString> {
    CString::new(value.as_ref()).map_err(|_| {
        AsrError::new(
            "invalid_nul_byte",
            format!("Value for {field} contains an unsupported NUL byte"),
        )
    })
}

unsafe fn sqlite_error(handle: *mut sqlite3) -> String {
    let message = sqlite3_errmsg(handle);
    if message.is_null() {
        return "unknown SQLite error".to_string();
    }
    CStr::from_ptr(message).to_string_lossy().to_string()
}