clickhouse-activerecord 1.7.0 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +13 -0
- data/README.md +19 -4
- data/lib/active_record/connection_adapters/clickhouse/schema_statements.rb +114 -12
- data/lib/active_record/connection_adapters/clickhouse_adapter.rb +51 -17
- data/lib/clickhouse-activerecord/schema_dumper.rb +6 -6
- data/lib/clickhouse-activerecord/structure_dumper.rb +176 -0
- data/lib/clickhouse-activerecord/tasks.rb +3 -25
- data/lib/clickhouse-activerecord/version.rb +1 -1
- data/lib/clickhouse-activerecord.rb +6 -0
- data/lib/core_extensions/active_record/insert_all/builder.rb +13 -0
- data/lib/core_extensions/active_record/insert_all.rb +14 -0
- data/lib/core_extensions/active_record/internal_metadata.rb +1 -1
- data/lib/core_extensions/active_record/relation.rb +1 -1
- data/lib/core_extensions/active_record/schema_cache.rb +30 -0
- data/lib/core_extensions/active_record/schema_migration.rb +1 -1
- metadata +5 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 47d8bdd65d248e43d5d468827a6b936655e6c2ef11ce678cf08bf470f3fc2999
|
|
4
|
+
data.tar.gz: ac4915ec5a0ca3793e0d4e2b8ef789d7e5a7b49f7937fc9dc7ac83b944ff54e0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 5640acd1183d3c4b72338c40ddd327f49e9cef90776743ffa57fd2fb0ef26d458399d1fe1a33839425ad77cbef7975918682dc33aba7a0903fc795a68ad52bae
|
|
7
|
+
data.tar.gz: 6db5cfb93e123289441da10689b8d0d47abdc485fd9995f6c0f82f8752c7187e5b31f3a5787d9cb8f09b013a2dead37e422c24292143ba267b27a195fbd781c8
|
data/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
### Version 1.7.1 (Nov 25, 2026)
|
|
2
|
+
|
|
3
|
+
* Compare ClickHouse server versions as versions, not floats #276
|
|
4
|
+
* Order structure dump by a dependency graph #267
|
|
5
|
+
* Close the HTTP session when a request is interrupted #282
|
|
6
|
+
* Apply relation settings to `insert_all` (#279)
|
|
7
|
+
* Keep the types of settings that Rails gives as strings (#286)
|
|
8
|
+
* Round-trip schema.rb functions and structure.sql dumps (#285)
|
|
9
|
+
* Retry any statement once when its connection fails to open (#283)
|
|
10
|
+
* Keep the query cache when a read misses it (#278)
|
|
11
|
+
* Pass sslca to Net::HTTP.start so the TLS handshake uses it. (#275)
|
|
12
|
+
* Fill the schema cache with one query instead of two per table (#284)
|
|
13
|
+
|
|
1
14
|
### Version 1.7.0 (Sep 29, 2026)
|
|
2
15
|
|
|
3
16
|
* Fix structure dump table sort
|
data/README.md
CHANGED
|
@@ -38,6 +38,7 @@ default: &default
|
|
|
38
38
|
write_timeout: 300
|
|
39
39
|
keep_alive_timeout: 300
|
|
40
40
|
open_timeout: 5 # timeout for establishing the TCP connection itself, optional (Net::HTTP's default applies if unset)
|
|
41
|
+
retry_on_connect_error: true # optional, retry any statement once when the connection fails to open (default: false)
|
|
41
42
|
insecure: false # optional, skip TLS certificate verification (default: true, matching prior behavior - set to false to verify)
|
|
42
43
|
sslca: /path/to/ca.pem # optional, custom CA bundle for TLS verification
|
|
43
44
|
max_execution_time: 25 # optional, server-side query time limit in seconds, sent as a ClickHouse session setting
|
|
@@ -60,7 +61,7 @@ Optional settings can be passed as query parameters:
|
|
|
60
61
|
clickhouse://username:password@localhost:8123/database?ssl=true&http_auth=basic&read_timeout=300&write_timeout=300&keep_alive_timeout=300&open_timeout=5&debug=false&cluster_name=my_cluster
|
|
61
62
|
```
|
|
62
63
|
|
|
63
|
-
Supported query parameters: `ssl` (true/false), `debug` (true/false), `insecure` (true/false), `http_auth` (query_params/basic/x_clickhouse_headers), `open_timeout`, `read_timeout`, `write_timeout`, `keep_alive_timeout`, `max_execution_time` (integers), `cancel_http_readonly_queries_on_client_close` (true/false), `cluster_name`, `sslca`.
|
|
64
|
+
Supported query parameters: `ssl` (true/false), `debug` (true/false), `insecure` (true/false), `http_auth` (query_params/basic/x_clickhouse_headers), `open_timeout`, `read_timeout`, `write_timeout`, `keep_alive_timeout`, `max_execution_time` (integers), `cancel_http_readonly_queries_on_client_close` (true/false), `retry_on_connect_error` (true/false), `cluster_name`, `sslca`.
|
|
64
65
|
|
|
65
66
|
If both a `url` and explicit keys are provided, the explicit keys take precedence:
|
|
66
67
|
|
|
@@ -119,13 +120,22 @@ clickhouse:
|
|
|
119
120
|
take. It's optional and unset by default (`Net::HTTP`'s own default applies), unlike
|
|
120
121
|
`read_timeout`/`write_timeout` which only apply once a connection exists - a network path that
|
|
121
122
|
never completes the TCP handshake (a dead route, a security group silently dropping packets)
|
|
122
|
-
previously had no bound here at all.
|
|
123
|
+
previously had no bound here at all. It bounds each attempt to open. A read that retries below
|
|
124
|
+
can open three times (the request, the reconnect and the retry), so it can wait up to three
|
|
125
|
+
times as long.
|
|
123
126
|
- **Read queries (`SELECT`) are retried once** on a fresh connection when the failure happens
|
|
124
127
|
before the server responds at all (`Net::OpenTimeout`, `EOFError`, `ECONNRESET`, `IOError`) -
|
|
125
|
-
the kind of failure a stale pooled connection produces. Writes are
|
|
128
|
+
the kind of failure a stale pooled connection produces. Writes are not retried on these, and
|
|
126
129
|
`Net::ReadTimeout` (the server received the query and hasn't answered yet) is deliberately
|
|
127
130
|
**not** retried on any query - re-sending a query that's already loading the server doesn't
|
|
128
131
|
help. If the retry also fails, `ActiveRecord::ConnectionFailed` is raised.
|
|
132
|
+
- **`retry_on_connect_error: true`** retries every statement, a write included, once when the
|
|
133
|
+
connection fails to open (`Net::OpenTimeout`, `SocketError`, `ECONNREFUSED`). `Net::HTTP`
|
|
134
|
+
raises these before it writes the request, so the server never received it and a write is
|
|
135
|
+
safe to send again. If the connection fails to open again,
|
|
136
|
+
`ActiveRecord::ConnectionNotEstablished` is raised. It's off by default. When it's on, the read
|
|
137
|
+
retry above still covers a connection that drops, and a read reaches the server at most twice.
|
|
138
|
+
It doesn't cover the first connection, which opens when the adapter is created.
|
|
129
139
|
- **Timeouts and cancellations now raise distinct, Rails-standard error classes** instead of a
|
|
130
140
|
generic `ActiveRecord::ActiveRecordError`, so callers can `rescue` them the same way they
|
|
131
141
|
would for any other adapter:
|
|
@@ -133,7 +143,9 @@ clickhouse:
|
|
|
133
143
|
`max_execution_time` or `cancel_http_readonly_queries_on_client_close`.
|
|
134
144
|
- `ActiveRecord::AdapterTimeout` - the client gave up waiting for a response
|
|
135
145
|
(`Net::ReadTimeout`); the query may still be running server-side.
|
|
136
|
-
- `ActiveRecord::ConnectionFailed` - the
|
|
146
|
+
- `ActiveRecord::ConnectionFailed` - the read retry above failed again.
|
|
147
|
+
- `ActiveRecord::ConnectionNotEstablished` - with `retry_on_connect_error`, the connection failed
|
|
148
|
+
to open twice.
|
|
137
149
|
|
|
138
150
|
## Usage in Rails
|
|
139
151
|
|
|
@@ -275,6 +287,9 @@ Action.settings(optimize_read_in_order: 1).where(date: Date.current).limit(10)
|
|
|
275
287
|
# Clickhouse Action Load (10.3ms) SELECT actions.* FROM actions FINAL WHERE actions.date = '2017-11-29' LIMIT 10 SETTINGS optimize_read_in_order = 1
|
|
276
288
|
#=> #<ActiveRecord::Relation [#<Action *** >]>
|
|
277
289
|
|
|
290
|
+
Action.settings(async_insert: 1).insert_all([{ url: 'http://example.com', date: Date.current }])
|
|
291
|
+
# Clickhouse Action Insert (10.3ms) INSERT INTO actions (url,date) SETTINGS async_insert = 1 VALUES ('http://example.com', '2017-11-29')
|
|
292
|
+
|
|
278
293
|
User.joins(:actions).using(:group_id)
|
|
279
294
|
# Clickhouse User Load (10.3ms) SELECT users.* FROM users INNER JOIN actions USING group_id
|
|
280
295
|
#=> #<ActiveRecord::Relation [#<User *** >]>
|
|
@@ -13,9 +13,20 @@ module ActiveRecord
|
|
|
13
13
|
HTTP_AUTH_X_HEADERS = :x_clickhouse_headers
|
|
14
14
|
HTTP_AUTH_TYPES = [HTTP_AUTH_QUERY_PARAMS, HTTP_AUTH_BASIC, HTTP_AUTH_X_HEADERS].freeze
|
|
15
15
|
|
|
16
|
-
#
|
|
16
|
+
# Same threshold as `primary_keys`: before it the primary key is guessed from the column
|
|
17
|
+
# named `id`, which `system.columns` cannot reproduce.
|
|
18
|
+
BULK_SCHEMA_MIN_VERSION = Gem::Version.new('23.4')
|
|
19
|
+
|
|
20
|
+
# Connection-level failures worth a single retry of a read on a fresh connection. With
|
|
21
|
+
# `retry_on_connect_error`, `with_http_session` retries Net::OpenTimeout first, so a read sees
|
|
22
|
+
# it here only when that setting is off.
|
|
17
23
|
RETRYABLE_CONNECTION_ERRORS = [Net::OpenTimeout, EOFError, Errno::ECONNRESET, IOError].freeze
|
|
18
24
|
|
|
25
|
+
# The connection fails to open, before Net::HTTP writes the request. Nothing reached the
|
|
26
|
+
# server, so with `retry_on_connect_error` every statement, a write included, retries once
|
|
27
|
+
# on these.
|
|
28
|
+
CONNECT_ERRORS = [Net::OpenTimeout, SocketError, Errno::ECONNREFUSED].freeze
|
|
29
|
+
|
|
19
30
|
def with_settings(**settings)
|
|
20
31
|
@block_settings ||= {}
|
|
21
32
|
prev_settings = @block_settings
|
|
@@ -49,11 +60,7 @@ module ActiveRecord
|
|
|
49
60
|
end
|
|
50
61
|
|
|
51
62
|
def execute(sql, name = nil, format: response_format, settings: {})
|
|
52
|
-
|
|
53
|
-
log(sql, [adapter_name, name].compact.join(' ')) do
|
|
54
|
-
raw_execute(sql, settings: settings)
|
|
55
|
-
end
|
|
56
|
-
end
|
|
63
|
+
execute_statement(sql, name, format: format, settings: settings)
|
|
57
64
|
end
|
|
58
65
|
|
|
59
66
|
def execute_batch(statements, name = nil, **kwargs)
|
|
@@ -69,9 +76,8 @@ module ActiveRecord
|
|
|
69
76
|
log(sql, [adapter_name, 'Stream', name].compact.join(' ')) do
|
|
70
77
|
statement = Statement.new(sql, format: response_format)
|
|
71
78
|
result = nil
|
|
72
|
-
|
|
79
|
+
with_http_session do
|
|
73
80
|
req = Net::HTTP::Post.new("/?#{settings_params(settings)}", build_request_headers)
|
|
74
|
-
@connection.start unless @connection.started?
|
|
75
81
|
@connection.request(req, statement.formatted_sql) do |response|
|
|
76
82
|
result = statement.streaming_response(response)
|
|
77
83
|
end
|
|
@@ -90,7 +96,8 @@ module ActiveRecord
|
|
|
90
96
|
def internal_exec_query(sql, name = nil, binds = [], prepare: false, async: false, allow_retry: false)
|
|
91
97
|
connection_retries = 0
|
|
92
98
|
begin
|
|
93
|
-
|
|
99
|
+
# `select_all` reaches here on each cache miss, so this must not clear the cache.
|
|
100
|
+
result = execute_statement(sql, name)
|
|
94
101
|
columns = result['meta'].map { |m| m['name'] }
|
|
95
102
|
types = {}
|
|
96
103
|
result['meta'].each_with_index do |m, i|
|
|
@@ -169,10 +176,22 @@ module ActiveRecord
|
|
|
169
176
|
end
|
|
170
177
|
|
|
171
178
|
def show_create_function(function)
|
|
172
|
-
result = do_system_execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' AND name =
|
|
179
|
+
result = do_system_execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' AND name = #{quote(function)}")
|
|
173
180
|
return if result.nil?
|
|
174
181
|
|
|
175
|
-
result['data'].flatten.first
|
|
182
|
+
result['data'].flatten.first&.sub(/\ACREATE FUNCTION/, 'CREATE OR REPLACE FUNCTION')
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# The body that `create_function` takes. Raises on a definition in any other shape, because a
|
|
186
|
+
# whole statement passed back as the body fails only when it runs.
|
|
187
|
+
def function_body(function)
|
|
188
|
+
sql = show_create_function(function)
|
|
189
|
+
return if sql.nil?
|
|
190
|
+
|
|
191
|
+
match = sql.match(/\ACREATE OR REPLACE FUNCTION `?#{Regexp.escape(function)}`? AS (.*)\z/m)
|
|
192
|
+
raise ActiveRecord::ActiveRecordError, "Unexpected definition for function #{function}: #{sql}" unless match
|
|
193
|
+
|
|
194
|
+
match[1].strip
|
|
176
195
|
end
|
|
177
196
|
|
|
178
197
|
def table_options(table)
|
|
@@ -255,9 +274,26 @@ module ActiveRecord
|
|
|
255
274
|
end
|
|
256
275
|
end
|
|
257
276
|
|
|
277
|
+
# Read the columns and primary keys of every table in one request for the duration of
|
|
278
|
+
# the block. Lookups for a table inside the block are answered from that result; a table
|
|
279
|
+
# the result does not contain still falls back to its own request.
|
|
280
|
+
# Servers older than BULK_SCHEMA_MIN_VERSION keep the request per table.
|
|
281
|
+
def with_bulk_schema_load
|
|
282
|
+
return yield if @bulk_schema || Gem::Version.new(server_version) < BULK_SCHEMA_MIN_VERSION
|
|
283
|
+
|
|
284
|
+
begin
|
|
285
|
+
@bulk_schema = load_bulk_schema
|
|
286
|
+
yield
|
|
287
|
+
ensure
|
|
288
|
+
@bulk_schema = nil
|
|
289
|
+
end
|
|
290
|
+
end
|
|
291
|
+
|
|
258
292
|
protected
|
|
259
293
|
|
|
260
294
|
def table_structure(table_name)
|
|
295
|
+
return @bulk_schema[:structures][table_name] if @bulk_schema&.dig(:structures, table_name)
|
|
296
|
+
|
|
261
297
|
result = do_system_execute("DESCRIBE TABLE `#{table_name}`", table_name)
|
|
262
298
|
data = result['data']
|
|
263
299
|
|
|
@@ -281,6 +317,35 @@ module ActiveRecord
|
|
|
281
317
|
|
|
282
318
|
private
|
|
283
319
|
|
|
320
|
+
# One query for all tables. It gives what `DESCRIBE TABLE` gives for the columns (same
|
|
321
|
+
# order, ephemeral columns included) and what `SHOW COLUMNS` gives for the primary keys
|
|
322
|
+
# (alphabetical). Same table filter as `tables`.
|
|
323
|
+
def load_bulk_schema
|
|
324
|
+
result = do_system_execute(<<~SQL.squish, 'SCHEMA')
|
|
325
|
+
SELECT table, name, type, default_kind, default_expression, comment, compression_codec, is_in_primary_key
|
|
326
|
+
FROM system.columns
|
|
327
|
+
WHERE database = currentDatabase() AND table NOT LIKE '.inner_id.%'
|
|
328
|
+
ORDER BY table, position
|
|
329
|
+
SQL
|
|
330
|
+
|
|
331
|
+
schema = { structures: {}, primary_keys: {} }
|
|
332
|
+
result['data'].each do |table, name, type, default_kind, default_expression, comment, codec, in_primary_key|
|
|
333
|
+
(schema[:structures][table] ||= []) << Clickhouse::DescribedColumn.new(
|
|
334
|
+
name: name,
|
|
335
|
+
sql_type: type,
|
|
336
|
+
default_type: default_kind,
|
|
337
|
+
default_expression: default_expression,
|
|
338
|
+
comment: comment,
|
|
339
|
+
# `system.columns` wraps the codec as `CODEC(...)`, `DESCRIBE TABLE` does not
|
|
340
|
+
codec: codec.sub(/\ACODEC\((.*)\)\z/m, '\1'),
|
|
341
|
+
)
|
|
342
|
+
keys = (schema[:primary_keys][table] ||= [])
|
|
343
|
+
keys << name if in_primary_key.to_i == 1
|
|
344
|
+
end
|
|
345
|
+
schema[:primary_keys].each_value(&:sort!)
|
|
346
|
+
schema
|
|
347
|
+
end
|
|
348
|
+
|
|
284
349
|
def schema_creation
|
|
285
350
|
Clickhouse::SchemaCreation.new(self)
|
|
286
351
|
end
|
|
@@ -322,6 +387,16 @@ module ActiveRecord
|
|
|
322
387
|
(%r{\w+\(.*\)} === default)
|
|
323
388
|
end
|
|
324
389
|
|
|
390
|
+
# `execute` without the cache-clearing wrapper ClickhouseAdapter puts on it. Not named
|
|
391
|
+
# `internal_execute`: Rails calls that with positional binds and `allow_retry:`.
|
|
392
|
+
def execute_statement(sql, name = nil, format: response_format, settings: {})
|
|
393
|
+
with_response_format(format) do
|
|
394
|
+
log(sql, [adapter_name, name].compact.join(' ')) do
|
|
395
|
+
raw_execute(sql, settings: settings)
|
|
396
|
+
end
|
|
397
|
+
end
|
|
398
|
+
end
|
|
399
|
+
|
|
325
400
|
def raw_execute(sql, settings: {}, except_params: [])
|
|
326
401
|
statement = Statement.new(sql, format: response_format)
|
|
327
402
|
response = request(statement, settings: settings, except_params: except_params)
|
|
@@ -334,13 +409,40 @@ module ActiveRecord
|
|
|
334
409
|
# @param [Array] except_params
|
|
335
410
|
# @return [Net::HTTPResponse]
|
|
336
411
|
def request(statement, settings: {}, except_params: [])
|
|
337
|
-
|
|
412
|
+
with_http_session do
|
|
338
413
|
@connection.post("/?#{settings_params(settings, except: except_params)}",
|
|
339
414
|
statement.formatted_sql,
|
|
340
415
|
build_request_headers(include_database: !except_params.include?(:database)))
|
|
341
416
|
end
|
|
342
417
|
end
|
|
343
418
|
|
|
419
|
+
# The connection can fail to open in `start` or, when Net::HTTP reopens a stale keep-alive
|
|
420
|
+
# socket, inside the yielded request. Both happen before Net::HTTP writes the request, so with
|
|
421
|
+
# `retry_on_connect_error` the whole block runs again on a new session.
|
|
422
|
+
#
|
|
423
|
+
# Any other Exception, an interrupt included, also finishes the session: the reply left unread
|
|
424
|
+
# on the keep-alive socket would otherwise answer the next request.
|
|
425
|
+
def with_http_session
|
|
426
|
+
connect_retries = 0
|
|
427
|
+
@lock.synchronize do
|
|
428
|
+
begin
|
|
429
|
+
@connection.start unless @connection.started?
|
|
430
|
+
yield
|
|
431
|
+
rescue *CONNECT_ERRORS => e
|
|
432
|
+
@connection.finish if @connection.started?
|
|
433
|
+
raise unless @retry_on_connect_error
|
|
434
|
+
raise ActiveRecord::ConnectionNotEstablished, "Response: #{e.message}" if connect_retries.positive?
|
|
435
|
+
|
|
436
|
+
connect_retries += 1
|
|
437
|
+
logger&.warn("[clickhouse-activerecord] retrying statement after the connection failed to open (#{e.class}: #{e.message})")
|
|
438
|
+
retry
|
|
439
|
+
rescue Exception
|
|
440
|
+
@connection.finish if @connection.started?
|
|
441
|
+
raise
|
|
442
|
+
end
|
|
443
|
+
end
|
|
444
|
+
end
|
|
445
|
+
|
|
344
446
|
def log_with_debug(sql, name = nil)
|
|
345
447
|
return yield unless @debug
|
|
346
448
|
log(sql, "#{name} (system)") { yield }
|
|
@@ -153,17 +153,19 @@ module ActiveRecord
|
|
|
153
153
|
connection: @config[:connection]
|
|
154
154
|
}
|
|
155
155
|
else
|
|
156
|
-
|
|
156
|
+
# Rails gives the query parameters of a clickhouse:// URL, and a quoted value in database.yml,
|
|
157
|
+
# as strings, so each setting is cast where it is read.
|
|
158
|
+
port = self.class.type_cast_config_to_integer(@config[:port]) || 8123
|
|
157
159
|
connection = {
|
|
158
160
|
host: @config[:host] || 'localhost',
|
|
159
161
|
port: port,
|
|
160
|
-
ssl: @config[:ssl].
|
|
161
|
-
insecure: @config.fetch(:insecure, true),
|
|
162
|
+
ssl: @config[:ssl].to_s.empty? ? port == 443 : self.class.type_cast_config_to_boolean(@config[:ssl]),
|
|
163
|
+
insecure: self.class.type_cast_config_to_boolean(@config.fetch(:insecure, true)),
|
|
162
164
|
sslca: @config[:sslca],
|
|
163
|
-
open_timeout: @config[:open_timeout],
|
|
164
|
-
read_timeout: @config[:read_timeout],
|
|
165
|
-
write_timeout: @config[:write_timeout],
|
|
166
|
-
keep_alive_timeout: @config[:keep_alive_timeout]
|
|
165
|
+
open_timeout: self.class.type_cast_config_to_integer(@config[:open_timeout]),
|
|
166
|
+
read_timeout: self.class.type_cast_config_to_integer(@config[:read_timeout]),
|
|
167
|
+
write_timeout: self.class.type_cast_config_to_integer(@config[:write_timeout]),
|
|
168
|
+
keep_alive_timeout: self.class.type_cast_config_to_integer(@config[:keep_alive_timeout])
|
|
167
169
|
}
|
|
168
170
|
end
|
|
169
171
|
@connection_parameters = connection
|
|
@@ -172,12 +174,14 @@ module ActiveRecord
|
|
|
172
174
|
user: @config[:username],
|
|
173
175
|
password: @config[:password],
|
|
174
176
|
database: @config[:database],
|
|
175
|
-
max_execution_time: @config[:max_execution_time],
|
|
176
|
-
cancel_http_readonly_queries_on_client_close: @config[:cancel_http_readonly_queries_on_client_close],
|
|
177
|
+
max_execution_time: self.class.type_cast_config_to_integer(@config[:max_execution_time]),
|
|
178
|
+
cancel_http_readonly_queries_on_client_close: self.class.type_cast_config_to_boolean(@config[:cancel_http_readonly_queries_on_client_close]),
|
|
177
179
|
}.compact
|
|
178
|
-
@debug = @config[:debug] || false
|
|
180
|
+
@debug = self.class.type_cast_config_to_boolean(@config[:debug]) || false
|
|
179
181
|
@default_response_format = @config[:format] || DEFAULT_RESPONSE_FORMAT
|
|
180
182
|
@http_auth = @config[:http_auth]&.to_sym
|
|
183
|
+
# Rails passes the query parameters of a `clickhouse://` URL through as strings, so "false" must be cast.
|
|
184
|
+
@retry_on_connect_error = self.class.type_cast_config_to_boolean(@config[:retry_on_connect_error]) || false
|
|
181
185
|
|
|
182
186
|
@prepared_statements = false
|
|
183
187
|
|
|
@@ -262,6 +266,8 @@ module ActiveRecord
|
|
|
262
266
|
when 'max_execution_time' then config[:max_execution_time] = value.to_i
|
|
263
267
|
when 'cancel_http_readonly_queries_on_client_close'
|
|
264
268
|
config[:cancel_http_readonly_queries_on_client_close] = (value == 'true')
|
|
269
|
+
when 'retry_on_connect_error'
|
|
270
|
+
config[:retry_on_connect_error] = (value == 'true')
|
|
265
271
|
end
|
|
266
272
|
end
|
|
267
273
|
end
|
|
@@ -381,7 +387,9 @@ module ActiveRecord
|
|
|
381
387
|
# SCHEMA STATEMENTS ========================================
|
|
382
388
|
|
|
383
389
|
def primary_keys(table_name)
|
|
384
|
-
if
|
|
390
|
+
return @bulk_schema[:primary_keys][table_name] if @bulk_schema&.dig(:primary_keys, table_name)
|
|
391
|
+
|
|
392
|
+
if Gem::Version.new(server_version) >= Clickhouse::SchemaStatements::BULK_SCHEMA_MIN_VERSION
|
|
385
393
|
structure = do_system_execute("SHOW COLUMNS FROM `#{table_name}`")
|
|
386
394
|
return structure['data'].select {|m| m[3]&.include?('PRI') }.pluck(0)
|
|
387
395
|
end
|
|
@@ -399,7 +407,8 @@ module ActiveRecord
|
|
|
399
407
|
# @option [Boolean] single_line
|
|
400
408
|
# @return [String]
|
|
401
409
|
def show_create_table(table, single_line: true)
|
|
402
|
-
sql = do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first)
|
|
410
|
+
sql = do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first)
|
|
411
|
+
sql = remove_database_qualifier(sql)
|
|
403
412
|
single_line ? sql.squish : sql
|
|
404
413
|
end
|
|
405
414
|
|
|
@@ -571,7 +580,7 @@ module ActiveRecord
|
|
|
571
580
|
end
|
|
572
581
|
|
|
573
582
|
def use_default_replicated_merge_tree_params?
|
|
574
|
-
database_engine_atomic? && @config[:use_default_replicated_merge_tree_params]
|
|
583
|
+
database_engine_atomic? && self.class.type_cast_config_to_boolean(@config[:use_default_replicated_merge_tree_params])
|
|
575
584
|
end
|
|
576
585
|
|
|
577
586
|
def use_replica?
|
|
@@ -616,8 +625,7 @@ module ActiveRecord
|
|
|
616
625
|
end
|
|
617
626
|
|
|
618
627
|
def build_insert_sql(insert) # :nodoc:
|
|
619
|
-
|
|
620
|
-
sql
|
|
628
|
+
['INSERT', insert.into, insert.settings_list, insert.values_list].compact.join(' ')
|
|
621
629
|
end
|
|
622
630
|
|
|
623
631
|
protected
|
|
@@ -639,16 +647,42 @@ module ActiveRecord
|
|
|
639
647
|
|
|
640
648
|
private
|
|
641
649
|
|
|
650
|
+
# Removes the database qualifier from the names in a statement, so it loads into a database
|
|
651
|
+
# with another name. The dictionary functions (dictGet and its variants, dictHas, dictIsIn)
|
|
652
|
+
# take the dictionary name as a string, and ClickHouse qualifies that string with the current
|
|
653
|
+
# database again on CREATE, so the qualifier comes off there too. Every other string stays as
|
|
654
|
+
# it is: most are data (a default, an Enum label, a comment), and joinGet and dictionary()
|
|
655
|
+
# resolve an unqualified name against the database of the session that runs the query, not
|
|
656
|
+
# the one that created the view. A backquoted identifier stays as it is, so a database name
|
|
657
|
+
# that needs backquotes keeps its qualifier.
|
|
658
|
+
#
|
|
659
|
+
# The order of the alternatives matters: the dictionary function comes before the general
|
|
660
|
+
# string, which would otherwise match it, and each string and identifier comes before the
|
|
661
|
+
# bare qualifier.
|
|
662
|
+
def remove_database_qualifier(sql)
|
|
663
|
+
return sql if database.blank?
|
|
664
|
+
|
|
665
|
+
qualifier = Regexp.escape(database)
|
|
666
|
+
pattern = /(?<identifier>`(?:[^`\\]|\\.)*`)|(?<function>\bdict(?:Get\w*|Has|IsIn)\(\s*)'#{qualifier}\.(?<name>[^'\\]+)'|(?<string>'(?:[^'\\]|\\.)*')|(?<![\w.`])#{qualifier}\./
|
|
667
|
+
sql.gsub(pattern) do
|
|
668
|
+
match = Regexp.last_match
|
|
669
|
+
if match[:identifier] then match[:identifier]
|
|
670
|
+
elsif match[:function] then "#{match[:function]}'#{match[:name]}'"
|
|
671
|
+
elsif match[:string] then match[:string]
|
|
672
|
+
else ''
|
|
673
|
+
end
|
|
674
|
+
end
|
|
675
|
+
end
|
|
676
|
+
|
|
642
677
|
def connect
|
|
643
678
|
@connection = @connection_parameters[:connection] || Net::HTTP.start(
|
|
644
679
|
@connection_parameters[:host],
|
|
645
680
|
@connection_parameters[:port],
|
|
646
681
|
use_ssl: @connection_parameters[:ssl],
|
|
647
682
|
verify_mode: @connection_parameters[:insecure] ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER,
|
|
648
|
-
**{ open_timeout: @connection_parameters[:open_timeout] }.compact
|
|
683
|
+
**{ open_timeout: @connection_parameters[:open_timeout], ca_file: @connection_parameters[:sslca] }.compact
|
|
649
684
|
)
|
|
650
685
|
|
|
651
|
-
@connection.ca_file = @connection_parameters[:sslca] if @connection_parameters[:sslca]
|
|
652
686
|
@connection.read_timeout = @connection_parameters[:read_timeout] if @connection_parameters[:read_timeout]
|
|
653
687
|
@connection.write_timeout = @connection_parameters[:write_timeout] if @connection_parameters[:write_timeout]
|
|
654
688
|
|
|
@@ -130,13 +130,13 @@ module ClickhouseActiverecord
|
|
|
130
130
|
end
|
|
131
131
|
|
|
132
132
|
def function(function, stream)
|
|
133
|
+
body = @connection.function_body(function)
|
|
134
|
+
return if body.nil?
|
|
135
|
+
|
|
133
136
|
stream.puts " # FUNCTION: #{function}"
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
stream.puts " create_function \"#{function}\", \"#{sql.sub(/\ACREATE(OR REPLACE)? FUNCTION .*? AS/, '').strip}\", force: true"
|
|
138
|
-
stream.puts
|
|
139
|
-
end
|
|
137
|
+
stream.puts " # SQL: #{@connection.show_create_function(function)}"
|
|
138
|
+
stream.puts " create_function #{function.inspect}, #{body.inspect}, force: true"
|
|
139
|
+
stream.puts
|
|
140
140
|
end
|
|
141
141
|
|
|
142
142
|
def format_options(options)
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ClickhouseActiverecord
|
|
4
|
+
# Builds the ordered list of `CREATE` statements that makes up `structure.sql`.
|
|
5
|
+
#
|
|
6
|
+
# Rails 8 prepares an empty database by loading `structure.sql` instead of
|
|
7
|
+
# replaying every migration, so the file has to be replayable top to bottom.
|
|
8
|
+
# ClickHouse resolves a view's query when the view is created and refuses to
|
|
9
|
+
# create a materialized view whose `TO` target is missing, which a dump grouped
|
|
10
|
+
# by kind and sorted by name only satisfies by luck. Statements are therefore
|
|
11
|
+
# ordered by a dependency graph built from `system.tables` metadata and from
|
|
12
|
+
# the `CREATE` statements themselves.
|
|
13
|
+
class StructureDumper
|
|
14
|
+
Definition = Struct.new(:name, :kind, :sql, :dependencies, keyword_init: true)
|
|
15
|
+
|
|
16
|
+
KIND_RANK = %i[function table dictionary view materialized_view].freeze
|
|
17
|
+
|
|
18
|
+
KIND_PATTERNS = {
|
|
19
|
+
materialized_view: /\ACREATE\s+(?:OR\s+REPLACE\s+)?MATERIALIZED\s+VIEW\b/i,
|
|
20
|
+
view: /\ACREATE\s+(?:OR\s+REPLACE\s+)?(?:LIVE\s+|WINDOW\s+)?VIEW\b/i,
|
|
21
|
+
dictionary: /\ACREATE\s+(?:OR\s+REPLACE\s+)?DICTIONARY\b/i
|
|
22
|
+
}.freeze
|
|
23
|
+
|
|
24
|
+
NAME = /(?:`[^`]+`|[A-Za-z_]\w*)/
|
|
25
|
+
QUALIFIED_NAME = /(?:(#{NAME})\.)?(#{NAME})/
|
|
26
|
+
|
|
27
|
+
# Table functions (`FROM numbers(10)`) and `ARRAY JOIN`, whose operand is a
|
|
28
|
+
# column rather than a table, are left out.
|
|
29
|
+
FROM_OR_JOIN = /\b(?:FROM|(?<!ARRAY\s)JOIN)\s+#{QUALIFIED_NAME}(?!\s*\()/i
|
|
30
|
+
MATERIALIZED_TARGET = /\ACREATE\s+MATERIALIZED\s+VIEW\s+#{QUALIFIED_NAME}(?:\s+UUID\s+'[^']*')?\s+TO\s+#{QUALIFIED_NAME}/i
|
|
31
|
+
BUFFER_ENGINE = /\bENGINE\s*=\s*Buffer\s*\(\s*'?(#{NAME})'?\s*,\s*'?(#{NAME})'?/i
|
|
32
|
+
DICTIONARY_ENGINE = /\bENGINE\s*=\s*Dictionary\s*\(\s*'?#{QUALIFIED_NAME}'?\s*\)/i
|
|
33
|
+
|
|
34
|
+
def initialize(connection, database)
|
|
35
|
+
@connection = connection
|
|
36
|
+
@database = database
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def dump(path)
|
|
40
|
+
File.open(path, 'w:utf-8') do |file|
|
|
41
|
+
statements.each { |sql| file.puts "#{sql};\n\n" }
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def statements
|
|
46
|
+
(order(function_definitions) + order(table_definitions)).map(&:sql)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
private
|
|
50
|
+
|
|
51
|
+
def function_definitions
|
|
52
|
+
# A function dropped since `functions` listed it has no definition left to dump.
|
|
53
|
+
definitions = @connection.functions.filter_map do |name|
|
|
54
|
+
sql = @connection.show_create_function(name)
|
|
55
|
+
next if sql.nil?
|
|
56
|
+
|
|
57
|
+
Definition.new(name: name, kind: :function, sql: sql.gsub('\\n', "\n"), dependencies: Set.new)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
names = definitions.map(&:name)
|
|
61
|
+
definitions.each do |definition|
|
|
62
|
+
calls = names.select { |name| name != definition.name && definition.sql.match?(/\b#{Regexp.escape(name)}\s*\(/) }
|
|
63
|
+
definition.dependencies = Set.new(calls)
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
definitions
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def table_definitions
|
|
70
|
+
ignore_tables = ActiveRecord::SchemaDumper.ignore_tables
|
|
71
|
+
rows = table_rows.reject { |name, *| ignore_tables.any? { |pattern| pattern === name } }
|
|
72
|
+
names = Set.new(rows.map(&:first))
|
|
73
|
+
|
|
74
|
+
# `show_create_table` already removes the database qualifier.
|
|
75
|
+
definitions = rows.map do |name, *|
|
|
76
|
+
sql = @connection.show_create_table(name, single_line: false)
|
|
77
|
+
.gsub("/#{@database}/", '/{database}/')
|
|
78
|
+
Definition.new(name: name, kind: kind_of(sql), sql: sql, dependencies: Set.new)
|
|
79
|
+
end
|
|
80
|
+
by_name = definitions.index_by(&:name)
|
|
81
|
+
|
|
82
|
+
definitions.each do |definition|
|
|
83
|
+
references(definition.sql).each do |reference|
|
|
84
|
+
definition.dependencies << reference if names.include?(reference) && reference != definition.name
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
rows.each do |name, loading_databases, loading_tables, dependent_databases, dependent_tables|
|
|
89
|
+
loading_databases.zip(loading_tables).each do |database, table|
|
|
90
|
+
next unless database == @database && names.include?(table) && table != name
|
|
91
|
+
|
|
92
|
+
by_name[name].dependencies << table
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# `dependencies_*` points the other way: those objects select from `name`.
|
|
96
|
+
dependent_databases.zip(dependent_tables).each do |database, table|
|
|
97
|
+
next unless database == @database && names.include?(table) && table != name
|
|
98
|
+
|
|
99
|
+
by_name[table].dependencies << name
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
definitions
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def table_rows
|
|
107
|
+
@connection.execute(<<~SQL)['data']
|
|
108
|
+
SELECT
|
|
109
|
+
name,
|
|
110
|
+
loading_dependencies_database,
|
|
111
|
+
loading_dependencies_table,
|
|
112
|
+
dependencies_database,
|
|
113
|
+
dependencies_table
|
|
114
|
+
FROM system.tables
|
|
115
|
+
WHERE database = #{@connection.quote(@database)} AND name NOT LIKE '.inner_id.%'
|
|
116
|
+
ORDER BY name
|
|
117
|
+
SQL
|
|
118
|
+
rescue ActiveRecord::StatementInvalid
|
|
119
|
+
# `loading_dependencies_*` were added in ClickHouse 22.4.
|
|
120
|
+
@connection.execute(<<~SQL)['data'].map { |name, *dependencies| [name, [], [], *dependencies] }
|
|
121
|
+
SELECT name, dependencies_database, dependencies_table
|
|
122
|
+
FROM system.tables
|
|
123
|
+
WHERE database = #{@connection.quote(@database)} AND name NOT LIKE '.inner_id.%'
|
|
124
|
+
ORDER BY name
|
|
125
|
+
SQL
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def order(definitions)
|
|
129
|
+
pending = definitions.sort_by { |definition| [KIND_RANK.index(definition.kind), definition.name] }
|
|
130
|
+
emitted = Set.new
|
|
131
|
+
ordered = []
|
|
132
|
+
|
|
133
|
+
until pending.empty?
|
|
134
|
+
ready, pending = pending.partition { |definition| definition.dependencies.subset?(emitted) }
|
|
135
|
+
|
|
136
|
+
# Nothing is ready only when the definitions left depend on each other. A
|
|
137
|
+
# cyclic schema has no replayable order, so emit the first one and move
|
|
138
|
+
# on rather than loop forever.
|
|
139
|
+
ready, pending = [pending.first], pending.drop(1) if ready.empty?
|
|
140
|
+
|
|
141
|
+
ordered.concat(ready)
|
|
142
|
+
emitted.merge(ready.map(&:name))
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
ordered
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def kind_of(sql)
|
|
149
|
+
KIND_PATTERNS.find { |_kind, pattern| sql.match?(pattern) }&.first || :table
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def references(sql)
|
|
153
|
+
[
|
|
154
|
+
scan(sql, FROM_OR_JOIN).map { |match| qualified_name(match, 1) },
|
|
155
|
+
scan(sql, MATERIALIZED_TARGET).map { |match| qualified_name(match, 3) },
|
|
156
|
+
scan(sql, BUFFER_ENGINE).map { |match| qualified_name(match, 1) },
|
|
157
|
+
scan(sql, DICTIONARY_ENGINE).map { |match| qualified_name(match, 1) }
|
|
158
|
+
].flatten.compact
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def scan(sql, regexp)
|
|
162
|
+
sql.to_enum(:scan, regexp).map { Regexp.last_match }
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def qualified_name(match, index)
|
|
166
|
+
database = match[index]
|
|
167
|
+
return if database && unquote(database) != @database
|
|
168
|
+
|
|
169
|
+
unquote(match[index + 1])
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def unquote(name)
|
|
173
|
+
name.start_with?('`') ? name[1..-2] : name
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
end
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require 'clickhouse-activerecord/structure_dumper'
|
|
4
|
+
|
|
3
5
|
module ClickhouseActiverecord
|
|
4
6
|
class Tasks
|
|
5
7
|
delegate :connection, :establish_connection, to: ActiveRecord::Base
|
|
@@ -37,31 +39,7 @@ module ClickhouseActiverecord
|
|
|
37
39
|
def structure_dump(path, *)
|
|
38
40
|
establish_master_connection
|
|
39
41
|
|
|
40
|
-
|
|
41
|
-
functions = connection.execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' ORDER BY name")['data']
|
|
42
|
-
.flatten
|
|
43
|
-
.map { |function| function.gsub('\\n', "\n") }
|
|
44
|
-
|
|
45
|
-
# get all tables
|
|
46
|
-
table_defs = connection.execute("SHOW TABLES FROM #{@configuration.database} WHERE name NOT LIKE '.inner_id.%'")['data']
|
|
47
|
-
.flatten
|
|
48
|
-
.map { |name| connection.show_create_table(name, single_line: false).gsub("#{@configuration.database}.", '') }
|
|
49
|
-
|
|
50
|
-
# separate views from tables
|
|
51
|
-
views, tables = table_defs.partition { |sql| sql.match(/^CREATE\s+(MATERIALIZED\s+)?VIEW/) }
|
|
52
|
-
|
|
53
|
-
# separate materialized from regular views
|
|
54
|
-
mat_views, views = views.partition { |sql| sql.match(/^CREATE\s+MATERIALIZED\s+VIEW/) }
|
|
55
|
-
|
|
56
|
-
# sort: UDFs -> tables -> materialized views -> views
|
|
57
|
-
ordered_definitions = functions.sort + tables.sort + mat_views.sort + views.sort
|
|
58
|
-
|
|
59
|
-
# puts to file
|
|
60
|
-
File.open(path, 'w:utf-8') do |file|
|
|
61
|
-
ordered_definitions.each do |sql|
|
|
62
|
-
file.puts "#{sql};\n\n"
|
|
63
|
-
end
|
|
64
|
-
end
|
|
42
|
+
StructureDumper.new(connection, @configuration.database).dump(path)
|
|
65
43
|
end
|
|
66
44
|
|
|
67
45
|
def structure_load(*args)
|
|
@@ -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,9 +24,12 @@ 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)
|
|
@@ -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'}"
|
|
@@ -17,7 +17,7 @@ module CoreExtensions
|
|
|
17
17
|
self
|
|
18
18
|
end
|
|
19
19
|
|
|
20
|
-
# 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.
|
|
21
21
|
# For example:
|
|
22
22
|
#
|
|
23
23
|
# users = User.settings(optimize_read_in_order: 1, cast_keep_nullable: 1).where(name: 'John')
|
|
@@ -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.7.
|
|
4
|
+
version: 1.7.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Sergey Odintsov
|
|
@@ -127,11 +127,15 @@ files:
|
|
|
127
127
|
- lib/clickhouse-activerecord/rspec.rb
|
|
128
128
|
- lib/clickhouse-activerecord/schema.rb
|
|
129
129
|
- lib/clickhouse-activerecord/schema_dumper.rb
|
|
130
|
+
- lib/clickhouse-activerecord/structure_dumper.rb
|
|
130
131
|
- lib/clickhouse-activerecord/tasks.rb
|
|
131
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
|
|
132
135
|
- lib/core_extensions/active_record/internal_metadata.rb
|
|
133
136
|
- lib/core_extensions/active_record/migration/command_recorder.rb
|
|
134
137
|
- lib/core_extensions/active_record/relation.rb
|
|
138
|
+
- lib/core_extensions/active_record/schema_cache.rb
|
|
135
139
|
- lib/core_extensions/active_record/schema_migration.rb
|
|
136
140
|
- lib/core_extensions/arel/nodes/select_core.rb
|
|
137
141
|
- lib/core_extensions/arel/nodes/select_statement.rb
|