exwiw 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 224bdc1d3b0f94e08463ad9e42a6e67d0592d902388b5873f5840226dbdbd3fe
4
- data.tar.gz: de9ddd4a625565e0bcd28ff3f74df8da06092c443ad1f170d41c5858a24c4802
3
+ metadata.gz: 2af5a1cc29946424a2b6498f19d7ad77714f108194575ddd6014c5fc2d829416
4
+ data.tar.gz: 3113e80b88ab11a95344140f819a9247eadc3706c45a9b2a665f946a88a945b7
5
5
  SHA512:
6
- metadata.gz: '08f564c07c09561a4b9b825bb7f6ca43a076df5b8262f165addad471639084fa5b5074330215edd36951ce0c427f510533f39d03e0632c1306ba4e9054391b33'
7
- data.tar.gz: 2c161f236a676a15774fb097a7a2c4d66f95f38be8c465dfc29788b4c45165aa3b13dee2b1da771e317672e63f089d2496e10cf4fe2ebf16f97885e0e1c49c76
6
+ metadata.gz: 539f4ab428d75f97714475d607d91ae2870a2bf860ac8ab2f732d5a5709d5e0cf2fd085c0bc3bbdf9b095f969542eb866c1f3c3766cc5e3a8be0294cf3cfcf0f
7
+ data.tar.gz: 7b41f191e5e6d5ff60a1c927111d06f85b6c461a1dd63d5665b254338eafcde037233bb7f67027306258515e71aa1af3cf38e6aadf20b02ec9f6a91f05c7f2c4
data/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.5.1] - 2026-06-18
6
+
7
+ ### Added
8
+
9
+ - **Scope-column extraction mode** (`--scope-column`, SQL adapters only). For schemas where many independent top-level tables share the same scope/tenant column instead of converging on a single `belongs_to` root, exwiw can now filter **every** table by that shared column (`--scope-column=COLUMN` with `--ids` as its values) rather than anchoring on one `--target-table`. A table that carries the column is filtered directly; a table that lacks it but `belongs_to` a table that has it is joined up to the nearest such table and filtered there. A table that `belongs_to` a parent which is itself scoped but carries no scope column of its own (e.g. a *hub* table scoped only because an extractable child references it) is constrained to the parent's in-scope ids via a subquery (`fk IN (SELECT parent.pk FROM <parent's scoped query>)`), so the hub's other children ride along to just the in-scope rows — limited to a single forward hop and a single unambiguous scopable parent. A table that cannot be scoped at all (no column and no path to one) makes the run **abort with a list of the offending tables**, so an unscoped table is never silently dumped in full. Two user-owned table-config keys support this and are preserved across `schema:generate` regeneration: **`scope_exempt: true`** exports a genuine reference/master table in full (rails-managed tables are treated as exempt automatically), and **`scope_column`** overrides the filtered column name for a table that stores the same scope value under a different name. `--scope-column` is mutually exclusive with `--target-table`, `--target-collection`, `--ids-column`, and `--ids-field`, can be set in `exwiw.yml`, and works with `exwiw explain`.
10
+
5
11
  ## [0.5.0] - 2026-06-16
6
12
 
7
13
  ### Added
data/README.md CHANGED
@@ -129,6 +129,88 @@ exwiw explain \
129
129
 
130
130
  The `--output-dir`, `--output-format`, `--insert-only`, and `--after-insert-hook` options are dump-specific and rejected when used with `explain`.
131
131
 
132
+ ### Scope-column mode (`--scope-column`)
133
+
134
+ The default `--target-table` extraction assumes the schema converges on a single
135
+ root: every table is reached by walking `belongs_to` toward that one table. Some
136
+ schemas are not shaped that way — many independent top-level tables each carry the
137
+ *same* scope/tenant column (e.g. `tenant_id`, `account_uuid`) and there is no
138
+ single root. Choosing one of them as `--target-table` would leave the others
139
+ unrelated to it, and an unrelated table is dumped in full — a problem if it holds
140
+ personal data.
141
+
142
+ `--scope-column` handles this shape: instead of one anchor table, **every table is
143
+ filtered by a shared column** whose values are `--ids`.
144
+
145
+ ```bash
146
+ exwiw \
147
+ --adapter=postgresql \
148
+ --host=localhost --port=5432 --user=reader \
149
+ --database=app_production \
150
+ --schema-dir=exwiw/schema \
151
+ --scope-column=tenant_id \
152
+ --ids=42,43 \
153
+ --output-dir=dump
154
+ ```
155
+
156
+ Each table is resolved as follows:
157
+
158
+ - **Carries the scope column** → `WHERE scope_column IN (ids)`.
159
+ - **Lacks it but `belongs_to` reaches a table that has it** → exwiw joins up to the
160
+ nearest such table and applies the scope filter there (the same join machinery
161
+ the single-target mode uses).
162
+ - **`belongs_to` a parent that is itself scoped but carries no scope column of its
163
+ own** → exwiw constrains this table to the parent's in-scope ids via a subquery
164
+ (`fk IN (SELECT parent.pk FROM <parent's scoped query>)`). This covers a *hub*
165
+ table that has no scope column and is scoped only because an extractable child
166
+ references it (see referenced-by below): the hub's other `belongs_to` children
167
+ ride along to just the in-scope rows instead of being dumped in full. Limited to
168
+ a single forward hop and a single unambiguous scopable parent.
169
+ - **Cannot be scoped at all** (no scope column and no path to one) → exwiw
170
+ **aborts** and lists the offending tables, so an unscoped table is never silently
171
+ dumped in full. For each, either add a `belongs_to` path, set `ignore: true` to
172
+ skip it, or mark it `scope_exempt: true` (below) to export it in full.
173
+
174
+ `--scope-column` is SQL-only (mysql / postgresql / sqlite) and mutually exclusive
175
+ with `--target-table`, `--target-collection`, `--ids-column`, and `--ids-field`.
176
+ It works with `exwiw explain` too, which is the recommended way to preview the
177
+ queries before exporting.
178
+
179
+ #### `scope_exempt` (intentional full dump)
180
+
181
+ A genuine reference/master table (no personal data) that has no scope linkage can
182
+ opt out of the strict check and be exported in full:
183
+
184
+ ```json
185
+ {
186
+ "name": "countries",
187
+ "primary_key": "id",
188
+ "scope_exempt": true,
189
+ "columns": [{ "name": "id" }, { "name": "code" }]
190
+ }
191
+ ```
192
+
193
+ Rails-managed tables (`schema_migrations`, `ar_internal_metadata`) are treated as
194
+ exempt automatically.
195
+
196
+ #### Per-table `scope_column` override
197
+
198
+ scope-column mode assumes a single shared **value** space — the same `--ids` apply
199
+ to every scoped table. If a table stores that same value under a differently named
200
+ column, override the column name for that table:
201
+
202
+ ```json
203
+ {
204
+ "name": "legacy_orders",
205
+ "primary_key": "id",
206
+ "scope_column": "legacy_tenant_id",
207
+ "columns": [{ "name": "id" }, { "name": "legacy_tenant_id" }]
208
+ }
209
+ ```
210
+
211
+ Both `scope_exempt` and `scope_column` are user-maintained and preserved across
212
+ `schema:generate` regeneration (the generators never emit them).
213
+
132
214
  ### Config file (`exwiw.yml`)
133
215
 
134
216
  Options you would otherwise repeat on every run can be kept in a YAML config file. Pass it with `--config=PATH`; when `--config` is omitted, exwiw automatically loads `exwiw.yml` (or `exwiw.yaml`) from the current directory if present.
@@ -144,7 +226,7 @@ output_format: insert # insert | copy
144
226
  insert_only: false
145
227
  after_insert_hook: hooks/seed.rb
146
228
  log_level: info # debug | info
147
- # target_table / ids / ids_field / ids_column may also be set here
229
+ # target_table / ids / ids_field / ids_column / scope_column may also be set here
148
230
  ```
149
231
 
150
232
  With the file above, only the connection details need to be supplied on the CLI:
@@ -38,6 +38,7 @@ module Exwiw
38
38
  'EXWIW_DATABASE_USER' => cli_options[:database_user].to_s,
39
39
  'EXWIW_DATABASE_NAME' => cli_options[:database_name].to_s,
40
40
  'EXWIW_TARGET_TABLE' => cli_options[:target_table].to_s,
41
+ 'EXWIW_SCOPE_COLUMN' => cli_options[:scope_column].to_s,
41
42
  'EXWIW_IDS' => Array(cli_options[:ids]).join(','),
42
43
  'EXWIW_OUTPUT_FORMAT' => cli_options[:output_format].to_s,
43
44
  }
data/lib/exwiw/cli.rb CHANGED
@@ -35,6 +35,7 @@ module Exwiw
35
35
  ids
36
36
  ids_field
37
37
  ids_column
38
+ scope_column
38
39
  ].freeze
39
40
 
40
41
  # Database connection settings are environment-specific (and sometimes
@@ -77,6 +78,7 @@ module Exwiw
77
78
  @ids = []
78
79
  @ids_field = nil
79
80
  @ids_column = nil
81
+ @scope_column = nil
80
82
  @output_format = nil
81
83
  @insert_only = nil
82
84
  @after_insert_hook_path = nil
@@ -109,6 +111,7 @@ module Exwiw
109
111
  table_name: @target_table_name,
110
112
  ids: @ids,
111
113
  ids_field: @ids_field,
114
+ scope_column: @scope_column,
112
115
  )
113
116
 
114
117
  logger = build_logger
@@ -161,6 +164,7 @@ module Exwiw
161
164
  end
162
165
 
163
166
  resolve_target_collection_alias!
167
+ resolve_scope_column!
164
168
  resolve_ids_column_alias!
165
169
  resolve_uri_option!
166
170
 
@@ -228,8 +232,13 @@ module Exwiw
228
232
  exit 1
229
233
  end
230
234
 
231
- if !@target_table_name && @ids.any?
232
- $stderr.puts "--target-table is required when --ids is specified"
235
+ if @scope_column && @ids.empty?
236
+ $stderr.puts "--ids is required when --scope-column is specified"
237
+ exit 1
238
+ end
239
+
240
+ if !@target_table_name && !@scope_column && @ids.any?
241
+ $stderr.puts "--target-table or --scope-column is required when --ids is specified"
233
242
  exit 1
234
243
  end
235
244
 
@@ -309,6 +318,7 @@ module Exwiw
309
318
  end
310
319
  @ids_field ||= config["ids_field"]
311
320
  @ids_column ||= config["ids_column"]
321
+ @scope_column ||= config["scope_column"]
312
322
  end
313
323
 
314
324
  # Strip a trailing slash (like the CLI's dir options) and expand relative to
@@ -376,6 +386,33 @@ module Exwiw
376
386
  end
377
387
  end
378
388
 
389
+ # `--scope-column` switches to scope-column mode: every table is filtered by a
390
+ # shared column (`--ids` are its values) instead of anchoring on one
391
+ # `--target-table`. It is SQL-only and mutually exclusive with the single-target
392
+ # flags. Runs after resolve_target_collection_alias! (so --target-collection is
393
+ # already folded into @target_table_name) and before resolve_ids_column_alias!
394
+ # so the clearer "cannot combine" message wins over the generic ids-column one.
395
+ private def resolve_scope_column!
396
+ return if @scope_column.nil?
397
+
398
+ sql_adapters = ["mysql", "postgresql", "sqlite"]
399
+ unless sql_adapters.include?(@database_adapter)
400
+ $stderr.puts "--scope-column is only supported by the sql adapters"
401
+ exit 1
402
+ end
403
+
404
+ if @target_table_name
405
+ $stderr.puts "--scope-column cannot be combined with --target-table/--target-collection"
406
+ exit 1
407
+ end
408
+
409
+ if @ids_field || @ids_column
410
+ flag = @ids_column ? "--ids-column" : "--ids-field"
411
+ $stderr.puts "--scope-column cannot be combined with #{flag}"
412
+ exit 1
413
+ end
414
+ end
415
+
379
416
  # `--uri` supplies a full connection string (e.g. `mongodb+srv://...`) and is
380
417
  # mongodb-only — the SQL adapters shell out to their own client binaries with
381
418
  # discrete host/port/user flags and have no equivalent. Runs after the
@@ -442,6 +479,7 @@ module Exwiw
442
479
  target_table: @target_table_name,
443
480
  ids: @ids.dup.freeze,
444
481
  ids_field: @ids_field,
482
+ scope_column: @scope_column,
445
483
  output_format: @output_format,
446
484
  insert_only: @insert_only,
447
485
  log_level: @log_level,
@@ -500,6 +538,7 @@ module Exwiw
500
538
  opts.on("--ids=[IDS]", "Comma-separated list of identifiers. Required when --target-table is given.") { |v| @ids = v.split(',') }
501
539
  opts.on("--ids-field=[FIELD]", "Field on the target collection that --ids is matched against. Defaults to the primary key. (mongodb adapter only)") { |v| @ids_field = v }
502
540
  opts.on("--ids-column=[COLUMN]", "Column on the target table that --ids is matched against. Defaults to the primary key. (sql adapters only)") { |v| @ids_column = v }
541
+ opts.on("--scope-column=[COLUMN]", "Filter every table by this shared column (--ids are its values) instead of a single --target-table. Tables lacking it are reached via belongs_to. SQL adapters only; mutually exclusive with --target-table.") { |v| @scope_column = v }
503
542
  opts.on("--output-format=[FORMAT]", "Output format: insert (default) or copy (PostgreSQL only, export subcommand only)") { |v| @output_format = v }
504
543
  opts.on("--insert-only", "Do not generate DELETE SQL files (export subcommand only)") { @insert_only = true }
505
544
  opts.on("--after-insert-hook=PATH", "Path to a .rb or .sh post-processing hook executed after all insert/delete files are written (export subcommand only)") do |v|
@@ -26,8 +26,11 @@ module Exwiw
26
26
  target = table_by_name[@dump_target.table_name]
27
27
  adapter.validate_as_dump_target!(target) if target
28
28
 
29
+ dumpable_configs = configs.select { |c| adapter.dumpable?(c) }
30
+ QueryAstBuilder.validate_scope!(dumpable_configs, table_by_name, @dump_target, @logger)
31
+
29
32
  @logger.debug("Determining table processing order...")
30
- ordered_table_names = DetermineTableProcessingOrder.run(configs.select { |c| adapter.dumpable?(c) })
33
+ ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs)
31
34
 
