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

Avoid casting a tsvector column to text and back again. #262

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion lib/pg_search/configuration/column.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ def full_name
end

def to_sql
"coalesce(#{expression}::text, '')"
coalesce("#{expression}::text")
end

def to_sql_no_cast
coalesce(expression)
end

def tsvector?
psql_column = @model.columns_hash[name]
psql_column && psql_column.type.eql?(:tsvector)
end

private
Expand All @@ -34,6 +43,10 @@ def column_name
def expression
full_name
end

def coalesce(value)
"coalesce(#{value}, '')"
end
end
end
end
20 changes: 12 additions & 8 deletions lib/pg_search/features/tsearch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,20 @@ def columns_to_use
end

def column_to_tsvector(search_column)
tsvector = Arel::Nodes::NamedFunction.new(
"to_tsvector",
[dictionary, Arel.sql(normalize(search_column.to_sql))]
).to_sql

if search_column.weight.nil?
tsvector
if search_column.tsvector?
tsvector = Arel.sql(normalize(search_column.to_sql_no_cast))
else
"setweight(#{tsvector}, #{connection.quote(search_column.weight)})"
tsvector = Arel::Nodes::NamedFunction.new(
"to_tsvector",
[dictionary, Arel.sql(normalize(search_column.to_sql))]
).to_sql
end

if search_column.weight
tsvector = "setweight(#{tsvector}, #{connection.quote(search_column.weight)})"
end

tsvector
end
end
end
Expand Down