pg_search icon indicating copy to clipboard operation
pg_search copied to clipboard

SQL error when using pg_search in combination with eager_load or includes with references

Open kreintjes opened this issue 10 years ago • 11 comments

PgSearch's pg_search_scope option does not work when combining it with Rails' includes/eager_loads functionality (and using the associations in the query, i.e. references). The generated SQL is then invalid. I believe using pg_search then overwrites the given includes/eager_loads associations, causing the query to be invalid because it is missing the needed (left outer) join statements. I think I can best illustrate this with an example:

Suppose we have a simple setup with two models: Book and Author. A book belongs_to an author. I can search books by their title using PgSearch. For this I use the following definition: pg_search_scope :search, against: :title. I can search books by title using Book.search('sometitle'). So far so good.

Now I want to select all books with their authors not written by a Kevin: Book.includes(:author).where.not(authors: { name: 'Kevin' }).references(:author). Still so far so good.

However, now I want to combine these two, i.e. I want to search in the books not written by a Kevin and eager load their author's. The following statement does not work: Book.includes(:author).where.not(authors: { name: 'Kevin' }).references(:author).search('sometitle'). This leads to an SQL error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "authors"
LINE 1: ...search_6e317bcd6839e887739541.pg_search_id WHERE ("authors"....
                                                             ^
: SELECT "books".* FROM "books" INNER JOIN (SELECT "books"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("books"."title"::text, ''))), (to_tsquery('simple', ''' ' || 'sometitle' || ' ''')), 0)) AS rank FROM "books" WHERE (((to_tsvector('simple', coalesce("books"."title"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'sometitle' || ' '''))))) AS pg_search_6e317bcd6839e887739541 ON "books"."id" = pg_search_6e317bcd6839e887739541.pg_search_id WHERE ("authors"."name" != $1)  ORDER BY pg_search_6e317bcd6839e887739541.rank DESC, "books"."id" ASC
from /home/kevin/co2m/eq/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql_adapter.rb:637:in `prepare'

Removing the references(:author) call or using eager_load(:author) instead of includes(:author) does not work either. Any solution for this? I am running pg_search 1.0.6 in combination with Rails 4.2.5.1.

UPDATE: might be a duplicate of https://github.com/Casecommons/pg_search/issues/246 and/or https://github.com/Casecommons/pg_search/issues/229 (my own issue apparently; I am running into this again in another project).

kreintjes avatar Oct 04 '16 09:10 kreintjes

For others running into this problem: in some cases you can work around this by rewriting the query to multiple queries and using preloads instead of eager_loads. So in my example above you could rewrite Book.includes(:author).where.not(authors: { name: 'Kevin' }).references(:author).search('sometitle') to:

non_kevin_book_ids = Book.includes(:author).where.not(authors: { name: 'Kevin' }).references(:author).pluck(:id)
Book.preload(:author).where(id: non_kevin_book_ids).search('sometitle')

However this is a workaround. It causes some inefficiency (two queries instead of one) and cannot be applied to all situations (for example when you want to order the results on the author's name).

kreintjes avatar Oct 04 '16 10:10 kreintjes

The problem potentially arises from pg_search explicitly turning off all eager-loading of associations directly on the query. This has very serious performance implications (n+1) that any users of the gem should be made aware.

See: https://github.com/Casecommons/pg_search/blob/master/lib/pg_search/scope_options.rb#L28

I was able to work-around the issue by adding my own module that re-enables the eager-loading.

module EnableEagerLoading
  def eager_loading?
    true
  end
end

Comment.eager_load(:author).where(author: {id: author_id}).search("hello")# -> SQL failure
Comment.eager_load(:author).where(author: {id: author_id}).search("hello").extend(EnableEagerLoading) # Success

I believe you can accomplish the equivalent using the following monkey-patch:

module PgSearch
  class ScopeOptions
    module DisableEagerLoading
      def eager_loading?
        return true
      end
    end
  end
end

This will potentially re-introduce the bug described in the original ticket here: https://github.com/Casecommons/pg_search/issues/14 But I'm not experiencing that problem and not having eager-loading is a dealbreaker for me with this gem.

melcher avatar Jan 30 '17 22:01 melcher

I'm running into this with a joins/where combination:

# Query
@form_results
.joins(:form)
.where(forms: { type: type })
.by_form_name params[:filters]['form_name']

# Scope
pg_search_scope :by_form_name,
                  associated_against: {
                    form: %i[name]
                  },
                  using: { tsearch: { prefix: true } }

Without the search scope applied all references to forms use that reference. With the search scope applied an alias to forms AS forms_form_results is created, breaking other scopes and where conditions.

miwillhite avatar Oct 30 '17 18:10 miwillhite

Running into the same issue as @miwillhite. This was my workaround, using 2 queries:

Query:

ids = MyModel.search(params[:search]).pluck(:id)
@results = MyModel.joins(:foobar).where(id: ids, foobar: {baz: baz})

Model:

pg_search_scope :search,
  associated_against: {
    foobar: %i[name]
  },
  using: { tsearch: { prefix: true } }

sergiopantoja avatar Jul 26 '18 02:07 sergiopantoja

Hmmm, wish there were better workarounds, because if the ids array is roughly 100,000 or more records, you get a gigantic where id in (....) clause, and postgres starts having trouble.

herohhnparaiso avatar Mar 24 '19 22:03 herohhnparaiso

@herohhnparaiso You could use select instead:

search = MyModel.search(params[:search])
@results = MyModel.joins(:foobar).where(id: search.select(:id), foobar: {baz: baz})

sliminas avatar Jul 19 '19 09:07 sliminas

FYI for anyone who stumbles onto this issue: it was resolved with https://github.com/Casecommons/pg_search/commit/38b62368d5f6bb7c6623dfc32eadad6110c4b72b.

flats avatar Nov 11 '19 22:11 flats

Thanks for letting me know, @flats. Marking this as closed.

nertzy avatar Dec 02 '19 02:12 nertzy

For information, I also have this issue with version 2.3.2

damienlethiec avatar Jan 23 '20 16:01 damienlethiec

This is still happening on the latest version.

JosephTico avatar Mar 04 '21 18:03 JosephTico

Still happening now when using pg_search_scope + a scope that references the relation with a joins

Intrepidd avatar Dec 04 '23 09:12 Intrepidd