Skip to content

sql

triplum.store.sql

SQL-backed stores through SQLAlchemy/SQLModel.

SQLAlchemyStore

SQLAlchemyStore(
    url: str = "sqlite://",
    *,
    text: BM25Settings | None = None,
)

Bases: RecordStore, TextSearchStore

Records in the database at url (any SQLAlchemy URL); missing tables are created.

The default URL is an in-memory SQLite database, private to this store instance and shared by all threads using it. Backend-specific stores may subclass this where specific SQL is faster.

Source code in src/triplum/store/sql/generic.py
28
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(self, url: str = "sqlite://", *, text: BM25Settings | None = None) -> None:
    self._text_settings = HIPPORAG1 if text is None else text
    self._text_indexes: dict[UUID, BM25] = {}
    if url == "sqlite://":
        # One shared connection; otherwise each thread gets its own empty in-memory database.
        self.engine = create_engine(
            url, poolclass=StaticPool, connect_args={"check_same_thread": False}
        )
    else:
        self.engine = create_engine(url)
    rows = (SourceRow, SourceAccessRow, ChunkRow)
    tables = [SQLModel.metadata.tables[row.__tablename__] for row in rows]  # pyright: ignore[reportArgumentType]
    SQLModel.metadata.create_all(self.engine, tables=tables)  # not every imported table

engine instance-attribute

engine = create_engine(
    url,
    poolclass=StaticPool,
    connect_args={"check_same_thread": False},
)

index_text

index_text(collection_id: UUID, /) -> None

Replace this collection's search snapshot only after a successful build.

Source code in src/triplum/store/sql/generic.py
42
43
44
45
46
47
48
def index_text(self, collection_id: UUID, /) -> None:
    """Replace this collection's search snapshot only after a successful build."""
    from triplum.steps.retrieval import BM25

    self._text_indexes[collection_id] = BM25(
        self, collection_id=collection_id, settings=self._text_settings
    )

search_text

search_text(
    query: str,
    /,
    *,
    collection_id: UUID,
    viewer: Viewer | None = None,
    k: int,
) -> list[RetrievalHit]

Search the last built snapshot; see TextSearchStore for the contract.

Source code in src/triplum/store/sql/generic.py
50
51
52
53
54
55
56
def search_text(
    self, query: str, /, *, collection_id: UUID, viewer: Viewer | None = None, k: int
) -> list[RetrievalHit]:
    """Search the last built snapshot; see `TextSearchStore` for the contract."""
    if k < 1:
        raise ValueError("k must be at least 1")
    return self._text_indexes[collection_id](query, viewer=viewer, k=k)

add_sources

add_sources(
    sources: Iterable[Source], /, *, allow: Iterable[str]
) -> None
Source code in src/triplum/store/sql/generic.py
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
def add_sources(self, sources: Iterable[Source], /, *, allow: Iterable[str]) -> None:
    access = principals(allow)
    with Session(self.engine) as session, session.begin():

        def stored(id: UUID) -> tuple[Source, frozenset[str]] | None:
            row = session.get(SourceRow, id)
            if row is None:
                return None
            principals = session.exec(
                select(SourceAccessRow.principal).where(SourceAccessRow.source_id == id)
            ).all()
            return _source(row), frozenset(principals)

        def holder(collection_id: UUID, external_id: str) -> UUID | None:
            return session.exec(
                select(SourceRow.id).where(
                    SourceRow.collection_id == collection_id,
                    SourceRow.external_id == external_id,
                )
            ).first()

        added = new_sources(sources, access, stored, holder)
        for s in added:
            session.add(
                SourceRow(
                    id=s.id,
                    collection_id=s.collection_id,
                    origin=s.origin,
                    text=s.text,
                    external_id=s.external_id,
                    fingerprint=s.fingerprint(),
                )
            )
        session.flush()  # sources first: access rows reference them by foreign key
        session.add_all(
            SourceAccessRow(source_id=s.id, principal=p) for s in added for p in access
        )

replace_chunks

replace_chunks(
    source_id: UUID, chunks: Iterable[Chunk], /
) -> None
Source code in src/triplum/store/sql/generic.py
 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
