magellan 3.3.1

Deterministic codebase mapping tool for local development
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Code generation and storage module.
//!
//! This module provides functionality for storing and retrieving source code chunks
//! with their byte spans. This enables token-efficient queries by storing code
//! fragments in the database rather than re-reading entire files.
//!
//! # :memory: Database Path Retrieval
//!
//! ChunkStore uses SQLite Shared connections (via `Arc<Mutex<Connection>>`), which
//! don't work with `:memory:` databases. Each thread would get its own separate
//! in-memory database, breaking the shared state assumption.
//!
//! Additionally, operations that retrieve the database file path (e.g., the `connect()`
//! method's shared connection branch) will fail for `:memory:` databases because
//! in-memory databases have no file path.
//!
//! **Workaround:** Use file-based databases for ChunkStore operations.
//! See [MANUAL.md](../../MANUAL.md#known-limitations) for details.

pub mod schema;

use anyhow::Result;
use rusqlite::{params, OptionalExtension};
use std::path::Path;
use std::sync::{Arc, Mutex};

pub use schema::CodeChunk;

/// Storage backend for ChunkStore.
///
/// Supports three modes:
/// - Owned: ChunkStore opens its own SQLite connections (legacy)
/// - Shared: Uses a shared SQLite connection for transactions
/// - SideTables: Uses the SideTables trait abstraction (V3 backend)
enum ChunkStoreBackend {
    /// Owned connection source - ChunkStore opens connections as needed
    Owned(std::path::PathBuf),
    /// Shared connection - provided by CodeGraph for transactional operations
    /// Thread-safe: uses Arc<Mutex<>> instead of Rc<RefCell<>>
    Shared(Arc<Mutex<rusqlite::Connection>>),
    /// SideTables abstraction - for V3 backend (no SQLite dependency)
    SideTables(Arc<dyn crate::graph::side_tables::SideTables>),
}

/// Code chunk storage operations.
///
/// Can use either its own connections (legacy), a shared connection provided
/// by CodeGraph for transactional operations, or the SideTables abstraction
/// for backend-agnostic storage (V3).
pub struct ChunkStore {
    /// Backend - either SQLite connection or SideTables trait
    backend: ChunkStoreBackend,
}

impl ChunkStore {
    /// Create a new ChunkStore with the given database path.
    ///
    /// This is the legacy constructor that opens its own connections.
    pub fn new(db_path: &Path) -> Self {
        Self {
            backend: ChunkStoreBackend::Owned(db_path.to_path_buf()),
        }
    }

    /// Create a ChunkStore with a shared connection.
    ///
    /// This constructor enables transactional operations by using a connection
    /// shared with CodeGraph. All operations will use this shared connection.
    ///
    /// # Arguments
    /// * `conn` - Shared SQLite connection wrapped in Arc<Mutex<>> for thread-safe interior mutability
    pub fn with_connection(conn: rusqlite::Connection) -> Self {
        Self {
            backend: ChunkStoreBackend::Shared(Arc::new(Mutex::new(conn))),
        }
    }

    /// Create a ChunkStore using the SideTables abstraction.
    ///
    /// This constructor is used for V3 backend where we want to avoid SQLite
    /// entirely for side tables.
    ///
    /// # Arguments
    /// * `side_tables` - Arc<dyn SideTables> implementation
    pub fn with_side_tables(side_tables: Arc<dyn crate::graph::side_tables::SideTables>) -> Self {
        Self {
            backend: ChunkStoreBackend::SideTables(side_tables),
        }
    }

