clickhouse-activerecord 1.6.7 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,11 @@
2
2
 
3
3
  require 'active_record/connection_adapters/clickhouse_adapter'
4
4
 
5
+ require 'core_extensions/active_record/insert_all'
6
+ require 'core_extensions/active_record/insert_all/builder'
5
7
  require 'core_extensions/active_record/internal_metadata'
6
8
  require 'core_extensions/active_record/relation'
9
+ require 'core_extensions/active_record/schema_cache'
7
10
  require 'core_extensions/active_record/schema_migration'
8
11
  require 'core_extensions/active_record/migration/command_recorder'
9
12
  require 'core_extensions/arel/nodes/select_core'
@@ -21,14 +24,27 @@ end
21
24
 
22
25
  module ClickhouseActiverecord
23
26
  def self.load
27
+ ActiveRecord::InsertAll.prepend(CoreExtensions::ActiveRecord::InsertAll)
28
+ ActiveRecord::InsertAll::Builder.prepend(CoreExtensions::ActiveRecord::InsertAll::Builder)
24
29
  ActiveRecord::InternalMetadata.prepend(CoreExtensions::ActiveRecord::InternalMetadata)
25
30
  ActiveRecord::Migration::CommandRecorder.include(CoreExtensions::ActiveRecord::Migration::CommandRecorder)
26
31
  ActiveRecord::Relation.prepend(CoreExtensions::ActiveRecord::Relation)
32
+ ActiveRecord::ConnectionAdapters::SchemaCache.prepend(CoreExtensions::ActiveRecord::SchemaCache)
27
33
  ActiveRecord::SchemaMigration.prepend(CoreExtensions::ActiveRecord::SchemaMigration)
28
34
 
29
35
  Arel::Nodes::SelectCore.prepend(CoreExtensions::Arel::Nodes::SelectCore)
30
36
  Arel::Nodes::SelectStatement.prepend(CoreExtensions::Arel::Nodes::SelectStatement)
31
37
  Arel::SelectManager.prepend(CoreExtensions::Arel::SelectManager)
32
38
  Arel::Table.prepend(CoreExtensions::Arel::Table)
39
+
40
+ # Prevent TimeZoneConverter wrapping for Map OID with DateTime subtype.
41
+ # Map(String, DateTime) would crash with "Hash values are not supported"
42
+ # when TimeZoneConverter tries to convert Hash values.
43
+ ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods.prepend(Module.new do
44
+ def create_time_zone_conversion_attribute?(name, cast_type)
45
+ return false if cast_type.is_a?(ActiveRecord::ConnectionAdapters::Clickhouse::OID::Map)
46
+ super
47
+ end
48
+ end)
33
49
  end
34
50
  end
@@ -0,0 +1,13 @@
1
+ module CoreExtensions
2
+ module ActiveRecord
3
+ module InsertAll
4
+ module Builder
5
+
6
+ def settings_list
7
+ settings = insert_all.settings_values
8
+ connection.visitor.compile(::Arel::Nodes::Settings.new(settings)) unless settings.empty?
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,14 @@
1
+ module CoreExtensions
2
+ module ActiveRecord
3
+ module InsertAll
4
+
5
+ # The `Relation#settings_values` of the relation that runs the insert.
6
+ # Rails 7.1 builds InsertAll from the model inside the relation's `scoping` block and keeps no
7
+ # relation, so `model.all` gives that relation back, the same way it gives one to Rails 7.2.
8
+ def settings_values
9
+ relation = ::ActiveRecord::version >= Gem::Version.new('7.2') ? @relation : model.all
10
+ relation.settings_values
11
+ end
12
+ end
13
+ end
14
+ end
@@ -14,7 +14,7 @@ module CoreExtensions
14
14
  }
15
15
  full_config = connection.instance_variable_get(:@config) || {}
16
16
 
17
- if full_config[:distributed_service_tables]
17
+ if connection.class.type_cast_config_to_boolean(full_config[:distributed_service_tables])
18
18
  table_options.merge!(with_distributed: table_name, sharding_key: 'cityHash64(created_at)')
19
19
 