def replace_chunks(self, source_id: UUID, chunks: Iterable[Chunk], /) -> None:
    # One transaction: SQLite serializes it against other writers, so no union is visible.
    with Session(self.engine) as session, session.begin():
        row = session.get(SourceRow, source_id)
        if row is None:
            raise KeyError(source_id)

        def stored(id: UUID) -> Chunk | None:
            row = session.get(ChunkRow, id)
            return None if row is None else _chunk(row)

        checked = checked_chunks(_source(row), chunks, stored)
        session.exec(delete(ChunkRow).where(col(ChunkRow.source_id) == source_id))
        for c in checked:
            session.add(
                ChunkRow(
                    id=c.id,
                    collection_id=c.collection_id,
                    source_id=c.source_id,
                    origin=c.origin,
                    ordinal=c.ordinal,
                    start=c.start,
                    text=c.text,
                    fingerprint=c.fingerprint(),
                )
            )

source

source(
    id: UUID, /, *, viewer: Viewer | None = None
) -> Source
Source code in src/triplum/store/sql/generic.py
123
124
125
126
127
128
129
130
def source(self, id: UUID, /, *, viewer: Viewer | None = None) -> Source:
    with Session(self.engine) as session:
        row = session.exec(
            select(SourceRow).where(SourceRow.id == id, _visible(viewer))
        ).first()
        if row is None:
            raise KeyError(id)
        return _source(row)

sources

sources(
    *, collection_id: UUID, viewer: Viewer | None = None
) -> Iterator[Source]
Source code in src/triplum/store/sql/generic.py
132
133
134
135
136
137
138
def sources(self, *, collection_id: UUID, viewer: Viewer | None = None) -> Iterator[Source]:
    with Session(self.engine) as session:
        rows = session.exec(
            select(SourceRow).where(SourceRow.collection_id == collection_id, _visible(viewer))
        ).all()
    for row in rows:
        yield _source(row)

chunks

chunks(
    source_id: UUID, /, *, viewer: Viewer | None = None
) -> list[Chunk]
Source code in src/triplum/store/sql/generic.py
140
141
142
143
144
145
146
147
def chunks(self, source_id: UUID, /, *, viewer: Viewer | None = None) -> list[Chunk]:
    with Session(self.engine) as session:
        visible = session.exec(
            select(SourceRow.id).where(SourceRow.id == source_id, _visible(viewer))
        ).first()
        if visible is None:
            raise KeyError(source_id)
        return _chunks(session, source_id)

close

close() -> None

Close this store's database connections. An in-memory database is discarded.

Source code in src/triplum/store/sql/generic.py
149
150
151
def close(self) -> None:
    """Close this store's database connections. An in-memory database is discarded."""
    self.engine.dispose()

FTS5Settings

Bases: FingerprintedDataModel

FTS5 tokenizer declaration and the pattern extracting literal OR query terms.

FTS5 fixes BM25's k1=1.2 and b=0.75. The default tokenizer retains accents and underscores, closer to the reference's lowercased Unicode word tokens.

Attributes:

Name Type Description
tokenizer str
token_pattern str

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

tokenizer class-attribute instance-attribute

tokenizer: str = (
    "unicode61 remove_diacritics 0 tokenchars '_'"
)

token_pattern class-attribute instance-attribute

token_pattern: str = '\\w+'

SQLiteStore

SQLiteStore(
    url: str = "sqlite://",
    *,
    text: FTS5Settings | None = None,
)

Bases: SQLAlchemyStore

SQLite records with persisted FTS5 search snapshots and backend-specific settings.

Source code in src/triplum/store/sql/sqlite.py
32
33
34
35
36
37
38
39
40
def __init__(self, url: str = "sqlite://", *, text: FTS5Settings | None = None) -> None:
    if make_url(url).get_backend_name() != "sqlite":
        raise ValueError("SQLiteStore requires a SQLite URL")
    super().__init__(url)
    self._fts_settings = FTS5Settings() if text is None else text
    self._query_pattern = re.compile(self._fts_settings.token_pattern)
    SQLModel.metadata.create_all(
        self.engine, tables=[SQLModel.metadata.tables[TextIndexRow.__tablename__]]
    )

index_text

index_text(collection_id: UUID, /) -> None

Atomically replace a collection's FTS5 table and its recorded settings.