32
35
  total_size = ordered_table_names.size
33
36
  ordered_table_names.each_with_index do |table_name, idx|
@@ -2,23 +2,58 @@
2
2
 
3
3
  module Exwiw
4
4
  class QueryAstBuilder
5
- def self.run(table_name, table_by_name, dump_target, logger, allow_reverse: true)
6
- new(table_name, table_by_name, dump_target, logger, allow_reverse: allow_reverse).run
5
+ def self.run(table_name, table_by_name, dump_target, logger, allow_reverse: true, allow_forward: true)
6
+ new(table_name, table_by_name, dump_target, logger, allow_reverse: allow_reverse, allow_forward: allow_forward).run
7
+ end
8
+
9
+ # Scope-column mode classification for a single table. One of
10
+ # :exempt / :direct / :via_path / :referenced_by / :via_scoped_parent / :unscopable.
11
+ def self.scope_category(table_name, table_by_name, dump_target, logger)
12
+ new(table_name, table_by_name, dump_target, logger).scope_category
13
+ end
14
+
15
+ # Strict pre-flight for scope-column mode: abort if any extractable table
16
+ # cannot be scoped, so an unscoped (potentially sensitive) table is never
17
+ # silently dumped in full. No-op outside scope mode. `tables` is the set of
18
+ # dumpable configs (ignore:true tables are skipped — they are not extracted).
19
+ def self.validate_scope!(tables, table_by_name, dump_target, logger)
20
+ return if dump_target.scope_column.nil?
21
+
22
+ unscopable =
23
+ tables.reject(&:ignore).select do |table|
24
+ scope_category(table.name, table_by_name, dump_target, logger) == :unscopable
25
+ end
26
+ return if unscopable.empty?
27
+
28
+ names = unscopable.map(&:name).sort.join(", ")
29
+ raise ArgumentError,
30
+ "scope-column mode: #{unscopable.size} table(s) cannot be scoped by " \
31
+ "'#{dump_target.scope_column}': #{names}. For each, add `scope_exempt: true` " \
32
+ "to export it in full, set `ignore: true` to skip it, or add a belongs_to path " \
33
+ "to a table that carries the scope column (use a per-table `scope_column` if the " \
34
+ "column name differs on that table)."
7
35
  end