20
20
  distributed_suffix = "_#{full_config[:distributed_service_tables_suffix] || 'distributed'}"
@@ -3,11 +3,12 @@ module CoreExtensions
3
3
  module Relation
4
4
 
5
5
  def self.prepended(base)
6
- base::VALID_UNSCOPING_VALUES << :final << :settings
6
+ base::VALID_UNSCOPING_VALUES << :final << :settings << :joins_final
7
7
  end
8
8
 
9
9
  def reverse_order!
10
- return super unless connection.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)
10
+ conn = respond_to?(:lease_connection) ? lease_connection : connection
11
+ return super unless conn.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)
11
12
 
12
13
  orders = order_values.uniq.reject(&:blank?)
13
14
  return super unless orders.empty? && !primary_key
@@ -16,7 +17,7 @@ module CoreExtensions
16
17
  self
17
18
  end
18
19
 
19
- # Define settings in the SETTINGS clause of the SELECT query. The setting value is applied only to that query and is reset to the default or previous value after the query is executed.
20
+ # Define settings in the SETTINGS clause of the SELECT or INSERT query. The setting value is applied only to that query and is reset to the default or previous value after the query is executed.
20
21
  # For example:
21
22
  #
22
23
  # users = User.settings(optimize_read_in_order: 1, cast_keep_nullable: 1).where(name: 'John')
@@ -90,6 +91,79 @@ module CoreExtensions
90
91
  @values.fetch(:final, nil)
91
92
  end
92
93
 
94
+ # Apply the FINAL modifier to one or more joined tables. Unlike #final,
95
+ # which only adds FINAL to the query's primary FROM table, #joins_final
96
+ # adds the join(s) and renders FINAL on the joined table so ClickHouse
97
+ # merges those rows before joining.
98
+ # For example:
99
+ #
100
+ # AppControlEvent.final.joins_final(:espm_binary)
101
+ # # SELECT ... FROM espm_app_control_events FINAL
102
+ # # INNER JOIN espm_binaries FINAL ON ...
103
+ #
104
+ # Each argument is an association name and is added as a join (like
105
+ # #joins); FINAL is then rendered on the joined table. Joins are matched
106
+ # by table name, so if the same table is joined more than once every join
107
+ # of that table receives FINAL. An
108
+ # <tt>ActiveRecord::ActiveRecordError</tt> will be raised if the database
109
+ # is not ClickHouse.
110
+ #
111
+ # @param [Array] args
112
+ def joins_final(*args)
113
+ spawn.joins_final!(*args)
114
+ end
115
+
116
+ # @param [Array] args
117
+ def joins_final!(*args)
118
+ check_command!('FINAL')
119
+ joins!(*args)
120
+ self.joins_final_values |= args
121
+ self
122
+ end
123
+
124
+ # Like #joins_final, but adds the join(s) as LEFT OUTER JOINs (via
125
+ # #left_outer_joins) and renders FINAL on the joined table. Use this when
126
+ # the joined rows must be preserved even with no match (e.g. an optional
127
+ # catalog lookup) while still merging the joined table with FINAL.
128
+ # For example:
129
+ #
130
+ # AppControlEvent.left_joins_final(:espm_binary)
131
+ # # SELECT ... FROM espm_app_control_events
132
+ # # LEFT OUTER JOIN espm_binaries FINAL ON ...
133
+ #
134
+ # Each argument is an association name and is added as a left outer join
135
+ # (like #left_outer_joins); FINAL is then rendered on the joined table.
136
+ # Joins are matched by table name, so if the same table is joined more
137
+ # than once every join of that table receives FINAL. An
138
+ # <tt>ActiveRecord::ActiveRecordError</tt> will be raised if the database
139
+ # is not ClickHouse.
140
+ #
141
+ # @param [Array] args
142
+ def left_joins_final(*args)
143
+ spawn.left_joins_final!(*args)
144
+ end
145
+
146
+ # @param [Array] args
147
+ def left_joins_final!(*args)
148
+ check_command!('FINAL')
149
+ left_outer_joins!(*args)
150
+ self.joins_final_values |= args
151
+ self
152
+ end
153
+
154
+ def joins_final_values
155
+ @values.fetch(:joins_final, ::ActiveRecord::QueryMethods::FROZEN_EMPTY_ARRAY)
156
+ end
157
+
158
+ def joins_final_values=(value)
159
+ if ::ActiveRecord::version >= Gem::Version.new('7.2')
160
+ assert_modifiable!
161
+ else
162
+ assert_mutability!
163
+ end
164
+ @values[:joins_final] = value
165
+ end
166
+
93
167
  # GROUPING SETS allows you to specify multiple groupings in the GROUP BY clause.