Source code in src/triplum/store/sql/sqlite.py
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
def index_text(self, collection_id: UUID, /) -> None:
    """Atomically replace a collection's FTS5 table and its recorded settings."""
    table = f"chunk_text_{collection_id.hex}"
    tokenizer = self._fts_settings.tokenizer.replace("'", "''")
    with self.engine.begin() as connection:
        # sqlite3's legacy transaction mode does not BEGIN for DDL. Explicit BEGIN
        # makes a failed DROP/CREATE/repopulation roll back to the old snapshot.
        connection.exec_driver_sql("BEGIN")
        connection.exec_driver_sql(f'DROP TABLE IF EXISTS "{table}"')
        connection.exec_driver_sql(
            f'CREATE VIRTUAL TABLE "{table}" USING fts5('
            "text, chunk_id UNINDEXED, source_id UNINDEXED, ordinal UNINDEXED, "
            f"start UNINDEXED, tokenize='{tokenizer}')"
        )
        connection.execute(
            sql(
                f'INSERT INTO "{table}" (text, chunk_id, source_id, ordinal, start) '
                "SELECT text, id, source_id, ordinal, start FROM chunk "
                "WHERE collection_id = :collection"
            ),
            {"collection": collection_id.hex},
        )
        connection.execute(
            sql(
                "INSERT INTO text_index (collection_id, settings) VALUES (:id, :settings) "
                "ON CONFLICT(collection_id) DO UPDATE SET settings = excluded.settings"
            ),
            {"id": collection_id.hex, "settings": self._fts_settings.model_dump_json()},
        )

search_text

search_text(
    query: str,
    /,
    *,
    collection_id: UUID,
    viewer: Viewer | None = None,
    k: int,
) -> list[RetrievalHit]

Search the persisted snapshot, checking settings and filtering before top-k.

Source code in src/triplum/store/sql/sqlite.py
 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
def search_text(
    self, query: str, /, *, collection_id: UUID, viewer: Viewer | None = None, k: int
) -> list[RetrievalHit]:
    """Search the persisted snapshot, checking settings and filtering before top-k."""
    if k < 1:
        raise ValueError("k must be at least 1")
    table = f"chunk_text_{collection_id.hex}"
    with self.engine.connect() as connection:
        # Keep the settings check and MATCH on the same actual SQLite read snapshot.
        connection.exec_driver_sql("BEGIN")
        settings = connection.execute(
            sql("SELECT settings FROM text_index WHERE collection_id = :id"),
            {"id": collection_id.hex},
        ).scalar_one_or_none()
        if settings is None:
            raise KeyError(collection_id)
        if FTS5Settings.model_validate_json(settings) != self._fts_settings:
            raise ValueError("text index settings changed; call index_text to rebuild")
        terms = [m.group() for m in self._query_pattern.finditer(query) if m.group()]
        if not terms:
            return []
        if any("\x00" in term for term in terms):
            raise ValueError("FTS5 query terms cannot contain NUL characters")
        parameters: dict[str, object] = {
            "query": " OR ".join('"' + term.replace('"', '""') + '"' for term in terms),
            "k": k,
        }
        visibility = ""
        if viewer is not None:
            if not viewer.principals:
                return []
            placeholders = []
            for i, principal in enumerate(sorted(viewer.principals)):
                key = f"principal_{i}"
                placeholders.append(f":{key}")
                parameters[key] = principal
            visibility = (
                " AND EXISTS (SELECT 1 FROM source_access a WHERE a.source_id = s.id "
                f"AND a.principal IN ({', '.join(placeholders)}))"
            )
        rows = connection.execute(
            sql(
                f"SELECT f.text, f.chunk_id, f.source_id, f.ordinal, f.start, s.origin, "
                f'-bm25("{table}") AS score FROM "{table}" f '
                "JOIN source s ON s.id = f.source_id "
                f'WHERE "{table}" MATCH :query{visibility} '
                "ORDER BY score DESC, f.source_id, CAST(f.ordinal AS INTEGER) LIMIT :k"
            ),
            parameters,
        ).mappings()
        return [
            RetrievalHit(
                chunk=Chunk(
                    id=UUID(row["chunk_id"]),
                    collection_id=collection_id,
                    source_id=UUID(row["source_id"]),
                    origin=row["origin"],
                    ordinal=row["ordinal"],
                    start=row["start"],
                    text=row["text"],
                ),
                score=row["score"],
            )
            for row in rows
        ]