lib/pg_search/features/tsearch.rb in pg_search-0.5.1 vs lib/pg_search/features/tsearch.rb in pg_search-0.5.2

- old
+ new

@@ -1,18 +1,14 @@ require "active_support/core_ext/module/delegation" module PgSearch module Features - class TSearch + class TSearch < Feature delegate :connection, :quoted_table_name, :to => :'@model' def initialize(query, options, columns, model, normalizer) - @query = query - @options = options || {} - @model = model - @columns = columns - @normalizer = normalizer + super if @options[:prefix] && @model.connection.send(:postgresql_version) < 80400 raise PgSearch::NotSupportedForPostgresqlVersion.new(<<-MESSAGE.gsub /^\s*/, '') Sorry, {:using => {:tsearch => {:prefix => true}}} only works in PostgreSQL 8.4 and above.") MESSAGE @@ -31,45 +27,47 @@ def interpolations {:query => @query.to_s, :dictionary => dictionary.to_s} end - def document - @columns.map { |column| column.to_sql }.join(" || ' ' || ") - end - DISALLOWED_TSQUERY_CHARACTERS = /['?\\:]/ def tsquery_for_term(term) sanitized_term = term.gsub(DISALLOWED_TSQUERY_CHARACTERS, " ") - term_sql = @normalizer.add_normalization(connection.quote(sanitized_term)) + term_sql = normalize(connection.quote(sanitized_term)) # After this, the SQL expression evaluates to a string containing the term surrounded by single-quotes. # If :prefix is true, then the term will also have :* appended to the end. tsquery_sql = [ - connection.quote("' "), - term_sql, - connection.quote(" '"), - (connection.quote(':*') if @options[:prefix]) + connection.quote("' "), + term_sql, + connection.quote(" '"), + (connection.quote(':*') if @options[:prefix]) ].compact.join(" || ") "to_tsquery(:dictionary, #{tsquery_sql})" end def tsquery return "''" if @query.blank? - @query.split(" ").compact.map { |term| tsquery_for_term(term) }.join(@options[:any_word] ? ' || ' : ' && ') + query_terms = @query.split(" ").compact + tsquery_terms = query_terms.map { |term| tsquery_for_term(term) } + tsquery_terms.join(@options[:any_word] ? ' || ' : ' && ') end def tsdocument if @options[:tsvector_column] column_name = connection.quote_column_name(@options[:tsvector_column]) "#{quoted_table_name}.#{column_name}" else @columns.map do |search_column| - tsvector = "to_tsvector(:dictionary, #{@normalizer.add_normalization(search_column.to_sql)})" - search_column.weight.nil? ? tsvector : "setweight(#{tsvector}, #{connection.quote(search_column.weight)})" + tsvector = "to_tsvector(:dictionary, #{normalize(search_column.to_sql)})" + if search_column.weight.nil? + tsvector + else + "setweight(#{tsvector}, #{connection.quote(search_column.weight)})" + end end.join(" || ") end end # From http://www.postgresql.org/docs/8.3/static/textsearch-controls.html