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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 48ec3fe01120adc07f02f2f8c8ff989d8866f8ce054efff32e63940e13dbc29c
4
- data.tar.gz: 28f2c0189a4ef073849ea84bae2bb900bdd6c2e59014730e6a683714209f1b88
3
+ metadata.gz: 47d8bdd65d248e43d5d468827a6b936655e6c2ef11ce678cf08bf470f3fc2999
4
+ data.tar.gz: ac4915ec5a0ca3793e0d4e2b8ef789d7e5a7b49f7937fc9dc7ac83b944ff54e0
5
5
  SHA512:
6
- metadata.gz: 940ae4fc464c3bd1526a1c9694ed7ce21496e76dfea85127ad3c37a3cc2aa09661b67e4ad3ec9f640c009ac032106f5c99d70afdcb03c7d0ecc7b6511a1d2523
7
- data.tar.gz: c98f507ba8e99e0096251eeff287f18259e2568b62fb60f8cc10385943c18b4877bae0b518c2ba4389af04a965885c4a04b171e033fd15ac38b3e6742d828c07
6
+ metadata.gz: 5640acd1183d3c4b72338c40ddd327f49e9cef90776743ffa57fd2fb0ef26d458399d1fe1a33839425ad77cbef7975918682dc33aba7a0903fc795a68ad52bae
7
+ data.tar.gz: 6db5cfb93e123289441da10689b8d0d47abdc485fd9995f6c0f82f8752c7187e5b31f3a5787d9cb8f09b013a2dead37e422c24292143ba267b27a195fbd781c8
@@ -32,10 +32,10 @@ jobs:
32
32
  rails: 7.2.3
33
33
  - ruby: 4.0
34
34
  rails: 8.1
35
- clickhouse: [ '24.6', '24.9', '25.10' ]
35
+ clickhouse: [ '24.9', '25.10' ]
36
36
 
37
37
  steps:
38
- - uses: actions/checkout@v4
38
+ - uses: actions/checkout@v6
39
39
 
40
40
  - name: Start ClickHouse ${{ matrix.clickhouse }}
41
41
  uses: hoverkraft-tech/compose-action@v2.5.0
@@ -82,7 +82,7 @@ jobs:
82
82
  clickhouse: [ '24.9', '25.10' ]
83
83
 
84
84
  steps:
85
- - uses: actions/checkout@v4
85
+ - uses: actions/checkout@v6
86
86
 
87
87
  - name: Start ClickHouse Cluster ${{ matrix.clickhouse }}
88
88
  uses: hoverkraft-tech/compose-action@v2.5.0
data/CHANGELOG.md CHANGED
@@ -1,3 +1,38 @@
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
+
14
+ ### Version 1.7.0 (Sep 29, 2026)
15
+
16
+ * Fix structure dump table sort
17
+ * Add configurable HTTP auth modes for ClickHouse requests in #240
18
+ * Parse column `DEFAULT` kinds in #246
19
+ * Honor unsigned: false on integer columns without a limit in #253
20
+ * Fix `@response_format` thread race in `with_response_format` in #251
21
+ * Implement URL-based configuration in #249
22
+ * Rails 8 compatibility fixes in #245
23
+ * Update specs in #244
24
+ * Add Float and Bool subtype support for Map OID in #237
25
+ * Fix TimeZoneConverter crash for Map OID attributes in #238
26
+ * Fix Map OID deserialize crash for already-parsed Date/DateTime values in #239
27
+ * Fix multi-column indexes in schema dumper in #234
28
+ * Use `lease_connection` instead of `connection` for Rails 7.2+ in #262
29
+ * Harden HTTP connection: open_timeout, TLS verification, retry, query limits in #266
30
+ * Detect Array columns via Column#array in #260
31
+ * Round-trip Float64 columns through the schema dumper in #269
32
+ * Add support for FINAL when joining tables in #261
33
+ * Clear the query cache when a raw statement writes in #271
34
+ * Treat DEFAULT NULL as a nil column default in #272
35
+
1
36
  ### Version 1.6.7 (Mar 5, 2026)
2
37
 
3
38
  * Fix insert with default values in Ruby 4.0 and Rails 8.1
data/README.md CHANGED
@@ -28,14 +28,48 @@ default: &default
28
28
  port: 8123
29
29
  username: username
30
30
  password: password
31
+ http_auth: query_params # optional, supports query_params, basic, x_clickhouse_headers
31
32
  ssl: true # optional for using ssl connection
32
33
  debug: true # use for showing in to log technical information
33
- migrations_paths: db/clickhouse # optional, default: db/migrate_clickhouse
34
+ migrations_paths: db/clickhouse # optional
34
35
  cluster_name: 'cluster_name' # optional for creating tables in cluster
35
36
  replica_name: '{replica}' # replica macros name, optional for creating replicated tables
36
37
  read_timeout: 300 # change network timeouts, by default 60 seconds
37
38
  write_timeout: 300
38
39
  keep_alive_timeout: 300
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)
42
+ insecure: false # optional, skip TLS certificate verification (default: true, matching prior behavior - set to false to verify)
43
+ sslca: /path/to/ca.pem # optional, custom CA bundle for TLS verification
44
+ max_execution_time: 25 # optional, server-side query time limit in seconds, sent as a ClickHouse session setting
45
+ cancel_http_readonly_queries_on_client_close: true # optional, tell the server to abort a SELECT once the client disconnects
46
+ ```
47
+
48
+ ### URL-based configuration
49
+
50
+ You can configure the adapter with a single `url` key instead of individual fields:
51
+
52
+ ```yml
53
+ default: &default
54
+ adapter: clickhouse
55
+ url: clickhouse://username:password@localhost:8123/database
56
+ ```
57
+
58
+ Optional settings can be passed as query parameters:
59
+
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
62
+ ```
63
+
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`.
65
+
66
+ If both a `url` and explicit keys are provided, the explicit keys take precedence:
67
+
68
+ ```yml
69
+ default: &default
70
+ adapter: clickhouse
71
+ url: clickhouse://username:password@localhost:8123/database
72
+ host: production.db.internal # overrides the host from the URL
39
73
  ```
40
74
 
41
75
  Alternatively if you wish to pass a custom `Net::HTTP` transport (or any other
@@ -53,6 +87,66 @@ class ActionView < ActiveRecord::Base
53
87
  end
54
88
  ```
55
89
 
90
+ ### HTTP authentication mode
91
+
92
+ By default, the adapter sends `user` and `password` as URL parameters.
93
+ You can set `http_auth` explicitly (or omit it and keep the same default behavior):
94
+
95
+ ```yml
96
+ clickhouse:
97
+ adapter: clickhouse
98
+ host: localhost
99
+ port: 8123
100
+ database: my_db
101
+ username: app_user
102
+ password: secret
103
+ http_auth: x_clickhouse_headers # or basic / query_params
104
+ ```
105
+
106
+ - Use YAML string values: `http_auth: query_params`, `http_auth: basic`, or `http_auth: x_clickhouse_headers`.
107
+ - Both strings and Ruby symbols are accepted internally.
108
+ - `http_auth: x_clickhouse_headers` sends `X-ClickHouse-User`, `X-ClickHouse-Key`, and `X-ClickHouse-Database` headers.
109
+ - `http_auth: basic` sends `Authorization: Basic ...` and keeps `database` in URL params.
110
+ - `http_auth: query_params` sends `user`, `password`, and `database` in URL params (same as omitting `http_auth`).
111
+
112
+ ### Connection hardening
113
+
114
+ - **TLS verification is now configurable.** Every connection has always been made with
115
+ `verify_mode: OpenSSL::SSL::VERIFY_NONE`, so an SSL connection to ClickHouse never actually
116
+ checked the server's certificate. That remains the default (`insecure: true`) to avoid
117
+ breaking existing setups; set `insecure: false` to turn verification on, optionally with
118
+ `sslca` pointing at your CA bundle.
119
+ - **`open_timeout`** bounds how long establishing the underlying TCP connection is allowed to
120
+ take. It's optional and unset by default (`Net::HTTP`'s own default applies), unlike
121
+ `read_timeout`/`write_timeout` which only apply once a connection exists - a network path that
122
+ never completes the TCP handshake (a dead route, a security group silently dropping packets)
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.
126
+ - **Read queries (`SELECT`) are retried once** on a fresh connection when the failure happens
127
+ before the server responds at all (`Net::OpenTimeout`, `EOFError`, `ECONNRESET`, `IOError`) -
128
+ the kind of failure a stale pooled connection produces. Writes are not retried on these, and
129
+ `Net::ReadTimeout` (the server received the query and hasn't answered yet) is deliberately
130
+ **not** retried on any query - re-sending a query that's already loading the server doesn't
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.
139
+ - **Timeouts and cancellations now raise distinct, Rails-standard error classes** instead of a
140
+ generic `ActiveRecord::ActiveRecordError`, so callers can `rescue` them the same way they
141
+ would for any other adapter:
142
+ - `ActiveRecord::StatementTimeout` - the server killed the query server-side, via
143
+ `max_execution_time` or `cancel_http_readonly_queries_on_client_close`.
144
+ - `ActiveRecord::AdapterTimeout` - the client gave up waiting for a response
145
+ (`Net::ReadTimeout`); the query may still be running server-side.
146
+ - `ActiveRecord::ConnectionFailed` - the read retry above failed again.
147
+ - `ActiveRecord::ConnectionNotEstablished` - with `retry_on_connect_error`, the connection failed
148
+ to open twice.
149
+
56
150
  ## Usage in Rails
57
151
 
58
152
  Add your `database.yml` connection information with postfix `_clickhouse` for you environment:
@@ -193,10 +287,20 @@ Action.settings(optimize_read_in_order: 1).where(date: Date.current).limit(10)
193
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
194
288
  #=> #<ActiveRecord::Relation [#<Action *** >]>
195
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
+
196
293
  User.joins(:actions).using(:group_id)
197
294
  # Clickhouse User Load (10.3ms) SELECT users.* FROM users INNER JOIN actions USING group_id
198
295
  #=> #<ActiveRecord::Relation [#<User *** >]>
199
296
 
297
+ # `final` only applies the FINAL modifier to the primary FROM table. Use
298
+ # `joins_final` to also apply FINAL to a joined table (the join is added for
299
+ # you, like `joins`). Pass association names; joins are matched by table name.
300
+ User.final.joins_final(:actions)
301
+ # Clickhouse User Load (10.3ms) SELECT users.* FROM users FINAL INNER JOIN actions FINAL ON actions.user_id = users.id
302
+ #=> #<ActiveRecord::Relation [#<User *** >]>
303
+
200
304
  User.window('x', order: 'date', partition: 'name', rows: 'UNBOUNDED PRECEDING').select('sum(value) OVER x')
201
305
  # SELECT sum(value) OVER x FROM users WINDOW x AS (PARTITION BY name ORDER BY date ROWS UNBOUNDED PRECEDING)
202
306
  #=> #<ActiveRecord::Relation [#<User *** >]>
@@ -343,6 +447,38 @@ Donations to this project are going directly to [PNixx](https://github.com/PNixx
343
447
 
344
448
  After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
345
449
 
450
+ ### Run locally
451
+
452
+ 1. Start ClickHouse (single node):
453
+
454
+ ```bash
455
+ docker compose -f .docker/docker-compose.yml up -d
456
+ ```
457
+
458
+ 2. Run single-node specs:
459
+
460
+ ```bash
461
+ bin/test-single
462
+ ```
463
+
464
+ If your local workflow expects `bin/single_test`, use the same command format as `bin/test-single`:
465
+
466
+ ```bash
467
+ CLICKHOUSE_PORT=18123 CLICKHOUSE_DATABASE=default bundle exec rspec spec/single --format progress
468
+ ```
469
+
470
+ 3. Start ClickHouse cluster:
471
+
472
+ ```bash
473
+ docker compose -f .docker/docker-compose.cluster.yml up -d
474
+ ```
475
+
476
+ 4. Run cluster specs:
477
+
478
+ ```bash
479
+ CLICKHOUSE_PORT=28123 CLICKHOUSE_DATABASE=default CLICKHOUSE_CLUSTER=test_cluster bundle exec rspec spec/cluster --format progress
480
+ ```
481
+
346
482
  To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
347
483
 
348
484
  Testing github actions:
data/bin/console CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env ruby
2
2
 
3
3
  require "bundler/setup"
4
- require "clickhouse/activerecord"
4
+ require "clickhouse-activerecord"
5
5
 
6
6
  # You can add fixtures and/or initialization code here to make experimenting
7
7
  # with your gem easier. You can also use a different console, if you like.
data/bin/test-single ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ export CLICKHOUSE_PORT="${CLICKHOUSE_PORT:-18123}"
5
+ export CLICKHOUSE_DATABASE="${CLICKHOUSE_DATABASE:-default}"
6
+
7
+ exec bundle exec rspec spec/single --format progress "$@"
@@ -1,13 +1,33 @@
1
1
  module ActiveRecord
2
2
  module ConnectionAdapters
3
3
  module Clickhouse
4
- class Column < ActiveRecord::ConnectionAdapters::Column
4
+ DescribedColumn =
5
+ Data.define(:name, :sql_type, :default_type, :default_expression, :comment, :codec) do
6
+ def ephemeral?
7
+ default_type.to_s.downcase == 'ephemeral'
8
+ end
9
+ end
5
10
 
6
- attr_reader :codec
11
+ class Column < ActiveRecord::ConnectionAdapters::Column
12
+ attr_reader :codec, :default_kind
7
13
 
8
- def initialize(*, codec: nil, **)
14
+ def initialize(*, codec: nil, default_kind: nil, **)
9
15
  super
10
16
  @codec = codec
17
+ @default_kind = ActiveSupport::StringInquirer.new(default_kind.to_s.downcase.presence || 'none')
18
+ end
19
+
20
+ def virtual?
21
+ default_kind.materialized? || default_kind.alias?
22
+ end
23
+
24
+ # Whether the column holds a ClickHouse `Array(...)` type.
25
+ #
26
+ # ActiveRecord core never calls this, but tooling such as annotaterb
27
+ # detects array columns via `column.respond_to?(:array) && column.array`,
28
+ # so the base adapter's missing `array` reader left them undetected.
29
+ def array
30
+ sql_type.start_with?('Array(')
11
31
  end
12
32
 
13
33
  private
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Clickhouse
6
+ module OID # :nodoc:
7
+ class Json < Type::Json # :nodoc:
8
+
9
+ def deserialize(value)
10
+ if value.is_a?(::String)
11
+ ::JSON.parse(value)
12
+ else
13
+ super
14
+ end
15
+ rescue ::JSON::ParserError => e
16
+ ActiveSupport.error_reporter.report(e, source: "application.active_record")
17
+ nil
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -11,6 +11,10 @@ module ActiveRecord
11
11
  when /U?Int(\d+)/
12
12
  @subtype = :integer
13
13
  @limit = bits_to_limit(Regexp.last_match(1)&.to_i)
14
+ when /Float/
15
+ @subtype = :float
16
+ when /Bool/
17
+ @subtype = :boolean
14
18
  when /DateTime/
15
19
  @subtype = :datetime
16
20
  when /Date/
@@ -31,9 +35,14 @@ module ActiveRecord
31
35
  value.map { |item| deserialize(item) }
32
36
  else
33
37
  return value if value.nil?
38
+ return value if already_deserialized?(value)
34
39
  case @subtype
35
40
  when :integer
36
41
  value.to_i
42
+ when :float
43
+ value.to_f
44
+ when :boolean
45
+ ActiveRecord::Type::Boolean.new.cast(value)
37
46
  when :datetime
38
47
  ::DateTime.parse(value)
39
48
  when :date
@@ -51,6 +60,8 @@ module ActiveRecord
51
60
  value.map { |item| serialize(item) }
52
61
  else
53
62
  return value if value.nil?
63
+ return value.to_f if @subtype == :float
64
+ return ActiveRecord::Type::Boolean.new.cast(value) if @subtype == :boolean
54
65
  case @subtype
55
66
  when :integer
56
67
  value.to_i
@@ -68,6 +79,11 @@ module ActiveRecord
68
79
 
69
80
  private
70
81
 
82
+ def already_deserialized?(value)
83
+ (@subtype == :date && value.is_a?(::Date)) ||
84
+ (@subtype == :datetime && (value.is_a?(::DateTime) || value.is_a?(::Time)))
85
+ end
86
+
71
87
  def bits_to_limit(bits)
72
88
  case bits
73
89
  when 8 then 1