Skip to content

Instantly share code, notes, and snippets.

@tkling
Created March 30, 2023 15:03
Show Gist options
  • Save tkling/3976e6ae08e09fd2a7e005c558a85701 to your computer and use it in GitHub Desktop.
Save tkling/3976e6ae08e09fd2a7e005c558a85701 to your computer and use it in GitHub Desktop.
ActiveRecord::Relation methods for fluent force-index and index-hint query modifications with CockroachDB-specific syntax
module ActiveRecord
class Relation
def force_index(index_name, direction: nil)
directionality = direction.to_s.upcase
directionality = directionality.in?(%w[ASC DESC]) ? ",#{directionality}" : ""
@crdb_force_index = "FORCE_INDEX=#{index_name}#{directionality}"
compiled_index_hint_text
end
def index_hint(hint_lable)
@crdb_index_hint = hint_lable.to_s
compiled_index_hint_text
end
private
def compiled_index_hint_text
force_index = @crdb_force_index || ""
index_hint = @crdb_index_hint || ""
index_hint += "," if [index_hint, force_index].all?(&:present?)
self.from("#{self.quoted_table_name}@{#{index_hint + force_index}}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment