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
44 changes: 35 additions & 9 deletions src/sqlalchemy_fts5/_ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from sqlalchemy import Table
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.compiler import IdentifierPreparer
from sqlalchemy.sql.ddl import CreateTable, DropTable, ExecutableDDLElement


Expand All @@ -26,35 +27,59 @@ def _is_fts5_table(table: Table) -> bool:
return bool(table.info.get("fts5_columns"))


def quote_identifier(preparer: IdentifierPreparer, identifier: str) -> str:
"""Render one SQLite identifier according to the active dialect."""
return preparer.quote(identifier)


def format_table_identifier(
preparer: IdentifierPreparer, table: Table | str
) -> str:
"""Render a Table or public string table name as an identifier."""
if isinstance(table, Table):
return preparer.format_table(table)
return quote_identifier(preparer, table)


def _render_fts5_string_literal(value: str) -> str:
"""Render an FTS5 option value as a SQLite string literal."""
return "'" + value.replace("'", "''") + "'"


def _render_fts5_create(table: Table, compiler: Any, if_not_exists: bool = False) -> str:
"""Render CREATE VIRTUAL TABLE ... USING fts5(...)."""
info = table.info
fts_columns: list[str] = info.get("fts5_columns", [])
options: dict[str, Any] = info.get("fts5_options", {})
preparer: IdentifierPreparer = compiler.preparer

parts = list(fts_columns)
parts = [quote_identifier(preparer, column) for column in fts_columns]

if "content" in options:
content_ref = options["content"]
content_name = content_ref.name if hasattr(content_ref, "name") else str(content_ref)
parts.append(f"content='{content_name}'")
content_ref: Table | str = options["content"]
content_name = format_table_identifier(preparer, content_ref)
parts.append(f"content={_render_fts5_string_literal(content_name)}")

if "content_rowid" in options:
parts.append(f"content_rowid='{options['content_rowid']}'")
content_rowid: str = options["content_rowid"]
quoted_rowid = quote_identifier(preparer, content_rowid)
parts.append(f"content_rowid={_render_fts5_string_literal(quoted_rowid)}")

if "tokenize" in options:
parts.append(f"tokenize='{options['tokenize']}'")
tokenize: str = options["tokenize"]
parts.append(f"tokenize={_render_fts5_string_literal(tokenize)}")

if "prefix" in options:
parts.append(f"prefix='{options['prefix']}'")
prefix: str = options["prefix"]
parts.append(f"prefix={_render_fts5_string_literal(prefix)}")

if "detail" in options:
parts.append(f"detail={options['detail']}")

if "columnsize" in options:
parts.append(f"columnsize={options['columnsize']}")

table_name = compiler.preparer.format_table(table)
table_name = format_table_identifier(preparer, table)
column_spec = ", ".join(parts)
maybe_ine = "IF NOT EXISTS " if if_not_exists else ""

