trellis-pg 0.2.1 → 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 +4 -4
- data/README.md +327 -25
- data/ext/trellis_ruby/Cargo.lock +5 -5
- data/ext/trellis_ruby/Cargo.toml +3 -3
- data/ext/trellis_ruby/src/lib.rs +98 -11
- data/lib/trellis/instance.rb +4 -0
- data/lib/trellis/log_bridge.rb +201 -0
- data/lib/trellis/metrics.rb +129 -11
- data/lib/trellis/migration.rb +34 -0
- data/lib/trellis/pg.rb +37 -0
- data/lib/trellis/railtie.rb +119 -3
- data/lib/trellis/release_check.rb +165 -0
- data/lib/trellis/schema_dump.rb +26 -2
- data/lib/trellis/target.rb +141 -0
- data/lib/trellis/test_support.rb +176 -2
- data/lib/trellis/version.rb +1 -1
- metadata +4 -1
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "open3"
|
|
4
|
+
require "pathname"
|
|
5
|
+
|
|
6
|
+
module Trellis
|
|
7
|
+
# A static check for CI: does this release both change the trellis-pg
|
|
8
|
+
# gem's version and add a migration that uses Trellis?
|
|
9
|
+
#
|
|
10
|
+
# Such a release fails where migrations run before the old processes stop
|
|
11
|
+
# (a release phase, a pre-deploy job): while a worker of the old version is
|
|
12
|
+
# live, a define, ALTER, PAUSE, RESUME or DROP from the new version refuses
|
|
13
|
+
# with Trellis::VersionHandoverError (docs/embedding.md, "Rolling
|
|
14
|
+
# deploys"). The remedy is to ship the version change by itself and the
|
|
15
|
+
# migrations in the next release, and this check says so on the pull
|
|
16
|
+
# request instead of in the deploy.
|
|
17
|
+
#
|
|
18
|
+
# result = Trellis::ReleaseCheck.call(root: Rails.root, base: "origin/main")
|
|
19
|
+
# abort result.message unless result.ok?
|
|
20
|
+
#
|
|
21
|
+
# `rails trellis:release_check BASE=origin/main` runs it in a Rails app.
|
|
22
|
+
#
|
|
23
|
+
# It reads git and files only: no database, no Trellis handle, and none of
|
|
24
|
+
# the gem's extension. It compares the working tree under `root` with its
|
|
25
|
+
# merge base against `base`, so a branch that is behind `base` is judged by
|
|
26
|
+
# what the branch itself changes, and uncommitted work counts.
|
|
27
|
+
#
|
|
28
|
+
# It sees migrations only. A state-changing call from a deploy script or a
|
|
29
|
+
# console isn't in any file it reads; the engine's refusal covers those.
|
|
30
|
+
module ReleaseCheck
|
|
31
|
+
GEM_NAME = "trellis-pg"
|
|
32
|
+
|
|
33
|
+
# The check couldn't run: no base ref, not a git checkout, or a base
|
|
34
|
+
# this clone has no merge base with (a shallow clone, usually).
|
|
35
|
+
class Error < StandardError; end
|
|
36
|
+
|
|
37
|
+
# What the check found. `base` is the merge-base commit it compared with,
|
|
38
|
+
# the versions are trellis-pg's in the lockfile there and in the working
|
|
39
|
+
# tree (nil where the lockfile doesn't list the gem), and `migrations` are
|
|
40
|
+
# the migrations added since `base` that mention Trellis, relative to
|
|
41
|
+
# `root`.
|
|
42
|
+
Result = Data.define(:base, :old_version, :new_version, :migrations) do
|
|
43
|
+
# Any difference counts, a patch release and a downgrade too: Trellis
|
|
44
|
+
# versions match exactly, so every change of release is a handover. A
|
|
45
|
+
# release that adds the gem has no old worker to hand over from.
|
|
46
|
+
def version_changed?
|
|
47
|
+
!old_version.nil? && !new_version.nil? && old_version != new_version
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def ok?
|
|
51
|
+
!(version_changed? && migrations.any?)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def message
|
|
55
|
+
ok? ? ok_message : failure_message
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
def ok_message
|
|
61
|
+
version = if version_changed?
|
|
62
|
+
"#{GEM_NAME} changes from #{old_version} to #{new_version}"
|
|
63
|
+
else
|
|
64
|
+
"#{GEM_NAME} #{new_version || 'is not in the lockfile'}, unchanged"
|
|
65
|
+
end
|
|
66
|
+
"trellis:release_check: ok (#{version}; #{migrations.size} Trellis migration(s) added since #{base[0, 12]})"
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def failure_message
|
|
70
|
+
<<~MESSAGE.chomp
|
|
71
|
+
trellis:release_check: this release changes #{GEM_NAME} from #{old_version} to #{new_version} and adds Trellis migrations:
|
|
72
|
+
#{migrations.map { |path| " #{path}" }.join("\n")}
|
|
73
|
+
While a worker of #{old_version} is still running, #{new_version} may not define, alter, pause, resume
|
|
74
|
+
or drop a transform (Trellis::VersionHandoverError), so a deploy that migrates before the old
|
|
75
|
+
worker stops fails at these migrations. Ship the #{GEM_NAME} change by itself, then these
|
|
76
|
+
migrations in the next release.
|
|
77
|
+
MESSAGE
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
class << self
|
|
82
|
+
# Runs the check for the app at `root` against the git ref `base`: the
|
|
83
|
+
# branch a pull request targets, or the last deployed ref for a release
|
|
84
|
+
# of several merged pull requests. `migrations_paths` and `lockfile` are
|
|
85
|
+
# relative to `root` (absolute paths under it work too).
|
|
86
|
+
#
|
|
87
|
+
# Returns a Result; raises Error when the check can't run.
|
|
88
|
+
def call(root:, base:, migrations_paths: ["db/migrate"], lockfile: "Gemfile.lock")
|
|
89
|
+
root = Pathname(root).expand_path
|
|
90
|
+
base = base.to_s.strip
|
|
91
|
+
if base.empty?
|
|
92
|
+
raise Error, "set BASE to the git ref this release is compared with: the branch a pull " \
|
|
93
|
+
"request targets (BASE=origin/main), or the last deployed ref"
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Never an option to git, whatever the environment variable held.
|
|
97
|
+
raise Error, "#{base.inspect} is not a git ref" if base.start_with?("-")
|
|
98
|
+
|
|
99
|
+
merge_base = merge_base(root, base)
|
|
100
|
+
lockfile = relative(root, lockfile)
|
|
101
|
+
Result.new(
|
|
102
|
+
base: merge_base,
|
|
103
|
+
old_version: locked_version(git(root, "show", "#{merge_base}:./#{lockfile}", allow_failure: true)),
|
|
104
|
+
new_version: locked_version(read(root.join(lockfile))),
|
|
105
|
+
migrations: added_trellis_migrations(root, merge_base, migrations_paths.map { |path| relative(root, path) })
|
|
106
|
+
)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
private
|
|
110
|
+
|
|
111
|
+
def merge_base(root, base)
|
|
112
|
+
git(root, "rev-parse", "--is-inside-work-tree")
|
|
113
|
+
unless git(root, "rev-parse", "--verify", "--quiet", "#{base}^{commit}", allow_failure: true)
|
|
114
|
+
raise Error, "#{base} is not a commit this clone knows: fetch it first"
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
git(root, "merge-base", base, "HEAD", allow_failure: true)&.strip or
|
|
118
|
+
raise Error, "this checkout has no merge base with #{base}: fetch more history " \
|
|
119
|
+
"(a shallow clone has none; with actions/checkout, set fetch-depth: 0)"
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# trellis-pg's version in a lockfile's text: its `specs:` entry, without
|
|
123
|
+
# the platform a platform gem's entry carries (`0.2.0-x86_64-linux`).
|
|
124
|
+
# nil for no text or no entry.
|
|
125
|
+
def locked_version(text)
|
|
126
|
+
text&.[](/^ {4}#{Regexp.escape(GEM_NAME)} \(([^)-]+)/, 1)
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# The migrations under `paths` that the working tree has and
|
|
130
|
+
# `merge_base` hasn't (committed, staged or untracked), and that
|
|
131
|
+
# mention Trellis: the Trellis::Migration helpers, or a direct
|
|
132
|
+
# Trellis.apply. An edited old migration doesn't run again, so only
|
|
133
|
+
# added (and renamed) files count.
|
|
134
|
+
def added_trellis_migrations(root, merge_base, paths)
|
|
135
|
+
added = git(root, "diff", "--name-only", "-z", "--diff-filter=AR", "--relative", merge_base, "--", *paths)
|
|
136
|
+
untracked = git(root, "ls-files", "-z", "--others", "--exclude-standard", "--", *paths)
|
|
137
|
+
(added.split("\0") + untracked.split("\0"))
|
|
138
|
+
.uniq
|
|
139
|
+
.select { |path| path.end_with?(".rb") && read(root.join(path))&.match?(/\bTrellis\b/) }
|
|
140
|
+
.sort
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def read(path)
|
|
144
|
+
path.file? ? path.read : nil
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def relative(root, path)
|
|
148
|
+
path = Pathname(path)
|
|
149
|
+
(path.absolute? ? path.relative_path_from(root) : path).to_s
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# git's stdout, run in `root`. A failing command raises Error, or
|
|
153
|
+
# returns nil with allow_failure.
|
|
154
|
+
def git(root, *args, allow_failure: false)
|
|
155
|
+
out, err, status = Open3.capture3("git", *args, chdir: root.to_s)
|
|
156
|
+
return out if status.success?
|
|
157
|
+
return nil if allow_failure
|
|
158
|
+
|
|
159
|
+
raise Error, "git #{args.first} failed in #{root}: #{err.strip}"
|
|
160
|
+
rescue Errno::ENOENT => e
|
|
161
|
+
raise Error, "can't run git in #{root}: #{e.message}"
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
end
|
data/lib/trellis/schema_dump.rb
CHANGED
|
@@ -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
|
|
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
|
data/lib/trellis/test_support.rb
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require_relative "
|
|
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.
|
data/lib/trellis/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: trellis-pg
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.3.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Salesforce
|
|
@@ -41,11 +41,14 @@ files:
|
|
|
41
41
|
- ext/trellis_ruby/src/lib.rs
|
|
42
42
|
- lib/trellis/error.rb
|
|
43
43
|
- lib/trellis/instance.rb
|
|
44
|
+
- lib/trellis/log_bridge.rb
|
|
44
45
|
- lib/trellis/metrics.rb
|
|
45
46
|
- lib/trellis/migration.rb
|
|
46
47
|
- lib/trellis/pg.rb
|
|
47
48
|
- lib/trellis/railtie.rb
|
|
49
|
+
- lib/trellis/release_check.rb
|
|
48
50
|
- lib/trellis/schema_dump.rb
|
|
51
|
+
- lib/trellis/target.rb
|
|
49
52
|
- lib/trellis/test_support.rb
|
|
50
53
|
- lib/trellis/values.rb
|
|
51
54
|
- lib/trellis/version.rb
|