Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search truncates text fields silently #2436

Open
ScotterC opened this issue Sep 18, 2023 · 2 comments
Open

Search truncates text fields silently #2436

ScotterC opened this issue Sep 18, 2023 · 2 comments

Comments

@ScotterC
Copy link

ScotterC commented Sep 18, 2023

The existing search code when applied to text fields that are longer then 256 characters filters out results silently which is unexpected behavior.

Let's say you have an Post model with a content attribute that's a postgres text column. The queries below can return very different results depending on where in the content text field the query string resides.

SELECT COUNT(*) FROM "posts" WHERE "posts"."content" LIKE '%{query-string}%'
# => returns all results

SELECT COUNT(*) FROM "posts" WHERE CAST("posts"."content" AS CHAR(256)) LIKE '%{query-string}%'
# => returns only results where 'query-string' is in the first 256 characters

I would expect text fields to be as searchable as string fields.

@nickcharlton
Copy link
Member

Ah yeah, that's annoying. Do you think you'd be able to contribute a fix?

@ScotterC
Copy link
Author

ScotterC commented Dec 12, 2023

Probably won't have the time but here's the questions that would pop up

  • What's the purpose of the CHAR(256)? if the column is a text field is it necessary?
  • Does this change per database type?
  • would getting the column type and determining the solution based on string or text column be sufficient?

If the above is true then maybe something like this could work

def query_template
  search_attributes.map do |attr|
    table_name = query_table_name(attr)
    searchable_fields(attr).map do |field|
      column_name = column_to_query(field)
      column_type = model.columns_hash[column_name].type

      # Decide whether to use CHAR(256) based on column type
      cast_type = column_type == :text ? "TEXT" : "CHAR(256)"
      
      "LOWER(CAST(#{table_name}.#{column_name} AS #{cast_type})) LIKE ?"
    end.join(" OR ")
  end.join(" OR ")
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants