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,6 +2,7 @@
2
2
 
3
3
  require 'arel/visitors/clickhouse'
4
4
  require 'arel/nodes/final'
5
+ require 'arel/nodes/final_table'
5
6
  require 'arel/nodes/grouping_sets'
6
7
  require 'arel/nodes/settings'
7
8
  require 'arel/nodes/using'
@@ -11,6 +12,7 @@ require 'active_record/connection_adapters/clickhouse/oid/date'
11
12
  require 'active_record/connection_adapters/clickhouse/oid/date_time'
12
13
  require 'active_record/connection_adapters/clickhouse/oid/big_integer'
13
14
  require 'active_record/connection_adapters/clickhouse/oid/map'
15
+ require 'active_record/connection_adapters/clickhouse/oid/json'
14
16
  require 'active_record/connection_adapters/clickhouse/oid/uuid'
15
17
  require 'active_record/connection_adapters/clickhouse/column'
16
18
  require 'active_record/connection_adapters/clickhouse/quoting'
@@ -20,6 +22,7 @@ require 'active_record/connection_adapters/clickhouse/statement'
20
22
  require 'active_record/connection_adapters/clickhouse/table_definition'
21
23
  require 'net/http'
22
24
  require 'openssl'
25
+ require 'uri'
23
26
 
24
27
  module ActiveRecord
25
28
  class Base
@@ -28,10 +31,22 @@ module ActiveRecord
28
31
  def clickhouse_connection(config)
29
32
  config = config.symbolize_keys
30
33
 
34
+ if config[:url]
35
+ url_config = ConnectionAdapters::ClickhouseAdapter.parse_clickhouse_url(config.delete(:url))
36
+ config = url_config.merge(config)
37
+ end
38
+
31
39
  unless config.key?(:database)
32
40
  raise ArgumentError, 'No database specified. Missing argument: database.'
33
41
  end
34
42
 
43
+ if config[:http_auth]
44
+ unless ConnectionAdapters::Clickhouse::SchemaStatements::HTTP_AUTH_TYPES.include?(config[:http_auth]&.to_sym)
45
+ raise ArgumentError, "Unknown :http_auth mode #{config[:http_auth].inspect}. " \
46
+ + "Use one of #{ConnectionAdapters::Clickhouse::SchemaStatements::HTTP_AUTH_TYPES}."
47
+ end
48
+ end
49
+
35
50
  ConnectionAdapters::ClickhouseAdapter.new(config)
36
51
  end
37
52
  end
@@ -52,6 +67,8 @@ module ActiveRecord
52
67
  module ModelSchema
53
68
  module ClassMethods
54
69
  delegate :final, :final!,
70
+ :joins_final, :joins_final!,
71
+ :left_joins_final, :left_joins_final!,
55
72
  :group_by_grouping_sets, :group_by_grouping_sets!,
56
73
  :settings, :settings!,
57
74
  :window, :window!,
@@ -90,6 +107,7 @@ module ActiveRecord
90
107
  integer: { name: 'UInt32' },
91
108
  big_integer: { name: 'UInt64' },
92
109
  float: { name: 'Float32' },
110
+ float64: { name: 'Float64' },
93
111
  decimal: { name: 'Decimal' },
94
112
  datetime: { name: 'DateTime' },
95
113
  datetime64: { name: 'DateTime64' },
@@ -119,30 +137,51 @@ module ActiveRecord
119
137
 
120
138
  include Clickhouse::SchemaStatements
121
139
 
140
+ # our `execute` shadows the wrapper `QueryCache` installs on `AbstractAdapter`
141
+ ActiveRecord::ConnectionAdapters::QueryCache.dirties_query_cache(self, :execute)
142
+
122
143
  # Initializes and connects a Clickhouse adapter.
123
144
  def initialize(config_or_deprecated_connection, deprecated_logger = nil, deprecated_connection_options = nil, deprecated_config = nil)
145
+ if config_or_deprecated_connection.is_a?(Hash) && config_or_deprecated_connection[:url]
146
+ config_or_deprecated_connection = config_or_deprecated_connection.dup
147
+ url_config = self.class.parse_clickhouse_url(config_or_deprecated_connection.delete(:url))
148
+ config_or_deprecated_connection = url_config.merge(config_or_deprecated_connection)
149
+ end
124
150
  super
125
151
  if @config[:connection]
126
152
  connection = {
127
153
  connection: @config[:connection]
128
154
  }
129
155
  else
130
- port = @config[:port] || 8123
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
131
159
  connection = {
132
160
  host: @config[:host] || 'localhost',
133
161
  port: port,
134
- ssl: @config[:ssl].present? ? @config[:ssl] : port == 443,
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)),
135
164
  sslca: @config[:sslca],