94
168
  # Whereas GROUP BY CUBE generates all possible groupings, GROUP BY GROUPING SETS generates only the specified groupings.
95
169
  # For example:
@@ -175,6 +249,50 @@ module CoreExtensions
175
249
  raise ::ActiveRecord::ActiveRecordError, cmd + ' is a ClickHouse specific query clause' unless connection.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)
176
250
  end
177
251
 
252
+ # Wrap the left (table) side of every join source that matches a
253
+ # requested #joins_final argument in an Arel::Nodes::FinalTable so the
254
+ # ClickHouse visitor renders FINAL on that join. Called before
255
+ # +arel.final!+ so the join source is still the plain JoinSource (and not
256
+ # yet wrapped in the FROM-level Final node).
257
+ def mark_final_joins!(arel)
258
+ names = final_join_table_names
259
+ return if names.empty?
260
+
261
+ arel.join_sources.each do |join|
262
+ next unless join.respond_to?(:left) && join.respond_to?(:left=)
263
+
264
+ left = join.left
265
+ next if left.is_a?(::Arel::Nodes::FinalTable)
266
+ next unless final_join_match?(left, names)
267
+
268
+ join.left = ::Arel::Nodes::FinalTable.new(left)
269
+ end
270
+ end
271
+
272
+ # Resolve the #joins_final arguments to the set of table names that
273
+ # should carry FINAL. Association names are mapped to their table;
274
+ # anything else is treated as a literal table name.
275
+ def final_join_table_names
276
+ joins_final_values.flatten.filter_map do |arg|
277
+ case arg
278
+ when Symbol, String
279
+ reflection = klass.reflect_on_association(arg.to_sym)
280
+ reflection ? reflection.table_name : arg.to_s
281
+ end
282
+ end.to_set
283
+ end
284
+
285
+ # Does the join's table source match one of the requested FINAL names?
286
+ # Handles both Arel::Table (name) and Arel::Nodes::TableAlias (alias name
287
+ # plus the underlying relation's name).
288
+ def final_join_match?(left, names)
289
+ candidates = []
290
+ candidates << left.name if left.respond_to?(:name)
291
+ candidates << left.table_alias if left.respond_to?(:table_alias) && left.table_alias
292
+ candidates << left.relation.name if left.respond_to?(:relation) && left.relation.respond_to?(:name)
293
+ candidates.any? { |c| names.include?(c.to_s) }
294
+ end
295
+
178
296
  def build_arel(connection_or_aliases = nil, aliases = nil)
179
297
  requirement = Gem::Requirement.new('>= 7.2', '< 8.1')
180
298
 
@@ -184,6 +302,7 @@ module CoreExtensions
184
302
  arel = super(connection_or_aliases)
185
303
  end
186
304
 
305
+ mark_final_joins!(arel) if joins_final_values.present?
187
306
  arel.final! if final_value
188
307
  arel.limit_by(*@values[:limit_by]) if @values[:limit_by].present?
189
308
  arel.settings(settings_values) unless settings_values.empty?
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CoreExtensions
4
+ module ActiveRecord
5
+ module SchemaCache
6
+ # Filling the whole cache (for example `db:schema:cache:dump`) asks for the columns
7
+ # and primary keys of every table. For ClickHouse, read them all in one request
8
+ # instead of two requests per table. Other adapters are not affected.
9
+ #
10
+ # Rails 7.1 passes a connection to `add_all`. Rails 7.2 and later pass a pool.
11
+ def add_all(pool_or_connection)
12
+ if pool_or_connection.is_a?(::ActiveRecord::ConnectionAdapters::AbstractAdapter)
13
+ with_bulk_schema_load_on(pool_or_connection) { super(pool_or_connection) }
14
+ else
15
+ pool_or_connection.with_connection do |connection|
16
+ with_bulk_schema_load_on(connection) { super(pool_or_connection) }
17
+ end
18
+ end
19
+ end
20
+
21
+ private
22
+
23
+ def with_bulk_schema_load_on(connection, &block)
24
+ return yield unless connection.respond_to?(:with_bulk_schema_load)
25
+
26
+ connection.with_bulk_schema_load(&block)
27
+ end
28
+ end
29
+ end
30
+ end
@@ -13,7 +13,7 @@ module CoreExtensions
13
13
  }
