pg-statistics-rails 0.2.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5f7c688f5b7b0fc7a1d1da6e664d7ead527752bfe15bd68acfacfeb852d3b640
4
+ data.tar.gz: 9eaa3769be4bd92e435f77e1aa289c9761fdd5680d5455994218a1f4d0d92cd2
5
+ SHA512:
6
+ metadata.gz: 9bdcbd43ac11cb18dde949a2dddfd1a85b44be060ae637c9bf2f83659f2f51949dce3529bca8a460cd91de8ff08e3f6c59cb62c1e9c4e089bb1250817854ceac
7
+ data.tar.gz: 763d5a8c361732c196571724e41a947032e91e778bb95543c79c91b547524cb0aa07f66b760ef9e345dabef2865f677e313bdf30026135504fd9eed007ecd019
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-10-24)
4
+
5
+ - 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.
6
+ - Column and index targets for a whole dump come from one catalog query per schema.
7
+
8
+ ## 0.1.0 (2026-10-23)
9
+
10
+ - Initial release extracted from [rails/rails#59317](https://github.com/rails/rails/pull/59317):
11
+ - `create_statistics` and `drop_statistics` migration methods on the PostgreSQL adapter
12
+ - Reversible migration support via `ActiveRecord::Migration::CommandRecorder`
13
+ - `statistics` introspection on `PostgreSQLAdapter`
14
+ - `db/schema.rb` dumping support via `PostgreSQL::SchemaDumper`
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Fader
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # pg-statistics-rails
2
+
3
+ [![CI](https://github.com/andrewfader/pg-statistics-rails/actions/workflows/ci.yml/badge.svg)](https://github.com/andrewfader/pg-statistics-rails/actions/workflows/ci.yml)
4
+ [![Coverage](https://codecov.io/gh/andrewfader/pg-statistics-rails/graph/badge.svg)](https://codecov.io/gh/andrewfader/pg-statistics-rails)
5
+ [![Gem Version](https://badge.fury.io/rb/pg-statistics-rails.svg)](https://rubygems.org/gems/pg-statistics-rails)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.txt)
7
+
8
+ PostgreSQL extended statistics (`CREATE STATISTICS`) support for Active Record migrations and `db/schema.rb`.
9
+
10
+ PostgreSQL extended statistics let the query planner estimate how columns and expressions depend on each other, fixing row estimates where the column-independence assumption breaks down. Without schema dumper support, statistics created via `execute` only exist in databases that ran that migration — any database built via `db:schema:load` (test databases, CI, fresh environments) plans queries without them.
11
+
12
+ `pg-statistics-rails` adds:
13
+
14
+ - `create_statistics` and `drop_statistics` migration helpers (reversible via `CommandRecorder`)
15
+ - `connection.statistics(table_name)` introspection reading `pg_statistic_ext`
16
+ - Statistics targets (`SET STATISTICS`) on statistics objects, columns, and expression index columns
17
+ - Automatic dumping of all of it in `db/schema.rb` after each table's `create_table` block
18
+
19
+ ## Installation
20
+
21
+ Add to your `Gemfile`:
22
+
23
+ ```ruby
24
+ gem "pg-statistics-rails"
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Creating statistics in a migration
30
+
31
+ ```ruby
32
+ class AddAddressStatistics < ActiveRecord::Migration[8.0]
33
+ def change
34
+ # Specific statistics kinds (:ndistinct, :dependencies, :mcv)
35
+ create_statistics :addresses, [:city, :zip_code],
36
+ kinds: [:dependencies],
37
+ name: "addresses_city_zip_code_stat"
38
+
39
+ # Default kinds (all supported by the server) and auto-generated stat_rails_<hash> name
40
+ create_statistics :addresses, [:city, :state]
41
+
42
+ # Expression statistics (PostgreSQL 14+)
43
+ create_statistics :users, [:city, "lower(email)"],
44
+ kinds: [:mcv],
45
+ name: "users_city_lower_email_stat"
46
+ end
47
+ end
48
+ ```
49
+
50
+ Options:
51
+
52
+ - `:name` — Custom statistics object name. Defaults to `stat_rails_<10-char sha256>`. When the table name is schema-qualified and `:name` is not, the statistics object is created in the table's schema.
53
+ - `:kinds` — Array of kinds to build (`:ndistinct`, `:dependencies`, `:mcv`). Defaults to all kinds.
54
+ - `:if_not_exists` — Emits `CREATE STATISTICS IF NOT EXISTS`.
55
+ - `:target` — The object's statistics target (`ALTER STATISTICS ... SET STATISTICS`). Defaults to `default_statistics_target`.
56
+
57
+ ### Statistics targets
58
+
59
+ A statistics target sets how much `ANALYZE` samples. Raise it for a column, or an expression index's column, whose estimates are off:
60
+
61
+ ```ruby
62
+ set_column_statistics_target :addresses, :city, 1000
63
+ set_index_statistics_target "index_addresses_on_lower_city", 1, 1000 # column by position
64
+
65
+ # nil restores default_statistics_target
66
+ set_column_statistics_target :addresses, :city, nil
67
+ ```
68
+
69
+ These are not reversible, since the previous target is not recorded; use `up`/`down`. Explicit targets are dumped after the table:
70
+
71
+ ```ruby
72
+ create_statistics "addresses", ["city", "zip_code"], name: "addresses_city_zip_code_stat", target: 900
73
+ set_column_statistics_target "addresses", "city", 1000
74
+ set_index_statistics_target "index_addresses_on_lower_city", 1, 1000
75
+ ```
76
+
77
+ ### Dropping statistics
78
+
79
+ ```ruby
80
+ # Reversible in `change` when columns are provided:
81
+ drop_statistics :addresses, [:city, :zip_code],
82
+ kinds: [:dependencies],
83
+ name: "addresses_city_zip_code_stat",
84
+ if_exists: true
85
+
86
+ # Or by name alone in `up`/`down`:
87
+ drop_statistics :addresses, name: "addresses_city_zip_code_stat"
88
+ ```
89
+
90
+ ### Inspecting statistics
91
+
92
+ ```ruby
93
+ ActiveRecord::Base.lease_connection.statistics(:addresses)
94
+ # => [#<struct PgStatisticsRails::StatisticsDefinition
95
+ # table_name="addresses",
96
+ # name="addresses_city_zip_code_stat",
97
+ # columns=["city", "zip_code"],
98
+ # kinds=[:dependencies],
99
+ # target=nil>]
100
+
101
+ ActiveRecord::Base.lease_connection.statistics_targets(:addresses)
102
+ # => #<struct PgStatisticsRails::StatisticsTargets
103
+ # columns={"city"=>1000},
104
+ # indexes=[["index_addresses_on_lower_city", 1, 1000]]>
105
+ ```
106
+
107
+ ## License
108
+
109
+ Released under the [MIT License](LICENSE.txt).
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "pg_statistics_rails"
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgStatisticsRails
4
+ module CommandRecorder
5
+ def self.included(recorder_class)
6
+ if recorder_class.const_defined?(:ReversibleAndIrreversibleMethods) &&
7
+ !recorder_class::ReversibleAndIrreversibleMethods.frozen? &&
8
+ !recorder_class::ReversibleAndIrreversibleMethods.include?(:create_statistics)
9
+ recorder_class::ReversibleAndIrreversibleMethods.push(:create_statistics, :drop_statistics)
10
+ end
11
+
12
+ if recorder_class.private_instance_methods.include?(:inverse_of) &&
13
+ recorder_class.instance_method(:inverse_of).arity == 3
14
+ recorder_class.include(KwargsRecorder)
15
+ else
16
+ recorder_class.include(LegacyArgsRecorder)
17
+ end
18
+ end
19
+
20
+ module KwargsRecorder
21
+ def create_statistics(*args, **kwargs, &block)
22
+ record(:create_statistics, args, kwargs, &block)
23
+ end
24
+
25
+ def drop_statistics(*args, **kwargs, &block)
26
+ record(:drop_statistics, args, kwargs, &block)
27
+ end
28
+
29
+ private
30
+ def invert_create_statistics(args, kwargs, &block)
31
+ kwargs = kwargs.dup
32
+ kwargs[:if_exists] = kwargs.delete(:if_not_exists) if kwargs.key?(:if_not_exists)
33
+ [:drop_statistics, args, kwargs, block]
34
+ end
35
+
36
+ def invert_drop_statistics(args, kwargs, &block)
37
+ _table, columns = args
38
+ raise ActiveRecord::IrreversibleMigration, "drop_statistics is only reversible if given columns." if columns.blank?
39
+
40
+ kwargs = kwargs.dup
41
+ kwargs[:if_not_exists] = kwargs.delete(:if_exists) if kwargs.key?(:if_exists)
42
+ [:create_statistics, args, kwargs, block]
43
+ end
44
+ end
45
+
46
+ module LegacyArgsRecorder
47
+ ruby2_keywords def create_statistics(*args, &block)
48
+ record(:create_statistics, args, &block)
49
+ end
50
+
51
+ ruby2_keywords def drop_statistics(*args, &block)
52
+ record(:drop_statistics, args, &block)
53
+ end
54
+
55
+ private
56
+ def invert_create_statistics(args, &block)
57
+ if (options = args.last).is_a?(Hash)
58
+ options[:if_exists] = options.delete(:if_not_exists) if options.key?(:if_not_exists)
59
+ end
60
+ [:drop_statistics, args, block]
61
+ end
62
+
63
+ def invert_drop_statistics(args, &block)
64
+ _table, columns = args.dup.tap(&:extract_options!)
65
+ raise ActiveRecord::IrreversibleMigration, "drop_statistics is only reversible if given columns." if columns.blank?
66
+
67
+ if (options = args.last).is_a?(Hash)
68
+ options[:if_not_exists] = options.delete(:if_exists) if options.key?(:if_exists)
69
+ end
70
+ [:create_statistics, args, block]
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgStatisticsRails
4
+ module SchemaDumper
5
+ ALL_KINDS = [:ndistinct, :dependencies, :mcv].freeze
6
+
7
+ private
8
+ def read_schema_metadata(tables)
9
+ super
10
+ @statistics = @connection.statistics(tables)
11
+ @statistics_targets = @connection.statistics_targets(tables)
12
+ end
13
+
14
+ def table(table, stream)
15
+ super
16
+ statistics(table, stream)
17
+ end
18
+
19
+ # After the table, since a definition names the columns and indexes it covers.
20
+ def statistics(table, stream)
21
+ table_statistics = defined?(@statistics) && @statistics ? @statistics[table] : @connection.statistics(table)
22
+ targets = defined?(@statistics_targets) && @statistics_targets ? @statistics_targets[table] : @connection.statistics_targets(table)
23
+ return if table_statistics.blank? && (targets.nil? || targets.empty?)
24
+
25
+ stream.puts
26
+ table_name = remove_prefix_and_suffix(table)
27
+ table_name = relation_name(table_name) if respond_to?(:relation_name, true)
28
+
29
+ Array(table_statistics).each do |statistic|
30
+ parts = [table_name.inspect, statistic.columns.inspect, "name: #{statistic.name.inspect}"]
31
+ parts << "kinds: #{statistic.kinds.inspect}" unless statistic.kinds.empty? || statistic.kinds == ALL_KINDS
32
+ parts << "target: #{statistic.target}" unless statistic.target.nil?
33
+
34
+ stream.puts " create_statistics #{parts.join(', ')}"
35
+ end
36
+
37
+ return if targets.nil?
38
+
39
+ targets.columns.each do |column, target|
40
+ stream.puts " set_column_statistics_target #{table_name.inspect}, #{column.inspect}, #{target}"
41
+ end
42
+ targets.indexes.each do |index, column_number, target|
43
+ stream.puts " set_index_statistics_target #{index.inspect}, #{column_number}, #{target}"
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,260 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest/sha2"
4
+
5
+ module PgStatisticsRails
6
+ module SchemaStatements
7
+ # Returns an array of extended statistics objects for the given table, or a
8
+ # Hash of them keyed by table name when given an Array of tables.
9
+ # The statistics are represented as StatisticsDefinition objects.
10
+ def statistics(table_name)
11
+ result = fetch_statistics(Array(table_name).map(&:to_s))
12
+ table_name.is_a?(Array) ? result : result[table_name.to_s]
13
+ end
14
+
15
+ # Creates an extended statistics object, which lets the planner estimate
16
+ # how the given columns and expressions depend on each other.
17
+ #
18
+ # ```
19
+ # create_statistics :addresses, [:city, :zip_code], kinds: [:dependencies], name: "addresses_city_zip_code_stat"
20
+ # ```
21
+ #
22
+ # generates:
23
+ #
24
+ # ```
25
+ # CREATE STATISTICS "addresses_city_zip_code_stat" (dependencies) ON "city", "zip_code" FROM "addresses"
26
+ # ```
27
+ #
28
+ # A string that is not a plain column name is treated as an expression:
29
+ #
30
+ # ```
31
+ # create_statistics :users, ["lower(email)"], name: "users_lower_email_stat"
32
+ # ```
33
+ #
34
+ # The `options` hash can include the following keys:
35
+ #
36
+ # `:name`
37
+ # : The statistics name. Defaults to `stat_rails_<identifier>`.
38
+ #
39
+ # `:kinds`
40
+ # : The statistics kinds to build: any of `:ndistinct`, `:dependencies`, and `:mcv`.
41
+ # Defaults to every kind the server supports.
42
+ #
43
+ # `:if_not_exists`
44
+ # : Silently ignore if the statistics object already exists.
45
+ #
46
+ # `:target`
47
+ # : The object's statistics target (`ALTER STATISTICS ... SET STATISTICS`).
48
+ # Defaults to the server's `default_statistics_target`.
49
+ #
50
+ # Statistics are built by the next `ANALYZE` of the table.
51
+ def create_statistics(table_name, columns, **options)
52
+ name = statistics_name(table_name, columns: columns, **options)
53
+ kinds = Array(options[:kinds])
54
+
55
+ sql = +"CREATE STATISTICS"
56
+ sql << " IF NOT EXISTS" if options[:if_not_exists]
57
+ sql << " #{quote_table_name(name)}"
58
+ sql << " (#{kinds.map(&:to_s).join(', ')})" if kinds.any?
59
+ sql << " ON #{quoted_statistics_columns(columns)} FROM #{quote_table_name(table_name)}"
60
+
61
+ execute sql
62
+ execute "ALTER STATISTICS #{quote_table_name(name)} SET STATISTICS #{Integer(options[:target])}" unless options[:target].nil?
63
+ end
64
+
65
+ # Sets a column's statistics target, how much `ANALYZE` samples it. A nil
66
+ # target restores `default_statistics_target`.
67
+ #
68
+ # ```
69
+ # set_column_statistics_target :addresses, :city, 1000
70
+ # ```
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)}"
73
+ end
74
+
75
+ # Sets the statistics target of an expression index's column, by position
76
+ # (1-based), which is the only way PostgreSQL addresses it.
77
+ #
78
+ # ```
79
+ # set_index_statistics_target "index_addresses_on_lower_city", 1, 1000
80
+ # ```
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)}"
83
+ end
84
+
85
+ # Returns the explicit statistics targets on the given table's columns and
86
+ # on its indexes' columns, or a Hash of them keyed by table name when given
87
+ # an Array of tables.
88
+ def statistics_targets(table_name)
89
+ result = fetch_statistics_targets(Array(table_name).map(&:to_s))
90
+ table_name.is_a?(Array) ? result : result[table_name.to_s]
91
+ end
92
+
93
+ # Drops the given extended statistics object.
94
+ #
95
+ # ```
96
+ # drop_statistics :addresses, name: "addresses_city_zip_code_stat"
97
+ # ```
98
+ #
99
+ # The `columns` parameter will be ignored if present. It can be helpful
100
+ # to provide it, with the same options, in a migration's `change` method
101
+ # so it can be reverted. In that case, they will be used by #create_statistics.
102
+ def drop_statistics(table_name, columns = nil, **options)
103
+ name = statistics_name(table_name, columns: columns, **options)
104
+
105
+ execute "DROP STATISTICS#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(name)}"
106
+ end
107
+
108
+ private
109
+ # Columns are stored ordered by attribute number, ahead of any expressions,
110
+ # whatever order they were created in.
111
+ def fetch_statistics(tables)
112
+ return {} if tables.empty?
113
+
114
+ expressions = database_version >= 14_00_00 ? "pg_get_statisticsobjdef_expressions(s.oid)" : "NULL"
115
+ # `stxstattarget` is NULL for the default from PostgreSQL 17, -1 before it.
116
+ target = database_version >= 13_00_00 ? "s.stxstattarget" : "NULL"
117
+
118
+ fetch_statistics_by_schema(tables) do |schema, group|
119
+ quoted_names = group.map { |table| quote(extract_schema_qualified_name(table).last) }.join(", ")
120
+ sql = <<~SQL
121
+ WITH tables AS (
122
+ SELECT DISTINCT ON (c.relname) c.oid, c.relname, c.relkind
123
+ FROM pg_class c
124
+ JOIN pg_namespace n ON n.oid = c.relnamespace
125
+ WHERE n.nspname = #{schema}
126
+ AND c.relname IN (#{quoted_names})
127
+ ORDER BY c.relname, array_position(current_schemas(false), n.nspname)
128
+ )
129
+ SELECT t.relname AS table_name, s.stxname, sn.nspname, sn.nspname = #{schema} AS same_schema, s.stxkind,
130
+ (
131
+ SELECT array_agg(a.attname ORDER BY a.attnum)
132
+ FROM pg_attribute a
133
+ WHERE a.attrelid = t.oid AND a.attnum = ANY (s.stxkeys)
134
+ ) AS columns,
135
+ #{expressions} AS expressions,
136
+ #{target} AS target
137
+ FROM pg_statistic_ext s
138
+ JOIN tables t ON s.stxrelid = t.oid
139
+ JOIN pg_namespace sn ON sn.oid = s.stxnamespace
140
+ ORDER BY s.stxname
141
+ SQL
142
+
143
+ by_name = select_schema_rows(sql).group_by { |row| row["table_name"] }
144
+
145
+ group.index_with do |table|
146
+ bare_name = extract_schema_qualified_name(table).last
147
+ build_statistics(table, by_name[bare_name] || [])
148
+ end
149
+ end
150
+ end
151
+
152
+ # One query per schema for every table's column and index targets, since a
153
+ # dump asks for every table. NULL (PostgreSQL 17+) and -1 both mean default.
154
+ def fetch_statistics_targets(tables)
155
+ return {} if tables.empty?
156
+
157
+ fetch_statistics_by_schema(tables) do |schema, group|
158
+ quoted_names = group.map { |table| quote(extract_schema_qualified_name(table).last) }.join(", ")
159
+ sql = <<~SQL
160
+ WITH tables AS (
161
+ SELECT DISTINCT ON (c.relname) c.oid, c.relname
162
+ FROM pg_class c
163
+ JOIN pg_namespace n ON n.oid = c.relnamespace
164
+ WHERE n.nspname = #{schema}
165
+ AND c.relname IN (#{quoted_names})
166
+ ORDER BY c.relname, array_position(current_schemas(false), n.nspname)
167
+ )
168
+ SELECT t.relname AS table_name, 'column' AS kind, a.attname AS name, a.attnum, a.attstattarget AS target
169
+ FROM tables t
170
+ JOIN pg_attribute a ON a.attrelid = t.oid
171
+ WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attstattarget >= 0
172
+ UNION ALL
173
+ SELECT t.relname, 'index', ic.relname, a.attnum, a.attstattarget
174
+ FROM tables t
175
+ JOIN pg_index i ON i.indrelid = t.oid
176
+ JOIN pg_class ic ON ic.oid = i.indexrelid
177
+ JOIN pg_attribute a ON a.attrelid = ic.oid
178
+ WHERE a.attnum > 0 AND a.attstattarget >= 0
179
+ ORDER BY 1, 2, 3, 4
180
+ SQL
181
+
182
+ by_name = select_schema_rows(sql).group_by { |row| row["table_name"] }
183
+
184
+ group.index_with do |table|
185
+ schema_name, bare_name = extract_schema_qualified_name(table)
186
+ rows = by_name[bare_name] || []
187
+ columns = rows.select { |row| row["kind"] == "column" }.to_h { |row| [row["name"], row["target"].to_i] }
188
+ indexes = rows.select { |row| row["kind"] == "index" }.map do |row|
189
+ [schema_name ? "#{schema_name}.#{row['name']}" : row["name"], row["attnum"].to_i, row["target"].to_i]
190
+ end
191
+
192
+ StatisticsTargets.new(columns, indexes)
193
+ end
194
+ end
195
+ end
196
+
197
+ def select_schema_rows(sql)
198
+ if respond_to?(:query_all, true)
199
+ query_all(sql, "SCHEMA")
200
+ else
201
+ internal_exec_query(sql, "SCHEMA", allow_retry: true, materialize_transactions: false).to_a
202
+ end
203
+ end
204
+
205
+ def statistics_target_value(target)
206
+ target.nil? ? -1 : Integer(target)
207
+ end
208
+
209
+ def fetch_statistics_by_schema(tables, &block)
210
+ if respond_to?(:fetch_by_schema, true)
211
+ fetch_by_schema(tables, &block)
212
+ else
213
+ tables.group_by { |table| extract_schema_qualified_name(table).first }.each_with_object({}) do |(schema_name, group), result|
214
+ schema = schema_name ? quote(schema_name) : "ANY (current_schemas(false))"
215
+ result.merge!(yield(schema, group))
216
+ end
217
+ end
218
+ end
219
+
220
+ def build_statistics(table_name, rows)
221
+ rows.map do |row|
222
+ name = row["same_schema"] ? row["stxname"] : "#{row['nspname']}.#{row['stxname']}"
223
+ columns = [row["columns"], row["expressions"]].compact.flat_map { |list| decode_statistics_string_array(list) }
224
+ kinds = decode_statistics_string_array(row["stxkind"]).filter_map { |kind| { "d" => :ndistinct, "f" => :dependencies, "m" => :mcv }[kind] }
225
+
226
+ target = row["target"]&.to_i
227
+ StatisticsDefinition.new(table_name, name, columns, kinds, target&.negative? ? nil : target)
228
+ end
229
+ end
230
+
231
+ def decode_statistics_string_array(value)
232
+ if respond_to?(:decode_string_array, true)
233
+ decode_string_array(value)
234
+ else
235
+ PG::TextDecoder::Array.new.decode(value)
236
+ end
237
+ end
238
+
239
+ # An unqualified name is created in the first schema on the search path,
240
+ # not the table's, so it takes the table's schema when the table names one.
241
+ def statistics_name(table_name, columns: nil, **options)
242
+ options.fetch(:name) do
243
+ raise ArgumentError, "Statistics require a name or columns" if columns.blank?
244
+
245
+ identifier = "#{table_name}_#{Array(columns).map(&:to_s) * '_and_'}_stat"
246
+ "stat_rails_#{Digest::SHA256.hexdigest(identifier).first(10)}"
247
+ end.then do |name|
248
+ schema, = extract_schema_qualified_name(table_name.to_s)
249
+ schema && !name.to_s.include?(".") ? "#{schema}.#{name}" : name
250
+ end
251
+ end
252
+
253
+ def quoted_statistics_columns(columns)
254
+ Array(columns).map do |column|
255
+ column = column.to_s
256
+ column.match?(/\A\w+\z/) ? quote_column_name(column) : "(#{column})"
257
+ end.join(", ")
258
+ end
259
+ end
260
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgStatisticsRails
4
+ # `target` is the object's explicit statistics target, or nil for the default.
5
+ StatisticsDefinition = Struct.new(:table_name, :name, :columns, :kinds, :target)
6
+
7
+ # Explicit `SET STATISTICS` targets on a table's columns and on its indexes'
8
+ # expression columns. `columns` maps a column name to its target; `indexes`
9
+ # holds `[index_name, column_number, target]`.
10
+ StatisticsTargets = Struct.new(:columns, :indexes) do
11
+ def empty?
12
+ columns.empty? && indexes.empty?
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgStatisticsRails
4
+ VERSION = "0.2.0"
5
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require_relative "pg_statistics_rails/version"
5
+ require_relative "pg_statistics_rails/statistics_definition"
6
+ require_relative "pg_statistics_rails/schema_statements"
7
+ require_relative "pg_statistics_rails/schema_dumper"
8
+ require_relative "pg_statistics_rails/command_recorder"
9
+
10
+ ActiveSupport.on_load(:active_record) do
11
+ require "active_record/migration/command_recorder"
12
+ ActiveRecord::Migration::CommandRecorder.include(PgStatisticsRails::CommandRecorder)
13
+ end
14
+
15
+ ActiveSupport.on_load(:active_record_postgresqladapter) do
16
+ unless ActiveRecord::ConnectionAdapters::PostgreSQL.const_defined?(:StatisticsDefinition)
17
+ ActiveRecord::ConnectionAdapters::PostgreSQL.const_set(
18
+ :StatisticsDefinition,
19
+ PgStatisticsRails::StatisticsDefinition
20
+ )
21
+ end
22
+
23
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.include(PgStatisticsRails::SchemaStatements)
24
+ ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaDumper.prepend(PgStatisticsRails::SchemaDumper)
25
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pg-statistics-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Andrew Fader
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activerecord
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: activesupport
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '7.1'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '7.1'
40
+ description: |-
41
+ Adds create_statistics, drop_statistics, and statistics introspection to the
42
+ Active Record PostgreSQL adapter, with reversible migration support and
43
+ automatic schema.rb dumping so extended statistics survive db:schema:load.
44
+ email:
45
+ - fader@yagni.co
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - CHANGELOG.md
51
+ - LICENSE.txt
52
+ - README.md
53
+ - lib/pg-statistics-rails.rb
54
+ - lib/pg_statistics_rails.rb
55
+ - lib/pg_statistics_rails/command_recorder.rb
56
+ - lib/pg_statistics_rails/schema_dumper.rb
57
+ - lib/pg_statistics_rails/schema_statements.rb
58
+ - lib/pg_statistics_rails/statistics_definition.rb
59
+ - lib/pg_statistics_rails/version.rb
60
+ homepage: https://github.com/andrewfader/pg-statistics-rails
61
+ licenses:
62
+ - MIT
63
+ metadata:
64
+ source_code_uri: https://github.com/andrewfader/pg-statistics-rails
65
+ changelog_uri: https://github.com/andrewfader/pg-statistics-rails/blob/main/CHANGELOG.md
66
+ rubygems_mfa_required: 'true'
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 3.1.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 4.0.20
82
+ specification_version: 4
83
+ summary: PostgreSQL extended statistics (CREATE STATISTICS) support for Active Record
84
+ migrations and schema.rb
85
+ test_files: []