Expand All @@ -63,7 +88,8 @@ def _render_fts5_create(table: Table, compiler: Any, if_not_exists: bool = False

def _render_fts5_drop(table: Table, compiler: Any, if_exists: bool = False) -> str:
"""Render DROP TABLE for an FTS5 virtual table."""
table_name = compiler.preparer.format_table(table)
preparer: IdentifierPreparer = compiler.preparer
table_name = format_table_identifier(preparer, table)
maybe_ie = "IF EXISTS " if if_exists else ""
return f"DROP TABLE {maybe_ie}{table_name}"

Expand Down
46 changes: 30 additions & 16 deletions src/sqlalchemy_fts5/_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,44 +108,58 @@ def _create_sync_triggers(
These triggers follow the pattern recommended by the SQLite FTS5
documentation for external content tables.
"""
fts_name = fts_table.name
content_ref = options["content"]
content_name = content_ref.name if hasattr(content_ref, "name") else str(content_ref)
rowid_col = options["content_rowid"]

col_list = ", ".join(columns)
new_col_list = ", ".join(f"new.{c}" for c in columns)
old_col_list = ", ".join(f"old.{c}" for c in columns)
preparer = connection.dialect.identifier_preparer
fts_name = _ddl.format_table_identifier(preparer, fts_table)
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)
rowid_col = _ddl.quote_identifier(preparer, options["content_rowid"])
rowid = _ddl.quote_identifier(preparer, "rowid")

quoted_columns = [_ddl.quote_identifier(preparer, column) for column in columns]
col_list = ", ".join(quoted_columns)
new_col_list = ", ".join(f"new.{column}" for column in quoted_columns)
old_col_list = ", ".join(f"old.{column}" for column in quoted_columns)

# INSERT trigger
connection.execute(text(
f"CREATE TRIGGER IF NOT EXISTS {fts_name}_ai AFTER INSERT ON {content_name} "
f"CREATE TRIGGER IF NOT EXISTS "
f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_ai')} "
f"AFTER INSERT ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}(rowid, {col_list}) VALUES (new.{rowid_col}, {new_col_list});"
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(
f"CREATE TRIGGER IF NOT EXISTS {fts_name}_ad AFTER DELETE ON {content_name} "
f"CREATE TRIGGER IF NOT EXISTS "
f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_ad')} "
f"AFTER DELETE ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}({fts_name}, rowid, {col_list})"
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(
f"CREATE TRIGGER IF NOT EXISTS {fts_name}_au AFTER UPDATE ON {content_name} "
f"CREATE TRIGGER IF NOT EXISTS "
f"{_ddl.quote_identifier(preparer, f'{fts_table.name}_au')} "
f"AFTER UPDATE ON {content_name} "
f"BEGIN"
f" INSERT INTO {fts_name}({fts_name}, rowid, {col_list})"
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}) VALUES (new.{rowid_col}, {new_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:
"""Drop the INSERT/DELETE/UPDATE sync triggers."""
preparer = connection.dialect.identifier_preparer
for suffix in ("_ai", "_ad", "_au"):
connection.execute(text(f"DROP TRIGGER IF EXISTS {fts_name}{suffix}"))
trigger_name = _ddl.quote_identifier(preparer, f"{fts_name}{suffix}")
connection.execute(text(f"DROP TRIGGER IF EXISTS {trigger_name}"))
65 changes: 65 additions & 0 deletions tests/test_ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ def test_single_column(self, engine: Engine, metadata: MetaData) -> None:
sql = CreateFTS5Table(fts).compile(dialect=engine.dialect)
assert str(sql) == "CREATE VIRTUAL TABLE t USING fts5(title)"

def test_quotes_table_and_column_identifiers(
self, engine: Engine, metadata: MetaData
) -> None:
fts = FTS5Table(
"search-index",
metadata,
columns=["body text", "select", 'quote"column'],
)

sql = CreateFTS5Table(fts).compile(dialect=engine.dialect)

assert str(sql) == (
'CREATE VIRTUAL TABLE "search-index" USING '
'fts5("body text", "select", "quote""column")'
)

def test_content_table_by_object(
self, engine: Engine, metadata: MetaData, content_table: Table
) -> None:
Expand All @@ -40,6 +56,22 @@ def test_content_table_by_name(
sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))
assert "content='docs'" in sql

def test_quotes_content_table_name_string(
self, engine: Engine, metadata: MetaData
) -> None:
fts = FTS5Table(
"docs_fts",
metadata,
columns=["title"],
content="content table",
content_rowid="row id",
)

sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))

assert "content='\"content table\"'" in sql
assert "content_rowid='\"row id\"'" in sql

def test_tokenizer(self, engine: Engine, metadata: MetaData) -> None:
fts = FTS5Table(
"t", metadata, columns=["a"],
Expand All @@ -48,6 +80,30 @@ def test_tokenizer(self, engine: Engine, metadata: MetaData) -> None:
sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))
assert "tokenize='porter unicode61'" in sql

def test_quotes_option_identifiers_separately_from_string_literals(
self, engine: Engine, metadata: MetaData
) -> None:
content = Table(
"content's table",
metadata,
Column('row"id', Integer, primary_key=True),
Column("body text", String),
)
fts = FTS5Table(
"search index",
metadata,
columns=["body text"],
content=content,
content_rowid='row"id',
tokenize="unicode61 tokenchars '-'",
)

sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))

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:
fts = FTS5Table("t", metadata, columns=["a"], prefix="2,3")
sql = str(CreateFTS5Table(fts).compile(dialect=engine.dialect))
Expand Down Expand Up @@ -99,6 +155,15 @@ def test_if_exists(self, engine: Engine, metadata: MetaData) -> None:
sql = DropFTS5Table(fts, if_exists=True).compile(dialect=engine.dialect)
assert "IF EXISTS" in str(sql)

def test_quotes_table_identifier(
self, engine: Engine, metadata: MetaData
) -> None:
fts = FTS5Table("search-index", metadata, columns=["body"])

sql = DropFTS5Table(fts, if_exists=True).compile(dialect=engine.dialect)

assert str(sql) == 'DROP TABLE IF EXISTS "search-index"'


class TestMetadataCreateAll:
def test_create_all_emits_fts5_ddl(self, engine: Engine) -> None:
Expand Down
44 changes: 15 additions & 29 deletions tests/test_hypothesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,25 @@
from sqlalchemy_fts5 import CreateFTS5Table, FTS5Match, FTS5Table, fts5_bm25


# Strategy for valid FTS5 column names
column_name = st.text(
plain_identifier = st.text(
alphabet=string.ascii_lowercase + "_",
min_size=1,
max_size=20,
).filter(lambda s: s[0] != "_" and s not in ("rowid", "rank"))
).filter(lambda value: value[0] != "_")

column_names = st.lists(column_name, min_size=1, max_size=10, unique=True)

# SQLite reserved words that can't be used as unquoted identifiers
_SQLITE_RESERVED = frozenset(
"abort action add after all alter analyze and as asc attach autoincrement "
"before begin between by cascade case cast check collate column commit "
"conflict constraint create cross current current_date current_time "
"current_timestamp database default deferrable deferred delete desc detach "
"distinct do drop each else end escape except exclusive exists explain "
"fail filter first following for foreign from full generated glob group "
"having if ignore immediate in index indexed initially inner insert "
"instead intersect into is isnull join key last left like limit match "
"natural no not nothing notnull null nulls of offset on or order others "
"outer over partition plan pragma preceding primary query raise range "
"recursive references regexp reindex release rename replace restrict "
"returning right rollback row rows savepoint select set table temp "
"temporary then ties to transaction trigger unbounded union unique update "
"using vacuum values view virtual when where window with without".split()
identifier = st.one_of(
plain_identifier,
st.sampled_from(
["select", "two words", "hyphen-name", "2fast", 'quote"name', "author's"]
),
)

# Strategy for valid table names (avoid SQL reserved words)
table_name = st.text(
alphabet=string.ascii_lowercase + "_",
min_size=2,
max_size=30,
).filter(lambda s: s[0] != "_" and s not in _SQLITE_RESERVED and s not in ("rowid", "rank"))
# FTS5 reserves rowid and rank as hidden column names.
column_name = identifier.filter(lambda value: value not in ("rowid", "rank"))

column_names = st.lists(column_name, min_size=1, max_size=10, unique=True)

table_name = identifier.filter(lambda value: value not in ("rowid", "rank"))

# Strategy for FTS5 tokenizer specs
tokenizer = st.sampled_from([
Expand Down Expand Up @@ -77,9 +63,9 @@ def test_ddl_always_valid_sql(
assert sql.startswith("CREATE VIRTUAL TABLE")
assert "USING fts5(" in sql
assert sql.endswith(")")
# Every column name appears in the DDL
# Every column uses the active dialect's identifier representation.
for col in cols:
assert col in sql
assert engine.dialect.identifier_preparer.quote(col) in sql

@given(name=table_name, cols=column_names)
@settings(max_examples=30)
Expand Down
57 changes: 57 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,63 @@ def test_triggers_dropped_on_drop_all(self, engine: Engine) -> None:
assert "docs_fts_ad" not in trigger_names
assert "docs_fts_au" not in trigger_names

def test_sync_with_identifiers_requiring_quoting(self, engine: Engine) -> None:
meta = MetaData()
docs = Table(
"content table",
meta,
Column("row id", Integer, primary_key=True),
Column("title text", String),
Column("select", String),
)
fts = FTS5Table(
"search-index",
meta,
columns=["title text", "select"],
content=docs,
content_rowid="row id",
)

meta.create_all(engine)

with engine.connect() as conn:
conn.execute(
docs.insert().values(
{"row id": 1, "title text": "hello", "select": "world"}
)
)
conn.commit()
inserted = conn.execute(
select(fts.c.rowid).where(FTS5Match(fts, "hello"))
).fetchall()
assert [row.rowid for row in inserted] == [1]

conn.execute(
docs.update()
.where(docs.c["row id"] == 1)
.values({"title text": "goodbye"})
)
conn.commit()
updated = conn.execute(
select(fts.c.rowid).where(FTS5Match(fts, "goodbye"))
).fetchall()
assert [row.rowid for row in updated] == [1]

conn.execute(docs.delete().where(docs.c["row id"] == 1))
conn.commit()
deleted = conn.execute(
select(fts.c.rowid).where(FTS5Match(fts, "goodbye"))
).fetchall()
assert deleted == []

meta.drop_all(engine)

with engine.connect() as conn:
triggers = conn.execute(
text("SELECT name FROM sqlite_master WHERE type='trigger'")
).fetchall()
assert triggers == []


# ---------------------------------------------------------------------------
# ORM mapping
Expand Down