    /// Create a stub ChunkStore using a temporary file (for testing).
    ///
    /// Uses a temporary file so that new connections can access the same data.
    pub fn in_memory() -> Self {
        // Create: Create a unique temporary file for each call
        // This prevents conflicts when multiple tests run concurrently
        let temp_dir = std::env::temp_dir();
        let unique_id = format!(
            "{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let db_path = temp_dir.join(format!("magellan_chunkstore_stub_{}.db", unique_id));

        let conn = rusqlite::Connection::open(&db_path)
            .expect("Failed to create temporary database for ChunkStore stub");

        // Create the code_chunks table with full schema for compatibility
        conn.execute(
            "CREATE TABLE IF NOT EXISTS code_chunks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                file_path TEXT NOT NULL,
                byte_start INTEGER NOT NULL,
                byte_end INTEGER NOT NULL,
                content TEXT NOT NULL,
                content_hash TEXT NOT NULL,
                symbol_name TEXT,
                symbol_kind TEXT,
                created_at INTEGER NOT NULL,
                UNIQUE(file_path, byte_start, byte_end)
            )",
            [],
        )
        .expect("Failed to create code_chunks table in ChunkStore stub");

        // Create the ast_nodes table for AST storage
        conn.execute(
            "CREATE TABLE IF NOT EXISTS ast_nodes (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                parent_id INTEGER,
                kind TEXT NOT NULL,
                byte_start INTEGER NOT NULL,
                byte_end INTEGER NOT NULL,
                file_id INTEGER
            )",
            [],
        )
        .expect("Failed to create ast_nodes table in ChunkStore stub");

