trellis-pg 0.2.1-aarch64-linux → 0.3.0-aarch64-linux

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.
@@ -47,6 +47,13 @@ module Trellis
47
47
  # that database: the instances' options with the database's host, port,
48
48
  # name, user and password from its config.
49
49
  #
50
+ # None of this applies to a database of an environment named in
51
+ # config.trellis.off_in (`%w[test]`): its load creates the target tables as
52
+ # plain tables and restores nothing, and its dump is Rails' own. A dump of
53
+ # such a database run from an environment Trellis is on in (`db:prepare` in
54
+ # development also dumps the test database) is skipped, since the file is
55
+ # that environment's.
56
+ #
50
57
  # A load that doesn't go through Rails (`psql -f structure.sql`) is followed
51
58
  # by `rails trellis:migrate`.
52
59
  #
@@ -88,9 +95,25 @@ module Trellis
88
95
  end
89
96
 
90
97
  # Whether Trellis's definitions belong in the dump of db_config: Trellis
91
- # is configured, and db_config is the database config.trellis.dump_database
92
- # names.
98
+ # is configured and on in db_config's environment, and db_config is
99
+ # the database config.trellis.dump_database names.
93
100
  def applies?(db_config)
101
+ configured_for?(db_config) && !Railtie.off_in?(db_config.env_name)
102
+ end
103
+
104
+ # Whether a dump of db_config is left undone: db_config belongs to an
105
+ # environment Trellis is off in, and the environment running the task is
106
+ # one it is on in. The dump file is the running environment's, and
107
+ # a dump of the off database would overwrite it with one that has no
108
+ # definitions.
109
+ def skip_dump?(db_config)
110
+ configured_for?(db_config) && Railtie.off_in?(db_config.env_name) &&
111
+ !Railtie.off_in?(::ActiveRecord::Tasks::DatabaseTasks.env)
112
+ end
113
+
114
+ # Whether Trellis is configured, and db_config is the database
115
+ # config.trellis.dump_database names.
116
+ def configured_for?(db_config)
94
117
  return false unless Railtie.connect_options || !Railtie.instance_options.empty?
95
118
 
96
119
  db_config.name == dump_database
@@ -353,6 +376,7 @@ module Trellis
353
376
  # versions to ActiveRecord.schema_format: the default is left to Rails'
354
377
  # own signature, which an unconfigured database goes straight to.
355
378
  def dump_schema(db_config, *args)
379
+ return nil if SchemaDump.skip_dump?(db_config)
356
380
  return super unless SchemaDump.applies?(db_config) && db_config.schema_dump
357
381
 