8
36
 
9
37
  attr_reader :table_name, :table_by_name, :dump_target
10
38
 
11
- def initialize(table_name, table_by_name, dump_target, logger, allow_reverse: true)
39
+ def initialize(table_name, table_by_name, dump_target, logger, allow_reverse: true, allow_forward: true)
12
40
  @table_name = table_name
13
41
  @table_by_name = table_by_name
14
42
  @dump_target = dump_target
15
43
  @logger = logger
16
44
  @allow_reverse = allow_reverse
45
+ # @allow_forward gates the "scope via an indirectly-scoped belongs_to
46
+ # parent" rescue (build_belongs_to_scoped_clause). Disabled while building a
47
+ # parent/child subquery so a single forward hop never recurses into another
48
+ # (which could loop on a belongs_to cycle).
49
+ @allow_forward = allow_forward
17
50
  end
18
51
 
19
52
  def run
20
53
  table = table_by_name.fetch(table_name)
21
54
 
55
+ return build_scoped(table) if scope_mode?
56
+
22
57
  where_clauses = build_where_clauses(table, dump_target)
23
58
  join_clauses = build_join_clauses(table, table_by_name, dump_target)
24
59
 
@@ -130,8 +165,10 @@ module Exwiw
130
165
  next if relation.nil? || relation.polymorphic?
