pg-statistics-rails 0.2.0 → 0.3.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: 5f7c688f5b7b0fc7a1d1da6e664d7ead527752bfe15bd68acfacfeb852d3b640
4
- data.tar.gz: 9eaa3769be4bd92e435f77e1aa289c9761fdd5680d5455994218a1f4d0d92cd2
3
+ metadata.gz: e404844e378d2520a0684d71a938fce19e48d221814b06dd5d1a8d3be39dff95
4
+ data.tar.gz: b197537afaed5af5cb1fc3b4441f05f5051955e40216b658bf575b71b53f5e48
5
5
  SHA512:
6
- metadata.gz: 9bdcbd43ac11cb18dde949a2dddfd1a85b44be060ae637c9bf2f83659f2f51949dce3529bca8a460cd91de8ff08e3f6c59cb62c1e9c4e089bb1250817854ceac
7
- data.tar.gz: 763d5a8c361732c196571724e41a947032e91e778bb95543c79c91b547524cb0aa07f66b760ef9e345dabef2865f677e313bdf30026135504fd9eed007ecd019
6
+ metadata.gz: 248502d7eb94d3027ec7316b81ef286a21cf8937f2ca7678a1e2d613945e1500c744cfdbb64d09fe33275cbc66ec50f7d01047a81a1c712e524f88639579858c
7
+ data.tar.gz: 40a7d654d1ce2b686b1095da8c5982de56e99df3aad9fc7464fbfa395af1743bd3a1a84fa876dbdb29943de335955d5568fa5e1c34464c4766a72fe4b663a308
data/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 (2026-11-26)
4
+
5
+ - In a migration, `create_statistics` analyzes each table once, after the migration's last step, instead of after every call. A table or statistics object the migration drops is not analyzed.
6
+
7
+ ## 0.3.0 (2026-11-26)
8
+
9
+ - `create_statistics` analyzes the table right after creating the object, so the planner uses it before autovacuum next analyzes the table. The `ANALYZE` covers the plain columns of every statistics object on the table, which builds their expressions too, or the whole table when they have only expressions. `if_not_exists: true` skips it when the object already exists. `analyze: false` skips it. On PostgreSQL 18+ a partitioned table gets `ANALYZE ONLY`, leaving its partitions alone.
10
+ - `set_column_statistics_target` and `set_index_statistics_target` take `from:` and `to:`, which makes them reversible in `change`. Given a bare target, rolling them back raises `ActiveRecord::IrreversibleMigration` instead of applying the target again. A `from:` without `to:`, or the reverse, raises `ArgumentError`.
11
+ - Package every file world-readable. 0.2.0 shipped four files under `lib/` with mode 0640, so Ruby running as any user other than the one that installed the gem cannot load it. `rake build` and `rake release` now stop when a packaged file is not world-readable.
12
+
3
13
  ## 0.2.0 (2026-10-24)
4
14
 
5
15
  - Statistics targets: `create_statistics` takes `target:`, and `set_column_statistics_target` / `set_index_statistics_target` set column and expression-index targets. All three are read back by `statistics` / `statistics_targets` and dumped into `db/schema.rb` after each table.
data/README.md CHANGED
@@ -53,6 +53,9 @@ Options:
53
53
  - `:kinds` — Array of kinds to build (`:ndistinct`, `:dependencies`, `:mcv`). Defaults to all kinds.
54
54
  - `:if_not_exists` — Emits `CREATE STATISTICS IF NOT EXISTS`.
55
55
  - `:target` — The object's statistics target (`ALTER STATISTICS ... SET STATISTICS`). Defaults to `default_statistics_target`.
56
+ - `:analyze` — Set to `false` to skip the `ANALYZE` that follows. By default the table is analyzed right after the object is created, so the planner uses it before autovacuum next analyzes the table. The `ANALYZE` reads only the plain columns of the table's statistics objects, which also builds their expressions, or the whole table when they have only expressions. With `:if_not_exists`, an object that already exists is not analyzed again. In a migration the `ANALYZE` waits for the migration's last step and runs once per table, so several `create_statistics` calls on one table sample it once, and a table or object the migration drops is not analyzed. On a partitioned table it runs `ANALYZE ONLY` on PostgreSQL 18+, so the partitions are not analyzed one by one.
57
+
58
+ `ANALYZE` reads a sample of 300 × the largest statistics target rows, whatever the table's size: about 30,000 rows at the default target of 100, and up to 3,000,000 at 10,000. It holds a `SHARE UPDATE EXCLUSIVE` lock, the same lock `CREATE STATISTICS` takes, until the migration's transaction commits. Reads and writes go on, but autovacuum, other `ANALYZE` runs and most DDL on the table wait. On a large table with a high target, pass `analyze: false` and run `ANALYZE` outside the migration.
56
59
 
