DuckDB/DDL.pm

filter: Statementstmt 11.2% 13 / 116 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 37 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 40.0% 4 / 10 Podpod 100% 1 / 1 totaltotal 7.3% 18 / 246 CC 55 SCAR 60.9
CC
55
Cov
6%
install_ddl
812.0
_topo_sort_sources
306.0
_resolve_table_name
30.0
CRAP 441.6
↑ Summary DuckDB/Introspect/Columns.pm »
1 package DBIO::DuckDB::DDL;
2 # ABSTRACT: Generate DuckDB DDL from DBIO Result classes
3  
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 3 ▶use DBIO::SQL::Util qw(_quote_ident);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use DBIO::DuckDB::DDL::Emit qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
9 column_def pk_clause unique_clause create_table create_index create_sequence
10 3 );
11  
12  
13  
14 0 ▶sub install_ddl {
Subroutine install_ddl: not called CC=28 SCAR=67.0
Pod documented
15 0 my ($class, $schema) = @_;
16  
17 0 my @stmts;
18 my %seen_table;
19 0 my @view_stmts;
20 0 my %seen_view;
21  
22 0 for my $source_name (_topo_sort_sources($schema)) {
23 0 my $source = $schema->source($source_name);
24 0 my $result_class = $source->result_class;
25 # Views: emit CREATE VIEW after all tables; skip virtual views.
26 0 ▶ if ($source->isa('DBIO::ResultSource::View')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source->isa("DBIO::ResultSource::View")) 0 0 0
27 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
28 0 my $vname = _resolve_table_name($source->name);
29 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
30 0 ▶ my $def = $source->can('view_definition') ? $source->view_definition : undef;
Branch: 1 branch
BranchTrueFalseTotal
$source->can('view_definition') ? : 0 0 0
31 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
32 0 push @view_stmts, sprintf 'CREATE VIEW %s AS %s;', _quote_ident($vname), $def;
33 0 next;
34 }
35  
36 0 my $table_name = _resolve_table_name($source->name);
37  
38 # Virtual / view source whose name is inline SQL: skip here. A
39 # CREATE VIEW path can come later.
40 0 ▶ next unless defined $table_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 0 0 0
41  
42 # Multiple Result classes may share one physical table (e.g. Artist /
43 # ArtistSubclass / SourceNameArtists all map to the "artist" table).
44 # Emit CREATE TABLE only once per distinct table name.
45 0 ▶ next if $seen_table{$table_name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_table{$table_name}++ 0 0 0
46  
47 0 my @col_defs;
48 my %is_pk;
49 0 my @pk_cols = $source->primary_columns;
50 0 @is_pk{@pk_cols} = (1) x @pk_cols;
51  
52 0 for my $col_name ($source->columns) {
53 0 my $info = $source->column_info($col_name);
54  
55 # Resolve the DEFAULT fragment. DuckDB prefers sequences, so a
56 # simple auto-increment becomes a generated-by-sequence default;
57 # a dedicated sequence per table keeps round-trip predictable.
58 0 my $default;
59 0 ▶ if ($info->{is_auto_increment}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($info->{'is_auto_increment'}) { } 0 0 0
elsif (defined $info->{'default_value'}) { } 0 0 0
60 0 ▶ if (_is_guid_type($info)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_guid_type($info)) { } 0 0 0
61 # A UUID column cannot default from an integer sequence; DuckDB
62 # generates GUIDs with uuid().
63 0 $default = 'uuid()';
64 }
65 else {
66 0 my $seq = "${table_name}_${col_name}_seq";
67 0 $default = sprintf q{nextval('%s')}, $seq;
68 }
69 }
70 elsif (defined $info->{default_value}) {
71 0 my $dv = $info->{default_value};
72 0 ▶ $default = ref $dv eq 'SCALAR' ? $$dv : "'$dv'";
Branch: 1 branch
BranchTrueFalseTotal
ref $dv eq 'SCALAR' ? : 0 0 0
73 }
74  
75 push @col_defs, column_def(
76 name => $col_name,
77 type => _duckdb_column_type($info),
78 0 ▶ not_null => (defined $info->{is_nullable} && !$info->{is_nullable}),
Condition0%0/3
defined $info->{'is_nullable'} && !$info->{'is_nullable'}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $info->{'is_nullable'} && !$info->{'is_nullable'}
defined $info->{'is_nullable'} !$info->{'is_nullable'}
Truth table0%0/3
A && not(B)
A= defined $info->{'is_nullable'}B= !$info->{'is_nullable'}
ABresult
0X0
100
111
79 default => $default,
80 );
81 }
82  
83 0 ▶ push @col_defs, pk_clause(@pk_cols) if @pk_cols;
Branch: 1 branch
BranchTrueFalseTotal
if @pk_cols 0 0 0
84  
85 0 ▶ if ($source->can('unique_constraints')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source->can("unique_constraints")) 0 0 0
86 0 my %uniques = $source->unique_constraints;
87 0 for my $uname (sort keys %uniques) {
88 0 ▶ next if $uname eq 'primary';
Branch: 1 branch
BranchTrueFalseTotal
if $uname eq "primary" 0 0 0
89 0 push @col_defs, unique_clause(@{ $uniques{$uname} });
90 }
91 }
92  
93 # Foreign keys are intentionally NOT emitted in install DDL.
94 #
95 # DuckDB does not enforce FK constraints at runtime (as of 1.x), but
96 # it IS strict at CREATE TABLE time: the referenced column tuple
97 # must match a primary key or unique constraint on the parent table
98 # *in the same column order*. DBIO result classes often declare FKs
99 # with alphabetically-sorted condition hashes that do not match the
100 # parent PK order, which DuckDB rejects.
101 #
102 # Since the constraint has no runtime effect anyway, we skip it here
103 # and rely on application logic for referential integrity. The
104 # introspect/diff layer can still round-trip FKs if a user adds them
105 # via raw SQL.
106  
107 # Emit any required sequences BEFORE the table.
108 0 for my $col_name ($source->columns) {
109 0 my $info = $source->column_info($col_name);
110 0 ▶ next unless $info->{is_auto_increment};
Branch: 1 branch
BranchTrueFalseTotal
unless $info->{"is_auto_increment"} 0 0 0
111 0 ▶ next if _is_guid_type($info); # GUID auto columns default via uuid(), no sequence
Branch: 1 branch
BranchTrueFalseTotal
if _is_guid_type($info) 0 0 0
112 0 my $seq = "${table_name}_${col_name}_seq";
113 # Start high enough that test fixtures / manual inserts with small
114 # explicit IDs don't collide with nextval(). DuckDB sequences do
115 # not auto-advance on manual inserts the way PG IDENTITY columns
116 # do, so we bias the range instead.
117 0 push @stmts, create_sequence(name => $seq, start => 1000000);
118 }
119  
120 0 push @stmts, create_table($table_name, @col_defs);
121  
122 # Standalone indexes declared via duckdb_indexes class method.
123 0 ▶ if ($result_class->can('duckdb_indexes')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class->can("duckdb_indexes")) 0 0 0
124 0 my $indexes = $result_class->duckdb_indexes;
125 0 for my $idx_name (sort keys %$indexes) {
126 0 my $idx = $indexes->{$idx_name};
127 push @stmts, create_index(
128 name => $idx_name,
129 table => $table_name,
130 columns => $idx->{columns} // [],
131 unique => $idx->{unique},
132 0 ▶ );
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
133 }
134 }
135 }
136  
137 0 return join "
138  
139 ", @stmts, @view_stmts;
140 }
141  
142 0 ▶sub _resolve_table_name {
Subroutine _resolve_table_name: not called CC=5 SCAR=34.0
143 0 my ($name) = @_;
144 # Plain string: real table name.
145 0 ▶ return $name unless ref $name;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $name 0 0 0
146 0 ▶ return undef unless ref $name eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $name eq "SCALAR" 0 0 0
147 # SCALAR ref: either a pointer to a plain identifier (DBIx::Class test
148 # idiom for "this is a real table whose name happens to come from a
149 # ref") or inline SQL for a virtual view. Treat word-only content as
150 # a real identifier; anything else (whitespace, SELECT, parens) is a
151 # virtual view and is skipped.
152 0 my $v = $$name;
153 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
154 0 ▶ return $v if $v =~ /\A\w+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A\w+\z/ 0 0 0
155 0 return undef;
156 }
157  
158 0 ▶sub _topo_sort_sources {
Subroutine _topo_sort_sources: not called CC=17 SCAR=57.2
159 0 my ($schema) = @_;
160  
161 0 my %deps; # source_name => { dep_source_name => 1 }
162 my %by_table; # table_name => first source_name seen
163 0 my @sources = sort $schema->sources;
164  
165 0 for my $name (@sources) {
166 0 my $s = $schema->source($name);
167 0 my $t = _resolve_table_name($s->name);
168 0 ▶ next unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 0 0
169 0 ▶ $by_table{$t} //= $name;
Condition0%0/3
$by_table{$t} //= $name
l!l&&r!l&&!r
000
MC/DC0%0/2
$by_table{$t} //= $name
$by_table{$t} $name
Truth table0%0/3
A //= B
A= $by_table{$t}B= $name
ABresult
1X1
011
000
170 }
171  
172 0 for my $name (@sources) {
173 0 my $s = $schema->source($name);
174 0 ▶ next unless defined _resolve_table_name($s->name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _resolve_table_name($s->name) 0 0 0
175 0 ▶ $deps{$name} ||= {};
Condition0%0/2
$deps{$name} ||= {}
l!l
00
MC/DC0%0/1
$deps{$name} ||= {}
$deps{$name}
Truth table0%0/2
A
A= $deps{$name}
Aresult
11
00
176 0 for my $rel ($s->relationships) {
177 0 my $info = $s->relationship_info($rel);
178 next unless $info && $info->{attrs}
179 0 ▶ && $info->{attrs}{is_foreign_key_constraint};
Branch: 1 branch
BranchTrueFalseTotal
unless $info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"} 0 0 0
Condition0%0/6
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
!ll&&!rl&&r
000
$info and $info->{"attrs"}
!ll&&!rl&&r
000
MC/DC0%0/3
$info and $info->{"attrs"} and $info->{"attrs"}{"is_foreign_key_constraint"}
$info $info->{"attrs"} $info->{"attrs"}{"is_foreign_key_constraint"}
Truth table0%0/4
A and B and C
A= $infoB= $info->{"attrs"}C= $info->{"attrs"}{"is_foreign_key_constraint"}
ABCresult
0XX0
10X0
1100
1111
180 0 my $foreign = $info->{class};
181 0 my $fs = eval { $schema->source($foreign) }
182 0 ▶ // eval { $schema->source($foreign =~ s/.*:://r) };
Condition0%0/3
eval { // eval {
l!l&&r!l&&!r
000
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 table0%0/3
A // B
A= eval { do { $schema->source($foreign) } }B= eval { do { $schema->source($foreign =~ s/.*:://r) } }
ABresult
1X1
011
000
183 0 ▶ next unless $fs;
Branch: 1 branch
BranchTrueFalseTotal
unless $fs 0 0 0
184 0 my $ft = _resolve_table_name($fs->name);
185 0 ▶ next unless defined $ft;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ft 0 0 0
186 # Depend on whichever source "owns" the foreign table.
187 0 my $owner = $by_table{$ft};
188 0 ▶ next unless $owner;
Branch: 1 branch
BranchTrueFalseTotal
unless $owner 0 0 0
189 0 ▶ next if $owner eq $name; # self-reference
Branch: 1 branch
BranchTrueFalseTotal
if $owner eq $name 0 0 0
190 0 $deps{$name}{$owner} = 1;
191 }
192 }
193  
194 # Kahn's algorithm with stable alphabetical tiebreak.
195 0 my @out;
196 my %visited;
197 0 my $visit;
198 0 ▶ $visit = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
199 0 my ($n) = @_;
200 0 ▶ return if $visited{$n}++;
Branch: 1 branch
BranchTrueFalseTotal
if $visited{$n}++ 0 0 0
201 0 ▶ for my $d (sort keys %{ $deps{$n} || {} }) {
Condition0%0/2
$deps{$n} || {}
l!l
00
MC/DC0%0/1
$deps{$n} || {}
$deps{$n}
Truth table0%0/2
A
A= $deps{$n}
Aresult
11
00
202 0 $visit->($d);
203 }
204 0 push @out, $n;
205 0 };
206 0 $visit->($_) for @sources;
207 0 return @out;
208 }
209  
210 0 ▶sub _duckdb_column_type {
Subroutine _duckdb_column_type: not called CC=4 SCAR=30.0
211 0 my ($info) = @_;
212 0 ▶ my $type = $info->{data_type} // 'VARCHAR';
Condition0%0/2
$info->{"data_type"} // "VARCHAR"
l!l
00
MC/DC0%0/1
$info->{"data_type"} // "VARCHAR"
$info->{"data_type"}
Truth table0%0/2
A
A= $info->{"data_type"}
Aresult
11
00
213  
214 0 ▶ return $type if $type =~ /\(.+\)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ /\(.+\)$/ 0 0 0
215  
216 0 my %type_map = (
217 # integers
218 tinyint => 'TINYINT',
219 smallint => 'SMALLINT',
220 int => 'INTEGER',
221 integer => 'INTEGER',
222 bigint => 'BIGINT',
223 hugeint => 'HUGEINT',
224 serial => 'INTEGER',
225 bigserial => 'BIGINT',
226  
227 # floats / decimals
228 real => 'REAL',
229 float => 'FLOAT',
230 double => 'DOUBLE',
231 'double precision'=> 'DOUBLE',
232 money => 'DECIMAL(19,4)', # DuckDB has no MONEY type
233 numeric => 'DECIMAL',
234 decimal => 'DECIMAL',
235  
236 # strings
237 text => 'VARCHAR',
238 string => 'VARCHAR',
239 varchar => 'VARCHAR',
240 char => 'VARCHAR',
241 character => 'VARCHAR',
242 clob => 'VARCHAR',
243 tinytext => 'VARCHAR',
244 mediumtext => 'VARCHAR',
245 longtext => 'VARCHAR',
246 ntext => 'VARCHAR',
247  
248 # booleans
249 boolean => 'BOOLEAN',
250 bool => 'BOOLEAN',
251  
252 # blobs
253 blob => 'BLOB',
254 bytea => 'BLOB',
255 tinyblob => 'BLOB',
256 mediumblob => 'BLOB',
257 longblob => 'BLOB',
258 binary => 'BLOB',
259 varbinary => 'BLOB',
260 'bit varying' => 'BLOB',
261  
262 # temporal
263 date => 'DATE',
264 time => 'TIME',
265 datetime => 'TIMESTAMP',
266 timestamp => 'TIMESTAMP',
267 timestamptz => 'TIMESTAMPTZ',
268 'timestamp with time zone' => 'TIMESTAMPTZ',
269 interval => 'INTERVAL',
270  
271 # misc
272 uuid => 'UUID',
273 guid => 'UUID',
274 uniqueidentifier => 'UUID', # MSSQL/Sybase GUID type -> DuckDB native UUID
275 json => 'JSON',
276 );
277  
278 0 ▶ return $type_map{ lc $type } // uc $type;
Condition0%0/3
$type_map{lc $type} // uc $type
l!l&&r!l&&!r
000
MC/DC0%0/2
$type_map{lc $type} // uc $type
$type_map{lc $type} uc $type
Truth table0%0/3
A // B
A= $type_map{lc $type}B= uc $type
ABresult
1X1
011
000
279 }
280  
281 # A GUID-family column maps to DuckDB's native UUID type, which (unlike an
282 # integer surrogate key) cannot take a nextval() sequence default — its
283 # auto-generated value comes from uuid() instead.
284 0 ▶sub _is_guid_type {
Subroutine _is_guid_type: not called CC=2 SCAR=17.9
285 0 my $info = shift;
286 0 ▶ return ( ($info->{data_type} // '') =~ /\A(?:uniqueidentifier|guid|uuid)\z/i );
Condition0%0/2
$info->{"data_type"} // ""
l!l
00
MC/DC0%0/1
$info->{"data_type"} // ""
$info->{"data_type"}
Truth table0%0/2
A
A= $info->{"data_type"}
Aresult
11
00
287 }
288  
289 3 1;
290  
291 __END__
292  
293 =pod
294  
295 =encoding UTF-8
296  
297 =head1 NAME
298  
299 DBIO::DuckDB::DDL - Generate DuckDB DDL from DBIO Result classes
300  
301 =head1 VERSION
302  
303 version 0.900001
304  
305 =head1 DESCRIPTION
306  
307 C<DBIO::DuckDB::DDL> generates a DuckDB DDL script from a L<DBIO::Schema>
308 class hierarchy. It is the desired-state side of the test-deploy-and-
309 compare strategy used by L<DBIO::DuckDB::Deploy>.
310  
311 my $ddl = DBIO::DuckDB::DDL->install_ddl($schema_class_or_instance);
312  
313 The output is plain SQL, suitable for executing one statement at a time
314 against a fresh DuckDB database. Emits C<CREATE TABLE> (inline columns,
315 primary key, unique, foreign keys) and C<CREATE INDEX>.
316  
317 DuckDB has real sequences and real schemas (namespaces), but for the
318 first cut we mirror the dbio-sqlite shape and emit only tables + indexes.
319 Sequences can be added later when the ResultSource metadata carries them.
320  
321 =head1 METHODS
322  
323 =head2 install_ddl
324  
325 my $ddl = DBIO::DuckDB::DDL->install_ddl($schema);
326  
327 Returns the full installation DDL as a single string.
328  
329 =head1 AUTHOR
330  
331 DBIO Authors
332  
333 =head1 COPYRIGHT AND LICENSE
334  
335 Copyright (C) 2026 DBIO Authors
336  
337 This is free software; you can redistribute it and/or modify it under
338 the same terms as the Perl 5 programming language system itself.
339  
340 =cut
↑ Summary DuckDB/Introspect/Columns.pm »