136
- read_timeout: @config[:read_timeout],
137
- write_timeout: @config[:write_timeout],
138
- 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])
139
169
  }
140
170
  end
141
171
  @connection_parameters = connection
142
172
 
143
- @connection_config = { user: @config[:username], password: @config[:password], database: @config[:database] }.compact
144
- @debug = @config[:debug] || false
145
- @response_format = @config[:format] || DEFAULT_RESPONSE_FORMAT
173
+ @connection_config = {
174
+ user: @config[:username],
175
+ password: @config[:password],
176
+ database: @config[:database],
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]),
179
+ }.compact
180
+ @debug = self.class.type_cast_config_to_boolean(@config[:debug]) || false
181
+ @default_response_format = @config[:format] || DEFAULT_RESPONSE_FORMAT
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
146
185
 
147
186
  @prepared_statements = false
148
187
 
@@ -185,11 +224,57 @@ module ActiveRecord
185
224
  !native_database_types[type].nil?
186
225
  end
187
226
 
227
+ # Rails appends the limit to the native type name (e.g. "Float32(8)"), which is not valid in ClickHouse.
228
+ # Resolve the float width by limit here so that add_column / change_column behave like TableDefinition#float.
229
+ def type_to_sql(type, limit: nil, precision: nil, scale: nil, **)
230
+ return native_database_types[limit == 8 ? :float64 : :float][:name] if type.to_s == 'float'
231
+
232
+ super
233
+ end
234
+
188
235
  def supports_indexes_in_create?
189
236
  true
190
237
  end
191
238
 
192
239
  class << self
240
+ def parse_clickhouse_url(url)
241
+ uri = URI.parse(url)
242
+ config = {}
243
+
244
+ config[:host] = uri.host if uri.host
245
+ config[:port] = uri.port if uri.port
246
+ config[:username] = URI.decode_www_form_component(uri.user) if uri.user
247
+ config[:password] = URI.decode_www_form_component(uri.password) if uri.password
248
+
249
+ if uri.path && uri.path.length > 1
250
+ config[:database] = uri.path.delete_prefix('/')
251
+ end
252
+
253
+ if uri.query
254
+ URI.decode_www_form(uri.query).each do |key, value|
255
+ case key
256
+ when 'ssl' then config[:ssl] = (value == 'true')
257
+ when 'debug' then config[:debug] = (value == 'true')
258
+ when 'insecure' then config[:insecure] = (value == 'true')
259
+ when 'open_timeout' then config[:open_timeout] = value.to_i
260
+ when 'read_timeout' then config[:read_timeout] = value.to_i
261
+ when 'write_timeout' then config[:write_timeout] = value.to_i
262
+ when 'keep_alive_timeout' then config[:keep_alive_timeout] = value.to_i
263
+ when 'http_auth' then config[:http_auth] = value
264
+ when 'cluster_name' then config[:cluster_name] = value
265
+ when 'sslca' then config[:sslca] = value
266
+ when 'max_execution_time' then config[:max_execution_time] = value.to_i
267
+ when 'cancel_http_readonly_queries_on_client_close'
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')
271
+ end
272
+ end
273
+ end
274
+
275
+ config
276
+ end
277
+
193
278
  def extract_limit(sql_type) # :nodoc:
194
279
  case sql_type
195
280
  when /(Nullable)?\(?String\)?/
@@ -204,6 +289,10 @@ module ActiveRecord
204
289
  8
205
290
  when /(Nullable)?\(?U?Int128\)?/
206
291
  16
292
+ when /(Nullable)?\(?Float32\)?/
293
+ nil
294
+ when /(Nullable)?\(?Float64\)?/
295
+ 8
207
296
  else
208
297
  super
209
298
  end
@@ -254,7 +343,7 @@ module ActiveRecord
254
343
  Clickhouse::OID::Map.new(sql_type)
255
344
  end
256
345
 
257
- m.register_type %r(JSON)i, ActiveRecord::Type::Json.new
346
+ m.register_type(%r(JSON)) { Clickhouse::OID::Json.new }
258
347
  end
259
348
  end
260
349
 
@@ -298,13 +387,15 @@ module ActiveRecord
298
387
  # SCHEMA STATEMENTS ========================================
299
388
 
300
389
  def primary_keys(table_name)
301
- if server_version.to_f >= 23.4
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
302
393
  structure = do_system_execute("SHOW COLUMNS FROM `#{table_name}`")
303
394
  return structure['data'].select {|m| m[3]&.include?('PRI') }.pluck(0)
304
395
  end
305
396
 
306
397
  pk = table_structure(table_name).first
307
- return ['id'] if pk.present? && pk[0] == 'id'
398
+ return ['id'] if pk.present? && pk.name == 'id'
308
399
  []