57
60
  ### Statistics targets
58
61
 
@@ -66,7 +69,14 @@ set_index_statistics_target "index_addresses_on_lower_city", 1, 1000 # column by
66
69
  set_column_statistics_target :addresses, :city, nil
67
70
  ```
68
71
 
69
- These are not reversible, since the previous target is not recorded; use `up`/`down`. Explicit targets are dumped after the table:
72
+ Given the previous target as `from:` and the new one as `to:`, they are reversible in `change`. Without `from:`, rolling back raises `ActiveRecord::IrreversibleMigration`:
73
+
74
+ ```ruby
75
+ set_column_statistics_target :addresses, :city, from: nil, to: 1000
76
+ set_index_statistics_target "index_addresses_on_lower_city", 1, from: nil, to: 1000
77
+ ```
78
+
79
+ Explicit targets are dumped after the table:
70
80
 
71
81
  ```ruby
72
82
  create_statistics "addresses", ["city", "zip_code"], name: "addresses_city_zip_code_stat", target: 900
@@ -6,7 +6,7 @@ module PgStatisticsRails
6
6
  if recorder_class.const_defined?(:ReversibleAndIrreversibleMethods) &&
7
7
  !recorder_class::ReversibleAndIrreversibleMethods.frozen? &&
8
8
  !recorder_class::ReversibleAndIrreversibleMethods.include?(:create_statistics)
9
- recorder_class::ReversibleAndIrreversibleMethods.push(:create_statistics, :drop_statistics)
9
+ recorder_class::ReversibleAndIrreversibleMethods.push(:create_statistics, :drop_statistics, :set_column_statistics_target, :set_index_statistics_target)
10
10
  end
11
11
 
12
12
  if recorder_class.private_instance_methods.include?(:inverse_of) &&
@@ -17,6 +17,14 @@ module PgStatisticsRails
17
17
  end
18
18
  end
19
19
 
20
+ def self.invert_statistics_target(command, args, changes)
21
+ unless changes.is_a?(Hash) && changes.key?(:from) && changes.key?(:to)
22
+ raise ActiveRecord::IrreversibleMigration, "#{command} is only reversible if given a :from and :to option."
23
+ end
24
+
25
+ [command, [*args.first(2), { from: changes[:to], to: changes[:from] }]]
26
+ end
27
+
20
28
  module KwargsRecorder
21
29
  def create_statistics(*args, **kwargs, &block)
22
30
  record(:create_statistics, args, kwargs, &block)
@@ -26,6 +34,14 @@ module PgStatisticsRails
26
34
  record(:drop_statistics, args, kwargs, &block)
27
35
  end
28
36
 
37
+ def set_column_statistics_target(*args, **kwargs, &block)
38
+ record(:set_column_statistics_target, args, kwargs, &block)
39
+ end
40
+
41
+ def set_index_statistics_target(*args, **kwargs, &block)
42
+ record(:set_index_statistics_target, args, kwargs, &block)
43
+ end
44
+
29
45
  private
30
46
  def invert_create_statistics(args, kwargs, &block)
31
47
  kwargs = kwargs.dup
@@ -41,6 +57,14 @@ module PgStatisticsRails
41
57
  kwargs[:if_not_exists] = kwargs.delete(:if_exists) if kwargs.key?(:if_exists)
42
58
  [:create_statistics, args, kwargs, block]
43
59
  end
60
+
61
+ def invert_set_column_statistics_target(args, kwargs, &block)
62
+ [*CommandRecorder.invert_statistics_target(:set_column_statistics_target, args, args[2] || kwargs), {}, block]
63
+ end
64
+
65
+ def invert_set_index_statistics_target(args, kwargs, &block)
66
+ [*CommandRecorder.invert_statistics_target(:set_index_statistics_target, args, args[2] || kwargs), {}, block]
67
+ end
44
68
  end
45
69
 
46
70
  module LegacyArgsRecorder
@@ -52,6 +76,14 @@ module PgStatisticsRails
52
76
  record(:drop_statistics, args, &block)
53
77
  end
54
78
 
