PostgreSQL/Diff.pm

filter: Statementstmt 56.7% 67 / 118 Branchbran 20.0% 10 / 50 Conditioncond 19.3% 6 / 31 MC/DCmcdc 5.5% 1 / 18 Subroutinesub 88.8% 16 / 18 Podpod 100% 2 / 2 totaltotal 43.0% 102 / 237 CC 42 SCAR 45.7
CC
42
Cov
42%
_format_pg_default
240.0
target_from_compiled
156.0
register_diff_class
12.5
CRAP 96.7
« PostgreSQL/DDL.pm ↑ Summary PostgreSQL/Introspect/Indexes.pm »
1 package DBIO::PostgreSQL::Diff;
2 # ABSTRACT: Compare two introspected PostgreSQL models
3  
4 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 8 ▶use base 'DBIO::Diff::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9  
10 8 ▶use DBIO::PostgreSQL::Diff::Schema ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use DBIO::PostgreSQL::Diff::Table ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use DBIO::PostgreSQL::Diff::Column ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use DBIO::PostgreSQL::Diff::Type ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use DBIO::PostgreSQL::Diff::Index ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use DBIO::PostgreSQL::Diff::Function ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 8 ▶use DBIO::PostgreSQL::Diff::Trigger ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 8 ▶use DBIO::PostgreSQL::Diff::Policy ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 8 ▶use DBIO::PostgreSQL::Diff::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 8 my %_REGISTRY = (
21 extensions => 'DBIO::PostgreSQL::Diff::Extension',
22 schemas => 'DBIO::PostgreSQL::Diff::Schema',
23 types => 'DBIO::PostgreSQL::Diff::Type',
24 functions => 'DBIO::PostgreSQL::Diff::Function',
25 tables => 'DBIO::PostgreSQL::Diff::Table',
26 columns => 'DBIO::PostgreSQL::Diff::Column',
27 indexes => 'DBIO::PostgreSQL::Diff::Index',
28 triggers => 'DBIO::PostgreSQL::Diff::Trigger',
29 policies => 'DBIO::PostgreSQL::Diff::Policy',
30 );
31  
32 8 my @_ORDER = qw(
33 extensions schemas types functions tables columns indexes triggers policies
34 );
35  
36 # Trailing context each table-aware diff class needs after its own
37 # (source, target) section pair. Diff::Table builds full CREATE TABLE
38 # statements and therefore needs the *column* data; Diff::Column and
39 # Diff::Policy need the *table* list for schema/table context; Diff::Index
40 # needs the *table* list to detect which tables are being dropped in the
41 # same pass, so it can suppress standalone DROP INDEX ops that DROP TABLE
42 # ... CASCADE already covers (karr #32).
43 8 my %_AUX_SECTION = (
44 tables => 'columns',
45 columns => 'tables',
46 indexes => 'tables',
47 policies => 'tables',
48 );
49  
50 2 ▶sub _diff_registry { %_REGISTRY }
Subroutine _diff_registry: called CC=1 SCAR=0.0
51 1 ▶sub _diff_order { @_ORDER }
Subroutine _diff_order: called CC=1 SCAR=0.0
52  
53  
54 2 ▶sub register_diff_class {
Subroutine register_diff_class: called CC=8 SCAR=25.2
Pod documented
55 2 my ($class, %args) = @_;
56 2 ▶ my $key = $args{model_key} or die 'model_key required';
Branch: 1 branch
BranchTrueFalseTotal
my $key = $args{"model_key"} or die "model_key required" 2 0 2
57 2 ▶ my $diff_cls = $args{class} or die 'class required';
Branch: 1 branch
BranchTrueFalseTotal
my $diff_cls = $args{"class"} or die "class required" 2 0 2
58 2 my $position = $args{position};
59  
60 2 $_REGISTRY{$key} = $diff_cls;
61 2 @_ORDER = grep { $_ ne $key } @_ORDER;
62  
63 2 ▶ if (!defined $position) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $position) { } 1 1 2
elsif ($position =~ /\Aafter:(.+)\z/) { } 1 0 1
elsif ($position =~ /\Abefore:(.+)\z/) { } 0 0 0
64 1 push @_ORDER, $key;
65 } elsif ($position =~ /\Aafter:(.+)\z/) {
66 1 my $anchor = $1;
67 1 my ($i) = grep { $_ORDER[$_] eq $anchor } 0..$#_ORDER;
68 1 ▶ die "position anchor '$anchor' not found in diff order" unless defined $i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 0 1 1
69 1 splice @_ORDER, $i + 1, 0, $key;
70 } elsif ($position =~ /\Abefore:(.+)\z/) {
71 0 my $anchor = $1;
72 0 my ($i) = grep { $_ORDER[$_] eq $anchor } 0..$#_ORDER;
73 0 ▶ die "position anchor '$anchor' not found in diff order" unless defined $i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 0 0 0
74 0 splice @_ORDER, $i, 0, $key;
75 } else {
76 0 die "invalid position '$position' — use 'after:KEY' or 'before:KEY'";
77 }
78 }
79  
80 3 ▶sub _build_operations {
Subroutine _build_operations: called CC=10 SCAR=24.6
81 3 my ($self) = @_;
82 3 my @ops;
83  
84 3 for my $key (@_ORDER) {
85 27 ▶ my $diff_cls = $_REGISTRY{$key} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $diff_cls = $_REGISTRY{$key} or next 27 0 27
86 27 ▶ next unless exists $self->source->{$key} || exists $self->target->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->source->{$key} or exists $self->target->{$key} 19 8 27
Condition66%2/3
exists $self->source->{$key} or exists $self->target->{$key}
l!l&&r!l&&!r
8019
MC/DC50%1/2
exists $self->source->{$key} or exists $self->target->{$key}
exists $self->source->{$key} exists $self->target->{$key}
Truth table66%2/3
A or B
A= exists $self->source->{$key}B= exists $self->target->{$key}
ABresult
1X1
011
000
87  
88 8 my @extra;
89 8 ▶ if (my $aux = $_AUX_SECTION{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $aux = $_AUX_SECTION{$key}) 8 0 8
90 @extra = (
91 $self->source->{$aux} // {},
92 8 ▶ $self->target->{$aux} // {},
Condition50%2/4
$self->source->{$aux} // {}
l!l
80
$self->target->{$aux} // {}
l!l
80
MC/DC0%0/1
$self->source->{$aux} // {}
$self->source->{$aux}
MC/DC0%0/1
$self->target->{$aux} // {}
$self->target->{$aux}
Truth table50%1/2
A
A= $self->source->{$aux}
Aresult
11
00
Truth table50%1/2
A
A= $self->target->{$aux}
Aresult
11
00
93 );
94 }
95  
96 push @ops, $diff_cls->diff(
97 $self->source->{$key} // {},
98 8 ▶ $self->target->{$key} // {},
Condition50%2/4
$self->source->{$key} // {}
l!l
80
$self->target->{$key} // {}
l!l
80
MC/DC0%0/1
$self->source->{$key} // {}
$self->source->{$key}
MC/DC0%0/1
$self->target->{$key} // {}
$self->target->{$key}
Truth table50%1/2
A
A= $self->source->{$key}
Aresult
11
00
Truth table50%1/2
A
A= $self->target->{$key}
Aresult
11
00
99 @extra,
100 );
101 }
102  
103 3 return \@ops;
104 }
105  
106  
107 # Map native_type strings that differ between the adapter output and what
108 # pg_catalog.format_type actually reports back.
109 8 my %_PG_FORMAT_TYPE = (
110 'timestamptz' => 'timestamp with time zone',
111 );
112  
113 # Render a default value in the same string form that pg_get_expr reports
114 # back from pg_attrdef, so the synthesized target model round-trips against
115 # the live (introspected) source. Returns undef when there is no default.
116 #
117 # $c->{default} shape (from DBIO::Schema::Type::canonical_column):
118 # undef -- no default
119 # \"now()" -- SCALAR ref holding a raw PG expression
120 # \"5" -- SCALAR ref holding a numeric literal
121 # "draft" -- plain string (a text/varchar literal in single quotes)
122 #
123 # pg_get_expr output for common cases:
124 # text 'draft' -> "'draft'::text" (string + ::textype)
125 # numeric 42 -> "42" (number, no cast)
126 # now() -> "now()" (expression, unchanged)
127 # nextval seq -> "nextval('schema.seq'::regclass)"
128 0 ▶sub _format_pg_default {
Subroutine _format_pg_default: not called CC=15 SCAR=54.8
129 0 my ($default, $data_type) = @_;
130 0 ▶ return undef unless defined $default;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $default 0 0 0
131  
132 0 ▶ my $expr = ref $default eq 'SCALAR' ? $$default : $default;
Branch: 1 branch
BranchTrueFalseTotal
ref $default eq 'SCALAR' ? : 0 0 0
133 0 ▶ return undef unless defined $expr && length $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr and length $expr 0 0 0
Condition0%0/3
defined $expr and length $expr
!ll&&!rl&&r
000
MC/DC0%0/2
defined $expr and length $expr
defined $expr length $expr
Truth table0%0/3
A and B
A= defined $exprB= length $expr
ABresult
0X0
100
111
134 0 $expr =~ s/^\s+|\s+$//g;
135  
136 # nextval() -- left untouched (matches pg_get_expr for IDENTITY-adjacent cols,
137 # though those are handled via $identity above and not via default).
138 0 ▶ return $expr if $expr =~ /\bnextval\s*\(/i;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /\bnextval\s*\(/i 0 0 0
139  
140 # Already a quoted string (e.g. DDL-emitted literal). Pass through as-is so
141 # any embedded ::cast is preserved.
142 0 ▶ return $expr if $expr =~ /^['"]/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^['"]/ 0 0 0
143  
144 # Already a quoted expression like 'now()' as a SCALAR ref string content
145 # of a non-string column -- common case: default_value => \'now()'.
146 # If it has parens or ::cast, leave alone.
147 0 ▶ return $expr if $expr =~ /[()]/ || $expr =~ /::/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /[()]/ or $expr =~ /::/ 0 0 0
Condition0%0/3
$expr =~ /[()]/ or $expr =~ /::/
l!l&&r!l&&!r
000
MC/DC0%0/2
$expr =~ /[()]/ or $expr =~ /::/
$expr =~ /[()]/ $expr =~ /::/
Truth table0%0/3
A or B
A= $expr =~ /[()]/B= $expr =~ /::/
ABresult
1X1
011
000
148  
149 # Pure number or numeric expression -- PG renders numeric defaults
150 # as a quoted literal with an explicit cast (e.g. '0'::bigint), not as
151 # a bare number. The column type is *not* implied by the value.
152 0 ▶ if ($expr =~ /^-?\d+(?:\.\d+)?\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^-?\d+(?:\.\d+)?\z/) 0 0 0
153 0 ▶ my $cast = $data_type // 'text';
Condition0%0/2
$data_type // "text"
l!l
00
MC/DC0%0/1
$data_type // "text"
$data_type
Truth table0%0/2
A
A= $data_type
Aresult
11
00
154 0 ▶ $cast = "timestamp with time zone" if $cast eq 'timestamptz';
Branch: 1 branch
BranchTrueFalseTotal
if $cast eq "timestamptz" 0 0 0
155 0 return sprintf(q{'%s'} . '::%s', $expr, $cast);
156 }
157  
158 # Boolean literals -- PG renders as 'true' / 'false' / 'null' (no cast).
159 0 ▶ return lc $expr if $expr =~ /^(?:true|false|null)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^(?:true|false|null)\z/i 0 0 0
160  
161 # Fallback: treat as a string literal, quoting and casting to the column
162 # type. pg_get_expr appends '::textype' (the column's data_type string as
163 # format_type renders it). Use the already-normalized $data_type.
164 0 ▶ my $cast = $data_type // 'text';
Condition0%0/2
$data_type // "text"
l!l
00
MC/DC0%0/1
$data_type // "text"
$data_type
Truth table0%0/2
A
A= $data_type
Aresult
11
00
165 0 ▶ $cast = "timestamp with time zone" if $cast eq 'timestamptz';
Branch: 1 branch
BranchTrueFalseTotal
if $cast eq "timestamptz" 0 0 0
166 0 return sprintf(q{'%s'} . '::%s', $expr, $cast);
167 }
168  
169 0 ▶sub target_from_compiled {
Subroutine target_from_compiled: not called CC=12 SCAR=50.5
Pod documented
170 0 my ($class, $compiled) = @_;
171 0 my (%tables, %columns, %indexes);
172  
173 # The public schema always exists in PostgreSQL; include it so the schema
174 # diff does not emit a spurious DROP SCHEMA public.
175 0 my %schemas = ( public => {} );
176  
177 0 ▶ for my $tname (keys %{ $compiled->{tables} // {} }) {
Condition0%0/2
$compiled->{"tables"} // {}
l!l
00
MC/DC0%0/1
$compiled->{"tables"} // {}
$compiled->{"tables"}
Truth table0%0/2
A
A= $compiled->{"tables"}
Aresult
11
00
178 0 my $t = $compiled->{tables}{$tname};
179 0 my $key = "public.$tname";
180  
181 0 $tables{$key} = {
182 schema_name => 'public',
183 table_name => $tname,
184 kind => 'r',
185 };
186  
187 0 my @cols;
188 my @pk_cols;
189 0 ▶ for my $c (@{ $t->{columns} // [] }) {
Condition0%0/2
$t->{"columns"} // []
l!l
00
MC/DC0%0/1
$t->{"columns"} // []
$t->{"columns"}
Truth table0%0/2
A
A= $t->{"columns"}
Aresult
11
00
190 0 my $native = $c->{native_type};
191 0 ▶ my $data_type = $_PG_FORMAT_TYPE{$native} // $native;
Condition0%0/3
$_PG_FORMAT_TYPE{$native} // $native
l!l&&r!l&&!r
000
MC/DC0%0/2
$_PG_FORMAT_TYPE{$native} // $native
$_PG_FORMAT_TYPE{$native} $native
Truth table0%0/3
A // B
A= $_PG_FORMAT_TYPE{$native}B= $native
ABresult
1X1
011
000
192  
193 0 my $identity = undef;
194 0 my $default_value = _format_pg_default($c->{default}, $data_type);
195  
196 0 ▶ if ($c->{auto_increment} && $c->{is_pk}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($c->{'auto_increment'} and $c->{'is_pk'}) { } 0 0 0
elsif ($c->{'auto_increment'}) { } 0 0 0
Condition0%0/3
$c->{"auto_increment"} and $c->{"is_pk"}
!ll&&!rl&&r
000
MC/DC0%0/2
$c->{"auto_increment"} and $c->{"is_pk"}
$c->{"auto_increment"} $c->{"is_pk"}
Truth table0%0/3
A and B
A= $c->{"auto_increment"}B= $c->{"is_pk"}
ABresult
0X0
100
111
197 # Deploy as GENERATED ALWAYS AS IDENTITY; PG reports identity='a' and no default.
198 0 $identity = 'a';
199 0 $default_value = undef;
200 }
201 elsif ($c->{auto_increment}) {
202 # Non-PK auto-increment: DDL.pm emits GENERATED BY DEFAULT AS IDENTITY,
203 # and PG reports attidentity='d' with no default expression.
204 0 $identity = 'd';
205 0 $default_value = undef;
206 }
207  
208 push @cols, {
209 column_name => $c->{column_name},
210 data_type => $data_type,
211 0 ▶ not_null => ($c->{not_null} ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
$c->{'not_null'} ? : 0 0 0
212 default_value => $default_value,
213 identity => $identity,
214 generated => undef,
215 };
216  
217 0 ▶ push @pk_cols, $c->{column_name} if $c->{is_pk};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"is_pk"} 0 0 0
218 }
219 0 $columns{$key} = \@cols;
220  
221 # PostgreSQL automatically creates a primary key index named <table>_pkey.
222 # Include it in the target so the index diff does not flag it as dropped.
223 # The definition string matches what pg_get_indexdef returns, enabling
224 # the definition-based comparison in Diff::Index.
225 0 ▶ if (@pk_cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pk_cols) 0 0 0
226 0 my $pkey_name = "${tname}_pkey";
227 0 my $cols_str = join ', ', @pk_cols;
228 0 my $definition = "CREATE UNIQUE INDEX $pkey_name ON public.$tname USING btree ($cols_str)";
229 0 $indexes{$key}{$pkey_name} = {
230 index_name => $pkey_name,
231 access_method => 'btree',
232 is_unique => 1,
233 is_primary => 1,
234 is_valid => 1,
235 definition => $definition,
236 predicate => undef,
237 expressions => undef,
238 columns => \@pk_cols,
239 include_columns => [],
240 storage_params => {},
241 };
242 }
243 }
244  
245 return {
246 0 tables => \%tables,
247 columns => \%columns,
248 schemas => \%schemas,
249 extensions => {},
250 types => {},
251 functions => {},
252 indexes => \%indexes,
253 triggers => {},
254 policies => {},
255 sequences => {},
256 foreign_keys => {},
257 check_constraints => {},
258 };
259 }
260  
261  
262 8 1;
263  
264 __END__
265  
266 =pod
267  
268 =encoding UTF-8
269  
270 =head1 NAME
271  
272 DBIO::PostgreSQL::Diff - Compare two introspected PostgreSQL models
273  
274 =head1 VERSION
275  
276 version 0.900001
277  
278 =head1 DESCRIPTION
279  
280 C<DBIO::PostgreSQL::Diff> compares two introspected PostgreSQL database models
281 (as produced by L<DBIO::PostgreSQL::Introspect>) and produces a list of
282 structured diff operations. These operations can then be rendered to SQL or a
283 human-readable summary.
284  
285 my $diff = DBIO::PostgreSQL::Diff->new(
286 source => $current_model,
287 target => $desired_model,
288 );
289  
290 if ($diff->has_changes) {
291 print $diff->as_sql;
292 print $diff->summary;
293 }
294  
295 Diff operations are generated in dependency order: extensions first, then
296 schemas, types, functions, tables, columns, indexes, triggers, and policies.
297 That same order is used for both C<summary> and C<as_sql>, so review output and
298 executable output stay aligned.
299  
300 =head1 METHODS
301  
302 =head2 register_diff_class
303  
304 DBIO::PostgreSQL::Diff->register_diff_class(
305 model_key => 'spatial_refs',
306 class => 'DBIO::PostgreSQL::PostGIS::Diff::SpatialRef',
307 position => 'after:indexes',
308 );
309  
310 Register a Diff class for a model key. Use C<position> (C<after:KEY> or C<before:KEY>) to control ordering.
311  
312 =head2 target_from_compiled
313  
314 my $target = DBIO::PostgreSQL::Diff->target_from_compiled($compiled_model);
315  
316 Translates the neutral model from L<DBIO::Schema::ModelCompiler> into the
317 PostgreSQL introspect-shaped model that C<diff> consumes.
318  
319 The compiled model uses C<native_type> (as produced by
320 L<DBIO::PostgreSQL::Adapter>). This method translates that into the exact
321 C<data_type> strings that L<DBIO::PostgreSQL::Introspect::Columns> returns
322 (i.e. whatever C<pg_catalog.format_type> reports), keys tables as
323 C<"public.$table_name">, and populates all top-level sections the Diff
324 engine dereferences so that no spurious diffs arise from missing keys.
325  
326 Auto-increment primary-key columns are mapped to C<identity = 'a'>
327 (C<GENERATED ALWAYS AS IDENTITY>), which is the canonical DBIO convention
328 for integer PKs in PostgreSQL.
329  
330 =seealso
331  
332 =over 4
333  
334 =item * L<DBIO::PostgreSQL::Deploy> - orchestrates introspection and diff
335  
336 =item * L<DBIO::PostgreSQL::Introspect> - produces the models being compared
337  
338 =item * L<DBIO::PostgreSQL::Diff::Schema>
339  
340 =item * L<DBIO::PostgreSQL::Diff::Table>
341  
342 =item * L<DBIO::PostgreSQL::Diff::Column>
343  
344 =item * L<DBIO::PostgreSQL::Diff::Type>
345  
346 =item * L<DBIO::PostgreSQL::Diff::Index>
347  
348 =item * L<DBIO::PostgreSQL::Diff::Function>
349  
350 =item * L<DBIO::PostgreSQL::Diff::Trigger>
351  
352 =item * L<DBIO::PostgreSQL::Diff::Policy>
353  
354 =item * L<DBIO::PostgreSQL::Diff::Extension>
355  
356 =back
357  
358 =head1 AUTHOR
359  
360 DBIO & DBIx::Class Authors
361  
362 =head1 COPYRIGHT AND LICENSE
363  
364 Copyright (C) 2026 DBIO Authors
365 Portions Copyright (C) 2005-2025 DBIx::Class Authors
366 Based on DBIx::Class, heavily modified.
367  
368 This is free software; you can redistribute it and/or modify it under
369 the same terms as the Perl 5 programming language system itself.
370  
371 =cut
« PostgreSQL/DDL.pm ↑ Summary PostgreSQL/Introspect/Indexes.pm »