309
400
  end
310
401
 
@@ -316,7 +407,8 @@ module ActiveRecord
316
407
  # @option [Boolean] single_line
317
408
  # @return [String]
318
409
  def show_create_table(table, single_line: true)
319
- sql = do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first).gsub("#{@config[:database]}.", '')
410
+ sql = do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first)
411
+ sql = remove_database_qualifier(sql)
320
412
  single_line ? sql.squish : sql
321
413
  end
322
414
 
@@ -426,9 +518,9 @@ module ActiveRecord
426
518
  end
427
519
 
428
520
  def change_column_null(table_name, column_name, null, default = nil)
429
- structure = table_structure(table_name).select{|v| v[0] == column_name.to_s}.first
521
+ structure = table_structure(table_name).find { |col| col.name == column_name.to_s }
430
522
  raise "Column #{column_name} not found in table #{table_name}" if structure.nil?
431
- change_column table_name, column_name, structure[1].gsub(/(Nullable\()?(.*?)\)?/, '\2'), {null: null, default: default}.compact
523
+ change_column table_name, column_name, structure.sql_type.gsub(/(Nullable\()?(.*?)\)?/, '\2'), {null: null, default: default}.compact
432
524
  end
433
525
 
434
526
  def change_column_default(table_name, column_name, default)
@@ -488,7 +580,7 @@ module ActiveRecord
488
580
  end
489
581
 
490
582
  def use_default_replicated_merge_tree_params?
491
- 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])
492
584
  end
493
585
 
494
586
  def use_replica?
@@ -533,14 +625,18 @@ module ActiveRecord
533
625
  end
534
626
 
535
627
  def build_insert_sql(insert) # :nodoc:
536
- sql = +"INSERT #{insert.into} #{insert.values_list}"
537
- sql
628
+ ['INSERT', insert.into, insert.settings_list, insert.values_list].compact.join(' ')
538
629
  end
539
630
 
540
631
  protected
541
632
 
542
- def last_inserted_id(result)
543
- result
633
+ def last_inserted_id(_result)
634
+ # Rails 7.1 persistence.rb:1258:
635
+ # _write_attribute(column, value) # wrote true directly — ugly but no crash
636
+
637
+ # Rails 8.0 persistence.rb:933:
638
+ # _write_attribute(column, type_for_attribute(column).deserialize(value)) # now deserializes first
639
+ nil
544
640
  end
545
641
 
546
642
  def change_column_for_alter(table_name, column_name, type, **options)
@@ -551,10 +647,42 @@ module ActiveRecord
551
647
 
552
648
  private
553
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
+
554
677
  def connect
555
- @connection = @connection_parameters[:connection] || Net::HTTP.start(@connection_parameters[:host], @connection_parameters[:port], use_ssl: @connection_parameters[:ssl], verify_mode: OpenSSL::SSL::VERIFY_NONE)
678
+ @connection = @connection_parameters[:connection] || Net::HTTP.start(
679
+ @connection_parameters[:host],
680
+ @connection_parameters[:port],
681
+ use_ssl: @connection_parameters[:ssl],
682
+ verify_mode: @connection_parameters[:insecure] ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER,
683
+ **{ open_timeout: @connection_parameters[:open_timeout], ca_file: @connection_parameters[:sslca] }.compact
684
+ )
556
685
 
557
- @connection.ca_file = @connection_parameters[:ca_file] if @connection_parameters[:ca_file]
558
686
  @connection.read_timeout = @connection_parameters[:read_timeout] if @connection_parameters[:read_timeout]
559
687
  @connection.write_timeout = @connection_parameters[:write_timeout] if @connection_parameters[:write_timeout]
560
688
 
@@ -0,0 +1,10 @@
1
+ module Arel # :nodoc: all
2
+ module Nodes
3
+ # Wraps the table source of a JOIN so the ClickHouse visitor renders
4
+ # `<table> FINAL ON ...` for that join. Built by
5
+ # ActiveRecord::Relation#joins_final, which marks the matching join
6
+ # sources after Arel has been constructed.
7
+ class FinalTable < Arel::Nodes::Unary
8
+ end
9
+ end
10
+ end
@@ -10,8 +10,7 @@ module Arel
10
10
  end
11
11
 
12
12
  def aggregate(name, o, collector)
13
- # replacing function name for materialized view
14
- if o.expressions.first && o.expressions.first != '*' && !o.expressions.first.is_a?(String) && o.expressions.first.relation&.is_view
13
+ if o.expressions.first && o.expressions.first != '*' && !o.expressions.first.is_a?(String) && o.expressions.first.respond_to?(:relation) && o.expressions.first.relation&.is_view
15
14
  super("#{name.downcase}Merge", o, collector)