358
382
  format = SchemaDump.format_of(db_config, args)
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+ require_relative "pg"
5
+
6
+ module Trellis
7
+ # Raised for a write to a model over a Trellis target where Trellis is on.
8
+ # A ReadOnlyRecord, so code that rescues ActiveRecord's read-only error
9
+ # rescues this one too.
10
+ class ReadOnlyTarget < ActiveRecord::ReadOnlyRecord; end
11
+
12
+ # An ActiveRecord model over a target table: only Trellis writes a target,
13
+ # so every write ActiveRecord would send for the model raises
14
+ # Trellis::ReadOnlyTarget. Reads, scopes and associations are untouched.
15
+ #
16
+ # class EventCount < ApplicationRecord
17
+ # include Trellis::Target
18
+ # self.primary_key = [:account_id, :kind] # a GROUP BY target's key
19
+ # belongs_to :account
20
+ # end
21
+ #
22
+ # Where Trellis is off (config.trellis.off_in, so Trellis.enabled? is
23
+ # false) a target is an ordinary table that tests fill, and the model
24
+ # writes like any other. Trellis::Target.allow_writes does the same for a
25
+ # block, for a suite that runs with Trellis on.
26
+ #
27
+ # The guard sits where ActiveRecord builds each write: the record writes
28
+ # (save, update, update_columns, touch, increment!, delete, destroy) all
29
+ # reach the class's _insert_record, _update_record or _delete_record, and
30
+ # the bulk ones (insert_all, upsert_all, update_all, update_counters,
31
+ # touch_all, delete_all, delete_by) the relation's insert_all, insert_all!,
32
+ # upsert_all, update_all or delete_all, whether called on the class, a
33
+ # scope or an association. SQL sent through the connection (execute,
34
+ # fixtures) goes around it: that is the database grant's job
35
+ # (docs/recommendations.md, "Application roles read targets, and nothing
36
+ # else").
37
+ module Target
38
+ extend ActiveSupport::Concern
39
+
40
+ DOCS = "https://github.com/salesforce-misc/trellis/tree/main/clients/ruby#targets-as-models"
41
+ RELATION_WRITES = %i[insert_all insert_all! upsert_all update_all delete_all].freeze
42
+ ALLOWED = :trellis_target_writes_allowed
43
+
44
+ class << self
45
+ # Lets this thread write target models for the block, where Trellis
46
+ # is on: a test that stubs a target's rows by hand. Returns the
47
+ # block's value.
48
+ def allow_writes
49
+ state = ActiveSupport::IsolatedExecutionState
50
+ allowed = state[ALLOWED]
51
+ state[ALLOWED] = true
52
+ yield
53
+ ensure
54
+ state[ALLOWED] = allowed
55
+ end
56
+
57
+ # Whether target models write here: Trellis is off in this
58
+ # environment, or inside allow_writes.
59
+ def writable?
60
+ !Trellis.enabled? || ActiveSupport::IsolatedExecutionState[ALLOWED] == true
61
+ end
62
+
63
+ # Raises ReadOnlyTarget unless writable?. `write` names it: the
64
+ # relation method, or the statement a record write sends.
65
+ def guard!(model, write)
66
+ return if writable?
67
+
68
+ raise ReadOnlyTarget,
69
+ "#{model.name} is a model over the Trellis target #{model.table_name}, which only Trellis " \
70
+ "writes: #{write} refused. Tests write it with Trellis off (config.trellis.off_in) or in " \
71
+ "Trellis::Target.allow_writes; see #{DOCS}"
72
+ end
73
+
74
+ # The ActiveRecord internals the guard overrides that this
75
+ # ActiveRecord lacks. They are :nodoc:, so a release may move one, and
76
+ # the guard would then let that write through: including the concern
77
+ # raises instead.
78
+ def missing_internals
79
+ records = %i[_insert_record _update_record _delete_record].reject do |write|
80
+ ActiveRecord::Base.respond_to?(write, true)
81
+ end
82
+ relations = RELATION_WRITES.reject { |write| ActiveRecord::Relation.method_defined?(write) }
83
+ delegation = [[ActiveRecord::Delegation, :delegated_classes], [ActiveRecord::Base, :relation_delegate_class]]
84
+ .reject { |owner, method| owner.respond_to?(method, true) }.map(&:last)
85
+ records + relations + delegation
86
+ end
87
+
88
+ # Every relation of `model` (Model.where, Model.all, association
89
+ # scopes) is an instance of one of its relation classes.
90
+ def guard_relations(model)
91
+ ActiveRecord::Delegation.delegated_classes.each do |relation|
92
+ model.relation_delegate_class(relation).prepend(RelationGuard)
93
+ end
94
+ end
95
+ end
96
+
97
+ module RelationGuard
98
+ RELATION_WRITES.each do |write|
99
+ define_method(write) do |*args, **options, &block|
100
+ Target.guard!(model, write)
101
+ super(*args, **options, &block)
102
+ end
103
+ end
104
+ end
105
+
106
+ included do
107
+ missing = Target.missing_internals
108
+ unless missing.empty?
109
+ raise NotImplementedError,
110
+ "Trellis::Target can't guard #{name} on ActiveRecord #{ActiveRecord.version}, which has no " \
111
+ "#{missing.join(", ")}: writes to it would go through unrefused"
112
+ end
113
+
114
+ Target.guard_relations(self)
115
+ end
116
+
117
+ class_methods do
118
+ # A subclass (single-table inheritance) gets relation classes of its
119
+ # own.
120
+ def inherited(subclass)
121
+ super
122
+ Target.guard_relations(subclass)
123
+ end
124
+
125
+ def _insert_record(...)
126
+ Target.guard!(self, "INSERT")
127
+ super
128
+ end
129
+
130
+ def _update_record(...)
131
+ Target.guard!(self, "UPDATE")
132
+ super
133
+ end
134
+
135
+ def _delete_record(...)
136
+ Target.guard!(self, "DELETE")
137
+ super
138
+ end
139
+ end
140
+ end
141
+ end
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "error"
4
- require_relative "instance"
3
+ require_relative "pg"
5
4
 
