DB2/DDL.pm

filter: Statementstmt 82.1% 124 / 151 Branchbran 44.1% 30 / 68 Conditioncond 38.3% 18 / 47 MC/DCmcdc 14.2% 4 / 28 Subroutinesub 100% 12 / 12 Podpod 100% 1 / 1 totaltotal 61.5% 189 / 307 CC 63 SCAR 39.3
CC
63
Cov
65%
install_ddl
128.0
_topo_sort_sources
20.6
_resolve_table_name
17.8
CRAP 50.7
« DB2/Introspect/Indexes.pm ↑ Summary DB2/Introspect/ForeignKeys.pm »
1 package DBIO::DB2::DDL;
2 # ABSTRACT: Generate DB2 DDL from DBIO Result classes
3  
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use DBIO::DB2::Type qw(_db2_column_type);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use DBIO::SQL::Util qw(_quote_ident);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 5 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 5 our @EXPORT_OK = qw(_fk_constraint_clause);
13  
14  
15  
16 1 ▶sub install_ddl {
Subroutine install_ddl: called CC=24 SCAR=48.5
Pod documented
17 1 my ($class, $schema) = @_;
18  
19 1 my @stmts;
20 my %seen_table;
21 1 my @view_stmts;
22 1 my %seen_view;
23  
24 1 for my $source_name (_topo_sort_sources($schema)) {
25 3 my $source = $schema->source($source_name);
26 3 my $result_class = $source->result_class;
27 # Views: emit CREATE VIEW after all tables; skip virtual views.
28 3 ▶ if ($source->isa('DBIO::ResultSource::View')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source->isa("DBIO::ResultSource::View")) 0 3 3
29 0 ▶ next if $source->can('is_virtual') && $source->is_virtual;
Branch: 1 branch
BranchTrueFalseTotal
if $source->can("is_virtual") and $source->is_virtual 0 0 0
Condition0%0/3
$source->can("is_virtual") and $source->is_virtual
!ll&&!rl&&r
000
MC/DC0%0/2
$source->can("is_virtual") and $source->is_virtual
$source->can("is_virtual") $source->is_virtual
Truth table0%0/3
A and B
A= $source->can("is_virtual")B= $source->is_virtual
ABresult
0X0
100
111
30 0 my $vname = _resolve_table_name($source->name);
31 0 ▶ next if !defined $vname || $seen_view{$vname}++;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $vname or $seen_view{$vname}++ 0 0 0
Condition0%0/3
not defined $vname or $seen_view{$vname}++
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $vname or $seen_view{$vname}++
not defined $vname $seen_view{$vname}++
Truth table0%0/3
not(A) or B
A= not defined $vnameB= $seen_view{$vname}++
ABresult
1X1
011
000
32 0 ▶ my $def = $source->can('view_definition') ? $source->view_definition : undef;
Branch: 1 branch
BranchTrueFalseTotal
$source->can('view_definition') ? : 0 0 0
33 0 ▶ next unless defined $def && length $def;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $def and length $def 0 0 0
Condition0%0/3
defined $def and length $def
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def and length $def
defined $def length $def
Truth table0%0/3
A and B
A= defined $defB= length $def
ABresult
0X0
100
111
34 0 push @view_stmts, sprintf 'CREATE VIEW %s AS %s;', _quote_ident($vname), $def;
35 0 next;
36 }
37  
38 3 my $table_name = _resolve_table_name($source->name);
39  
40 3 ▶ next unless defined $table_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 0 3 3
41 3 ▶ next if $seen_table{$table_name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_table{$table_name}++ 0 3 3
42  
43 3 my @col_defs;
44 my %is_pk;
45 3 my @pk_cols = $source->primary_columns;
46 3 @is_pk{@pk_cols} = (1) x @pk_cols;
47  
48 3 for my $col_name ($source->columns) {
49 7 my $info = $source->column_info($col_name);
50 7 my $type = _db2_column_type($info);
51  
52 7 my $def = sprintf ' %s %s', _quote_ident($col_name), $type;
53  
54 7 ▶ $def .= ' NOT NULL' if defined $info->{is_nullable} && !$info->{is_nullable};
Branch: 1 branch
BranchTrueFalseTotal
if defined $info->{"is_nullable"} and not $info->{"is_nullable"} 0 7 7
Condition33%1/3
defined $info->{"is_nullable"} and not $info->{"is_nullable"}
!ll&&!rl&&r
700
MC/DC0%0/2
defined $info->{"is_nullable"} and not $info->{"is_nullable"}
defined $info->{"is_nullable"} not $info->{"is_nullable"}
Truth table33%1/3
A and not(B)
A= defined $info->{"is_nullable"}B= not $info->{"is_nullable"}
ABresult
0X0
100
111
55  
56 7 ▶ if ($info->{is_auto_increment}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($info->{'is_auto_increment'}) { } 3 4 7
elsif (defined $info->{'default_value'}) { } 0 4 4
57 # DB2 uses GENERATED ALWAYS AS IDENTITY for auto-increment
58 3 $def .= ' GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)';
59 }
60 elsif (defined $info->{default_value}) {
61 0 my $dv = $info->{default_value};
62 0 ▶ if (ref $dv eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $dv eq 'SCALAR') { } 0 0 0
63 0 $def .= " DEFAULT $$dv";
64 } else {
65 0 $def .= " DEFAULT '$dv'";
66 }
67 }
68  
69 7 push @col_defs, $def;
70 }
71  
72 3 ▶ if (@pk_cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pk_cols) 3 0 3
73 push @col_defs, sprintf ' PRIMARY KEY (%s)',
74 3 join(', ', map { _quote_ident($_) } @pk_cols);
75 }
76  
77 # Named inline foreign keys derived from belongs_to relationships. DB2
78 # enforces RI, so the install DDL must carry them; the deterministic name
79 # (fk_<table>_<from_cols>) makes the constraint round-trip with a stable
80 # identity for the name-based diff in DBIO::DB2::Diff::ForeignKey.
81 3 for my $fk (_table_foreign_keys($schema, $source)) {
82 2 push @col_defs, ' ' . _fk_constraint_clause($fk);
83 }
84  
85 3 push @stmts, sprintf "CREATE TABLE %s (\n%s\n);",
86 _quote_ident($table_name), join(",\n", @col_defs);
87  
88 # Standalone indexes
89 3 ▶ if ($result_class->can('db2_indexes')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class->can("db2_indexes")) 0 3 3
90 0 my $indexes = $result_class->db2_indexes;
91 0 for my $idx_name (sort keys %$indexes) {
92 0 my $idx = $indexes->{$idx_name};
93 0 ▶ my $unique = $idx->{unique} ? 'UNIQUE ' : '';
Branch: 1 branch
BranchTrueFalseTotal
$idx->{'unique'} ? : 0 0 0
94 my $columns = join ', ',
95 0 ▶ map { _quote_ident($_) } @{ $idx->{columns} // [] };
Condition0%0/2
$idx->{"columns"} // []
l!l
00
MC/DC0%0/1
$idx->{"columns"} // []
$idx->{"columns"}
Truth table0%0/2
A
A= $idx->{"columns"}
Aresult
11
00
96 0 my $sql = sprintf 'CREATE %sINDEX %s ON %s (%s)',
97 $unique, _quote_ident($idx_name),
98 _quote_ident($table_name), $columns;
99 0 push @stmts, "$sql;";
100 }
101 }
102 }
103  
104 1 return join "
105  
106 ", @stmts, @view_stmts;
107 }
108  
109 16 ▶sub _resolve_table_name {
Subroutine _resolve_table_name: called CC=5 SCAR=28.8
110 16 my ($name) = @_;
111 16 ▶ return $name unless ref $name;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $name 16 0 16
112 0 ▶ return undef unless ref $name eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $name eq "SCALAR" 0 0 0
113 0 my $v = $$name;
114 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
115 0 ▶ return $v if $v =~ /\A\w+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A\w+\z/ 0 0 0
116 0 return undef;
117 }
118  
119 # Deterministic constraint name for an FK, derived from the owning table and
120 # its local columns: fk_<table>_<col1>_<col2>. Stable across the live DB and
121 # the throwaway compare schema (both built from this same DDL), which is what
122 # makes the name-based FK diff sound (ADR 0005).
123 2 ▶sub _fk_constraint_name {
Subroutine _fk_constraint_name: called CC=1 SCAR=0.0
124 2 my ($table, $from_cols) = @_;
125 2 return join '_', 'fk', $table, @$from_cols;
126 }
127  
128 # Single source of truth for the inline foreign-key clause shape (ADR 0005):
129 # CONSTRAINT <name> FOREIGN KEY (<from>) REFERENCES <to>(<to_cols>)
130 # [ON DELETE <rule>] [ON UPDATE <rule>]
131 # Returned WITHOUT leading indent and WITHOUT an ALTER TABLE ... ADD prefix, so
132 # install_ddl (inline, indented), DBIO::DB2::Diff::Table (inline, indented) and
133 # DBIO::DB2::Diff::ForeignKey (ALTER TABLE ... ADD <clause>) all render the same
134 # body. NO ACTION rules are suppressed (DB2's implicit default). The name comes
135 # straight from the model -- callers must NOT regenerate it.
136 11 ▶sub _fk_constraint_clause {
Subroutine _fk_constraint_clause: called CC=5 SCAR=16.2
137 11 my ($fk) = @_;
138 my $sql = sprintf 'CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s)',
139 _quote_ident($fk->{constraint_name}),
140 11 join(', ', map { _quote_ident($_) } @{ $fk->{from_columns} }),
141 _quote_ident($fk->{to_table}),
142 11 join(', ', map { _quote_ident($_) } @{ $fk->{to_columns} });
143 $sql .= " ON DELETE $fk->{on_delete}"
144 11 ▶ if $fk->{on_delete} && $fk->{on_delete} ne 'NO ACTION';
Branch: 1 branch
BranchTrueFalseTotal
if $fk->{"on_delete"} and $fk->{"on_delete"} ne "NO ACTION" 6 5 11
Condition100%3/3
$fk->{"on_delete"} and $fk->{"on_delete"} ne "NO ACTION"
!ll&&!rl&&r
146
MC/DC100%2/2
$fk->{"on_delete"} and $fk->{"on_delete"} ne "NO ACTION"
$fk->{"on_delete"} $fk->{"on_delete"} ne "NO ACTION"
Truth table100%3/3
A and B
A= $fk->{"on_delete"}B= $fk->{"on_delete"} ne "NO ACTION"
ABresult
0X0
100
111
145 $sql .= " ON UPDATE $fk->{on_update}"
146 11 ▶ if $fk->{on_update} && $fk->{on_update} ne 'NO ACTION';
Branch: 1 branch
BranchTrueFalseTotal
if $fk->{"on_update"} and $fk->{"on_update"} ne "NO ACTION" 0 11 11
Condition66%2/3
$fk->{"on_update"} and $fk->{"on_update"} ne "NO ACTION"
!ll&&!rl&&r
290
MC/DC0%0/2
$fk->{"on_update"} and $fk->{"on_update"} ne "NO ACTION"
$fk->{"on_update"} $fk->{"on_update"} ne "NO ACTION"
Truth table66%2/3
A and B
A= $fk->{"on_update"}B= $fk->{"on_update"} ne "NO ACTION"
ABresult
0X0
100
111
147 11 return $sql;
148 }
149  
150 # Collect the named foreign keys for one source, derived from its belongs_to
151 # relationships. Mirrors the column extraction in DBIO::MySQL::DDL: a FK cond
152 # is { "foreign.<refcol>" => "self.<localcol>" }.
153 3 ▶sub _table_foreign_keys {
Subroutine _table_foreign_keys: called CC=13 SCAR=27.1
154 3 my ($schema, $source) = @_;
155  
156 3 my $table_name = _resolve_table_name($source->name);
157 3 my @fks;
158 my %seen_name;
159  
160 3 for my $rel ($source->relationships) {
161 3 my $info = $source->relationship_info($rel);
162 next unless $info && $info->{attrs}
163 3 ▶ && $info->{attrs}{is_foreign_key_constraint};
Branch: 1 branch
BranchTrueFalseTotal
unless $info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"} 1 2 3
Condition50%3/6
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
!ll&&!rl&&r
012
$info and $info->{"attrs"}
!ll&&!rl&&r
003
MC/DC33%1/3
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
$info $info->{"attrs"} $info->{"attrs"}{"is_foreign_key_constraint"}
Truth table50%2/4
A and B and C
A= $infoB= $info->{"attrs"}C= $info->{"attrs"}{"is_foreign_key_constraint"}
ABCresult
0XX0
10X0
1100
1111
164  
165 2 my $foreign = $info->{class};
166 2 my $fs = eval { $schema->source($foreign) }
167 2 ▶ // eval { $schema->source($foreign =~ s/.*:://r) };
Condition33%1/3
eval { // eval {
l!l&&r!l&&!r
200
MC/DC0%0/2
eval { do { $schema->source($foreign) } } // eval { do { $schema->source($foreign =~ s/.*:://r) } }
eval { do { $schema->source($foreign) } } eval { do { $schema->source($foreign =~ s/.*:://r) } }
Truth table33%1/3
A // B
A= eval { do { $schema->source($foreign) } }B= eval { do { $schema->source($foreign =~ s/.*:://r) } }
ABresult
1X1
011
000
168 2 ▶ next unless $fs;
Branch: 1 branch
BranchTrueFalseTotal
unless $fs 0 2 2
169  
170 2 my $cond = $info->{cond};
171 2 ▶ next unless ref $cond eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cond eq "HASH" 0 2 2
172  
173 2 my (@from, @to);
174 2 for my $foreign_col (sort keys %$cond) {
175 2 my $fcol = $foreign_col;
176 2 $fcol =~ s/^foreign\.//;
177 2 my $self_col = $cond->{$foreign_col};
178 2 $self_col =~ s/^self\.//;
179 2 push @to, $fcol;
180 2 push @from, $self_col;
181 }
182 2 ▶ next unless @from;
Branch: 1 branch
BranchTrueFalseTotal
unless @from 0 2 2
183  
184 2 my $foreign_name = _resolve_table_name($fs->name);
185 2 ▶ next unless defined $foreign_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $foreign_name 0 2 2
186  
187 # The deterministic name keys on the local columns, so two relationships
188 # over the same column(s) would collide (DB2 rejects a duplicate constraint
189 # name, and the name-based diff needs one identity per name). Keep the
190 # first; a single FK per column-set is the normal case and is untouched.
191 2 my $name = _fk_constraint_name($table_name, \@from);
192 2 ▶ next if $seen_name{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_name{$name}++ 0 2 2
193  
194 2 ▶ my $attrs = $info->{attrs} || {};
Condition50%1/2
$info->{'attrs'} || {}
l!l
20
MC/DC0%0/1
$info->{'attrs'} || {}
$info->{'attrs'}
Truth table50%1/2
A
A= $info->{'attrs'}
Aresult
11
00
195 push @fks, {
196 constraint_name => $name,
197 from_columns => \@from,
198 to_table => $foreign_name,
199 to_columns => \@to,
200 on_delete => $attrs->{on_delete},
201 on_update => $attrs->{on_update},
202 2 };
203 }
204  
205 3 return @fks;
206 }
207  
208 1 ▶sub _topo_sort_sources {
Subroutine _topo_sort_sources: called CC=17 SCAR=30.3
209 1 my ($schema) = @_;
210  
211 1 my %deps;
212 my %by_table;
213 1 my @sources = sort $schema->sources;
214  
215 1 for my $name (@sources) {
216 3 my $s = $schema->source($name);
217 3 my $t = _resolve_table_name($s->name);
218 3 ▶ next unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 3 3
219 3 ▶ $by_table{$t} //= $name;
Condition33%1/3
$by_table{$t} //= $name
l!l&&r!l&&!r
030
MC/DC0%0/2
$by_table{$t} //= $name
$by_table{$t} $name
Truth table33%1/3
A //= B
A= $by_table{$t}B= $name
ABresult
1X1
011
000
220 }
221  
222 1 for my $name (@sources) {
223 3 my $s = $schema->source($name);
224 3 ▶ next unless defined _resolve_table_name($s->name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _resolve_table_name($s->name) 0 3 3
225 3 ▶ $deps{$name} ||= {};
Condition50%1/2
$deps{$name} ||= {}
l!l
03
MC/DC0%0/1
$deps{$name} ||= {}
$deps{$name}
Truth table50%1/2
A
A= $deps{$name}
Aresult
11
00
226 3 for my $rel ($s->relationships) {
227 3 my $info = $s->relationship_info($rel);
228 next unless $info && $info->{attrs}
229 3 ▶ && $info->{attrs}{is_foreign_key_constraint};
Branch: 1 branch
BranchTrueFalseTotal
unless $info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"} 1 2 3
Condition50%3/6
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
!ll&&!rl&&r
012
$info and $info->{"attrs"}
!ll&&!rl&&r
003
MC/DC33%1/3
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
$info $info->{"attrs"} $info->{"attrs"}{"is_foreign_key_constraint"}
Truth table50%2/4
A and B and C
A= $infoB= $info->{"attrs"}C= $info->{"attrs"}{"is_foreign_key_constraint"}
ABCresult
0XX0
10X0
1100
1111
230 2 my $foreign = $info->{class};
231 2 my $fs = eval { $schema->source($foreign) }
232 2 ▶ // eval { $schema->source($foreign =~ s/.*:://r) };
Condition33%1/3
eval { // eval {
l!l&&r!l&&!r
200
MC/DC0%0/2
eval { do { $schema->source($foreign) } } // eval { do { $schema->source($foreign =~ s/.*:://r) } }
eval { do { $schema->source($foreign) } } eval { do { $schema->source($foreign =~ s/.*:://r) } }
Truth table33%1/3
A // B
A= eval { do { $schema->source($foreign) } }B= eval { do { $schema->source($foreign =~ s/.*:://r) } }
ABresult
1X1
011
000
233 2 ▶ next unless $fs;
Branch: 1 branch
BranchTrueFalseTotal
unless $fs 0 2 2
234 2 my $ft = _resolve_table_name($fs->name);
235 2 ▶ next unless defined $ft;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ft 0 2 2
236 2 my $owner = $by_table{$ft};
237 2 ▶ next unless $owner;
Branch: 1 branch
BranchTrueFalseTotal
unless $owner 0 2 2
238 2 ▶ next if $owner eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if $owner eq $name 0 2 2
239 2 $deps{$name}{$owner} = 1;
240 }
241 }
242  
243 1 my @out;
244 my %visited;
245 1 my $visit;
246 5 ▶ $visit = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
247 5 my ($n) = @_;
248 5 ▶ return if $visited{$n}++;
Branch: 1 branch
BranchTrueFalseTotal
if $visited{$n}++ 2 3 5
249 3 ▶ for my $d (sort keys %{ $deps{$n} || {} }) {
Condition50%1/2
$deps{$n} || {}
l!l
30
MC/DC0%0/1
$deps{$n} || {}
$deps{$n}
Truth table50%1/2
A
A= $deps{$n}
Aresult
11
00
250 2 $visit->($d);
251 }
252 3 push @out, $n;
253 1 };
254 1 $visit->($_) for @sources;
255 1 return @out;
256 }
257  
258 5 1;
259  
260 __END__
261  
262 =pod
263  
264 =encoding UTF-8
265  
266 =head1 NAME
267  
268 DBIO::DB2::DDL - Generate DB2 DDL from DBIO Result classes
269  
270 =head1 VERSION
271  
272 version 0.900001
273  
274 =head1 DESCRIPTION
275  
276 C<DBIO::DB2::DDL> generates a DB2 DDL script from a L<DBIO::Schema>
277 class hierarchy. It is the desired-state side of the test-deploy-and-
278 compare strategy used by L<DBIO::DB2::Deploy>.
279  
280 my $ddl = DBIO::DB2::DDL->install_ddl($schema_class_or_instance);
281  
282 The output is plain SQL, suitable for executing one statement at a time
283 against a fresh DB2 database. Emits C<CREATE TABLE> (inline columns,
284 primary key and named C<FOREIGN KEY> constraints) and C<CREATE INDEX>.
285  
286 Foreign keys are emitted as B<named> inline constraints
287 (C<CONSTRAINT fk_E<lt>tableE<gt>_E<lt>colsE<gt> FOREIGN KEY ...>) with a
288 deterministic name derived from the relationship. DB2 enforces referential
289 integrity, so the install DDL must carry the FKs; the deterministic name
290 gives the live database and the throwaway compare schema the same stable
291 constraint identity, which is what makes the name-based FK diff in
292 L<DBIO::DB2::Diff::ForeignKey> sound (see ADR 0005). New-table FKs are also
293 rendered inline by L<DBIO::DB2::Diff::Table> on the diff path.
294  
295 =head1 METHODS
296  
297 =head2 install_ddl
298  
299 my $ddl = DBIO::DB2::DDL->install_ddl($schema);
300  
301 Returns the full installation DDL as a single string.
302  
303 =head1 AUTHOR
304  
305 DBIO & DBIx::Class Authors
306  
307 =head1 COPYRIGHT AND LICENSE
308  
309 Copyright (C) 2026 DBIO Authors
310 Portions Copyright (C) 2005-2025 DBIx::Class Authors
311 Based on DBIx::Class, heavily modified.
312  
313 This is free software; you can redistribute it and/or modify it under
314 the same terms as the Perl 5 programming language system itself.
315  
316 =cut
« DB2/Introspect/Indexes.pm ↑ Summary DB2/Introspect/ForeignKeys.pm »