14
14
  full_config = connection.instance_variable_get(:@config) || {}
15
15
 
16
- if full_config[:distributed_service_tables]
16
+ if connection.class.type_cast_config_to_boolean(full_config[:distributed_service_tables])
17
17
  table_options.merge!(with_distributed: table_name, sharding_key: 'cityHash64(version)')
18
18
 
19
19
  distributed_suffix = "_#{full_config[:distributed_service_tables_suffix] || 'distributed'}"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: clickhouse-activerecord
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.6.7
4
+ version: 1.7.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sergey Odintsov
@@ -96,12 +96,14 @@ files:
96
96
  - Rakefile
97
97
  - bin/console
98
98
  - bin/setup
99
+ - bin/test-single
99
100
  - clickhouse-activerecord.gemspec
100
101
  - lib/active_record/connection_adapters/clickhouse/column.rb
101
102
  - lib/active_record/connection_adapters/clickhouse/oid/array.rb
102
103
  - lib/active_record/connection_adapters/clickhouse/oid/big_integer.rb
103
104
  - lib/active_record/connection_adapters/clickhouse/oid/date.rb
104
105
  - lib/active_record/connection_adapters/clickhouse/oid/date_time.rb
106
+ - lib/active_record/connection_adapters/clickhouse/oid/json.rb
105
107
  - lib/active_record/connection_adapters/clickhouse/oid/map.rb
106
108
  - lib/active_record/connection_adapters/clickhouse/oid/uuid.rb
107
109
  - lib/active_record/connection_adapters/clickhouse/quoting.rb
@@ -113,6 +115,7 @@ files:
113
115
  - lib/active_record/connection_adapters/clickhouse/table_definition.rb
114
116
  - lib/active_record/connection_adapters/clickhouse_adapter.rb
115
117
  - lib/arel/nodes/final.rb
118
+ - lib/arel/nodes/final_table.rb
116
119
  - lib/arel/nodes/grouping_sets.rb
117
120
  - lib/arel/nodes/limit_by.rb
118
121
  - lib/arel/nodes/settings.rb
@@ -124,11 +127,15 @@ files:
124
127
  - lib/clickhouse-activerecord/rspec.rb
125
128
  - lib/clickhouse-activerecord/schema.rb
126
129
  - lib/clickhouse-activerecord/schema_dumper.rb
130
+ - lib/clickhouse-activerecord/structure_dumper.rb
127
131
  - lib/clickhouse-activerecord/tasks.rb
128
132
  - lib/clickhouse-activerecord/version.rb
133
+ - lib/core_extensions/active_record/insert_all.rb
134
+ - lib/core_extensions/active_record/insert_all/builder.rb
129
135
  - lib/core_extensions/active_record/internal_metadata.rb
130
136
  - lib/core_extensions/active_record/migration/command_recorder.rb
131
137
  - lib/core_extensions/active_record/relation.rb
138
+ - lib/core_extensions/active_record/schema_cache.rb
132
139
  - lib/core_extensions/active_record/schema_migration.rb
133
140
  - lib/core_extensions/arel/nodes/select_core.rb
134
141
  - lib/core_extensions/arel/nodes/select_statement.rb
@@ -153,7 +160,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
153
160
  - !ruby/object:Gem::Version
154
161
  version: '0'
155
162
  requirements: []
156
- rubygems_version: 4.0.6
163
+ rubygems_version: 4.0.9
157
164
  specification_version: 4
158
165
  summary: ClickHouse ActiveRecord
159
166
  test_files: []