131
166
 
132
167
  # Build the child's own extraction query. allow_reverse:false stops a
133
- # chain of FK-less tables from recursing back into each other.
134
- child_query = self.class.run(other.name, table_by_name, dump_target, @logger, allow_reverse: false)
168
+ # chain of FK-less tables from recursing back into each other;
169
+ # allow_forward:false stops the child from forward-scoping back through
170
+ # this very table (which would loop).
171
+ child_query = self.class.run(other.name, table_by_name, dump_target, @logger, allow_reverse: false, allow_forward: false)
135
172
 
136
173
  # Only an *already constrained* child narrows anything; an unconstrained
137
174
  # child would select every fk value (i.e. dump all) and not help.
@@ -169,6 +206,64 @@ module Exwiw
169
206
  )
170
207
  end
171
208
 
209
+ # Scope-column mode. Builds a `fk IN (SELECT parent.pk FROM <parent
210
+ # extraction query>)` clause for a table whose belongs_to parent is itself
211
+ # scopable but carries no scope column of its own — so find_path_to_scoped
212
+ # cannot terminate on it (via_path fails) and nothing references this table
213
+ # (referenced_by fails). The classic shape is a hub scoped only via
214
+ # referenced_by (e.g. CDP `customer_accounts`, scoped by the `customers` that
215
+ # reference it) with sibling detail tables (`customer_account_details`, ...)
216
+ # hanging off it. Constraining those siblings to the hub's in-scope ids keeps
217
+ # them out of a full dump. Returns nil when there is no single, unambiguous
218
+ # scopable parent, leaving the caller on the unscopable path.
219
+ private def build_belongs_to_scoped_clause(table)
220
+ candidates = table.belongs_tos.filter_map do |relation|
221
+ # A polymorphic belongs_to points at several parent tables through one
222
+ # column, so it cannot project to a single parent id set; skip it.
223
+ next if relation.polymorphic?
224
+
225
+ parent = table_by_name[relation.table_name]
226
+ next if parent.nil?
227
+
228
+ # Build the parent's own scoped query. allow_reverse stays true so the
229
+ # parent may be scoped via referenced_by; allow_forward:false bounds this
230
+ # to a single forward hop so a belongs_to cycle cannot loop.
231
+ parent_query = self.class.run(parent.name, table_by_name, dump_target, @logger, allow_reverse: true, allow_forward: false)
232
+
233
+ # Only a constrained parent narrows anything; an unconstrained parent
234
+ # would select every pk (i.e. dump all) and not help.
235
+ next unless parent_query.where_clauses.any? || parent_query.join_clauses.any?
236
+
237
+ [relation, parent, parent_query]
238
+ end
239
+
240
+ # Only the unambiguous single-parent case. Multiple scopable parents would
241
+ # need their subqueries combined (not supported); fall back to unscopable.
242
+ if candidates.size != 1
243
+ if candidates.size > 1
244
+ @logger.debug(" #{table.name} has multiple scopable parents; skipping forward scope (unscopable).")
245
+ end
246
+ return nil
247
+ end
248
+
249
+ relation, parent, parent_query = candidates.first
250
+
251
+ # Project the parent's extraction query down to just its primary key — the
252
+ # column this table's foreign key points at.
253
+ pk_column = TableColumn.from_symbol_keys(name: parent.primary_key)
254
+ projected = QueryAst::Select.new
255
+ projected.from(parent_query.from_table_name)
256
+ projected.select([pk_column])
257
+ parent_query.join_clauses.each { |j| projected.join(j) }
258
+ parent_query.where_clauses.each { |w| projected.where(w) }
259
+
260
+ QueryAst::WhereClause.new(
261
+ column_name: relation.foreign_key,
262
+ operator: :in_subquery,
263
+ value: QueryAst::SelectSubquery.new(query: projected)
264
+ )
265
+ end
266
+
172
267
  private def build_where_clauses(table, dump_target)
173
268
  clauses = []
174
269
 
@@ -264,5 +359,208 @@ module Exwiw
264
359
 
265
360
  queue
266
361
  end
362
+
363
+ # ------------------------------------------------------------------
364
+ # Scope-column mode (Exwiw::DumpTarget#scope_column).
365
+ #
366
+ # The single-target machinery above anchors everything on one named table.
367
+ # Scope mode instead filters every table by a shared column. The relationship
368
+ # walk is the same idea — the *terminus* is just "any table carrying the
369
+ # scope column" rather than "the one named target".
370
+ # ------------------------------------------------------------------
371
+
372
+ private def scope_mode?
373
+ !dump_target.scope_column.nil?
374
+ end
375
+
376
+ # Classifier used by validate_scope! and mirrored by build_scoped below.
377
+ def scope_category
378
+ table = table_by_name.fetch(table_name)
379
+ return :exempt if scope_exempt?(table)
380
+ return :direct if directly_scoped?(table)
381
+ return :via_path if build_join_clauses_scoped(table).any?
382
+ return :referenced_by if @allow_reverse && build_referenced_by_clause(table)
383
+ return :via_scoped_parent if @allow_forward && build_belongs_to_scoped_clause(table)
384
+
385
+ :unscopable
386
+ end
387
+
388
+ private def build_scoped(table)
389
+ ast = QueryAst::Select.new
390
+ ast.from(table.name)
391
+ if table.rails_managed?
392
+ ast.select_all!
393
+ else
394
+ ast.select(table.columns)
395
+ end
396
+
397
+ # Reference/master (or rails-managed) table: export every row.
398
+ return ast if scope_exempt?(table)
399
+
400
+ # Carries the scope column itself: filter on it directly.
401
+ if directly_scoped?(table)
402
+ ast.where(scope_where_clause(table))
403
+ ast.where(table.filter) if table.filter
404
+ return ast
405
+ end
406
+
407
+ # Reachable via belongs_to: join up to the scoped ancestor (the scope
408
+ # filter is applied at the terminal join inside build_join_clauses_scoped).
409
+ join_clauses = build_join_clauses_scoped(table)
410
+ unless join_clauses.empty?
411
+ join_clauses.each { |join_clause| ast.join(join_clause) }
412
+ ast.where(table.filter) if table.filter
413
+ return ast
414
+ end
415
+
416
+ if @allow_reverse
417
+ # Referenced by an extractable (scoped) child: constrain via subquery.
418
+ reverse_clause = build_referenced_by_clause(table)
419
+ if reverse_clause
420
+ ast.where(reverse_clause)
421
+ return ast
422
+ end
423
+ end
424
+
425
+ if @allow_forward
426
+ # Belongs_to a parent that is itself scoped but carries no scope column of
427
+ # its own (so via_path cannot terminate on it) — e.g. a hub table scoped
428
+ # only via referenced_by. Constrain this table to that parent's in-scope
429
+ # ids so its rows ride along instead of being dumped in full.
430
+ parent_clause = build_belongs_to_scoped_clause(table)
431
+ if parent_clause
432
+ ast.where(parent_clause)
433
+ return ast
434
+ end
435
+ end
436
+
437
+ # Only the genuine top-level build (no rescue disabled) is allowed to fail
438
+ # hard. The Runner/ExplainRunner pre-flight (validate_scope!) rejects
439
+ # unscopable tables before extraction, so a top-level build never
440
+ # legitimately lands here; if it does, raise rather than emit an unfiltered
441
+ # (potential full PII) dump.
442
+ if @allow_reverse && @allow_forward
443
+ raise ArgumentError, scope_unscopable_message(table)
444
+ end
445
+
446
+ # Unscopable during a reverse/forward subquery build (a rescue is disabled):
447
+ # return the unconstrained AST so the caller's "constrained only" check
448
+ # filters this candidate out (it never becomes a real dump query).
449
+ ast
450
+ end
451
+
452
+ # The shared column this table is filtered on: a per-table `scope_column`
453
+ # override when present, otherwise the global `--scope-column`.
454
+ private def resolved_scope_column(table)
455
+ table.scope_column || dump_target.scope_column
456
+ end
457
+
458
+ private def scope_exempt?(table)
459
+ table.scope_exempt || table.rails_managed?
460
+ end
461
+
462
+ private def directly_scoped?(table)
463
+ column = resolved_scope_column(table)
464
+ table.columns.any? { |c| c.name == column }
465
+ end
466
+
467
+ private def scope_where_clause(table)
468
+ Exwiw::QueryAst::WhereClause.new(
469
+ column_name: resolved_scope_column(table),
470
+ operator: :eq,
471
+ value: dump_target.ids
472
+ )
473
+ end
474
+
475
+ # BFS over belongs_tos to the nearest *directly scoped* ancestor. Unlike the
476
+ # target-mode walk, the returned path INCLUDES that ancestor: the scope column
477
+ # lives on the ancestor itself (not on a foreign key of the child), so the
478
+ # ancestor must be joined and then filtered.
479
+ private def find_path_to_scoped(table)
480
+ visited = {}
481
+ queue = [[table.name, [table.name]]]
482
+
483
+ until queue.empty?
484
+ current_table_name, path = queue.shift
485
+ next if visited[current_table_name]
486
+ visited[current_table_name] = true
487
+
488
+ current_table = table_by_name[current_table_name]
489
+ next if current_table.nil?
490
+
491
+ current_table.belongs_tos.each do |relation|
492
+ next_table_name = relation.table_name
493
+ next_table = table_by_name[next_table_name]
494
+ next if next_table.nil?
495
+
496
+ next_path = path + [next_table_name]
497
+ return next_path if directly_scoped?(next_table)
498
+
499
+ queue.push([next_table_name, next_path])
500
+ end
501
+ end
502
+
503
+ []
504
+ end
505
+
506
+ private def build_join_clauses_scoped(table)
507
+ path_tables = find_path_to_scoped(table)
508
+ @logger.debug(" Join path from #{table.name} to a scoped table: #{path_tables}")
509
+
510
+ return [] if path_tables.size < 2
511
+
512
+ path_tables.each_cons(2).map do |from_table_name, to_table_name|
513
+ from_table = table_by_name[from_table_name]
514
+ to_table = table_by_name[to_table_name]
515
+
516
+ join_clause = build_scoped_join_clause(from_table, to_table)
517
+
518
+ # Only the final hop's to_table is directly scoped (the BFS stops there),
519
+ # so the scope filter rides on that join's where_clauses, compiled against
520
+ # join_table_name = the scoped ancestor.
521
+ if directly_scoped?(to_table)
522
+ join_clause.where_clauses.push scope_where_clause(to_table)
523
+ end
524
+
525
+ if to_table.filter
526
+ join_clause.where_clauses.push to_table.filter
527
+ end
528
+
529
+ join_clause
530
+ end
531
+ end
532
+
533
+ # One belongs_to hop as a JoinClause, with the polymorphic type condition
534
+ # placed on the source table (base_where_clauses) when the hop is polymorphic
535
+ # — mirroring the target-mode loop in build_join_clauses.
536
+ private def build_scoped_join_clause(from_table, to_table)
537
+ relation = from_table.belongs_to(to_table.name)
538
+
539
+ join_clause = QueryAst::JoinClause.new(
540
+ base_table_name: from_table.name,
541
+ foreign_key: relation.foreign_key,
542
+ join_table_name: to_table.name,
543
+ primary_key: to_table.primary_key,
544
+ where_clauses: [],
545
+ base_where_clauses: []
546
+ )
547
+
548
+ if relation.polymorphic?
549
+ join_clause.base_where_clauses.push QueryAst::WhereClause.new(
550
+ column_name: relation.foreign_type,
551
+ operator: :eq,
552
+ value: [relation.type_value]
553
+ )
554
+ end
555
+
556
+ join_clause
557
+ end
558
+
559
+ private def scope_unscopable_message(table)
560
+ "Table '#{table.name}' cannot be scoped in scope-column mode: it has no " \
561
+ "'#{dump_target.scope_column}' column (nor a per-table scope_column override) and no " \
562
+ "belongs_to path to a table that does. Add `scope_exempt: true` to export it in full, " \
563
+ "set `ignore: true` to skip it, or add the missing belongs_to."
564
+ end
267
565
  end
268
566
  end
data/lib/exwiw/runner.rb CHANGED
@@ -38,8 +38,13 @@ module Exwiw
38
38
  target = table_by_name[@dump_target.table_name]
39
39
  adapter.validate_as_dump_target!(target) if target
40
40
 
41
+ dumpable_configs = configs.select { |c| adapter.dumpable?(c) }
42
+ # Scope-column mode: abort if any extractable table cannot be scoped (no-op
43
+ # otherwise). Done before extraction so nothing is dumped if it would leak.
44
+ QueryAstBuilder.validate_scope!(dumpable_configs, table_by_name, @dump_target, @logger)
45
+
41
46
  @logger.info("Determining table processing order...")
42
- ordered_table_names = DetermineTableProcessingOrder.run(configs.select { |c| adapter.dumpable?(c) })
47
+ ordered_table_names = DetermineTableProcessingOrder.run(dumpable_configs)
43
48
 
44
49
  clean_output_dir!
45
50
 
@@ -26,6 +26,18 @@ module Exwiw
26
26
  attribute :columns, array(TableColumn), default: []
27
27
  attribute :bulk_insert_chunk_size, optional(Integer), skip_serializing_if_nil: true
28
28
  attribute :ignore, Serdes::OptionalType.new(Serdes::ConcreteType.new(Boolean)), skip_serializing_if_nil: true
