exwiw 0.5.1 → 0.5.2

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: 2af5a1cc29946424a2b6498f19d7ad77714f108194575ddd6014c5fc2d829416
4
- data.tar.gz: 3113e80b88ab11a95344140f819a9247eadc3706c45a9b2a665f946a88a945b7
3
+ metadata.gz: 567683d65df5d9f147ab9415a67baf48a80e21ad32e1ef7635c624dfc3d28c47
4
+ data.tar.gz: 1513b577f6f2368df60edc45a54c96495ece4f1ee9b453e92adb8991f182fcdf
5
5
  SHA512:
6
- metadata.gz: 539f4ab428d75f97714475d607d91ae2870a2bf860ac8ab2f732d5a5709d5e0cf2fd085c0bc3bbdf9b095f969542eb866c1f3c3766cc5e3a8be0294cf3cfcf0f
7
- data.tar.gz: 7b41f191e5e6d5ff60a1c927111d06f85b6c461a1dd63d5665b254338eafcde037233bb7f67027306258515e71aa1af3cf38e6aadf20b02ec9f6a91f05c7f2c4
6
+ metadata.gz: a9680642eb34f99ed3f0c2924154a5171edf541286dfed14befe15b8c029271419a13d3295694847b1143898b0200bf6eb1d6448e6665dbad7bef026e3c3fbbb
7
+ data.tar.gz: 30e6ef9f988965b85f899fdb0646b6e4e2befd68f95a247a9edfeddb8d3a6088f611f07d5376c7d3b9f4f58f147072e03294a140312dec1622994fb6da175720
data/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.5.2] - 2026-06-18
6
+
7
+ ### Fixed
8
+
9
+ - **PostgreSQL: an extension the restore target cannot create no longer aborts the restore, and `pglogical` is never emitted.** `dump_schema` prepends `CREATE EXTENSION IF NOT EXISTS` for every extension installed on the source, wrapped in a `DO` block that previously swallowed only `feature_not_supported` (the extension's binaries are unavailable on the target). A source on managed Postgres/AlloyDB carrying `pglogical` (logical replication) emitted `CREATE EXTENSION ... SCHEMA "pglogical"`, which on a target lacking that schema fails with `invalid_schema_name` — an error the handler did not catch, so the whole restore aborted. The handler now also catches `invalid_schema_name`, and instead of silently discarding the skip it re-raises it as a `WARNING` (carrying SQLSTATE and the original message) so the skip is visible in the restore logs rather than vanishing. `insufficient_privilege` is intentionally **not** caught: a restore role lacking `CREATE` privilege is a misconfiguration that must fail loudly. Separately, `pglogical` is now excluded from the prepended extensions entirely (alongside `plpgsql` and the `google_*`/`rds_*`/`aiven_*` managed-platform extensions) — it is a replication mechanism of the source, not part of the copied data.
10
+ - **Table processing order no longer aborts on `belongs_to` cycles.** Two distinct problems made `export`/`explain` fail with "Circular belongs_to dependency detected" on schemas that have no resolvable order: (1) a `belongs_to` whose target table is **not part of the run** — most commonly an embedded MongoDB collection, which is masked through its parent and never dumped on its own — was treated as a dependency that could never be satisfied, so every table that (transitively) referenced one froze and was misreported as a cycle; such out-of-run targets are now ignored when ordering. (2) A **genuine** cycle (e.g. `a belongs_to b` and `b belongs_to a`) now **breaks deterministically with a warning** instead of raising: exwiw emits the cycle member (a table in a strongly-connected component of the unresolved-dependency graph) with the fewest unresolved dependencies, preferring one that still has an already-ordered parent so its extraction stays constrained, and logs which `belongs_to` edge was dropped. The dropped edge is not enforced while ordering, so for the mongodb adapter that table may match a superset of rows (the not-yet-processed parent contributes no `$in` filter); mark one of the `belongs_to` entries forming the cycle with `ignore: true` to break it explicitly instead. Acyclic tables that merely wait on a cycle are never reordered ahead of their parents.
11
+ - **MongoDB: `dump_schema` tolerates collections declared in the schema but absent from the source database.** Listing indexes for a non-existent collection makes the driver raise `NamespaceNotFound` (code 26), which aborted the whole export when the schema covered more collections than the connected database actually had (schema/DB drift, or a sparse development database). The existing collections are now resolved once up front and indexes are emitted only for those; `createCollection` is still emitted for every configured collection, so the target schema is created in full.
12
+ - **MongoDB: a related collection that cannot be scoped no longer falls back to dumping the whole collection.** When a non-target collection's `belongs_to` parents all yield no ids to filter by — because every parent matched nothing or is not dumped on its own (e.g. an embedded collection) — the assembled filter is empty. Previously that empty filter was sent as `find({})`, scanning and dumping the **entire collection across every scope** (a cross-scope data-exposure risk). Such a collection is now constrained to match no rows and a warning is logged instead. A collection with no `belongs_to` at all is still treated as reference/master data and dumped in full.
13
+
5
14
  ## [0.5.1] - 2026-06-18
6
15
 
7
16
  ### Added
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
+ require 'set'
4
5
 
5
6
  # NOTE: This adapter consumes MongodbCollectionConfig (`fields` instead of
6
7
  # `columns`, plus `embedded_in`). Top-level collections are dumped as one
@@ -71,16 +72,7 @@ module Exwiw
71
72
  { config.primary_key => { "$in" => coerce_ids(dump_target.ids) } }
72
73
  end
73
74
  else
74
- config.belongs_tos.each_with_object({}) do |relation, acc|
75
- # Constrain by the parent field this FK actually references
76
- # (`relation.references`, default the parent primary_key). The
77
- # values were captured from that field's documents in #execute, so
78
- # their BSON type already matches the stored FK — no coercion.
79
- values = parent_state_for(relation, config_by_name)
80
- next if values.nil? || values.empty?
81
-
82
- acc[relation.foreign_key] = { "$in" => values }
83
- end
75
+ related_collection_filter(config, config_by_name)
84
76
  end
85
77
 
86
78
  Exwiw::MongoQuery::Find.new(
@@ -160,6 +152,14 @@ module Exwiw
160
152
 
161
153
  collections = ordered_tables.reject(&:embedded?)
162
154
 
155
+ # Index listing targets a specific collection, and MongoDB raises
156
+ # NamespaceNotFound (code 26) for one that does not exist. The schema may
157
+ # declare collections absent from this database (schema/DB drift, or a
158
+ # sparse dev DB), so resolve the set that actually exists up front and emit
159
+ # indexes only for those. `createCollection` is still emitted for every
160
+ # config below, so the target schema is created in full regardless.
161
+ existing_collections = db.database.collection_names.to_set
162
+
163
163
  File.open(output_path, 'w') do |file|
164
164
  file.puts("// Auto-generated by exwiw. Apply with: mongosh \"$MONGODB_URI\" #{File.basename(output_path)}")
165
165
  file.puts
@@ -172,6 +172,11 @@ module Exwiw
172
172
 
173
173
  collections.each do |config|
174
174
  name = config.name
175
+ unless existing_collections.include?(name)
176
+ @logger.debug(" Collection '#{name}' is not present in the source database; emitting no indexes.")
177
+ next
178
+ end
179
+
175
180
  indexes = db[name].indexes.to_a.reject { |idx| idx['name'] == '_id_' }
176
181
  indexes.each do |idx|
177
182
  key = idx['key']
@@ -274,6 +279,39 @@ module Exwiw
274
279
  ([config.primary_key] + referenced).uniq
275
280
  end
276
281
 
282
+ # Build the scoping filter for a non-target collection from its belongs_to
283
+ # parents' captured ids. Each belongs_to is constrained by the parent field
284
+ # the FK references (`relation.references`, default the parent primary_key);
285
+ # the values were captured from that field in #execute, so their BSON type
286
+ # already matches the stored FK — no coercion.
287
+ #
288
+ # A belongs_to whose parent produced no ids contributes no constraint:
289
+ # either the parent matched nothing, or it is not dumped here (e.g. an
290
+ # embedded collection, or one excluded from the run). If that leaves the
291
+ # filter empty even though the collection HAS belongs_to, the collection
292
+ # cannot be scoped from the dump target — and falling back to an empty `{}`
293
+ # filter would scan and dump the ENTIRE collection across every scope. That
294
+ # is never what a scoped extraction wants, so constrain it to match nothing
295
+ # and warn instead. (A collection with no belongs_to at all is genuine
296
+ # reference/master data and is still dumped in full via `{}`.)
297
+ private def related_collection_filter(config, config_by_name)
298
+ filter = config.belongs_tos.each_with_object({}) do |relation, acc|
299
+ values = parent_state_for(relation, config_by_name)
300
+ next if values.nil? || values.empty?
301
+
302
+ acc[relation.foreign_key] = { "$in" => values }
303
+ end
304
+
305
+ return filter unless filter.empty? && config.belongs_tos.any?
306
+
307
+ @logger.warn(
308
+ " Collection '#{config.name}' has belongs_to but no parent produced ids to scope by " \
309
+ "(parents matched nothing, or are not dumped on their own such as embedded collections). " \
310
+ "Constraining it to match no rows to avoid an unscoped full-collection dump."
311
+ )
312
+ { config.primary_key => { "$in" => [] } }
313
+ end
314
+
277
315
  # The captured parent-collection values a child belongs_to should be
278
316
  # constrained by: the values of the parent field the FK references
279
317
  # (`relation.references`, default the parent primary_key). nil when the
@@ -65,7 +65,18 @@ module Exwiw
65
65
  ext_ddl = extensions.map do |extname, schema|
66
66
  stmt = "CREATE EXTENSION IF NOT EXISTS #{connection.quote_ident(extname)}"
67
67
  stmt += " SCHEMA #{connection.quote_ident(schema)}" unless schema == "public"
68
- "DO $$ BEGIN #{stmt}; EXCEPTION WHEN feature_not_supported THEN NULL; END $$;"
68
+ # Best-effort prepend: a restore target that genuinely cannot create the
69
+ # extension should not abort the whole restore. Two such cases are caught:
70
+ # feature_not_supported (0A000) -- the extension's binaries are unavailable
71
+ # invalid_schema_name (3F000) -- the extension's required schema is absent
72
+ # insufficient_privilege (42501) is deliberately NOT caught: a restore role
73
+ # lacking CREATE privilege is a misconfiguration to fix, not to skip silently.
74
+ # The skip is re-raised as a WARNING so it surfaces in the restore logs
75
+ # instead of vanishing.
76
+ warning = connection.escape_literal("exwiw: skipped CREATE EXTENSION #{extname} (SQLSTATE %): %")
77
+ "DO $$ BEGIN #{stmt}; " \
78
+ "EXCEPTION WHEN feature_not_supported OR invalid_schema_name THEN " \
79
+ "RAISE WARNING #{warning}, SQLSTATE, SQLERRM; END $$;"
69
80
  end.join("\n") + "\n\n"
70
81
  @logger.debug(" Found #{extensions.size} extension(s) to prepend.")
71
82
  stdout = ext_ddl + stdout
@@ -382,11 +393,17 @@ module Exwiw
382
393
  end
383
394
 
384
395
  private def query_extensions
396
+ # Skip plpgsql (always present) and managed-platform bookkeeping extensions
397
+ # (google_*/rds_*/aiven_*). pglogical is also skipped: it is a logical-
398
+ # replication mechanism of the source, not part of the data being copied,
399
+ # and its dedicated `pglogical` schema is typically absent on the restore
400
+ # target — so prepending CREATE EXTENSION for it only breaks the restore.
385
401
  sql = <<~SQL
386
402
  SELECT e.extname, n.nspname
387
403
  FROM pg_extension e
388
404
  JOIN pg_namespace n ON n.oid = e.extnamespace
389
405
  WHERE e.extname != 'plpgsql'
406
+ AND e.extname != 'pglogical'
390
407
  AND e.extname NOT LIKE 'google\\_%' ESCAPE '\\'
391
408
  AND e.extname NOT LIKE 'rds\\_%' ESCAPE '\\'
392
409
  AND e.extname NOT LIKE 'aiven\\_%' ESCAPE '\\'
@@ -1,35 +1,58 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "set"
4
+
3
5
  module Exwiw
4
6
  module DetermineTableProcessingOrder
5
7
  module_function
6
8
 
7
9
  # @param tables [Array<Exwiw::TableConfig>] tables
10
+ # @param logger [Logger, nil] receives a warning when a cycle has to be broken
8
11
  # @return [Array<String>] sorted table names
9
- def run(tables)
12
+ def run(tables, logger: nil)
10
13
  return tables.map(&:name) if tables.size < 2
11
14
 
12
15
  ordered_table_names = []
16
+ ordered = Set.new
13
17
 
14
18
  table_by_name = tables.each_with_object({}) do |table, acc|
15
19
  acc[table.name] = table
16
20
  end
17
21
 
22
+ # Only belongs_to relations whose target is also in this run constrain the
23
+ # order. A belongs_to pointing at a table that is not being processed here
24
+ # — e.g. an embedded MongoDB collection (masked through its parent, never
25
+ # dumped on its own) or any table excluded from the run — is not something
26
+ # we can or need to order against, so it must never block resolution.
27
+ # Without this, such a dependency would stay unresolved forever and
28
+ # masquerade as a circular dependency, freezing every table that
29
+ # (transitively) references it.
30
+ present_names = table_by_name.keys.to_set
31
+
18
32
  loop do
19
33
  break if table_by_name.empty?
20
34
 
21
- tables_with_no_dependencies = table_by_name.values.select do |table|
22
- not_resolved_names = compute_table_dependencies(table) - ordered_table_names - [table.name]
23
-
24
- not_resolved_names.empty?
35
+ resolvable = table_by_name.values.select do |table|
36
+ unresolved_dependencies(table, present_names, ordered).empty?
25
37
  end
26
38
 
27
- if tables_with_no_dependencies.empty?
28
- raise ArgumentError, build_cycle_error_message(table_by_name, ordered_table_names)
39
+ if resolvable.empty?
40
+ # No table has all its (in-run) dependencies satisfied, yet tables
41
+ # remain: the belongs_to graph has a genuine cycle and no strict
42
+ # topological order exists. Rather than aborting the whole export, break
43
+ # the cycle by emitting one cycle member; see pick_cycle_victim for how
44
+ # the member is chosen. Warn so the dropped constraint is visible.
45
+ victim = pick_cycle_victim(table_by_name.values, present_names, ordered)
46
+ warn_cycle_break(logger, victim, unresolved_dependencies(victim, present_names, ordered))
47
+ resolvable = [victim]
29
48
  end
30
49
 
31
- tables_with_no_dependencies.each do |table|
50
+ # In the normal (acyclic) path, emit every currently-resolvable table in
51
+ # insertion order — preserving the historical ordering the snapshot specs
52
+ # depend on. The cycle-break path emits exactly its single chosen victim.
53
+ resolvable.each do |table|
32
54
  ordered_table_names << table.name
55
+ ordered << table.name
33
56
  table_by_name.delete(table.name)
34
57
  end
35
58
  end
@@ -37,30 +60,124 @@ module Exwiw
37
60
  ordered_table_names
38
61
  end
39
62
 
63
+ # The belongs_to target table names of `table`. A polymorphic belongs_to is
64
+ # expanded into one entry per concrete target by schema generation, so each
65
+ # entry is a plain table name here.
40
66
  def compute_table_dependencies(table)
41
- table.belongs_tos.each_with_object([]) do |relation, acc|
42
- acc << relation.table_name
67
+ table.belongs_tos.map(&:table_name)
68
+ end
69
+
70
+ # The dependencies still blocking `table`: belongs_to targets that are part
71
+ # of this run, not yet ordered, and not the table itself (a self-referential
72
+ # belongs_to never blocks).
73
+ private_class_method def unresolved_dependencies(table, present_names, ordered)
74
+ compute_table_dependencies(table).uniq.select do |dep|
75
+ present_names.include?(dep) && !ordered.include?(dep) && dep != table.name
43
76
  end
44
77
  end
45
78
 
46
- # When no table can be resolved but some remain, the belongs_to graph
47
- # contains a cycle (e.g. A belongs_to B and B belongs_to A). A topological
48
- # order cannot exist, so report the offending tables instead of looping
49
- # forever.
50
- private_class_method def cycle_diagnostics(table_by_name, ordered_table_names)
51
- table_by_name.values.map do |table|
52
- unresolved = (compute_table_dependencies(table) - ordered_table_names - [table.name]).uniq
53
- " #{table.name} -> #{unresolved.join(', ')}"
79
+ # Choose the next table to emit when the order is stuck in a cycle. Only
80
+ # genuine cycle members are eligible a table in a non-trivial
81
+ # strongly-connected component of the unresolved-dependency subgraph so an
82
+ # acyclic table that merely waits on a cycle is never reordered ahead of its
83
+ # parent. Among the members, prefer one that still has at least one
84
+ # already-ordered parent, so its extraction stays constrained instead of
85
+ # collapsing to "match every row" (a cross-scope over-extraction risk for the
86
+ # mongodb adapter); break remaining ties by fewest unresolved dependencies,
87
+ # then by name, for determinism.
88
+ private_class_method def pick_cycle_victim(remaining, present_names, ordered)
89
+ adjacency = remaining.each_with_object({}) do |table, acc|
90
+ acc[table.name] = unresolved_dependencies(table, present_names, ordered)
91
+ end
92
+ cyclic_names = strongly_connected_members(adjacency)
93
+
94
+ candidates = remaining.select { |table| cyclic_names.include?(table.name) }
95
+ candidates = remaining if candidates.empty? # defensive; a stall implies a cycle
96
+
97
+ anchored = candidates.select { |table| ordered_parent?(table, present_names, ordered) }
98
+ pool = anchored.empty? ? candidates : anchored
99
+
100
+ pool.min_by { |table| [unresolved_dependencies(table, present_names, ordered).size, table.name] }
101
+ end
102
+
103
+ # True when `table` has a belongs_to whose target was already ordered, so its
104
+ # extraction filter will be constrained rather than an unscoped full scan.
105
+ private_class_method def ordered_parent?(table, present_names, ordered)
106
+ compute_table_dependencies(table).any? do |dep|
107
+ dep != table.name && present_names.include?(dep) && ordered.include?(dep)
54
108
  end
55
109
  end
56
110
 
57
- private_class_method def build_cycle_error_message(table_by_name, ordered_table_names)
58
- "Circular belongs_to dependency detected among tables: " \
59
- "#{table_by_name.keys.sort.join(', ')}. " \
60
- "A processing order cannot be determined. " \
61
- "Remove one of the belongs_to entries forming the cycle.\n" \
62
- "Unresolved dependencies:\n" \
63
- "#{cycle_diagnostics(table_by_name, ordered_table_names).join("\n")}"
111
+ # Names belonging to a non-trivial strongly-connected component (size > 1) of
112
+ # `adjacency` (table name -> unresolved dependency names), i.e. the genuine
113
+ # cycle participants. Iterative Tarjan; nodes and edges are visited in name
114
+ # order so the result is deterministic. Self-edges are already excluded from
115
+ # the adjacency, so a size-1 component is never a cycle.
116
+ private_class_method def strongly_connected_members(adjacency)
117
+ index = {}
118
+ low = {}
119
+ on_stack = {}
120
+ stack = []
121
+ counter = 0
122
+ members = Set.new
123
+ neighbors = adjacency.each_with_object({}) { |(name, deps), acc| acc[name] = deps.sort }
124
+
125
+ adjacency.keys.sort.each do |start|
126
+ next if index.key?(start)
127
+
128
+ work = [[start, 0]]
129
+ until work.empty?
130
+ node, edge_i = work.last
131
+ if edge_i.zero?
132
+ index[node] = counter
133
+ low[node] = counter
134
+ counter += 1
135
+ stack.push(node)
136
+ on_stack[node] = true
137
+ end
138
+
139
+ adj = neighbors[node] || []
140
+ if edge_i < adj.size
141
+ work.last[1] += 1
142
+ w = adj[edge_i]
143
+ next unless adjacency.key?(w) # ignore edges leaving the remaining set
144
+
145
+ if index.key?(w)
146
+ low[node] = [low[node], index[w]].min if on_stack[w]
147
+ else
148
+ work.push([w, 0])
149
+ end
150
+ else
151
+ if low[node] == index[node]
152
+ component = []
153
+ loop do
154
+ w = stack.pop
155
+ on_stack[w] = false
156
+ component << w
157
+ break if w == node
158
+ end
159
+ members.merge(component) if component.size > 1
160
+ end
161
+ work.pop
162
+ low[work.last[0]] = [low[work.last[0]], low[node]].min unless work.empty?
163
+ end
164
+ end
165
+ end
166
+
167
+ members
168
+ end
169
+
170
+ private_class_method def warn_cycle_break(logger, victim, dropped)
171
+ return if logger.nil?
172
+
173
+ logger.warn(
174
+ "Circular belongs_to dependency detected. Breaking it by ordering " \
175
+ "'#{victim.name}' before its parent table(s): #{dropped.join(', ')}. The dropped " \
176
+ "relationship is not enforced while ordering, so '#{victim.name}' is extracted " \
177
+ "without that parent constraint (the mongodb adapter may then match a superset of " \
178
+ "rows; SQL output may not load in foreign-key order). To break the cycle explicitly " \
179
+ "instead, mark one of the belongs_to entries forming it with `ignore: true`."
180
+ )
64
181
  end
65
182
  end
66
183
  end
@@ -30,7 +30,7 @@ module Exwiw
30
30
  QueryAstBuilder.validate_scope!(dumpable_configs, table_by_name, @dump_target, @logger)
31
31
 
32
32
  @logger.debug("Determining table processing order...")
33
- ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs)
33
+ ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs, logger: @logger)
34
34
 
35
35
  total_size = ordered_table_names.size
36
36
  ordered_table_names.each_with_index do |table_name, idx|
data/lib/exwiw/runner.rb CHANGED
@@ -44,7 +44,7 @@ module Exwiw
44
44
  QueryAstBuilder.validate_scope!(dumpable_configs, table_by_name, @dump_target, @logger)
45
45
 
46
46
  @logger.info("Determining table processing order...")
47
- ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs)
47
+ ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs, logger: @logger)
48
48
 
49
49
  clean_output_dir!
50
50
 
data/lib/exwiw/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Exwiw
4
- VERSION = "0.5.1"
4
+ VERSION = "0.5.2"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: exwiw
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.1
4
+ version: 0.5.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Shia