79
+ ruby2_keywords def set_column_statistics_target(*args, &block)
80
+ record(:set_column_statistics_target, args, &block)
81
+ end
82
+
83
+ ruby2_keywords def set_index_statistics_target(*args, &block)
84
+ record(:set_index_statistics_target, args, &block)
85
+ end
86
+
55
87
  private
56
88
  def invert_create_statistics(args, &block)
57
89
  if (options = args.last).is_a?(Hash)
@@ -69,6 +101,14 @@ module PgStatisticsRails
69
101
  end
70
102
  [:create_statistics, args, block]
71
103
  end
104
+
105
+ def invert_set_column_statistics_target(args, &block)
106
+ [*CommandRecorder.invert_statistics_target(:set_column_statistics_target, args, args[2]), block]
107
+ end
108
+
109
+ def invert_set_index_statistics_target(args, &block)
110
+ [*CommandRecorder.invert_statistics_target(:set_index_statistics_target, args, args[2]), block]
111
+ end
72
112
  end
73
113
  end
74
114
  end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgStatisticsRails
4
+ module Migration
5
+ def exec_migration(connection, direction)
6
+ return super unless connection.respond_to?(:analyzing_statistics_once)
7
+
8
+ connection.analyzing_statistics_once { super }
9
+ end
10
+ end
11
+ end
@@ -47,10 +47,16 @@ module PgStatisticsRails
47
47
  # : The object's statistics target (`ALTER STATISTICS ... SET STATISTICS`).
48
48
  # Defaults to the server's `default_statistics_target`.
49
49
  #
50
- # Statistics are built by the next `ANALYZE` of the table.
50
+ # `:analyze`
51
+ # : Set to `false` to leave building the statistics to the next `ANALYZE`
52
+ # of the table. Defaults to `true`.
53
+ #
54
+ # Statistics are built by an `ANALYZE` of the table straight after, so the
55
+ # planner can use them before autovacuum next analyzes the table.
51
56
  def create_statistics(table_name, columns, **options)
52
57
  name = statistics_name(table_name, columns: columns, **options)
53
58
  kinds = Array(options[:kinds])
59
+ analyze = options[:analyze] != false && !(options[:if_not_exists] && statistics_exist?(name))
54
60
 
55
61
  sql = +"CREATE STATISTICS"
56
62
  sql << " IF NOT EXISTS" if options[:if_not_exists]
@@ -60,6 +66,28 @@ module PgStatisticsRails
60
66
 
61
67
  execute sql
62
68
  execute "ALTER STATISTICS #{quote_table_name(name)} SET STATISTICS #{Integer(options[:target])}" unless options[:target].nil?
69
+ return unless analyze
70
+
71
+ if @statistics_tables_to_analyze
72
+ @statistics_tables_to_analyze << table_name.to_s
73
+ else
74
+ analyze_statistics(table_name)
75
+ end
76
+ end
77
+
78
+ # Runs the block, then analyzes each table that `create_statistics` was
79
+ # asked to analyze in it once. Every migration runs inside this.
80
+ def analyzing_statistics_once
81
+ return yield if @statistics_tables_to_analyze
82
+
83
+ begin
84
+ @statistics_tables_to_analyze = []
85
+ result = yield
86
+ @statistics_tables_to_analyze.uniq.each { |table_name| analyze_statistics(table_name) }
87
+ result
88
+ ensure
89
+ @statistics_tables_to_analyze = nil
90
+ end
63
91
  end
64
92
 
65
93
  # Sets a column's statistics target, how much `ANALYZE` samples it. A nil
@@ -68,8 +96,14 @@ module PgStatisticsRails
68
96
  # ```
69
97
  # set_column_statistics_target :addresses, :city, 1000
70
98
  # ```
71
- def set_column_statistics_target(table_name, column_name, target)
72
- execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET STATISTICS #{statistics_target_value(target)}"
99
+ #
100
+ # Passing the previous target as `:from` makes it reversible in `change`:
101
+ #
102
+ # ```
103
+ # set_column_statistics_target :addresses, :city, from: nil, to: 1000
104
+ # ```
105
+ def set_column_statistics_target(table_name, column_name, target_or_changes)
106
+ execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET STATISTICS #{statistics_target_value(target_or_changes)}"
73
107
  end
74
108
 
75
109
  # Sets the statistics target of an expression index's column, by position
@@ -78,8 +112,10 @@ module PgStatisticsRails
78
112
  # ```
79
113
  # set_index_statistics_target "index_addresses_on_lower_city", 1, 1000
80
114
  # ```