        // Create the cfg_blocks table for CFG storage
        conn.execute(
            "CREATE TABLE IF NOT EXISTS cfg_blocks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                function_id INTEGER NOT NULL,
                kind TEXT NOT NULL,
                terminator TEXT NOT NULL,
                byte_start INTEGER NOT NULL,
                byte_end INTEGER NOT NULL,
                start_line INTEGER NOT NULL,
                start_col INTEGER NOT NULL,
                end_line INTEGER NOT NULL,
                end_col INTEGER NOT NULL,
                cfg_hash TEXT,
                statements TEXT,
                coord_x INTEGER DEFAULT 0,
                coord_y INTEGER DEFAULT 0,
                coord_z INTEGER DEFAULT 0,
                coord_t TEXT DEFAULT NULL
            )",
            [],
        )
        .expect("Failed to create cfg_blocks table in ChunkStore stub");

        // Create indexes (use IF NOT EXISTS to avoid conflicts on reconnect)
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_chunks_file_path ON code_chunks(file_path)",
            [],
        )
        .expect("Failed to create file_path index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_chunks_symbol_name ON code_chunks(symbol_name)",
            [],
        )
        .expect("Failed to create symbol_name index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_chunks_content_hash ON code_chunks(content_hash)",
            [],
        )
        .expect("Failed to create content_hash index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_ast_nodes_parent ON ast_nodes(parent_id)",
            [],
        )
        .expect("Failed to create ast_nodes parent index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_ast_nodes_span ON ast_nodes(byte_start, byte_end)",
            [],
        )
        .expect("Failed to create ast_nodes span index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_ast_nodes_file_id ON ast_nodes(file_id)",
            [],
        )
        .expect("Failed to create ast_nodes file_id index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_cfg_blocks_function ON cfg_blocks(function_id)",
            [],
        )
        .expect("Failed to create cfg_blocks function index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_cfg_blocks_span ON cfg_blocks(byte_start, byte_end)",
            [],
        )
        .expect("Failed to create cfg_blocks span index");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_cfg_blocks_hash ON cfg_blocks(cfg_hash)",
            [],
        )
        .expect("Failed to create cfg_blocks hash index");

        conn.execute(
            "CREATE TABLE IF NOT EXISTS cfg_edges (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                function_id INTEGER NOT NULL,
                source_idx INTEGER NOT NULL,
                target_idx INTEGER NOT NULL,
                edge_type TEXT NOT NULL
            )",
            [],
        )
        .expect("Failed to create cfg_edges table in ChunkStore");

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_cfg_edges_function ON cfg_edges(function_id)",
            [],
        )
        .expect("Failed to create cfg_edges function index");

        Self {
            backend: ChunkStoreBackend::Owned(db_path),
        }
    }

    /// Get a connection to the database.
    ///
    /// For owned connections, opens a new connection.
    /// For shared connections, also opens a new connection (to the same database).
    ///
    /// Note: This method always opens a NEW connection, even when using shared mode.
    /// This is needed for operations that require raw access to the connection,
    /// such as delete_edges_touching_entities which operates on sqlitegraph tables.
    ///
    /// # Panics
    /// Panics if called when using SideTables backend (not applicable).
    pub fn connect(&self) -> Result<rusqlite::Connection, rusqlite::Error> {
        match &self.backend {
            ChunkStoreBackend::Owned(path) => rusqlite::Connection::open(path),
            ChunkStoreBackend::Shared(arc) => {
                // Open a new connection to the same database.
                // We need to extract the path from the existing connection.
                let conn = arc.lock().map_err(|_| {
                    rusqlite::Error::InvalidParameterName(
                        "Shared connection lock failed".to_string(),
                    )
                })?;
                // Get the database path from the existing connection
                let path = conn.path().ok_or_else(|| {
                    rusqlite::Error::InvalidParameterName(
                        "Cannot get database path. :memory: databases have no file path. \
                        Use a file-based database (e.g., --db magellan.db) instead. \
                        See MANUAL.md for details."
                            .to_string(),
                    )
                })?;
                // Open a new connection to the same database
                rusqlite::Connection::open(path)
            }
            ChunkStoreBackend::SideTables(_) => Err(rusqlite::Error::InvalidParameterName(
                "SQLite connection not available with V3 backend".to_string(),
            )),
        }
    }

    /// Execute an operation with a connection.
    ///
    /// This helper method abstracts over owned vs shared connection sources,
    /// allowing all ChunkStore methods to work with both modes.
    fn with_conn<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&rusqlite::Connection) -> Result<R>,
    {
        match &self.backend {
            ChunkStoreBackend::Owned(path) => {
                let conn = rusqlite::Connection::open(path)?;
                let result = f(&conn)?;
                Ok(result)
            }
            ChunkStoreBackend::Shared(arc) => {
                let conn = arc
                    .lock()
                    .map_err(|_| anyhow::anyhow!("Shared connection lock poisoned"))?;
                let result = f(&conn)?;
                Ok(result)
            }
            ChunkStoreBackend::SideTables(_) => Err(anyhow::anyhow!(
                "SQLite operations not available with V3 backend. Use SideTables trait methods."
            )),
        }
    }

    /// Execute a mutable operation with a connection.
    ///
    /// This helper method is for operations that need mutable access to the connection.
    fn with_connection_mut<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&mut rusqlite::Connection) -> Result<R>,
    {
        match &self.backend {
            ChunkStoreBackend::Owned(path) => {
                let mut conn = rusqlite::Connection::open(path)?;
                let result = f(&mut conn)?;
                Ok(result)
            }
            ChunkStoreBackend::Shared(arc) => {
                let mut conn = arc
                    .lock()
                    .map_err(|_| anyhow::anyhow!("Shared connection lock poisoned"))?;
                let result = f(&mut conn)?;
                Ok(result)
            }
            ChunkStoreBackend::SideTables(_) => Err(anyhow::anyhow!(
                "SQLite operations not available with V3 backend. Use SideTables trait methods."
            )),
        }
    }

    /// Ensure the code_chunks table exists.
    pub fn ensure_schema(&self) -> Result<()> {
        self.with_connection_mut(|conn| {
            conn.execute(
                "CREATE TABLE IF NOT EXISTS code_chunks (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    file_path TEXT NOT NULL,
                    byte_start INTEGER NOT NULL,
                    byte_end INTEGER NOT NULL,
                    content TEXT NOT NULL,
                    content_hash TEXT NOT NULL,
                    symbol_name TEXT,
                    symbol_kind TEXT,
                    created_at INTEGER NOT NULL,
                    UNIQUE(file_path, byte_start, byte_end)
                )",
                [],
            )
            .map_err(|e| anyhow::anyhow!("Failed to create code_chunks table: {}", e))?;

            // Create indexes for common queries
            conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_chunks_file_path ON code_chunks(file_path)",
                [],
            )
            .map_err(|e| anyhow::anyhow!("Failed to create file_path index: {}", e))?;

            conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_chunks_symbol_name ON code_chunks(symbol_name)",
                [],
            )
            .map_err(|e| anyhow::anyhow!("Failed to create symbol_name index: {}", e))?;

            conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_chunks_content_hash ON code_chunks(content_hash)",
                [],
            )
            .map_err(|e| anyhow::anyhow!("Failed to create content_hash index: {}", e))?;

            Ok(())
        })
    }

    /// Store a code chunk in the database.
    ///
    /// Uses INSERT OR REPLACE to handle duplicates based on (file_path, byte_start, byte_end).
    pub fn store_chunk(&self, chunk: &CodeChunk) -> Result<i64> {
        self.with_connection_mut(|conn| {
            conn.execute(
                "INSERT OR REPLACE INTO code_chunks
                    (file_path, byte_start, byte_end, content, content_hash, symbol_name, symbol_kind, created_at)
                    VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    chunk.file_path,
                    chunk.byte_start as i64,
                    chunk.byte_end as i64,
                    chunk.content,
                    chunk.content_hash,
                    chunk.symbol_name,
                    chunk.symbol_kind,
                    chunk.created_at,
                ],
            )
            .map_err(|e| anyhow::anyhow!("Failed to store code chunk: {}", e))?;

            Ok(conn.last_insert_rowid())
        })
    }

    /// Store multiple code chunks in a transaction.
    pub fn store_chunks(&self, chunks: &[CodeChunk]) -> Result<Vec<i64>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => {
                // V3 backend: use SideTables trait method
                let mut ids = Vec::new();
                for chunk in chunks {
                    let id = tables.store_chunk(chunk)?;
                    ids.push(id);
                }
                Ok(ids)
            }
            _ => {
                // SQLite backend: use direct connection
                self.with_connection_mut(|conn| {
                    let tx = conn
                        .unchecked_transaction()
                        .map_err(|e| anyhow::anyhow!("Failed to start transaction: {}", e))?;

                    let mut ids = Vec::new();

                    for chunk in chunks {
                        tx.execute(
                            "INSERT OR REPLACE INTO code_chunks
                                (file_path, byte_start, byte_end, content, content_hash, symbol_name, symbol_kind, created_at)
                                VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                            params![
                                chunk.file_path,
                                chunk.byte_start as i64,
                                chunk.byte_end as i64,
                                chunk.content,
                                chunk.content_hash,
                                chunk.symbol_name,
                                chunk.symbol_kind,
                                chunk.created_at,
                            ],
                        )
                        .map_err(|e| anyhow::anyhow!("Failed to store code chunk: {}", e))?;

                        ids.push(tx.last_insert_rowid());
                    }

                    tx.commit()
                        .map_err(|e| anyhow::anyhow!("Failed to commit transaction: {}", e))?;

                    Ok(ids)
                })
            }
        }
    }

    /// Get a code chunk by file path and byte span.
    pub fn get_chunk_by_span(
        &self,
        file_path: &str,
        byte_start: usize,
        byte_end: usize,
    ) -> Result<Option<CodeChunk>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => {
                tables.get_chunk_by_span(file_path, byte_start, byte_end)
            }
            _ => self.with_conn(|conn| {
                let mut stmt = conn
                    .prepare_cached(
                        "SELECT id, file_path, byte_start, byte_end, content, content_hash,
                                    symbol_name, symbol_kind, created_at
                             FROM code_chunks
                             WHERE file_path = ?1 AND byte_start = ?2 AND byte_end = ?3",
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to prepare query: {}", e))?;

                let result = stmt
                    .query_row(
                        params![file_path, byte_start as i64, byte_end as i64],
                        |row: &rusqlite::Row| {
                            Ok(CodeChunk {
                                id: Some(row.get(0)?),
                                file_path: row.get(1)?,
                                byte_start: row.get::<_, i64>(2)? as usize,
                                byte_end: row.get::<_, i64>(3)? as usize,
                                content: row.get(4)?,
                                content_hash: row.get(5)?,
                                symbol_name: row.get(6)?,
                                symbol_kind: row.get(7)?,
                                created_at: row.get(8)?,
                            })
                        },
                    )
                    .optional()
                    .map_err(|e| anyhow::anyhow!("Failed to query code chunk: {}", e))?;

                Ok(result)
            }),
        }
    }

    /// Get all code chunks for a specific file.
    pub fn get_chunks_for_file(&self, file_path: &str) -> Result<Vec<CodeChunk>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => tables.get_chunks_for_file(file_path),
            _ => self.with_conn(|conn| {
                let mut stmt = conn
                    .prepare_cached(
                        "SELECT id, file_path, byte_start, byte_end, content, content_hash,
                                    symbol_name, symbol_kind, created_at
                             FROM code_chunks
                             WHERE file_path = ?1
                             ORDER BY byte_start",
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to prepare query: {}", e))?;

                let chunks = stmt
                    .query_map(params![file_path], |row: &rusqlite::Row| {
                        Ok(CodeChunk {
                            id: Some(row.get(0)?),
                            file_path: row.get(1)?,
                            byte_start: row.get::<_, i64>(2)? as usize,
                            byte_end: row.get::<_, i64>(3)? as usize,
                            content: row.get(4)?,
                            content_hash: row.get(5)?,
                            symbol_name: row.get(6)?,
                            symbol_kind: row.get(7)?,
                            created_at: row.get(8)?,
                        })
                    })
                    .map_err(|e| anyhow::anyhow!("Failed to query code chunks: {}", e))?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunks: {}", e))?;

                Ok(chunks)
            }),
        }
    }

    /// Get code chunks for a specific symbol in a file.
    pub fn get_chunks_for_symbol(
        &self,
        file_path: &str,
        symbol_name: &str,
    ) -> Result<Vec<CodeChunk>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => {
                tables.get_chunks_by_symbol(file_path, symbol_name)
            }
            _ => self.with_conn(|conn| {
                let mut stmt = conn
                    .prepare_cached(
                        "SELECT id, file_path, byte_start, byte_end, content, content_hash,
                                    symbol_name, symbol_kind, created_at
                             FROM code_chunks
                             WHERE file_path = ?1 AND symbol_name = ?2
                             ORDER BY byte_start",
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to prepare query: {}", e))?;

                let chunks = stmt
                    .query_map(params![file_path, symbol_name], |row: &rusqlite::Row| {
                        Ok(CodeChunk {
                            id: Some(row.get(0)?),
                            file_path: row.get(1)?,
                            byte_start: row.get::<_, i64>(2)? as usize,
                            byte_end: row.get::<_, i64>(3)? as usize,
                            content: row.get(4)?,
                            content_hash: row.get(5)?,
                            symbol_name: row.get(6)?,
                            symbol_kind: row.get(7)?,
                            created_at: row.get(8)?,
                        })
                    })
                    .map_err(|e| anyhow::anyhow!("Failed to query code chunks: {}", e))?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunks: {}", e))?;

                Ok(chunks)
            }),
        }
    }

    /// Delete all code chunks for a specific file.
    pub fn delete_chunks_for_file(&self, file_path: &str) -> Result<usize> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => tables.delete_chunks_for_file(file_path),
            _ => self.with_connection_mut(|conn| {
                let affected = conn
                    .execute(
                        "DELETE FROM code_chunks WHERE file_path = ?1",
                        params![file_path],
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to delete code chunks: {}", e))?;

                Ok(affected)
            }),
        }
    }

    /// Count total code chunks stored.
    pub fn count_chunks(&self) -> Result<usize> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => tables.count_chunks(),
            _ => self.with_conn(|conn| {
                let count: i64 = conn
                    .query_row(
                        "SELECT COUNT(*) FROM code_chunks",
                        [],
                        |row: &rusqlite::Row| row.get(0),
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to count chunks: {}", e))?;

                Ok(count as usize)
            }),
        }
    }

    /// Count code chunks for a specific file.
    pub fn count_chunks_for_file(&self, file_path: &str) -> Result<usize> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => tables.count_chunks_for_file(file_path),
            _ => self.with_conn(|conn| {
                let count: i64 = conn
                    .query_row(
                        "SELECT COUNT(*) FROM code_chunks WHERE file_path = ?1",
                        params![file_path],
                        |row: &rusqlite::Row| row.get(0),
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to count chunks for file: {}", e))?;

                Ok(count as usize)
            }),
        }
    }

    /// Get all code chunks from storage.
    ///
    /// For SQLite, queries the code_chunks table.
    /// For V3, uses SideTables trait method.
    pub fn get_all_chunks(&self) -> Result<Vec<CodeChunk>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(tables) => tables.get_all_chunks(),
            _ => self.with_conn(|conn| {
                let mut stmt = conn
                    .prepare_cached(
                        "SELECT id, file_path, byte_start, byte_end, content, content_hash,
                                symbol_name, symbol_kind, created_at
                         FROM code_chunks
                         ORDER BY file_path, byte_start",
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to prepare query: {}", e))?;

                let chunks = stmt
                    .query_map([], |row: &rusqlite::Row| {
                        Ok(CodeChunk {
                            id: Some(row.get(0)?),
                            file_path: row.get(1)?,
                            byte_start: row.get::<_, i64>(2)? as usize,
                            byte_end: row.get::<_, i64>(3)? as usize,
                            content: row.get(4)?,
                            content_hash: row.get(5)?,
                            symbol_name: row.get(6)?,
                            symbol_kind: row.get(7)?,
                            created_at: row.get(8)?,
                        })
                    })
                    .map_err(|e| anyhow::anyhow!("Failed to query code chunks: {}", e))?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunks: {}", e))?;

                Ok(chunks)
            }),
        }
    }

    /// Check if this ChunkStore is using KV backend
    ///
    /// This method always returns false since the KV backend was removed.
    pub fn has_kv_backend(&self) -> bool {
        false
    }

    /// Get chunks by symbol kind (e.g., "fn", "struct").
    pub fn get_chunks_by_kind(&self, symbol_kind: &str) -> Result<Vec<CodeChunk>> {
        match &self.backend {
            ChunkStoreBackend::SideTables(_) => {
                // V3 backend: filter from all chunks
                let all_chunks = self.get_all_chunks()?;
                Ok(all_chunks
                    .into_iter()
                    .filter(|c| c.symbol_kind.as_ref() == Some(&symbol_kind.to_string()))
                    .collect())
            }
            _ => self.with_conn(|conn| {
                let mut stmt = conn
                    .prepare_cached(
                        "SELECT id, file_path, byte_start, byte_end, content, content_hash,
                                    symbol_name, symbol_kind, created_at
                             FROM code_chunks
                             WHERE symbol_kind = ?1
                             ORDER BY file_path, byte_start",
                    )
                    .map_err(|e| anyhow::anyhow!("Failed to prepare query: {}", e))?;

                let chunks = stmt
                    .query_map(params![symbol_kind], |row: &rusqlite::Row| {
                        Ok(CodeChunk {
                            id: Some(row.get(0)?),
                            file_path: row.get(1)?,
                            byte_start: row.get::<_, i64>(2)? as usize,
                            byte_end: row.get::<_, i64>(3)? as usize,
                            content: row.get(4)?,
                            content_hash: row.get(5)?,
                            symbol_name: row.get(6)?,
                            symbol_kind: row.get(7)?,
                            created_at: row.get(8)?,
                        })
                    })
                    .map_err(|e| anyhow::anyhow!("Failed to query code chunks: {}", e))?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect chunks: {}", e))?;

                Ok(chunks)
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Note: These are unit tests for the schema.
    // Integration tests with a real database are in tests/.

    #[test]
    fn test_code_chunk_creation() {
        let chunk = CodeChunk::new(
            "test.rs".to_string(),
            0,
            10,
            "fn main() {}".to_string(),
            Some("main".to_string()),
            Some("fn".to_string()),
        );

        assert_eq!(chunk.file_path, "test.rs");
        assert_eq!(chunk.byte_start, 0);
        assert_eq!(chunk.byte_end, 10);
        assert_eq!(chunk.content, "fn main() {}");
        assert_eq!(chunk.symbol_name, Some("main".to_string()));
        assert_eq!(chunk.symbol_kind, Some("fn".to_string()));
        assert!(!chunk.content_hash.is_empty());
        assert!(chunk.id.is_none());
    }
}