Skip to content

Commit

Permalink
Fix bug with detect_fts() and similar table names, closes #434
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jun 14, 2022
1 parent 1b09538 commit b8af3b9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 15 deletions.
22 changes: 12 additions & 10 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2212,24 +2212,26 @@ def rebuild_fts(self):

def detect_fts(self) -> Optional[str]:
"Detect if table has a corresponding FTS virtual table and return it"
sql = (
textwrap.dedent(
"""
sql = textwrap.dedent(
"""
SELECT name FROM sqlite_master
WHERE rootpage = 0
AND (
sql LIKE '%VIRTUAL TABLE%USING FTS%content=%{table}%'
sql LIKE :like
OR sql LIKE :like2
OR (
tbl_name = "{table}"
tbl_name = :table
AND sql LIKE '%VIRTUAL TABLE%USING FTS%'
)
)
"""
)
.strip()
.format(table=self.name)
)
rows = self.db.execute(sql).fetchall()
).strip()
args = {
"like": "%VIRTUAL TABLE%USING FTS%content=[{}]%".format(self.name),
"like2": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name),
"table": self.name,
}
rows = self.db.execute(sql, args).fetchall()
if len(rows) == 0:
return None
else:
Expand Down
17 changes: 17 additions & 0 deletions tests/test_introspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ def test_detect_fts(existing_db):
assert existing_db["foo"].detect_fts() is None


@pytest.mark.parametrize("reverse_order", (True, False))
def test_detect_fts_similar_tables(fresh_db, reverse_order):
# https://github.com/simonw/sqlite-utils/issues/434
table1, table2 = ("demo", "demo2")
if reverse_order:
table1, table2 = table2, table1

fresh_db[table1].insert({"title": "Hello"}).enable_fts(
["title"], fts_version="FTS4"
)
fresh_db[table2].insert({"title": "Hello"}).enable_fts(
["title"], fts_version="FTS4"
)
assert fresh_db[table1].detect_fts() == "{}_fts".format(table1)
assert fresh_db[table2].detect_fts() == "{}_fts".format(table2)


def test_tables(existing_db):
assert 1 == len(existing_db.tables)
assert "foo" == existing_db.tables[0].name
Expand Down
15 changes: 10 additions & 5 deletions tests/test_tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,19 @@ def tracer(sql, params):
"SELECT name FROM sqlite_master\n"
" WHERE rootpage = 0\n"
" AND (\n"
" sql LIKE '%VIRTUAL TABLE%USING FTS%content=%dogs%'\n"
" sql LIKE :like\n"
" OR sql LIKE :like2\n"
" OR (\n"
' tbl_name = "dogs"\n'
" tbl_name = :table\n"
" AND sql LIKE '%VIRTUAL TABLE%USING FTS%'\n"
" )\n"
" )"
),
None,
" )",
{
"like": "%VIRTUAL TABLE%USING FTS%content=[dogs]%",
"like2": '%VIRTUAL TABLE%USING FTS%content="dogs"%',
"table": "dogs",
},
)
),
("select name from sqlite_master where type = 'view'", None),
("select sql from sqlite_master where name = ?", ("dogs_fts",)),
Expand Down

0 comments on commit b8af3b9

Please sign in to comment.