29
+ # Scope-column mode only (see Exwiw::DumpTarget#scope_column). Both are
30
+ # user-configured and never emitted by the schema generators.
31
+ #
32
+ # `scope_exempt: true` exports the whole table without scope filtering — the
33
+ # explicit, auditable escape hatch for genuine reference/master tables under
34
+ # the strict "every table must be scopable" rule.
35
+ #
36
+ # `scope_column` overrides the physical column this table is filtered on when
37
+ # it differs from the global `--scope-column` name (same scope value, just a
38
+ # different column name on this table).
39
+ attribute :scope_exempt, Serdes::OptionalType.new(Serdes::ConcreteType.new(Boolean)), skip_serializing_if_nil: true
40
+ attribute :scope_column, optional(String), skip_serializing_if_nil: true
29
41
 
30
42
  def self.from(hash)
31
43
  config = super
@@ -137,6 +149,9 @@ module Exwiw
137
149
  merged_table.filter = filter
138
150
  merged_table.bulk_insert_chunk_size = passed_table.bulk_insert_chunk_size
139
151
  merged_table.ignore = ignore
152
+ # User-owned, never regenerated: carry over from the existing config.
153
+ merged_table.scope_exempt = scope_exempt
154
+ merged_table.scope_column = scope_column
140
155
 
