Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 43 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,8 @@ wheels/

# Virtual environments
.venv

# Generated test data; regression examples belong in tracked test code.
.hypothesis/
.pytest_cache/
test-results.xml
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
6 changes: 3 additions & 3 deletions src/sqlalchemy_fts5/_ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
8 changes: 5 additions & 3 deletions src/sqlalchemy_fts5/_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
6 changes: 3 additions & 3 deletions src/sqlalchemy_fts5/_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
71 changes: 50 additions & 21 deletions src/sqlalchemy_fts5/_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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"``.
Expand All @@ -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)

Expand All @@ -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

Expand All @@ -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)
Expand All @@ -121,45 +142,53 @@ 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})"
f" VALUES('delete', old.{rowid_col}, {old_col_list});"
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}")
4 changes: 4 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
8 changes: 4 additions & 4 deletions tests/test_ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
30 changes: 30 additions & 0 deletions tests/test_hypothesis_copy.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading