Skip to content

Commit

Permalink
feat: add update_rows parameter to sync_trigger()
Browse files Browse the repository at this point in the history
  • Loading branch information
scribu authored and jpvanhal committed Feb 19, 2024
1 parent 178993d commit 86227ec
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -10,6 +10,8 @@ Unreleased
- Add support for PostgreSQL 16
- Allow specifying schema in ``drop_trigger`` and ``sync_trigger`` (#95, pull
request by @acarapetis)
- Add ``update_rows`` parameter to ``sync_trigger`` (#76, pull request by
@scribu)

2.0.0 (2023-08-28)
^^^^^^^^^^^^^^^^^^
Expand Down
14 changes: 10 additions & 4 deletions sqlalchemy_searchable/__init__.py
Expand Up @@ -296,6 +296,7 @@ def sync_trigger(
metadata=None,
options=None,
schema=None,
update_rows=True,
):
"""Synchronize the search trigger and trigger function for the given table and
search vector column. Internally, this function executes the following SQL
Expand Down Expand Up @@ -380,6 +381,9 @@ def hstore_vectorizer(column):
Table. If None is given, then a new MetaData object is initialized within
this function.
:param options: Dictionary of configuration options
:param update_rows:
If set to False, the values in the vector column will remain unchanged
until one of the indexed columns is updated.
"""
if metadata is None:
metadata = sa.MetaData()
Expand All @@ -402,10 +406,12 @@ def hstore_vectorizer(column):
]
for class_ in classes:
conn.execute(class_(**params))
update_sql = table.update().values(
{indexed_columns[0]: sa.text(indexed_columns[0])}
)
conn.execute(update_sql)

if update_rows:
update_sql = table.update().values(
{indexed_columns[0]: sa.text(indexed_columns[0])}
)
conn.execute(update_sql)


def drop_trigger(
Expand Down
29 changes: 29 additions & 0 deletions tests/test_sync_trigger.py
Expand Up @@ -126,6 +126,35 @@ def test_updates_column_values(self, engine, ts_vector_options):
vector = conn.execute(text("SELECT search_vector FROM article")).scalar()
assert vector == "'content':2"

def test_does_not_update_column_values_when_updating_rows_disabled(
self, engine, ts_vector_options
):
with engine.begin() as conn:
sync_trigger(
conn,
"article",
"search_vector",
["name", "content"],
options=ts_vector_options,
)
conn.execute(
text(
"""INSERT INTO article (name, content)
VALUES ('some name', 'some content')"""
)
)
conn.execute(text("ALTER TABLE article DROP COLUMN name"))
sync_trigger(
conn,
"article",
"search_vector",
["content"],
options=ts_vector_options,
update_rows=False,
)
vector = conn.execute(text("SELECT search_vector FROM article")).scalar()
assert vector == "'content':4 'name':2"

def test_custom_vectorizers(sel, Base, engine, session, ts_vector_options):
articles = sa.Table(
"article",
Expand Down

0 comments on commit 86227ec

Please sign in to comment.