The catalog module handles collection schema management and CRUD operations.

simplevecdb.engine.catalog.CatalogManager

Handles SQLite metadata and FTS operations.

This manager is responsible for: - Creating and managing SQLite tables (metadata and FTS) - Adding, deleting, and removing document metadata - Building filter clauses for metadata queries - FTS5 full-text search indexing

Note: Vector operations are handled by UsearchIndex, not CatalogManager.

Parameters:

Name Type Description Default
conn Connection

SQLite database connection

required
table_name str

Name of the metadata table

required
fts_table_name str

Name of the full-text search table

required
Source code in src/simplevecdb/engine/catalog.py
 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
class CatalogManager:
    """
    Handles SQLite metadata and FTS operations.

    This manager is responsible for:
    - Creating and managing SQLite tables (metadata and FTS)
    - Adding, deleting, and removing document metadata
    - Building filter clauses for metadata queries
    - FTS5 full-text search indexing

    Note: Vector operations are handled by UsearchIndex, not CatalogManager.

    Args:
        conn: SQLite database connection
        table_name: Name of the metadata table
        fts_table_name: Name of the full-text search table
    """

    def __init__(
        self,
        conn: sqlite3.Connection,
        table_name: str,
        fts_table_name: str,
    ):
        # Defense-in-depth: validate table names
        _validate_table_name(table_name)
        _validate_table_name(fts_table_name)

        self.conn = conn
        self._table_name = table_name
        self._fts_table_name = fts_table_name
        self._fts_enabled = False

    def create_tables(self) -> None:
        """Create metadata and FTS tables if they don't exist."""
        self.conn.execute(
            f"""
            CREATE TABLE IF NOT EXISTS {self._table_name} (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                text TEXT NOT NULL,
                metadata TEXT,
                embedding BLOB,
                parent_id INTEGER REFERENCES {self._table_name}(id) ON DELETE SET NULL
            )
            """
        )
        # Create index for parent_id lookups
        self.conn.execute(
            f"""
            CREATE INDEX IF NOT EXISTS idx_{self._table_name}_parent
            ON {self._table_name}(parent_id)
            WHERE parent_id IS NOT NULL
            """
        )
        # Migrate existing tables that lack columns
        self._ensure_embedding_column()
        self._ensure_parent_id_column()
        self._ensure_fts_table()

    def _ensure_embedding_column(self) -> None:
        """Add embedding column if missing (migration for v2.0.0)."""
        try:
            cursor = self.conn.execute(f"PRAGMA table_info({self._table_name})")
            columns = {row[1] for row in cursor.fetchall()}
            if "embedding" not in columns:
                self.conn.execute(
                    f"ALTER TABLE {self._table_name} ADD COLUMN embedding BLOB"
                )
                _logger.info(
                    "Migrated table %s: added embedding column", self._table_name
                )
        except Exception as e:
            _logger.warning("Could not check/add embedding column: %s", e)

    def _ensure_parent_id_column(self) -> None:
        """Add parent_id column if missing (migration for v2.1.0)."""
        try:
            cursor = self.conn.execute(f"PRAGMA table_info({self._table_name})")
            columns = {row[1] for row in cursor.fetchall()}
            if "parent_id" not in columns:
                self.conn.execute(
                    f"ALTER TABLE {self._table_name} ADD COLUMN parent_id INTEGER "
                    f"REFERENCES {self._table_name}(id) ON DELETE SET NULL"
                )
                # Create index for efficient parent lookups
                self.conn.execute(
                    f"""
                    CREATE INDEX IF NOT EXISTS idx_{self._table_name}_parent
                    ON {self._table_name}(parent_id)
                    WHERE parent_id IS NOT NULL
                    """
                )
                _logger.info(
                    "Migrated table %s: added parent_id column", self._table_name
                )
        except Exception as e:
            _logger.warning("Could not check/add parent_id column: %s", e)

    def _ensure_fts_table(self) -> None:
        """Create FTS5 virtual table for full-text search."""
        import sqlite3

        try:
            self.conn.execute(
                f"""
                CREATE VIRTUAL TABLE IF NOT EXISTS {self._fts_table_name}
                USING fts5(text)
                """
            )
            self._fts_enabled = True
        except sqlite3.OperationalError:
            _logger.warning("FTS5 not available - keyword search disabled")
            self._fts_enabled = False

    @property
    def fts_enabled(self) -> bool:
        """Whether FTS5 is available for keyword search."""
        return self._fts_enabled

    def upsert_fts_rows(self, ids: Sequence[int], texts: Sequence[str]) -> None:
        """Update FTS index for given document IDs.

        Args:
            ids: Document IDs to update
            texts: Corresponding text content
        """
        if not self._fts_enabled or not ids:
            return
        placeholders = ",".join("?" for _ in ids)
        self.conn.execute(
            f"DELETE FROM {self._fts_table_name} WHERE rowid IN ({placeholders})",
            tuple(ids),
        )
        rows = list(zip(ids, texts))
        self.conn.executemany(
            f"INSERT INTO {self._fts_table_name}(rowid, text) VALUES (?, ?)", rows
        )

    def delete_fts_rows(self, ids: Sequence[int]) -> None:
        """Remove documents from FTS index.

        Args:
            ids: Document IDs to remove
        """
        if not self._fts_enabled or not ids:
            return
        placeholders = ",".join("?" for _ in ids)
        self.conn.execute(
            f"DELETE FROM {self._fts_table_name} WHERE rowid IN ({placeholders})",
            tuple(ids),
        )

    @retry_on_lock(max_retries=5, base_delay=0.1)
    def add_documents(
        self,
        texts: Sequence[str],
        metadatas: Sequence[dict],
        ids: Sequence[int | None] | None = None,
        embeddings: Sequence[Sequence[float]] | None = None,
        parent_ids: Sequence[int | None] | None = None,
    ) -> list[int]:
        """
        Insert or update document metadata.

        Args:
            texts: Document text content
            metadatas: Metadata dicts for each document
            ids: Optional document IDs for upsert behavior
            embeddings: Optional embedding vectors to store
            parent_ids: Optional parent document IDs for hierarchical relationships

        Returns:
            List of document IDs (rowids)
        """
        if not texts:
            return []

        _logger.debug(
            "Adding %d documents to metadata table",
            len(texts),
            extra={"table": self._table_name},
        )

        import numpy as np

        ids_list = list(ids) if ids else [None] * len(texts)
        parent_ids_list = list(parent_ids) if parent_ids else [None] * len(texts)

        # Convert embeddings to bytes if provided
        embedding_blobs: list[bytes | None] = []
        if embeddings is not None:
            for emb in embeddings:
                arr = np.asarray(emb, dtype=np.float32)
                embedding_blobs.append(arr.tobytes())
        else:
            embedding_blobs = [None] * len(texts)

        rows = [
            (uid, txt, json.dumps(meta), emb_blob, pid)
            for uid, txt, meta, emb_blob, pid in zip(
                ids_list, texts, metadatas, embedding_blobs, parent_ids_list
            )
        ]

        with self.conn:
            self.conn.executemany(
                f"""
                INSERT INTO {self._table_name}(id, text, metadata, embedding, parent_id)
                VALUES (?, ?, ?, ?, ?)
                ON CONFLICT(id) DO UPDATE SET
                    text=excluded.text,
                    metadata=excluded.metadata,
                    embedding=excluded.embedding,
                    parent_id=excluded.parent_id
                """,
                rows,
            )

            # Get the actual rowids (handles both insert and upsert)
            real_ids = [
                r[0]
                for r in self.conn.execute(
                    f"SELECT id FROM {self._table_name} ORDER BY id DESC LIMIT ?",
                    (len(texts),),
                )
            ]
            real_ids.reverse()

            # Update FTS index
            self.upsert_fts_rows(real_ids, list(texts))

        _logger.debug("Added %d documents, ids=%s", len(real_ids), real_ids[:5])
        return real_ids

    @retry_on_lock(max_retries=5, base_delay=0.1)
    def delete_by_ids(self, ids: Iterable[int]) -> list[int]:
        """
        Delete documents by their IDs.

        Args:
            ids: Document IDs to delete

        Returns:
            List of IDs that were actually deleted
        """
        ids = list(ids)
        if not ids:
            return []

        _logger.debug("Deleting %d documents", len(ids))

        placeholders = ",".join("?" for _ in ids)
        params = tuple(ids)

        with self.conn:
            # Check which IDs actually exist
            existing = self.conn.execute(
                f"SELECT id FROM {self._table_name} WHERE id IN ({placeholders})",
                params,
            ).fetchall()
            existing_ids = [r[0] for r in existing]

            if existing_ids:
                placeholders = ",".join("?" for _ in existing_ids)
                self.conn.execute(
                    f"DELETE FROM {self._table_name} WHERE id IN ({placeholders})",
                    tuple(existing_ids),
                )
                self.delete_fts_rows(existing_ids)

        _logger.debug("Deleted %d documents", len(existing_ids))
        return existing_ids

    def get_documents_by_ids(
        self, ids: Sequence[int]
    ) -> dict[int, tuple[str, dict[str, Any]]]:
        """
        Fetch document text and metadata by IDs.

        Args:
            ids: Document IDs to fetch

        Returns:
            Dict mapping id -> (text, metadata)
        """
        if not ids:
            return {}

        placeholders = ",".join("?" for _ in ids)
        rows = self.conn.execute(
            f"SELECT id, text, metadata FROM {self._table_name} WHERE id IN ({placeholders})",
            tuple(ids),
        ).fetchall()

        result = {}
        for row_id, text, meta_json in rows:
            meta = json.loads(meta_json) if meta_json else {}
            result[row_id] = (text, meta)
        return result

    def get_embeddings_by_ids(self, ids: Sequence[int]) -> dict[int, Any]:
        """
        Fetch embeddings by document IDs.

        Args:
            ids: Document IDs to fetch

        Returns:
            Dict mapping id -> numpy array (or None if no embedding stored)
        """
        import numpy as np

        if not ids:
            return {}

        placeholders = ",".join("?" for _ in ids)
        rows = self.conn.execute(
            f"SELECT id, embedding FROM {self._table_name} WHERE id IN ({placeholders})",
            tuple(ids),
        ).fetchall()

        result: dict[int, np.ndarray | None] = {}
        for row_id, emb_blob in rows:
            if emb_blob is not None:
                result[row_id] = np.frombuffer(emb_blob, dtype=np.float32)
            else:
                result[row_id] = None
        return result

    def find_ids_by_texts(self, texts: Sequence[str]) -> list[int]:
        """Find document IDs matching exact text content."""
        if not texts:
            return []
        placeholders = ",".join("?" for _ in texts)
        rows = self.conn.execute(
            f"SELECT id FROM {self._table_name} WHERE text IN ({placeholders})",
            tuple(texts),
        ).fetchall()
        return [r[0] for r in rows]

    def find_ids_by_filter(
        self,
        filter_dict: dict[str, Any],
        filter_builder: Callable[[dict[str, Any], str], tuple[str, list[Any]]],
    ) -> list[int]:
        """Find document IDs matching metadata filter."""
        if not filter_dict:
            return []

        filter_clause, filter_params = filter_builder(filter_dict, "metadata")
        # Remove leading "AND " from clause
        filter_clause = filter_clause.replace("AND ", "", 1)
        where_clause = f"WHERE {filter_clause}" if filter_clause else ""

        rows = self.conn.execute(
            f"SELECT id FROM {self._table_name} {where_clause}",
            tuple(filter_params),
        ).fetchall()
        return [r[0] for r in rows]

    def keyword_search(
        self,
        query: str,
        k: int,
        filter_dict: dict[str, Any] | None = None,
        filter_builder: Callable | None = None,
    ) -> list[tuple[int, float]]:
        """
        Perform BM25 keyword search using FTS5.

        Args:
            query: Search query (FTS5 syntax supported)
            k: Maximum results
            filter_dict: Optional metadata filter
            filter_builder: Function to build filter clause

        Returns:
            List of (id, bm25_score) tuples, sorted by relevance
        """
        if not self._fts_enabled:
            raise RuntimeError("FTS5 not available - cannot perform keyword search")
        if not query.strip():
            return []

        filter_clause = ""
        filter_params: list[Any] = []
        if filter_dict and filter_builder:
            filter_clause, filter_params = filter_builder(filter_dict, "ti.metadata")

        sql = f"""
            SELECT ti.id, bm25({self._fts_table_name}) as score
            FROM {self._fts_table_name} f
            JOIN {self._table_name} ti ON ti.id = f.rowid
            WHERE {self._fts_table_name} MATCH ?
            {filter_clause}
            ORDER BY score ASC
            LIMIT ?
        """
        params = (query,) + tuple(filter_params) + (k,)
        rows = self.conn.execute(sql, params).fetchall()
        return [(int(row[0]), float(row[1])) for row in rows]

    def build_filter_clause(
        self, filter_dict: dict[str, Any] | None, metadata_column: str = "metadata"
    ) -> tuple[str, list[Any]]:
        """
        Build SQL WHERE clause from metadata filter dictionary.

        Args:
            filter_dict: Metadata key-value pairs to filter by
            metadata_column: Name of JSON metadata column

        Returns:
            Tuple of (where_clause, parameters) for SQL query

        Raises:
            ValueError: If filter keys are not strings or values are unsupported types
        """
        if not filter_dict:
            return "", []

        # Validate filter structure before processing
        validate_filter(filter_dict)

        clauses = []
        params: list[Any] = []
        for key, value in filter_dict.items():
            json_path = f"$.{key}"
            if isinstance(value, (int, float)):
                clauses.append(f"json_extract({metadata_column}, ?) = ?")
                params.extend([json_path, value])
            elif isinstance(value, str):
                # Escape LIKE special characters to prevent injection
                escaped_value = (
                    value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
                )
                clauses.append(f"json_extract({metadata_column}, ?) LIKE ? ESCAPE '\\'")
                params.extend([json_path, f"%{escaped_value}%"])
            elif isinstance(value, list):
                placeholders = ",".join("?" for _ in value)
                clauses.append(
                    f"json_extract({metadata_column}, ?) IN ({placeholders})"
                )
                params.extend([json_path] + value)
            else:
                raise ValueError(f"Unsupported filter value type for {key}")
        where = " AND ".join(clauses)
        return f"AND ({where})" if where else "", params

    def count(self) -> int:
        """Return total number of documents."""
        row = self.conn.execute(f"SELECT COUNT(*) FROM {self._table_name}").fetchone()
        return row[0] if row else 0

    def get_all_docs_with_text(
        self,
        filter_dict: dict[str, Any] | None = None,
        filter_builder: Callable[[dict[str, Any], str], tuple[str, list[Any]]]
        | None = None,
    ) -> list[tuple[int, str, dict[str, Any]]]:
        """
        Get all documents with their text content.

        Args:
            filter_dict: Optional metadata filter
            filter_builder: Function to build filter clause

        Returns:
            List of (doc_id, text, metadata) tuples
        """
        filter_clause = ""
        filter_params: list[Any] = []
        if filter_dict and filter_builder:
            filter_clause, filter_params = filter_builder(filter_dict, "metadata")

        sql = f"""
            SELECT id, text, metadata FROM {self._table_name}
            WHERE 1=1 {filter_clause}
            ORDER BY id
        """
        rows = self.conn.execute(sql, tuple(filter_params)).fetchall()
        result = []
        for row_id, text, meta_json in rows:
            meta = json.loads(meta_json) if meta_json else {}
            result.append((int(row_id), text, meta))
        return result

    def update_metadata_batch(self, updates: list[tuple[int, dict[str, Any]]]) -> int:
        """
        Update metadata for multiple documents in a single transaction.

        Merges new metadata with existing metadata (shallow merge).

        Args:
            updates: List of (doc_id, metadata_updates) tuples

        Returns:
            Number of documents updated
        """
        if not updates:
            return 0

        updated = 0
        # Batch into chunks of 500 for performance
        for i in range(0, len(updates), 500):
            batch = updates[i : i + 500]
            ids = [u[0] for u in batch]

            # Fetch all existing metadata in one query
            placeholders = ",".join(["?"] * len(ids))
            rows = self.conn.execute(
                f"SELECT id, metadata FROM {self._table_name} WHERE id IN ({placeholders})",
                ids,
            ).fetchall()

            current_meta_map = {r[0]: (json.loads(r[1]) if r[1] else {}) for r in rows}

            # Prepare updates
            update_data = []
            for doc_id, meta_updates in batch:
                if doc_id in current_meta_map:
                    meta = current_meta_map[doc_id]
                    meta.update(meta_updates)
                    update_data.append((json.dumps(meta), doc_id))
                    updated += 1

            if update_data:
                self.conn.executemany(
                    f"UPDATE {self._table_name} SET metadata = ? WHERE id = ?",
                    update_data,
                )

        self.conn.commit()
        return updated

    def check_legacy_sqlite_vec(self, vec_table_name: str) -> bool:
        """
        Check if legacy sqlite-vec tables exist (for migration).

        Args:
            vec_table_name: Expected name of the old vec0 virtual table

        Returns:
            True if legacy sqlite-vec data exists
        """
        try:
            row = self.conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
                (vec_table_name,),
            ).fetchone()
            return row is not None
        except Exception:
            return False

    def get_legacy_vectors(self, vec_table_name: str) -> list[tuple[int, bytes]]:
        """
        Extract vectors from legacy sqlite-vec table for migration.

        Args:
            vec_table_name: Name of the old vec0 virtual table

        Returns:
            List of (rowid, embedding_blob) tuples
        """
        try:
            rows = self.conn.execute(
                f"SELECT rowid, embedding FROM {vec_table_name}"
            ).fetchall()
            return [(int(r[0]), r[1]) for r in rows]
        except Exception as e:
            _logger.warning("Failed to read legacy vectors: %s", e)
            return []

    def drop_legacy_vec_table(self, vec_table_name: str) -> None:
        """Drop legacy sqlite-vec table after migration."""
        try:
            self.conn.execute(f"DROP TABLE IF EXISTS {vec_table_name}")
            self.conn.commit()
            _logger.info("Dropped legacy sqlite-vec table: %s", vec_table_name)
        except Exception as e:
            _logger.warning("Failed to drop legacy table %s: %s", vec_table_name, e)

    # ------------------------------------------------------------------ #
    # Hierarchical Relationships
    # ------------------------------------------------------------------ #

    def get_children(self, parent_id: int) -> list[tuple[int, str, dict[str, Any]]]:
        """
        Get all direct children of a document.

        Args:
            parent_id: ID of the parent document

        Returns:
            List of (id, text, metadata) tuples for child documents
        """
        rows = self.conn.execute(
            f"SELECT id, text, metadata FROM {self._table_name} WHERE parent_id = ?",
            (parent_id,),
        ).fetchall()

        return [(int(r[0]), r[1], json.loads(r[2]) if r[2] else {}) for r in rows]

    def get_parent(self, doc_id: int) -> tuple[int, str, dict[str, Any]] | None:
        """
        Get the parent document of a given document.

        Args:
            doc_id: ID of the child document

        Returns:
            Tuple of (id, text, metadata) for parent, or None if no parent
        """
        # First get the parent_id
        row = self.conn.execute(
            f"SELECT parent_id FROM {self._table_name} WHERE id = ?",
            (doc_id,),
        ).fetchone()

        if not row or row[0] is None:
            return None

        parent_id = row[0]

        # Then fetch the parent document
        parent_row = self.conn.execute(
            f"SELECT id, text, metadata FROM {self._table_name} WHERE id = ?",
            (parent_id,),
        ).fetchone()

        if not parent_row:
            return None

        return (
            int(parent_row[0]),
            parent_row[1],
            json.loads(parent_row[2]) if parent_row[2] else {},
        )

    def get_descendants(
        self, root_id: int, max_depth: int | None = None
    ) -> list[tuple[int, str, dict[str, Any], int]]:
        """
        Get all descendants of a document (recursive).

        Uses a recursive CTE for efficient traversal.

        Args:
            root_id: ID of the root document
            max_depth: Maximum depth to traverse (None for unlimited)

        Returns:
            List of (id, text, metadata, depth) tuples
        """
        # Validate max_depth to prevent SQL injection (it's interpolated into query)
        if max_depth is not None:
            max_depth = int(max_depth)
        depth_clause = f"AND depth < {max_depth}" if max_depth else ""

        sql = f"""
            WITH RECURSIVE descendants(id, text, metadata, depth) AS (
                SELECT id, text, metadata, 1 as depth
                FROM {self._table_name}
                WHERE parent_id = ?

                UNION ALL

                SELECT t.id, t.text, t.metadata, d.depth + 1
                FROM {self._table_name} t
                JOIN descendants d ON t.parent_id = d.id
                WHERE 1=1 {depth_clause}
            )
            SELECT id, text, metadata, depth FROM descendants
            ORDER BY depth, id
        """

        rows = self.conn.execute(sql, (root_id,)).fetchall()

        return [
            (int(r[0]), r[1], json.loads(r[2]) if r[2] else {}, int(r[3])) for r in rows
        ]

    def get_ancestors(
        self, doc_id: int, max_depth: int | None = None
    ) -> list[tuple[int, str, dict[str, Any], int]]:
        """
        Get all ancestors of a document (path to root).

        Args:
            doc_id: ID of the document
            max_depth: Maximum depth to traverse (None for unlimited)

        Returns:
            List of (id, text, metadata, depth) tuples, from immediate parent to root
        """
        # Validate max_depth to prevent SQL injection (it's interpolated into query)
        if max_depth is not None:
            max_depth = int(max_depth)
        depth_clause = f"AND depth < {max_depth}" if max_depth else ""

        sql = f"""
            WITH RECURSIVE ancestors(id, text, metadata, parent_id, depth) AS (
                SELECT id, text, metadata, parent_id, 1 as depth
                FROM {self._table_name}
                WHERE id = (SELECT parent_id FROM {self._table_name} WHERE id = ?)

                UNION ALL

                SELECT t.id, t.text, t.metadata, t.parent_id, a.depth + 1
                FROM {self._table_name} t
                JOIN ancestors a ON t.id = a.parent_id
                WHERE a.parent_id IS NOT NULL {depth_clause}
            )
            SELECT id, text, metadata, depth FROM ancestors
            ORDER BY depth
        """

        rows = self.conn.execute(sql, (doc_id,)).fetchall()

        return [
            (int(r[0]), r[1], json.loads(r[2]) if r[2] else {}, int(r[3])) for r in rows
        ]

    def set_parent(self, doc_id: int, parent_id: int | None) -> bool:
        """
        Set or update the parent of a document.

        Args:
            doc_id: ID of the document to update
            parent_id: New parent ID (None to remove parent)

        Returns:
            True if document was updated, False if not found

        Raises:
            ValueError: If setting parent would create a cycle
        """
        # Check for cycles: parent_id cannot be doc_id or any of its descendants
        if parent_id is not None:
            if parent_id == doc_id:
                raise ValueError("A document cannot be its own parent")
            descendants = self.get_descendants(doc_id)
            descendant_ids = {d[0] for d in descendants}
            if parent_id in descendant_ids:
                raise ValueError(
                    f"Cannot set parent: document {parent_id} is a descendant of {doc_id}"
                )

        with self.conn:
            cursor = self.conn.execute(
                f"UPDATE {self._table_name} SET parent_id = ? WHERE id = ?",
                (parent_id, doc_id),
            )
            return cursor.rowcount > 0

    # ------------------------------------------------------------------ #
    # Cluster State Persistence
    # ------------------------------------------------------------------ #

    def _ensure_cluster_table(self) -> None:
        """Create cluster state table if it doesn't exist."""
        cluster_table = f"{self._table_name}_clusters"
        self.conn.execute(
            f"""
            CREATE TABLE IF NOT EXISTS {cluster_table} (
                name TEXT PRIMARY KEY,
                algorithm TEXT NOT NULL,
                n_clusters INTEGER NOT NULL,
                centroids BLOB,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                metadata TEXT
            )
            """
        )
        self.conn.commit()

    def save_cluster_state(
        self,
        name: str,
        algorithm: str,
        n_clusters: int,
        centroids: bytes | None,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """
        Save cluster state for later reuse.

        Args:
            name: Unique name for this cluster configuration
            algorithm: Algorithm used (kmeans, minibatch_kmeans, hdbscan)
            n_clusters: Number of clusters
            centroids: Serialized centroid array (numpy bytes)
            metadata: Additional metadata (inertia, silhouette, etc.)
        """
        self._ensure_cluster_table()
        cluster_table = f"{self._table_name}_clusters"

        meta_json = json.dumps(metadata) if metadata else None

        self.conn.execute(
            f"""
            INSERT OR REPLACE INTO {cluster_table}
            (name, algorithm, n_clusters, centroids, metadata, created_at)
            VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
            """,
            (name, algorithm, n_clusters, centroids, meta_json),
        )
        self.conn.commit()

    def load_cluster_state(
        self, name: str
    ) -> tuple[str, int, bytes | None, dict[str, Any]] | None:
        """
        Load saved cluster state.

        Args:
            name: Name of the cluster configuration

        Returns:
            Tuple of (algorithm, n_clusters, centroids_bytes, metadata) or None
        """
        self._ensure_cluster_table()
        cluster_table = f"{self._table_name}_clusters"

        row = self.conn.execute(
            f"SELECT algorithm, n_clusters, centroids, metadata FROM {cluster_table} WHERE name = ?",
            (name,),
        ).fetchone()

        if not row:
            return None

        algorithm, n_clusters, centroids, meta_json = row
        metadata = json.loads(meta_json) if meta_json else {}
        return (algorithm, n_clusters, centroids, metadata)

    def list_cluster_states(self) -> list[dict[str, Any]]:
        """List all saved cluster configurations."""
        self._ensure_cluster_table()
        cluster_table = f"{self._table_name}_clusters"

        rows = self.conn.execute(
            f"SELECT name, algorithm, n_clusters, created_at, metadata FROM {cluster_table}"
        ).fetchall()

        result = []
        for name, algorithm, n_clusters, created_at, meta_json in rows:
            result.append(
                {
                    "name": name,
                    "algorithm": algorithm,
                    "n_clusters": n_clusters,
                    "created_at": created_at,
                    "metadata": json.loads(meta_json) if meta_json else {},
                }
            )
        return result

    def delete_cluster_state(self, name: str) -> bool:
        """Delete a saved cluster configuration."""
        self._ensure_cluster_table()
        cluster_table = f"{self._table_name}_clusters"

        cursor = self.conn.execute(
            f"DELETE FROM {cluster_table} WHERE name = ?", (name,)
        )
        self.conn.commit()
        return cursor.rowcount > 0

fts_enabled property

Whether FTS5 is available for keyword search.

create_tables()

Create metadata and FTS tables if they don't exist.

Source code in src/simplevecdb/engine/catalog.py
def create_tables(self) -> None:
    """Create metadata and FTS tables if they don't exist."""
    self.conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS {self._table_name} (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            text TEXT NOT NULL,
            metadata TEXT,
            embedding BLOB,
            parent_id INTEGER REFERENCES {self._table_name}(id) ON DELETE SET NULL
        )
        """
    )
    # Create index for parent_id lookups
    self.conn.execute(
        f"""
        CREATE INDEX IF NOT EXISTS idx_{self._table_name}_parent
        ON {self._table_name}(parent_id)
        WHERE parent_id IS NOT NULL
        """
    )
    # Migrate existing tables that lack columns
    self._ensure_embedding_column()
    self._ensure_parent_id_column()
    self._ensure_fts_table()

upsert_fts_rows(ids, texts)

Update FTS index for given document IDs.

Parameters:

Name Type Description Default
ids Sequence[int]

Document IDs to update

required
texts Sequence[str]

Corresponding text content

required
Source code in src/simplevecdb/engine/catalog.py
def upsert_fts_rows(self, ids: Sequence[int], texts: Sequence[str]) -> None:
    """Update FTS index for given document IDs.

    Args:
        ids: Document IDs to update
        texts: Corresponding text content
    """
    if not self._fts_enabled or not ids:
        return
    placeholders = ",".join("?" for _ in ids)
    self.conn.execute(
        f"DELETE FROM {self._fts_table_name} WHERE rowid IN ({placeholders})",
        tuple(ids),
    )
    rows = list(zip(ids, texts))
    self.conn.executemany(
        f"INSERT INTO {self._fts_table_name}(rowid, text) VALUES (?, ?)", rows
    )

delete_fts_rows(ids)

Remove documents from FTS index.

Parameters:

Name Type Description Default
ids Sequence[int]

Document IDs to remove

required
Source code in src/simplevecdb/engine/catalog.py
def delete_fts_rows(self, ids: Sequence[int]) -> None:
    """Remove documents from FTS index.

    Args:
        ids: Document IDs to remove
    """
    if not self._fts_enabled or not ids:
        return
    placeholders = ",".join("?" for _ in ids)
    self.conn.execute(
        f"DELETE FROM {self._fts_table_name} WHERE rowid IN ({placeholders})",
        tuple(ids),
    )

add_documents(texts, metadatas, ids=None, embeddings=None, parent_ids=None)

Insert or update document metadata.

Parameters:

Name Type Description Default
texts Sequence[str]

Document text content

required
metadatas Sequence[dict]

Metadata dicts for each document

required
ids Sequence[int | None] | None

Optional document IDs for upsert behavior

None
embeddings Sequence[Sequence[float]] | None

Optional embedding vectors to store

None
parent_ids Sequence[int | None] | None

Optional parent document IDs for hierarchical relationships

None

Returns:

Type Description
list[int]

List of document IDs (rowids)

Source code in src/simplevecdb/engine/catalog.py
@retry_on_lock(max_retries=5, base_delay=0.1)
def add_documents(
    self,
    texts: Sequence[str],
    metadatas: Sequence[dict],
    ids: Sequence[int | None] | None = None,
    embeddings: Sequence[Sequence[float]] | None = None,
    parent_ids: Sequence[int | None] | None = None,
) -> list[int]:
    """
    Insert or update document metadata.

    Args:
        texts: Document text content
        metadatas: Metadata dicts for each document
        ids: Optional document IDs for upsert behavior
        embeddings: Optional embedding vectors to store
        parent_ids: Optional parent document IDs for hierarchical relationships

    Returns:
        List of document IDs (rowids)
    """
    if not texts:
        return []

    _logger.debug(
        "Adding %d documents to metadata table",
        len(texts),
        extra={"table": self._table_name},
    )

    import numpy as np

    ids_list = list(ids) if ids else [None] * len(texts)
    parent_ids_list = list(parent_ids) if parent_ids else [None] * len(texts)

    # Convert embeddings to bytes if provided
    embedding_blobs: list[bytes | None] = []
    if embeddings is not None:
        for emb in embeddings:
            arr = np.asarray(emb, dtype=np.float32)
            embedding_blobs.append(arr.tobytes())
    else:
        embedding_blobs = [None] * len(texts)

    rows = [
        (uid, txt, json.dumps(meta), emb_blob, pid)
        for uid, txt, meta, emb_blob, pid in zip(
            ids_list, texts, metadatas, embedding_blobs, parent_ids_list
        )
    ]

    with self.conn:
        self.conn.executemany(
            f"""
            INSERT INTO {self._table_name}(id, text, metadata, embedding, parent_id)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(id) DO UPDATE SET
                text=excluded.text,
                metadata=excluded.metadata,
                embedding=excluded.embedding,
                parent_id=excluded.parent_id
            """,
            rows,
        )

        # Get the actual rowids (handles both insert and upsert)
        real_ids = [
            r[0]
            for r in self.conn.execute(
                f"SELECT id FROM {self._table_name} ORDER BY id DESC LIMIT ?",
                (len(texts),),
            )
        ]
        real_ids.reverse()

        # Update FTS index
        self.upsert_fts_rows(real_ids, list(texts))

    _logger.debug("Added %d documents, ids=%s", len(real_ids), real_ids[:5])
    return real_ids

delete_by_ids(ids)

Delete documents by their IDs.

Parameters:

Name Type Description Default
ids Iterable[int]

Document IDs to delete

required

Returns:

Type Description
list[int]

List of IDs that were actually deleted

Source code in src/simplevecdb/engine/catalog.py
@retry_on_lock(max_retries=5, base_delay=0.1)
def delete_by_ids(self, ids: Iterable[int]) -> list[int]:
    """
    Delete documents by their IDs.

    Args:
        ids: Document IDs to delete

    Returns:
        List of IDs that were actually deleted
    """
    ids = list(ids)
    if not ids:
        return []

    _logger.debug("Deleting %d documents", len(ids))

    placeholders = ",".join("?" for _ in ids)
    params = tuple(ids)

    with self.conn:
        # Check which IDs actually exist
        existing = self.conn.execute(
            f"SELECT id FROM {self._table_name} WHERE id IN ({placeholders})",
            params,
        ).fetchall()
        existing_ids = [r[0] for r in existing]

        if existing_ids:
            placeholders = ",".join("?" for _ in existing_ids)
            self.conn.execute(
                f"DELETE FROM {self._table_name} WHERE id IN ({placeholders})",
                tuple(existing_ids),
            )
            self.delete_fts_rows(existing_ids)

    _logger.debug("Deleted %d documents", len(existing_ids))
    return existing_ids

get_documents_by_ids(ids)

Fetch document text and metadata by IDs.

Parameters:

Name Type Description Default
ids Sequence[int]

Document IDs to fetch

required

Returns:

Type Description
dict[int, tuple[str, dict[str, Any]]]

Dict mapping id -> (text, metadata)

Source code in src/simplevecdb/engine/catalog.py
def get_documents_by_ids(
    self, ids: Sequence[int]
) -> dict[int, tuple[str, dict[str, Any]]]:
    """
    Fetch document text and metadata by IDs.

    Args:
        ids: Document IDs to fetch

    Returns:
        Dict mapping id -> (text, metadata)
    """
    if not ids:
        return {}

    placeholders = ",".join("?" for _ in ids)
    rows = self.conn.execute(
        f"SELECT id, text, metadata FROM {self._table_name} WHERE id IN ({placeholders})",
        tuple(ids),
    ).fetchall()

    result = {}
    for row_id, text, meta_json in rows:
        meta = json.loads(meta_json) if meta_json else {}
        result[row_id] = (text, meta)
    return result

get_embeddings_by_ids(ids)

Fetch embeddings by document IDs.

Parameters:

Name Type Description Default
ids Sequence[int]

Document IDs to fetch

required

Returns:

Type Description
dict[int, Any]

Dict mapping id -> numpy array (or None if no embedding stored)

Source code in src/simplevecdb/engine/catalog.py
def get_embeddings_by_ids(self, ids: Sequence[int]) -> dict[int, Any]:
    """
    Fetch embeddings by document IDs.

    Args:
        ids: Document IDs to fetch

    Returns:
        Dict mapping id -> numpy array (or None if no embedding stored)
    """
    import numpy as np

    if not ids:
        return {}

    placeholders = ",".join("?" for _ in ids)
    rows = self.conn.execute(
        f"SELECT id, embedding FROM {self._table_name} WHERE id IN ({placeholders})",
        tuple(ids),
    ).fetchall()

    result: dict[int, np.ndarray | None] = {}
    for row_id, emb_blob in rows:
        if emb_blob is not None:
            result[row_id] = np.frombuffer(emb_blob, dtype=np.float32)
        else:
            result[row_id] = None
    return result

find_ids_by_texts(texts)

Find document IDs matching exact text content.

Source code in src/simplevecdb/engine/catalog.py
def find_ids_by_texts(self, texts: Sequence[str]) -> list[int]:
    """Find document IDs matching exact text content."""
    if not texts:
        return []
    placeholders = ",".join("?" for _ in texts)
    rows = self.conn.execute(
        f"SELECT id FROM {self._table_name} WHERE text IN ({placeholders})",
        tuple(texts),
    ).fetchall()
    return [r[0] for r in rows]

find_ids_by_filter(filter_dict, filter_builder)

Find document IDs matching metadata filter.

Source code in src/simplevecdb/engine/catalog.py
def find_ids_by_filter(
    self,
    filter_dict: dict[str, Any],
    filter_builder: Callable[[dict[str, Any], str], tuple[str, list[Any]]],
) -> list[int]:
    """Find document IDs matching metadata filter."""
    if not filter_dict:
        return []

    filter_clause, filter_params = filter_builder(filter_dict, "metadata")
    # Remove leading "AND " from clause
    filter_clause = filter_clause.replace("AND ", "", 1)
    where_clause = f"WHERE {filter_clause}" if filter_clause else ""

    rows = self.conn.execute(
        f"SELECT id FROM {self._table_name} {where_clause}",
        tuple(filter_params),
    ).fetchall()
    return [r[0] for r in rows]

Perform BM25 keyword search using FTS5.

Parameters:

Name Type Description Default
query str

Search query (FTS5 syntax supported)

required
k int

Maximum results

required
filter_dict dict[str, Any] | None

Optional metadata filter

None
filter_builder Callable | None

Function to build filter clause

None

Returns:

Type Description
list[tuple[int, float]]

List of (id, bm25_score) tuples, sorted by relevance

Source code in src/simplevecdb/engine/catalog.py
def keyword_search(
    self,
    query: str,
    k: int,
    filter_dict: dict[str, Any] | None = None,
    filter_builder: Callable | None = None,
) -> list[tuple[int, float]]:
    """
    Perform BM25 keyword search using FTS5.

    Args:
        query: Search query (FTS5 syntax supported)
        k: Maximum results
        filter_dict: Optional metadata filter
        filter_builder: Function to build filter clause

    Returns:
        List of (id, bm25_score) tuples, sorted by relevance
    """
    if not self._fts_enabled:
        raise RuntimeError("FTS5 not available - cannot perform keyword search")
    if not query.strip():
        return []

    filter_clause = ""
    filter_params: list[Any] = []
    if filter_dict and filter_builder:
        filter_clause, filter_params = filter_builder(filter_dict, "ti.metadata")

    sql = f"""
        SELECT ti.id, bm25({self._fts_table_name}) as score
        FROM {self._fts_table_name} f
        JOIN {self._table_name} ti ON ti.id = f.rowid
        WHERE {self._fts_table_name} MATCH ?
        {filter_clause}
        ORDER BY score ASC
        LIMIT ?
    """
    params = (query,) + tuple(filter_params) + (k,)
    rows = self.conn.execute(sql, params).fetchall()
    return [(int(row[0]), float(row[1])) for row in rows]

build_filter_clause(filter_dict, metadata_column='metadata')

Build SQL WHERE clause from metadata filter dictionary.

Parameters:

Name Type Description Default
filter_dict dict[str, Any] | None

Metadata key-value pairs to filter by

required
metadata_column str

Name of JSON metadata column

'metadata'

Returns:

Type Description
tuple[str, list[Any]]

Tuple of (where_clause, parameters) for SQL query

Raises:

Type Description
ValueError

If filter keys are not strings or values are unsupported types

Source code in src/simplevecdb/engine/catalog.py
def build_filter_clause(
    self, filter_dict: dict[str, Any] | None, metadata_column: str = "metadata"
) -> tuple[str, list[Any]]:
    """
    Build SQL WHERE clause from metadata filter dictionary.

    Args:
        filter_dict: Metadata key-value pairs to filter by
        metadata_column: Name of JSON metadata column

    Returns:
        Tuple of (where_clause, parameters) for SQL query

    Raises:
        ValueError: If filter keys are not strings or values are unsupported types
    """
    if not filter_dict:
        return "", []

    # Validate filter structure before processing
    validate_filter(filter_dict)

    clauses = []
    params: list[Any] = []
    for key, value in filter_dict.items():
        json_path = f"$.{key}"
        if isinstance(value, (int, float)):
            clauses.append(f"json_extract({metadata_column}, ?) = ?")
            params.extend([json_path, value])
        elif isinstance(value, str):
            # Escape LIKE special characters to prevent injection
            escaped_value = (
                value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
            )
            clauses.append(f"json_extract({metadata_column}, ?) LIKE ? ESCAPE '\\'")
            params.extend([json_path, f"%{escaped_value}%"])
        elif isinstance(value, list):
            placeholders = ",".join("?" for _ in value)
            clauses.append(
                f"json_extract({metadata_column}, ?) IN ({placeholders})"
            )
            params.extend([json_path] + value)
        else:
            raise ValueError(f"Unsupported filter value type for {key}")
    where = " AND ".join(clauses)
    return f"AND ({where})" if where else "", params

count()

Return total number of documents.

Source code in src/simplevecdb/engine/catalog.py
def count(self) -> int:
    """Return total number of documents."""
    row = self.conn.execute(f"SELECT COUNT(*) FROM {self._table_name}").fetchone()
    return row[0] if row else 0

get_all_docs_with_text(filter_dict=None, filter_builder=None)

Get all documents with their text content.

Parameters:

Name Type Description Default
filter_dict dict[str, Any] | None

Optional metadata filter

None
filter_builder Callable[[dict[str, Any], str], tuple[str, list[Any]]] | None

Function to build filter clause

None

Returns:

Type Description
list[tuple[int, str, dict[str, Any]]]

List of (doc_id, text, metadata) tuples

Source code in src/simplevecdb/engine/catalog.py
def get_all_docs_with_text(
    self,
    filter_dict: dict[str, Any] | None = None,
    filter_builder: Callable[[dict[str, Any], str], tuple[str, list[Any]]]
    | None = None,
) -> list[tuple[int, str, dict[str, Any]]]:
    """
    Get all documents with their text content.

    Args:
        filter_dict: Optional metadata filter
        filter_builder: Function to build filter clause

    Returns:
        List of (doc_id, text, metadata) tuples
    """
    filter_clause = ""
    filter_params: list[Any] = []
    if filter_dict and filter_builder:
        filter_clause, filter_params = filter_builder(filter_dict, "metadata")

    sql = f"""
        SELECT id, text, metadata FROM {self._table_name}
        WHERE 1=1 {filter_clause}
        ORDER BY id
    """
    rows = self.conn.execute(sql, tuple(filter_params)).fetchall()
    result = []
    for row_id, text, meta_json in rows:
        meta = json.loads(meta_json) if meta_json else {}
        result.append((int(row_id), text, meta))
    return result

update_metadata_batch(updates)

Update metadata for multiple documents in a single transaction.

Merges new metadata with existing metadata (shallow merge).

Parameters:

Name Type Description Default
updates list[tuple[int, dict[str, Any]]]

List of (doc_id, metadata_updates) tuples

required

Returns:

Type Description
int

Number of documents updated

Source code in src/simplevecdb/engine/catalog.py
def update_metadata_batch(self, updates: list[tuple[int, dict[str, Any]]]) -> int:
    """
    Update metadata for multiple documents in a single transaction.

    Merges new metadata with existing metadata (shallow merge).

    Args:
        updates: List of (doc_id, metadata_updates) tuples

    Returns:
        Number of documents updated
    """
    if not updates:
        return 0

    updated = 0
    # Batch into chunks of 500 for performance
    for i in range(0, len(updates), 500):
        batch = updates[i : i + 500]
        ids = [u[0] for u in batch]

        # Fetch all existing metadata in one query
        placeholders = ",".join(["?"] * len(ids))
        rows = self.conn.execute(
            f"SELECT id, metadata FROM {self._table_name} WHERE id IN ({placeholders})",
            ids,
        ).fetchall()

        current_meta_map = {r[0]: (json.loads(r[1]) if r[1] else {}) for r in rows}

        # Prepare updates
        update_data = []
        for doc_id, meta_updates in batch:
            if doc_id in current_meta_map:
                meta = current_meta_map[doc_id]
                meta.update(meta_updates)
                update_data.append((json.dumps(meta), doc_id))
                updated += 1

        if update_data:
            self.conn.executemany(
                f"UPDATE {self._table_name} SET metadata = ? WHERE id = ?",
                update_data,
            )

    self.conn.commit()
    return updated

check_legacy_sqlite_vec(vec_table_name)

Check if legacy sqlite-vec tables exist (for migration).

Parameters:

Name Type Description Default
vec_table_name str

Expected name of the old vec0 virtual table

required

Returns:

Type Description
bool

True if legacy sqlite-vec data exists

Source code in src/simplevecdb/engine/catalog.py
def check_legacy_sqlite_vec(self, vec_table_name: str) -> bool:
    """
    Check if legacy sqlite-vec tables exist (for migration).

    Args:
        vec_table_name: Expected name of the old vec0 virtual table

    Returns:
        True if legacy sqlite-vec data exists
    """
    try:
        row = self.conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
            (vec_table_name,),
        ).fetchone()
        return row is not None
    except Exception:
        return False

get_legacy_vectors(vec_table_name)

Extract vectors from legacy sqlite-vec table for migration.

Parameters:

Name Type Description Default
vec_table_name str

Name of the old vec0 virtual table

required

Returns:

Type Description
list[tuple[int, bytes]]

List of (rowid, embedding_blob) tuples

Source code in src/simplevecdb/engine/catalog.py
def get_legacy_vectors(self, vec_table_name: str) -> list[tuple[int, bytes]]:
    """
    Extract vectors from legacy sqlite-vec table for migration.

    Args:
        vec_table_name: Name of the old vec0 virtual table

    Returns:
        List of (rowid, embedding_blob) tuples
    """
    try:
        rows = self.conn.execute(
            f"SELECT rowid, embedding FROM {vec_table_name}"
        ).fetchall()
        return [(int(r[0]), r[1]) for r in rows]
    except Exception as e:
        _logger.warning("Failed to read legacy vectors: %s", e)
        return []

drop_legacy_vec_table(vec_table_name)

Drop legacy sqlite-vec table after migration.

Source code in src/simplevecdb/engine/catalog.py
def drop_legacy_vec_table(self, vec_table_name: str) -> None:
    """Drop legacy sqlite-vec table after migration."""
    try:
        self.conn.execute(f"DROP TABLE IF EXISTS {vec_table_name}")
        self.conn.commit()
        _logger.info("Dropped legacy sqlite-vec table: %s", vec_table_name)
    except Exception as e:
        _logger.warning("Failed to drop legacy table %s: %s", vec_table_name, e)

get_children(parent_id)

Get all direct children of a document.

Parameters:

Name Type Description Default
parent_id int

ID of the parent document

required

Returns:

Type Description
list[tuple[int, str, dict[str, Any]]]

List of (id, text, metadata) tuples for child documents

Source code in src/simplevecdb/engine/catalog.py
def get_children(self, parent_id: int) -> list[tuple[int, str, dict[str, Any]]]:
    """
    Get all direct children of a document.

    Args:
        parent_id: ID of the parent document

    Returns:
        List of (id, text, metadata) tuples for child documents
    """
    rows = self.conn.execute(
        f"SELECT id, text, metadata FROM {self._table_name} WHERE parent_id = ?",
        (parent_id,),
    ).fetchall()

    return [(int(r[0]), r[1], json.loads(r[2]) if r[2] else {}) for r in rows]

get_parent(doc_id)

Get the parent document of a given document.

Parameters:

Name Type Description Default
doc_id int

ID of the child document

required

Returns:

Type Description
tuple[int, str, dict[str, Any]] | None

Tuple of (id, text, metadata) for parent, or None if no parent

Source code in src/simplevecdb/engine/catalog.py
def get_parent(self, doc_id: int) -> tuple[int, str, dict[str, Any]] | None:
    """
    Get the parent document of a given document.

    Args:
        doc_id: ID of the child document

    Returns:
        Tuple of (id, text, metadata) for parent, or None if no parent
    """
    # First get the parent_id
    row = self.conn.execute(
        f"SELECT parent_id FROM {self._table_name} WHERE id = ?",
        (doc_id,),
    ).fetchone()

    if not row or row[0] is None:
        return None

    parent_id = row[0]

    # Then fetch the parent document
    parent_row = self.conn.execute(
        f"SELECT id, text, metadata FROM {self._table_name} WHERE id = ?",
        (parent_id,),
    ).fetchone()

    if not parent_row:
        return None

    return (
        int(parent_row[0]),
        parent_row[1],
        json.loads(parent_row[2]) if parent_row[2] else {},
    )

get_descendants(root_id, max_depth=None)

Get all descendants of a document (recursive).

Uses a recursive CTE for efficient traversal.

Parameters:

Name Type Description Default
root_id int

ID of the root document

required
max_depth int | None

Maximum depth to traverse (None for unlimited)

None

Returns:

Type Description
list[tuple[int, str, dict[str, Any], int]]

List of (id, text, metadata, depth) tuples

Source code in src/simplevecdb/engine/catalog.py
def get_descendants(
    self, root_id: int, max_depth: int | None = None
) -> list[tuple[int, str, dict[str, Any], int]]:
    """
    Get all descendants of a document (recursive).

    Uses a recursive CTE for efficient traversal.

    Args:
        root_id: ID of the root document
        max_depth: Maximum depth to traverse (None for unlimited)

    Returns:
        List of (id, text, metadata, depth) tuples
    """
    # Validate max_depth to prevent SQL injection (it's interpolated into query)
    if max_depth is not None:
        max_depth = int(max_depth)
    depth_clause = f"AND depth < {max_depth}" if max_depth else ""

    sql = f"""
        WITH RECURSIVE descendants(id, text, metadata, depth) AS (
            SELECT id, text, metadata, 1 as depth
            FROM {self._table_name}
            WHERE parent_id = ?

            UNION ALL

            SELECT t.id, t.text, t.metadata, d.depth + 1
            FROM {self._table_name} t
            JOIN descendants d ON t.parent_id = d.id
            WHERE 1=1 {depth_clause}
        )
        SELECT id, text, metadata, depth FROM descendants
        ORDER BY depth, id
    """

    rows = self.conn.execute(sql, (root_id,)).fetchall()

    return [
        (int(r[0]), r[1], json.loads(r[2]) if r[2] else {}, int(r[3])) for r in rows
    ]

get_ancestors(doc_id, max_depth=None)

Get all ancestors of a document (path to root).

Parameters:

Name Type Description Default
doc_id int

ID of the document

required
max_depth int | None

Maximum depth to traverse (None for unlimited)

None

Returns:

Type Description
list[tuple[int, str, dict[str, Any], int]]

List of (id, text, metadata, depth) tuples, from immediate parent to root

Source code in src/simplevecdb/engine/catalog.py
def get_ancestors(
    self, doc_id: int, max_depth: int | None = None
) -> list[tuple[int, str, dict[str, Any], int]]:
    """
    Get all ancestors of a document (path to root).

    Args:
        doc_id: ID of the document
        max_depth: Maximum depth to traverse (None for unlimited)

    Returns:
        List of (id, text, metadata, depth) tuples, from immediate parent to root
    """
    # Validate max_depth to prevent SQL injection (it's interpolated into query)
    if max_depth is not None:
        max_depth = int(max_depth)
    depth_clause = f"AND depth < {max_depth}" if max_depth else ""

    sql = f"""
        WITH RECURSIVE ancestors(id, text, metadata, parent_id, depth) AS (
            SELECT id, text, metadata, parent_id, 1 as depth
            FROM {self._table_name}
            WHERE id = (SELECT parent_id FROM {self._table_name} WHERE id = ?)

            UNION ALL

            SELECT t.id, t.text, t.metadata, t.parent_id, a.depth + 1
            FROM {self._table_name} t
            JOIN ancestors a ON t.id = a.parent_id
            WHERE a.parent_id IS NOT NULL {depth_clause}
        )
        SELECT id, text, metadata, depth FROM ancestors
        ORDER BY depth
    """

    rows = self.conn.execute(sql, (doc_id,)).fetchall()

    return [
        (int(r[0]), r[1], json.loads(r[2]) if r[2] else {}, int(r[3])) for r in rows
    ]

set_parent(doc_id, parent_id)

Set or update the parent of a document.

Parameters:

Name Type Description Default
doc_id int

ID of the document to update

required
parent_id int | None

New parent ID (None to remove parent)

required

Returns:

Type Description
bool

True if document was updated, False if not found

Raises:

Type Description
ValueError

If setting parent would create a cycle

Source code in src/simplevecdb/engine/catalog.py
def set_parent(self, doc_id: int, parent_id: int | None) -> bool:
    """
    Set or update the parent of a document.

    Args:
        doc_id: ID of the document to update
        parent_id: New parent ID (None to remove parent)

    Returns:
        True if document was updated, False if not found

    Raises:
        ValueError: If setting parent would create a cycle
    """
    # Check for cycles: parent_id cannot be doc_id or any of its descendants
    if parent_id is not None:
        if parent_id == doc_id:
            raise ValueError("A document cannot be its own parent")
        descendants = self.get_descendants(doc_id)
        descendant_ids = {d[0] for d in descendants}
        if parent_id in descendant_ids:
            raise ValueError(
                f"Cannot set parent: document {parent_id} is a descendant of {doc_id}"
            )

    with self.conn:
        cursor = self.conn.execute(
            f"UPDATE {self._table_name} SET parent_id = ? WHERE id = ?",
            (parent_id, doc_id),
        )
        return cursor.rowcount > 0

save_cluster_state(name, algorithm, n_clusters, centroids, metadata=None)

Save cluster state for later reuse.

Parameters:

Name Type Description Default
name str

Unique name for this cluster configuration

required
algorithm str

Algorithm used (kmeans, minibatch_kmeans, hdbscan)

required
n_clusters int

Number of clusters

required
centroids bytes | None

Serialized centroid array (numpy bytes)

required
metadata dict[str, Any] | None

Additional metadata (inertia, silhouette, etc.)

None
Source code in src/simplevecdb/engine/catalog.py
def save_cluster_state(
    self,
    name: str,
    algorithm: str,
    n_clusters: int,
    centroids: bytes | None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """
    Save cluster state for later reuse.

    Args:
        name: Unique name for this cluster configuration
        algorithm: Algorithm used (kmeans, minibatch_kmeans, hdbscan)
        n_clusters: Number of clusters
        centroids: Serialized centroid array (numpy bytes)
        metadata: Additional metadata (inertia, silhouette, etc.)
    """
    self._ensure_cluster_table()
    cluster_table = f"{self._table_name}_clusters"

    meta_json = json.dumps(metadata) if metadata else None

    self.conn.execute(
        f"""
        INSERT OR REPLACE INTO {cluster_table}
        (name, algorithm, n_clusters, centroids, metadata, created_at)
        VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
        """,
        (name, algorithm, n_clusters, centroids, meta_json),
    )
    self.conn.commit()

load_cluster_state(name)

Load saved cluster state.

Parameters:

Name Type Description Default
name str

Name of the cluster configuration

required

Returns:

Type Description
tuple[str, int, bytes | None, dict[str, Any]] | None

Tuple of (algorithm, n_clusters, centroids_bytes, metadata) or None

Source code in src/simplevecdb/engine/catalog.py
def load_cluster_state(
    self, name: str
) -> tuple[str, int, bytes | None, dict[str, Any]] | None:
    """
    Load saved cluster state.

    Args:
        name: Name of the cluster configuration

    Returns:
        Tuple of (algorithm, n_clusters, centroids_bytes, metadata) or None
    """
    self._ensure_cluster_table()
    cluster_table = f"{self._table_name}_clusters"

    row = self.conn.execute(
        f"SELECT algorithm, n_clusters, centroids, metadata FROM {cluster_table} WHERE name = ?",
        (name,),
    ).fetchone()

    if not row:
        return None

    algorithm, n_clusters, centroids, meta_json = row
    metadata = json.loads(meta_json) if meta_json else {}
    return (algorithm, n_clusters, centroids, metadata)

list_cluster_states()

List all saved cluster configurations.

Source code in src/simplevecdb/engine/catalog.py
def list_cluster_states(self) -> list[dict[str, Any]]:
    """List all saved cluster configurations."""
    self._ensure_cluster_table()
    cluster_table = f"{self._table_name}_clusters"

    rows = self.conn.execute(
        f"SELECT name, algorithm, n_clusters, created_at, metadata FROM {cluster_table}"
    ).fetchall()

    result = []
    for name, algorithm, n_clusters, created_at, meta_json in rows:
        result.append(
            {
                "name": name,
                "algorithm": algorithm,
                "n_clusters": n_clusters,
                "created_at": created_at,
                "metadata": json.loads(meta_json) if meta_json else {},
            }
        )
    return result

delete_cluster_state(name)

Delete a saved cluster configuration.

Source code in src/simplevecdb/engine/catalog.py
def delete_cluster_state(self, name: str) -> bool:
    """Delete a saved cluster configuration."""
    self._ensure_cluster_table()
    cluster_table = f"{self._table_name}_clusters"

    cursor = self.conn.execute(
        f"DELETE FROM {cluster_table} WHERE name = ?", (name,)
    )
    self.conn.commit()
    return cursor.rowcount > 0