6
5
  module Trellis
7
6
  # Helpers for a test suite that loads fixtures or bulk data into tables
@@ -34,6 +33,13 @@ module Trellis
34
33
  #
35
34
  # The call is cheap when nothing was disrupted (one catalog read per
36
35
  # captured table), so running it before every test is fine.
36
+ #
37
+ # Where Trellis is off (config.trellis.off_in), refresh_trellis_target fills
38
+ # a target from its definition's own query, inside the test's transaction:
39
+ #
40
+ # 3.times { Event.create!(account: accounts(:one)) }
41
+ # refresh_trellis_target :event_counts
42
+ # assert_equal 3, accounts(:one).event_count.events_count
37
43
  module TestSupport
38
44
  # Raised when a RESUME is refused or a resumed definition pauses again.
39
45
  # `refused` maps each such target (as "schema.table") to the reason: the
@@ -51,6 +57,9 @@ module Trellis
51
57
  end
52
58
 
53
59
  POLL_SECONDS = 0.05
60
+ # The schema Trellis keeps an instance's tables in, unless its connect
61
+ # options name another.
62
+ DEFAULT_SCHEMA = "trellis"
54
63
  # How a CaptureFailure's error starts while a resume is still under way.
55
64
  RESUMING = "resuming:"
56
65
 
@@ -111,6 +120,171 @@ module Trellis
111
120
  end
112
121
  end
113
122
 
