blib/lib/DBIx/QuickORM/Dialect.pm

filter: Statementstmt 94.8% 510 / 538 Branchbran 91.2% 199 / 218 Conditioncond 74.2% 95 / 128 MC/DCmcdc 55.0% 38 / 69 Subroutinesub 94.9% 94 / 99 Podpod 100% 63 / 63 totaltotal 89.6% 999 / 1115 CC 330 SCAR 19.5
CC
330
Cov
91%
dialect_pairs
17.0
dialect_pairs
17.0
_pretty_table_body
14.0
CRAP 7.0
« blib/lib/DBIx/QuickORM/SchemaBuilder/View.pm ↑ Summary blib/lib/DBIx/QuickORM/RowState.pm »
1 package DBIx::QuickORM::Dialect;
2 274 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 274 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 274 our $VERSION = '0.000033';
6  
7 274 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 274 ▶use Scalar::Util qw/blessed weaken/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 274 ▶use DBI();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 274 ▶use POSIX();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 274 ▶use Object::HashBase qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
13 <server_version
14 <dbh
15 274 };
16  
17 =pod
18  
19 =encoding UTF-8
20  
21 =head1 NAME
22  
23 DBIx::QuickORM::Dialect - Base for the per-database facts and session setup.
24  
25 =head1 DESCRIPTION
26  
27 A dialect holds what the ORM needs to know about one database: quoting,
28 savepoints, C<RETURNING>, bind limits, error codes, session setup, and how to
29 scan the schema. Each supported database has one under
30 C<DBIx::QuickORM::Dialect::>. C<for_dbh> picks the one for a handle.
31  
32 C<for_dbh> returns a dialect object for one connection. It holds the
33 server's version (C<server_version>), read once at connect, so a method can
34 depend on it, and a weak reference to the handle (C<dbh>). Methods that need no server fact also work on the class.
35  
36 This base class holds the defaults most databases share: double-quoted
37 identifiers, savepoints, C<RETURNING> on every statement, and
38 C<current_schema()> as the namespace. A subclass overrides only what differs.
39  
40 Every dialect provides C<init_session($dbh, $time_zone)>, which turns on
41 UTF-8 for the session and sets the session time zone where the database has
42 one. C<$time_zone> is a zone name such as C<UTC> or C<America/New_York>,
43 passed to the database as given, except that MySQL and MariaDB get C<UTC> as
44 C<+00:00>.
45  
46 =head1 SYNOPSIS
47  
48 my $dialect = DBIx::QuickORM::Dialect->for_dbh($dbh);
49 $dialect->init_session($dbh, 'UTC');
50  
51 my $modern = $dialect->server_version >= 110000; # PostgreSQL 11 or later
52  
53 my $sql = 'SELECT * FROM ' . $dialect->quote_identifier('users');
54  
55 =head1 ATTRIBUTES
56  
57 =over 4
58  
59 =item $version = $dialect->server_version
60  
61 The server's version as one integer, so versions compare with C<< >= >>:
62  
63 =over 4
64  
65 =item *
66  
67 PostgreSQL: its own number, C<pg_server_version> (C<110000> is 11.0, C<90603>
68 is 9.6.3).
69  
70 =item *
71  
72 MySQL, MariaDB, SQLite, DuckDB: C<major * 1_000_000 + minor * 1_000 + patch>,
73 from the server's version string (C<8.0.36> is C<8000036>).
74  
75 =back
76  
77 Undef when the server's version string cannot be read.
78  
79 =item $dbh = $dialect->dbh
80  
81 The handle C<for_dbh> was given, held weakly. Undef for a dialect from
82 C<for_name>, which has no connection.
83  
84 =back
85  
86 =head1 PUBLIC METHODS
87  
88 The examples use a Connection's dialect and handle, on PostgreSQL with the
89 C<users> and C<posts> tables of L<DBIx::QuickORM::Manual::Quickstart>:
90  
91 my $dialect = $orm->connection->dialect;
92 my $dbh = $orm->connection->dbh;
93  
94 The C<My::Dialect> sketches show what a dialect overrides, as when a database
95 is added to the distribution. A subclass of your own cannot be registered:
96 C<for_dbh> picks only from the dialects that ship here.
97  
98 =over 4
99  
100 =item $dialect = DBIx::QuickORM::Dialect->for_dbh($dbh)
101  
102 The dialect object for a connected handle, chosen by driver name, with the
103 server's version read from the handle.
104  
105 The chosen class may refine the choice from the server (C<dialect_for_dbh>).
106 L<DBD::MariaDB> gives the MariaDB dialect for a MariaDB server, the MySQL one
107 otherwise. An unsupported driver croaks, naming the supported ones.
108  
109 =back
110  
111 =cut
112  
113 274 my %DRIVERS = (
114 Pg => 'PostgreSQL',
115 MariaDB => 'MySQL',
116 SQLite => 'SQLite',
117 DuckDB => 'DuckDB',
118 );
119  
120 490 ▶sub for_dbh {
Subroutine for_dbh: called CC=2 SCAR=9.2
Pod documented
121 0 ▶ my $class = shift;
Subroutine for_dbh: not called CC=2 SCAR=9.2
Pod documented
122 0 my ($dbh) = @_;
123  
124 0 my $driver = $dbh->{Driver}->{Name};
125 0 ▶ my $name = $DRIVERS{$driver} or croak "Unsupported database driver 'DBD::$driver', supported drivers are: " . join(', ' => map { "DBD::$_" } sort keys %DRIVERS);
Branch: 2 branches
BranchTrueFalseTotal
my $name = $DRIVERS{$driver} or croak("Unsupported database driver 'DBD::${driver}', supported drivers are: " . join(", ", map({"DBD::$_";} sort(keys %DRIVERS)))) 488 2 490
my $name = $DRIVERS{$driver} or croak("Unsupported database driver 'DBD::${driver}', supported drivers are: " . join(", ", map({"DBD::$_";} sort(keys %DRIVERS)))) 0 0 0
126  
127 0 require "DBIx/QuickORM/Dialect/$name.pm";
128 0 my $dialect = "DBIx::QuickORM::Dialect::$name"->dialect_for_dbh($dbh);
129 0 my $self = $dialect->new(server_version => $dialect->_server_version($dbh), dbh => $dbh);
130 0 weaken($self->{+DBH});
131 0 return $self;
132 }
133  
134 =pod
135  
136 =over 4
137  
138 =item $dialect = DBIx::QuickORM::Dialect->for_name($name)
139  
140 =item $dialect = DBIx::QuickORM::Dialect->for_name($name, $version)
141  
142 A dialect object with no database, for writing SQL.
143  
144 my $newest = DBIx::QuickORM::Dialect->for_name('postgresql');
145 my $pg96 = DBIx::QuickORM::Dialect->for_name('PostgreSQL', '9.6');
146  
147 my $version = $pg96->server_version; # 90600
148  
149 # Identity columns need PostgreSQL 10, so only $newest writes one
150 my $identity = $newest->identity_sql('posts', {name => 'id'}, 0);
151  
152 C<$name> is one of
153 C<postgresql>, C<mysql>, C<mariadb>, C<sqlite>, or C<duckdb> (any case), and
154 C<$version> a version string such as C<'10.6'>, read by C<version_number>.
155 Without a version, the newest server is assumed, so no feature is refused
156 for age. Croaks for another name or an unreadable version.
157  
158 =item $number = $dialect->version_number($string)
159  
160 A version string as C<server_version> holds it.
161  
162 my $mariadb = DBIx::QuickORM::Dialect->for_name('mariadb');
163  
164 my $full = $mariadb->version_number('10.6.2'); # 10006002
165 my $short = $mariadb->version_number('8'); # 8000000
166 my $none = $mariadb->version_number('beta'); # undef
167  
168 C<major * 1_000_000 + minor * 1_000 + patch> by default, missing parts 0.
169 Undef when the string starts with no number. PostgreSQL numbers its versions
170 its own way (see L<DBIx::QuickORM::Dialect::PostgreSQL>).
171  
172 =back
173  
174 =cut
175  
176 274 my %NAMES = (postgresql => 'PostgreSQL', mysql => 'MySQL', mariadb => 'MariaDB', sqlite => 'SQLite', duckdb => 'DuckDB');
177  
178 274 ▶use constant NEWEST_VERSION => 999_999_999;
Subroutine BEGIN: called CC=1 SCAR=0.0
179  
180 76 ▶sub for_name {
Subroutine for_name: called CC=6 SCAR=25.0
Pod documented
181 0 ▶ my $class = shift;
Subroutine for_name: not called CC=6 SCAR=25.0
Pod documented
182 0 my ($key, $version) = @_;
183 0 ▶ my $name = $NAMES{lc($key // '')} or croak "Unknown dialect '" . ($key // 'undef') . "', one of: " . join(', ' => sort keys %NAMES);
Branch: 2 branches
BranchTrueFalseTotal
my $name = $NAMES{lc($key // "")} or croak(q[Unknown dialect '] . ($key // "undef") . q[', one of: ] . join(", ", sort(keys %NAMES))) 74 2 76
my $name = $NAMES{lc($key // "")} or croak(q[Unknown dialect '] . ($key // "undef") . q[', one of: ] . join(", ", sort(keys %NAMES))) 0 0 0
Condition25%2/8
$key // ""
l!l
760
$key // "undef"
l!l
20
$key // ""
l!l
00
$key // "undef"
l!l
00
MC/DC0%0/1
$key // ""
$key
MC/DC0%0/1
$key // "undef"
$key
MC/DC0%0/1
$key // ""
$key
MC/DC0%0/1
$key // "undef"
$key
Truth table50%1/2
A
A= $key
Aresult
11
00
Truth table50%1/2
A
A= $key
Aresult
11
00
Truth table0%0/2
A
A= $key
Aresult
11
00
Truth table0%0/2
A
A= $key
Aresult
11
00
184 0 require "DBIx/QuickORM/Dialect/$name.pm";
185 0 my $dialect = "DBIx::QuickORM::Dialect::$name";
186 0 ▶ return $dialect->new(server_version => NEWEST_VERSION) unless defined $version;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $version 54 20 74
unless defined $version 0 0 0
187 0 ▶ my $number = $dialect->version_number($version) // croak "Cannot read the version '$version'";
Condition50%2/4
$dialect->version_number($version) // croak("Cannot read the version '${version}'")
l!l
191
$dialect->version_number($version) // croak("Cannot read the version '${version}'")
l!l
00
MC/DC100%1/1
$dialect->version_number($version) // croak("Cannot read the version '${version}'")
$dialect->version_number($version)
MC/DC0%0/1
$dialect->version_number($version) // croak("Cannot read the version '${version}'")
$dialect->version_number($version)
Truth table100%2/2
A
A= $dialect->version_number($version)
Aresult
11
00
Truth table0%0/2
A
A= $dialect->version_number($version)
Aresult
11
00
188 0 return $dialect->new(server_version => $number);
189 }
190  
191 14 ▶sub version_number {
Subroutine version_number: called CC=5 SCAR=21.9
Pod documented
192 0 ▶ my $class = shift;
Subroutine version_number: not called CC=5 SCAR=21.9
Pod documented
193 0 my ($string) = @_;
194 0 ▶ my ($major, $minor, $patch) = ($string // '') =~ m/^\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?/ or return undef;
Branch: 2 branches
BranchTrueFalseTotal
() = ($string // "") =~ /^\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?/ or return undef 13 1 14
() = ($string // "") =~ /^\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?/ or return undef 0 0 0
Condition25%1/4
$string // ""
l!l
140
$string // ""
l!l
00
MC/DC0%0/1
$string // ""
$string
MC/DC0%0/1
$string // ""
$string
Truth table50%1/2
A
A= $string
Aresult
11
00
Truth table0%0/2
A
A= $string
Aresult
11
00
195 0 ▶ return $major * 1_000_000 + ($minor // 0) * 1_000 + ($patch // 0);
Condition50%4/8
$minor // 0
l!l
121
$patch // 0
l!l
76
$minor // 0
l!l
00
$patch // 0
l!l
00
MC/DC100%1/1
$minor // 0
$minor
MC/DC100%1/1
$patch // 0
$patch
MC/DC0%0/1
$minor // 0
$minor
MC/DC0%0/1
$patch // 0
$patch
Truth table100%2/2
A
A= $minor
Aresult
11
00
Truth table100%2/2
A
A= $patch
Aresult
11
00
Truth table0%0/2
A
A= $minor
Aresult
11
00
Truth table0%0/2
A
A= $patch
Aresult
11
00
196 }
197  
198 =pod
199  
200 =over 4
201  
202 =item $name = $dialect->name
203  
204 The dialect's short name, the last part of its class, such as C<PostgreSQL>,
205 for messages.
206  
207 =item $class = $dialect->dialect_for_dbh($dbh)
208  
209 The dialect to use for this handle: the dialect itself, unless a subclass
210 looks at the server.
211  
212 =item $char = $dialect->quote_char
213  
214 The character that quotes identifiers. C<"> by default.
215  
216 =item $bool = $dialect->supports_savepoints
217  
218 Whether the database has savepoints, so transactions can nest. True by
219 default.
220  
221 =item $bool = $dialect->supports_isolation
222  
223 Whether C<begin_sql> can set a transaction isolation level. False by default
224 (SQLite, DuckDB). Where it is true, a transaction states a level every time it
225 opens (see L<DBIx::QuickORM::Manual::Transactions/ISOLATION>).
226  
227 =item $bool = $dialect->supports_returning_insert
228  
229 =item $bool = $dialect->supports_returning_update
230  
231 =item $bool = $dialect->supports_returning_delete
232  
233 Whether C<INSERT>, C<UPDATE>, and C<DELETE> take a C<RETURNING> clause. True
234 by default.
235  
236 =item $bool = $dialect->having_uses_alias
237  
238 Whether a C<having> naming a computed column sends that name to the database.
239 False by default: the SQL builder writes the column's SQL in its place, which
240 works everywhere (PostgreSQL rejects a select alias in C<HAVING>, and SQLite
241 lets a table column of the same name win over it).
242  
243 =item $n = $dialect->bind_limit
244  
245 The most binds one statement may hold. 999 by default, the lowest limit of
246 the supported databases (SQLite before 3.32.0).
247  
248 =item ($parser, $formatter) = $dialect->datetime_format
249  
250 =item ($parser, $formatter, \%instants) = $dialect->datetime_format
251  
252 How the database's dates and timestamps are read and written: a parser and a
253 formatter, then an optional map of instant types.
254  
255 my ($parser, $formatter, $instants) = $dialect->datetime_format;
256 # $parser: 'DateTime::Format::Pg', the class that parses values read
257 # $formatter: 'DateTime::Format::Pg', the class that formats values sent
258 # $instants: undef: PostgreSQL returns only the first two
259  
260 require DateTime::Format::Pg;
261 my $when = $parser->parse_timestamp('2026-11-30 12:34:56');
262 my $sent = $formatter->format_timestamp($when); # '2026-11-30 12:34:56'
263  
264 A dialect overrides it to name its own (a sketch):
265  
266 package My::Dialect;
267 use parent 'DBIx::QuickORM::Dialect';
268  
269 # TIMESTAMP stores an instant, DATETIME does not
270 sub datetime_format { ('DateTime::Format::MySQL', 'DateTime::Format::MySQL', {timestamp => 1}) }
271  
272 C<$parser> and C<$formatter> are L<DateTime::Format> class names,
273 L<DateTime::Format::Pg> for both by default. C<$formatter> may be undef:
274 L<DBIx::QuickORM::Type::DateTime> then formats values itself (SQLite).
275  
276 The third value is returned only by a dialect with base types that have no
277 zone in their name but still store an instant (MySQL's
278 C<< {timestamp => 1} >>). None by default.
279  
280 =item $bool = $dialect->supports_temp_views
281  
282 Whether the database has temporary views. True by default.
283  
284 =item $bool = $dialect->temp_ddl_transactional
285  
286 Whether a rollback undoes creating or dropping a temporary table, as it does
287 other work. True by default. Where it is false (the MySQL family) the
288 Connection drops a rolled-back temporary table itself, and holds back a drop
289 until the outermost transaction commits.
290  
291 =item @keys = $dialect->db_type_keys
292  
293 The keys a per-database value (a field's C<db_type> or C<collate>, a
294 C<schema_sql> or C<view_sql> entry) is looked up by, in order.
295  
296 my @keys = $dialect->db_type_keys; # ('postgresql', 'any')
297  
298 my $mariadb = DBIx::QuickORM::Dialect->for_name('mariadb');
299 my @mariadb = $mariadb->db_type_keys; # ('mariadb', 'any_mysql', 'any')
300  
301 The lowercased C<name>, then C<any> by default. The MySQL family puts
302 C<any_mysql> between.
303  
304 =item $why = $dialect->unsupported
305  
306 Why QuickORM cannot use this server, or undef when it can. Connecting croaks
307 with it.
308  
309 my $why = $dialect->unsupported; # undef
310  
311 MariaDB needs 10.5 and SQLite 3.35, the first versions with C<RETURNING>.
312 Undef for every other database, and for a dialect with no server version.
313  
314 =back
315  
316 =cut
317  
318 302 ▶sub name { ((ref($_[0]) || $_[0]) =~ m/(\w+)$/)[0] }
Subroutine name: called CC=2 SCAR=7.2
Pod documented
Condition66%2/3
ref $_[0] || $_[0]
l!l&&r!l&&!r
29840
MC/DC0%0/2
ref $_[0] || $_[0]
ref $_[0] $_[0]
Truth table66%2/3
A || B
A= ref $_[0]B= $_[0]
ABresult
1X1
011
000
319 489 ▶sub dialect_for_dbh { $_[0] }
Subroutine dialect_for_dbh: called CC=1 SCAR=0.0
Pod documented
320 3 ▶sub unsupported { undef }
Subroutine unsupported: called CC=1 SCAR=0.0
Pod documented
321 6525 ▶sub quote_char { '"' }
Subroutine quote_char: called CC=1 SCAR=0.0
Pod documented
322 51 ▶sub supports_savepoints { 1 }
Subroutine supports_savepoints: called CC=1 SCAR=0.0
Pod documented
323 143 ▶sub supports_isolation { 0 }
Subroutine supports_isolation: called CC=1 SCAR=0.0
Pod documented
324 214 ▶sub supports_returning_insert { 1 }
Subroutine supports_returning_insert: called CC=1 SCAR=0.0
Pod documented
325 135 ▶sub supports_returning_update { 1 }
Subroutine supports_returning_update: called CC=1 SCAR=0.0
Pod documented
326 17 ▶sub supports_returning_delete { 1 }
Subroutine supports_returning_delete: called CC=1 SCAR=0.0
Pod documented
327 15 ▶sub having_uses_alias { 0 }
Subroutine having_uses_alias: called CC=1 SCAR=0.0
Pod documented
328 71 ▶sub bind_limit { 999 }
Subroutine bind_limit: called CC=1 SCAR=0.0
Pod documented
329 1 ▶sub datetime_format { ('DateTime::Format::Pg', 'DateTime::Format::Pg') }
Subroutine datetime_format: called CC=1 SCAR=0.0
Pod documented
330 28 ▶sub supports_temp_views { 1 }
Subroutine supports_temp_views: called CC=1 SCAR=0.0
Pod documented
331 24 ▶sub temp_ddl_transactional { 1 }
Subroutine temp_ddl_transactional: called CC=1 SCAR=0.0
Pod documented
332 105 ▶sub db_type_keys { (lc $_[0]->name, 'any') }
Subroutine db_type_keys: called CC=1 SCAR=0.0
Pod documented
333  
334 =pod
335  
336 =over 4
337  
338 =item @sql = $dialect->begin_sql
339  
340 =item @sql = $dialect->begin_sql($level)
341  
342 The statements that open a root transaction: C<BEGIN> by default.
343  
344 my @plain = $dialect->begin_sql; # ('BEGIN')
345 my @level = $dialect->begin_sql('SERIALIZABLE'); # ('BEGIN ISOLATION LEVEL SERIALIZABLE')
346  
347 # MySQL sets the level in a statement of its own
348 my $mysql = DBIx::QuickORM::Dialect->for_name('mysql');
349 my @steps = $mysql->begin_sql('SERIALIZABLE'); # ('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE', 'BEGIN')
350  
351 C<$level> is an upper-case isolation level, such as C<SERIALIZABLE>. The
352 Connection passes one for every root transaction where the dialect
353 C<supports_isolation>, and none for C<< isolation => 'server' >>. The base
354 croaks when one is given: the database has no level to set (SQLite, DuckDB).
355  
356 =back
357  
358 =cut
359  
360 148 ▶sub begin_sql {
Subroutine begin_sql: called CC=2 SCAR=6.9
Pod documented
361 148 my $self = shift;
362 148 my ($level) = @_;
363 148 ▶ croak "The " . $self->name . " dialect cannot set a transaction isolation level" if $level;
Branch: 1 branch
BranchTrueFalseTotal
if $level 5 143 148
364 143 return ('BEGIN');
365 }
366  
367 =pod
368  
369 =over 4
370  
371 =item $sql = $dialect->quote_identifier($name)
372  
373 C<$name> quoted with C<quote_char>, doubling any quote character inside it.
374  
375 my $users = $dialect->quote_identifier('users'); # "users"
376 my $odd = $dialect->quote_identifier('say "hi"'); # "say ""hi"""
377  
378 =back
379  
380 =cut
381  
382 6244 ▶sub quote_identifier {
Subroutine quote_identifier: called CC=1 SCAR=0.0
Pod documented
383 6244 my $self = shift;
384 6244 my ($name) = @_;
385  
386 6244 my $q = $self->quote_char;
387 6244 $name =~ s/\Q$q\E/$q$q/g;
388 6244 return "$q$name$q";
389 }
390  
391 =pod
392  
393 =over 4
394  
395 =item $ns = $dialect->namespace($dbh)
396  
397 The namespace the connection works in, or undef when it has none.
398 C<current_schema()> by default.
399  
400 my $ns = $dialect->namespace($dbh); # 'public' in a new PostgreSQL database
401  
402 =back
403  
404 =cut
405  
406 1 ▶sub namespace {
Subroutine namespace: called CC=1 SCAR=0.0
Pod documented
407 1 my $self = shift;
408 1 my ($dbh) = @_;
409 1 my ($ns) = $dbh->selectrow_array('SELECT current_schema()');
410 1 return $ns;
411 }
412  
413 =pod
414  
415 =over 4
416  
417 =item $dialect->release_inherited($dbh)
418  
419 Lets go of a handle a forked child inherited without closing the parent's
420 session.
421  
422 my $pid = fork // die "Could not fork: $!";
423 unless ($pid) {
424 $dialect->release_inherited($dbh); # leaves the parent's session alone
425 exit 0;
426 }
427 waitpid($pid, 0);
428  
429 my ($still) = $dbh->selectrow_array('SELECT 1'); # the parent's handle still works
430  
431 Sets C<InactiveDestroy> by default.
432  
433 =back
434  
435 =cut
436  
437 11 ▶sub release_inherited {
Subroutine release_inherited: called CC=1 SCAR=0.0
Pod documented
438 11 my $self = shift;
439 11 my ($dbh) = @_;
440 11 $dbh->{InactiveDestroy} = 1;
441 11 return;
442 }
443  
444 =pod
445  
446 =over 4
447  
448 =item $bool = $dialect->supports_second_connection($dbh)
449  
450 Whether another connection, from this process or a forked child, reaches the
451 same data as this handle. True by default.
452  
453 =item $bool = $dialect->supports_async
454  
455 Whether a query can run on the handle without waiting for it. False by
456 default.
457  
458 A dialect that says true also provides C<async_prepare_attrs> (the C<prepare>
459 attributes for such a statement, which is executed once),
460 C<async_ready($dbh, $sth)>, C<async_result($dbh, $sth)> (waits for the
461 result), and C<cancel_async($dbh, $sth)>:
462  
463 my $async = $dialect->supports_async; # true on PostgreSQL
464  
465 my $sth = $dbh->prepare('SELECT count(*) FROM users', $dialect->async_prepare_attrs);
466 $sth->execute; # returns at once
467  
468 my $done = $dialect->async_ready($dbh, $sth); # true once the result is in
469  
470 $dialect->async_result($dbh, $sth); # waits for it
471 my ($count) = $sth->fetchrow_array;
472  
473 my $slow = $dbh->prepare('SELECT pg_sleep(10)', $dialect->async_prepare_attrs);
474 $slow->execute;
475 $dialect->cancel_async($dbh, $slow); # gives up on it
476  
477 On PostgreSQL, cancelling a query inside a transaction aborts the transaction.
478  
479 =back
480  
481 =cut
482  
483 1 ▶sub supports_second_connection { 1 }
Subroutine supports_second_connection: called CC=1 SCAR=0.0
Pod documented
484  
485 =pod
486  
487 =over 4
488  
489 =item $key = $dialect->scan_cache_key($dbh, $namespace)
490  
491 Which database a scan of this handle describes, as a string, or undef when no
492 other connection could see the same tables. The Connection keys its scan cache
493 by it (see L<DBIx::QuickORM::Connection/"The scan cache">).
494  
495 my $key = $dialect->scan_cache_key($dbh, $dialect->namespace($dbh));
496  
497 By default it joins the driver, the DSN (C<< $dbh->{Name} >>, holding the host,
498 port or socket, and database), the user name, and the namespace. A dialect
499 adds whatever else changes what its scan sees (a sketch):
500  
501 package My::Dialect;
502 use parent 'DBIx::QuickORM::Dialect';
503  
504 # Sessions with different search paths see different tables
505 sub scan_cache_key {
506 my $self = shift;
507 my ($dbh, $namespace) = @_;
508 my ($path) = $dbh->selectrow_array('SHOW search_path');
509 return join "\0" => $self->SUPER::scan_cache_key($dbh, $namespace), $path;
510 }
511  
512 =back
513  
514 =cut
515  
516 4 ▶sub scan_cache_key {
Subroutine scan_cache_key: called CC=2 SCAR=6.9
Pod documented
517 4 my $self = shift;
518 4 my ($dbh, $namespace) = @_;
519 4 ▶ return join "\0" => map { $_ // '' } $dbh->{Driver}->{Name}, $dbh->{Name}, $dbh->{Username}, $namespace;
Condition100%2/2
$_ // ""
l!l
133
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
520 }
521 27 ▶sub supports_async { 0 }
Subroutine supports_async: called CC=1 SCAR=0.0
Pod documented
522  
523 =pod
524  
525 =over 4
526  
527 =item $dialect->text_from_db(@values)
528  
529 =item $dialect->text_to_db(@values)
530  
531 Convert text in place, as it is fetched from the database and before it is
532 sent, for drivers that do not exchange character strings themselves. Both do
533 nothing by default.
534  
535 A dialect for a driver that exchanges UTF-8 bytes converts them (a sketch,
536 as DuckDB's does):
537  
538 package My::Dialect;
539 use parent 'DBIx::QuickORM::Dialect';
540  
541 # The driver returns UTF-8 bytes, and sends a string's internal buffer as is
542  
543 sub text_from_db { shift; utf8::decode($_) for grep { defined } @_; return }
544 sub text_to_db { shift; utf8::upgrade($_) for grep { defined } @_; return }
545  
546 package main;
547  
548 my @row = ("caf\xC3\xA9", undef);
549 My::Dialect->new->text_from_db(@row); # $row[0] is now "caf\x{e9}"
550  
551 Callers pass only text, never values of binary fields.
552  
553 =back
554  
555 =cut
556  
557 5094 ▶sub text_from_db { }
Subroutine text_from_db: called CC=1 SCAR=0.0
Pod documented
558 1682 ▶sub text_to_db { }
Subroutine text_to_db: called CC=1 SCAR=0.0
Pod documented
559  
560 =pod
561  
562 =over 4
563  
564 =item $attrs = $dialect->binary_bind_attrs
565  
566 The C<bind_param> attributes for a binary value. C<< {TYPE => SQL_BLOB} >> by
567 default.
568  
569 my $sth = $dbh->prepare('SELECT octet_length(?)');
570 $sth->bind_param(1, "\x00\xFF", $dialect->binary_bind_attrs);
571 $sth->execute;
572 my ($length) = $sth->fetchrow_array; # 2
573  
574 =back
575  
576 =cut
577  
578 56 ▶sub binary_bind_attrs { {TYPE => DBI::SQL_BLOB()} }
Subroutine binary_bind_attrs: called CC=1 SCAR=0.0
Pod documented
579  
580 =pod
581  
582 =over 4
583  
584 =item $attrs = $dialect->bind_attrs(\%field)
585  
586 The C<bind_param> attributes for a value going to the field (a map field
587 record, or undef): C<binary_bind_attrs> for a field of C<binary> affinity,
588 otherwise undef.
589  
590 my $blob = $dialect->bind_attrs({affinity => 'binary'}); # binary_bind_attrs
591 my $text = $dialect->bind_attrs({affinity => 'string'}); # undef
592  
593 =back
594  
595 =cut
596  
597 1836 ▶sub bind_attrs {
Subroutine bind_attrs: called CC=4 SCAR=13.9
Pod documented
598 1836 my $self = shift;
599 1836 my ($field) = @_;
600 1836 ▶ return undef unless $field && ($field->{affinity} // '') eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $field and ($field->{"affinity"} // "") eq "binary" 1781 55 1836
Condition80%4/5
$field and ($field->{"affinity"} // "") eq "binary"
!ll&&!rl&&r
2177955
$field->{"affinity"} // ""
l!l
18340
MC/DC50%1/2
$field and ($field->{"affinity"} // "") eq "binary"
$field $field->{"affinity"}
Truth table66%2/3
A and B
A= $fieldB= $field->{"affinity"}
ABresult
0X0
100
111
601 55 return $self->binary_bind_attrs;
602 }
603  
604 =pod
605  
606 =over 4
607  
608 =item $id = $dialect->last_insert_id($dbh, $table, $field)
609  
610 The value the database generated for the field by the last insert.
611  
612 $dbh->do(q{INSERT INTO users (name) VALUES ('Bob')});
613 my $id = $dialect->last_insert_id($dbh, 'users', 'id');
614  
615 =back
616  
617 =cut
618  
619 2 ▶sub last_insert_id {
Subroutine last_insert_id: called CC=1 SCAR=0.0
Pod documented
620 2 my $self = shift;
621 2 my ($dbh, $table, $field) = @_;
622 2 return $dbh->last_insert_id(undef, undef, $table, $field);
623 }
624  
625 =pod
626  
627 =over 4
628  
629 =item \%kinds = $dialect->native_error_kinds
630  
631 Native error codes mapped to error kinds. Empty by default.
632  
633 A dialect whose database reports a generic SQLSTATE maps its own codes (a
634 sketch):
635  
636 package My::Dialect;
637 use parent 'DBIx::QuickORM::Dialect';
638  
639 my %KIND = (
640 1062 => 'unique_violation',
641 1213 => 'deadlock',
642 );
643  
644 sub native_error_kinds { \%KIND }
645  
646 package main;
647  
648 my $kind = My::Dialect->new->error_kind(1062, 'HY000'); # 'unique_violation'
649  
650 =back
651  
652 =cut
653  
654 274 my %STATE_KIND = (
655 '40001' => 'serialization_failure',
656 '40P01' => 'deadlock',
657 '55P03' => 'lock_timeout',
658 '23505' => 'unique_violation',
659 '23503' => 'foreign_key_violation',
660 '23502' => 'not_null_violation',
661 '23514' => 'check_violation',
662 );
663  
664 11 ▶sub native_error_kinds { {} }
Subroutine native_error_kinds: called CC=1 SCAR=0.0
Pod documented
665  
666 =pod
667  
668 =over 4
669  
670 =item $kind = $dialect->error_kind($native, $state, $errstr)
671  
672 The kind of a database error (see L<DBIx::QuickORM::Exception::DB>), or undef.
673  
674 eval { $dbh->do('INSERT INTO users (name) VALUES (NULL)') };
675 my $kind = $dialect->error_kind($dbh->err, $dbh->state, $dbh->errstr); # 'not_null_violation'
676  
677 The native code is looked up in C<native_error_kinds> first, then the
678 SQLSTATE. C<$errstr> is unused here. The SQLSTATEs known:
679  
680 =for highlighter language=text
681  
682 40001 serialization_failure
683 40P01 deadlock
684 55P03 lock_timeout
685 23505 unique_violation
686 23503 foreign_key_violation
687 23502 not_null_violation
688 23514 check_violation
689  
690 =back
691  
692 =cut
693  
694 83 ▶sub error_kind {
Subroutine error_kind: called CC=4 SCAR=13.9
Pod documented
695 83 my $self = shift;
696 83 my ($native, $state) = @_;
697  
698 83 ▶ my $kind = defined($native) ? $self->native_error_kinds->{$native} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $native ? : 82 1 83
699 83 ▶ $kind //= $STATE_KIND{$state} if defined $state;
Branch: 1 branch
BranchTrueFalseTotal
if defined $state 82 1 83
Condition100%3/3
$kind //= $STATE_KIND{$state}
l!l&&r!l&&!r
521020
MC/DC100%2/2
$kind //= $STATE_KIND{$state}
$kind $STATE_KIND{$state}
Truth table100%3/3
A //= B
A= $kindB= $STATE_KIND{$state}
ABresult
1X1
011
000
700 83 return $kind;
701 }
702  
703 # {{{ Temporary tables and views
704  
705 =pod
706  
707 =over 4
708  
709 =item @sql = $dialect->create_table_sql($name, \%spec, temp => $bool, foreign_keys => \@fks, pretty => $bool)
710  
711 The statements that create a table, temporary with C<< temp => 1 >>.
712  
713 =for highlighter language=perl
714  
715 my @sql = $dialect->create_table_sql(
716 drafts => {
717 columns => [
718 {
719 name => 'id',
720 db_type => 'serial',
721 },
722 {
723 name => 'title',
724 db_type => 'text',
725 not_null => 1,
726 },
727 {
728 name => 'views',
729 db_type => 'integer',
730 not_null => 1,
731 default => 0,
732 },
733 {
734 name => 'note',
735 sql => \'text',
736 },
737 ],
738 pk => ['id'],
739 uniques => [{columns => ['title']}],
740 indexes => [{columns => ['views']}],
741 checks => [
742 {
743 name => 'counted',
744 sql => \'views >= 0',
745 },
746 ],
747 },
748 temp => 1,
749 pretty => 1,
750 );
751  
752 $dbh->do($_) for @sql;
753  
754 C<@sql> holds these two statements, each without a closing semicolon:
755  
756 =for highlighter language=sql
757  
758 CREATE TEMPORARY TABLE "drafts" (
759 "id" serial,
760  
761 "title" text NOT NULL,
762 "views" integer DEFAULT '0' NOT NULL,
763 "note" text,
764  
765 PRIMARY KEY ("id"),
766 UNIQUE ("title"),
767 CONSTRAINT "counted" CHECK (views >= 0)
768 )
769  
770 CREATE INDEX "drafts_idx_1" ON "drafts" ("views")
771  
772 C<%spec> is a L<DBIx::QuickORM::SchemaBuilder::Table> spec with every
773 column's C<db_type> and C<collate> resolved to a string. C<pk> is undef for
774 no primary key. Each index takes C<columns>, and may take C<name>, C<unique>,
775 C<using> (see C<index_using_sql>), and C<dialect> (per-database options or
776 SQL). A column's C<indexed> adds an index on it. Each unique key takes
777 C<columns> and each check C<sql>, and both may take a C<name>. See
778 L<DBIx::QuickORM::SchemaBuilder::Table/add_index> for the index options.
779  
780 With C<< pretty => 1 >>, each column and table constraint is on a line of its
781 own, and the columns line up within the table: name, type, the value
782 (default, identity, or generated), C<NOT NULL>, then the rest. A part no
783 column has takes no room. The leading key or identity columns line up only
784 by name and type, with a blank line after them, and a blank line comes
785 before the table constraints. A column given as SQL is its name, then the
786 SQL as given, which takes no part in the alignment past the name.
787  
788 A column's C<default> is a plain value (quoted by C<quote_literal>), a
789 reference to literal SQL, or an C<sql()> marker (its binds written in as
790 literals). A column's C<generated> and C<check> are literal SQL in the same
791 forms. Its C<not_null> makes it C<NOT NULL>.
792  
793 C<@fks> are the foreign keys to declare in the table, as C<foreign_key_sql>
794 takes them. A temporary table takes none: its references are links in the
795 map only, so it croaks when given some. Keys between tables that reference
796 each other are added afterwards with C<add_foreign_key_sql>.
797  
798 Indexes follow the C<CREATE TABLE> as C<CREATE INDEX> statements, named
799 C<${name}_idx_N> unless given a name.
800  
801 =back
802  
803 =cut
804  
805 136 ▶sub create_table_sql {
Subroutine create_table_sql: called CC=12 SCAR=24.8
Pod documented
806 136 my $self = shift;
807 136 my ($name, $spec, %opts) = @_;
808 136 ▶ my $temp = $opts{temp} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'temp'} ? : 53 83 136
809 136 ▶ my $fks = $opts{foreign_keys} // [];
Condition100%2/2
$opts{"foreign_keys"} // []
l!l
7462
MC/DC100%1/1
$opts{"foreign_keys"} // []
$opts{"foreign_keys"}
Truth table100%2/2
A
A= $opts{"foreign_keys"}
Aresult
11
00
810 136 ▶ croak "A temporary table writes no foreign keys; its references are links in the map only" if $temp && @$fks;
Branch: 1 branch
BranchTrueFalseTotal
if $temp and @$fks 1 135 136
Condition100%3/3
$temp and @$fks
!ll&&!rl&&r
83521
MC/DC100%2/2
$temp and @$fks
$temp @$fks
Truth table100%3/3
A and B
A= $tempB= @$fks
ABresult
0X0
100
111
811  
812 135 my $q = $self->quote_identifier($name);
813 135 my %inline = map { $_ => 1 } $self->_inline_pk($spec);
814 135 my @constraints;
815 135 ▶ push @constraints => 'PRIMARY KEY (' . join(', ' => map { $self->quote_identifier($_) } @{$spec->{pk}}) . ')' if $spec->{pk} && !%inline;
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"pk"} and not %inline 104 31 135
Condition100%3/3
$spec->{"pk"} and not %inline
!ll&&!rl&&r
265104
MC/DC100%2/2
$spec->{"pk"} and not %inline
$spec->{"pk"} not %inline
Truth table100%3/3
A and not(B)
A= $spec->{"pk"}B= not %inline
ABresult
0X0
100
111
816 push @constraints => map {
817 9 $self->_constraint_sql($_->{name}, 'UNIQUE (' . join(', ' => map { $self->quote_identifier($_) } @{$_->{columns}}) . ')')
818 135 ▶ } @{$spec->{uniques} // []};
Condition100%2/2
$spec->{"uniques"} // []
l!l
9045
MC/DC100%1/1
$spec->{"uniques"} // []
$spec->{"uniques"}
Truth table100%2/2
A
A= $spec->{"uniques"}
Aresult
11
00
819 135 ▶ push @constraints => map { $self->_constraint_sql($_->{name}, 'CHECK (' . $self->_literal_sql($_->{sql}) . ')') } @{$spec->{checks} // []};
Condition100%2/2
$spec->{"checks"} // []
l!l
11322
MC/DC100%1/1
$spec->{"checks"} // []
$spec->{"checks"}
Truth table100%2/2
A
A= $spec->{"checks"}
Aresult
11
00
820 135 push @constraints => map { $self->foreign_key_sql($_) } @$fks;
821  
822 133 my @indexes = $self->_index_sql($name, [$self->_dialect_indexes($name, $spec, $temp)]);
823 128 ▶ push @constraints => @{shift @indexes} if ref($indexes[0]);
Branch: 1 branch
BranchTrueFalseTotal
if ref $indexes[0] 17 111 128
824  
825 128 ▶ my $create = $temp ? 'CREATE TEMPORARY TABLE' : 'CREATE TABLE';
Branch: 1 branch
BranchTrueFalseTotal
$temp ? : 47 81 128
826 my $body =
827 $opts{pretty}
828 ? $self->_pretty_table_body($name, $spec, \%inline, \@constraints)
829 128 ▶ : "(" . join(', ' => (map { $self->_column_sql($name, $_, \%inline) } @{$spec->{columns}}), @constraints) . ")";
Branch: 1 branch
BranchTrueFalseTotal
$opts{'pretty'} ? : 14 114 128
830 126 return ($self->_sequence_sql($name, $spec, $temp), "$create $q $body", @indexes);
831 }
832  
833 =pod
834  
835 =over 4
836  
837 =item $sql = $dialect->foreign_key_sql(\%fk)
838  
839 =item $sql = $dialect->add_foreign_key_sql($table, \%fk)
840  
841 A C<FOREIGN KEY> constraint, and the C<ALTER TABLE> that adds one to a table
842 already created (for keys between tables that reference each other).
843  
844 =for highlighter language=perl
845  
846 my $fk = {
847 columns => ['user_id'],
848 table => 'users',
849 their_columns => ['id'],
850 on_delete => 'cascade',
851 };
852  
853 my $inline = $dialect->foreign_key_sql($fk);
854 # FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE
855  
856 my $later = $dialect->add_foreign_key_sql(posts => {%$fk, name => 'post_author'});
857 # ALTER TABLE "posts" ADD CONSTRAINT "post_author" FOREIGN KEY ("user_id") ...
858  
859 C<%fk> is C<< {columns => [...], table => $other, their_columns => [...],
860 name => $name, on_delete => $action, on_update => $action} >>, the name and
861 actions optional. An action is C<cascade>, C<set null>, C<set default>, C<restrict>,
862 or C<no action>, in any case.
863  
864 =item $sql = $dialect->fk_action_sql($action)
865  
866 An action as SQL, upper case. Croaks for any other.
867  
868 =item $db_type = $dialect->column_type(\%column)
869  
870 A builder column's type on this database: its C<db_type> through
871 C<pick_value>, else its loaded C<type>'s C<db_type_for>. Croaks when neither
872 gives one.
873  
874 my $body = $dialect->column_type({
875 name => 'body',
876 db_type => {
877 postgresql => 'jsonb',
878 any => 'text',
879 },
880 }); # 'jsonb'
881  
882 require DBIx::QuickORM::Type::UUID;
883 my $token = $dialect->column_type({
884 name => 'token',
885 type => 'DBIx::QuickORM::Type::UUID',
886 }); # 'uuid'
887  
888  
889 =item $value = $dialect->pick_value($value)
890  
891 =item $value = $dialect->pick_value({postgresql => $v, any_mysql => $v, any => $v, ...})
892  
893 A value as given, or from a per-database hash the first defined entry
894 C<db_type_keys> names, or undef when it has none. Column types and
895 collations are chosen this way.
896  
897 my $plain = $dialect->pick_value('text'); # 'text'
898  
899 my $json = $dialect->pick_value({
900 postgresql => 'jsonb',
901 any_mysql => 'json',
902 any => 'text',
903 }); # 'jsonb' on PostgreSQL, 'json' on MySQL and MariaDB, 'text' elsewhere
904  
905  
906 =item ($found, $value) = $dialect->pick_entry(\%by_dialect)
907  
908 The first entry C<db_type_keys> names that exists, even undef, and a true
909 C<$found>, or an empty list when none does. Per-database SQL is chosen this
910 way, where undef means "not on this database".
911  
912 my %by_dialect = (
913 postgresql => undef,
914 any => 'CREATE INDEX posts_views ON posts (views)',
915 );
916  
917 my ($found, $sql) = $dialect->pick_entry(\%by_dialect); # (1, undef): skip it on PostgreSQL
918 my @none = $dialect->pick_entry({sqlite => 'VACUUM'}); # (): no entry for PostgreSQL
919  
920  
921 =item @keys = DBIx::QuickORM::Dialect->dialect_keys
922  
923 The keys a per-database value may use: C<postgresql>, C<mysql>, C<mariadb>,
924 C<sqlite>, C<duckdb>, C<any_mysql> (MySQL and MariaDB), and C<any> (every
925 database).
926  
927 =item (\%sql, \%options) = DBIx::QuickORM::Dialect->dialect_pairs($what, \@args, options => \@names, code => $bool)
928  
929 C<@args> as C<< dialect => $sql >> pairs mixed with the named options,
930 checked.
931  
932 my ($sql, $options) = DBIx::QuickORM::Dialect->dialect_pairs(
933 'schema_sql()',
934 [
935 postgresql => 'CREATE EXTENSION citext',
936 any => undef,
937 after => 1,
938 ],
939 options => ['after'],
940 );
941  
942 my $pg = $sql->{postgresql}; # 'CREATE EXTENSION citext'
943 my $after = $options->{after}; # 1
944  
945 Each dialect key may come once, and each value must be a string, a
946 reference to one, undef, or with C<code> a code reference. Anything else
947 croaks. C<$what> names the caller in errors.
948  
949 =item $sql = $dialect->setting_sql($name, $value)
950  
951 A session setting: C<SET $name = $value>, a number as is and anything else
952 quoted.
953  
954 my $timeout = $dialect->setting_sql(statement_timeout => 5000); # SET statement_timeout = 5000
955 my $path = $dialect->setting_sql(search_path => 'app'); # SET search_path = 'app'
956  
957  
958 =item @sql = $dialect->extension_sql($name)
959  
960 The statements that add an extension. Croaks by default: only PostgreSQL and
961 DuckDB have extensions.
962  
963 =item @sql = $dialect->create_enum_sql($name, \@values)
964  
965 The statements that create an enum type: C<CREATE TYPE ... AS ENUM> by
966 default, none where enums are written into the column.
967  
968 my @sql = $dialect->create_enum_sql(mood => ['happy', 'sad']);
969 # CREATE TYPE "mood" AS ENUM ('happy', 'sad')
970  
971  
972 =item ($db_type, $check) = $dialect->enum_column($column, $enum, \@values, temp => $bool)
973  
974 A column of the enum's type: its column type, and the check expression when
975 the column is constrained text (temporary tables, SQLite), otherwise undef.
976  
977 # the column 'status' of the enum type 'post_status'
978 my ($type, $check) = $dialect->enum_column('status', 'post_status', ['draft', 'live']);
979 # '"post_status"' and undef
980  
981 my ($temp_type, $temp_check) = $dialect->enum_column('status', 'post_status', ['draft', 'live'], temp => 1);
982 # 'text' and q{"status" IN ('draft', 'live')}
983  
984 By default the named type, or for a temporary table C<text> with the check,
985 since a type created for it would outlive the table.
986  
987 =item $field = $dialect->rowid_alias(\%spec)
988  
989 The field of a built table spec that the database fills as its row id, or
990 undef: SQLite's single C<integer> primary key. Undef by default.
991  
992 =item $sql = $dialect->collate_sql($collation)
993  
994 C<COLLATE> and the name. PostgreSQL quotes it as an identifier.
995  
996 =item $sql = $dialect->quote_literal($value)
997  
998 C<$value> as an SQL string literal, or C<NULL> for undef, with no database
999 handle.
1000  
1001 my $text = $dialect->quote_literal("it's"); # 'it''s'
1002 my $null = $dialect->quote_literal(undef); # NULL
1003  
1004 Single quotes are doubled by default. The MySQL family escapes with
1005 backslashes instead, as its default mode reads them (see
1006 L<DBIx::QuickORM::Dialect::MySQL>).
1007  
1008 =back
1009  
1010 =cut
1011  
1012 274 my %FK_ACTION = map { $_ => 1 } ('cascade', 'set null', 'set default', 'restrict', 'no action');
1013  
1014 26 ▶sub foreign_key_sql {
Subroutine foreign_key_sql: called CC=3 SCAR=11.0
Pod documented
1015 26 my $self = shift;
1016 26 my ($fk) = @_;
1017 52 ▶ my $q = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1018 52 join ', ' => map { $self->quote_identifier($_) } @_;
1019 26 };
1020 26 my $sql = "FOREIGN KEY (" . $q->(@{$fk->{columns}}) . ") REFERENCES " . $self->quote_identifier($fk->{table}) . " (" . $q->(@{$fk->{their_columns}}) . ")";
1021 26 ▶ $sql .= " ON DELETE " . $self->fk_action_sql($fk->{on_delete}) if defined $fk->{on_delete};
Branch: 1 branch
BranchTrueFalseTotal
if defined $fk->{"on_delete"} 7 19 26
1022 24 ▶ $sql .= " ON UPDATE " . $self->fk_action_sql($fk->{on_update}) if defined $fk->{on_update};
Branch: 1 branch
BranchTrueFalseTotal
if defined $fk->{"on_update"} 1 23 24
1023 24 return $self->_constraint_sql($fk->{name}, $sql);
1024 }
1025  
1026 4 ▶sub add_foreign_key_sql {
Subroutine add_foreign_key_sql: called CC=1 SCAR=0.0
Pod documented
1027 4 my $self = shift;
1028 4 my ($table, $fk) = @_;
1029 4 return "ALTER TABLE " . $self->quote_identifier($table) . " ADD " . $self->foreign_key_sql($fk);
1030 }
1031  
1032 7 ▶sub fk_action_sql {
Subroutine fk_action_sql: called CC=3 SCAR=11.0
Pod documented
1033 7 my $self = shift;
1034 7 my ($action) = @_;
1035 7 ▶ my $want = lc($action // '');
Condition50%1/2
$action // ""
l!l
70
MC/DC0%0/1
$action // ""
$action
Truth table50%1/2
A
A= $action
Aresult
11
00
1036 7 ▶ croak "'$want' is not a foreign key action, use one of: " . join(', ' => map { "'$_'" } sort keys %FK_ACTION) unless $FK_ACTION{$want};
Branch: 1 branch
BranchTrueFalseTotal
unless $FK_ACTION{$want} 1 6 7
1037 6 return uc $want;
1038 }
1039  
1040 4 ▶sub collate_sql { "COLLATE $_[1]" }
Subroutine collate_sql: called CC=1 SCAR=0.0
Pod documented
1041  
1042 3 ▶sub setting_sql {
Subroutine setting_sql: called CC=1 SCAR=0.0
Pod documented
1043 3 my $self = shift;
1044 3 my ($name, $value) = @_;
1045 3 return "SET $name = " . $self->_setting_value($value);
1046 }
1047  
1048 7 ▶sub _setting_value { defined($_[1]) && $_[1] =~ m/^-?\d+(?:\.\d+)?\z/ ? $_[1] : $_[0]->quote_literal($_[1]) }
Subroutine _setting_value: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
defined $_[1] && $_[1] =~ /^-?\d+(?:\.\d+)?\z/ ? : 5 2 7
Condition66%2/3
defined $_[1] and $_[1] =~ /^-?\d+(?:\.\d+)?\z/
!ll&&!rl&&r
025
MC/DC50%1/2
defined $_[1] and $_[1] =~ /^-?\d+(?:\.\d+)?\z/
defined $_[1] $_[1] =~ /^-?\d+(?:\.\d+)?\z/
Truth table66%2/3
A and B
A= defined $_[1]B= $_[1] =~ /^-?\d+(?:\.\d+)?\z/
ABresult
0X0
100
111
1049  
1050 3 ▶sub extension_sql { croak "The " . $_[0]->name . " dialect has no extensions" }
Subroutine extension_sql: called CC=1 SCAR=0.0
Pod documented
1051  
1052 20 ▶sub create_enum_sql {
Subroutine create_enum_sql: called CC=1 SCAR=0.0
Pod documented
1053 20 my $self = shift;
1054 20 my ($name, $values) = @_;
1055 20 return "CREATE TYPE " . $self->quote_identifier($name) . " AS ENUM (" . join(', ' => map { $self->quote_literal($_) } @$values) . ")";
1056 }
1057  
1058 29 ▶sub enum_column {
Subroutine enum_column: called CC=2 SCAR=6.9
Pod documented
1059 29 my $self = shift;
1060 29 my ($column, $enum, $values, %opts) = @_;
1061 29 ▶ return ('text', $self->_enum_check($column, $values)) if $opts{temp};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"temp"} 3 26 29
1062 26 return ($self->quote_identifier($enum), undef);
1063 }
1064  
1065 32 ▶sub _enum_check {
Subroutine _enum_check: called CC=1 SCAR=0.0
1066 32 my $self = shift;
1067 32 my ($column, $values) = @_;
1068 32 return $self->quote_identifier($column) . ' IN (' . join(', ' => map { $self->quote_literal($_) } @$values) . ')';
1069 }
1070 7 ▶sub rowid_alias { undef }
Subroutine rowid_alias: called CC=1 SCAR=0.0
Pod documented
1071  
1072 347 ▶sub column_type {
Subroutine column_type: called CC=6 SCAR=17.9
Pod documented
1073 347 my $self = shift;
1074 347 my ($field) = @_;
1075 347 ▶ my $given = defined($field->{db_type}) ? $self->pick_value($field->{db_type}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $field->{'db_type'} ? : 333 14 347
1076 347 ▶ return $given if defined $given;
Branch: 1 branch
BranchTrueFalseTotal
if defined $given 330 17 347
1077 17 my $type = $field->{type};
1078 17 ▶ my $db_type = $type ? $type->db_type_for($self) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$type ? : 14 3 17
1079 17 ▶ return $db_type if defined $db_type;
Branch: 1 branch
BranchTrueFalseTotal
if defined $db_type 13 4 17
1080 4 ▶ croak "The column '$field->{name}' has no type for " . $self->name . ": give it a 'db_type'" . ($type ? " ($type names none)" : '');
Branch: 1 branch
BranchTrueFalseTotal
$type ? : 1 3 4
1081 }
1082  
1083 345 ▶sub pick_value {
Subroutine pick_value: called CC=4 SCAR=13.9
Pod documented
1084 345 my $self = shift;
1085 345 my ($value) = @_;
1086 345 ▶ return $value unless ref($value) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 318 27 345
1087 27 ▶ defined($value->{$_}) and return $value->{$_} for $self->db_type_keys;
Branch: 1 branch
BranchTrueFalseTotal
defined $value->{$_} and return $value->{$_} 21 22 43
1088 6 return undef;
1089 }
1090  
1091 31 ▶sub pick_entry {
Subroutine pick_entry: called CC=3 SCAR=11.0
Pod documented
1092 31 my $self = shift;
1093 31 my ($hash) = @_;
1094 31 ▶ exists($hash->{$_}) and return (1, $hash->{$_}) for $self->db_type_keys;
Branch: 1 branch
BranchTrueFalseTotal
exists $hash->{$_} and return 1, $hash->{$_} 26 26 52
1095 5 return;
1096 }
1097  
1098 274 my @DIALECT_KEYS = qw/postgresql mysql mariadb sqlite duckdb any_mysql any/;
1099 274 my %DIALECT_KEY = map { $_ => 1 } @DIALECT_KEYS;
1100  
1101 1 ▶sub dialect_keys { @DIALECT_KEYS }
Subroutine dialect_keys: called CC=1 SCAR=0.0
Pod documented
1102  
1103 69 ▶sub dialect_pairs {
Subroutine dialect_pairs: called CC=17 SCAR=28.3
Pod documented
1104 69 my $class = shift;
1105 69 my ($what, $args, %opts) = @_;
1106 69 my ($options, $code) = @opts{qw/options code/};
1107 69 ▶ my %ok = map { $_ => 1 } @{$options // []};
Condition100%2/2
$options // []
l!l
645
MC/DC100%1/1
$options // []
$options
Truth table100%2/2
A
A= $options
Aresult
11
00
1108  
1109 69 ▶ croak "$what takes dialect => \$sql pairs" . (@$args ? '' : ', and got none') unless @$args && !(@$args % 2);
Branch: 2 branches
BranchTrueFalseTotal
unless @$args and not @$args % 2 4 65 69
@$args ? : 3 1 4
Condition100%3/3
@$args and not @$args % 2
!ll&&!rl&&r
1365
MC/DC100%2/2
@$args and not @$args % 2
@$args not @$args % 2
Truth table100%3/3
A and not(B)
A= @$argsB= not @$args % 2
ABresult
0X0
100
111
1110 65 my (%sql, %given);
1111 65 my @list = @$args;
1112 65 ▶ while (my ($key, $value) = splice(@list, 0, 2)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@list, 0, 2)) 103 55 158
1113 103 ▶ croak "$what got an undefined key" unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 103 103
1114 103 ▶ if ($ok{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok{$key}) 26 77 103
1115 26 $given{$key} = $value;
1116 26 next;
1117 }
1118 77 ▶ croak "$what got '$key', which is not a dialect (" . join(', ' => @DIALECT_KEYS) . ")" . (%ok ? " or an option (" . join(', ' => sort keys %ok) . ")" : '') unless $DIALECT_KEY{$key};
Branch: 2 branches
BranchTrueFalseTotal
unless $DIALECT_KEY{$key} 7 70 77
%ok ? : 6 1 7
1119 70 ▶ croak "$what gives '$key' twice" if exists $sql{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $sql{$key} 1 69 70
1120 69 my $type = ref($value);
1121 69 ▶ croak "$what: the '$key' entry must be SQL (a string or a reference to one)" . ($code ? ", a code reference," : '') . " or undef"
Branch: 2 branches
BranchTrueFalseTotal
unless not $type or $type eq "SCALAR" or $code and $type eq "CODE" 2 67 69
$code ? : 1 1 2
Condition100%9/9
not $type or $type eq "SCALAR" or $code and $type eq "CODE"
l!l&&r!l&&!r
6432
not $type or $type eq "SCALAR"
l!l&&r!l&&!r
5685
$code and $type eq "CODE"
!ll&&!rl&&r
113
MC/DC100%4/4
not $type or $type eq "SCALAR" or $code and $type eq "CODE"
not $type $type eq "SCALAR" $code $type eq "CODE"
Truth table100%5/5
not(A) or B or C and D
A= not $typeB= $type eq "SCALAR"C= $codeD= $type eq "CODE"
ABCDresult
1XXX1
01XX1
00111
000X0
00100
1122 unless !$type || $type eq 'SCALAR' || ($code && $type eq 'CODE');
1123 67 $sql{$key} = $value;
1124 }
1125 55 ▶ croak "$what gives no dialect, only options" unless %sql;
Branch: 1 branch
BranchTrueFalseTotal
unless %sql 1 54 55
1126 54 return (\%sql, \%given);
1127 }
1128 144 ▶sub quote_literal { defined($_[1]) ? "'" . ($_[1] =~ s/'/''/gr) . "'" : 'NULL' }
Subroutine quote_literal: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
defined $_[1] ? : 143 1 144
1129  
1130 =pod
1131  
1132 =over 4
1133  
1134 =item $sql = $dialect->create_view_sql($name, $select_sql)
1135  
1136 =item $sql = $dialect->create_view_sql($name, $select_sql, temp => 1)
1137  
1138 C<CREATE VIEW>, or C<CREATE TEMPORARY VIEW> with C<< temp => 1 >>, which
1139 croaks where the database has no temporary views.
1140  
1141 my $view = $dialect->create_view_sql(popular => 'SELECT * FROM posts WHERE views > 10');
1142 # CREATE VIEW "popular" AS SELECT * FROM posts WHERE views > 10
1143  
1144 my $temp = $dialect->create_view_sql(
1145 recent => 'SELECT * FROM posts ORDER BY id DESC LIMIT 10',
1146 temp => 1,
1147 );
1148 $dbh->do($temp);
1149  
1150  
1151 =item $sql = $dialect->create_table_as_sql($name, $select_sql, temp => 1)
1152  
1153 =item $sql = $dialect->insert_select_sql($name, $select_sql, \@columns)
1154  
1155 C<CREATE TEMPORARY TABLE ... AS> the query (croaking without
1156 C<< temp => 1 >>), and C<INSERT INTO> the table from it, into C<@columns>
1157 when given. The query keeps its placeholders: both take binds.
1158  
1159 my $create = $dialect->create_table_as_sql(
1160 busy => 'SELECT id, title FROM posts WHERE views > ?',
1161 temp => 1,
1162 );
1163 $dbh->do($create, undef, 100);
1164  
1165 my $add = $dialect->insert_select_sql('busy', 'SELECT id, title FROM posts WHERE user_id = ?', ['id', 'title']);
1166 $dbh->do($add, undef, 1);
1167  
1168  
1169 =item @sql = $dialect->drop_sql($name, $kind, \%spec, temp => 1)
1170  
1171 The statements that drop a temporary table (C<$kind> C<table>, with its
1172 builder's spec when it had one, or undef) or view (C<view>): one C<DROP> by
1173 default. Croaks without C<< temp => 1 >>.
1174  
1175 my @table = $dialect->drop_sql('busy', 'table', undef, temp => 1); # ('DROP TABLE "busy"')
1176 my @view = $dialect->drop_sql('recent', 'view', undef, temp => 1); # ('DROP VIEW "recent"')
1177  
1178 The name is not qualified: run them on the handle that created the temporary
1179 objects, right after, so no permanent table of the same name is dropped.
1180  
1181  
1182 =back
1183  
1184 =cut
1185  
1186 9 ▶sub create_table_as_sql {
Subroutine create_table_as_sql: called CC=1 SCAR=0.0
Pod documented
1187 9 my $self = shift;
1188 9 my ($name, $select, %opts) = @_;
1189 9 $self->_only_temp(create_table_as_sql => %opts);
1190 8 return "CREATE TEMPORARY TABLE " . $self->quote_identifier($name) . " AS $select";
1191 }
1192  
1193 7 ▶sub insert_select_sql {
Subroutine insert_select_sql: called CC=2 SCAR=6.9
Pod documented
1194 7 my $self = shift;
1195 7 my ($name, $select, $columns) = @_;
1196 7 ▶ my $list = $columns ? ' (' . join(', ' => map { $self->quote_identifier($_) } @$columns) . ')' : '';
Branch: 1 branch
BranchTrueFalseTotal
$columns ? : 5 2 7
1197 7 return "INSERT INTO " . $self->quote_identifier($name) . "$list $select";
1198 }
1199  
1200 35 ▶sub create_view_sql {
Subroutine create_view_sql: called CC=3 SCAR=11.0
Pod documented
1201 35 my $self = shift;
1202 35 my ($name, $select, %opts) = @_;
1203 35 ▶ return "CREATE VIEW " . $self->quote_identifier($name) . " AS $select" unless $opts{temp};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"temp"} 21 14 35
1204 14 ▶ croak "The " . $self->name . " dialect has no temporary views" unless $self->supports_temp_views;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->supports_temp_views 1 13 14
1205 13 return "CREATE TEMPORARY VIEW " . $self->quote_identifier($name) . " AS $select";
1206 }
1207  
1208 59 ▶sub drop_sql {
Subroutine drop_sql: called CC=1 SCAR=0.0
Pod documented
1209 59 my $self = shift;
1210 59 my ($name, $kind, $spec, %opts) = @_;
1211 59 $self->_only_temp(drop_sql => %opts);
1212 59 return "DROP " . uc($kind) . " " . $self->quote_identifier($name);
1213 }
1214  
1215 =pod
1216  
1217 =over 4
1218  
1219 =item $sql = $dialect->quote_binary($dbh, $bytes)
1220  
1221 C<$bytes> as a literal for a view's SQL. The base croaks: each
1222 dialect provides its own.
1223  
1224 my $literal = $dialect->quote_binary($dbh, "\xDE\xAD"); # '\xdead'::bytea
1225 my ($bytes) = $dbh->selectrow_array("SELECT $literal"); # "\xDE\xAD"
1226  
1227  
1228 =back
1229  
1230 =cut
1231  
1232 0 ▶sub quote_binary {
Subroutine quote_binary: not called CC=1 SCAR=6.9
Pod documented
1233 0 my $self = shift;
1234 0 croak "The " . $self->name . " dialect cannot write a binary value into SQL";
1235 }
1236  
1237 =pod
1238  
1239 =over 4
1240  
1241 =item $sql = $dialect->identity_sql($table, \%field, $inline_pk)
1242  
1243 The clause that makes a column an identity (C<identity> in its spec), or
1244 undef when declaring the column is enough.
1245  
1246 my $field = {
1247 name => 'id',
1248 db_type => 'integer',
1249 identity => 1,
1250 };
1251  
1252 my $pg = DBIx::QuickORM::Dialect->for_name('postgresql');
1253 my $pg_sql = $pg->identity_sql('posts', $field, 0); # GENERATED BY DEFAULT AS IDENTITY
1254  
1255 my $mysql = DBIx::QuickORM::Dialect->for_name('mysql');
1256 my $mysql_sql = $mysql->identity_sql('posts', $field, 0); # AUTO_INCREMENT
1257  
1258 C<$inline_pk> is true when the column declares the primary key itself (see
1259 C<_inline_pk>). Croaks by default.
1260  
1261 =item $sql = $dialect->generated_sql($expression)
1262  
1263 The clause that makes a column generated from C<$expression>:
1264 C<GENERATED ALWAYS AS ($expression) STORED> by default.
1265  
1266 =item $sql = $dialect->index_using_sql($type)
1267  
1268 The clause that picks an index type, for C<add_index>'s C<using>. Croaks by
1269 default: SQLite and DuckDB have no index types.
1270  
1271 my $gin = $dialect->index_using_sql('gin'); # USING gin
1272  
1273 # A reference is SQL written after USING, in place of the column list
1274 my @sql = $dialect->create_table_sql(
1275 docs => {
1276 columns => [
1277 {
1278 name => 'body',
1279 db_type => 'text',
1280 },
1281 ],
1282 indexes => [{using => \"gin (to_tsvector('english', body))"}],
1283 },
1284 temp => 1,
1285 );
1286 # $sql[1]: CREATE INDEX "docs_idx_1" ON "docs" USING gin (to_tsvector('english', body))
1287  
1288 PostgreSQL writes a name as given, MySQL in upper case (C<USING BTREE>).
1289  
1290 =back
1291  
1292 =cut
1293  
1294 0 ▶sub identity_sql {
Subroutine identity_sql: not called CC=1 SCAR=6.9
Pod documented
1295 0 my $self = shift;
1296 0 croak "The " . $self->name . " dialect cannot make an identity column in a temporary table";
1297 }
1298  
1299 1 ▶sub generated_sql { "GENERATED ALWAYS AS ($_[1]) STORED" }
Subroutine generated_sql: called CC=1 SCAR=0.0
Pod documented
1300  
1301 3 ▶sub index_using_sql {
Subroutine index_using_sql: called CC=1 SCAR=0.0
Pod documented
1302 3 my $self = shift;
1303 3 croak "The " . $self->name . " dialect has no index types, so add_index() cannot take 'using'";
1304 }
1305  
1306 # }}} Temporary tables and views
1307  
1308 =pod
1309  
1310 =over 4
1311  
1312 =item \%tables = $dialect->scan($dbh)
1313  
1314 =item \%tables = $dialect->scan($dbh, $temp)
1315  
1316 Scans the tables and views of the connection's namespace and returns them as
1317 plain map data.
1318  
1319 my $tables = $dialect->scan($dbh);
1320 my $posts = $tables->{posts};
1321  
1322 With C<$temp>, PostgreSQL, SQLite, and DuckDB scan only the temporary table
1323 or view of that name instead (see C<scan_temp>). The MySQL family ignores
1324 C<$temp> and scans the namespace. Every table's record has C<fields>, C<pk>, C<unique>,
1325 and C<fk>. For the C<users> and C<posts> tables, C<$tables> holds this, with
1326 only some of each table's fields shown:
1327  
1328 {
1329 posts => {
1330 fields => {
1331 id => {
1332 table => 'posts',
1333 name => 'id',
1334 affinity => 'numeric',
1335 db_type => 'integer',
1336 type => 'integer',
1337 db_fills => 1, # SERIAL: the database fills it
1338 },
1339 title => {
1340 table => 'posts',
1341 name => 'title',
1342 affinity => 'string',
1343 db_type => 'text',
1344 type => 'text',
1345 },
1346 },
1347 pk => ['id'], # key order, or undef when there is none
1348 unique => [], # each sorted, and the primary key is not repeated
1349 fk => {users => [{user_id => 'id'}]},
1350 },
1351 users => {
1352 fields => {
1353 email => {
1354 table => 'users',
1355 name => 'email',
1356 affinity => 'string',
1357 db_type => 'text',
1358 type => 'text',
1359 },
1360 },
1361 pk => ['id'],
1362 unique => [['email']],
1363 fk => {users => [{referred_by => 'id'}]},
1364 },
1365 }
1366  
1367 A view's record also has C<view> set to 1, and a materialized view's
1368 C<materialized> too. A view's fields never have C<db_fills> or
1369 C<db_refuses_value>. Temporary tables and system tables are left out. So are
1370 partial and expression unique indexes, since they do not make their columns
1371 unique across all rows.
1372  
1373 The scan runs one query per kind of metadata (DuckDB two for unique keys).
1374 Each dialect provides the SQL through these methods, each given the handle
1375 and C<$temp> (undef for the namespace scan):
1376  
1377 =over 4
1378  
1379 =item C<tables_sql>: C<(table, kind)> rows. C<kind> is undef for a table, C<view>, or C<materialized>.
1380  
1381 =item C<fields_sql>: C<(table, field, db_type, base_db_type, db_fills, db_refuses_value)> rows. C<base_db_type> is the type a user-defined type stands for, or undef. The last two are true or undef (see C<field_facts>).
1382  
1383 =item C<pk_sql>: C<(table, field)> rows in key order.
1384  
1385 =item C<unique_sql>: C<(table, key, field)> rows, with an undef field for a key that does not cover whole columns.
1386  
1387 =item C<fk_sql>: C<(table, key, field, other_table, other_field)> rows in key order, with an undef other field for a key on the other table's primary key.
1388  
1389 =back
1390  
1391 Each runs as is:
1392  
1393 my $rows = $dbh->selectall_arrayref($dialect->pk_sql($dbh, undef));
1394 # [['posts', 'id'], ['users', 'id']]
1395  
1396 =back
1397  
1398 =cut
1399  
1400 330 ▶sub scan {
Subroutine scan: called CC=10 SCAR=23.0
Pod documented
1401 330 my $self = shift;
1402 330 my ($dbh, $temp) = @_;
1403  
1404 330 my %tables;
1405 330 for my $row (@{$self->_rows($dbh, $self->tables_sql($dbh, $temp))}) {
1406 762 my ($name, $kind) = @$row;
1407 762 my $t = $tables{$name} = {fields => {}, pk => undef, unique => [], fk => {}};
1408 762 ▶ next unless $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless $kind 738 24 762
1409 24 $t->{view} = 1;
1410 24 ▶ $t->{materialized} = 1 if $kind eq 'materialized';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "materialized" 0 24 24
1411 }
1412  
1413 330 for my $row (@{$self->_rows($dbh, $self->fields_sql($dbh, $temp))}) {
1414 2199 my ($table, $field, @types) = @$row;
1415 2199 ▶ my $t = $tables{$table} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $tables{$table} or next 2198 1 2199
1416 2198 my $f = $t->{fields}->{$field} = {%{$self->field_facts(@types)}, table => $table, name => $field};
1417 2198 ▶ delete @{$f}{qw/db_fills db_refuses_value/} if $t->{view}; # a base table's default shows through a view
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"view"} 48 2150 2198
1418 }
1419  
1420 330 for my $row (@{$self->_rows($dbh, $self->pk_sql($dbh, $temp))}) {
1421 735 my ($table, $field) = @$row;
1422 735 ▶ my $t = $tables{$table} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $tables{$table} or next 735 0 735
1423 735 ▶ push @{$t->{pk} //= []} => $field;
Condition100%2/2
$t->{"pk"} //= []
l!l
97638
MC/DC100%1/1
$t->{"pk"} //= []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
1424 }
1425  
1426 330 $self->_add_unique(\%tables, $self->_keys_by_table($self->_unique_rows($dbh, $temp)));
1427 330 $self->_add_fks(\%tables, $self->_keys_by_table($self->_rows($dbh, $self->fk_sql($dbh, $temp))));
1428  
1429 330 return \%tables;
1430 }
1431  
1432 =pod
1433  
1434 =over 4
1435  
1436 =item \%table = $dialect->scan_temp($dbh, $name)
1437  
1438 The map record of the temporary table or view C<$name>, marked C<temp>, or
1439 undef when the session has none by that name.
1440  
1441 $dbh->do('CREATE TEMPORARY TABLE scratch (id INTEGER PRIMARY KEY, title TEXT)');
1442  
1443 my $scratch = $dialect->scan_temp($dbh, 'scratch'); # its record, with temp => 1
1444 my $none = $dialect->scan_temp($dbh, 'missing'); # undef
1445  
1446 By default it is C<scan> given C<$name>.
1447  
1448 The MySQL family reads C<SHOW COLUMNS> instead, which also finds a permanent
1449 table and croaks for a missing name. Pass it only the name of a temporary
1450 table created on that handle.
1451  
1452 =back
1453  
1454 =cut
1455  
1456 53 ▶sub scan_temp {
Subroutine scan_temp: called CC=2 SCAR=7.0
Pod documented
1457 53 my $self = shift;
1458 53 my ($dbh, $name) = @_;
1459 53 ▶ my $t = $self->scan($dbh, $name)->{$name} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->scan($dbh, $name)->{$name} or return undef 53 0 53
1460 53 $t->{temp} = 1;
1461 53 return $t;
1462 }
1463  
1464 =pod
1465  
1466 =over 4
1467  
1468 =item \%field = $dialect->field_facts($db_type, $base_db_type, $db_fills, $db_refuses_value)
1469  
1470 The map's facts about a field.
1471  
1472 my $title = $dialect->field_facts('character varying(255)');
1473 # type 'character varying', size 255, affinity 'string'
1474  
1475 my $id = $dialect->field_facts('integer', undef, 1);
1476 # type 'integer', affinity 'numeric', db_fills 1
1477  
1478 my $quantity = $dialect->field_facts('quantity', 'integer');
1479 # a domain over integer: type 'quantity', affinity 'numeric' from its base type
1480  
1481 The facts:
1482  
1483 =over 4
1484  
1485 =item C<db_type>: as given.
1486  
1487 =item C<type>: the lowercased base name, without sizes, array markers, C<unsigned>, or C<zerofill>.
1488  
1489 =item C<size>: the number the first parentheses start with, when they do.
1490  
1491 =item C<affinity>: from C<$base_db_type> when given, otherwise from C<$db_type>.
1492  
1493 =item C<db_fills>: 1 when the database fills the column when an insert leaves it out (a default, identity, serial, auto-increment, rowid alias, or generated column). Absent otherwise.
1494  
1495 =item C<db_refuses_value>: 1 when the database rejects an explicit value for the column (PostgreSQL C<GENERATED ALWAYS AS IDENTITY>, generated columns). Absent otherwise.
1496  
1497 =back
1498  
1499 =back
1500  
1501 =cut
1502  
1503 2320 ▶sub field_facts {
Subroutine field_facts: called CC=5 SCAR=16.1
Pod documented
1504 2320 my $self = shift;
1505 2320 my ($db_type, $base, $fills, $refuses) = @_;
1506  
1507 2320 my ($type, $size) = $self->_base_type($db_type);
1508 2320 ▶ my %field = (db_type => $db_type, type => $type, affinity => $self->affinity(defined($base) ? $base : $db_type));
Branch: 1 branch
BranchTrueFalseTotal
defined $base ? : 1 2319 2320
1509 2320 ▶ $field{size} = $size if defined $size;
Branch: 1 branch
BranchTrueFalseTotal
if defined $size 467 1853 2320
1510 2320 ▶ $field{db_fills} = 1 if $fills;
Branch: 1 branch
BranchTrueFalseTotal
if $fills 533 1787 2320
1511 2320 ▶ $field{db_refuses_value} = 1 if $refuses;
Branch: 1 branch
BranchTrueFalseTotal
if $refuses 7 2313 2320
1512  
1513 2320 return \%field;
1514 }
1515  
1516 my %AFFINITY = (
1517 4932 (map { $_ => 'string' } qw/bit char character string text bpchar clob nchar nvarchar enum set json jsonb money uuid xml citext name/),
1518 822 (map { $_ => 'string' } 'character varying', 'national character', 'national character varying'),
1519 2192 (map { $_ => 'string' } qw/date datetime interval time timestamp timestamptz timetz year/),
1520 1096 (map { $_ => 'string' } 'time with time zone', 'time without time zone', 'timestamp with time zone', 'timestamp without time zone'),
1521 822 (map { $_ => 'binary' } qw/binary blob bytea/),
1522 6302 (map { $_ => 'numeric' } qw/dec decimal double float float4 float8 hugeint int int2 int4 int8 integer tinyint smallint mediumint bigint number numeric real serial serial4 serial8 uhugeint/),
1523 274 (map { $_ => 'numeric' } 'double precision'),
1524 274 (map { $_ => 'boolean' } qw/bool boolean/),
1525 );
1526  
1527 =pod
1528  
1529 =over 4
1530  
1531 =item $affinity = $dialect->affinity($db_type)
1532  
1533 C<string>, C<numeric>, C<binary>, or C<boolean>.
1534  
1535 my $string = $dialect->affinity('varchar(20)'); # 'string'
1536 my $numeric = $dialect->affinity('bigint'); # 'numeric'
1537 my $binary = $dialect->affinity('bytea'); # 'binary'
1538 my $unknown = $dialect->affinity('point'); # 'string'
1539  
1540 Dates, times, JSON, and UUIDs are C<string>, and so is any type this does not
1541 know. C<bit> is C<string>: PostgreSQL returns bit strings and MySQL raw
1542 bytes, neither of which compares as a number.
1543  
1544 =back
1545  
1546 =cut
1547  
1548 38 ▶sub affinity {
Subroutine affinity: called CC=2 SCAR=6.9
Pod documented
1549 38 my $self = shift;
1550 38 my ($db_type) = @_;
1551 38 ▶ return $self->_known_affinity($db_type) // 'string';
Condition100%2/2
$self->_known_affinity($db_type) // "string"
l!l
362
MC/DC100%1/1
$self->_known_affinity($db_type) // "string"
$self->_known_affinity($db_type)
Truth table100%2/2
A
A= $self->_known_affinity($db_type)
Aresult
11
00
1552 }
1553  
1554 =head1 PRIVATE METHODS
1555  
1556 =over 4
1557  
1558 =item $version = $class->_server_version($dbh)
1559  
1560 The server's version for C<server_version>. By default C<SELECT version()>,
1561 through C<_version_number>.
1562  
1563 =item $version = $class->_version_number($string)
1564  
1565 The first C<major.minor[.patch]> in the string as
1566 C<major * 1_000_000 + minor * 1_000 + patch>, or undef when it has none, so
1567 an unreadable version string does not refuse the connection.
1568  
1569 =back
1570  
1571 =cut
1572  
1573 1 ▶sub _server_version {
Subroutine _server_version: called CC=1 SCAR=0.0
1574 1 my $class = shift;
1575 1 my ($dbh) = @_;
1576 1 my ($version) = $dbh->selectrow_array('SELECT version()');
1577 1 return $class->_version_number($version);
1578 }
1579  
1580 497 ▶sub _version_number {
Subroutine _version_number: called CC=4 SCAR=13.9
1581 497 my $class = shift;
1582 497 my ($string) = @_;
1583 497 ▶ my ($major, $minor, $patch) = ($string // '') =~ m/(\d+)\.(\d+)(?:\.(\d+))?/ or return undef;
Branch: 1 branch
BranchTrueFalseTotal
() = ($string // "") =~ /(\d+)\.(\d+)(?:\.(\d+))?/ or return undef 494 3 497
Condition100%2/2
$string // ""
l!l
4961
MC/DC100%1/1
$string // ""
$string
Truth table100%2/2
A
A= $string
Aresult
11
00
1584 494 ▶ return $major * 1_000_000 + $minor * 1_000 + ($patch // 0);
Condition100%2/2
$patch // 0
l!l
4931
MC/DC100%1/1
$patch // 0
$patch
Truth table100%2/2
A
A= $patch
Aresult
11
00
1585 }
1586  
1587 =pod
1588  
1589 =over 4
1590  
1591 =item $dialect->_null_socket($fd)
1592  
1593 Points the file descriptor at F</dev/null>, so nothing this process does with
1594 an inherited socket reaches the parent's session. Does nothing for undef or a
1595 negative descriptor.
1596  
1597 =back
1598  
1599 =cut
1600  
1601 1 ▶sub _null_socket {
Subroutine _null_socket: called CC=5 SCAR=24.5
1602 1 my $self = shift;
1603 1 my ($fd) = @_;
1604 1 ▶ return unless defined($fd) && $fd >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fd and $fd >= 0 1 0 1
Condition33%1/3
defined $fd and $fd >= 0
!ll&&!rl&&r
100
MC/DC0%0/2
defined $fd and $fd >= 0
defined $fd $fd >= 0
Truth table33%1/3
A and B
A= defined $fdB= $fd >= 0
ABresult
0X0
100
111
1605 0 ▶ open(my $null, '+<', '/dev/null') or die "Could not open /dev/null: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $null, "+<", "/dev/null" or die "Could not open /dev/null: $!" 0 0 0
1606 0 ▶ POSIX::dup2(fileno($null), $fd) // die "Could not redirect the inherited database socket: $!";
Condition0%0/2
POSIX::dup2(fileno $null, $fd) // die("Could not redirect the inherited database socket: $!")
l!l
00
MC/DC0%0/1
POSIX::dup2(fileno $null, $fd) // die("Could not redirect the inherited database socket: $!")
POSIX::dup2(fileno $null, $fd)
Truth table0%0/2
A
A= POSIX::dup2(fileno $null, $fd)
Aresult
11
00
1607 }
1608  
1609 =pod
1610  
1611 =over 4
1612  
1613 =item $affinity = $dialect->_known_affinity($db_type)
1614  
1615 The affinity of a known type, ignoring case, sizes, and a C<tiny>, C<small>,
1616 C<medium>, C<big>, C<long>, C<var>, or C<u> prefix, or undef for any other.
1617  
1618 =back
1619  
1620 =cut
1621  
1622 225 ▶sub _known_affinity {
Subroutine _known_affinity: called CC=4 SCAR=13.9
1623 225 my $self = shift;
1624 225 my ($db_type) = @_;
1625  
1626 225 my ($type) = $self->_base_type($db_type);
1627 225 ▶ return $AFFINITY{$type} if $AFFINITY{$type};
Branch: 1 branch
BranchTrueFalseTotal
if $AFFINITY{$type} 215 10 225
1628 10 ▶ return $AFFINITY{$1} if $type =~ m/^(?:tiny|small|medium|big|long|var|u)(.+)$/ && $AFFINITY{$1};
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ /^(?:tiny|small|medium|big|long|var|u)(.+)$/ and $AFFINITY{$1} 7 3 10
Condition66%2/3
$type =~ /^(?:tiny|small|medium|big|long|var|u)(.+)$/ and $AFFINITY{$1}
!ll&&!rl&&r
307
MC/DC50%1/2
$type =~ /^(?:tiny|small|medium|big|long|var|u)(.+)$/ and $AFFINITY{$1}
$type =~ /^(?:tiny|small|medium|big|long|var|u)(.+)$/ $AFFINITY{$1}
Truth table66%2/3
A and B
A= $type =~ /^(?:tiny|small|medium|big|long|var|u)(.+)$/B= $AFFINITY{$1}
ABresult
0X0
100
111
1629 3 return undef;
1630 }
1631  
1632 =pod
1633  
1634 =over 4
1635  
1636 =item \@rows = $dialect->_rows($dbh, $sql)
1637  
1638 Every row of a scan query, as arrayrefs, each value passed through
1639 C<text_from_db>.
1640  
1641 =back
1642  
1643 =cut
1644  
1645 1651 ▶sub _rows {
Subroutine _rows: called CC=2 SCAR=6.9
1646 1651 my $self = shift;
1647 1651 my ($dbh, $sql) = @_;
1648 1651 my $rows = $dbh->selectall_arrayref($sql);
1649 1651 $self->text_from_db(@$_) for @$rows;
1650 1651 return $rows;
1651 }
1652  
1653 =pod
1654  
1655 =over 4
1656  
1657 =item ($type, $size) = $dialect->_base_type($db_type)
1658  
1659 The C<type> and C<size> of C<field_facts>.
1660  
1661 =back
1662  
1663 =cut
1664  
1665 2547 ▶sub _base_type {
Subroutine _base_type: called CC=3 SCAR=11.0
1666 2547 my $self = shift;
1667 2547 my ($db_type) = @_;
1668  
1669 2547 my $type = lc($db_type);
1670 2547 my ($size) = $type =~ m/^[^(]*\(\s*(\d+)/;
1671 2547 ▶ 1 while $type =~ s/\([^()]*\)//g;
Branch: 1 branch
BranchTrueFalseTotal
$type =~ s/\([^()]*\)//g and do { '???' } 505 2547 3052
1672 2547 $type =~ s/\[\d*\]//g;
1673 2547 $type =~ s/\b(?:unsigned|zerofill)\b//g;
1674 2547 $type =~ s/\s+/ /g;
1675 2547 $type =~ s/^ | $//g;
1676  
1677 2547 ▶ return ($type, defined($size) ? $size + 0 : undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $size ? : 499 2048 2547
1678 }
1679  
1680 =pod
1681  
1682 =over 4
1683  
1684 =item \@rows = $dialect->_unique_rows($dbh, $temp)
1685  
1686 The C<(table, key, field)> rows of the unique keys: C<unique_sql>'s rows by
1687 default.
1688  
1689 =back
1690  
1691 =cut
1692  
1693 330 ▶sub _unique_rows {
Subroutine _unique_rows: called CC=1 SCAR=0.0
1694 330 my $self = shift;
1695 330 my ($dbh, $temp) = @_;
1696 330 return $self->_rows($dbh, $self->unique_sql($dbh, $temp));
1697 }
1698  
1699 =pod
1700  
1701 =over 4
1702  
1703 =item \%keys = $dialect->_keys_by_table(\@rows)
1704  
1705 Groups C<(table, key, ...)> rows as C<< {table => {key => [[...], ...]}} >>,
1706 keeping row order within each key.
1707  
1708 =back
1709  
1710 =cut
1711  
1712 663 ▶sub _keys_by_table {
Subroutine _keys_by_table: called CC=2 SCAR=6.9
1713 663 my $self = shift;
1714 663 my ($rows) = @_;
1715  
1716 663 my %keys;
1717 663 for my $row (@$rows) {
1718 503 my ($table, $key, @rest) = @$row;
1719 503 push @{$keys{$table}->{$key}} => \@rest;
1720 }
1721  
1722 663 return \%keys;
1723 }
1724  
1725 =pod
1726  
1727 =over 4
1728  
1729 =item $dialect->_add_unique(\%tables, \%keys)
1730  
1731 =item $dialect->_add_fks(\%tables, \%keys)
1732  
1733 Turn grouped C<unique_sql> and C<fk_sql> rows into each table's C<unique> and
1734 C<fk>, sorted and without duplicates.
1735  
1736 A unique key with an undef field, or a field the table does not have, is left
1737 out. A foreign key with undef other fields is used only when the other table
1738 was scanned and its primary key has as many fields. It then points at that
1739 key.
1740  
1741 =back
1742  
1743 =cut
1744  
1745 331 ▶sub _add_unique {
Subroutine _add_unique: called CC=8 SCAR=20.8
1746 331 my $self = shift;
1747 331 my ($tables, $keys) = @_;
1748  
1749 331 for my $table (keys %$keys) {
1750 251 ▶ my $t = $tables->{$table} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $tables->{$table} or next 250 1 251
1751 250 ▶ my %seen = $t->{pk} ? (join("\0" => sort @{$t->{pk}}) => 1) : ();
Branch: 1 branch
BranchTrueFalseTotal
$t->{'pk'} ? : 248 2 250
1752  
1753 250 my @unique;
1754 250 for my $rows (values %{$keys->{$table}}) {
1755 265 my @fields = map { $_->[0] } @$rows;
1756 265 ▶ next if grep { !defined($_) || !$t->{fields}->{$_} } @fields;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_ && $t->{"fields"}{$_};} @fields 5 260 265
Condition100%3/3
defined $_ && $t->{'fields'}{$_}
!ll&&!rl&&r
41366
MC/DC100%2/2
defined $_ && $t->{'fields'}{$_}
defined $_ $t->{'fields'}{$_}
Truth table100%3/3
A && B
A= defined $_B= $t->{'fields'}{$_}
ABresult
0X0
100
111
1757 260 @fields = sort @fields;
1758 260 ▶ push @unique => \@fields unless $seen{join "\0" => @fields}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{join "\0", @fields}++ 100 160 260
1759 }
1760  
1761 250 $t->{unique} = [sort { join("\0" => @$a) cmp join("\0" => @$b) } @unique];
1762 }
1763 }
1764  
1765 331 ▶sub _add_fks {
Subroutine _add_fks: called CC=9 SCAR=22.0
1766 331 my $self = shift;
1767 331 my ($tables, $keys) = @_;
1768  
1769 331 for my $table (keys %$keys) {
1770 115 ▶ my $t = $tables->{$table} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $tables->{$table} or next 115 0 115
1771  
1772 115 my %links;
1773 115 for my $rows (values %{$keys->{$table}}) {
1774 126 my $other = $rows->[0]->[1];
1775  
1776 # An undef other field means the other table's primary key, in key order.
1777 # A key on a table with none is unusable.
1778 126 ▶ my $other_pk = $tables->{$other} ? $tables->{$other}->{pk} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$tables->{$other} ? : 125 1 126
1779 126 my $usable = !grep { !defined $_->[2] } @$rows;
1780 126 ▶ $usable ||= $other_pk && @$other_pk == @$rows;
Condition83%5/6
$usable ||= $other_pk && @$other_pk == @$rows
l!l&&r!l&&!r
12231
$other_pk && @$other_pk == @$rows
!ll&&!rl&&r
103
MC/DC0%0/3
$usable ||= $other_pk && @$other_pk == @$rows
$usable $other_pk @$other_pk == @$rows
Truth table0%0/4
A ||= B && C
A= $usableB= $other_pkC= @$other_pk == @$rows
ABCresult
1XX1
0111
00X0
0100
1781 126 ▶ next unless $usable;
Branch: 1 branch
BranchTrueFalseTotal
unless $usable 1 125 126
1782  
1783 125 ▶ my %link = map { $rows->[$_]->[0] => $rows->[$_]->[2] // $other_pk->[$_] } 0 .. $#$rows;
Condition66%2/3
$rows->[$_][2] // $other_pk->[$_]
l!l&&r!l&&!r
12240
MC/DC0%0/2
$rows->[$_][2] // $other_pk->[$_]
$rows->[$_][2] $other_pk->[$_]
Truth table66%2/3
A // B
A= $rows->[$_][2]B= $other_pk->[$_]
ABresult
1X1
011
000
1784 125 $links{$other}->{join "\0" => map { "$_\0$link{$_}" } sort keys %link} = \%link;
1785 }
1786  
1787 115 $t->{fk} = {map { my $l = $links{$_}; ($_ => [@{$l}{sort keys %$l}]) } keys %links};
1788 }
1789 }
1790  
1791 =pod
1792  
1793 =over 4
1794  
1795 =item @columns = $dialect->_inline_pk(\%spec)
1796  
1797 The primary key columns to declare on their column instead of in a
1798 C<PRIMARY KEY> clause. None by default.
1799  
1800 =item $dialect->_only_temp($method, %opts)
1801  
1802 Croaks unless C<%opts> has a true C<temp>: C<create_table_as_sql> and
1803 C<drop_sql> are for temporary tables and views only.
1804  
1805 =item $why = $dialect->_too_old($minimum, $needs, $for)
1806  
1807 For C<unsupported>: a message when C<server_version> is below C<$minimum>
1808 (C<$needs> names that version, C<$for> the reason), otherwise undef. Undef
1809 when the version is unknown.
1810  
1811 =item $sql = $dialect->_column_sql($table, \%column, \%inline)
1812  
1813 One column of C<create_table_sql>, or a column given as SQL (C<sql>, a
1814 reference to SQL or an C<sql()> marker): its name, then the SQL as given.
1815 C<%inline> holds the columns C<_inline_pk> named.
1816  
1817 =item $sql = $dialect->_enum_check($column, \@values)
1818  
1819 The check that a column holds one of the values, for databases or tables
1820 without an enum type.
1821  
1822 =item @sql = $dialect->_index_sql($table, \@indexes)
1823  
1824 The index statements that follow the C<CREATE TABLE>. A dialect that declares
1825 indexes inside it returns one arrayref of the definitions instead.
1826  
1827 =item @sql = $dialect->_sequence_sql($table, \%spec, $temp)
1828  
1829 Statements to run before the C<CREATE TABLE>: none by default.
1830  
1831 =item \%parts = $dialect->_column_parts($table, \%column, \%inline)
1832  
1833 A column's parts, for C<_column_sql> to join and the pretty layout to line
1834 up: C<name>, C<type> (with its collation), C<value> (inline key, identity,
1835 generated, default), C<null>, and C<rest> (unique, check).
1836  
1837 =item $body = $dialect->_pretty_table_body($table, \%spec, \%inline, \@constraints)
1838  
1839 The parenthesized body of a pretty C<CREATE TABLE>, as C<create_table_sql>
1840 describes it.
1841  
1842 =item $sql = $dialect->_constraint_sql($name, $sql)
1843  
1844 C<$sql> as a named constraint (C<CONSTRAINT name ...>), or as is for an
1845 undef name.
1846  
1847 =item $sql = $dialect->_literal_sql($what)
1848  
1849 Literal SQL from a reference to a string or an C<sql()> marker (its binds
1850 written in as literals through C<quote_literal>), for a column's C<default>,
1851 C<generated>, or C<check>, or the SQL of a column given as SQL.
1852  
1853 =back
1854  
1855 =cut
1856  
1857 57 ▶sub _inline_pk { () }
Subroutine _inline_pk: called CC=1 SCAR=0.0
1858  
1859 483 ▶sub _too_old {
Subroutine _too_old: called CC=4 SCAR=13.9
1860 483 my $self = shift;
1861 483 my ($minimum, $needs, $for) = @_;
1862 483 ▶ my $version = ref($self) ? $self->{+SERVER_VERSION} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 482 1 483
1863 483 ▶ return undef if !defined($version) || $version >= $minimum;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $version or $version >= $minimum 481 2 483
Condition100%3/3
not defined $version or $version >= $minimum
l!l&&r!l&&!r
14802
MC/DC100%2/2
not defined $version or $version >= $minimum
not defined $version $version >= $minimum
Truth table100%3/3
not(A) or B
A= not defined $versionB= $version >= $minimum
ABresult
1X1
011
000
1864 2 my $have = join '.' => int($version / 1_000_000), int($version / 1_000) % 1_000, $version % 1_000;
1865 2 return "QuickORM needs $needs or later for $for, found $have";
1866 }
1867  
1868 70 ▶sub _only_temp {
Subroutine _only_temp: called CC=2 SCAR=6.9
1869 70 my $self = shift;
1870 70 my ($method, %opts) = @_;
1871 70 ▶ croak "$method() is for temporary tables and views only (pass temp => 1)" unless $opts{temp};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"temp"} 2 68 70
1872 }
1873  
1874 254 ▶sub _column_sql {
Subroutine _column_sql: called CC=2 SCAR=6.9
1875 254 my $self = shift;
1876 254 my ($table, $field, $inline) = @_;
1877 254 ▶ return $self->quote_identifier($field->{name}) . ' ' . $self->_literal_sql($field->{sql}) if exists $field->{sql};
Branch: 1 branch
BranchTrueFalseTotal
if exists $field->{"sql"} 9 245 254
1878 245 my $parts = $self->_column_parts($table, $field, $inline);
1879 243 return join ' ' => grep { length } $parts->{name}, $parts->{type}, @{$parts->{value}}, $parts->{null}, @{$parts->{rest}};
1880 }
1881  
1882 280 ▶sub _column_parts {
Subroutine _column_parts: called CC=12 SCAR=24.9
1883 280 my $self = shift;
1884 280 my ($table, $field, $inline) = @_;
1885  
1886 280 my $type = $field->{db_type};
1887 280 ▶ $type .= ' ' . $self->collate_sql($field->{collate}) if defined $field->{collate};
Branch: 1 branch
BranchTrueFalseTotal
if defined $field->{"collate"} 6 274 280
1888  
1889 280 my @value;
1890 280 ▶ push @value => 'PRIMARY KEY' if $inline->{$field->{name}};
Branch: 1 branch
BranchTrueFalseTotal
if $$inline{$field->{"name"}} 5 275 280
1891 280 ▶ if ($field->{identity}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field->{"identity"}) 11 269 280
1892 11 ▶ my $identity = $self->identity_sql($table, $field, $inline->{$field->{name}} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$$inline{$field->{'name'}} ? : 5 6 11
1893 10 ▶ push @value => $identity if defined $identity;
Branch: 1 branch
BranchTrueFalseTotal
if defined $identity 5 5 10
1894 }
1895 279 ▶ push @value => $self->generated_sql($self->_literal_sql($field->{generated})) if defined $field->{generated};
Branch: 1 branch
BranchTrueFalseTotal
if defined $field->{"generated"} 0 279 279
1896 279 ▶ push @value => 'DEFAULT ' . (ref($field->{default}) ? $self->_literal_sql($field->{default}) : $self->quote_literal($field->{default})) if exists $field->{default};
Branch: 2 branches
BranchTrueFalseTotal
if exists $field->{"default"} 26 253 279
ref $field->{'default'} ? : 5 21 26
1897  
1898 278 my @rest;
1899 278 ▶ push @rest => 'UNIQUE' if $field->{unique};
Branch: 1 branch
BranchTrueFalseTotal
if $field->{"unique"} 4 274 278
1900 278 ▶ push @rest => 'CHECK (' . $self->_literal_sql($field->{check}) . ')' if defined $field->{check};
Branch: 1 branch
BranchTrueFalseTotal
if defined $field->{"check"} 8 270 278
1901  
1902 return {
1903 name => $self->quote_identifier($field->{name}),
1904 type => $type,
1905 value => \@value,
1906 278 ▶ null => $field->{not_null} ? 'NOT NULL' : '',
Branch: 1 branch
BranchTrueFalseTotal
$field->{'not_null'} ? : 29 249 278
1907 rest => \@rest,
1908 };
1909 }
1910  
1911 14 ▶sub _pretty_table_body {
Subroutine _pretty_table_body: called CC=14 SCAR=26.4
1912 14 my $self = shift;
1913 14 my ($table, $spec, $inline, $constraints) = @_;
1914 14 my $spacer = ' ';
1915  
1916 # The leading key or identity columns get their own lines, aligned by name and type only.
1917 14 ▶ my %key = map { $_ => 1 } @{$spec->{pk} // []}, keys %$inline;
Condition100%2/2
$spec->{"pk"} // []
l!l
104
MC/DC100%1/1
$spec->{"pk"} // []
$spec->{"pk"}
Truth table100%2/2
A
A= $spec->{"pk"}
Aresult
11
00
1918 14 my (@lead, @rows);
1919 14 for my $field (@{$spec->{columns}}) {
1920 37 ▶ my $row = exists($field->{sql}) ? {name => $self->quote_identifier($field->{name}), literal => $self->_literal_sql($field->{sql})} : $self->_column_parts($table, $field, $inline);
Branch: 1 branch
BranchTrueFalseTotal
exists $field->{'sql'} ? : 2 35 37
1921 37 ▶ my $leading = !@rows && !$row->{literal} && ($key{$field->{name}} || $field->{identity});
Condition77%7/9
!(@rows || $row->{'literal'}) && ($key{$field->{'name'}} || $field->{'identity'})
!ll&&!rl&&r
141310
@rows || $row->{'literal'}
l!l&&r!l&&!r
14023
$key{$field->{"name"}} or $field->{"identity"}
l!l&&r!l&&!r
10013
MC/DC50%2/4
!(@rows || $row->{'literal'}) && ($key{$field->{'name'}} || $field->{'identity'})
@rows $row->{'literal'} $key{$field->{"name"}} $field->{"identity"}
Truth table60%3/5
not(A || B) && C or D
A= @rowsB= $row->{'literal'}C= $key{$field->{"name"}}D= $field->{"identity"}
ABCDresult
1XXX0
01XX0
00000
001X1
00011
1922 37 ▶ push @{$leading ? \@lead : \@rows} => $row;
Branch: 1 branch
BranchTrueFalseTotal
$leading ? : 10 27 37
1923 }
1924  
1925 14 my @parts = grep { !$_->{literal} } @lead, @rows;
1926 14 ▶ my $w = sub { my $max = 0; length($_) > $max and $max = length($_) for @_; $max };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
length $_ > $max and $max = length $_ 56 66 122
1927 14 my $name_w = $w->(map { $_->{name} } @lead, @rows);
1928 14 my $type_w = $w->(map { $_->{type} } @parts);
1929 14 my $value_w = $w->(map { join ' ' => @{$_->{value}} } grep { !$_->{literal} } @rows);
1930 14 my $null_w = $w->(map { $_->{null} } grep { !$_->{literal} } @rows);
1931 14 ▶ my $pad = sub { my ($text, $width) = @_; $width ? sprintf("%-*s", $width, $text) . $spacer : '' };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$width ? : 106 16 122
1932  
1933 37 ▶ my $line = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1934 37 my ($row, $lead) = @_;
1935 37 ▶ return $pad->($row->{name}, $name_w) . $row->{literal} if $row->{literal};
Branch: 1 branch
BranchTrueFalseTotal
if $row->{"literal"} 2 35 37
1936 35 my $start = $pad->($row->{name}, $name_w) . $pad->($row->{type}, $type_w);
1937 35 ▶ return ($start . join ' ' => grep { length } @{$row->{value}}, $row->{null}, @{$row->{rest}}) =~ s/\s+\z//r if $lead;
Branch: 1 branch
BranchTrueFalseTotal
if $lead 10 25 35
1938 25 return ($start . $pad->(join(' ' => @{$row->{value}}), $value_w) . $pad->($row->{null}, $null_w) . join(' ' => @{$row->{rest}})) =~ s/\s+\z//r;
1939 14 };
1940  
1941 14 my @groups = grep { @$_ } [map { $line->($_, 1) } @lead], [map { $line->($_, 0) } @rows], [@$constraints];
1942 14 my @lines;
1943 14 for my $g (0 .. $#groups) {
1944 33 ▶ push @lines => '' if $g;
Branch: 1 branch
BranchTrueFalseTotal
if $g 19 14 33
1945 33 for my $i (0 .. $#{$groups[$g]}) {
1946 51 ▶ my $last = $g == $#groups && $i == $#{$groups[$g]};
Condition100%3/3
$g == $#groups && $i == $#{$groups[$g];}
!ll&&!rl&&r
31614
MC/DC100%2/2
$g == $#groups && $i == $#{$groups[$g];}
$g == $#groups $i == $#{$groups[$g];}
Truth table100%3/3
A && B
A= $g == $#groupsB= $i == $#{$groups[$g];}
ABresult
0X0
100
111
1947 51 ▶ push @lines => ' ' . $groups[$g]->[$i] . ($last ? '' : ',');
Branch: 1 branch
BranchTrueFalseTotal
$last ? : 14 37 51
1948 }
1949 }
1950 14 ▶ return "(\n" . join("\n" => map { length($_) ? $_ : '' } @lines) . "\n)";
Branch: 1 branch
BranchTrueFalseTotal
length $_ ? : 51 19 70
1951 }
1952  
1953 60 ▶sub _constraint_sql {
Subroutine _constraint_sql: called CC=2 SCAR=6.9
1954 60 my $self = shift;
1955 60 my ($name, $sql) = @_;
1956 60 ▶ return defined($name) ? "CONSTRAINT " . $self->quote_identifier($name) . " $sql" : $sql;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 13 47 60
1957 }
1958  
1959 114 ▶sub _index_sql {
Subroutine _index_sql: called CC=6 SCAR=17.9
1960 114 my $self = shift;
1961 114 my ($table, $indexes) = @_;
1962 114 my $i = 0;
1963 return map {
1964 114 my $index = $_;
1965 27 ▶ $index->{sql} // do {
Condition100%3/3
$index->{"sql"} // do { my $name = $index->{"name"} // "${table}_idx_" . ++$i; my $using = defined $index->{"using"} ? ' ' . $self->index_using_sql($index->{"using"}) : ""; my $cols = ref $index->{"using"} ? "" : ' (' . join(", ", map({$self->quote_identifier($_);} @{$$index{"columns"};})) . ')'; 'CREATE ' . ($index->{"unique"} ? "UNIQUE " : "") . 'INDEX ' . $self->quote_identifier($name) . ' ON ' . $self->quote_identifier($table) . "$using$cols" }
l!l&&r!l&&!r
1242
MC/DC0%0/2
$index->{"sql"} // do { my $name = $index->{"name"} // "${table}_idx_" . ++$i; my $using = defined $index->{"using"} ? ' ' . $self->index_using_sql($index->{"using"}) : ""; my $cols = ref $index->{"using"} ? "" : ' (' . join(", ", map({$self->quote_identifier($_);} @{$$index{"columns"};})) . ')'; 'CREATE ' . ($index->{"unique"} ? "UNIQUE " : "") . 'INDEX ' . $self->quote_identifier($name) . ' ON ' . $self->quote_identifier($table) . "$using$cols" }
$index->{"sql"} do { my $name = $index->{"name"} // "${table}_idx_" . ++$i; my $using = defined $index->{"using"} ? ' ' . $self->index_using_sql($index->{"using"}) : ""; my $cols = ref $index->{"using"} ? "" : ' (' . join(", ", map({$self->quote_identifier($_);} @{$$index{"columns"};})) . ')'; 'CREATE ' . ($index->{"unique"} ? "UNIQUE " : "") . 'INDEX ' . $self->quote_identifier($name) . ' ON ' . $self->quote_identifier($table) . "$using$cols" }
Truth table66%2/3
A // B
A= $index->{"sql"}B= do { my $name = $index->{"name"} // "${table}_idx_" . ++$i; my $using = defined $index->{"using"} ? ' ' . $self->index_using_sql($index->{"using"}) : ""; my $cols = ref $index->{"using"} ? "" : ' (' . join(", ", map({$self->quote_identifier($_);} @{$$index{"columns"};})) . ')'; 'CREATE ' . ($index->{"unique"} ? "UNIQUE " : "") . 'INDEX ' . $self->quote_identifier($name) . ' ON ' . $self->quote_identifier($table) . "$using$cols" }
ABresult
1X1
011
000
1966 26 ▶ my $name = $index->{name} // "${table}_idx_" . ++$i;
Condition100%2/2
$index->{"name"} // "${table}_idx_" . ++$i
l!l
1115
MC/DC100%1/1
$index->{"name"} // "${table}_idx_" . ++$i
$index->{"name"}
Truth table100%2/2
A
A= $index->{"name"}
Aresult
11
00
1967 26 ▶ my $using = defined($index->{using}) ? ' ' . $self->index_using_sql($index->{using}) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $index->{'using'} ? : 5 21 26
1968 23 ▶ my $cols = ref($index->{using}) ? '' : " (" . join(', ' => map { $self->quote_identifier($_) } @{$index->{columns}}) . ")";
Branch: 1 branch
BranchTrueFalseTotal
ref $index->{'using'} ? : 1 22 23
1969 23 ▶ "CREATE " . ($index->{unique} ? 'UNIQUE ' : '') . "INDEX " . $self->quote_identifier($name) . " ON " . $self->quote_identifier($table) . "$using$cols";
Branch: 1 branch
BranchTrueFalseTotal
$index->{'unique'} ? : 1 22 23
1970 };
1971 } @$indexes;
1972 }
1973  
1974 133 ▶sub _dialect_indexes {
Subroutine _dialect_indexes: called CC=7 SCAR=19.5
1975 133 my $self = shift;
1976 133 my ($table, $spec, $temp) = @_;
1977  
1978 16 ▶ my $entry = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1979 16 my ($base, $by, $what) = @_;
1980 16 my ($found, $value) = $self->pick_entry($by);
1981 16 ▶ return $base unless $found;
Branch: 1 branch
BranchTrueFalseTotal
unless $found 3 13 16
1982 13 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 6 7 13
1983 7 ▶ return {%$base, %$value} if ref($value) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "HASH" 3 4 7
1984 4 ▶ croak "$what gives the " . $self->name . " dialect the index's SQL, which a temporary table cannot take: give it options or undef" if $temp;
Branch: 1 branch
BranchTrueFalseTotal
if $temp 2 2 4
1985 2 return {sql => $$value =~ s/;\s*\z//r};
1986 133 };
1987  
1988 133 my @indexes;
1989 133 for my $column (@{$spec->{columns}}) {
1990 298 ▶ my $index = $column->{indexed} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $index = $column->{"indexed"} or next 14 284 298
1991 14 my $base = {columns => [$column->{name}], name => "${table}_$column->{name}_idx"};
1992 14 ▶ push @indexes => ref($index) ? $entry->($base, $index, "The column '$column->{name}'") : $base;
Branch: 1 branch
BranchTrueFalseTotal
ref $index ? : 6 8 14
1993 }
1994 132 ▶ for my $index (@{$spec->{indexes} // []}) {
Condition100%2/2
$spec->{"indexes"} // []
l!l
11913
MC/DC100%1/1
$spec->{"indexes"} // []
$spec->{"indexes"}
Truth table100%2/2
A
A= $spec->{"indexes"}
Aresult
11
00
1995 31 my %base = %$index;
1996 31 my $by = delete $base{dialect};
1997 31 ▶ push @indexes => $by ? $entry->(\%base, $by, "An index of the table '$table'") : \%base;
Branch: 1 branch
BranchTrueFalseTotal
$by ? : 10 21 31
1998 }
1999 131 return @indexes;
2000 }
2001  
2002 123 ▶sub _sequence_sql { () }
Subroutine _sequence_sql: called CC=1 SCAR=0.0
2003  
2004 56 ▶sub _literal_sql {
Subroutine _literal_sql: called CC=8 SCAR=22.2
2005 56 my $self = shift;
2006 56 my ($what) = @_;
2007 56 ▶ return $$what if ref($what) eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if ref $what eq "SCALAR" 51 5 56
2008 5 ▶ croak "Literal SQL must be a reference to a string or an sql() marker" unless blessed($what) && $what->isa('DBIx::QuickORM::Value') && $what->kind eq 'sql';
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($what) and $what->isa("DBIx::QuickORM::Value") and $what->kind eq "sql" 0 5 5
Condition33%2/6
builtin::blessed($what) and $what->isa("DBIx::QuickORM::Value") and $what->kind eq "sql"
!ll&&!rl&&r
005
builtin::blessed($what) and $what->isa("DBIx::QuickORM::Value")
!ll&&!rl&&r
005
MC/DC0%0/3
builtin::blessed($what) and $what->isa("DBIx::QuickORM::Value") and $what->kind eq "sql"
builtin::blessed($what) $what->isa("DBIx::QuickORM::Value") $what->kind eq "sql"
Truth table25%1/4
A and B and C
A= builtin::blessed($what)B= $what->isa("DBIx::QuickORM::Value")C= $what->kind eq "sql"
ABCresult
0XX0
10X0
1100
1111
2009 5 ▶ my ($sql, @binds) = ($what->value, @{$what->binds // []});
Condition50%1/2
$what->binds // []
l!l
50
MC/DC0%0/1
$what->binds // []
$what->binds
Truth table50%1/2
A
A= $what->binds
Aresult
11
00
2010 5 ▶ $sql =~ s/\?/@binds ? $self->quote_literal(shift @binds) : croak "The sql() marker has fewer binds than placeholders"/ge;
Branch: 1 branch
BranchTrueFalseTotal
@binds ? : 4 1 5
2011 4 ▶ croak "The sql() marker has more binds than placeholders" if @binds;
Branch: 1 branch
BranchTrueFalseTotal
if @binds 0 4 4
2012 4 return $sql;
2013 }
2014 274 1;
2015  
2016 __END__
« blib/lib/DBIx/QuickORM/SchemaBuilder/View.pm ↑ Summary blib/lib/DBIx/QuickORM/RowState.pm »