diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e733df3..97fe7df 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,28 +2,62 @@ name: CI
on:
push:
- branches: [master]
pull_request:
+ merge_group:
+ workflow_dispatch:
+ schedule:
+ - cron: '23 7 * * 1'
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
+ cancel-in-progress: true
+
jobs:
test:
- name: Python ${{ matrix.python-version }}
+ name: Test (Python ${{ matrix.python }})
runs-on: ubuntu-latest
+ timeout-minutes: 15
strategy:
fail-fast: false
matrix:
- python-version: ["3.11", "3.12", "3.13"]
+ python: ['3.11', '3.14']
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
+ with:
+ python-version: ${{ matrix.python }}
+ enable-cache: true
+ - run: uv sync --locked
+ - name: Run tests and Hypothesis state machines
+ run: uv run --no-sync pytest --hypothesis-profile=ci --hypothesis-show-statistics --junitxml=test-results.xml
+ - name: Preserve test results and failure examples
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: tests-linux-${{ matrix.python }}
+ path: |
+ test-results.xml
+ .hypothesis/
+ include-hidden-files: true
+ if-no-files-found: ignore
+ quality:
+ name: Types and package build
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
steps:
- - uses: actions/checkout@v7
- - uses: astral-sh/setup-uv@v9.0.0
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
with:
- python-version: ${{ matrix.python-version }}
+ python-version: '3.11'
enable-cache: true
- - run: uv sync --locked --all-groups
- - run: uv run pytest
- - run: uv run pyright
+ - run: uv sync --locked
+ - run: uv run --no-sync pyright
- run: uv build
diff --git a/.gitignore b/.gitignore
index 505a3b1..22b4d3d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,8 @@ wheels/
# Virtual environments
.venv
+
+# Generated test data; regression examples belong in tracked test code.
+.hypothesis/
+.pytest_cache/
+test-results.xml
diff --git a/README.md b/README.md
index 376c463..528837f 100644
--- a/README.md
+++ b/README.md
@@ -42,7 +42,7 @@ with engine.connect() as conn:
## External content tables
-FTS5 can index a regular table without duplicating the data. Sync triggers are created automatically.
+FTS5 can index a regular table without duplicating the data. Sync triggers are created automatically, and existing rows are indexed when the FTS5 table is first created.
```python
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
@@ -125,6 +125,18 @@ FTS5Match(fts, "NEAR(python sqlite, 5)") # proximity
Works with `metadata.create_all()`, `metadata.drop_all()`, and ORM `Mapped[]` types.
+## Development and CI
+
+Install the locked development environment with `uv sync --locked`, then run
+`uv run pytest --hypothesis-profile=ci --hypothesis-show-statistics` and
+`uv run pyright`. Build distributions with `uv build`.
+
+GitHub Actions runs the complete suite, including generated lifecycle tests and
+transactional state machines, on pull requests, pushes, merge queues, manual
+dispatches, and a weekly schedule. Tests run on Linux with Python 3.11 and 3.14.
+CI uploads test reports and Hypothesis data for reproducing failures. Keep reduced
+regressions in test code; the local `.hypothesis` database is generated data.
+
## License
MIT
diff --git a/src/sqlalchemy_fts5/_ddl.py b/src/sqlalchemy_fts5/_ddl.py
index 281cf53..b230085 100644
--- a/src/sqlalchemy_fts5/_ddl.py
+++ b/src/sqlalchemy_fts5/_ddl.py
@@ -57,13 +57,13 @@ def _render_fts5_create(table: Table, compiler: Any, if_not_exists: bool = False
if "content" in options:
content_ref: Table | str = options["content"]
- content_name = format_table_identifier(preparer, content_ref)
+ # FTS5 quotes these names itself when reading the content table.
+ content_name = content_ref.name if isinstance(content_ref, Table) else content_ref
parts.append(f"content={_render_fts5_string_literal(content_name)}")
if "content_rowid" in options:
content_rowid: str = options["content_rowid"]
- quoted_rowid = quote_identifier(preparer, content_rowid)
- parts.append(f"content_rowid={_render_fts5_string_literal(quoted_rowid)}")
+ parts.append(f"content_rowid={_render_fts5_string_literal(content_rowid)}")
if "tokenize" in options:
tokenize: str = options["tokenize"]
diff --git a/src/sqlalchemy_fts5/_expression.py b/src/sqlalchemy_fts5/_expression.py
index f659391..f1c806d 100644
--- a/src/sqlalchemy_fts5/_expression.py
+++ b/src/sqlalchemy_fts5/_expression.py
@@ -38,14 +38,16 @@ class FTS5Match(Generative, elements.BinaryExpression[Any]):
def __init__(self, table: Table, against: Any):
self.fts5_table = table
against = coercions.expect(roles.ExpressionElementRole, against)
- # Placeholder left side — the actual table name is rendered by @compiles
- left: elements.ColumnElement[Any] = elements.literal_column(table.name)
+ # Retain table ownership for FROM inference and statement cache keys.
+ # The compiler renders the FTS hidden column instead of this placeholder.
+ left: elements.ColumnElement[Any] = table.table_valued()
super().__init__(left, against, operators.match_op)
@compiles(FTS5Match, "sqlite")
def _compile_fts5_match(element: FTS5Match, compiler: Any, **kw: Any) -> str:
# Use the compiler's identifier preparer to properly quote the table name
- table_name = compiler.preparer.format_table(element.fts5_table)
+ # MATCH uses the hidden column named after the table, without its schema.
+ table_name = compiler.preparer.quote(element.fts5_table.name)
right = compiler.process(element.right, **kw)
return f"{table_name} MATCH {right}"
diff --git a/src/sqlalchemy_fts5/_functions.py b/src/sqlalchemy_fts5/_functions.py
index 7433701..f608bee 100644
--- a/src/sqlalchemy_fts5/_functions.py
+++ b/src/sqlalchemy_fts5/_functions.py
@@ -21,7 +21,7 @@ def fts5_bm25(table: Table) -> Function[Any]:
.order_by(fts5_bm25(fts))
)
"""
- return func.bm25(expression.literal_column(table.name))
+ return func.bm25(expression.column(table.name))
def fts5_highlight(
@@ -44,7 +44,7 @@ def fts5_highlight(
close_tag: Markup inserted after each match.
"""
return func.highlight(
- expression.literal_column(table.name),
+ expression.column(table.name),
column_index,
open_tag,
close_tag,
@@ -74,7 +74,7 @@ def fts5_snippet(
max_tokens: Approximate maximum tokens in the returned snippet.
"""
return func.snippet(
- expression.literal_column(table.name),
+ expression.column(table.name),
column_index,
open_tag,
close_tag,
diff --git a/src/sqlalchemy_fts5/_table.py b/src/sqlalchemy_fts5/_table.py
index 0196441..e3bbaf8 100644
--- a/src/sqlalchemy_fts5/_table.py
+++ b/src/sqlalchemy_fts5/_table.py
@@ -6,7 +6,7 @@
from typing import Any
-from sqlalchemy import Column, Connection, Integer, MetaData, String, Table, event, text
+from sqlalchemy import Column, Connection, Integer, MetaData, String, Table, event
# Importing _ddl registers the @compiles handlers that intercept
# CreateTable/DropTable for FTS5-marked tables.
@@ -35,7 +35,8 @@ def FTS5Table(
If *content* is provided (external content table), DDL triggers are
automatically created to keep the FTS index in sync with the content table
- on INSERT, DELETE, and UPDATE.
+ on INSERT, DELETE, and UPDATE. Existing content is indexed when the FTS
+ table is first created.
Args:
name: Table name.
@@ -45,7 +46,7 @@ def FTS5Table(
When set, the FTS5 table stores no content itself and reads from
the content table on demand.
content_rowid: Column in the content table that maps to ``rowid``.
- Required when *content* is set.
+ Required for non-empty external *content*.
tokenize: FTS5 tokenizer specification (e.g. ``"porter unicode61"``).
prefix: Prefix index sizes (e.g. ``"2,3"``).
detail: FTS5 detail mode: ``"full"``, ``"column"``, or ``"none"``.
@@ -55,6 +56,12 @@ def FTS5Table(
A Table with FTS5 DDL, a ``rowid`` primary key column, and
String columns for each indexed column.
"""
+ if not columns:
+ raise ValueError("FTS5 requires at least one indexed column")
+ if content is not None and content != "" and not content_rowid:
+ raise ValueError("content_rowid is required for external content")
+
+ columns = list(columns)
sa_columns: list[Column[Any]] = [Column("rowid", Integer, primary_key=True)]
sa_columns.extend(Column(col, String) for col in columns)
@@ -79,20 +86,33 @@ def FTS5Table(
info={"fts5_columns": columns, "fts5_options": fts5_options},
)
+ content_table = content if isinstance(content, Table) else None
+ if isinstance(content, str) and content:
+ content_key = f"{table.schema}.{content}" if table.schema else content
+ content_table = metadata.tables.get(content_key)
+ if content_table is not None:
+ table.add_is_dependent_on(content_table)
+
# If there's an external content table, create sync triggers after
# the FTS5 table is created, and drop them before it's dropped.
- if content is not None and content_rowid is not None:
- @event.listens_for(table, "after_create")
+ if content is not None and content != "" and content_rowid is not None:
+ @event.listens_for(table, "after_create", propagate=True)
def _create_triggers(
target: Table, connection: Connection, **kw: Any
) -> None:
_create_sync_triggers(connection, target, fts5_options, columns)
-
- @event.listens_for(table, "before_drop")
+ preparer = connection.dialect.identifier_preparer
+ table_name = _ddl.format_table_identifier(preparer, target)
+ command_column = _ddl.quote_identifier(preparer, target.name)
+ connection.exec_driver_sql(
+ f"INSERT INTO {table_name}({command_column}) VALUES ('rebuild')"
+ )
+
+ @event.listens_for(table, "before_drop", propagate=True)
def _drop_triggers(
target: Table, connection: Connection, **kw: Any
) -> None:
- _drop_sync_triggers(connection, name)
+ _drop_sync_triggers(connection, target)
return table
@@ -109,7 +129,8 @@ def _create_sync_triggers(
documentation for external content tables.
"""
preparer = connection.dialect.identifier_preparer
- fts_name = _ddl.format_table_identifier(preparer, fts_table)
+ # SQLite forbids schema-qualified INSERT targets inside trigger bodies.
+ fts_name = _ddl.quote_identifier(preparer, fts_table.name)
fts_command_column = _ddl.quote_identifier(preparer, fts_table.name)
content_ref: Table | str = options["content"]
content_name = _ddl.format_table_identifier(preparer, content_ref)
@@ -121,32 +142,38 @@ def _create_sync_triggers(
new_col_list = ", ".join(f"new.{column}" for column in quoted_columns)
old_col_list = ", ".join(f"old.{column}" for column in quoted_columns)
+ def trigger_name(suffix: str) -> str:
+ identifier = _ddl.quote_identifier(preparer, f"{fts_table.name}{suffix}")
+ if fts_table.schema is not None:
+ identifier = f"{preparer.quote_schema(fts_table.schema)}.{identifier}"
+ return identifier
+
# INSERT trigger
- connection.execute(text(
+ connection.exec_driver_sql(
f"CREATE TRIGGER IF NOT EXISTS "
- f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_ai')} "
+ f"{trigger_name('_ai')} "
f"AFTER INSERT ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}({rowid}, {col_list}) "
f"VALUES (new.{rowid_col}, {new_col_list});"
f" END"
- ))
+ )
# DELETE trigger: uses FTS5 'delete' command to remove from index
- connection.execute(text(
+ connection.exec_driver_sql(
f"CREATE TRIGGER IF NOT EXISTS "
- f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_ad')} "
+ f"{trigger_name('_ad')} "
f"AFTER DELETE ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}({fts_command_column}, {rowid}, {col_list})"
f" VALUES('delete', old.{rowid_col}, {old_col_list});"
f" END"
- ))
+ )
# UPDATE trigger: delete old entry, insert new
- connection.execute(text(
+ connection.exec_driver_sql(
f"CREATE TRIGGER IF NOT EXISTS "
- f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_au')} "
+ f"{trigger_name('_au')} "
f"AFTER UPDATE ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}({fts_command_column}, {rowid}, {col_list})"
@@ -154,12 +181,14 @@ def _create_sync_triggers(
f" INSERT INTO {fts_name}({rowid}, {col_list}) "
f"VALUES (new.{rowid_col}, {new_col_list});"
f" END"
- ))
+ )
-def _drop_sync_triggers(connection: Connection, fts_name: str) -> None:
+def _drop_sync_triggers(connection: Connection, fts_table: Table) -> None:
"""Drop the INSERT/DELETE/UPDATE sync triggers."""
preparer = connection.dialect.identifier_preparer
for suffix in ("_ai", "_ad", "_au"):
- trigger_name = _ddl.quote_identifier(preparer, f"{fts_name}{suffix}")
- connection.execute(text(f"DROP TRIGGER IF EXISTS {trigger_name}"))
+ trigger_name = _ddl.quote_identifier(preparer, f"{fts_table.name}{suffix}")
+ if fts_table.schema is not None:
+ trigger_name = f"{preparer.quote_schema(fts_table.schema)}.{trigger_name}"
+ connection.exec_driver_sql(f"DROP TRIGGER IF EXISTS {trigger_name}")
diff --git a/tests/conftest.py b/tests/conftest.py
index 0f83430..933f1d5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,10 +3,14 @@
from __future__ import annotations
import pytest
+from hypothesis import settings
from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine
from sqlalchemy.engine import Engine
+settings.register_profile("ci", deadline=None, print_blob=True)
+
+
@pytest.fixture
def engine() -> Engine:
"""In-memory SQLite engine."""
diff --git a/tests/test_ddl.py b/tests/test_ddl.py
index 532fe3f..c80dac6 100644
--- a/tests/test_ddl.py
+++ b/tests/test_ddl.py
@@ -69,8 +69,8 @@ def test_quotes_content_table_name_string(
sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))
- assert "content='\"content table\"'" in sql
- assert "content_rowid='\"row id\"'" in sql
+ assert "content='content table'" in sql
+ assert "content_rowid='row id'" in sql
def test_tokenizer(self, engine: Engine, metadata: MetaData) -> None:
fts = FTS5Table(
@@ -100,8 +100,8 @@ def test_quotes_option_identifiers_separately_from_string_literals(
sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))
- assert "content='\"content''s table\"'" in sql
- assert "content_rowid='\"row\"\"id\"'" in sql
+ assert "content='content''s table'" in sql
+ assert "content_rowid='row\"id'" in sql
assert "tokenize='unicode61 tokenchars ''-'''" in sql
def test_prefix(self, engine: Engine, metadata: MetaData) -> None:
diff --git a/tests/test_hypothesis_copy.py b/tests/test_hypothesis_copy.py
new file mode 100644
index 0000000..745d001
--- /dev/null
+++ b/tests/test_hypothesis_copy.py
@@ -0,0 +1,30 @@
+"""Copied SQLAlchemy metadata retains FTS synchronization behavior."""
+
+from hypothesis import given, settings, strategies as st
+from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, select
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table
+
+
+@given(values=st.lists(st.sampled_from(["alpha", "beta", "gamma"]), min_size=1, max_size=10))
+@settings(deadline=None)
+def test_copied_metadata_keeps_sync_events(values: list[str]) -> None:
+ source = MetaData()
+ docs = Table("docs", source, Column("id", Integer, primary_key=True), Column("body", String))
+ fts = FTS5Table("idx", source, columns=["body"], content=docs, content_rowid="id")
+ copied = MetaData()
+ copied_docs = docs.to_metadata(copied)
+ copied_fts = fts.to_metadata(copied)
+ engine = create_engine("sqlite://")
+ try:
+ copied.create_all(engine)
+ with engine.begin() as conn:
+ for key, value in enumerate(values, 1):
+ conn.execute(copied_docs.insert(), {"id": key, "body": value})
+ for word in ("alpha", "beta", "gamma"):
+ actual = conn.execute(select(copied_fts.c.rowid).where(FTS5Match(copied_fts, word))).scalars().all()
+ assert actual == [key for key, value in enumerate(values, 1) if value == word]
+ copied_fts.drop(conn)
+ assert conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type='trigger'").all() == []
+ finally:
+ engine.dispose()
diff --git a/tests/test_hypothesis_dependencies.py b/tests/test_hypothesis_dependencies.py
new file mode 100644
index 0000000..0c7a0c7
--- /dev/null
+++ b/tests/test_hypothesis_dependencies.py
@@ -0,0 +1,31 @@
+"""FTS creation follows the dependencies of its external content table."""
+
+from hypothesis import given, settings, strategies as st
+from sqlalchemy import Column, ForeignKey, Integer, MetaData, String, Table, create_engine, select
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table
+
+
+@given(by_name=st.booleans(), depth=st.integers(1, 5))
+@settings(deadline=None)
+def test_content_dependency_chain(by_name: bool, depth: int) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData()
+ docs = Table(
+ "docs", meta, Column("id", Integer, primary_key=True),
+ Column("parent_id", Integer, ForeignKey("parent0.id")), Column("body", String),
+ )
+ fts = FTS5Table("idx", meta, columns=["body"], content=docs.name if by_name else docs, content_rowid="id")
+ for index in range(depth):
+ columns = [Column("id", Integer, primary_key=True)]
+ if index + 1 < depth:
+ columns.append(Column("parent_id", Integer, ForeignKey(f"parent{index + 1}.id")))
+ Table(f"parent{index}", meta, *columns)
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(docs.insert(), {"id": 1, "body": "alpha"})
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "alpha"))).scalars().all() == ["alpha"]
+ meta.drop_all(engine)
+ finally:
+ engine.dispose()
diff --git a/tests/test_hypothesis_lifecycle.py b/tests/test_hypothesis_lifecycle.py
new file mode 100644
index 0000000..0f13b76
--- /dev/null
+++ b/tests/test_hypothesis_lifecycle.py
@@ -0,0 +1,103 @@
+"""Property tests for metadata ownership, schemas, and expression composition."""
+
+from hypothesis import given, settings, strategies as st
+from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, literal, select
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table
+
+
+@given(schema=st.sampled_from(["main", "attached"]), by_name=st.booleans())
+@settings(deadline=None)
+def test_external_sync_in_schema(schema: str, by_name: bool) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData(schema=schema)
+ docs = Table("docs", meta, Column("id", Integer, primary_key=True), Column("body", String))
+ fts = FTS5Table("idx", meta, columns=["body"], content=docs.name if by_name else docs, content_rowid="id")
+ with engine.begin() as conn:
+ if schema == "attached":
+ conn.exec_driver_sql("ATTACH DATABASE ':memory:' AS attached")
+ meta.create_all(conn)
+ conn.execute(docs.insert(), {"id": 1, "body": "alpha"})
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "alpha"))).scalars().all() == ["alpha"]
+ conn.execute(docs.update().values(body="beta"))
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "alpha"))).all() == []
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "beta"))).scalars().all() == ["beta"]
+ conn.execute(docs.delete())
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "beta"))).all() == []
+ fts.drop(conn)
+ assert conn.exec_driver_sql(f"SELECT name FROM {schema}.sqlite_master WHERE type='trigger'").all() == []
+ finally:
+ engine.dispose()
+
+
+@given(rowid=st.sampled_from([None, "id", "row id"]))
+@settings(deadline=None)
+def test_contentless_tables_do_not_install_external_triggers(rowid: str | None) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData()
+ fts = FTS5Table("idx", meta, columns=["body"], content="", content_rowid=rowid)
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(fts.insert(), {"rowid": 1, "body": "alpha"})
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "alpha"))).scalars().all() == [1]
+ assert conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type='trigger'").all() == []
+ finally:
+ engine.dispose()
+
+
+@given(extra=st.lists(st.sampled_from(["title", "summary"]), unique=True))
+@settings(deadline=None)
+def test_table_owns_column_configuration(extra: list[str]) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData()
+ columns = ["body"]
+ fts = FTS5Table("idx", meta, columns=columns)
+ columns.clear()
+ columns.extend(extra)
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(fts.insert(), {"body": "alpha"})
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "alpha"))).scalars().all() == ["alpha"]
+ finally:
+ engine.dispose()
+
+
+@given(term=st.sampled_from(["alpha", "beta", "gamma"]))
+@settings(deadline=None)
+def test_match_contributes_its_from_table(term: str) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData()
+ fts = FTS5Table("idx", meta, columns=["body"])
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(fts.insert(), {"body": "alpha beta"})
+ statement = select(literal(1)).where(FTS5Match(fts, term))
+ assert conn.execute(statement).scalars().all() == ([1] if term != "gamma" else [])
+ finally:
+ engine.dispose()
+
+
+@given(counts=st.lists(st.integers(0, 5), min_size=2, max_size=2))
+@settings(deadline=None)
+def test_match_statement_cache_distinguishes_schemas(counts: list[int]) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ with engine.begin() as conn:
+ conn.exec_driver_sql("ATTACH DATABASE ':memory:' AS attached")
+ tables: list[Table] = []
+ for schema, count in zip(["main", "attached"], counts):
+ meta = MetaData(schema=schema)
+ fts = FTS5Table("idx", meta, columns=["body"])
+ meta.create_all(conn)
+ for _ in range(count):
+ conn.execute(fts.insert(), {"body": "alpha"})
+ tables.append(fts)
+ for index in [0, 1, 0, 1]:
+ statement = select(literal(1)).where(FTS5Match(tables[index], "alpha"))
+ assert len(conn.execute(statement).all()) == counts[index]
+ finally:
+ engine.dispose()
diff --git a/tests/test_hypothesis_runtime.py b/tests/test_hypothesis_runtime.py
new file mode 100644
index 0000000..5b11088
--- /dev/null
+++ b/tests/test_hypothesis_runtime.py
@@ -0,0 +1,94 @@
+"""Generated SQLite executions checked against an independent content model."""
+
+from hypothesis import example, given, settings, strategies as st
+from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, select
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table, fts5_bm25, fts5_highlight, fts5_snippet
+
+
+names = st.one_of(
+ st.sampled_from(["select", "two words", 'a"b', "author's", ":param", "é漢字", "a.b", "a%b"]),
+ st.text(alphabet="abcXYZ09 _-'\".:;%é漢", min_size=1, max_size=15),
+)
+words = ("alpha", "beta", "gamma")
+documents = st.lists(st.sampled_from(words), min_size=0, max_size=8).map(" ".join)
+operations = st.lists(
+ st.tuples(st.sampled_from(["put", "delete", "move"]), st.integers(1, 5), documents),
+ min_size=1, max_size=25,
+)
+
+
+@given(name=names, schema=st.sampled_from([None, "main", "attached"]))
+@settings(max_examples=80, deadline=None)
+def test_generated_names_support_all_query_helpers(name: str, schema: str | None) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData(schema=schema)
+ fts = FTS5Table("fts " + name, meta, columns=["body"])
+ with engine.begin() as conn:
+ if schema == "attached":
+ conn.exec_driver_sql("ATTACH DATABASE ':memory:' AS attached")
+ meta.create_all(conn)
+ conn.execute(fts.insert(), {"rowid": 1, "body": "alpha beta"})
+ row = conn.execute(
+ select(fts.c.rowid, fts5_bm25(fts), fts5_highlight(fts, 0), fts5_snippet(fts, 0))
+ .where(FTS5Match(fts, "alpha"))
+ ).one()
+ assert row[0] == 1
+ assert row[1] < 0
+ assert row[2] == row[3] == "alpha beta"
+ meta.drop_all(conn)
+ finally:
+ engine.dispose()
+
+
+@given(name=names, initial=st.lists(documents, max_size=5), ops=operations, by_name=st.booleans())
+@example(name=":param", initial=["alpha"], ops=[("put", 1, "beta")], by_name=True)
+@settings(max_examples=80, deadline=None)
+def test_external_content_operations_match_model(
+ name: str, initial: list[str], ops: list[tuple[str, int, str]], by_name: bool,
+) -> None:
+ engine = create_engine("sqlite://")
+ try:
+ meta = MetaData()
+ body = "body " + name
+ rowid = "id " + name
+ docs = Table("content " + name, meta, Column(rowid, Integer, primary_key=True), Column(body, String))
+ model = dict(enumerate(initial, 1))
+ with engine.begin() as conn:
+ meta.create_all(conn)
+ for key, value in model.items():
+ conn.execute(docs.insert(), {rowid: key, body: value})
+ fts = FTS5Table("fts " + name, meta, columns=[body], content=docs.name if by_name else docs, content_rowid=rowid)
+ meta.create_all(conn)
+
+ def check_model() -> None:
+ for word in words:
+ expected = {key: value for key, value in model.items() if word in value.split()}
+ actual = dict(conn.execute(select(fts.c.rowid, fts.c[body]).where(FTS5Match(fts, word))).tuples().all())
+ assert actual == expected
+
+ check_model()
+ for operation, key, value in ops:
+ if operation == "put":
+ if key in model:
+ conn.execute(docs.update().where(docs.c[rowid] == key).values({body: value}))
+ else:
+ conn.execute(docs.insert(), {rowid: key, body: value})
+ model[key] = value
+ elif operation == "delete":
+ conn.execute(docs.delete().where(docs.c[rowid] == key))
+ model.pop(key, None)
+ elif key in model:
+ destination = max(model) + 1
+ conn.execute(docs.update().where(docs.c[rowid] == key).values({rowid: destination}))
+ model[destination] = model.pop(key)
+ check_model()
+ # Recreating the index must recover the current model, without stale triggers.
+ fts.drop(conn)
+ fts.create(conn)
+ check_model()
+ meta.drop_all(conn)
+ assert conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type='trigger'").all() == []
+ finally:
+ engine.dispose()
diff --git a/tests/test_hypothesis_stateful.py b/tests/test_hypothesis_stateful.py
new file mode 100644
index 0000000..655aeb6
--- /dev/null
+++ b/tests/test_hypothesis_stateful.py
@@ -0,0 +1,95 @@
+"""Exercise index consistency across arbitrary transactional histories."""
+
+from hypothesis import settings, strategies as st
+from hypothesis.stateful import RuleBasedStateMachine, invariant, rule
+from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, select
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table
+
+
+text_values = st.one_of(
+ st.none(),
+ st.lists(st.sampled_from(["alpha", "beta", "gamma"]), max_size=6).map(" ".join),
+)
+
+
+class ContentTransactions(RuleBasedStateMachine):
+ def __init__(self) -> None:
+ super().__init__()
+ self.engine = create_engine("sqlite://")
+ self.conn = self.engine.connect()
+ self.meta = MetaData()
+ self.docs = Table(
+ "docs", self.meta, Column("id", Integer, primary_key=True),
+ Column("title", String), Column("body", String),
+ )
+ self.fts = FTS5Table(
+ "idx", self.meta, columns=["title", "body"],
+ content=self.docs, content_rowid="id",
+ )
+ self.meta.create_all(self.conn)
+ self.conn.commit()
+ # Explicit BEGIN makes SQLite DDL and SAVEPOINT rollback transactional,
+ # including Python versions with the driver's legacy transaction mode.
+ self.conn.exec_driver_sql("BEGIN")
+ self.pending: dict[int, tuple[str | None, str | None]] = {}
+ self.committed: dict[int, tuple[str | None, str | None]] = {}
+
+ @rule(key=st.integers(-3, 5), title=text_values, body=text_values, undo=st.booleans())
+ def put(self, key: int, title: str | None, body: str | None, undo: bool) -> None:
+ savepoint = self.conn.begin_nested()
+ if key in self.pending:
+ self.conn.execute(self.docs.update().where(self.docs.c.id == key).values(title=title, body=body))
+ else:
+ self.conn.execute(self.docs.insert(), {"id": key, "title": title, "body": body})
+ if undo:
+ savepoint.rollback()
+ else:
+ savepoint.commit()
+ self.pending[key] = (title, body)
+
+ @rule(key=st.integers(-3, 5))
+ def delete(self, key: int) -> None:
+ self.conn.execute(self.docs.delete().where(self.docs.c.id == key))
+ self.pending.pop(key, None)
+
+ @rule()
+ def commit(self) -> None:
+ self.conn.commit()
+ self.committed = self.pending.copy()
+ self.conn.exec_driver_sql("BEGIN")
+
+ @rule()
+ def rollback(self) -> None:
+ self.conn.rollback()
+ self.pending = self.committed.copy()
+ self.conn.exec_driver_sql("BEGIN")
+
+ @rule()
+ def recreate(self) -> None:
+ self.fts.drop(self.conn)
+ self.fts.create(self.conn)
+
+ @invariant()
+ def index_matches_content(self) -> None:
+ for word in ("alpha", "beta", "gamma"):
+ expected = {
+ key: value for key, value in self.pending.items()
+ if any(word in (field or "").split() for field in value)
+ }
+ rows = self.conn.execute(
+ select(self.fts.c.rowid, self.fts.c.title, self.fts.c.body)
+ .where(FTS5Match(self.fts, word))
+ ).all()
+ assert {row[0]: (row[1], row[2]) for row in rows} == expected
+ # Ask SQLite to compare the entire index with its external content.
+ self.conn.exec_driver_sql("INSERT INTO idx(idx, rank) VALUES ('integrity-check', 1)")
+
+ def teardown(self) -> None:
+ self.conn.close()
+ self.engine.dispose()
+
+
+# Hypothesis constructs this unittest class dynamically without a return annotation.
+TestContentTransactions = ContentTransactions.TestCase # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
+TestContentTransactions.settings = settings(max_examples=100, stateful_step_count=50, deadline=None)
diff --git a/tests/test_regressions.py b/tests/test_regressions.py
new file mode 100644
index 0000000..6e200ce
--- /dev/null
+++ b/tests/test_regressions.py
@@ -0,0 +1,97 @@
+"""Runtime regressions for FTS5 table setup and queries."""
+
+import pytest
+from sqlalchemy import Column, Integer, MetaData, String, Table, select
+from sqlalchemy.engine import Engine
+
+from sqlalchemy_fts5 import FTS5Match, FTS5Table, fts5_bm25, fts5_highlight, fts5_snippet
+
+
+@pytest.mark.parametrize("by_name", [False, True])
+def test_external_content_reads_quoted_names(engine: Engine, by_name: bool) -> None:
+ meta = MetaData()
+ docs = Table(
+ "content's table", meta,
+ Column('row"id', Integer, primary_key=True), Column("body", String),
+ )
+ fts = FTS5Table(
+ "idx", meta, columns=["body"],
+ content=docs.name if by_name else docs, content_rowid='row"id',
+ )
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(docs.insert(), {'row"id': 1, "body": "hello world"})
+ row = conn.execute(
+ select(fts.c.body, fts5_highlight(fts, 0))
+ .where(FTS5Match(fts, "hello"))
+ ).one()
+ assert tuple(row) == ("hello world", "hello world")
+
+
+def test_index_existing_content_and_keep_it_synced(engine: Engine) -> None:
+ meta = MetaData()
+ docs = Table("docs", meta, Column("id", Integer, primary_key=True), Column("body", String))
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(docs.insert(), [{"id": 1, "body": "hello"}, {"id": 2, "body": "hello"}])
+ fts = FTS5Table("idx", meta, columns=["body"], content=docs, content_rowid="id")
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "hello"))).scalars().all() == [1, 2]
+ conn.execute(docs.update().where(docs.c.id == 1).values(body="world"))
+ conn.execute(docs.delete().where(docs.c.id == 2))
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "hello"))).all() == []
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "world"))).scalars().all() == [1]
+ meta.create_all(engine)
+ with engine.connect() as conn:
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "world"))).scalars().all() == [1]
+
+
+@pytest.mark.parametrize("name", ["search index", "select", 'quote"name', "hyphen-name"])
+def test_auxiliary_functions_quote_names(engine: Engine, name: str) -> None:
+ meta = MetaData()
+ fts = FTS5Table(name, meta, columns=["body"])
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(fts.insert(), {"body": "hello world"})
+ assert conn.execute(select(fts5_bm25(fts)).select_from(fts).where(FTS5Match(fts, "hello"))).scalar_one() < 0
+ for expression in [fts5_highlight(fts, 0), fts5_snippet(fts, 0)]:
+ assert conn.execute(select(expression).select_from(fts).where(FTS5Match(fts, "hello"))).scalar_one() == "hello world"
+
+
+@pytest.mark.parametrize("schema", ["main", "attached"])
+def test_schema_qualified_match(engine: Engine, schema: str) -> None:
+ meta = MetaData(schema=schema)
+ fts = FTS5Table("search index", meta, columns=["body"])
+ with engine.begin() as conn:
+ if schema == "attached":
+ conn.exec_driver_sql("ATTACH DATABASE ':memory:' AS attached")
+ meta.create_all(conn)
+ conn.execute(fts.insert(), {"rowid": 1, "body": "hello"})
+ assert conn.execute(select(fts.c.rowid).where(FTS5Match(fts, "hello"))).scalars().all() == [1]
+
+
+def test_empty_columns_rejected_before_metadata_mutation() -> None:
+ meta = MetaData()
+ with pytest.raises(ValueError, match="at least one"):
+ FTS5Table("idx", meta, columns=[])
+ assert not meta.tables
+
+
+@pytest.mark.parametrize("rowid", [None, ""])
+def test_external_content_requires_rowid(rowid: str | None) -> None:
+ meta = MetaData()
+ with pytest.raises(ValueError, match="content_rowid"):
+ FTS5Table("idx", meta, columns=["body"], content="docs", content_rowid=rowid)
+ assert not meta.tables
+
+
+def test_trigger_identifiers_are_not_bind_parameters(engine: Engine) -> None:
+ meta = MetaData()
+ docs = Table("content :param", meta, Column("id", Integer, primary_key=True), Column("body", String))
+ fts = FTS5Table("fts :param", meta, columns=["body"], content=docs, content_rowid="id")
+ meta.create_all(engine)
+ with engine.begin() as conn:
+ conn.execute(docs.insert(), {"id": 1, "body": "alpha"})
+ assert conn.execute(select(fts.c.body).where(FTS5Match(fts, "alpha"))).scalars().all() == ["alpha"]
+ meta.drop_all(engine)