123
+ # Fills `target` (a table name, "schema.table", or a model class) from
124
+ # its definition, as a fresh build would compute it from the tables it
125
+ # reads as they stand: `DELETE FROM` the target, then `INSERT INTO` it
126
+ # the rows of the SELECT the engine renders from the definition
127
+ # (Trellis::Native.target_select_sql). It runs on `connection`, the
128
+ # test's own, so it sees the test's uncommitted rows and rolls back with
129
+ # the test. It doesn't exercise capture, the drain or any pause. A table
130
+ # the definition names without a schema resolves on the connection's
131
+ # search_path. Returns the number of rows written.
132
+ #
133
+ # The definition is the one the schema load left in the restore queue
134
+ # (`trellis.restore_queue`, or the schema config.trellis.connect or
135
+ # config.trellis.instances names). A definition that reads another
136
+ # transform's target refreshes that target first.
137
+ #
138
+ # Raises Trellis::NotFoundError when the target has no definition, and
139
+ # Trellis::ValidationError when Trellis is on in this environment
140
+ # (Trellis.enabled?), where the engine maintains the target and would
141
+ # overwrite what this writes. `trellis_on: true` writes anyway, reading
142
+ # the definition from the instance's catalog when there is no queue.
143
+ def refresh_trellis_target(target, connection: nil, trellis_on: false)
144
+ if Trellis.enabled? && !trellis_on
145
+ raise ValidationError,
146
+ "refresh_trellis_target fills a target where Trellis is off (config.trellis.off_in), and " \
147
+ "Trellis is on here: the engine maintains #{TargetRefresh.target_name(target)}. Pass " \
148
+ "trellis_on: true to write it anyway"
149
+ end
150
+
151
+ TargetRefresh.refresh(target, connection || TargetRefresh.active_record_connection)
152
+ end
153
+
154
+ # refresh_trellis_target's steps, kept off the test classes that include
155
+ # TestSupport so a test's own helper of the same name can't replace one.
156
+ module TargetRefresh
157
+ module_function
158
+
159
+ def refresh(target, connection)
160
+ definitions = recorded_definitions(connection)
161
+ refresh_target(connection, find_definition(definitions, target_name(target)), definitions, [])
162
+ end
163
+
164
+ # Refreshes each target `definition` reads that has a definition of its
165
+ # own, then `definition`'s. `path` holds the targets being refreshed
166
+ # below, which a stored definition can't read back.
167
+ def refresh_target(connection, definition, definitions, path)
168
+ target = definition.fetch(:target)
169
+ definition.fetch(:reads).each do |table|
170
+ upstream = definitions.find { |d| d.fetch(:target) == table }
171
+ refresh_target(connection, upstream, definitions, path + [target]) if upstream && !path.include?(table)
172
+ end
173
+
174
+ schema, table = target.split(".", 2)
175
+ quoted = "#{connection.quote_column_name(schema)}.#{connection.quote_column_name(table)}"
176
+ columns = connection.select_values(
177
+ "select a.attname::text from pg_catalog.pg_attribute a " \
178
+ "where a.attrelid = pg_catalog.to_regclass(#{connection.quote(quoted)}) " \
179
+ "and a.attnum > 0 and not a.attisdropped order by a.attnum"
180
+ )
181
+ raise NotFoundError, "the target #{target} of a recorded definition is no table" if columns.empty?
182
+
183
+ select = Trellis::Native.target_select_sql(definition.fetch(:text), definition.fetch(:grammar_version),
184
+ columns)
185
+ column_list = columns.map { |column| connection.quote_column_name(column) }.join(", ")
186
+ connection.exec_update("delete from #{quoted}")
187
+ connection.exec_update("insert into #{quoted} (#{column_list}) #{select}")
188
+ end
189
+
190
+ # Every definition recorded in the database, as hashes of :target and
191
+ # :reads ("schema.table" names, as the dump resolved them), :text and
192
+ # :grammar_version: a schema load's restore queue where there is one,
193
+ # and otherwise an instance's catalog.
194
+ def recorded_definitions(connection)
195
+ trellis_schemas.flat_map do |schema|
196
+ quoted = connection.quote_column_name(schema)
197
+ if regclass?(connection, "#{quoted}.restore_queue")
198
+ queued_definitions(connection, quoted)
199
+ elsif regclass?(connection, "#{quoted}.transform_definitions")
200
+ cataloged_definitions(connection, quoted)
201
+ else
202
+ []
203
+ end
204
+ end
205
+ end
206
+
207
+ def queued_definitions(connection, quoted_schema)
208
+ queue = "#{quoted_schema}.restore_queue"
209
+ # A dump with a definition that joins more than two tables has one more
210
+ # column (trellis::dump::RESTORE_QUEUE).
211
+ later = connection.select_value(
212
+ "select count(*) from pg_catalog.pg_attribute where attrelid = #{connection.quote(queue)}::regclass " \
213
+ "and attname = 'later_join_tables' and not attisdropped"
214
+ ).to_i.positive? ? "later_join_tables" : "'{}'::text[]"
215
+ definitions(connection, "select target_table, source_table, " \
216
+ "array_remove(array[join_table], null) || #{later}, definition_text, " \
217
+ "grammar_version from #{queue}")
218
+ end
219
+
220
+ def cataloged_definitions(connection, quoted_schema)
221
+ definitions(connection, "select d.target_table, d.source_table, " \
222
+ "array(select j.table_name from (select 1 as position, d.join_table as table_name " \
223
+ "where d.join_table is not null union all select f.position, f.table_name " \
224
+ "from #{quoted_schema}.definition_join_tables f where f.transform_id = d.id) j " \
225
+ "order by j.position), d.definition_text, d.grammar_version " \
226
+ "from #{quoted_schema}.transform_definitions d")
227
+ end
228
+
229
+ def definitions(connection, sql)
230
+ connection.select_rows("select target_table, source_table || joined, definition_text, grammar_version " \
231
+ "from (#{sql}) as d(target_table, source_table, joined, definition_text, " \
232
+ "grammar_version)").map do |target, reads, text, version|
233
+ { target:, reads: decode_text_array(connection, reads), text:, grammar_version: Integer(version) }
234
+ end
235
+ end
236
+
237
+ # The definition of `name` ("table" or "schema.table") among `definitions`.
238
+ def find_definition(definitions, name)
239
+ matches = definitions.select do |definition|
240
+ target = definition.fetch(:target)
241
+ name.include?(".") ? target == name : target.split(".", 2).last == name
242
+ end
243
+ case matches.size
244
+ when 1 then matches.first
245
+ when 0
246
+ raise NotFoundError,
247
+ "no Trellis definition is recorded for the target #{name}: refresh_trellis_target reads " \
248
+ "the definitions the schema load left in #{trellis_schemas.map { |s| "#{s}.restore_queue" }.join(', ')}"
249
+ else
250
+ raise ValidationError,
251
+ "#{name} names more than one target (#{matches.map { |d| d.fetch(:target) }.join(', ')}): " \
252
+ "qualify it as schema.table"
253
+ end
254
+ end
255
+
256
+ # The schemas Trellis keeps its tables in: each configured instance's.
257
+ def trellis_schemas
258
+ options = []
259
+ if defined?(Trellis::Railtie)
260
+ options << Trellis::Railtie.connect_options
261
+ options.concat(Trellis::Railtie.instance_options.values)
262
+ end
263
+ schemas = options.compact.map { |option| option.fetch(:schema, DEFAULT_SCHEMA).to_s }
264
+ schemas.empty? ? [DEFAULT_SCHEMA] : schemas.uniq
265
+ end
266
+
267
+ def target_name(target)
268
+ target.respond_to?(:table_name) ? target.table_name.to_s : target.to_s
269
+ end
270
+
271
+ def regclass?(connection, name)
272
+ !connection.select_value("select pg_catalog.to_regclass(#{connection.quote(name)})::text").nil?
273
+ end
274
+
275
+ def decode_text_array(connection, value)
276
+ return value if value.is_a?(Array)
277
+
278
+ connection.select_values("select unnest(#{connection.quote(value)}::text[])")
279
+ end
280
+
281
+ def active_record_connection
282
+ base = ::ActiveRecord::Base
283
+ base.respond_to?(:lease_connection) ? base.lease_connection : base.connection
284
+ end
285
+ end
286
+ private_constant :TargetRefresh
287
+
114
288
  # Waits for `target` to be :live. A resumed definition that pauses
