Module: ClickhouseRuby::ActiveRecord::RelationExtensions

Extended by:
ActiveSupport::Concern
Defined in:
lib/clickhouse_ruby/active_record/relation_extensions.rb

Overview

Extensions to ActiveRecord::Relation for ClickHouse-specific query methods

This module adds support for ClickHouse-specific clauses that aren’t part of standard ActiveRecord, such as PREWHERE, FINAL, SAMPLE, and SETTINGS.

These methods are mixed into ActiveRecord::Relation via the ConnectionAdapter when a ClickHouse connection is established.

Examples:

PREWHERE usage

Event.prewhere(date: Date.today).where(status: 'active')
# SELECT * FROM events PREWHERE date = '2024-01-31' WHERE status = 'active'

Defined Under Namespace

Classes: PrewhereChain

Instance Method Summary collapse

Instance Method Details

#prewhere(opts = :chain, *rest) ⇒ ActiveRecord::Relation

PREWHERE clause support

Filters data at an earlier stage than WHERE for better query optimization. ClickHouse reads only the columns needed for PREWHERE, applies the filter, then reads remaining columns for WHERE processing.

Can be called with:

  • Hash conditions: ‘prewhere(active: true, status: ’done’)‘

  • String conditions: ‘prewhere(’date > ?‘, date)`

  • Arel nodes: ‘prewhere(arel_expr)`

  • Chain syntax: ‘prewhere.not(deleted: true)`

Parameters:

  • opts (Hash, String, Arel::Nodes::Node, Symbol) (defaults to: :chain)

    the conditions

  • rest (Array)

    bind parameters for string conditions

Returns:

  • (ActiveRecord::Relation)

    self for chaining, or PrewhereChain if opts == :chain



35
36
37
38
39
40
41
42
43
44
# File 'lib/clickhouse_ruby/active_record/relation_extensions.rb', line 35

def prewhere(opts = :chain, *rest)
  case opts
  when :chain
    PrewhereChain.new(spawn)
  when nil, false
    self
  else
    spawn.prewhere!(opts, *rest)
  end
end

#prewhere!(opts, *rest) ⇒ ActiveRecord::Relation

Internal method to apply prewhere conditions

Parameters:

  • opts (Hash, String, Arel::Nodes::Node)

    the conditions

  • rest (Array)

    bind parameters

Returns:

  • (ActiveRecord::Relation)

    self



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/clickhouse_ruby/active_record/relation_extensions.rb', line 51

def prewhere!(opts, *rest)
  @prewhere_values ||= []

  case opts
  when String
    @prewhere_values << Arel.sql(sanitize_sql_array([opts, *rest]))
  when Hash
    opts.each do |key, value|
      @prewhere_values << build_prewhere_condition(key, value)
    end
  when Arel::Nodes::Node
    @prewhere_values << opts
  end

  self
end

#prewhere_valuesArray

Get the accumulated prewhere conditions

Returns:

  • (Array)

    array of prewhere condition nodes



71
72
73
# File 'lib/clickhouse_ruby/active_record/relation_extensions.rb', line 71

def prewhere_values
  @prewhere_values || []
end