16
15
  else
17
16
  super
@@ -89,6 +88,16 @@ module Arel
89
88
  collector
90
89
  end
91
90
 
91
+ # Renders the FINAL modifier for a single JOIN source, e.g.
92
+ # `INNER JOIN espm_binaries FINAL ON ...`. The join visitors inherited
93
+ # from ToSql all emit their table via `visit o.left`, so wrapping that
94
+ # table in a FinalTable node is enough to add FINAL to any join type.
95
+ def visit_Arel_Nodes_FinalTable(o, collector)
96
+ collector = visit o.expr, collector
97
+ collector << ' FINAL'
98
+ collector
99
+ end
100
+
92
101
  def visit_Arel_Nodes_GroupingSets(o, collector)
93
102
  collector << 'GROUPING SETS '
94
103
  grouping_array_or_grouping_element(o.expr, collector)
@@ -100,7 +109,7 @@ module Arel
100
109
  collector << "SETTINGS "
101
110
  o.expr.each_with_index do |(key, value), i|
102
111
  collector << ", " if i > 0
103
- collector << key.to_s.gsub(/\W+/, "")
112
+ collector << sanitize_as_setting_name(key).to_s
104
113
  collector << " = "
105
114
  collector << sanitize_as_setting_value(value)
106
115
  end
@@ -146,7 +155,7 @@ module Arel
146
155
 
147
156
  def sanitize_as_setting_name(value)
148
157
  return value if Arel::Nodes::SqlLiteral === value
149
- @connection.sanitize_as_setting_name(value)
158
+ value.to_s.gsub(/\W+/, "")
150
159
  end
151
160
 
152
161
  private
@@ -99,7 +99,7 @@ module ClickhouseActiverecord
99
99
  end
100
100
  end
101
101
 
102
- indexes = sql.scan(/INDEX \S+ \S+ TYPE .*? GRANULARITY \d+/)
102
+ indexes = sql.scan(/INDEX \S+ .+? TYPE .*? GRANULARITY \d+/)
103
103
  if indexes.any?
104
104
  tbl.puts ''
105
105
  indexes.flatten.map!(&:strip).each do |index|
@@ -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
- sql = @connection.show_create_function(function)
135
- if sql
136
- stream.puts " # SQL: #{sql}"
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)
@@ -154,22 +154,17 @@ module ClickhouseActiverecord
154
154
  end
155
155
  end
156
156
 
157
- def schema_limit(column)
158
- return nil if column.type == :float
159
- super
160
- end
161
-
162
157
  def schema_unsigned(column)
163
158
  return nil unless column.type == :integer && !simple
164
159
  (column.sql_type =~ /(Nullable)?\(?UInt\d+\)?/).nil? ? false : nil
165
160
  end
166
161
 
167
162
  def schema_array(column)
168
- (column.sql_type =~ /Array\(/).nil? ? nil : true
163
+ column.array ? true : nil
169
164
  end
170
165
 
171
166
  def schema_map(column)
172
- if column.sql_type =~ /Map\(([^,]+),\s*(Array)\)/
167
+ if column.sql_type =~ /Map\([^,]+,\s*Array\(/
173
168
  return :array
174
169
  end
175
170
 
@@ -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
@@ -34,30 +36,10 @@ module ClickhouseActiverecord
34
36
  create
35
37
  end
36
38
 
37
- def structure_dump(*args)
39
+ def structure_dump(path, *)
38
40
  establish_master_connection
39
41
 
40
- # get all tables
41
- tables = connection.execute("SHOW TABLES FROM #{@configuration.database} WHERE name NOT LIKE '.inner_id.%'")['data'].flatten.map do |table|
42
- connection.show_create_table(table, single_line: false).gsub("#{@configuration.database}.", '')
43
- end.compact
44
-
45
- # sort view to last
46
- tables.sort_by! {|table| table.match(/^CREATE\s+(MATERIALIZED\s+)?VIEW/) ? 1 : 0}
47
-
48
- # get all functions
49
- functions = connection.execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' ORDER BY name")['data'].flatten
50
-
51
- # put to file
52
- File.open(args.first, 'w:utf-8') do |file|
53
- functions.each do |function|
54
- file.puts function.gsub('\\n', "\n") + ";\n\n"
55
- end
56
-
57
- tables.each do |table|
58
- file.puts table + ";\n\n"
59
- end
60
- end
42
+ StructureDumper.new(connection, @configuration.database).dump(path)
61
43
  end
62
44
 
63
45
  def structure_load(*args)
@@ -1,3 +1,3 @@
1
1
  module ClickhouseActiverecord
2
- VERSION = '1.6.7'
2
+ VERSION = '1.7.1'
3
3
  end