115
289
  # again (its rebuild failed) is recorded in `refused` instead of waited
116
290
  # for.
@@ -3,5 +3,5 @@
3
3
  module Trellis
4
4
  # The trellis-pg gem's version: the Trellis release's, which a
5
5
  # `v<VERSION>` tag releases (docs/releasing.md).
6
- VERSION = "0.2.1"
6
+ VERSION = "0.3.0"
7
7
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: trellis-pg
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.1
4
+ version: 0.3.0
5
5
  platform: aarch64-linux
6
6
  authors:
7
7
  - Salesforce
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-13 00:00:00.000000000 Z
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: |
14
14
  A native extension over the trellis crate's BlockingTrellis, so a Rails
@@ -25,11 +25,14 @@ files:
25
25
  - lib/trellis/4.0/trellis_ruby.so
26
26
  - lib/trellis/error.rb
27
27
  - lib/trellis/instance.rb
28
+ - lib/trellis/log_bridge.rb
28
29
  - lib/trellis/metrics.rb
29
30
  - lib/trellis/migration.rb
30
31
  - lib/trellis/pg.rb
31
32
  - lib/trellis/railtie.rb
33
+ - lib/trellis/release_check.rb
32
34
  - lib/trellis/schema_dump.rb
35
+ - lib/trellis/target.rb
33
36
  - lib/trellis/test_support.rb
34
37
  - lib/trellis/values.rb
35
38
  - lib/trellis/version.rb