81
- def set_index_statistics_target(index_name, column_number, target)
82
- execute "ALTER INDEX #{quote_table_name(index_name)} ALTER COLUMN #{Integer(column_number)} SET STATISTICS #{statistics_target_value(target)}"
115
+ #
116
+ # Like `set_column_statistics_target`, it takes `from:` and `to:`.
117
+ def set_index_statistics_target(index_name, column_number, target_or_changes)
118
+ execute "ALTER INDEX #{quote_table_name(index_name)} ALTER COLUMN #{Integer(column_number)} SET STATISTICS #{statistics_target_value(target_or_changes)}"
83
119
  end
84
120
 
85
121
  # Returns the explicit statistics targets on the given table's columns and
@@ -202,8 +238,48 @@ module PgStatisticsRails
202
238
  end
203
239
  end
204
240
 
205
- def statistics_target_value(target)
206
- target.nil? ? -1 : Integer(target)
241
+ def statistics_exist?(name)
242
+ schema, bare_name = extract_schema_qualified_name(name.to_s)
243
+ select_value(<<~SQL, "SCHEMA")
244
+ SELECT EXISTS (
245
+ SELECT 1 FROM pg_statistic_ext s
246
+ JOIN pg_namespace n ON n.oid = s.stxnamespace
247
+ WHERE s.stxname = #{quote(bare_name)} AND n.nspname = #{schema ? quote(schema) : 'current_schema()'}
248
+ )
249
+ SQL
250
+ end
251
+
252
+ def analyze_statistics(table_name)
253
+ columns = select_values(<<~SQL, "SCHEMA")
254
+ SELECT DISTINCT a.attname
255
+ FROM pg_statistic_ext s
256
+ LEFT JOIN pg_attribute a ON a.attrelid = s.stxrelid AND a.attnum = ANY (s.stxkeys)
257
+ WHERE s.stxrelid = to_regclass(#{quote(quote_table_name(table_name))})
258
+ ORDER BY a.attname
259
+ SQL
260
+ return if columns.empty?
261
+
262
+ columns.compact!
263
+
264
+ sql = +"ANALYZE"
265
+ sql << " ONLY" if database_version >= 18_00_00 && partitioned_table?(table_name)
266
+ sql << " #{quote_table_name(table_name)}"
267
+ sql << " (#{columns.map { |column| quote_column_name(column) }.join(', ')})" if columns.any?
268
+
269
+ execute sql
270
+ end
271
+
272
+ def partitioned_table?(table_name)
273
+ select_value("SELECT relkind FROM pg_class WHERE oid = #{quote(quote_table_name(table_name))}::regclass", "SCHEMA") == "p"
274
+ end
275
+
276
+ def statistics_target_value(target_or_changes)
277
+ if target_or_changes.is_a?(Hash)
278
+ raise ArgumentError, "Statistics target changes need both :from and :to" unless target_or_changes.key?(:from) && target_or_changes.key?(:to)
279
+
280
+ target_or_changes = target_or_changes[:to]
281
+ end
282
+ target_or_changes.nil? ? -1 : Integer(target_or_changes)
207
283
  end
208
284
 
209
285
  def fetch_statistics_by_schema(tables, &block)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PgStatisticsRails
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.1"
5
5
  end
@@ -6,10 +6,12 @@ require_relative "pg_statistics_rails/statistics_definition"
6
6
  require_relative "pg_statistics_rails/schema_statements"
7
7
  require_relative "pg_statistics_rails/schema_dumper"
8
8
  require_relative "pg_statistics_rails/command_recorder"
9
+ require_relative "pg_statistics_rails/migration"
9
10
 
10
11
  ActiveSupport.on_load(:active_record) do
11
12
  require "active_record/migration/command_recorder"
12
13
  ActiveRecord::Migration::CommandRecorder.include(PgStatisticsRails::CommandRecorder)
14
+ ActiveRecord::Migration.prepend(PgStatisticsRails::Migration)
13
15
  end
14
16
 
15
17
  ActiveSupport.on_load(:active_record_postgresqladapter) do
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pg-statistics-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrew Fader
@@ -53,6 +53,7 @@ files:
53
53
  - lib/pg-statistics-rails.rb
54
54
  - lib/pg_statistics_rails.rb
55
55
  - lib/pg_statistics_rails/command_recorder.rb
56
+ - lib/pg_statistics_rails/migration.rb
56
57
  - lib/pg_statistics_rails/schema_dumper.rb
57
58
  - lib/pg_statistics_rails/schema_statements.rb
58
59
  - lib/pg_statistics_rails/statistics_definition.rb