141
156
  # Structural facts of each belongs_to come from the freshly generated
142
157
  # config, but the user-owned `comment`/`ignore`/`references` carry over
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.0"
4
+ VERSION = "0.5.1"
5
5
  end
data/lib/exwiw.rb CHANGED
@@ -39,7 +39,13 @@ module Exwiw
39
39
  # `ids_field` optionally overrides which field `--ids` is matched against on
40
40
  # the target table. When nil the table's primary key is used (the historical
41
41
  # behavior). Currently only honored by the mongodb adapter.
42
- DumpTarget = Struct.new(:table_name, :ids, :ids_field, keyword_init: true)
42
+ #
43
+ # `scope_column` switches the extraction to scope-column mode: instead of a
44
+ # single `table_name` anchor, every table is filtered by a shared column
45
+ # (`scope_column IN ids`) and tables lacking it are reached by walking
46
+ # belongs_to up to the nearest table that has it. When set, `table_name` is
47
+ # nil. SQL adapters only.
48
+ DumpTarget = Struct.new(:table_name, :ids, :ids_field, :scope_column, keyword_init: true)
43
49
  # `uri` is an optional full connection string (currently only honored by the
44
50
  # mongodb adapter, e.g. `mongodb+srv://...`). When present it is the source of
45
51
  # truth for the connection — host/port/user/password are ignored — so TLS,
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.0
4
+ version: 0.5.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Shia