Quiq/Sql.pm

filter: Statementstmt 67.6% 704 / 1040 Branchbran 51.5% 275 / 534 Conditioncond 43.5% 95 / 218 MC/DCmcdc 16.3% 20 / 122 Subroutinesub 77.6% 73 / 94 Podpod 98.7% 80 / 81 totaltotal 59.6% 1247 / 2089 CC 355 SCAR 44.7
CC
355
Cov
60%
select
490.1
modifyColumn
118.0
addForeignKeyConstraint
66.7
CRAP 87.7
« Quiq/Terminal.pm ↑ Summary Quiq/Http/Client.pm »
1 # -----------------------------------------------------------------------------
2  
3 =encoding utf8
4  
5 =head1 NAME
6  
7 Quiq::Sql - Klasse zur Generierung von SQL
8  
9 =head1 BASE CLASS
10  
11 L<Quiq::Dbms>
12  
13 =head1 SYNOPSIS
14  
15 Das Programm
16  
17 use Quiq::Sql;
18
19 my $sql = Quiq::Sql->new('Oracle');
20
21 my $stmt = $sql->createTable('person',
22 ['per_id',type=>'INTEGER',primaryKey=>1],
23 ['per_vorname',type=>'STRING(30)'],
24 ['per_nachname',type=>'STRING(30)',notNull=>1],
25 );
26
27 say $stmt;
28  
29 generiert das CREATE TABLE Statement
30  
31 CREATE TABLE person (
32 per_id NUMBER PRIMARY KEY,
33 per_vorname VARCHAR2(30),
34 per_nachname VARCHAR2(30) NOT NULL
35 )
36  
37 (man beachte die Abbildung der Kolumnentypen)
38  
39 Die Klasse stellt
40  
41 =head1 DESCRIPTION
42  
43 =head2 Zweck der Klasse
44  
45 Die Klasse unterstützt die Entwicklung von portablen Datenbankanwendungen,
46 d.h. Anwendungen, die unter mehreren DBMSen lauffähig sein sollen. Dies
47 wird erreicht, indem die Klasse Methoden zur Verfügung stellt, die zum
48 DBMS den passenden SQL-Code erzeugen.
49  
50 =head2 Unterstützte Datenbanksysteme
51  
52 Folgende DBMSe werden von der Klasse unterstützt:
53  
54 Oracle
55 PostgreSQL
56 SQLite
57 MySQL
58  
59 =cut
60  
61 # -----------------------------------------------------------------------------
62  
63 package Quiq::Sql;
64 6 ▶use base qw/Quiq::Dbms/;
Subroutine BEGIN: called CC=1 SCAR=0.0
65  
66 6 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
68 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
69 6 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
70  
71 6 our $VERSION = '1.240';
72  
73 6 ▶use Quiq::Hash;
Subroutine BEGIN: called CC=1 SCAR=0.0
74 6 ▶use Quiq::Option;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 6 ▶use Quiq::String;
Subroutine BEGIN: called CC=1 SCAR=0.0
76 6 ▶use Quiq::Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
77 6 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
78 6 ▶use Quiq::Unindent;
Subroutine BEGIN: called CC=1 SCAR=0.0
79 6 ▶use Quiq::Reference;
Subroutine BEGIN: called CC=1 SCAR=0.0
80  
81 # -----------------------------------------------------------------------------
82  
83 =head1 METHODS
84  
85 =head2 Utilities
86  
87 =head3 split() - Zerlege SQL-Statement in Rumpf und Stringliteral-Werte
88  
89 =head4 Synopsis
90  
91 ($stmt1,@arr) = $this->split($stmt);
92  
93 =head4 Description
94  
95 Zerlege $stmt in den Statement-Rumpf und eine Liste von
96 Stringliteral-Werten und liefere diese beiden Bestandteile zurück.
97  
98 Statement-Rumpf und Stringliteralwerte können unabhängig bearbeitet
99 und anschließend mit sprintf() wieder zusammengefügt werden.
100  
101 =head4 Example
102  
103 Zerlege Statement in Bestandteile:
104  
105 $stmt1 = "SELECT 'a', 'b' FROM x WHERE x = 'c' AND y = 'd''e'";
106 ($stmt2,@arr) = $class->split($stmt1);
107 =>
108 "SELECT '%s', '%s' FROM x WHERE x = '%s' AND y = '%s''%s'"
109 ('a','b','c','d','e')
110  
111 Füge Bestandteile wieder zusammen:
112  
113 $stmt2 = sprintf($stmt2,@arr);
114 =>
115 "SELECT 'a', 'b' FROM x WHERE x = 'c' AND y = 'd''e'"
116  
117 =cut
118  
119 # -----------------------------------------------------------------------------
120  
121 87 ▶sub split {
Subroutine split: called CC=1 SCAR=0.0
Pod documented
122 87 my $class = shift;
123 87 my $stmt = shift;
124  
125 87 my @arr = $stmt =~ /'(.*?)'/gs;
126 87 $stmt =~ s/'.*?'/'%s'/gs;
127  
128 87 return ($stmt,@arr);
129 }
130  
131 # -----------------------------------------------------------------------------
132  
133 =head3 resolve() - Ersetze SQL-Platzhalter durch Werte
134  
135 =head4 Synopsis
136  
137 $stmtResolved = $sql->resolve($stmt,@vals);
138  
139 =head4 Description
140  
141 Ersetze die Platzhalter ? in SQL-Statement $stmt durch die
142 Werte @val und liefere das resultierende Statement zurück.
143  
144 Diese Methode ist für Debugging-Zwecke nützlich, wenn mit
145 Platzhaltern gearbeitet wird, aber man das aufgelöste Statement
146 sehen möchte.
147  
148 =head4 Example
149  
150 $stmt = 'SELECT * FROM t WHERE x = ? AND y > ?';
151 @vals = (47,11);
152 $stmtResolved = $sql->resolve($stmt,@vals);
153 =>
154 "SELECT * FROM t WHERE x = '47' AND y > '11'"
155  
156 =cut
157  
158 # -----------------------------------------------------------------------------
159  
160 1 ▶sub resolve {
Subroutine resolve: called CC=3 SCAR=11.1
Pod documented
161 1 my $self = shift;
162 1 my $stmt = shift;
163 # @_: @vals
164  
165 # Stringliteral-Werte herausziehen
166 1 ($stmt,my @arr) = $self->split($stmt);
167  
168 1 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 1 3
169 2 my $val = shift;
170 2 ▶ if ($val =~ /%s/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /%s/) 0 2 2
171 0 $self->throw(
172 'SQL-00099: Wert enthält %s',
173 Value => $val,
174 );
175 }
176 2 $stmt =~ s/\?/$self->stringLiteral($val,'NULL')/e;
177 }
178  
179 # Stringliteral-Werte einsetzen
180 1 return sprintf $stmt,@arr;
181 }
182  
183 # -----------------------------------------------------------------------------
184  
185 =head3 removeSelectClause() - Entferne SELECT-Klausel
186  
187 =head4 Synopsis
188  
189 $newStmt = $sql->removeSelectClause($stmt);
190  
191 =head4 Description
192  
193 Entferne die Select-Klausel am Anfang von Select-Statement $stmt
194 und liefere das resultierende Statement zurück.
195  
196 Als Select-Klausel wird alles vom Beginn des Statement
197 bis zur FROM-Klausel angesehen.
198  
199 =cut
200  
201 # -----------------------------------------------------------------------------
202  
203 1 ▶sub removeSelectClause {
Subroutine removeSelectClause: called CC=1 SCAR=0.0
Pod documented
204 1 my ($self,$stmt) = @_;
205 1 $stmt =~ s|^.*?(?=FROM)||si;
206 1 return $stmt;
207 }
208  
209 # -----------------------------------------------------------------------------
210  
211 =head3 removeOrderByClause() - Entferne ORDER BY-Klausel
212  
213 =head4 Synopsis
214  
215 $newStmt = $sql->removeOrderByClause($stmt);
216  
217 =head4 Description
218  
219 Entferne die Order By-Klausel vom Ende des Select-Statement $stmt
220 und liefere das resultierende Statement zurück.
221  
222 Als Select-Klausel wird alles von der ORDER BY-Klausel bis zum
223 Ende des Statment angesehen.
224  
225 =cut
226  
227 # -----------------------------------------------------------------------------
228  
229 1 ▶sub removeOrderByClause {
Subroutine removeOrderByClause: called CC=1 SCAR=0.0
Pod documented
230 1 my ($self,$stmt) = @_;
231 1 $stmt =~ s|\s+ORDER\s+BY.*$||si;
232 1 return $stmt;
233 }
234  
235 # -----------------------------------------------------------------------------
236  
237 =head3 checkName() - Prüfe Bezeichner
238  
239 =head4 Synopsis
240  
241 $name = $sql->checkName($name);
242 $sql->checkName(\$name);
243  
244 =head4 Description
245  
246 Prüfe und manipuliere Bezeichner $name, so dass er den Konventionen
247 des DBMS entspricht.
248  
249 B<Oracle>
250  
251 =over 2
252  
253 =item *
254  
255 Ist der Bezeichner länger als 30 Zeichen, kürze ihn auf 29
256 Zeichen und ersetze das 30. Zeichen durch #.
257  
258 =back
259  
260 =cut
261  
262 # -----------------------------------------------------------------------------
263  
264 6 ▶sub checkName {
Subroutine checkName: called CC=7 SCAR=19.8
Pod documented
265 6 my $self = shift;
266 6 my $arg = shift;
267  
268 6 ▶ my $ref = ref $arg? $arg: \$arg;
Branch: 1 branch
BranchTrueFalseTotal
ref $arg ? : 5 1 6
269 6 ▶ if ($self->isOracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->isOracle) { } 1 5 6
elsif ($self->isPostgreSQL) { } 5 0 5
270 1 ▶ if (length $$ref > 30) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$ref > 30) 1 0 1
271 1 $$ref = substr($$ref,0,29).'$';
272 }
273 1 $$ref =~ s/[^\w#\$]/_/g;
274 }
275 elsif ($self->isPostgreSQL) {
276 5 ▶ if (length $$ref > 63) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$ref > 63) 0 5 5
277 0 $$ref = substr($$ref,0,63).'$';
278 }
279 5 $$ref =~ s/[^\w\$]/_/g;
280 }
281  
282 6 ▶ return ref $arg? (): $arg;
Branch: 1 branch
BranchTrueFalseTotal
ref $arg ? : 5 1 6
283 }
284  
285 # -----------------------------------------------------------------------------
286  
287 =head3 stmtListToScript() - Generiere aus Liste von SQL-Statements ein Skript
288  
289 =head4 Synopsis
290  
291 $script = $class->stmtListToScript(@stmt)
292  
293 =head4 Description
294  
295 Erzeuge aus einer Liste von SQL-Statements ein einzelnes Skript,
296 das von einem Client-Programm wie SQL*Plus, psql bzw. mysql
297 ausgeführt werden kann.
298  
299 Die SQL-Statements bzw. SQL-Kommentare in @stmt haben am Ende
300 weder Newline noch Semikolon. Diese Methode fügt sie hinzu
301 und konkateniert alle Statements zu einer Zeichenkette.
302  
303 Folgende Manipulationen werden vorgenommen:
304  
305 =over 2
306  
307 =item *
308  
309 SQL-Statements erhalten am Ende ein Semikolon und ein Newline.
310  
311 =item *
312  
313 Kommentare erhalten am Ende ein Newline und werden von den umgebenden
314 SQL-Statements abgesetzt, indem vor und nach ihnen eine Leerzeile
315 eingefügt wird.
316  
317 =back
318  
319 Diverse Details werden unterschieden (siehe EXAMPLES).
320  
321 =head4 Example
322  
323 So verhält es sich im Detail:
324  
325 $script = Quiq::Sql->stmtListToScript(
326 '-- TEXT1',
327 'STMT1',
328 "STMT2\n...',
329 "STMT3 (\n....\n)",
330 '-- TEXT2',
331 'STMT4',
332 '-- eof',
333 );
334  
335 wird zu:
336  
337 -- TEXT1 Kommentar am Anfang => danach "\n\n"
338
339 STMT1; einzeiliges Statement => danach ";\n\n")
340
341 STMT2 mehrzeilges Statement => danach "\n;\n")
342 ...
343 ;
344 STMT3 ( mehrzeiles Statement mit ) => danach ";\n")
345 ...
346 );
347
348 -- TEXT2 innerer Kommentar => davor "\n", danach "\n\n"
349
350 STMT4; (wie einzeiliges Statement oben)
351
352 -- eof Kommentar am Ende, nach einzeiligem Statement
353 => davor nichts, danach "\n"
354  
355 =cut
356  
357 # -----------------------------------------------------------------------------
358  
359 0 ▶sub stmtListToScript {
Subroutine stmtListToScript: not called CC=3 SCAR=24.8
Pod documented
360 0 my $this = shift;
361 0 my @stmt = @_;
362  
363 # Kommentare nachbearbeiten und Statement-Trenner hinzufügen
364 # 1. Leerzeile vor und hinter jeden Kommentar
365 # 2. Erste Zeile kein \n am Anfang und nur ein \n am Ende
366  
367 0 ▶ for (my $i = 0; $i < @stmt; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @stmt) 0 0 0
368 0 ▶ if (substr($stmt[$i],0,2) eq '--') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($stmt[$i], 0, 2) eq '--') { } 0 0 0
369 0 $stmt[$i] .= "\n\n";
370 }
371 else {
372 0 $stmt[$i] .= ";\n\n";
373 }
374 }
375 0 $stmt[-1] =~ s/\n+$/\n/;
376  
377 0 return join('',@stmt);
378 }
379  
380 # -----------------------------------------------------------------------------
381  
382 =head2 Commands
383  
384 =head3 commands() - Liste der Kommandos des DBMS
385  
386 =head4 Synopsis
387  
388 @commands | $commandA = $sql->commands;
389  
390 =cut
391  
392 # -----------------------------------------------------------------------------
393  
394 6 my %Commands = (
395 Oracle => [
396 ],
397 PostgreSQL => [
398 'ABORT',
399 'ALTER',
400 'ANALYZE',
401 'BEGIN',
402 'CALL',
403 'CHECKPOINT',
404 'CLOSE',
405 'CLUSTER',
406 'COMMENT',
407 'COMMIT',
408 'COPY',
409 'CREATE',
410 'DEALLOCATE',
411 'DECLARE',
412 'DELETE',
413 'DISCARD',
414 'DO',
415 'DROP',
416 'END',
417 'EXECUTE',
418 'EXPLAIN',
419 'FETCH',
420 'GRANT',
421 'IMPORT FOREIGN SCHEMA',
422 'INSERT',
423 'LISTEN',
424 'LOAD',
425 'LOCK',
426 'MOVE',
427 'NOTIFY',
428 'PREPARE',
429 'REASSIGN OWNED',
430 'REFRESH MATERIALIZED VIEW',
431 'REINDEX',
432 'RELEASE SAVEPOINT',
433 'ROLLBACK',
434 'SAVEPOINT',
435 'SECURITY LABEL',
436 'SELECT',
437 'SET',
438 'SHOW',
439 'START TRANSACTION',
440 'TRUNCATE',
441 'UNLISTEN',
442 'UPDATE',
443 'VACUUM',
444 'VALUES',
445 ],
446 SQLite => [
447 ],
448 MySQL => [
449 ],
450 Access => [
451 ],
452 MSSQL => [
453 ],
454 JDBC => [
455 ],
456 );
457  
458 0 ▶sub commands {
Subroutine commands: not called CC=3 SCAR=24.8
Pod documented
459 0 my $self = shift;
460  
461 0 my $dbms = $self->{'dbms'};
462 0 my $cmdA = $Commands{$dbms};
463 0 ▶ if (!@$cmdA) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$cmdA) 0 0 0
464 0 $self->throw(
465 'SQL-00099: No commands defined for DBMS',
466 Dbms => $dbms,
467 );
468 }
469  
470 0 ▶ return wantarray? @$cmdA: $cmdA;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
471 }
472  
473 # -----------------------------------------------------------------------------
474  
475 =head2 Data Types
476  
477 Methoden für die portable Spezifikation von Kolumnen-Datentypen.
478  
479 =head3 dataType() - Wandele portablen Datentyp-Bezeichner in DBMS-Typ-Bezeichner
480  
481 =head4 Synopsis
482  
483 $dbmsType = $sql->dataType($portableType);
484 ($dbmsType,$args) = $sql->dataType($portableType);
485  
486 =head4 Description
487  
488 Wandele den portablen Datentyp $portableType in den entsprechenden
489 DBMS-spezifischen Typ und liefere diesen zurück. Im Skalarkontext
490 liefere den Typbezeichner einschließlich etwaiger Argumente,
491 im Listkontext liefere Typ und Argumente getrennt.
492  
493 B<Typ-Abbildung>
494  
495 Portabel Oracle PostgreSQL SQLite MySQL
496 ---------- ---------- ---------- --------- ----------
497 STRING VARCHAR2 VARCHAR TEXT VARCHAR
498 TEXT CLOB TEXT TEXT LONGTEXT
499 INTEGER NUMBER NUMERIC INTEGER (TINY|SMALL|MEDIUM|BIG)INT
500 REAL NUMBER NUMERIC REAL DECIMAL
501 DATETIME TIMESTAMP TIMESTAMP TIMESTAMP TIMESTAMP
502 BLOB BLOB BYTEA BLOB LONGBLOB
503  
504 =over 2
505  
506 =item *
507  
508 VARCHAR2 kann bei Oracle max 4000 Zeichen lang sein
509  
510 =back
511  
512 =head4 Example
513  
514 Einige Konvertierungen im Falle von Oracle:
515  
516 $type = $sql->dataType('STRING');
517 # => 'VARCHAR2'
518
519 $type = $sql->dataType('STRING(20)');
520 # => 'VARCHAR2(20)'
521
522 ($type,$args) = $sql->dataType('STRING');
523 # => ('VARCHAR2','')
524
525 ($type,$args) = $sql->dataType('STRING(20)');
526 # => ('VARCHAR2','(20)')
527
528 ($type,$args) = $sql->dataType('DATETIME');
529 # => ('TIMESTAMP','(0)')
530  
531 =cut
532  
533 # -----------------------------------------------------------------------------
534  
535 6 my %DataType = (
536 Oracle => {
537 STRING => 'VARCHAR2',
538 TEXT => 'CLOB',
539 INTEGER => 'NUMBER',
540 REAL => 'NUMBER',
541 DATETIME => 'TIMESTAMP',
542 BLOB => 'BLOB',
543 },
544 PostgreSQL => {
545 STRING => 'VARCHAR',
546 TEXT => 'TEXT',
547 INTEGER => 'NUMERIC',
548 REAL => 'NUMERIC',
549 DATETIME => 'TIMESTAMP',
550 BLOB => 'BYTEA',
551 },
552 SQLite => {
553 STRING => 'TEXT',
554 TEXT => 'TEXT',
555 INTEGER => 'INTEGER',
556 REAL => 'REAL',
557 DATETIME => 'TIMESTAMP',
558 BLOB => 'BLOB',
559 },
560 MySQL => {
561 STRING => 'VARCHAR',
562 TEXT => 'LONGTEXT',
563 INTEGER => 'BIGINT',
564 REAL => 'DECIMAL',
565 DATETIME => 'TIMESTAMP',
566 BLOB => 'LONGBLOB',
567 },
568 Access => {
569 STRING => 'TEXT',
570 TEXT => 'MEMO',
571 INTEGER => 'LONG',
572 REAL => 'DOUBLE',
573 DATETIME => 'DATETIME',
574 BLOB => 'LONGBINARY',
575 },
576 MSSQL => {
577 # FIXME: Ungeprüft
578 STRING => 'TEXT',
579 TEXT => 'MEMO',
580 INTEGER => 'LONG',
581 REAL => 'DOUBLE',
582 DATETIME => 'DATETIME',
583 BLOB => 'LONGBINARY',
584 },
585 JDBC => {
586 # FIXME: Ungeprüft
587 STRING => 'TEXT',
588 TEXT => 'MEMO',
589 INTEGER => 'LONG',
590 REAL => 'DOUBLE',
591 DATETIME => 'DATETIME',
592 BLOB => 'LONGBINARY',
593 },
594 );
595  
596 100 ▶sub dataType {
Subroutine dataType: called CC=20 SCAR=30.4
Pod documented
597 100 my ($self,$portableType) = @_;
598  
599 # Typ-Argumente abschneiden, falls vorhanden.
600 # Mögliche Erweiterung: Argumente auswerten und bei DBMS-Typ
601 # berücksichtigen.
602  
603 100 $portableType =~ s/(\(([\d,]+)\))//;
604 100 ▶ my $args = $1 || '';
Condition100%2/2
$1 || ''
l!l
5644
MC/DC100%1/1
$1 || ''
$1
Truth table100%2/2
A
A= $1
Aresult
11
00
605 100 ▶ my $argVal = $2 || 0;
Condition100%2/2
$2 || 0
l!l
5644
MC/DC100%1/1
$2 || 0
$2
Truth table100%2/2
A
A= $2
Aresult
11
00
606  
607 100 my $dbms = $self->{'dbms'};
608 100 ▶ if (!exists $DataType{$dbms}{$portableType}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $DataType{$dbms}{$portableType}) 14 86 100
609 14 $self->throw(
610 'SQL-00003: Unbekannter Datentyp',
611 Type => $portableType,
612 );
613 }
614  
615 86 my $dbmsType = $DataType{$dbms}{$portableType};
616 86 ▶ unless ($dbmsType) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbmsType) 0 86 86
617 0 $self->throw(
618 'SQL-00004: Datentyp von DBMS nicht unterstützt',
619 Dbms => $dbms,
620 Type => $portableType,
621 );
622 }
623  
624 86 ▶ if ($self->isPostgreSQL) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->isPostgreSQL) { } 8 78 86
elsif ($self->isSQLite) { } 43 35 78
elsif ($self->isMySQL) { } 8 27 35
625 8 ▶ if ($portableType eq 'REAL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($portableType eq "REAL") 1 7 8
626 1 $args = ''; # Nachkommastellen werden sonst mit 0en aufgefüllt
627 }
628 }
629 elsif ($self->isSQLite) {
630 43 ▶ if ($portableType eq 'INTEGER') {
Branch: 1 branch
BranchTrueFalseTotal
if ($portableType eq "INTEGER") 20 23 43
631 20 $args = ''; # da AUTOINCREMENT nur INTEGER erlaubt
632 }
633 }
634 elsif ($self->isMySQL) {
635 8 ▶ if ($portableType eq 'INTEGER') {
Branch: 1 branch
BranchTrueFalseTotal
if ($portableType eq "INTEGER") 3 5 8
636 3 ▶ if ($argVal == 0) {
Branch: 5 branches
BranchTrueFalseTotal
if ($argVal == 0) { } 1 2 3
elsif ($argVal <= 2) { } 0 2 2
elsif ($argVal <= 4) { } 1 1 2
elsif ($argVal <= 6) { } 0 1 1
elsif ($argVal <= 9) { } 0 1 1
637 1 $dbmsType = 'BIGINT';
638 }
639 elsif ($argVal <= 2) {
640 0 $dbmsType = 'TINYINT';
641 }
642 elsif ($argVal <= 4) {
643 1 $dbmsType = 'SMALLINT';
644 }
645 elsif ($argVal <= 6) {
646 0 $dbmsType = 'MEDIUMINT';
647 }
648 elsif ($argVal <= 9) {
649 0 $dbmsType = 'INT';
650 }
651 else {
652 1 $dbmsType = 'BIGINT';
653 }
654 3 $args = '';
655 }
656 }
657  
658 86 ▶ if ($args eq '' && $portableType eq 'DATETIME' &&
Branch: 1 branch
BranchTrueFalseTotal
if ($args eq "" and $portableType eq "DATETIME" and $dbmsType eq "TIMESTAMP") 1 85 86
Condition83%5/6
$args eq "" and $portableType eq "DATETIME" and $dbmsType eq "TIMESTAMP"
!ll&&!rl&&r
8501
$args eq "" and $portableType eq "DATETIME"
!ll&&!rl&&r
39461
MC/DC66%2/3
$args eq "" and $portableType eq "DATETIME" and $dbmsType eq "TIMESTAMP"
$args eq "" $portableType eq "DATETIME" $dbmsType eq "TIMESTAMP"
Truth table75%3/4
A and B and C
A= $args eq ""B= $portableType eq "DATETIME"C= $dbmsType eq "TIMESTAMP"
ABCresult
0XX0
10X0
1100
1111
659 $dbmsType eq 'TIMESTAMP') {
660 1 $args = '(0)';
661 }
662  
663 86 ▶ return wantarray? ($dbmsType,$args): "$dbmsType$args";
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 35 51 86
664 }
665  
666 # -----------------------------------------------------------------------------
667  
668 =head3 columnDef() - Generiere Kolumnen-Definition
669  
670 =head4 Synopsis
671  
672 $colDef = $sql->columnDef(@colDef);
673 $colDef = $sql->columnDef($portableType,@colDef);
674  
675 =head4 Description
676  
677 Generiere aus der portablen Kolumnen-Spezifikation @colDef eine
678 DBMS-spezifische Kolumnen-Definition, die als Zeichenkette
679 nach dem Kolumnennamen in ein CREATE TABLE oder ALTER TABLE Statement
680 eingesetzt werden kann, und liefere diese zurück.
681  
682 Die Methode wird von den Methoden createTable() und addColumn()
683 genutzt.
684  
685 Die Kolumnen-Spezifikation @colDef besteht aus einer
686 nicht-leeren Aufzählung von folgenden Schlüssel/Wert-Paaren:
687  
688 =over 4
689  
690 =item default => $value
691  
692 Defaultwert der Kolumne.
693  
694 =item null => $bool
695  
696 Kolumne ist kein Pflichtfeld. Diese explizite Setzung wird bei
697 MySQL gebraucht, wenn ein TIMESTAMP-Feld nicht
698 '0000-00-00 00:00:00' als Defaultwert erhalten soll.
699  
700 =item notNull => $bool
701  
702 Kolumne ist Pflichtfeld.
703  
704 =item autoIncrement => $bool
705  
706 Das DBMS erzeugt beim Einfügen eines Datensatzes einen
707 eindeutigen Wert (SQLite und MySQL).
708  
709 =item primaryKey => $bool
710  
711 Kolumne ist Primärschlüsselkolumne.
712  
713 =item type => $type
714  
715 Portabler Kolumnentyp.
716  
717 =item oracleType => $oracleType
718  
719 Kolumnentyp für Oracle.
720  
721 =item postgresqlType => $postgresqlType
722  
723 Kolumnentyp für PostgreSQL.
724  
725 =item sqliteType => $sqliteType
726  
727 Kolumnentyp für SQLite.
728  
729 =item mysqlType => $mysqlType
730  
731 Kolumnentyp für MySQL.
732  
733 =back
734  
735 Der Kolumnentyp ist für eine Kolumnenspezifikation zwingend. Er
736 wird als portabler Typ (type=>$type) oder als DBMS-spezifischer
737 Typ (<dbms>Type=>$type) angegeben. Ist beides angegeben, hat der
738 DBMS-spezifische Typ Vorrang.
739  
740 Das Attribut autoIncrement ist nicht portabel, es ist
741  
742 =head4 Example
743  
744 =over 2
745  
746 =item *
747  
748 Portabler Typ wird verwendet, wenn nichts anderes
749 für das DBMS angegeben ist:
750  
751 $sql = Quiq::Sql->new('Oracle');
752 $type = $sql->columnDef(
753 type => 'STRING(20)',
754 );
755 ==>
756 'VARCHAR2(20)'
757  
758 =item *
759  
760 DBMS-Typ wird verwendet, wenn angegeben:
761  
762 $sql = Quiq::Sql->new('Oracle');
763 $type = $sql->columnDef(
764 type => 'INTEGER(5)',
765 oracleType => 'NUMBER(5)',
766 );
767 ==>
768 'NUMBER(5)'
769  
770 =back
771  
772 =cut
773  
774 # -----------------------------------------------------------------------------
775  
776 46 ▶sub columnDef {
Subroutine columnDef: called CC=13 SCAR=25.7
Pod documented
777 46 my $self = shift;
778 # @_: @typeSpec
779  
780 46 my $keyVal = Quiq::Hash->new(
781 default => undef,
782 null => undef,
783 notNull => undef,
784 primaryKey => undef,
785 autoIncrement => undef, # unportabel, nicht Oracle und PostgreSQL
786 type => undef,
787 oracleType => undef,
788 postgresqlType => undef,
789 sqliteType => undef,
790 mysqlType => undef,
791 );
792 46 ▶ if (@_%2 == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ % 2 == 1) 3 43 46
793 3 unshift @_,'type';
794 }
795 46 $keyVal->set(@_);
796  
797 # Datentyp der Kolumne bestimmen
798  
799 46 my $dbms = lc $self->{'dbms'};
800 46 my $type = $keyVal->{"${dbms}Type"};
801 46 ▶ if (!$type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 45 1 46
802 45 ▶ if ($type = $keyVal->{'type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type = $keyVal->{"type"}) 44 1 45
803 44 $type = $self->dataType($type);
804 }
805 }
806 46 ▶ if (!$type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 1 45 46
807 1 $self->throw(
808 'SQL-00007: Kein Kolumnen-Typ für DBMS angegeben',
809 DBMS => $dbms,
810 );
811 }
812  
813 45 my $colDef = $type;
814  
815 # weitere, optionale Kolumnen-Attribute
816  
817 45 my $val;
818 45 ▶ if (defined($val = $keyVal->{'default'}) && $val ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($val = $keyVal->{"default"}) and $val ne "") 1 44 45
Condition66%2/3
defined($val = $keyVal->{"default"}) and $val ne ""
!ll&&!rl&&r
4401
MC/DC50%1/2
defined($val = $keyVal->{"default"}) and $val ne ""
defined($val = $keyVal->{"default"}) $val ne ""
Truth table66%2/3
A and B
A= defined($val = $keyVal->{"default"})B= $val ne ""
ABresult
0X0
100
111
819 1 $val = $self->valExpr($val);
820 1 $colDef .= " DEFAULT $val"; # FIXME: ggf. allgemeiner machen
821 }
822 45 ▶ if ($val = $keyVal->{'null'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val = $keyVal->{"null"}) 0 45 45
823 0 $colDef .= ' NULL';
824 }
825 45 ▶ if ($val = $keyVal->{'notNull'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val = $keyVal->{"notNull"}) 13 32 45
826 13 $colDef .= ' NOT NULL';
827 }
828 45 ▶ if ($val = $keyVal->{'primaryKey'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val = $keyVal->{"primaryKey"}) 13 32 45
829 13 $colDef .= ' PRIMARY KEY';
830 }
831 45 ▶ if ($val = $keyVal->{'autoIncrement'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val = $keyVal->{"autoIncrement"}) 9 36 45
832 9 ▶ if ($self->isMySQL) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->isMySQL) { } 1 8 9
elsif ($self->isSQLite) { } 6 2 8
833 1 $colDef .= ' AUTO_INCREMENT';
834 }
835 elsif ($self->isSQLite) {
836 6 $colDef .= ' AUTOINCREMENT';
837 }
838 # kein Autoinkrement bei Oracle und PostgreSQL
839 }
840  
841 45 return $colDef;
842 }
843  
844 # -----------------------------------------------------------------------------
845  
846 =head2 Comments
847  
848 =head3 comment() - Generiere SQL-Kommentar
849  
850 =head4 Synopsis
851  
852 $stmt = $sql->comment($text);
853  
854 =head4 Description
855  
856 Setze an den Anfang jeder Zeile in $text die Zeichenfolge '-- '
857 und liefert das Resultat zurück.
858  
859 Whitespace am Ende wird entfernt, d.h. der SQL-Kommentar endet
860 wie die SQL-Statements per Default nicht mit einem Newline.
861  
862 =head4 Example
863  
864 Lorem ipsum dolor sit amet, consetetur sadipscing
865 elitr, sed diam nonumy eirmod tempor invidunt ut
866 labore et dolore magna
867  
868 wird zu
869  
870 -- Lorem ipsum dolor sit amet, consetetur sadipscing
871 -- elitr, sed diam nonumy eirmod tempor invidunt ut
872 -- labore et dolore magna
873  
874 =cut
875  
876 # -----------------------------------------------------------------------------
877  
878 3 ▶sub comment {
Subroutine comment: called CC=3 SCAR=11.0
Pod documented
879 3 my $self = shift;
880 3 my $text = shift;
881  
882 3 ▶ if (!defined $text || $text eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $text or $text eq "") 1 2 3
Condition66%2/3
not defined $text or $text eq ""
l!l&&r!l&&!r
102
MC/DC50%1/2
not defined $text or $text eq ""
not defined $text $text eq ""
Truth table66%2/3
not(A) or B
A= not defined $textB= $text eq ""
ABresult
1X1
011
000
883 1 return '';
884 }
885  
886 2 $text =~ s/\s+$//;
887 2 $text =~ s/^/-- /gm;
888 2 $text =~ s/^-- $/--/gm;
889  
890 2 return $text;
891 }
892  
893 # -----------------------------------------------------------------------------
894  
895 =head2 Session
896  
897 =head3 setDateFormat() - Generiere Statements zum Setzen des Datumsformats
898  
899 =head4 Synopsis
900  
901 @stmt = $class->setDateFormat;
902 @stmt = $class->setDateFormat($format);
903  
904 =head4 Description
905  
906 Setze als Default-Datumsformat $format. Ist $format nicht angegeben,
907 setzte iso-Format.
908  
909 Folgende Datumsformate sind definiert:
910  
911 =over 4
912  
913 =item iso
914  
915 YYYY-MM-DD HH:MM:SS
916  
917 =back
918  
919 B<Oracle>
920  
921 (iso)
922 ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
923 ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SSXFF'
924  
925 B<PostgreSQL>
926  
927 (iso)
928 SET datestyle TO iso, ymd
929  
930 B<SQLite>
931  
932 unbekannt
933  
934 B<MySQL>
935  
936 unbekannt
937  
938 =cut
939  
940 # -----------------------------------------------------------------------------
941  
942 12 ▶sub setDateFormat {
Subroutine setDateFormat: called CC=11 SCAR=36.9
Pod documented
943 12 my $self = shift;
944 12 ▶ my $format = shift || 'iso';
Condition50%1/2
shift() || 'iso'
l!l
012
MC/DC0%0/1
shift() || 'iso'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
945  
946 12 my ($oracle,$postgresql,$sqlite,$mysql,$access,$mssql,$jdbc) =
947 $self->dbmsTestVector;
948  
949 # Statement generieren
950  
951 12 my @stmt;
952 12 ▶ if ($oracle) {
Branch: 3 branches
BranchTrueFalseTotal
if ($oracle) { } 0 12 12
elsif ($postgresql) { } 0 12 12
elsif ($sqlite or $mysql or $access or $mssql or $jdbc) { } 12 0 12
953 0 ▶ if ($format eq 'iso') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "iso") 0 0 0
954 0 my $dateFmt = 'YYYY-MM-DD HH24:MI:SS';
955 0 my $timestampFmt = 'YYYY-MM-DD HH24:MI:SSXFF';
956 0 return ("ALTER SESSION SET NLS_DATE_FORMAT = '$dateFmt'",
957 "ALTER SESSION SET NLS_TIMESTAMP_FORMAT = '$timestampFmt'");
958 }
959 }
960 elsif ($postgresql) {
961 0 ▶ if ($format eq 'iso') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "iso") 0 0 0
962 0 return ('SET datestyle TO iso, ymd');
963 }
964 }
965 ▶ elsif ($sqlite || $mysql || $access || $mssql || $jdbc) {
Condition33%4/12
$sqlite or $mysql or $access or $mssql or $jdbc
l!l&&r!l&&!r
1200
$sqlite or $mysql or $access or $mssql
l!l&&r!l&&!r
1200
$sqlite or $mysql or $access
l!l&&r!l&&!r
1200
$sqlite or $mysql
l!l&&r!l&&!r
1200
MC/DC0%0/5
$sqlite or $mysql or $access or $mssql or $jdbc
$sqlite $mysql $access $mssql $jdbc
Truth table16%1/6
A or B or C or D or E
A= $sqliteB= $mysqlC= $accessD= $mssqlE= $jdbc
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
966 12 return; # FIXME: bislang nicht untersucht
967 }
968  
969 0 $self->throw('Not implemented');
970 }
971  
972 # -----------------------------------------------------------------------------
973  
974 =head3 setNumberFormat() - Generiere Statements zum Setzen des Zahlenformats
975  
976 =head4 Synopsis
977  
978 @stmt = $class->setNumberFormat;
979 @stmt = $class->setNumberFormat($format);
980  
981 =head4 Description
982  
983 Setze als Default-Zahlenformat $format. Ist $format nicht angegeben,
984 setzte angloamerikanisches Format.
985  
986 B<Oracle>
987  
988 ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '.,'
989  
990 B<PostgreSQL>
991  
992 unbekannt
993  
994 B<SQLite>
995  
996 unbekannt
997  
998 B<MySQL>
999  
1000 unbekannt
1001  
1002 =cut
1003  
1004 # -----------------------------------------------------------------------------
1005  
1006 # FIXME: (1) portable Lösung, (2) eventuell alle Setzungen in einem
1007 # Aufruf zusammenfassen
1008  
1009 12 ▶sub setNumberFormat {
Subroutine setNumberFormat: called CC=9 SCAR=30.1
Pod documented
1010 12 my $self = shift;
1011 12 ▶ my $format = shift || '.,';
Condition50%1/2
shift() || '.,'
l!l
012
MC/DC0%0/1
shift() || '.,'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1012  
1013 12 my ($oracle,$postgresql,$sqlite,$mysql,$access,$mssql,$jdbc) =
1014 $self->dbmsTestVector;
1015  
1016 # Statement generieren
1017  
1018 12 my @stmt;
1019 12 ▶ if ($oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle) { } 0 12 12
elsif ($postgresql or $sqlite or $mysql or $access or $mssql or $jdbc) { } 12 0 12
1020 0 return ("ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '$format'");
1021 }
1022 ▶ elsif ($postgresql || $sqlite || $mysql || $access || $mssql || $jdbc) {
Condition33%5/15
$postgresql or $sqlite or $mysql or $access or $mssql or $jdbc
l!l&&r!l&&!r
1200
$postgresql or $sqlite or $mysql or $access or $mssql
l!l&&r!l&&!r
1200
$postgresql or $sqlite or $mysql or $access
l!l&&r!l&&!r
1200
$postgresql or $sqlite or $mysql
l!l&&r!l&&!r
1200
$postgresql or $sqlite
l!l&&r!l&&!r
0120
MC/DC0%0/6
$postgresql or $sqlite or $mysql or $access or $mssql or $jdbc
$postgresql $sqlite $mysql $access $mssql $jdbc
Truth table14%1/7
A or B or C or D or E or F
A= $postgresqlB= $sqliteC= $mysqlD= $accessE= $mssqlF= $jdbc
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
1023 12 return; # FIXME: bislang nicht untersucht
1024 }
1025  
1026 0 $self->throw('Not implemented');
1027 }
1028  
1029 # -----------------------------------------------------------------------------
1030  
1031 =head3 setSchema() - Generiere Statement zum Setzen des aktuellen Schema
1032  
1033 =head4 Synopsis
1034  
1035 $class->setSchema($schema);
1036  
1037 =head4 Description
1038  
1039 B<Oracle>
1040  
1041 ALTER SESSION SET CURRENT_SCHEMA = <schema>
1042  
1043 B<PostgreSQL>
1044  
1045 SET search_path TO <schema>
1046  
1047 =over 2
1048  
1049 =item *
1050  
1051 Anstelle eines einzelnen Schema können mehrere Schemata, mit Komma
1052 getrennt, aufgezählt werden.
1053  
1054 =item *
1055  
1056 Die Setzung sollte sofort mit COMMIT bestätigt werden, da
1057 sie im Falle eines ROLLBACK sonst verfällt.
1058  
1059 =back
1060  
1061 B<SQLite>
1062  
1063 <leer>
1064  
1065 SQLite hat das Konzept mehrerer Schemata, von denen eins das
1066 Default-Schema ist, nicht.
1067  
1068 Bei einer SQLite-Datenbank gibt es per Default keinen Schema-Präfix,
1069 dieser wird erst durch ATTACH einer Datenbank eingeführt.
1070  
1071 Ein Tabellenname ohne Schema wird immer über allen Attachten Datenbanken
1072 aufgelöst. Die zuerst hinzugefügte Tabelle ist der Dafault.
1073  
1074 B<MySQL>
1075  
1076 USE <schema>
1077  
1078 =cut
1079  
1080 # -----------------------------------------------------------------------------
1081  
1082 0 ▶sub setSchema {
Subroutine setSchema: not called CC=5 SCAR=34.0
Pod documented
1083 0 my $self = shift;
1084 0 my $schema = shift;
1085  
1086 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1087  
1088 # Statement generieren
1089  
1090 0 my $stmt;
1091 0 ▶ if ($oracle) {
Branch: 4 branches
BranchTrueFalseTotal
if ($oracle) { } 0 0 0
elsif ($postgresql) { } 0 0 0
elsif ($sqlite) { } 0 0 0
elsif ($mysql) { } 0 0 0
1092 0 $stmt = "ALTER SESSION SET CURRENT_SCHEMA = $schema";
1093 }
1094 elsif ($postgresql) {
1095 0 $stmt = "SET search_path TO $schema";
1096 }
1097 elsif ($sqlite) {
1098 0 $stmt = '';
1099 }
1100 elsif ($mysql) {
1101 0 $stmt = "USE $schema";
1102 }
1103 else {
1104 0 $self->throw('Not implemented');
1105 }
1106  
1107 0 return $stmt;
1108 }
1109  
1110 # -----------------------------------------------------------------------------
1111  
1112 =head3 setSearchPath() - Generiere Statement zum Setzen des Search Path
1113  
1114 =head4 Synopsis
1115  
1116 $stmt = $class->setSearchPath(@schemas);
1117  
1118 =head4 Description
1119  
1120 B<Oracle>
1121  
1122 <not implemented>
1123  
1124 B<PostgreSQL>
1125  
1126 SET search_path TO SCHEMA, ...
1127  
1128 B<SQLite>
1129  
1130 <not implemented>
1131  
1132 B<MySQL>
1133  
1134 <not implemented>
1135  
1136 =cut
1137  
1138 # -----------------------------------------------------------------------------
1139  
1140 0 ▶sub setSearchPath {
Subroutine setSearchPath: not called CC=5 SCAR=34.0
Pod documented
1141 0 my ($self,@schemas) = @_;
1142  
1143 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1144  
1145 # Statement generieren
1146  
1147 0 my $stmt;
1148 0 ▶ if ($oracle) {
Branch: 4 branches
BranchTrueFalseTotal
if ($oracle) { } 0 0 0
elsif ($postgresql) { } 0 0 0
elsif ($sqlite) { } 0 0 0
elsif ($mysql) { } 0 0 0
1149 0 $self->throw('Not implemented');
1150 }
1151 elsif ($postgresql) {
1152 0 $stmt = sprintf 'SET search_path TO %s',join(', ',@schemas);
1153 }
1154 elsif ($sqlite) {
1155 0 $self->throw('Not implemented');
1156 }
1157 elsif ($mysql) {
1158 0 $self->throw('Not implemented');
1159 }
1160 else {
1161 0 $self->throw('Not implemented');
1162 }
1163  
1164 0 return $stmt;
1165 }
1166  
1167 # -----------------------------------------------------------------------------
1168  
1169 =head3 setEncoding() - Generiere Statement zum Setzen des Client-Encodings
1170  
1171 =head4 Synopsis
1172  
1173 $stmt = $class->setEncoding($charset);
1174  
1175 =head4 Description
1176  
1177 Werte für $charset:
1178  
1179 iso-8859-1
1180 utf-8
1181  
1182 B<Oracle>
1183  
1184 <not implemented>
1185  
1186 B<PostgreSQL>
1187  
1188 SET client_encoding TO <charset>
1189  
1190 B<SQLite>
1191  
1192 <not implemented>
1193  
1194 B<MySQL>
1195  
1196 <not implemented>
1197  
1198 =cut
1199  
1200 # -----------------------------------------------------------------------------
1201  
1202 0 ▶sub setEncoding {
Subroutine setEncoding: not called CC=7 SCAR=40.3
Pod documented
1203 0 my ($self,$charset) = @_;
1204  
1205 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1206  
1207 # Statement generieren
1208  
1209 0 my $stmt;
1210 0 ▶ if ($oracle) {
Branch: 4 branches
BranchTrueFalseTotal
if ($oracle) { } 0 0 0
elsif ($postgresql) { } 0 0 0
elsif ($sqlite) { } 0 0 0
elsif ($mysql) { } 0 0 0
1211 0 $self->throw('Not implemented');
1212 }
1213 elsif ($postgresql) {
1214 0 ▶ if ($charset eq 'iso-8859-1') {
Branch: 2 branches
BranchTrueFalseTotal
if ($charset eq 'iso-8859-1') { } 0 0 0
elsif ($charset eq 'utf-8') { } 0 0 0
1215 0 $charset = 'latin1';
1216 }
1217 elsif ($charset eq 'utf-8') {
1218 0 $charset = 'utf8';
1219 }
1220 0 $stmt = "SET client_encoding TO $charset";
1221 }
1222 elsif ($sqlite) {
1223 0 $self->throw('Not implemented');
1224 }
1225 elsif ($mysql) {
1226 0 $self->throw('Not implemented');
1227 }
1228 else {
1229 0 $self->throw('Not implemented');
1230 }
1231  
1232 0 return $stmt;
1233 }
1234  
1235 # -----------------------------------------------------------------------------
1236  
1237 =head2 Locking
1238  
1239 =head3 lockTable() - Generiere LOCK TABLE Statement
1240  
1241 =head4 Synopsis
1242  
1243 $stmt = $class->lockTable($table);
1244  
1245 =head4 Description
1246  
1247 B<Oracle>
1248  
1249 LOCK TABLE <table> IN EXCLUSIVE MODE NOWAIT
1250  
1251 B<PostgreSQL>
1252  
1253 LOCK TABLE <table> IN EXCLUSIVE MODE NOWAIT
1254  
1255 B<SQLite>
1256  
1257 nicht implementiert
1258  
1259 B<MySQL>
1260  
1261 nicht implementiert
1262  
1263 =cut
1264  
1265 # -----------------------------------------------------------------------------
1266  
1267 0 ▶sub lockTable {
Subroutine lockTable: not called CC=3 SCAR=24.8
Pod documented
1268 0 my ($self,$table) = @_;
1269  
1270 # Statement generieren
1271  
1272 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1273  
1274 0 ▶ if ($oracle || $postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql) 0 0 0
Condition0%0/3
$oracle or $postgresql
l!l&&r!l&&!r
000
MC/DC0%0/2
$oracle or $postgresql
$oracle $postgresql
Truth table0%0/3
A or B
A= $oracleB= $postgresql
ABresult
1X1
011
000
1275 0 return "LOCK TABLE $table IN EXCLUSIVE MODE NOWAIT";
1276 }
1277  
1278 0 $self->throw('Not implemented');
1279 }
1280  
1281 # -----------------------------------------------------------------------------
1282  
1283 =head2 User
1284  
1285 =head3 createUser() - Generiere CREATE USER Statement
1286  
1287 =head4 Synopsis
1288  
1289 $stmt = $class->createUser($name,$password,@opt);
1290  
1291 =head4 Options
1292  
1293 =over 4
1294  
1295 =item -defaultTableSpace => $name (Default: keiner)
1296  
1297 Name des Default-Tablespace
1298  
1299 =item -tempTableSpace => $name (Default: keiner)
1300  
1301 Name des Temporary-Tablespace
1302  
1303 =back
1304  
1305 =cut
1306  
1307 # -----------------------------------------------------------------------------
1308  
1309 1 ▶sub createUser {
Subroutine createUser: called CC=5 SCAR=16.5
Pod documented
1310 1 my $self = shift;
1311 1 my $name = shift;
1312 1 my $password = shift;
1313  
1314 # Optionen
1315  
1316 1 my $defaultTableSpace = undef;
1317 1 my $tempTableSpace = undef;
1318  
1319 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 0 1
1320 1 Quiq::Option->extract(\@_,
1321 -defaultTableSpace => \$defaultTableSpace,
1322 -tempTableSpace => \$tempTableSpace,
1323 );
1324 }
1325  
1326 # Statement generieren
1327  
1328 1 my $stmt;
1329  
1330 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1331  
1332 1 ▶ if ($oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle) { } 1 0 1
1333 1 $stmt = "CREATE USER $name\n".
1334 " IDENTIFIED BY $password";
1335  
1336 1 ▶ if ($defaultTableSpace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($defaultTableSpace) 1 0 1
1337 1 $stmt .= "\n DEFAULT TABLESPACE $defaultTableSpace";
1338 }
1339 1 ▶ if ($tempTableSpace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tempTableSpace) 1 0 1
1340 1 $stmt .= "\n TEMPORARY TABLESPACE $tempTableSpace";
1341 }
1342 }
1343 else {
1344 0 die;
1345 }
1346  
1347 1 return $stmt;
1348 }
1349  
1350 # -----------------------------------------------------------------------------
1351  
1352 =head2 Schema
1353  
1354 =head3 createSchema() - Generiere CREATE SCHEMA Statement
1355  
1356 =head4 Synopsis
1357  
1358 $stmt = $class->createSchema($name);
1359  
1360 =cut
1361  
1362 # -----------------------------------------------------------------------------
1363  
1364 1 ▶sub createSchema {
Subroutine createSchema: called CC=2 SCAR=7.1
Pod documented
1365 1 my $self = shift;
1366 1 my $name = shift;
1367  
1368 # Statement generieren
1369  
1370 1 my $stmt;
1371  
1372 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1373  
1374 1 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) { } 1 0 1
1375 1 $stmt = "CREATE SCHEMA $name";
1376 }
1377 else {
1378 0 die;
1379 }
1380  
1381 1 return $stmt;
1382 }
1383  
1384 # -----------------------------------------------------------------------------
1385  
1386 =head3 dropSchema() - Generiere DROP SCHEMA Statement
1387  
1388 =head4 Synopsis
1389  
1390 $stmt = $class->dropSchema($name);
1391  
1392 =cut
1393  
1394 # -----------------------------------------------------------------------------
1395  
1396 1 ▶sub dropSchema {
Subroutine dropSchema: called CC=3 SCAR=11.8
Pod documented
1397 1 my $self = shift;
1398 1 my $name = shift;
1399  
1400 # Statement generieren
1401  
1402 1 my $stmt;
1403  
1404 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1405  
1406 1 ▶ if ($oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle) { } 0 1 1
elsif ($postgresql) { } 1 0 1
1407 0 $stmt = "DROP USER $name CASCADE";
1408 }
1409 elsif ($postgresql) {
1410 1 $stmt = "DROP SCHEMA $name CASCADE";
1411 }
1412 else {
1413 0 die;
1414 }
1415  
1416 1 return $stmt;
1417 }
1418  
1419 # -----------------------------------------------------------------------------
1420  
1421 =head2 Table
1422  
1423 =head3 splitTableName() - Zerlege Tabellennamen
1424  
1425 =head4 Synopsis
1426  
1427 ($schema,$table) = $class->splitTableName($name);
1428 ($schema,$table) = $class->splitTableName($name,$sloppy);
1429  
1430 =head4 Alias
1431  
1432 splitTablename()
1433  
1434 =head4 Description
1435  
1436 Zerlege den Tabellennamen $name in die Komponenten $schema und $table.
1437 Besitzt der Tabellennamen keinen Schema-Präfix, wird eine Exception
1438 geworfen. Dies geschieht nicht, wenn der Parameter $sloppy gesetzt
1439 und wahr ist. In dem Fall wird keine Exception geworfen, sondern als
1440 Schemaname C<undef> geliefert.
1441  
1442 =cut
1443  
1444 # -----------------------------------------------------------------------------
1445  
1446 3 ▶sub splitTableName {
Subroutine splitTableName: called CC=3 SCAR=11.0
Pod documented
1447 3 my ($class,$name,$sloppy) = @_;
1448  
1449 3 my ($schema,$table) = split /\./,$name;
1450 3 ▶ if (!$table) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($table) 2 1 3
1451 2 ▶ if (!$sloppy) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sloppy) 1 1 2
1452 1 $class->throw(
1453 'SQL-00099: Tablename without schema prefix',
1454 Tablename => $name,
1455 );
1456 }
1457 1 $table = $schema;
1458 1 $schema = undef;
1459 }
1460  
1461 2 return ($schema,$table);
1462 }
1463  
1464 {
1465 6 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
1466 6 *splitTablename = \&splitTableName;
1467 }
1468  
1469 # -----------------------------------------------------------------------------
1470  
1471 =head3 createTable() - Generiere CREATE TABLE Statement
1472  
1473 =head4 Synopsis
1474  
1475 $stmt = $sql->createTable($table,
1476 [$colName,@colDef],
1477 ...
1478 @opt,
1479 );
1480  
1481 =head4 Options
1482  
1483 =over 4
1484  
1485 =item -check => \@expr
1486  
1487 Liste von CHECK-Contraints (Bedingungen).
1488  
1489 =item -reference => [[\@cols => $refTable,@opt], ...]
1490  
1491 Liste von Fremdschlüssel-Verweisen.
1492  
1493 =item -tableSpace => $tableSpaceName (Default: keiner)
1494  
1495 Name des Tablespace, in dem die Tabelle erzeugt wird
1496 (Oracle und PostgreSQL).
1497  
1498 =item -tableType => $tableType (Default: 'InnoDB')
1499  
1500 Tabellentyp bei MySQL: 'InnoDb', 'MyISAM'.
1501  
1502 =back
1503  
1504 =head4 Description
1505  
1506 Generiere ein CREATE TABLE Statement und liefere dieses zurück.
1507  
1508 Für jede Kolumne wird ihr Name $colName und ihr Typ.
1509  
1510 Der Kolumnentyp wird als portabler Typ (type=>$type)
1511 oder als DBMS-spezifischer Typ (<dbms>Type=>$type) angegeben.
1512 Ist beides angegeben, hat der DBMS-spezifische Typ Priorität.
1513 Für die portablen Typen siehe Methode columnType().
1514  
1515 Alle weiteren Angaben in @colOpts sind optional.
1516  
1517 Folgende Kolumnen-Optionen sind definiert:
1518  
1519 =over 4
1520  
1521 =item notNull => $bool
1522  
1523 Kolumne ist Pflichtfeld.
1524  
1525 =item autoIncrement => $bool
1526  
1527 Das DBMS erzeugt beim Einfügen eines Datensatzes einen
1528 eindeutigen Wert (nicht Oracle und PostgreSQL, diese
1529 haben das Konzept der Sequenz).
1530  
1531 =item primaryKey => $bool
1532  
1533 Kolumne ist Primärschlüsselkolumne.
1534  
1535 =item type => $type
1536  
1537 Portabler Kolumnentyp.
1538  
1539 =item oracleType => $oracleType
1540  
1541 Kolumnentyp für Oracle.
1542  
1543 =item postgresqlType => $postgresqlType
1544  
1545 Kolumnentyp für PostgreSQL.
1546  
1547 =item sqliteType => $sqliteType
1548  
1549 Kolumnentyp für SQLite.
1550  
1551 =item mysqlType => $mysqlType
1552  
1553 Kolumnentyp für MySQL.
1554  
1555 =back
1556  
1557 MySQL-Tabellen werden per Default als InnoDB-Tabellen erzeugt
1558 und erhalten als Zusatz die Angabe "TYPE = InnoDB". Der
1559 Tabellentyp kann mit der Option -tableType abweichend gesetzt werden.
1560  
1561 Die Typ-Attribute type und <dbms>Type werden von columnTypeSpec()
1562 in den DBMS-Typ umgewandelt.
1563  
1564 =cut
1565  
1566 # -----------------------------------------------------------------------------
1567  
1568 23 ▶sub createTable {
Subroutine createTable: called CC=13 SCAR=30.0
Pod documented
1569 23 my $self = shift;
1570 23 my $table = shift;
1571 # @_: @cols
1572  
1573 # Optionen
1574  
1575 23 my $checkA = [];
1576 23 my $referenceA = [];
1577 23 my $tableSpace = undef;
1578 23 my $tableType = 'InnoDB';
1579  
1580 23 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 23 0 23
1581 23 Quiq::Option->extract(-mode=>'sloppy',\@_,
1582 -check => \$checkA,
1583 -references => \$referenceA,
1584 -tableSpace => \$tableSpace,
1585 -tableType => \$tableType,
1586 );
1587 }
1588  
1589 # Statement generieren
1590  
1591 23 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1592  
1593 23 my $cols;
1594 23 for (@_) {
1595 36 my ($colName,@keyVal) = @$_;
1596 36 ▶ $cols .= $cols? "\n , ": ' ';
Branch: 1 branch
BranchTrueFalseTotal
$cols ? : 13 23 36
1597 36 $cols .= $colName.' '.$self->columnDef(@keyVal);
1598 }
1599  
1600 23 my $stmt = "CREATE TABLE $table (";
1601 23 ▶ if ($cols) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cols) 23 0 23
1602 23 $stmt .= "\n$cols\n";
1603 }
1604 23 ▶ if (@$checkA) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$checkA) 0 23 23
1605 0 for (@$checkA) {
1606 0 $stmt .= " , CHECK($_)\n";
1607 }
1608 }
1609 23 ▶ if (@$referenceA) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$referenceA) 0 23 23
1610 0 for (@$referenceA) {
1611 0 my $constr = $self->addForeignKeyConstraint($table,@$_);
1612 0 $constr =~ s/\s+/ /g;
1613 0 $constr =~ s/.*?(FOREIGN)/$1/;
1614 0 $stmt .= " , $constr\n";
1615 }
1616 }
1617 23 $stmt .= ')';
1618  
1619 23 ▶ if ($tableSpace && ($oracle || $postgresql)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tableSpace and $oracle || $postgresql) 0 23 23
Condition16%1/6
$tableSpace and $oracle || $postgresql
!ll&&!rl&&r
2300
$oracle or $postgresql
l!l&&r!l&&!r
000
MC/DC0%0/3
$tableSpace and $oracle || $postgresql
$tableSpace $oracle $postgresql
Truth table25%1/4
A and B or C
A= $tableSpaceB= $oracleC= $postgresql
ABCresult
0XX0
1000
11X1
1011
1620 0 $stmt .= "\nTABLESPACE $tableSpace";
1621 }
1622  
1623 # MySQL-Tabellen mit $tableType kreieren
1624  
1625 23 ▶ if ($mysql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mysql) 1 22 23
1626 # Ab MySQL 5.5 ist InnoDB die Default-Storage-Engine.
1627 # Das Schlüsselwort ist nicht mehr TYPE, sondern ENGINE.
1628 # $stmt .= "\nTYPE = $tableType";
1629 1 $stmt .= "\nENGINE = $tableType";
1630 }
1631  
1632 23 return $stmt;
1633 }
1634  
1635 # -----------------------------------------------------------------------------
1636  
1637 =head3 dropTable() - Generiere DROP TABLE Statement
1638  
1639 =head4 Synopsis
1640  
1641 $stmt = $sql->dropTable($table);
1642  
1643 =cut
1644  
1645 # -----------------------------------------------------------------------------
1646  
1647 15 ▶sub dropTable {
Subroutine dropTable: called CC=3 SCAR=12.0
Pod documented
1648 15 my $self = shift;
1649 15 my $table = shift;
1650  
1651 15 my $stmt = "DROP TABLE $table";
1652  
1653 15 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1654 15 ▶ if ($oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle) { } 0 15 15
elsif ($postgresql) { } 0 15 15
1655 0 $stmt .= ' CASCADE CONSTRAINTS';
1656 }
1657 elsif ($postgresql) {
1658 0 $stmt .= ' CASCADE';
1659 }
1660  
1661 15 return $stmt;
1662 }
1663  
1664 # -----------------------------------------------------------------------------
1665  
1666 =head3 renameTable() - Benenne Tabelle um
1667  
1668 =head4 Synopsis
1669  
1670 $stmt = $sql->renameTable($oldName,$newName);
1671  
1672 =cut
1673  
1674 # -----------------------------------------------------------------------------
1675  
1676 0 ▶sub renameTable {
Subroutine renameTable: not called CC=2 SCAR=17.9
Pod documented
1677 0 my ($self,$oldName,$newName) = @_;
1678  
1679 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1680  
1681 0 my $stmt;
1682 0 ▶ if ($sqlite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sqlite) { } 0 0 0
1683 0 $stmt = "ALTER TABLE $oldName RENAME TO $newName";
1684 }
1685 else {
1686 0 $self->throw;
1687 }
1688  
1689 0 return $stmt;
1690 }
1691  
1692 # -----------------------------------------------------------------------------
1693  
1694 =head3 analyzeTable() - Generiere ANALYZE TABLE Statement
1695  
1696 =head4 Synopsis
1697  
1698 $stmt = $sql->analyzeTable($table);
1699  
1700 =cut
1701  
1702 # -----------------------------------------------------------------------------
1703  
1704 0 ▶sub analyzeTable {
Subroutine analyzeTable: not called CC=2 SCAR=17.9
Pod documented
1705 0 my ($self,$table) = @_;
1706  
1707 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1708  
1709 # Für DBMSe, die kein ANALYZE kennen, liefern wir ein
1710 # leeres Statement.
1711  
1712 0 my $stmt = '';
1713 0 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) 0 0 0
1714 0 $stmt = "ANALYZE $table";
1715 }
1716  
1717 0 return $stmt;
1718 }
1719  
1720 # -----------------------------------------------------------------------------
1721  
1722 =head3 legalizeTablename() - Legalisiere Tabellennamen
1723  
1724 =head4 Synopsis
1725  
1726 $table = $sql->legalizeTablename($table);
1727  
1728 =head4 Description
1729  
1730 Legalisiere Tabellennamen durch Quotierung, wenn dieser Sonderzeichen
1731 enthält. Dies geschieht bei MySQL durch Backticks, z.B. bei Tabellen,
1732 deren Name einen Bindestrich enthält:
1733  
1734 Meine-Tabelle -> `Meine-Tabelle`
1735 Mein-Schema.Meine-Tabelle -> `Meine-Schema`.`Meine-Tabelle`
1736  
1737 Für die anderen DBMSe ist das Feature aktuell nicht implementiert,
1738 d.h. es wird immer der unveränderte Tabellenname zurückgegeben.
1739  
1740 =cut
1741  
1742 # -----------------------------------------------------------------------------
1743  
1744 6 ▶sub legalizeTablename {
Subroutine legalizeTablename: called CC=3 SCAR=11.0
Pod documented
1745 6 my ($self,$table) = @_;
1746  
1747 6 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1748  
1749 6 ▶ if ($mysql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mysql) 4 2 6
1750 4 ▶ if ($table =~ /[^\w.\$]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($table =~ /[^\w.\$]/) 2 2 4
1751 2 $table =~ s/([^.]+)/`$1`/g;
1752 }
1753 }
1754  
1755 6 return $table;
1756 }
1757  
1758 # -----------------------------------------------------------------------------
1759  
1760 =head2 Columns
1761  
1762 =head3 addColumn() - Generiere ALTER TABLE Statement, das eine Kolumne erzeugt
1763  
1764 =head4 Synopsis
1765  
1766 $stmt = $sql->addColumn($table,$column,@colDef);
1767  
1768 =head4 Description
1769  
1770 Erzeuge SQL-Statement, das der Tabelle $table die Kolumne $column
1771 mit der Spezifikation @colDef hinzufügt. Die portable
1772 Kolumnen-Spezifikation @colDef wird von Methode columnDef()
1773 in die DBMS-spezifische Zeichenkette gewandelt.
1774  
1775 B<PostgreSQL Syntax>
1776  
1777 ALTER TABLE table ADD COLUMN column type ...
1778  
1779 B<Oracle Syntax>
1780  
1781 ALTER TABLE table ADD (column type ...)
1782  
1783 B<SQLite Syntax>
1784  
1785 ALTER TABLE table ADD COLUMN column type ...
1786  
1787 B<MySQL Syntax>
1788  
1789 ALTER TABLE table ADD COLUMN column type ...
1790  
1791 Die Punkte stehen für zusätzliche optionale Kolumnen-Angaben, wie
1792 "DEFAULT expr", "NOT NULL", "PRIMARY KEY" usw.
1793  
1794 =cut
1795  
1796 # -----------------------------------------------------------------------------
1797  
1798 7 ▶sub addColumn {
Subroutine addColumn: called CC=5 SCAR=16.2
Pod documented
1799 7 my $self = shift;
1800 7 my $table = shift;
1801 7 my $column = shift;
1802 # @_: @typeSpec
1803  
1804 # Statement generieren
1805  
1806 7 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1807  
1808 7 my $colDef = $self->columnDef(@_);
1809  
1810 7 my $stmt;
1811 7 ▶ if ($oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle) { } 1 6 7
elsif ($postgresql or $sqlite or $mysql) { } 6 0 6
1812 1 $stmt = sprintf "ALTER TABLE $table ADD ($column $colDef)";
1813 }
1814 ▶ elsif ($postgresql || $sqlite || $mysql) {
Condition83%5/6
$postgresql or $sqlite or $mysql
l!l&&r!l&&!r
510
$postgresql or $sqlite
l!l&&r!l&&!r
141
MC/DC0%0/3
$postgresql or $sqlite or $mysql
$postgresql $sqlite $mysql
Truth table75%3/4
A or B or C
A= $postgresqlB= $sqliteC= $mysql
ABCresult
1XX1
01X1
0011
0000
1815 6 $stmt = sprintf "ALTER TABLE $table ADD COLUMN $column $colDef";
1816 }
1817 else {
1818 0 $self->throw('Not implemented');
1819 }
1820  
1821 7 return $stmt;
1822 }
1823  
1824 # -----------------------------------------------------------------------------
1825  
1826 =head3 dropColumn() - Generiere ALTER TABLE Statement, das eine Kolumne entfernt
1827  
1828 =head4 Synopsis
1829  
1830 $stmt = $sql->dropColumn($table,$column);
1831  
1832 =head4 Description
1833  
1834 Erzeuge SQL-Statement, das aus der Tabelle $table die Kolumne $column
1835 entfernt.
1836  
1837 B<Oracle, PostgreSQL, MySQL Syntax>
1838  
1839 ALTER TABLE table DROP COLUMN column
1840  
1841 B<SQLite Syntax>
1842  
1843 Eine Kolumne kann nicht entfernt werden (geprüft 3.6.13)
1844  
1845 =cut
1846  
1847 # -----------------------------------------------------------------------------
1848  
1849 2 ▶sub dropColumn {
Subroutine dropColumn: called CC=5 SCAR=18.0
Pod documented
1850 2 my $self = shift;
1851 2 my $table = shift;
1852 2 my $column = shift;
1853  
1854 2 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1855  
1856 # Statement generieren
1857  
1858 2 my $stmt;
1859 2 ▶ if ($oracle || $postgresql || $sqlite || $mysql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql or $sqlite or $mysql) { } 2 0 2
Condition44%4/9
$oracle or $postgresql or $sqlite or $mysql
l!l&&r!l&&!r
200
$oracle or $postgresql or $sqlite
l!l&&r!l&&!r
200
$oracle or $postgresql
l!l&&r!l&&!r
110
MC/DC0%0/4
$oracle or $postgresql or $sqlite or $mysql
$oracle $postgresql $sqlite $mysql
Truth table40%2/5
A or B or C or D
A= $oracleB= $postgresqlC= $sqliteD= $mysql
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1860 2 $stmt = sprintf "ALTER TABLE $table DROP COLUMN $column";
1861 }
1862 else {
1863 0 $self->throw('Not implemented');
1864 }
1865  
1866 2 return $stmt;
1867 }
1868  
1869 # -----------------------------------------------------------------------------
1870  
1871 =head3 modifyColumn() - Generiere ALTER TABLE Statement, das eine Kolumne modifiziert
1872  
1873 =head4 Synopsis
1874  
1875 $stmt = $sql->modifyColumn($table,$column,$property=>$value);
1876  
1877 =head4 Description
1878  
1879 Erzeuge SQL-Statement, das in Tabelle $table die Kolumne $column
1880 modifiziert. Verändert wird die Eigenschaft $property auf Wert
1881 $value.
1882  
1883 B<NULL>
1884  
1885 =over 4
1886  
1887 =item PostgreSQL:
1888  
1889 ALTER TABLE t ALTER COLUMN c DROP NOT NULL
1890  
1891 =item Oracle:
1892  
1893 ALTER TABLE t MODIFY c NULL
1894  
1895 =item MySQL:
1896  
1897 NOT NULL scheint nicht ohne Kenntnis des Kolumnentyps
1898 manipuliert werden zu können (5.1.41).
1899  
1900 =item SQLite:
1901  
1902 Eine Kolumne kann nicht modifiziert werden (geprüft 3.6.22)
1903  
1904 =back
1905  
1906 B<NOT NULL>
1907  
1908 =over 4
1909  
1910 =item PostgreSQL:
1911  
1912 ALTER TABLE t ALTER COLUMN c SET NOT NULL
1913  
1914 =item Oracle:
1915  
1916 ALTER TABLE t MODIFY COLUMN c NULL
1917  
1918 =item MySQL:
1919  
1920 NOT NULL scheint nicht ohne Kenntnis des Kolumnentyps
1921 manipuliert werden zu können (5.1.41).
1922  
1923 =item SQLite:
1924  
1925 Eine Kolumne kann nicht modifiziert werden (geprüft 3.6.22)
1926  
1927 =back
1928  
1929 B<TYPE>
1930  
1931 =over 4
1932  
1933 =item PostgreSQL:
1934  
1935 nicht implementiert
1936  
1937 =item Oracle:
1938  
1939 ALTER TABLE <t> MODIFY COLUMN <c> <type>
1940  
1941 =item MySQL:
1942  
1943 nicht implementiert
1944  
1945 =item SQLite:
1946  
1947 Eine Kolumne kann nicht modifiziert werden (geprüft 3.6.22)
1948  
1949 =back
1950  
1951 =cut
1952  
1953 # -----------------------------------------------------------------------------
1954  
1955 2 ▶sub modifyColumn {
Subroutine modifyColumn: called CC=16 SCAR=47.7
Pod documented
1956 2 my ($self,$table,$column,$property,$value) = @_;
1957  
1958 2 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
1959  
1960 # Statement generieren
1961  
1962 2 my $stmt;
1963 2 ▶ if ($property eq 'notNull') {
Branch: 2 branches
BranchTrueFalseTotal
if ($property eq 'notNull') { } 2 0 2
elsif ($property eq 'type') { } 0 0 0
1964 2 ▶ if ($value) { # NOT NULL
Branch: 1 branch
BranchTrueFalseTotal
if ($value) { } 2 0 2
1965 2 ▶ if ($postgresql) {
Branch: 3 branches
BranchTrueFalseTotal
if ($postgresql) { } 1 1 2
elsif ($oracle) { } 1 0 1
elsif ($sqlite or $mysql) { } 0 0 0
1966 1 $stmt = "ALTER TABLE $table ALTER COLUMN $column SET NOT NULL";
1967 }
1968 elsif ($oracle) {
1969 1 $stmt = "ALTER TABLE $table MODIFY $column NOT NULL";
1970 }
1971 ▶ elsif ($sqlite || $mysql) {
Condition0%0/3
$sqlite or $mysql
l!l&&r!l&&!r
000
MC/DC0%0/2
$sqlite or $mysql
$sqlite $mysql
Truth table0%0/3
A or B
A= $sqliteB= $mysql
ABresult
1X1
011
000
1972 0 $self->throw('Not implemented');
1973 }
1974 }
1975 else { # NULL
1976 0 ▶ if ($postgresql) {
Branch: 3 branches
BranchTrueFalseTotal
if ($postgresql) { } 0 0 0
elsif ($oracle) { } 0 0 0
elsif ($sqlite or $mysql) { } 0 0 0
1977 0 $stmt = "ALTER TABLE $table ALTER COLUMN $column".
1978 ' DROP NOT NULL';
1979 }
1980 elsif ($oracle) {
1981 0 $stmt = "ALTER TABLE $table MODIFY $column NULL";
1982 }
1983 ▶ elsif ($sqlite || $mysql) {
Condition0%0/3
$sqlite or $mysql
l!l&&r!l&&!r
000
MC/DC0%0/2
$sqlite or $mysql
$sqlite $mysql
Truth table0%0/3
A or B
A= $sqliteB= $mysql
ABresult
1X1
011
000
1984 0 $self->throw('Not implemented');
1985 }
1986 }
1987 }
1988 elsif ($property eq 'type') {
1989 0 my $type = $self->dataType($value);
1990  
1991 0 ▶ if ($postgresql) {
Branch: 3 branches
BranchTrueFalseTotal
if ($postgresql) { } 0 0 0
elsif ($oracle) { } 0 0 0
elsif ($sqlite or $mysql) { } 0 0 0
1992 0 $stmt = "ALTER TABLE $table ALTER COLUMN $column TYPE $type";
1993 }
1994 elsif ($oracle) {
1995 0 $stmt = "ALTER TABLE $table MODIFY $column $type";
1996 }
1997 ▶ elsif ($sqlite || $mysql) {
Condition0%0/3
$sqlite or $mysql
l!l&&r!l&&!r
000
MC/DC0%0/2
$sqlite or $mysql
$sqlite $mysql
Truth table0%0/3
A or B
A= $sqliteB= $mysql
ABresult
1X1
011
000
1998 0 $self->throw('Not implemented');
1999 }
2000 }
2001 else {
2002 0 $self->throw('Not implemented');
2003 }
2004  
2005 2 return $stmt;
2006 }
2007  
2008 # -----------------------------------------------------------------------------
2009  
2010 =head3 renameColumn() - Generiere ALTER TABLE Statement, das eine Kolumne umbenennt
2011  
2012 =head4 Synopsis
2013  
2014 $stmt = $sql->renameColumn($table,$oldName,$newName)
2015  
2016 =head4 Description
2017  
2018 Erzeuge SQL-Statement, das in Tabelle $table die Kolumne $oldName
2019 in $newName umbenennt.
2020  
2021 B<Syntax>
2022  
2023 =over 4
2024  
2025 =item PostgreSQL:
2026  
2027 ALTER TABLE t RENAME COLUMN c1 TO c2
2028  
2029 =item Oracle:
2030  
2031 ALTER TABLE t RENAME COLUMN c1 TO c2
2032  
2033 =item MySQL:
2034  
2035 nicht implementiert
2036  
2037 =item SQLite:
2038  
2039 nicht implementiert
2040  
2041 =back
2042  
2043 =cut
2044  
2045 # -----------------------------------------------------------------------------
2046  
2047 2 ▶sub renameColumn {
Subroutine renameColumn: called CC=5 SCAR=20.3
Pod documented
2048 2 my ($self,$table,$oldName,$newName) = @_;
2049  
2050 2 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2051  
2052 # Statement generieren
2053  
2054 2 my $stmt;
2055 2 ▶ if ($postgresql || $oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($postgresql or $oracle) { } 2 0 2
elsif ($sqlite or $mysql) { } 0 0 0
Condition66%2/3
$postgresql or $oracle
l!l&&r!l&&!r
110
MC/DC0%0/2
$postgresql or $oracle
$postgresql $oracle
Truth table66%2/3
A or B
A= $postgresqlB= $oracle
ABresult
1X1
011
000
2056 2 $stmt = "ALTER TABLE $table RENAME COLUMN $oldName TO $newName";
2057 }
2058 ▶ elsif ($sqlite || $mysql) {
Condition0%0/3
$sqlite or $mysql
l!l&&r!l&&!r
000
MC/DC0%0/2
$sqlite or $mysql
$sqlite $mysql
Truth table0%0/3
A or B
A= $sqliteB= $mysql
ABresult
1X1
011
000
2059 0 $self->throw('Not implemented');
2060 }
2061  
2062 2 return $stmt;
2063 }
2064  
2065 # -----------------------------------------------------------------------------
2066  
2067 =head2 Constraints
2068  
2069 =head3 addPrimaryKeyConstraint() - Generiere PRIMARY KEY Constraint Statement
2070  
2071 =head4 Synopsis
2072  
2073 $stmt = $sql->addPrimaryKeyConstraint($tableName,\@colNames,@opt);
2074  
2075 =head4 Options
2076  
2077 =over 4
2078  
2079 =item -constraintName => $str (Default: <TABLE>_PK)
2080  
2081 Name des Constraint.
2082  
2083 =item -exceptionTable => $tableName (Default: keiner)
2084  
2085 Constraint-Verletzende Datensätze werden in Tabelle $tableName
2086 protokollliert (nur Oracle).
2087  
2088 =item -tableSpace => $tableSpaceName (Default: keiner)
2089  
2090 Name des Tablespace, in dem der Index erzeugt wird
2091 (Oracle und PostgreSQL).
2092  
2093 =back
2094  
2095 =head4 Description
2096  
2097 B<Oracle Syntax>
2098  
2099 ALTER TABLE <TABLE_NAME> ADD
2100 CONSTRAINT <CONSTRAINT_NAME>
2101 PRIMARY KEY (<TABLE_COLUMNS>)
2102 USING INDEX TABLESPACE <TABLESPACE_NAME>
2103 EXCEPTIONS INTO <EXCEPTION_TABLE_NAME>
2104  
2105 B<PostgreSQL Syntax>
2106  
2107 ALTER TABLE <TABLE_NAME> ADD
2108 CONSTRAINT <CONSTRAINT_NAME>
2109 PRIMARY KEY (<TABLE_COLUMNS>)
2110 USING INDEX TABLESPACE <TABLESPACE_NAME>
2111  
2112 =cut
2113  
2114 # -----------------------------------------------------------------------------
2115  
2116 5 ▶sub splitObjectName {
Subroutine splitObjectName: called CC=1 SCAR=0.0
Pod undocumented
2117 5 my $this = shift;
2118 5 my $objectName = shift;
2119 5 return reverse split /\./,$objectName;
2120 }
2121  
2122 1 ▶sub addPrimaryKeyConstraint {
Subroutine addPrimaryKeyConstraint: called CC=8 SCAR=23.6
Pod documented
2123 1 my $self = shift;
2124 1 my $tableName = shift;
2125 1 my $colNameA = shift;
2126  
2127 # Optionen
2128  
2129 1 my $constraintName = undef;
2130 1 my $exceptionTable = undef;
2131 1 my $tableSpace = undef;
2132  
2133 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
2134 0 Quiq::Option->extract(\@_,
2135 -constraintName => \$constraintName,
2136 -exceptionTable => \$exceptionTable,
2137 -tableSpace => \$tableSpace,
2138 );
2139 }
2140  
2141 1 ▶ if (!$constraintName) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($constraintName) 1 0 1
2142 1 my ($table) = $self->splitObjectName($tableName);
2143 1 $constraintName = $table.'_PK';
2144 1 $self->checkName(\$constraintName);
2145 }
2146  
2147 # Statement generieren
2148  
2149 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2150  
2151 1 my $stmt;
2152 1 ▶ if ($oracle || $postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql) { } 1 0 1
Condition33%1/3
$oracle or $postgresql
l!l&&r!l&&!r
010
MC/DC0%0/2
$oracle or $postgresql
$oracle $postgresql
Truth table33%1/3
A or B
A= $oracleB= $postgresql
ABresult
1X1
011
000
2153 1 $stmt = sprintf "ALTER TABLE %s ADD\n".
2154 " CONSTRAINT %s\n".
2155 " PRIMARY KEY (%s)",
2156 $tableName,$constraintName,join(', ',@$colNameA);
2157  
2158 1 ▶ if ($tableSpace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tableSpace) 0 1 1
2159 0 $stmt .= "\n USING INDEX TABLESPACE $tableSpace";
2160 }
2161  
2162 1 ▶ if ($oracle && $exceptionTable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle and $exceptionTable) 0 1 1
Condition33%1/3
$oracle and $exceptionTable
!ll&&!rl&&r
100
MC/DC0%0/2
$oracle and $exceptionTable
$oracle $exceptionTable
Truth table33%1/3
A and B
A= $oracleB= $exceptionTable
ABresult
0X0
100
111
2163 0 $stmt .= "\n EXCEPTIONS INTO $exceptionTable";
2164 }
2165 }
2166 else {
2167 0 die;
2168 }
2169  
2170 1 return $stmt;
2171 }
2172  
2173 # -----------------------------------------------------------------------------
2174  
2175 =head3 addForeignKeyConstraint() - Generiere FOREIGN KEY Constraint Statement
2176  
2177 =head4 Synopsis
2178  
2179 $stmt = $sql->addForeignKeyConstraint($tableName,\@tableCols,
2180 $refTableName,@opt);
2181  
2182 =head4 Options
2183  
2184 =over 4
2185  
2186 =item -constraintName => $str (Default: <TABLE>_FK_<REFTABLE>)
2187  
2188 Name des Constraint.
2189  
2190 =item -defer => $bool (Default: 0)
2191  
2192 Constraint-Fehler wird verzögert gemeldet.
2193  
2194 =item -disable => $bool (Default: 0)
2195  
2196 Constraint wird erzeugt, ist aber abgeschaltet.
2197  
2198 =item -exceptionTable => $tableName (Default: keiner)
2199  
2200 Constraint-Verletzende Datensätze werden in Tabelle $tableName
2201 protokollliert (nur Oracle).
2202  
2203 =item -onDelete => 'cascade'|'null' (Default: keiner)
2204  
2205 Legt fest, was bei Löschung des Parent-Datensatzes passieren soll.
2206  
2207 =item -refTableCols => \@refTableCols (Default: undef)
2208  
2209 Liste der Kolumnen in der referenzierten Tabelle.
2210 Bei MySQL müssen die referenzierten Kolumnen aufgezählt werden, auch wenn
2211 ein Primary Key auf der referenzierten Tabelle definiert ist.
2212  
2213 =back
2214  
2215 =head4 Description
2216  
2217 B<Oracle Syntax>
2218  
2219 ALTER TABLE <TABLE_NAME> ADD
2220 CONSTRAINT <CONSTRAINT_NAME>
2221 FOREIGN KEY (<TABLE_COLUMNS>)
2222 REFERENCES <REF_TABLE_NAME>
2223 ON DELETE <ACTION>
2224 DEFERRABLE INITIALLY DEFERRED
2225 EXCEPTIONS INTO <EXCEPTION_TABLE_NAME>
2226 DISABLE
2227  
2228 B<PostgreSQL Syntax>
2229  
2230 ALTER TABLE <TABLE_NAME> ADD
2231 CONSTRAINT <CONSTRAINT_NAME>
2232 FOREIGN KEY (<TABLE_COLUMNS>)
2233 REFERENCES <REF_TABLE_NAME>
2234 ON DELETE <ACTION>
2235 DEFERRABLE INITIALLY DEFERRED
2236  
2237 B<MySQL Syntax>
2238  
2239 ALTER TABLE <TABLE_NAME> ADD
2240 CONSTRAINT <CONSTRAINT_NAME>
2241 FOREIGN KEY (<TABLE_COLUMNS>)
2242 REFERENCES <REF_TABLE_NAME> (REF_TABLE_COLUMNS)
2243 ON DELETE <ACTION>
2244  
2245 =cut
2246  
2247 # -----------------------------------------------------------------------------
2248  
2249 1 ▶sub addForeignKeyConstraint {
Subroutine addForeignKeyConstraint: called CC=18 SCAR=42.0
Pod documented
2250 1 my $self = shift;
2251 1 my $fromName = shift;
2252 1 my $cols = shift;
2253 1 my $toName = shift;
2254  
2255 # Optionen
2256  
2257 1 my $constraintName = undef;
2258 1 my $defer = 0;
2259 1 my $disable = 0;
2260 1 my $exceptionTable = undef;
2261 1 my $onDelete = undef;
2262 1 my $refTableColumns = undef;
2263  
2264 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 0 1
2265 1 Quiq::Option->extract(\@_,
2266 -constraintName => \$constraintName,
2267 -defer => \$defer,
2268 -disable => \$disable,
2269 -exceptionTable => \$exceptionTable,
2270 -onDelete => \$onDelete,
2271 -refTableColumns => \$refTableColumns,
2272 );
2273 }
2274  
2275 1 ▶ if (!$constraintName) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($constraintName) 0 1 1
2276 0 my ($fromTable) = $self->splitObjectName($fromName);
2277 0 my ($toTable) = $self->splitObjectName($toName);
2278 0 $constraintName = $fromTable.'_FK_'.$toTable;
2279 0 $self->checkName(\$constraintName);
2280 }
2281  
2282 # Statement generieren
2283  
2284 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2285  
2286 1 my $stmt;
2287 1 ▶ if ($postgresql || $oracle || $sqlite || $mysql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql or $oracle or $sqlite or $mysql) { } 1 0 1
Condition33%3/9
$postgresql or $oracle or $sqlite or $mysql
l!l&&r!l&&!r
100
$postgresql or $oracle or $sqlite
l!l&&r!l&&!r
100
$postgresql or $oracle
l!l&&r!l&&!r
100
MC/DC0%0/4
$postgresql or $oracle or $sqlite or $mysql
$postgresql $oracle $sqlite $mysql
Truth table20%1/5
A or B or C or D
A= $postgresqlB= $oracleC= $sqliteD= $mysql
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2288 # ALTER TABLE
2289  
2290 1 $stmt = sprintf "ALTER TABLE %s ADD\n".
2291 " CONSTRAINT %s\n".
2292 " FOREIGN KEY (%s)\n".
2293 " REFERENCES %s",
2294 $fromName,
2295 $constraintName,
2296 join(', ',@$cols),
2297 $toName;
2298  
2299 1 ▶ if ($refTableColumns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($refTableColumns) 0 1 1
2300 0 my $str = '';
2301 0 for (@$refTableColumns) {
2302 0 ▶ if ($str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str) 0 0 0
2303 0 $str .= ', ';
2304 }
2305 0 $str .= $_;
2306 }
2307 0 ▶ if ($str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str) 0 0 0
2308 0 $stmt .= " ($str)";
2309 }
2310 }
2311  
2312 # ON DELETE
2313  
2314 1 ▶ if ($onDelete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($onDelete) 1 0 1
2315 1 $stmt .= "\n ON DELETE ";
2316 1 ▶ if ($onDelete =~ /^CASCADE$/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($onDelete =~ /^CASCADE$/i) { } 1 0 1
elsif ($onDelete =~ /NULL/i) { } 0 0 0
2317 1 $stmt .= 'CASCADE';
2318 }
2319 elsif ($onDelete =~ /NULL/i) {
2320 0 $stmt .= 'SET NULL';
2321 }
2322 else {
2323 0 $self->throw(
2324 'SQL-00001: Unexpected ON DELETE action',
2325 Action => $onDelete,
2326 );
2327 }
2328 }
2329  
2330 # DEFERRABLE
2331  
2332 1 ▶ if ($defer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($defer) 1 0 1
2333 1 $stmt .= "\n DEFERRABLE INITIALLY DEFERRED";
2334 }
2335  
2336 1 ▶ if ($oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle) 0 1 1
2337 0 ▶ if ($exceptionTable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exceptionTable) 0 0 0
2338 0 $stmt .= "\n EXCEPTIONS INTO $exceptionTable";
2339 }
2340 0 ▶ if ($disable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disable) 0 0 0
2341 0 $stmt .= "\n DISABLE";
2342 }
2343 }
2344 }
2345 else {
2346 0 $self->throw;
2347 }
2348  
2349 1 return $stmt;
2350 }
2351  
2352 # -----------------------------------------------------------------------------
2353  
2354 =head3 addNotNullConstraint() - Generiere NOT NULL Constraint Statement
2355  
2356 =head4 Synopsis
2357  
2358 $stmt = $sql->addNotNullConstraint($tableName,$colName,@opt);
2359  
2360 =head4 Options
2361  
2362 =over 4
2363  
2364 =item -constraintName => $str (Default: <TABLE>_CK)
2365  
2366 Name des Constraint (nicht PostgreSQL).
2367  
2368 =item -exceptionTable => $tableName (Default: keiner)
2369  
2370 Constraint-Verletzende Datensätze werden in Tabelle $tableName
2371 protokollliert (nur Oracle).
2372  
2373 =back
2374  
2375 =head4 Description
2376  
2377 B<Oracle Syntax>
2378  
2379 ALTER TABLE <TABLE_NAME> MODIFY (
2380 <COLUMN NAME>
2381 CONSTRAINT <CONSTRAINT_NAME>
2382 NOT NULL
2383 EXCEPTIONS INTO <EXCEPTION_TABLE_NAME>
2384 )
2385  
2386 B<PostgreSQL Syntax>
2387  
2388 ALTER TABLE <TABLE_NAME>
2389 ALTER COLUMN <COLUMN_NAME>
2390 SET NOT NULL
2391  
2392 =cut
2393  
2394 # -----------------------------------------------------------------------------
2395  
2396 1 ▶sub addNotNullConstraint {
Subroutine addNotNullConstraint: called CC=6 SCAR=21.2
Pod documented
2397 1 my $self = shift;
2398 1 my $tableName = shift;
2399 1 my $columnName = shift;
2400  
2401 # Optionen
2402  
2403 1 my $constraintName = undef;
2404 1 my $exceptionTable = undef;
2405  
2406 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
2407 0 Quiq::Option->extract(\@_,
2408 -constraintName => \$constraintName,
2409 -exceptionTable => \$exceptionTable,
2410 );
2411 }
2412  
2413 1 ▶ if (!$constraintName) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($constraintName) 1 0 1
2414 1 my ($table) = $self->splitObjectName($tableName);
2415 1 $constraintName = $table.'_NN_'.$columnName;
2416 1 $self->checkName(\$constraintName);
2417 }
2418  
2419 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2420  
2421 # Statement generieren
2422  
2423 1 my $stmt;
2424 1 ▶ if ($postgresql) {
Branch: 2 branches
BranchTrueFalseTotal
if ($postgresql) { } 1 0 1
elsif ($oracle) { } 0 0 0
2425 1 $stmt = "ALTER TABLE $tableName\n".
2426 " ALTER COLUMN $columnName\n".
2427 " SET NOT NULL";
2428 }
2429 elsif ($oracle) {
2430 0 $stmt = "ALTER TABLE $tableName\n".
2431 " MODIFY $columnName\n".
2432 " CONSTRAINT $constraintName\n".
2433 " NOT NULL";
2434  
2435 0 ▶ if ($exceptionTable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exceptionTable) 0 0 0
2436 0 $stmt .= "\n EXCEPTIONS INTO $exceptionTable";
2437 }
2438 }
2439 else {
2440 0 die;
2441 }
2442  
2443 1 return $stmt;
2444 }
2445  
2446 # -----------------------------------------------------------------------------
2447  
2448 =head3 addCheckConstraint() - Generiere CHECK Constraint Statement
2449  
2450 =head4 Synopsis
2451  
2452 $stmt = $sql->addCheckConstraint($tableName,$clause,@opt);
2453  
2454 =head4 Options
2455  
2456 =over 4
2457  
2458 =item -constraintName => $str (Default: <TABLE>_CK)
2459  
2460 Name des Constraint.
2461  
2462 =item -exceptionTable => $tableName (Default: keiner)
2463  
2464 Constraint-Verletzende Datensätze werden in Tabelle $tableName
2465 protokollliert (nur Oracle).
2466  
2467 =back
2468  
2469 =head4 Description
2470  
2471 B<Oracle Syntax>
2472  
2473 ALTER TABLE <TABLE_NAME> ADD
2474 CONSTRAINT <CONSTRAINT_NAME>
2475 CHECK (<CHECK_CLAUSE>)
2476 EXCEPTIONS INTO <EXCEPTION_TABLE_NAME>
2477  
2478 B<PostgreSQL Syntax>
2479  
2480 ALTER TABLE <TABLE_NAME> ADD
2481 CONSTRAINT <CONSTRAINT_NAME>
2482 CHECK (<CHECK_CLAUSE>)
2483  
2484 B<SQLite Syntax>
2485  
2486 ALTER TABLE <TABLE_NAME> ADD
2487 CONSTRAINT <CONSTRAINT_NAME>
2488 CHECK (<CHECK_CLAUSE>)
2489  
2490 =cut
2491  
2492 # -----------------------------------------------------------------------------
2493  
2494 1 ▶sub addCheckConstraint {
Subroutine addCheckConstraint: called CC=8 SCAR=24.0
Pod documented
2495 1 my $self = shift;
2496 1 my $tableName = shift;
2497 1 my $clause = shift;
2498  
2499 # Optionen
2500  
2501 1 my $constraintName = undef;
2502 1 my $exceptionTable = undef;
2503  
2504 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
2505 0 Quiq::Option->extract(\@_,
2506 -constraintName => \$constraintName,
2507 -exceptionTable => \$exceptionTable,
2508 );
2509 }
2510  
2511 1 ▶ if (!$constraintName) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($constraintName) 1 0 1
2512 # ACHTUNG: generierter Name bei mehreren Check-Constraints
2513 # nicht eindeutig
2514 1 my ($table) = $self->splitObjectName($tableName);
2515 1 $constraintName = "${table}_CK";
2516 1 $self->checkName(\$constraintName);
2517 }
2518  
2519 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2520  
2521 # Statement generieren
2522  
2523 1 my $stmt;
2524 1 ▶ if ($oracle || $postgresql || $sqlite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql or $sqlite) { } 1 0 1
Condition33%2/6
$oracle or $postgresql or $sqlite
l!l&&r!l&&!r
100
$oracle or $postgresql
l!l&&r!l&&!r
010
MC/DC0%0/3
$oracle or $postgresql or $sqlite
$oracle $postgresql $sqlite
Truth table25%1/4
A or B or C
A= $oracleB= $postgresqlC= $sqlite
ABCresult
1XX1
01X1
0011
0000
2525 1 $stmt = sprintf "ALTER TABLE %s ADD\n".
2526 " CONSTRAINT %s\n".
2527 " CHECK (%s)",
2528 $tableName,
2529 $constraintName,
2530 $clause;
2531  
2532 1 ▶ if ($oracle && $exceptionTable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle and $exceptionTable) 0 1 1
Condition33%1/3
$oracle and $exceptionTable
!ll&&!rl&&r
100
MC/DC0%0/2
$oracle and $exceptionTable
$oracle $exceptionTable
Truth table33%1/3
A and B
A= $oracleB= $exceptionTable
ABresult
0X0
100
111
2533 0 $stmt .= "\n EXCEPTIONS INTO $exceptionTable";
2534 }
2535 }
2536 else {
2537 0 $self->throw;
2538 }
2539  
2540 1 return $stmt;
2541 }
2542  
2543 # -----------------------------------------------------------------------------
2544  
2545 =head3 addUniqueConstraint() - Generiere UNIQUE Constraint Statement
2546  
2547 =head4 Synopsis
2548  
2549 $stmt = $sql->addUniqueConstraint($tableName,\@colNames,@opt);
2550  
2551 =head4 Options
2552  
2553 =over 4
2554  
2555 =item -constraintName => $str (Default: <TABLE>_UQ_<COLUMNS>)
2556  
2557 Name des Constraint.
2558  
2559 =item -exceptionTable => $tableName (Default: keiner)
2560  
2561 Constraint-Verletzende Datensätze werden in Tabelle $tableName
2562 protokollliert (nur Oracle).
2563  
2564 =item -tableSpace => $tableSpaceName (Default: keiner)
2565  
2566 Name des Tablespace, in dem der Index erzeugt wird
2567 (Oracle und PostgreSQL).
2568  
2569 =back
2570  
2571 =head4 Description
2572  
2573 Liefere ein SQL-Statement zur Erzeugung eines UNIQUE-Constraint
2574 auf Tabelle $tableName über den Kolumnen @colNames und liefere
2575 dieses zurück.
2576  
2577 B<Oracle Syntax>
2578  
2579 ALTER TABLE <TABLE_NAME> ADD
2580 CONSTRAINT <CONSTRAINT_NAME>
2581 UNIQUE (<TABLE_COLUMNS>)
2582 USING INDEX TABLESPACE <TABLESPACE_NAME>
2583 EXCEPTIONS INTO <EXCEPTION_TABLE_NAME>
2584  
2585 B<PostgreSQL Syntax>
2586  
2587 ALTER TABLE <TABLE_NAME> ADD
2588 CONSTRAINT <CONSTRAINT_NAME>
2589 UNIQUE (<TABLE_COLUMNS>)
2590 USING INDEX TABLESPACE <TABLESPACE_NAME>
2591  
2592 =cut
2593  
2594 # -----------------------------------------------------------------------------
2595  
2596 1 ▶sub addUniqueConstraint {
Subroutine addUniqueConstraint: called CC=8 SCAR=23.6
Pod documented
2597 1 my $self = shift;
2598 1 my $tableName = shift;
2599 1 my $colNameA = shift;
2600  
2601 # Optionen
2602  
2603 1 my $constraintName = undef;
2604 1 my $exceptionTable = undef;
2605 1 my $tableSpace = undef;
2606  
2607 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
2608 0 Quiq::Option->extract(\@_,
2609 -constraintName => \$constraintName,
2610 -exceptionTable => \$exceptionTable,
2611 -tableSpace => \$tableSpace,
2612 );
2613 }
2614  
2615 1 ▶ if (!$constraintName) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($constraintName) 1 0 1
2616 1 my ($table) = $self->splitObjectName($tableName);
2617 1 $constraintName = $table.'_UQ_'.join('_',@$colNameA);
2618 1 $self->checkName(\$constraintName);
2619 }
2620  
2621 # Statement generieren
2622  
2623 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2624  
2625 1 my $stmt;
2626 1 ▶ if ($oracle || $postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql) { } 1 0 1
Condition33%1/3
$oracle or $postgresql
l!l&&r!l&&!r
010
MC/DC0%0/2
$oracle or $postgresql
$oracle $postgresql
Truth table33%1/3
A or B
A= $oracleB= $postgresql
ABresult
1X1
011
000
2627 1 $stmt = sprintf "ALTER TABLE %s ADD\n".
2628 " CONSTRAINT %s\n".
2629 " UNIQUE (%s)",
2630 $tableName,$constraintName,join(', ',@$colNameA);
2631  
2632 1 ▶ if ($tableSpace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tableSpace) 0 1 1
2633 0 $stmt .= "\n USING INDEX TABLESPACE $tableSpace";
2634 }
2635  
2636 1 ▶ if ($oracle && $exceptionTable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle and $exceptionTable) 0 1 1
Condition33%1/3
$oracle and $exceptionTable
!ll&&!rl&&r
100
MC/DC0%0/2
$oracle and $exceptionTable
$oracle $exceptionTable
Truth table33%1/3
A and B
A= $oracleB= $exceptionTable
ABresult
0X0
100
111
2637 0 $stmt .= "\n EXCEPTIONS INTO $exceptionTable";
2638 }
2639 }
2640 else {
2641 0 die;
2642 }
2643  
2644 1 return $stmt;
2645 }
2646  
2647 # -----------------------------------------------------------------------------
2648  
2649 =head2 Index
2650  
2651 =head3 indexName() - Liefere Namen für Index
2652  
2653 =head4 Synopsis
2654  
2655 $indexName = $sql->indexName($table,\@colNames);
2656  
2657 =cut
2658  
2659 # -----------------------------------------------------------------------------
2660  
2661 1 ▶sub indexName {
Subroutine indexName: called CC=1 SCAR=0.0
Pod documented
2662 1 my $self = shift;
2663 1 my $tableName = shift;
2664 1 my $colNameA = shift;
2665  
2666 1 my ($table) = $self->splitObjectName($tableName);
2667 1 my $indexName = lc $table.'_ix_'.join('_',@$colNameA);
2668 1 $self->checkName(\$indexName);
2669  
2670 1 return $indexName;
2671 }
2672  
2673 # -----------------------------------------------------------------------------
2674  
2675 =head3 createIndex() - Generiere CREATE INDEX Statement
2676  
2677 =head4 Synopsis
2678  
2679 $stmt = $sql->createIndex($tableName,\@colNames,@opt);
2680  
2681 =head4 Options
2682  
2683 =over 4
2684  
2685 =item -indexName => $str (Default: <TABLE>_ix_<COLUMNS>)
2686  
2687 Name des Index.
2688  
2689 =item -tableSpace => $tableSpaceName (Default: keiner)
2690  
2691 Name des Tablespace, in dem der Index erzeugt wird
2692 (Oracle und PostgreSQL).
2693  
2694 =item -unique => $bool (Default: 0)
2695  
2696 Statement für Unique Index.
2697  
2698 =back
2699  
2700 =head4 Description
2701  
2702 Generiere ein CREATE INDEX Statement und liefere dieses zurück.
2703  
2704 B<Oracle Syntax>
2705  
2706 CREATE [UNIQUE] INDEX <INDEX_NAME> ON <TABLE_NAME>
2707 (<TABLE_COLUMNS>)
2708 TABLESPACE <TABLESPACE_NAME>
2709  
2710 B<PostgreSQL Syntax>
2711  
2712 CREATE [UNIQUE] INDEX <INDEX_NAME> ON <TABLE_NAME>
2713 (<TABLE_COLUMNS>)
2714 TABLESPACE <TABLESPACE_NAME>
2715  
2716 B<SQLite Syntax>
2717  
2718 CREATE [UNIQUE] INDEX <INDEX_NAME> ON <TABLE_NAME>
2719 (<TABLE_COLUMNS>)
2720  
2721 B<MySQL Syntax>
2722  
2723 CREATE [UNIQUE] INDEX <INDEX_NAME> ON <TABLE_NAME>
2724 (<TABLE_COLUMNS>)
2725  
2726 =cut
2727  
2728 # -----------------------------------------------------------------------------
2729  
2730 1 ▶sub createIndex {
Subroutine createIndex: called CC=11 SCAR=30.3
Pod documented
2731 1 my $self = shift;
2732 1 my $tableName = shift;
2733 1 my $colNameA = shift;
2734  
2735 # Optionen
2736  
2737 1 my $indexName = undef;
2738 1 my $tableSpace = undef;
2739 1 my $unique = 0;
2740  
2741 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
2742 0 Quiq::Option->extract(\@_,
2743 -indexName => \$indexName,
2744 -tableSpace => \$tableSpace,
2745 -unique => \$unique,
2746 );
2747 }
2748  
2749 # FIXME: Methode indexName() implementieren
2750  
2751 1 ▶ if (!$indexName) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $indexName) { } 1 0 1
2752 #my ($table) = $self->splitObjectName($tableName);
2753 #$indexName = $table.'_ix_'.join('_',@$colNameA);
2754 1 $indexName = $self->indexName($tableName,$colNameA);
2755 }
2756 else {
2757 0 $self->checkName(\$indexName);
2758 }
2759  
2760 # Statement generieren
2761  
2762 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2763  
2764 1 my $stmt;
2765 1 ▶ if ($oracle || $postgresql || $sqlite || $mysql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql or $sqlite or $mysql) { } 1 0 1
Condition33%3/9
$oracle or $postgresql or $sqlite or $mysql
l!l&&r!l&&!r
100
$oracle or $postgresql or $sqlite
l!l&&r!l&&!r
100
$oracle or $postgresql
l!l&&r!l&&!r
010
MC/DC0%0/4
$oracle or $postgresql or $sqlite or $mysql
$oracle $postgresql $sqlite $mysql
Truth table20%1/5
A or B or C or D
A= $oracleB= $postgresqlC= $sqliteD= $mysql
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2766 1 ▶ $stmt = sprintf "CREATE%s INDEX %s\n".
Branch: 1 branch
BranchTrueFalseTotal
$unique ? : 0 1 1
2767 " ON %s\n".
2768 " (%s)",
2769 $unique? ' UNIQUE': '',
2770 $indexName,
2771 $tableName,
2772 join(', ',@$colNameA);
2773  
2774 1 ▶ if ($tableSpace && !$mysql && !$sqlite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tableSpace and not $mysql and not $sqlite) 0 1 1
Condition33%2/6
$tableSpace and not $mysql and not $sqlite
!ll&&!rl&&r
100
$tableSpace and not $mysql
!ll&&!rl&&r
100
MC/DC0%0/3
$tableSpace and not $mysql and not $sqlite
$tableSpace not $mysql not $sqlite
Truth table25%1/4
A and not(B) and not(C)
A= $tableSpaceB= not $mysqlC= not $sqlite
ABCresult
0XX0
10X0
1100
1111
2775 0 $stmt .= "\n TABLESPACE $tableSpace";
2776 }
2777  
2778 }
2779 else {
2780 0 $self->throw('Not implemented');
2781 }
2782  
2783 1 return $stmt;
2784 }
2785  
2786 # -----------------------------------------------------------------------------
2787  
2788 =head3 dropIndex() - Generiere DROP INDEX Statement
2789  
2790 =head4 Synopsis
2791  
2792 $stmt = $sql->dropIndex($tableName,\@colNames);
2793  
2794 =head4 Description
2795  
2796 Generiere ein DROP INDEX Statement und liefere dieses zurück.
2797  
2798 B<Syntax>
2799  
2800 DROP INDEX <INDEX_NAME>
2801  
2802 =cut
2803  
2804 # -----------------------------------------------------------------------------
2805  
2806 0 ▶sub dropIndex {
Subroutine dropIndex: not called CC=1 SCAR=6.9
Pod documented
2807 0 my $self = shift;
2808 0 my $tableName = shift;
2809 0 my $colNameA = shift;
2810  
2811 #!! FIXME: Methode indexName() implementieren
2812 #
2813 #my ($table) = $self->splitObjectName($tableName);
2814 #my $indexName = $table.'_ix_'.join('_',@$colNameA);
2815 #$self->checkName(\$indexName);
2816  
2817 0 my $indexName = $self->indexName($tableName,$colNameA);
2818 0 return "DROP INDEX $indexName";
2819 }
2820  
2821 # -----------------------------------------------------------------------------
2822  
2823 =head2 Sequence
2824  
2825 =head3 createSequence() - Generiere SQL-Statements zur Erzeugung einer Sequenz
2826  
2827 =head4 Synopsis
2828  
2829 @stmt = $sql->createSequence($name,@opt);
2830  
2831 =head4 Options
2832  
2833 =over 4
2834  
2835 =item -startWith => $n (Default: 1)
2836  
2837 Lasse die Sequenz mit Startwert $n beginnen.
2838  
2839 =back
2840  
2841 =head4 Description
2842  
2843 Generiere Statements zur Erzeugung von Sequenz $name und liefere
2844 diese zurück.
2845  
2846 Unter Oracle und PostgreSQL, die das Konzept der Sequenz haben,
2847 wird ein CREATE SEQUENCE Statement generiert.
2848  
2849 Unter MySQL und SQLite, die das Konzept der Sequenz nicht haben,
2850 wird eine Tabelle (CREATE TABLE) mit Autoinkrement-Kolumne zur
2851 Simulation einer Sequenz erzeugt. Ist die Option -startWith angegeben,
2852 wird zusätzlich ein INSERT-Statement generiert.
2853  
2854 =cut
2855  
2856 # -----------------------------------------------------------------------------
2857  
2858 2 ▶sub createSequence {
Subroutine createSequence: called CC=7 SCAR=21.1
Pod documented
2859 2 my $self = shift;
2860 2 my $name = shift;
2861  
2862 # Optionen
2863  
2864 2 my $startWith = 1;
2865 2 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 0 2
2866 2 Quiq::Option->extract(\@_,
2867 -startWith => \$startWith,
2868 );
2869 }
2870  
2871 # FIXME: Test $startWith auf >= 1
2872  
2873 # Statement(s) generieren
2874  
2875 2 my @stmt;
2876 2 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2877 2 ▶ if ($oracle || $postgresql) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle or $postgresql) { } 0 2 2
elsif ($mysql or $sqlite) { } 2 0 2
Condition33%1/3
$oracle or $postgresql
l!l&&r!l&&!r
002
MC/DC0%0/2
$oracle or $postgresql
$oracle $postgresql
Truth table33%1/3
A or B
A= $oracleB= $postgresql
ABresult
1X1
011
000
2878 0 push @stmt,"CREATE SEQUENCE $name START WITH $startWith";
2879 }
2880 ▶ elsif ($mysql || $sqlite) {
Condition33%1/3
$mysql or $sqlite
l!l&&r!l&&!r
020
MC/DC0%0/2
$mysql or $sqlite
$mysql $sqlite
Truth table33%1/3
A or B
A= $mysqlB= $sqlite
ABresult
1X1
011
000
2881 2 push @stmt,$self->createTable($name,
2882 ['n',type=>'INTEGER(10)',notNull=>1,primaryKey=>1,
2883 autoIncrement=>1],
2884 );
2885 2 ▶ if ($startWith != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($startWith != 1) 1 1 2
2886 1 push @stmt,$self->insert($name,n=>$startWith-1);
2887 }
2888 }
2889  
2890 2 return @stmt;
2891 }
2892  
2893 # -----------------------------------------------------------------------------
2894  
2895 =head3 dropSequence() - Generiere SQL-Statement zum Löschen einer Sequenz
2896  
2897 =head4 Synopsis
2898  
2899 $stmt = $sql->dropSequence($name);
2900  
2901 =head4 Description
2902  
2903 Generiere SQL-Statement zum Löschen von Sequenz $name und liefere
2904 dieses zurück.
2905  
2906 Unter Oracle und PostgreSQL, die das Konzept der Sequenz haben,
2907 wird ein DROP SEQUENCE Statement generiert.
2908  
2909 Unter MySQL und SQLite, die das Konzept der Sequenz nicht haben,
2910 wird ein DROP TABLE Statement generiert.
2911  
2912 =cut
2913  
2914 # -----------------------------------------------------------------------------
2915  
2916 0 ▶sub dropSequence {
Subroutine dropSequence: not called CC=3 SCAR=24.8
Pod documented
2917 0 my ($self,$name) = @_;
2918  
2919 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2920  
2921 # Statement generieren
2922  
2923 0 ▶ if ($mysql || $sqlite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mysql or $sqlite) 0 0 0
Condition0%0/3
$mysql or $sqlite
l!l&&r!l&&!r
000
MC/DC0%0/2
$mysql or $sqlite
$mysql $sqlite
Truth table0%0/3
A or B
A= $mysqlB= $sqlite
ABresult
1X1
011
000
2924 0 return $self->dropTable($name);
2925 }
2926  
2927 0 return "DROP SEQUENCE $name";
2928 }
2929  
2930 # -----------------------------------------------------------------------------
2931  
2932 =head3 setSequence() - Generiere SQL-Statements zum Setzen einer Sequenz
2933  
2934 =head4 Synopsis
2935  
2936 @stmt = $sql->setSequence($name,$n);
2937  
2938 =head4 Description
2939  
2940 Generiere SQL-Statements zum Setzen von Sequenz $name auf Wert $n.
2941  
2942 =over 2
2943  
2944 =item *
2945  
2946 Unter Oracle wird die Sequenz gedroppt und neu erzeugt.
2947  
2948 =item *
2949  
2950 Unter PostgreSQL wird der Wert mit ALTER SEQUENCE gesetzt.
2951  
2952 =item *
2953  
2954 Unter MySQL und SQLite, die das Konzept der Sequenz nicht haben,
2955 wird die Sequenz-Tabelle geleert und der Wert als neuer
2956 Datensatz hinzugefügt. Einschränkung: Der Sequenzwert kann
2957 hochgesetzt, aber nicht verringert werden!
2958  
2959 =back
2960  
2961 =cut
2962  
2963 # -----------------------------------------------------------------------------
2964  
2965 1 ▶sub setSequence {
Subroutine setSequence: called CC=5 SCAR=19.8
Pod documented
2966 1 my ($self,$sequence,$n) = @_;
2967  
2968 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
2969  
2970 # Statements generieren
2971  
2972 1 my @stmt;
2973 1 ▶ if ($oracle) {
Branch: 3 branches
BranchTrueFalseTotal
if ($oracle) { } 0 1 1
elsif ($postgresql) { } 0 1 1
elsif ($mysql or $sqlite) { } 1 0 1
2974 0 push @stmt,"DROP SEQUENCE $sequence";
2975 0 push @stmt,"CREATE SEQUENCE $sequence START WITH $n";
2976 }
2977 elsif ($postgresql) {
2978 0 push @stmt,"ALTER SEQUENCE $sequence RESTART WITH $n";
2979 }
2980 ▶ elsif ($mysql || $sqlite) {
Condition33%1/3
$mysql or $sqlite
l!l&&r!l&&!r
010
MC/DC0%0/2
$mysql or $sqlite
$mysql $sqlite
Truth table33%1/3
A or B
A= $mysqlB= $sqlite
ABresult
1X1
011
000
2981 1 push @stmt,"DELETE FROM $sequence";
2982 1 push @stmt,sprintf "INSERT INTO $sequence VALUES (%d)",$n-1;
2983 }
2984 else {
2985 0 die; # FIXME
2986 }
2987  
2988 1 return @stmt;
2989 }
2990  
2991 # -----------------------------------------------------------------------------
2992  
2993 =head2 Function
2994  
2995 =head3 createFunction() - Generiere Statement zum Erzeugen einer Funktion
2996  
2997 =head4 Synopsis
2998  
2999 $stmt = $sql->createFunction($signature,$body,@opt);
3000  
3001 =head4 Arguments
3002  
3003 =over 4
3004  
3005 =item $signature
3006  
3007 Signatur der Funktion, also Name mit Typ-Parameterliste und ggf.
3008 Schema-Präfix.
3009  
3010 =item $body
3011  
3012 Rumpf der Funktion.
3013  
3014 =back
3015  
3016 =head4 Options
3017  
3018 =over 4
3019  
3020 =item -replace => $bool (Default: 0)
3021  
3022 Generiere "OR REPLACE" Klausel.
3023  
3024 =item -returns => $type (Default: undef)
3025  
3026 Generiere "RETURNS $type" Klausel.
3027  
3028 =back
3029  
3030 =head4 Description
3031  
3032 B<PostgreSQL>
3033  
3034 CREATE OR REPLACE FUNCTION <signature>
3035 RETURNS <returns>
3036 AS $SQL$
3037 <body>
3038 $SQL$ LANGUAGE plpgsql
3039  
3040 =over 2
3041  
3042 =item *
3043  
3044 <name> kann Schema enthalten
3045  
3046 =back
3047  
3048 =cut
3049  
3050 # -----------------------------------------------------------------------------
3051  
3052 1 ▶sub createFunction {
Subroutine createFunction: called CC=4 SCAR=14.0
Pod documented
3053 1 my $self = shift;
3054 # @_: $signature,$body,@opt
3055  
3056 # Argumente
3057  
3058 1 my $replace = 0;
3059 1 my $returns = undef;
3060  
3061 1 Quiq::Option->extract(\@_,
3062 -replace => \$replace,
3063 -returns => \$returns,
3064 );
3065 1 my $signature = shift;
3066 1 my $body = Quiq::String->removeIndentation(shift);
3067  
3068 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3069  
3070 1 my $stmt;
3071 1 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) { } 1 0 1
3072 1 $stmt = 'CREATE';
3073 1 ▶ if ($replace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($replace) 1 0 1
3074 1 $stmt .= ' OR REPLACE';
3075 }
3076 1 $stmt .= " FUNCTION $signature";
3077 1 ▶ if ($returns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returns) 1 0 1
3078 1 $stmt .= "\nRETURNS $returns";
3079 }
3080 1 $stmt .= "\nAS \$SQL\$";
3081 1 $stmt .= "\n$body";
3082 1 $stmt .= "\n\$SQL\$ LANGUAGE plpgsql";
3083 }
3084 else {
3085 0 $self->throw('Not implemented');
3086 }
3087  
3088 1 return $stmt;
3089 }
3090  
3091 # -----------------------------------------------------------------------------
3092  
3093 =head3 dropFunction() - Generiere Statement zum Entfernen einer Funktion
3094  
3095 =head4 Synopsis
3096  
3097 $stmt = $sql->dropFunction($signature);
3098  
3099 =head4 Arguments
3100  
3101 =over 4
3102  
3103 =item $signature
3104  
3105 Signatur der Funktion, also Name mit Typ-Parameterliste und ggf.
3106 Schema-Präfix.
3107  
3108 =back
3109  
3110 =head4 Description
3111  
3112 B<PostgreSQL>
3113  
3114 DROP FUNCTION <signature> CASCADE
3115  
3116 =cut
3117  
3118 # -----------------------------------------------------------------------------
3119  
3120 0 ▶sub dropFunction {
Subroutine dropFunction: not called CC=3 SCAR=24.8
Pod documented
3121 0 my $self = shift;
3122 # @_: $signature,@opt
3123  
3124 # Argumente
3125  
3126 0 my $cascade = 0;
3127  
3128 0 Quiq::Option->extract(\@_,
3129 -cascade => \$cascade,
3130 );
3131 0 my $signature = shift;
3132  
3133 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3134  
3135 0 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) 0 0 0
3136 0 my $stmt = "DROP FUNCTION $signature";
3137 0 ▶ if ($cascade) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cascade) 0 0 0
3138 0 $stmt .= ' CASCADE';
3139 }
3140 0 return $stmt;
3141 }
3142  
3143 0 $self->throw('Not implemented');
3144 }
3145  
3146 # -----------------------------------------------------------------------------
3147  
3148 =head3 moveFunction() - Bewege Funktion in ein anderes Schema
3149  
3150 =head4 Synopsis
3151  
3152 $stmt = $sql->moveFunction($signature,$schema);
3153  
3154 =head4 Arguments
3155  
3156 =over 4
3157  
3158 =item $signature
3159  
3160 Signatur der Funktion, also Name mit Typ-Parameterliste und
3161 Schema-Präfix.
3162  
3163 =item $schema
3164  
3165 Zielschema, in das die Funktion bewegt wird.
3166  
3167 =back
3168  
3169 =head4 Description
3170  
3171 B<PostgreSQL>
3172  
3173 ALTER FUNCTION <signature> SET SCHEMA <schema>
3174  
3175 =cut
3176  
3177 # -----------------------------------------------------------------------------
3178  
3179 0 ▶sub moveFunction {
Subroutine moveFunction: not called CC=2 SCAR=17.9
Pod documented
3180 0 my ($self,$signature,$schema) = @_;
3181  
3182 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3183  
3184 0 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) 0 0 0
3185 0 return "ALTER FUNCTION $signature SET SCHEMA $schema";
3186 }
3187  
3188 0 $self->throw('Not implemented');
3189 }
3190  
3191 # -----------------------------------------------------------------------------
3192  
3193 =head2 Trigger
3194  
3195 =head3 createTrigger() - Generiere Statement zum Erzeugen eines Triggers
3196  
3197 =head4 Synopsis
3198  
3199 $stmt = $sql->createTrigger($table,$name,$when,$event,$level,
3200 $body,@opt);
3201 $stmt = $sql->createTrigger($table,$name,$when,$event,$level,
3202 -execute => $proc,@opt);
3203  
3204 =head4 Options
3205  
3206 =over 4
3207  
3208 =item -replace => $bool (Default: 0)
3209  
3210 Generiere "OR REPLACE" Klausel (Oracle).
3211  
3212 =item -execute => $proc (Default: undef)
3213  
3214 Generiere "EXECUTE PROCEDURE $proc()" Klausel.
3215  
3216 =back
3217  
3218 =head4 Description
3219  
3220 B<Oracle>
3221  
3222 $stmt = $sql->createTrigger(
3223 '<table>',
3224 '<name>',
3225 'before',
3226 'insert|update',
3227 'row',
3228 -replace => 1,'
3229 <body>
3230 '
3231 );
3232
3233 CREATE OR REPLACE TRIGGER <name>
3234 BEFORE INSERT OR UPDATE ON <table>
3235 FOR EACH ROW
3236 <body>
3237  
3238 =over 2
3239  
3240 =item *
3241  
3242 Oracle-Trigger können eine Prozedur können einen
3243 Trigger-Body definieren.
3244  
3245 =back
3246  
3247 B<PostgreSQL>
3248  
3249 $stmt = $sql->createTrigger(
3250 '<table>',
3251 '<name>',
3252 'before',
3253 'insert|update',
3254 'row',
3255 -execute => '<proc>',
3256 );
3257
3258 CREATE TRIGGER <name>
3259 BEFORE INSERT OR UPDATE ON <table>
3260 FOR EACH ROW
3261 EXECUTE PROCEDURE <proc>()
3262  
3263 =over 2
3264  
3265 =item *
3266  
3267 Trigger können eine Prozedur aufrufen (-execute=>$proc) aber keinen
3268 Trigger-Body definieren.
3269  
3270 =item *
3271  
3272 Keine Klausel "OR REPLACE" bei Triggern (-replace=>1 wird ignoriert)
3273  
3274 =back
3275  
3276 =cut
3277  
3278 # -----------------------------------------------------------------------------
3279  
3280 2 ▶sub createTrigger {
Subroutine createTrigger: called CC=8 SCAR=20.9
Pod documented
3281 2 my $self = shift;
3282 2 my $table = shift;
3283 2 my $trigger = shift;
3284 2 my $when = shift;
3285 2 my $event = shift;
3286 2 my $level = shift;
3287 # @_: @opt
3288  
3289 # Optionen
3290  
3291 2 my $execute = undef;
3292 2 my $replace = 0;
3293  
3294 2 Quiq::Option->extract(\@_,
3295 -execute => \$execute,
3296 -replace => \$replace,
3297 );
3298 2 my $body = Quiq::String->removeIndentation(shift);
3299  
3300 2 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3301  
3302 2 my $stmt;
3303 2 ▶ if ($oracle || $postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle or $postgresql) { } 2 0 2
Condition66%2/3
$oracle or $postgresql
l!l&&r!l&&!r
110
MC/DC0%0/2
$oracle or $postgresql
$oracle $postgresql
Truth table66%2/3
A or B
A= $oracleB= $postgresql
ABresult
1X1
011
000
3304 2 $stmt = 'CREATE';
3305 2 ▶ if ($replace && !$postgresql) { # PostgreSQL kennt REPLACE nicht
Branch: 1 branch
BranchTrueFalseTotal
if ($replace and not $postgresql) 1 1 2
Condition66%2/3
$replace and not $postgresql
!ll&&!rl&&r
011
MC/DC50%1/2
$replace and not $postgresql
$replace not $postgresql
Truth table66%2/3
A and not(B)
A= $replaceB= not $postgresql
ABresult
0X0
100
111
3306 1 $stmt .= ' OR REPLACE';
3307 }
3308 2 $stmt .= " TRIGGER $trigger";
3309 2 $stmt .= "\n".uc($when);
3310 2 $stmt .= ' '.join(' OR ',map {uc} split /\|/,$event)." ON $table";
3311 2 $stmt .= "\nFOR EACH ".uc($level);
3312 2 ▶ if ($body && !$postgresql) { # PostgreSQL kennt keinen Trigger-Body
Branch: 1 branch
BranchTrueFalseTotal
if ($body and not $postgresql) 1 1 2
Condition66%2/3
$body and not $postgresql
!ll&&!rl&&r
101
MC/DC50%1/2
$body and not $postgresql
$body not $postgresql
Truth table66%2/3
A and not(B)
A= $bodyB= not $postgresql
ABresult
0X0
100
111
3313 1 $stmt .= "\n$body";
3314 }
3315 2 ▶ if ($execute) {
Branch: 1 branch
BranchTrueFalseTotal
if ($execute) 1 1 2
3316 1 $stmt .= "\nEXECUTE PROCEDURE $execute()";
3317 }
3318 }
3319 else {
3320 0 $self->throw('Not implemented');
3321 }
3322  
3323 2 return $stmt;
3324 }
3325  
3326 # -----------------------------------------------------------------------------
3327  
3328 =head3 dropTrigger() - Generiere Statement zum Entfernen eines Triggers
3329  
3330 =head4 Synopsis
3331  
3332 $stmt = $sql->dropTrigger($name);
3333  
3334 =head4 Description
3335  
3336 B<Oracle>
3337  
3338 DROP TRIGGER <name>
3339  
3340 =cut
3341  
3342 # -----------------------------------------------------------------------------
3343  
3344 0 ▶sub dropTrigger {
Subroutine dropTrigger: not called CC=2 SCAR=17.9
Pod documented
3345 0 my ($self,$name) = @_;
3346  
3347 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3348  
3349 0 ▶ if ($oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle) 0 0 0
3350 0 return "DROP TRIGGER $name";
3351 }
3352  
3353 0 $self->throw('Not implemented');
3354 }
3355  
3356 # -----------------------------------------------------------------------------
3357  
3358 =head3 enableTrigger() - Generiere Statement zum Anschalten eines Triggers
3359  
3360 =head4 Synopsis
3361  
3362 $stmt = $sql->enableTrigger($table,$tigger);
3363  
3364 =head4 Description
3365  
3366 B<PostgreSQL>
3367  
3368 ALTER TABLE <table> ENABLE TRIGGER <trigger>
3369  
3370 =cut
3371  
3372 # -----------------------------------------------------------------------------
3373  
3374 0 ▶sub enableTrigger {
Subroutine enableTrigger: not called CC=2 SCAR=17.9
Pod documented
3375 0 my ($self,$table,$trigger) = @_;
3376  
3377 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3378  
3379 0 my $stmt;
3380 0 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) { } 0 0 0
3381 0 return "ALTER TABLE $table ENABLE TRIGGER $trigger";
3382 }
3383 else {
3384 0 $self->throw('Not implemented');
3385 }
3386  
3387 0 return $stmt;
3388 }
3389  
3390 # -----------------------------------------------------------------------------
3391  
3392 =head3 disableTrigger() - Generiere Statement zum Abschalten eines Triggers
3393  
3394 =head4 Synopsis
3395  
3396 $stmt = $sql->disableTrigger($table,$tigger);
3397  
3398 =head4 Description
3399  
3400 B<PostgreSQL>
3401  
3402 ALTER TABLE <table> DISABLE TRIGGER <trigger>
3403  
3404 =cut
3405  
3406 # -----------------------------------------------------------------------------
3407  
3408 0 ▶sub disableTrigger {
Subroutine disableTrigger: not called CC=2 SCAR=17.9
Pod documented
3409 0 my ($self,$table,$trigger) = @_;
3410  
3411 0 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3412  
3413 0 my $stmt;
3414 0 ▶ if ($postgresql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($postgresql) { } 0 0 0
3415 0 return "ALTER TABLE $table DISABLE TRIGGER $trigger";
3416 }
3417 else {
3418 0 $self->throw('Not implemented');
3419 }
3420  
3421 0 return $stmt;
3422 }
3423  
3424 # -----------------------------------------------------------------------------
3425  
3426 =head2 View
3427  
3428 =head3 createView() - Generiere CREATE VIEW Statement
3429  
3430 =head4 Synopsis
3431  
3432 $stmt = $sql->createView($viewName,$selectStmt);
3433  
3434 =head4 Description
3435  
3436 Generiere ein CREATE VIEW Statement und liefere dieses zurück.
3437  
3438 =cut
3439  
3440 # -----------------------------------------------------------------------------
3441  
3442 1 ▶sub createView {
Subroutine createView: called CC=1 SCAR=0.0
Pod documented
3443 1 my ($self,$viewName,$selectStmt) = @_;
3444 1 return "CREATE VIEW $viewName AS\n$selectStmt";
3445 }
3446  
3447 # -----------------------------------------------------------------------------
3448  
3449 =head3 dropView() - Generiere DROP VIEW Statement
3450  
3451 =head4 Synopsis
3452  
3453 $stmt = $sql->dropView($viewName);
3454  
3455 =head4 Description
3456  
3457 Generiere ein DROP VIEW Statement und liefere dieses zurück.
3458  
3459 =cut
3460  
3461 # -----------------------------------------------------------------------------
3462  
3463 1 ▶sub dropView {
Subroutine dropView: called CC=1 SCAR=0.0
Pod documented
3464 1 my ($self,$viewName) = @_;
3465 1 return "DROP VIEW $viewName";
3466 }
3467  
3468 # -----------------------------------------------------------------------------
3469  
3470 =head2 Privileges
3471  
3472 =head3 grant() - Generiere GRANT Statement
3473  
3474 =head4 Synopsis
3475  
3476 $stmt = $sql->grant($objType,$objName,$privs,$roles);
3477  
3478 =head4 Description
3479  
3480 Generiere ein GRANT-Statement und liefere dieses zurück.
3481  
3482 =head4 Example
3483  
3484 =over 2
3485  
3486 =item *
3487  
3488 PostgreSQL GRANT auf Tabelle
3489  
3490 $stmt = $sql->grant('TABLE','tab1','ALL','PUBLIC');
3491  
3492 generiert
3493  
3494 GRANT ALL
3495 ON TABLE tab1
3496 TO PUBLIC
3497  
3498 =back
3499  
3500 =cut
3501  
3502 # -----------------------------------------------------------------------------
3503  
3504 1 ▶sub grant {
Subroutine grant: called CC=3 SCAR=11.4
Pod documented
3505 1 my $self = shift;
3506 1 my $objType = shift;
3507 1 my $objName = shift;
3508 1 my $privs = shift;
3509 1 my $roles = shift;
3510  
3511 # Statement generieren
3512  
3513 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3514  
3515 1 my $stmt;
3516 1 ▶ if ($oracle) {
Branch: 2 branches
BranchTrueFalseTotal
if ($oracle) { } 0 1 1
elsif ($postgresql) { } 1 0 1
3517 0 $stmt = "GRANT $privs\n".
3518 " ON $objName\n".
3519 " TO $roles";
3520 }
3521 elsif ($postgresql) {
3522 1 $stmt = "GRANT $privs\n".
3523 " ON $objType $objName\n".
3524 " TO $roles";
3525 }
3526 else {
3527 0 die;
3528 }
3529  
3530 1 return $stmt;
3531 }
3532  
3533 # -----------------------------------------------------------------------------
3534  
3535 =head3 grantUser() - Generiere GRANT Statement für Benutzerrechte
3536  
3537 =head4 Synopsis
3538  
3539 $stmt = $sql->grantUser($userName,$privs);
3540  
3541 =head4 Example
3542  
3543 =over 2
3544  
3545 =item *
3546  
3547 Oracle GRANT für Benutzer
3548  
3549 $stmt = $sql->grantUser('user1','connect, resource, dba');
3550  
3551 generiert
3552  
3553 GRANT connect, resource, dba
3554 TO user1
3555  
3556 =back
3557  
3558 =cut
3559  
3560 # -----------------------------------------------------------------------------
3561  
3562 1 ▶sub grantUser {
Subroutine grantUser: called CC=2 SCAR=7.1
Pod documented
3563 1 my $self = shift;
3564 1 my $userName = shift;
3565 1 my $privs = shift;
3566  
3567 # Statement generieren
3568  
3569 1 my ($oracle,$postgresql,$sqlite,$mysql) = $self->dbmsTestVector;
3570  
3571 1 my $stmt;
3572 1 ▶ if ($oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oracle) { } 1 0 1
3573 1 $stmt = "GRANT $privs\n".
3574 " TO $userName";
3575 }
3576 else {
3577 0 die;
3578 }
3579  
3580 1 return $stmt;
3581 }
3582  
3583 # -----------------------------------------------------------------------------
3584  
3585 =head2 Transactions
3586  
3587 =head3 begin() - Generiere BEGIN Statement
3588  
3589 =head4 Synopsis
3590  
3591 $stmt = $sql->begin;
3592  
3593 =cut
3594  
3595 # -----------------------------------------------------------------------------
3596  
3597 9 ▶sub begin {
Subroutine begin: called CC=1 SCAR=0.0
Pod documented
3598 9 return 'BEGIN';
3599 }
3600  
3601 # -----------------------------------------------------------------------------
3602  
3603 =head3 commit() - Generiere COMMIT Statement
3604  
3605 =head4 Synopsis
3606  
3607 $stmt = $sql->commit;
3608  
3609 =cut
3610  
3611 # -----------------------------------------------------------------------------
3612  
3613 46 ▶sub commit {
Subroutine commit: called CC=1 SCAR=0.0
Pod documented
3614 46 return 'COMMIT';
3615 }
3616  
3617 # -----------------------------------------------------------------------------
3618  
3619 =head3 rollback() - Generiere ROLLBACK Statement
3620  
3621 =head4 Synopsis
3622  
3623 $stmt = $sql->rollback;
3624  
3625 =cut
3626  
3627 # -----------------------------------------------------------------------------
3628  
3629 9 ▶sub rollback {
Subroutine rollback: called CC=1 SCAR=0.0
Pod documented
3630 9 return 'ROLLBACK';
3631 }
3632  
3633 # -----------------------------------------------------------------------------
3634  
3635 =head2 Data Manipulation
3636  
3637 =head3 select() - Generiere SELECT Statement
3638  
3639 =head4 Synopsis
3640  
3641 $stmt = $sql->select($stmt,@opt);
3642 $stmt = $sql->select($table,@opt);
3643 $stmt = $sql->select(@opt);
3644  
3645 =head4 Options
3646  
3647 =over 4
3648  
3649 =item -comment => $text
3650  
3651 Setze Kommentar mit dem ein- oder mehrzeiligen Text $text an den
3652 Anfang des Statement.
3653  
3654 =item -with => @withElements
3655  
3656 Liste von WITH-Elementen. Dies ist eine Liste von
3657 Schlüssel/Wert-Paaren der Art
3658  
3659 $name => $select, ...
3660  
3661 =item -select => @selectExpr (Default: '*')
3662  
3663 Generiere eine SELECT-Klausel aus den Ausdrücken @selectExpr. Die
3664 Ausdrücke werden mit Komma separiert. Ist kein Select-Ausdrück
3665 spezifiziert, wird '*' angenommen.
3666  
3667 Platzhalter: %SELECT%
3668  
3669 =item -distinct => $bool
3670  
3671 Generiere "SELECT DISTINCT" statement.
3672  
3673 Schlüsselwort "DISTINCT" wird in %SELECT%-Platzhalter mit eingsetzt.
3674  
3675 =item -hint => $hint
3676  
3677 Setze im Statement hinter das Schlüsselwort SELECT einen
3678 Hint, d.h. einen Kommentar in der Form /*+ ... */. (nur Oracle)
3679  
3680 hint wird in %SELECT%-Platzhalter mit eingsetzt.
3681  
3682 =item -from => @fromExpr
3683  
3684 Generiere eine FROM-Klausel aus den Ausdrücken @fromExpr.
3685 Die Ausdrücke werden mit Komma separiert. Die FROM-Klausel ist
3686 bei Oracle eine Pflichtangabe.
3687  
3688 Platzhalter: %FROM%
3689  
3690 -from ist die Defaultoption, d.h. ist als erster Parameter keine
3691 Option angegeben, werden die folgenden Parameter als
3692 Tabellennamen interpretiert.
3693  
3694 =item -where => @whereExpr
3695  
3696 Generiere eine WHERE-Klausel aus den Ausdrücken @whereExpr.
3697 Die Ausdrücke werden mit 'AND' separiert.
3698  
3699 Platzhalter: %WHERE%
3700  
3701 =item -groupBy => @groupExpr
3702  
3703 Generiere eine GROUP BY-Klausel aus den Ausdrücken @groupExpr.
3704 Die Ausdrücke werden mit Komma separiert.
3705  
3706 Platzhalter: %GROUPBY%
3707  
3708 =item -having => @havingExpr
3709  
3710 Generiere eine HAVING-Klausel aus den Ausdrücken @havingExpr.
3711 Die Ausdrücke werden mit Komma separiert.
3712  
3713 Platzhalter: %HAVING%
3714  
3715 =item -orderBy => @orderExpr
3716  
3717 Generiere eine ORDER BY-Klausel aus den Ausdrücken @orderExpr.
3718 Die Ausdrücke werden mit Komma separiert.
3719  
3720 Platzhalter: %ORDERBY%
3721  
3722 =item -limit => $n
3723  
3724 Generiere eine LIMIT-Klausel.
3725  
3726 Platzhalter: %LIMIT%
3727  
3728 =item -offset => $n
3729  
3730 Generiere eine OFFSET-Klausel.
3731  
3732 Platzhalter: %OFFSET%
3733  
3734 =item -stmt => $stmt
3735  
3736 Liefere $stmt als Statement. Enthält $stmt Platzhalter,
3737 werden diese durch die entsprechenden Komponenten ersetzt
3738 (noch nicht implementiert).
3739  
3740 =back
3741  
3742 =head4 Description
3743  
3744 Konstruiere ein SELECT-Statement aus den Parametern und liefere
3745 dieses zurück.
3746  
3747 Ist das erste Argument keine Option und enthält es Whitespace,
3748 wird es als SQL-Statement interpretiert. Enthält es kein Whitespace, wird
3749 es als Tabellenname interpretiert.
3750  
3751 B<Besonderheiten>
3752  
3753 =over 2
3754  
3755 =item *
3756  
3757 Oracle: FROM-Klausel
3758  
3759 Bei Oracle ist die FROM-Klausel eine Pflichtangabe, fehlt sie,
3760 wird "FROM dual" generiert.
3761  
3762 =item *
3763  
3764 Oracle: LIMIT und OFFSET
3765  
3766 Oracle unterstützt weder LIMIT noch OFFSET.
3767  
3768 Im Falle von Oracle wird keine LIMIT-Klausel generiert, sondern
3769 die WHERE-Klausel um "ROWNUM <= $n" erweitert.
3770  
3771 Ist im Falle von Oracle OFFSET angegeben, wird eine Exception
3772 ausgelöst.
3773  
3774 =back
3775  
3776 B<FROM-Aliase>
3777  
3778 Bei PostgreSQL ist ein FROM-Alias zwingend erforderlich, wenn die
3779 FROM-Klausel ein Ausdruck ist statt ein Tabellenname, z.B.
3780  
3781 ... FROM (<SELECT_STMT>) AS x ...
3782  
3783 Bei Oracle ist ein Alias in dem Fall nicht erforderlich, kann aber
3784 angegeben werden. Ein FROM-Alias wird bei Oracle aber IL<lt>nicht> mit
3785 "AS" eingeleitet. Das "AS" muss weggelassen werden.
3786  
3787 =head4 Example
3788  
3789 =over 2
3790  
3791 =item *
3792  
3793 SELECT ohne Option mit einem Argument
3794  
3795 $stmt = $sql->select('x');
3796 =>
3797 SELECT
3798 *
3799 FROM
3800 x
3801  
3802 =item *
3803  
3804 SELECT ohne Option mit mehreren Argumenten
3805  
3806 $stmt = $sql->select('x',vorname=>'Elli',nachname=>'Pirelli');
3807 =>
3808 SELECT
3809 *
3810 FROM
3811 x
3812 WHERE
3813 vorname = 'Elli'
3814 AND nachname = 'Pirelli'
3815  
3816 =item *
3817  
3818 SELECT mit Statement-Platzhaltern
3819  
3820 $stmt = $sql->select("
3821 SELECT
3822 *
3823 FROM
3824 x
3825 WHERE
3826 vorname = '__VORNAME__'
3827 AND nachname = '__NACHNAME__'
3828 ",
3829 -placeholders =>
3830 __VORNAME__ => 'Elli',
3831 __NACHNAME__ => 'Pirelli'
3832 );
3833 =>
3834 SELECT
3835 *
3836 FROM
3837 x
3838 WHERE
3839 vorname = 'Elli'
3840 AND nachname = 'Pirelli'
3841  
3842 =item *
3843  
3844 SELECT mit Statement-Muster
3845  
3846 my $select = <<'__SQL__';
3847 SELECT
3848 %SELECT%
3849 FROM
3850 station sta LEFT JOIN parameter par
3851 ON par_station_id = sta_id
3852 __SQL__
3853
3854 $stmt = $sql->select(
3855 -stmt => $select,
3856 -select => qw/sta_id sta_name par_id par_name/,
3857 -orderBy => qw/sta_name par_name/,
3858 );
3859 =>
3860 SELECT
3861 sta_id,
3862 sta_name,
3863 par_id,
3864 par_name
3865 FROM
3866 station sta LEFT JOIN parameter par
3867 ON par_station_id = sta_id
3868 ORDER BY
3869 sta_name,
3870 par_name
3871  
3872 =back
3873  
3874 =cut
3875  
3876 # -----------------------------------------------------------------------------
3877  
3878 85 ▶sub select {
Subroutine select: called CC=65 SCAR=61.9
Pod documented
3879 85 my $self = shift;
3880 # @_: @opt
3881  
3882 85 ▶ if (@_ && substr($_[0],0,1) ne '-') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and substr($_[0], 0, 1) ne "-") 18 67 85
Condition100%3/3
@_ and substr($_[0], 0, 1) ne "-"
!ll&&!rl&&r
16618
MC/DC100%2/2
@_ and substr($_[0], 0, 1) ne "-"
@_ substr($_[0], 0, 1) ne "-"
Truth table100%3/3
A and B
A= @_B= substr($_[0], 0, 1) ne "-"
ABresult
0X0
100
111
3883 # -stmt ist Default-Option für erstes Argument, wenn Whitespace,
3884 # -from ist Default-Option sonst
3885 18 ▶ unshift @_,$_[0] =~ /\s/? '-stmt': '-from';
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /\s/ ? : 0 18 18
3886 18 ▶ if (@_ > 2 && substr($_[2],0,1) ne '-') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2 and substr($_[2], 0, 1) ne "-") 5 13 18
Condition100%3/3
@_ > 2 and substr($_[2], 0, 1) ne "-"
!ll&&!rl&&r
1035
MC/DC100%2/2
@_ > 2 and substr($_[2], 0, 1) ne "-"
@_ > 2 substr($_[2], 0, 1) ne "-"
Truth table100%3/3
A and B
A= @_ > 2B= substr($_[2], 0, 1) ne "-"
ABresult
0X0
100
111
3887 # -where ist Default-Option für die weiteren Argumente
3888 5 splice @_,2,0,'-where';
3889 }
3890 }
3891  
3892 # Optionen
3893  
3894 85 my @args;
3895 my $comment;
3896 85 my @with;
3897 85 my @select;
3898 85 my $distinct;
3899 85 my $hint;
3900 85 my @from;
3901 85 my @where;
3902 85 my @groupBy;
3903 85 my @having;
3904 85 my @orderBy;
3905 85 my @placeholders;
3906 85 my $limit;
3907 85 my $offset;
3908 85 my $stmt = '';
3909  
3910 85 Quiq::Option->extractMulti(\@_,
3911 -comment => \$comment,
3912 -with => \@with,
3913 -select => \@select,
3914 -distinct => \$distinct,
3915 -hint => \$hint,
3916 -from => \@from,
3917 -where => \@where,
3918 -groupBy => \@groupBy,
3919 -having => \@having,
3920 -orderBy => \@orderBy,
3921 -limit => \$limit,
3922 -offset => \$offset,
3923 -stmt => \$stmt,
3924 -placeholders => \@placeholders,
3925 );
3926  
3927 85 my ($oracle,$postgresql,$sqlite,$mysql,$access,$mssql,$jdbc) =
3928 $self->dbmsTestVector;
3929  
3930 85 ▶ if (defined $offset && $oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset and $oracle) 0 85 85
Condition33%1/3
defined $offset and $oracle
!ll&&!rl&&r
8500
MC/DC0%0/2
defined $offset and $oracle
defined $offset $oracle
Truth table33%1/3
A and B
A= defined $offsetB= $oracle
ABresult
0X0
100
111
3931 0 die;
3932 }
3933  
3934 # Statementbestandteile generieren
3935  
3936 # Für alle Statementbestandteile gilt:
3937 # 1) Sie haben kein Whitespace am Anfang und am Ende
3938 # 2) Jedes Subelement (Select-Kolumne, Where-Bedingung usw.) steht auf
3939 # einer eigenen Zeile
3940 # 3) ab dem zweiten Subelement sind alle Subelemente um
3941 # vier Leerzeichen eingerückt
3942  
3943 # Anfangs-Kommentar ($comment)
3944  
3945 85 ▶ if (defined $comment && length $comment) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comment and length $comment) 0 85 85
Condition33%1/3
defined $comment and length $comment
!ll&&!rl&&r
8500
MC/DC0%0/2
defined $comment and length $comment
defined $comment length $comment
Truth table33%1/3
A and B
A= defined $commentB= length $comment
ABresult
0X0
100
111
3946 0 $comment =~ s/\s+$//; # Whitespace am Ende entfernen
3947 0 $comment =~ s/^/ /mg; # Text einrücken
3948 0 $comment = "/*\n$comment\n*/";
3949 }
3950  
3951 # Select-Klausel ($selectClause)
3952  
3953 85 ▶ if (@select == 1 && (!defined $select[0] || $select[0] eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@select == 1 and !defined($select[0]) || $select[0] eq "") 0 85 85
Condition50%3/6
@select == 1 and !defined($select[0]) || $select[0] eq ""
!ll&&!rl&&r
44410
not defined $select[0] or $select[0] eq ""
l!l&&r!l&&!r
0041
MC/DC0%0/3
@select == 1 and !defined($select[0]) || $select[0] eq ""
@select == 1 not defined $select[0] $select[0] eq ""
Truth table50%2/4
A and not(B) or C
A= @select == 1B= not defined $select[0]C= $select[0] eq ""
ABCresult
0XX0
1000
11X1
1011
3954 # Wenn die SELECT-Liste aus einem einzigen leeren Wert
3955 # besteht, leeren wir sie.
3956 0 @select = ();
3957 }
3958  
3959 85 my $selectClause;
3960 85 ▶ if (@select) {
Branch: 1 branch
BranchTrueFalseTotal
if (@select) 51 34 85
3961 51 ▶ if ($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 0 51 51
3962 0 $selectClause .= 'DISTINCT';
3963 }
3964 51 ▶ if ($hint && $oracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hint and $oracle) 0 51 51
Condition33%1/3
$hint and $oracle
!ll&&!rl&&r
5100
MC/DC0%0/2
$hint and $oracle
$hint $oracle
Truth table33%1/3
A and B
A= $hintB= $oracle
ABresult
0X0
100
111
3965 0 ▶ if ($selectClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($selectClause) 0 0 0
3966 0 $selectClause .= "\n ";
3967 }
3968 0 $selectClause .= "/*+ $hint */";
3969 }
3970 51 ▶ if ($selectClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($selectClause) 0 51 51
3971 0 $selectClause .= "\n ";
3972 }
3973 51 $selectClause .= $self->selectClause(@select);
3974 }
3975  
3976 # Where-Klausel ($whereClause)
3977  
3978 # Im Falle von $limit u.U. @where erweitern
3979  
3980 85 ▶ if (defined($limit) && $limit ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit and $limit ne "") 39 46 85
Condition66%2/3
defined $limit and $limit ne ""
!ll&&!rl&&r
46039
MC/DC50%1/2
defined $limit and $limit ne ""
defined $limit $limit ne ""
Truth table66%2/3
A and B
A= defined $limitB= $limit ne ""
ABresult
0X0
100
111
3981 39 ▶ if ($limit == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($limit == 0) { } 39 0 39
elsif ($oracle) { } 0 0 0
3982 39 push @where,'1 = 0';
3983 39 $limit = undef; # keine zusätzliche LIMIT-Klausel generieren
3984 }
3985 elsif ($oracle) {
3986 0 push @where,"ROWNUM <= $limit";
3987 }
3988 }
3989  
3990 # MEMO: auch existente WHERE-Klauseln können einen Leerstring ergeben
3991 85 my $whereClause = $self->whereClause(@where);
3992  
3993 # GroupBy-Klausel ($groupByClause)
3994 85 my $groupByClause = join(",\n ",@groupBy);
3995  
3996 # Having-Klausel ($havingClause)
3997 85 my $havingClause = join(",\n ",@having);
3998  
3999 # OrderBy-Klausel ($orderByClause)
4000 85 my $orderByClause = join(",\n ",@orderBy);
4001  
4002 # Statement generieren
4003  
4004 # if ($comment) {
4005 # $stmt .= "$comment\n";
4006 # }
4007 # $selectClause ||= '*';
4008 # $stmt .= "SELECT\n $selectClause";
4009 # if ($fromClause) {
4010 # $stmt .= "\nFROM\n $fromClause";
4011 # }
4012 # if ($whereClause) {
4013 # $stmt .= "\nWHERE\n $whereClause";
4014 # }
4015 # if ($groupByClause) {
4016 # $stmt .= "\nGROUP BY\n $groupByClause";
4017 # }
4018 # if ($havingClause) {
4019 # $stmt .= "\nHAVING\n $havingClause";
4020 # }
4021 # if ($orderByClause) {
4022 # $stmt .= "\nORDER BY\n $orderByClause";
4023 # }
4024 # unless ($oracle) {
4025 # if (defined $limit) {
4026 # $stmt .= "\nLIMIT\n $limit";
4027 # }
4028 # if (defined $offset) {
4029 # $stmt .= "\nOFFSET\n $offset";
4030 # }
4031 # }
4032  
4033 # Der folgende Code beherrscht die vollständige Generierung
4034 # und die Ergänzung eines Statement-Musters per -stmt.
4035  
4036 # 1) Wenn Platzhalter (nur bei -stmt), diesen *ersetzen*
4037 # 2) Wenn Platzhalter nicht vorhanden und Klausel-Schlüsselwort auch
4038 # nichgt (bei vollständifer Statement-Generierung und bei -stmt)
4039 # Klausel *hinzufügen*
4040 # 3) Andernfalls (Klausel-Schlüsselwort vorhanden, aber kein Platzhalter),
4041 # Exception, da die Klauseloption sonst ohne Wirkung bliebe
4042  
4043 85 Quiq::String->removeIndentation(\$stmt);
4044 85 my ($body) = ref($self)->split($stmt);
4045  
4046 85 ▶ if ($body =~ /%SELECT%/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($body =~ /%SELECT%/) { } 3 82 85
elsif (not $stmt) { } 80 2 82
elsif ($selectClause) { } 0 2 2
4047 3 ▶ $selectClause ||= '*';
Condition50%1/2
$selectClause ||= "*"
l!l
30
MC/DC0%0/1
$selectClause ||= "*"
$selectClause
Truth table50%1/2
A
A= $selectClause
Aresult
11
00
4048 3 $stmt =~ s/%SELECT%/$selectClause/g;
4049 }
4050 elsif (!$stmt) {
4051 80 ▶ $selectClause ||= '*';
Condition100%2/2
$selectClause ||= "*"
l!l
1466
MC/DC100%1/1
$selectClause ||= "*"
$selectClause
Truth table100%2/2
A
A= $selectClause
Aresult
11
00
4052 80 $stmt .= "SELECT\n $selectClause";
4053 }
4054 elsif ($selectClause) {
4055 0 $self->throw(
4056 'SELECT-00001: Kein Platzhalter für SELECT-Kolumnen',
4057 Stmt => $stmt,
4058 SelectClause => $selectClause,
4059 );
4060 }
4061  
4062 # WITH-Klausel
4063  
4064 85 ▶ if (@with == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@with == 1) 0 85 85
4065 0 unshift @with,'query';
4066 0 ▶ if (!@from) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@from) 0 0 0
4067 0 @from = ('query');
4068 }
4069 }
4070  
4071 85 my $withClause = $self->withClause(@with);
4072 85 ▶ if ($withClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($withClause) 0 85 85
4073 0 ▶ if ($body =~ /%WITH%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%WITH%/) { } 0 0 0
elsif (not $body =~ /\bWITH\b/i) { } 0 0 0
4074 0 $stmt =~ s/%WITH%/$withClause/g;
4075 }
4076 elsif ($body !~ /\bWITH\b/i) {
4077 # WITH-Klausel an den Anfang stellen
4078 0 $stmt = "WITH $withClause\n$stmt";
4079 }
4080 else {
4081 0 $self->throw(
4082 'SELECT-00002: Kein Platzhalter für WITH-Klausel',
4083 Stmt => $stmt,
4084 WithClause => $withClause,
4085 );
4086 }
4087 }
4088  
4089 # FROM-Klausel
4090  
4091 85 my $fromClause = $self->fromClause(@from);
4092 85 ▶ if ($fromClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fromClause) 81 4 85
4093 81 $fromClause =~ s/\n/\n /mg;
4094 81 ▶ if ($body =~ /%FROM%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%FROM%/) { } 1 80 81
elsif (not $body =~ /\bFROM\b/i) { } 80 0 80
4095 1 $stmt =~ s/%FROM%/$fromClause/g;
4096 }
4097 elsif ($body !~ /\bFROM\b/i) {
4098 80 ▶ if ($fromClause =~ /^\s*\(/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fromClause =~ /^\s*\(/) { } 0 80 80
4099 0 $stmt .= "\nFROM $fromClause";
4100 }
4101 else {
4102 80 $stmt .= "\nFROM\n $fromClause";
4103 }
4104 }
4105 else {
4106 0 $self->throw(
4107 'SELECT-00002: Kein Platzhalter für FROM-Klausel',
4108 Stmt => $stmt,
4109 FromClause => $fromClause,
4110 );
4111 }
4112 }
4113  
4114 85 ▶ if ($body =~ /%WHERE%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%WHERE%/) { } 1 84 85
elsif ($whereClause) { } 58 26 84
4115 1 ▶ $whereClause ||= '1 = 1';
Condition50%1/2
$whereClause ||= "1 = 1"
l!l
10
MC/DC0%0/1
$whereClause ||= "1 = 1"
$whereClause
Truth table50%1/2
A
A= $whereClause
Aresult
11
00
4116 1 $stmt =~ s/%WHERE%/$whereClause/g;
4117 }
4118 elsif ($whereClause) {
4119 58 ▶ if ($body !~ /\bWHERE\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $body =~ /\bWHERE\b/i) { } 58 0 58
4120 58 $stmt .= "\nWHERE\n $whereClause";
4121 }
4122 else {
4123 0 $self->throw(
4124 'SELECT-00003: Kein Platzhalter für WHERE-Klausel',
4125 Stmt => $stmt,
4126 WhereClause => $whereClause,
4127 );
4128 }
4129 }
4130  
4131 85 ▶ if ($groupByClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($groupByClause) 0 85 85
4132 0 ▶ if ($body =~ /%GROUPBY%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%GROUPBY%/) { } 0 0 0
elsif (not $body =~ /\bGROUP\s+BY\b/i) { } 0 0 0
4133 0 $stmt =~ s/%GROUPBY%/$groupByClause/g;
4134 }
4135 elsif ($body !~ /\bGROUP\s+BY\b/i) {
4136 0 $stmt .= "\nGROUP BY\n $groupByClause";
4137 }
4138 else {
4139 0 $self->throw(
4140 'SELECT-00003: Kein Platzhalter für GROUP BY-Klausel',
4141 Stmt => $stmt,
4142 GroupByClause => $groupByClause,
4143 );
4144 }
4145 }
4146  
4147 85 ▶ if ($havingClause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($havingClause) 0 85 85
4148 0 ▶ if ($body =~ /%HAVING%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%HAVING%/) { } 0 0 0
elsif (not $body =~ /\bHAVING\b/i) { } 0 0 0
4149 0 $stmt =~ s/%HAVING%/$havingClause/g;
4150 }
4151 elsif ($body !~ /\bHAVING\b/i) {
4152 0 $stmt .= "\nHAVING\n $havingClause";
4153 }
4154 else {
4155 0 $self->throw(
4156 'SELECT-00003: Kein Platzhalter für HAVING-Klausel',
4157 Stmt => $stmt,
4158 HavingClause => $havingClause,
4159 );
4160 }
4161 }
4162  
4163 85 ▶ if ($orderByClause) {
Branch: 2 branches
BranchTrueFalseTotal
if ($orderByClause) { } 10 75 85
elsif ($mssql and $offset || $limit) { } 0 150 150
4164 10 ▶ if ($body =~ /%ORDERBY%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%ORDERBY%/) { } 1 9 10
elsif (not $body =~ /\bORDER\s+BY\b/i) { } 9 0 9
4165 1 $stmt =~ s/%ORDERBY%/$orderByClause/g;
4166 }
4167 elsif ($body !~ /\bORDER\s+BY\b/i) {
4168 9 $stmt .= "\nORDER BY\n $orderByClause";
4169 }
4170 else {
4171 0 $self->throw(
4172 'SELECT-00003: Kein Platzhalter für ORDER BY-Klausel',
4173 Stmt => $stmt,
4174 OrderByClause => $orderByClause,
4175 );
4176 }
4177 }
4178 ▶ elsif ($mssql && ($offset || $limit)) {
Condition16%1/6
$mssql and $offset || $limit
!ll&&!rl&&r
7500
$offset or $limit
l!l&&r!l&&!r
000
MC/DC0%0/3
$mssql and $offset || $limit
$mssql $offset $limit
Truth table25%1/4
A and B or C
A= $mssqlB= $offsetC= $limit
ABCresult
0XX0
1000
11X1
1011
4179 # Bei MSSQL sind OFFSET und LIMIT Ergänzungen zu ORDER BY.
4180 # Wir brauchen also eine ORDER BY Klausel, wenn -offset
4181 # und/oder -limit angegeben sind
4182 0 $stmt .= "\nORDER BY\n 1";
4183 }
4184  
4185 85 ▶ unless ($oracle) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oracle) 85 0 85
4186 85 ▶ if (defined $offset) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $offset) 0 85 85
4187 0 ▶ if ($body =~ /%OFFSET%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%OFFSET%/) { } 0 0 0
elsif (not $body =~ /\bOFFSET\b/i) { } 0 0 0
4188 0 $stmt =~ s/%OFFSET%/$offset/g;
4189 }
4190 elsif ($body !~ /\bOFFSET\b/i) {
4191 0 $stmt .= "\nOFFSET\n $offset";
4192 0 ▶ if ($mssql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mssql) 0 0 0
4193 0 $stmt .= ' ROWS';
4194 }
4195 }
4196 else {
4197 0 $self->throw(
4198 'SELECT-00003: Kein Platzhalter für OFFSET',
4199 Stmt => $stmt,
4200 Offset => $offset,
4201 );
4202 }
4203 }
4204 85 ▶ if ($limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit) 0 85 85
4205 0 ▶ if ($body =~ /%LIMIT%/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /%LIMIT%/) { } 0 0 0
elsif (not $body =~ /\bLIMIT\b/i) { } 0 0 0
4206 0 $stmt =~ s/%LIMIT%/$limit/g;
4207 }
4208 elsif ($body !~ /\bLIMIT\b/i) {
4209 0 ▶ if ($mssql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mssql) { } 0 0 0
4210 0 ▶ if (!$offset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($offset) 0 0 0
4211 # Bei MSSQL ist FETCH eine Ergänzug zu OFFSET.
4212 # Wir brauchen also eine OFFSET-Klausel, wenn
4213 # -limit angegeben ist.
4214 0 $stmt .= "\nOFFSET\n 0 ROWS";
4215 }
4216 0 $stmt .= "\nFETCH\n NEXT $limit ROWS ONLY";
4217 }
4218 else {
4219 0 $stmt .= "\nLIMIT\n $limit";
4220 }
4221 }
4222 else {
4223 0 $self->throw(
4224 'SELECT-00003: Kein Platzhalter für LIMIT',
4225 Stmt => $stmt,
4226 Limit => $limit,
4227 );
4228 }
4229 }
4230 }
4231  
4232 # Anfangs-Kommentar als letztes voranstellen
4233  
4234 85 ▶ if ($comment) {
Branch: 1 branch
BranchTrueFalseTotal
if ($comment) 0 85 85
4235 # Kommentar dem Statement voranstellen
4236 0 $stmt = "$comment\n$stmt";
4237 }
4238  
4239 # Platzhalter-Ersetzung
4240  
4241 85 ▶ if (@placeholders) {
Branch: 1 branch
BranchTrueFalseTotal
if (@placeholders) 0 85 85
4242 0 $stmt = Quiq::Template->combine(
4243 placeholders => \@placeholders,
4244 template => $stmt,
4245 );
4246 }
4247  
4248 85 return $stmt;
4249 }
4250  
4251 # -----------------------------------------------------------------------------
4252  
4253 =head3 insert() - Generiere INSERT-Statement
4254  
4255 =head4 Synopsis
4256  
4257 $stmt = $sql->insert($table,$row);
4258 $stmt = $sql->insert($table,%keyVal);
4259 $stmt = $sql->insert($table,@keyVal);
4260 $stmt = $sql->insert($table,\@keys,\@vals);
4261  
4262 =head4 Description
4263  
4264 Generiere ein INSERT-Statement für Tabelle $table mit den Kolumnen
4265 und Werten %keyVal bzw. @keyVal bzw. @keys,@vals und liefere
4266 dieses zurück.
4267  
4268 Schlüssel/Wert-Paare ohne Wert (Leerstring, undef) werden
4269 ausgelassen. Damit ist sichergestellt, dass der Defaultwert der
4270 Kolumne verwendet wird, wenn einer auf der Datenbank deklariert
4271 ist.
4272  
4273 Ist der Kolumnenwert eine String-Referenz, wird der Wert ohne
4274 Anführungsstriche in das Statement eingesetzt. Auf diese Weise
4275 können per SQL berechnete Werte (Expressions) eingesetzt werden.
4276  
4277 Ist die Liste der Schlüssel/Wert-Paare leer oder sind alle
4278 Werte leer, wird ein Null-Statement (Leerstring) geliefert.
4279  
4280 =head4 Example
4281  
4282 =over 2
4283  
4284 =item *
4285  
4286 Normales INSERT, Schlüssel/Wert-Paare
4287  
4288 $stmt = $sql->insert('person',
4289 per_id => 10,
4290 per_vorname => 'Hanno',
4291 per_nachname => 'Seitz',
4292 per_geburtstag => undef,
4293 );
4294
4295 =>
4296
4297 INSERT INTO person
4298 (
4299 per_id,
4300 per_vorname,
4301 per_nachname,
4302 )
4303 VALUES
4304 (
4305 '10',
4306 'Hanno',
4307 'Seitz',
4308 )
4309  
4310 =item *
4311  
4312 Normales Insert, Schlüssel und Werte als getrennte Listen
4313  
4314 @keys = qw/per_id per_vorname per_nachname per_geburtstag/;
4315 @vals = (10,'Hanno','Seitz',undef);
4316 $stmt = $sql->insert('person',\@keys,\@vals);
4317
4318 =>
4319
4320 INSERT INTO person
4321 (
4322 per_id,
4323 per_vorname,
4324 per_nachname,
4325 )
4326 VALUES
4327 (
4328 '10',
4329 'Hanno',
4330 'Seitz',
4331 )
4332  
4333 =item *
4334  
4335 INSERT mit berechnetem Kolumnenwert
4336  
4337 $stmt = $sql->insert('objekt',
4338 obj_id => 4711,
4339 obj_letzteaenderung => \'SYSDATE',
4340 );
4341
4342 =>
4343
4344 INSERT INTO objekt
4345 (
4346 obj_id,
4347 obj_letzteaenderung
4348 )
4349 VALUES
4350 (
4351 '4711',
4352 SYSDATE
4353 )
4354  
4355 =item *
4356  
4357 Null-Statements
4358  
4359 $stmt = $sql->insert('person');
4360
4361 =>
4362
4363 ''
4364
4365 $stmt = $sql->insert('person',
4366 per_id => '',
4367 per_vorname => '',
4368 per_nachname => '',
4369 per_geburtstag => '',
4370 );
4371
4372 =>
4373
4374 ''
4375  
4376 =item *
4377  
4378 INSERT mit Platzhaltern
4379  
4380 $stmt = $sql->insert('person',
4381 per_id => \'?',
4382 per_vorname => \'?',
4383 per_nachname => \'?',
4384 per_geburtstag => \'?',
4385 );
4386
4387 INSERT INTO person
4388 (
4389 per_id,
4390 per_vorname,
4391 per_nachname,
4392 per_geburtstag
4393 )
4394 VALUES
4395 (
4396 ?,
4397 ?,
4398 ?,
4399 ?
4400 )
4401  
4402 =back
4403  
4404 =cut
4405  
4406 # -----------------------------------------------------------------------------
4407  
4408 31 ▶sub insert {
Subroutine insert: called CC=11 SCAR=25.0
Pod documented
4409 31 my $self = shift;
4410 31 my $table = shift;
4411 # @_: $row -or- @keyVal -or- \@keys,\@vals
4412  
4413 31 my ($titles,$values);
4414  
4415 31 ▶ if (ref $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0]) { } 7 24 31
4416 7 ▶ if (Scalar::Util::blessed($_[0]) &&
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($_[0]) and $_[0]->isa('Quiq::Database::Row::Object')) { } 0 7 7
Condition66%2/3
builtin::blessed($_[0]) and $_[0]->isa("Quiq::Database::Row::Object")
!ll&&!rl&&r
610
MC/DC0%0/2
builtin::blessed($_[0]) and $_[0]->isa("Quiq::Database::Row::Object")
builtin::blessed($_[0]) $_[0]->isa("Quiq::Database::Row::Object")
Truth table66%2/3
A and B
A= builtin::blessed($_[0])B= $_[0]->isa("Quiq::Database::Row::Object")
ABresult
0X0
100
111
4417 $_[0]->isa('Quiq::Database::Row::Object')) { # $row
4418 0 my $row = shift;
4419 0 for my $key ($row->titles) {
4420 0 my $val = $self->valExpr($row->$key);
4421 0 ▶ if ($val ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($val ne "") 0 0 0
4422 0 $titles .= "\n $key,";
4423 0 $values .= "\n $val,";
4424 }
4425 }
4426 }
4427 else { # \@keys,\@vals
4428 7 my ($keys,$vals) = @_;
4429 7 ▶ for (my $i = 0; $i < @$keys; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$keys) 19 7 26
4430 19 my $val = $self->valExpr($vals->[$i]);
4431 19 ▶ if ($val ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($val ne "") 18 1 19
4432 18 my $key = $keys->[$i];
4433 18 $titles .= "\n $key,";
4434 18 $values .= "\n $val,";
4435 }
4436 }
4437 }
4438 }
4439 else { # @keyVal
4440 24 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 46 24 70
4441 46 my $key = shift;
4442 46 my $val = $self->valExpr(shift);
4443 46 ▶ if ($val ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($val ne "") 37 9 46
4444 37 $titles .= "\n $key,";
4445 37 $values .= "\n $val,";
4446 }
4447 }
4448 }
4449  
4450 # Abbruch: Keine Daten
4451 31 ▶ return '' unless $titles;
Branch: 1 branch
BranchTrueFalseTotal
unless $titles 3 28 31
4452  
4453 28 chop $titles;
4454 28 chop $values;
4455  
4456 28 return "INSERT INTO $table ($titles\n)\nVALUES ($values\n)";
4457 }
4458  
4459 # -----------------------------------------------------------------------------
4460  
4461 =head3 insertMulti() - Generiere INSERT-Statement mit mehreren Zeilen
4462  
4463 =head4 Synopsis
4464  
4465 $stmt = $sql->insertMulti($table,\@keys,[
4466 [@vals1],
4467 [@vals2],
4468 ...
4469 ]
4470 );
4471  
4472 =head4 Description
4473  
4474 Generiere ein INSERT-Statement für Tabelle $table mit den Kolumnen
4475 @keys und den Datensätzen @records. @records ist eine Liste von
4476 Arrays mit gleich vielen Elementen wie @keys.
4477  
4478 =head4 Example
4479  
4480 $stmt = $sql->insertMulti('person',
4481 [qw/per_id per_vorname per_nachname per_geburtstag/],[
4482 [qw/1 Linus Seitz 2002-11-11/],
4483 [qw/2 Hanno Seitz 2000-04-07/],
4484 [qw/3 Emily Philippi 1997-05-05/],
4485 ]
4486 );
4487 =>
4488 INSERT INTO person
4489 (per_id, per_vorname, per_nachname, per_geburtstag)
4490 VALUES
4491 ('1', 'Linus', 'Seitz', '2002-11-11'),
4492 ('2', 'Hanno', 'Seitz', '2000-04-07')
4493 ('3', 'Emily', 'Philippi', '1997-05-05')
4494  
4495 =cut
4496  
4497 # -----------------------------------------------------------------------------
4498  
4499 4 ▶sub insertMulti {
Subroutine insertMulti: called CC=7 SCAR=19.5
Pod documented
4500 4 my ($self,$table,$keyA,$recA) = @_;
4501  
4502 4 ▶ if (!@$recA) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$recA) 1 3 4
4503 # Keine Daten => kein Statement
4504 1 return '';
4505 }
4506  
4507 3 my $sql = sprintf Quiq::Unindent->string('
4508 INSERT INTO %s
4509 (%s)
4510 VALUES
4511 '),$table,join(', ',@$keyA);
4512  
4513 3 my $i = 0;
4514 3 for my $rec (@$recA) {
4515 7 ▶ if ($i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i++) 4 3 7
4516 4 $sql .= ",\n";
4517 }
4518 7 my $str = '';
4519 7 for (@$rec) {
4520 19 my $val = $self->valExpr($_);
4521 19 ▶ if ($str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str) 12 7 19
4522 12 $str .= ', ';
4523 }
4524 19 ▶ $str .= $val eq ''? 'NULL': $val;
Branch: 1 branch
BranchTrueFalseTotal
$val eq '' ? : 0 19 19
4525
4526 }
4527 7 $sql .= sprintf ' (%s)',$str;
4528 }
4529  
4530 3 return $sql;
4531  
4532 #my $i = 0;
4533 #my $fmt = sprintf ' (%s)',join ', ',('%s') x @$keyA;
4534 #for my $rec (@$recA) {
4535 # if ($i++) {
4536 # $sql .= ",\n";
4537 # }
4538 # $sql .= sprintf $fmt,map {$self->valExpr($_)} @$rec;
4539 #}
4540 #
4541 #return $sql;
4542 }
4543  
4544 # -----------------------------------------------------------------------------
4545  
4546 =head3 update() - Generiere UPDATE Statement
4547  
4548 =head4 Synopsis
4549  
4550 $stmt = $sql->update($table,@keyVal,-where,@where);
4551  
4552 =head4 Example
4553  
4554 $stmt = $sql->update('person',
4555 per_geburtstag => '7.4.2000',
4556 -where,per_id => 4711,
4557 );
4558  
4559 =cut
4560  
4561 # -----------------------------------------------------------------------------
4562  
4563 5 ▶sub update {
Subroutine update: called CC=3 SCAR=11.0
Pod documented
4564 5 my $self = shift;
4565 5 my $table = shift;
4566 # @_: @keyVal,-where,@where
4567  
4568 5 my @where;
4569 5 Quiq::Option->extractMulti(\@_,
4570 -where => \@where,
4571 );
4572  
4573 5 ▶ unless (@_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_) 1 4 5
4574 # Ohne SET-Klausel liefern wir ein leeres Statement
4575 1 return '';
4576 }
4577  
4578 4 my $stmt = "UPDATE $table SET\n ";
4579 4 $stmt .= $self->setClause(@_);
4580  
4581 # FIXME: Exception, wenn keine WHERE-Klausel?
4582  
4583 4 ▶ if (@where) {
Branch: 1 branch
BranchTrueFalseTotal
if (@where) 1 3 4
4584 1 $stmt .= "\nWHERE\n ";
4585 1 $stmt .= $self->whereClause(@where);
4586 }
4587  
4588 4 return $stmt;
4589 }
4590  
4591 # -----------------------------------------------------------------------------
4592  
4593 =head3 delete() - Generiere DELETE Statement
4594  
4595 =head4 Synopsis
4596  
4597 $stmt = $sql->delete($table,@opt,@where);
4598  
4599 =head4 Options
4600  
4601 =over 4
4602  
4603 =item -hint => $hint (Default: undef)
4604  
4605 Füge Hint (Oracle) in Statement ein.
4606  
4607 =back
4608  
4609 =cut
4610  
4611 # -----------------------------------------------------------------------------
4612  
4613 4 ▶sub delete {
Subroutine delete: called CC=5 SCAR=16.2
Pod documented
4614 4 my $self = shift;
4615 4 my $table = shift;
4616 # @_: @where
4617  
4618 4 my $hint;
4619  
4620 4 Quiq::Option->extractMulti(\@_,
4621 -hint => \$hint,
4622 );
4623  
4624 4 my $stmt = 'DELETE';
4625 4 ▶ if ($hint) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hint) 0 4 4
4626 0 $stmt .= " /*+ $hint */";
4627 }
4628 4 $stmt .= " FROM $table";
4629  
4630 # FIXME: Optionale Angabe +null eleganter feststellen
4631  
4632 4 ▶ if (@_ && !(@_ == 1 && $_[0] eq '+null')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and not @_ == 1 && $_[0] eq "+null") 2 2 4
Condition83%5/6
@_ and not @_ == 1 && $_[0] eq "+null"
!ll&&!rl&&r
112
@_ == 1 && $_[0] eq '+null'
!ll&&!rl&&r
201
MC/DC66%2/3
@_ and not @_ == 1 && $_[0] eq "+null"
@_ @_ == 1 $_[0] eq '+null'
Truth table75%3/4
A and not(B && C)
A= @_B= @_ == 1C= $_[0] eq '+null'
ABCresult
0XX0
1110
10X1
1101
4633 2 $stmt .= "\nWHERE\n ";
4634 2 $stmt .= $self->whereClause(@_);
4635 }
4636  
4637 4 return $stmt;
4638 }
4639  
4640 # -----------------------------------------------------------------------------
4641  
4642 =head2 Operators and Functions
4643  
4644 =head3 Vergleichsoperatoren: <EXPR> <OP> <EXPR>
4645  
4646 !=
4647 <
4648 <=
4649 =
4650 >
4651 >=
4652 (NOT) BETWEEN
4653 (NOT) IN
4654 (NOT) LIKE
4655  
4656 =head3 Aggregatfunktionen: <OP>(<EXPR>)
4657  
4658 Implement.
4659 ------------
4660 AVG
4661 COUNT
4662 MAX
4663 MIN
4664 SUM
4665 Oracle PostgreSQL SQLite MySQL
4666 ------------ ------------ ------------ ------------
4667 GROUP_CONCAT
4668 TOTAL
4669  
4670 =head3 Funktionen: <OP>(<EXPR>,...)
4671  
4672 Implement. Oracle PostgreSQL SQLite MySQL
4673 ------------- ------------ ------------ ------------ ------------
4674 ABS
4675 COALESCE
4676 GLOB
4677 IFNULL
4678 HEX
4679 LENGTH
4680 LOWER LOWER LOWER LOWER
4681 LTRIM
4682 MAX
4683 MIN
4684 NULLIF
4685 QUOTE
4686 RANDOM
4687 RANDOMBLOB
4688 REPLACE
4689 ROUND
4690 RTRIM
4691 SUBSTR SUBSTR SUBSTR SUBSTR
4692 TRIM
4693 TYPEOF
4694 UPPER UPPER UPPER UPPER
4695 CAT || ||
4696  
4697 =head3 opFunc() - Generiere Funktionsaufruf
4698  
4699 =head4 Synopsis
4700  
4701 $sqlExpr = $sql->opFunc($op,@args);
4702  
4703 =head4 Description
4704  
4705 Generiere Funktionsaufruf "<OP>(<EXPR1>, <EXPR2>, ...)" und
4706 liefere diesen zurück.
4707  
4708 Diese Methode wird zur Generierung von portablen Funktionsausdrücken
4709 wie UPPER, LOWER, MIN, MAX, SUBSTR, etc. benutzt.
4710  
4711 =cut
4712  
4713 # -----------------------------------------------------------------------------
4714  
4715 5 ▶sub opFunc {
Subroutine opFunc: called CC=1 SCAR=0.0
Pod documented
4716 5 my $self = shift;
4717 5 my $op = shift;
4718 # @_: @args
4719  
4720 5 return sprintf '%s(%s)',$op,join(',',@_);
4721 }
4722  
4723 # -----------------------------------------------------------------------------
4724  
4725 =head3 opRel() - Generiere rechte Seite eines Vergleichsausdrucks
4726  
4727 =head4 Synopsis
4728  
4729 $sqlExpr = $sql->opRel($op,$arg);
4730  
4731 =head4 Description
4732  
4733 Generiere Ausdruck "<OP> <EXPR>" und liefere diesen zurück.
4734  
4735 =cut
4736  
4737 # -----------------------------------------------------------------------------
4738  
4739 3 ▶sub opRel {
Subroutine opRel: called CC=1 SCAR=0.0
Pod documented
4740 3 my $self = shift;
4741 3 my $op = shift;
4742 3 my $str = shift;
4743  
4744 3 return "$op $str";
4745 }
4746  
4747 # -----------------------------------------------------------------------------
4748  
4749 =head3 opAS() - Generiere AS-Ausdruck (Alias)
4750  
4751 =head4 Synopsis
4752  
4753 $sqlExpr = $sql->opAS($op,$arg,$name);
4754  
4755 =head4 Description
4756  
4757 Generiere Ausdruck "<EXPR> AS <NAME>" und liefere diesen zurück.
4758  
4759 =cut
4760  
4761 # -----------------------------------------------------------------------------
4762  
4763 0 ▶sub opAS {
Subroutine opAS: not called CC=1 SCAR=6.9
Pod documented
4764 0 my $self = shift;
4765 0 my $op = shift;
4766 0 my $arg = shift;
4767 0 my $name = shift;
4768  
4769 0 return "$arg AS $name";
4770 }
4771  
4772 # -----------------------------------------------------------------------------
4773  
4774 =head3 opBETWEEN() - Generiere BETWEEN-Ausdruck
4775  
4776 =head4 Synopsis
4777  
4778 $sqlExpr = $sql->opBETWEEN($op,$arg1,$arg2);
4779  
4780 =head4 Description
4781  
4782 Generiere Ausdruck "BETWEEN <EXPR1> AND <EXPR2>" und liefere diesen zurück.
4783  
4784 =cut
4785  
4786 # -----------------------------------------------------------------------------
4787  
4788 0 ▶sub opBETWEEN {
Subroutine opBETWEEN: not called CC=1 SCAR=6.9
Pod documented
4789 0 my $self = shift;
4790 0 my $op = shift;
4791 0 my $arg1 = shift;
4792 0 my $arg2 = shift;
4793  
4794 0 return "BETWEEN $arg1 AND $arg2";
4795 }
4796  
4797 # -----------------------------------------------------------------------------
4798  
4799 =head3 opCASEXPR() - Generiere CASE-Ausdruck
4800  
4801 =head4 Synopsis
4802  
4803 $sqlExpr = $sql->opCASEXPR($op,@args);
4804  
4805 =head4 Description
4806  
4807 Für diff() implementiert, funktioniert aber nicht.
4808  
4809 =cut
4810  
4811 # -----------------------------------------------------------------------------
4812  
4813 0 ▶sub opCASEXPR {
Subroutine opCASEXPR: not called CC=2 SCAR=17.9
Pod documented
4814 0 my $self = shift;
4815 0 my $op = shift;
4816 0 my $expr = shift;
4817 # @_: @pairs
4818  
4819 0 my $stmt = 'CASE '.$self->keyExpr($expr);
4820 0 ▶ while (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
4821 0 my $val1 = shift;
4822 0 my $val2 = shift;
4823 0 $stmt .= ' WHEN '.$self->valExpr($val1).' THEN '.$self->valExpr($val2);
4824 }
4825 0 $stmt .= ' END';
4826  
4827 0 return $stmt;
4828 }
4829  
4830 # -----------------------------------------------------------------------------
4831  
4832 =head3 opCAST() - Generiere CAST-Ausdruck (Wandlung Datentyp)
4833  
4834 =head4 Synopsis
4835  
4836 $sqlExpr = $sql->opCAST($op,$dataType,$arg);
4837  
4838 =cut
4839  
4840 # -----------------------------------------------------------------------------
4841  
4842 0 ▶sub opCAST {
Subroutine opCAST: not called CC=3 SCAR=24.8
Pod documented
4843 0 my $self = shift;
4844 0 my $op = shift;
4845 0 my $dataType = shift;
4846 0 my $arg = shift;
4847  
4848 # FIXME: Datentypen konvertieren
4849  
4850 0 ▶ if ($self->isPostgreSQL || $self->isSQLite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isPostgreSQL or $self->isSQLite) 0 0 0
Condition0%0/3
$self->isPostgreSQL or $self->isSQLite
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->isPostgreSQL or $self->isSQLite
$self->isPostgreSQL $self->isSQLite
Truth table0%0/3
A or B
A= $self->isPostgreSQLB= $self->isSQLite
ABresult
1X1
011
000
4851 0 return "CAST($arg AS $dataType)";
4852 }
4853 0 $self->throw('Not implemented');
4854 }
4855  
4856 # -----------------------------------------------------------------------------
4857  
4858 =head3 opIN() - Generiere IN- oder NOT IN-Ausdruck
4859  
4860 =head4 Synopsis
4861  
4862 $sqlExpr = $sql->opIN($op,@arr);
4863  
4864 =head4 Description
4865  
4866 Generiere Ausdruck "IN / NOT IN (VAL1, VAL2, ...)" und liefere diesen zurück.
4867  
4868 =cut
4869  
4870 # -----------------------------------------------------------------------------
4871  
4872 0 ▶sub opIN {
Subroutine opIN: not called CC=6 SCAR=37.4
Pod documented
4873 0 my $self = shift;
4874 0 my $op = shift;
4875 # @_: Werte
4876  
4877 0 my $str;
4878 0 ▶ if (@_ == 1 && $_[0] =~ /SELECT/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and $_[0] =~ /SELECT/i) 0 0 0
Condition0%0/3
@_ == 1 and $_[0] =~ /SELECT/i
!ll&&!rl&&r
000
MC/DC0%0/2
@_ == 1 and $_[0] =~ /SELECT/i
@_ == 1 $_[0] =~ /SELECT/i
Truth table0%0/3
A and B
A= @_ == 1B= $_[0] =~ /SELECT/i
ABresult
0X0
100
111
4879 # Subselect
4880 0 $str = Quiq::String->removeIndentationNl($_[0]);
4881 0 $str =~ s/^/ /mg;
4882 0 return "$op (\n$str )";
4883 }
4884  
4885 0 for (@_) {
4886 0 ▶ if ($str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str) 0 0 0
4887 0 $str .= ', ';
4888 }
4889 0 $str .= $_;
4890 # $str .= $self->valExpr($_); Problem: STRING wird zu '''STRING'''
4891 }
4892  
4893 0 ▶ return $str? "$op ($str)": '';
Branch: 1 branch
BranchTrueFalseTotal
$str ? : 0 0 0
4894 }
4895  
4896 # -----------------------------------------------------------------------------
4897  
4898 =head2 Expressions
4899  
4900 =head3 keyExpr() - Generiere SQL Identifier-Ausdruck
4901  
4902 =head4 Synopsis
4903  
4904 $sqlExpr = $sql->keyExpr($expr);
4905  
4906 =head4 Description
4907  
4908 Generiere einen SQL Bezeichner-Ausdruck zum portablen Ausdruck $expr
4909 und liefere den generierten Ausdruck zurück.
4910  
4911 Ein Bezeichner-Ausdruck ist ein Ausdruck, wie er in der Select-Liste
4912 und auf der linken Seite von WHERE-Klausel-Bedingungen vorkommt.
4913 Er zeichnet sich dadurch aus, dass seine elementaren Komponenten
4914 ungequotete Bezeichner sind (und keine Werte).
4915  
4916 =head4 Example
4917  
4918 =over 2
4919  
4920 =item *
4921  
4922 Einfacher Bezeichner
4923  
4924 $sql->keyExpr('per_id');
4925 ==>
4926 "per_id"
4927  
4928 =item *
4929  
4930 Ausdruck als Zeichenkette (nicht empfohlen, da nicht portabel)
4931  
4932 $sql->keyExpr('UPPER(per_nachname)');
4933 ==>
4934 "UPPER(per_nachname)"
4935  
4936 =item *
4937  
4938 Portabler Ausdruck
4939  
4940 $sql->keyExpr(['UPPER',['per_nachname']]);
4941 ==>
4942 "UPPER(per_nachname)"
4943  
4944 =item *
4945  
4946 Portabler Ausdruck mit Stringreferenz (wird String-Literal)
4947  
4948 $sql->keyExpr(['UPPER',[\'Ratlos']]);
4949 ==>
4950 "UPPER('Ratlos')"
4951  
4952 =back
4953  
4954 =cut
4955  
4956 # -----------------------------------------------------------------------------
4957  
4958 92 ▶sub keyExpr {
Subroutine keyExpr: called CC=5 SCAR=16.4
Pod documented
4959 92 my ($self,$expr) = @_;
4960  
4961 92 my $refType = ref $expr;
4962 92 ▶ if (!$refType) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $refType) { } 90 2 92
elsif ($refType eq 'SCALAR') { } 0 2 2
4963 90 ▶ if (!defined $expr || $expr eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $expr or $expr eq "") 1 89 90
Condition66%2/3
not defined $expr or $expr eq ""
l!l&&r!l&&!r
1089
MC/DC50%1/2
not defined $expr or $expr eq ""
not defined $expr $expr eq ""
Truth table66%2/3
not(A) or B
A= not defined $exprB= $expr eq ""
ABresult
1X1
011
000
4964 1 $self->throw('SQL-00005: Identifier fehlt');
4965 }
4966 89 return $expr;
4967 }
4968 elsif ($refType eq 'SCALAR') {
4969 0 return $self->stringLiteral($$expr);
4970 }
4971  
4972 2 return $self->expr('key',@$expr);
4973 }
4974  
4975 # -----------------------------------------------------------------------------
4976  
4977 =head3 valExpr() - Generiere SQL Wert-Ausdruck
4978  
4979 =head4 Synopsis
4980  
4981 $sqlExpr = $sql->valExpr($expr);
4982  
4983 =head4 Description
4984  
4985 Generiere einen SQL Wert-Ausdruck zum portablen Ausdruck $expr
4986 und liefere den generierten Ausdruck zurück.
4987  
4988 Ein Wert-Ausdruck ist ein Ausdruck, wie er auf der rechten Seite
4989 von WHERE-Klausel-Bedingungen vorkommt. Er zeichnet sich dadurch aus,
4990 dass seine elementaren Komponenten Literale, keine Bezeichner sind.
4991  
4992 =head4 Example
4993  
4994 =over 2
4995  
4996 =item *
4997  
4998 Literal
4999  
5000 $sql->valExpr('Kai Nelust');
5001 ==>
5002 "'Kai Nelust'"
5003  
5004 =item *
5005  
5006 Ausdruck
5007  
5008 $sql->valExpr(\'USERNAME');
5009 ==>
5010 "USERNAME"
5011  
5012 =item *
5013  
5014 Portabler Ausdruck
5015  
5016 $sql->valExpr(['UPPER','Kai Nelust']);
5017 ==>
5018 "UPPER('Kai Nelust')"
5019  
5020 =item *
5021  
5022 Portabler Ausdruck mit Stringreferenz (wird Identifier-Ausdruck)
5023  
5024 $sql->valExpr(['LOWER',\'USERNAME']);
5025 ==>
5026 "LOWER(USERNAME)"
5027  
5028 =back
5029  
5030 =cut
5031  
5032 # -----------------------------------------------------------------------------
5033  
5034 124 ▶sub valExpr {
Subroutine valExpr: called CC=3 SCAR=11.0
Pod documented
5035 124 my ($self,$expr) = @_;
5036  
5037 124 my $refType = ref $expr;
5038 124 ▶ if (!$refType) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $refType) { } 80 44 124
elsif ($refType eq 'SCALAR') { } 38 6 44
5039 80 return $self->stringLiteral($expr);
5040 }
5041 elsif ($refType eq 'SCALAR') {
5042 38 return $$expr;
5043 }
5044  
5045 6 return $self->expr('val',@$expr);
5046 }
5047  
5048 # -----------------------------------------------------------------------------
5049  
5050 =head3 whereExpr() - Generiere rechte Seite eines WHERE-Ausdrucks
5051  
5052 =head4 Synopsis
5053  
5054 $sqlExpr = $sql->whereExpr($expr);
5055  
5056 =head4 Description
5057  
5058 Generiere die rechte Seite eines WHERE-Ausdrucks zum portablen
5059 Ausdruck $expr und liefere den generierten Ausdruck zurück.
5060  
5061 Der Ausdruck besteht aus einem Operator gefolgt von einem Wert-Ausdruck.
5062  
5063 =head4 Example
5064  
5065 =over 2
5066  
5067 =item *
5068  
5069 Literal
5070  
5071 $sql->whereExpr('Kai Nelust');
5072 ==>
5073 "= 'Kai Nelust'"
5074  
5075 =item *
5076  
5077 Ausdruck
5078  
5079 $sql->whereExpr(\'USERNAME');
5080 ==>
5081 "= USERNAME"
5082  
5083 =item *
5084  
5085 Portabler Ausdruck
5086  
5087 $sql->whereExpr(['!=',['UPPER','Kai Nelust']]);
5088 ==>
5089 "!= UPPER('Kai Nelust')"
5090  
5091 =item *
5092  
5093 Portabler Ausdruck mit Stringreferenz (wird Identifier-Ausdruck)
5094  
5095 $sql->whereExpr(['!=',['LOWER',\'USERNAME']]);
5096 ==>
5097 "!= LOWER(USERNAME)"
5098  
5099 =back
5100  
5101 =cut
5102  
5103 # -----------------------------------------------------------------------------
5104  
5105 19 ▶sub whereExpr {
Subroutine whereExpr: called CC=3 SCAR=11.0
Pod documented
5106 19 my ($self,$expr) = @_;
5107  
5108 19 my $opExpr = $self->valExpr($expr);
5109 19 ▶ if ($opExpr eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($opExpr eq '') { } 5 14 19
elsif ('Quiq::Reference'->isArrayRef($expr)) { } 3 11 14
5110 5 return '';
5111 }
5112 elsif (Quiq::Reference->isArrayRef($expr)) {
5113 3 return $opExpr;
5114 }
5115 else {
5116 11 return "= $opExpr";
5117 }
5118 }
5119  
5120 # -----------------------------------------------------------------------------
5121  
5122 =head3 expr() - Wandele portablen Ausdruck in SQL-Ausdruck
5123  
5124 =head4 Synopsis
5125  
5126 $str = $sql->expr($type,$op,@args);
5127  
5128 =cut
5129  
5130 # -----------------------------------------------------------------------------
5131  
5132 6 my %opMethod = (
5133 '!=' => 'opRel',
5134 '<' => 'opRel',
5135 '<=' => 'opRel',
5136 '=' => 'opRel',
5137 '>' => 'opRel',
5138 '>=' => 'opRel',
5139 '~' => 'opRel',
5140 '!~' => 'opRel',
5141 'LIKE' => 'opRel',
5142 'NOT LIKE' => 'opRel',
5143 'AS' => 'opAS',
5144 'BETWEEN' => 'opBETWEEN',
5145 'CAST' => 'opCAST',
5146 'IN' => 'opIN',
5147 'NOT IN' => 'opIN',
5148 'LOWER' => 'opFunc',
5149 'MAX' => 'opFunc',
5150 'MIN' => 'opFunc',
5151 'SUBSTR' => 'opFunc',
5152 'UPPER' => 'opFunc',
5153 'COALESCE' => 'opFunc',
5154 'CASEXPR' => 'opCASEXPR',
5155 );
5156  
5157 8 ▶sub expr {
Subroutine expr: called CC=5 SCAR=17.6
Pod documented
5158 8 my $self = shift;
5159 8 my $type = shift;
5160 8 my $op = shift;
5161 # @_: @args
5162  
5163 8 my $meth = $opMethod{$op};
5164 8 ▶ if (!$meth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($meth) 0 8 8
5165 0 $self->throw('SQL-00006: Unbekannte SQL-Operation',Operation=>$op);
5166 }
5167  
5168 # Argumente (indirekt rekursiv) auflösen
5169  
5170 8 my $resMeth = $self->can($type.'Expr');
5171 8 for my $arg (@_) {
5172 8 $arg = $self->$resMeth($arg);
5173 8 ▶ if ($arg eq '' && $type eq 'val') {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg eq "" and $type eq "val") 0 8 8
Condition33%1/3
$arg eq "" and $type eq "val"
!ll&&!rl&&r
800
MC/DC0%0/2
$arg eq "" and $type eq "val"
$arg eq "" $type eq "val"
Truth table33%1/3
A and B
A= $arg eq ""B= $type eq "val"
ABresult
0X0
100
111
5174 # Wenn ein Argument leer ist, ist der gesamte Ausdruck leer
5175 0 return '';
5176 }
5177 }
5178  
5179 8 return $self->$meth($op,@_)
5180 }
5181  
5182 # -----------------------------------------------------------------------------
5183  
5184 =head3 stringLiteral() - Generiere SQL Stringliteral
5185  
5186 =head4 Synopsis
5187  
5188 $literal = $sql->stringLiteral($str);
5189 $literal = $sql->stringLiteral($str,$default);
5190  
5191 =head4 Description
5192  
5193 Verdoppele alle in $str enthaltenen einfachen Anführungsstriche,
5194 fasse den gesamten String in einfache Anführungsstriche ein und
5195 liefere das Resultat zurück.
5196  
5197 Ist der String leer ('' oder undef) liefere einen Leerstring
5198 (kein leeres String-Literal!). Ist $default angegeben, liefere diesen
5199 Wert.
5200  
5201 B<Anmerkung>: PostgreSQL erlaubt aktuell Escape-Sequenzen in
5202 String-Literalen. Wir behandeln diese nicht. Escape-Sequenzen sollten in
5203 postgresql.conf abgeschaltet werden mit der Setzung:
5204  
5205 standard_conforming_strings = on
5206  
5207 =head4 Examples
5208  
5209 Eingebettete Anführungsstriche:
5210  
5211 $sel->stringLiteral('Sie hat's');
5212 =>
5213 "'Sie hat''s'"
5214  
5215 Leerstring, wenn kein Wert:
5216  
5217 $sel->stringLiteral('');
5218 =>
5219 ""
5220  
5221 'NULL', wenn kein Wert:
5222  
5223 $sel->stringLiteral('','NULL');
5224 =>
5225 "NULL"
5226  
5227 =cut
5228  
5229 # -----------------------------------------------------------------------------
5230  
5231 83 ▶sub stringLiteral {
Subroutine stringLiteral: called CC=5 SCAR=16.4
Pod documented
5232 83 my $self = shift;
5233 83 my $str = shift;
5234 # @_: $default
5235  
5236 83 ▶ if (!defined $str || $str eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $str or $str eq "") 18 65 83
Condition100%3/3
not defined $str or $str eq ""
l!l&&r!l&&!r
11765
MC/DC100%2/2
not defined $str or $str eq ""
not defined $str $str eq ""
Truth table100%3/3
not(A) or B
A= not defined $strB= $str eq ""
ABresult
1X1
011
000
5237 18 ▶ return @_? shift: '';
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 18 18
5238 }
5239 65 ▶ if ($self->isMySQL) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isMySQL) 0 65 65
5240 0 $str =~ s|\\|\\\\|g;
5241 }
5242 65 $str =~ s/'/''/g;
5243  
5244 65 return "'$str'";
5245 }
5246  
5247 # -----------------------------------------------------------------------------
5248  
5249 =head3 withClause() - Liefere WITH-Klausel
5250  
5251 =head4 Synopsis
5252  
5253 $withClause = $sql->withClause(@keyVal);
5254  
5255 =head4 Description
5256  
5257 Wandele die Liste von Schlüssel/Wert-Paaren @keyVal in eine WITH-Klausel
5258 (ohne WITH-Schlüsselwort) und liefere diese zurück. Der Wert ist jeweils
5259 ein SELECT-Statement und der Schlüssel ein Bezeichner für das Statement.
5260  
5261 =head4 Example
5262  
5263 $sql->withClause(x=>'SELECT * FROM a',y=>'SELECT * FROM b');
5264  
5265 liefert
5266  
5267 x AS (
5268 SELECT * FROM a
5269 ),
5270 y AS (
5271 SELECT * FROM b
5272 )
5273  
5274 =cut
5275  
5276 # -----------------------------------------------------------------------------
5277  
5278 86 ▶sub withClause {
Subroutine withClause: called CC=3 SCAR=11.0
Pod documented
5279 86 my $self = shift;
5280 # @_: @keyVal
5281  
5282 86 my @arr;
5283 86 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 86 88
5284 2 my $name = shift;
5285 2 my $stmt = Quiq::Unindent->trim(shift);
5286 2 $stmt =~ s/^/ /mg;
5287 2 push @arr,"$name AS (\n$stmt\n)";
5288 }
5289  
5290 86 ▶ return @arr? join(",\n",@arr): '';
Branch: 1 branch
BranchTrueFalseTotal
@arr ? : 1 85 86
5291 }
5292  
5293 # -----------------------------------------------------------------------------
5294  
5295 =head3 selectClause() - Liefere SELECT-Klausel
5296  
5297 =head4 Synopsis
5298  
5299 $selectClause = $sql->selectClause(@select);
5300  
5301 =cut
5302  
5303 # -----------------------------------------------------------------------------
5304  
5305 51 ▶sub selectClause {
Subroutine selectClause: called CC=2 SCAR=6.9
Pod documented
5306 51 my $self = shift;
5307 51 my @select = @_;
5308  
5309 51 for my $expr (@select) {
5310 70 $expr = $self->keyExpr($expr);
5311 70 $expr =~ s/\n/\n /g; # mehrzeilige Ausdrücke rücken wir ein
5312 }
5313  
5314 51 return join "\n , ",@select;
5315 }
5316  
5317 # -----------------------------------------------------------------------------
5318  
5319 =head3 fromClause() - Liefere FROM-Klausel
5320  
5321 =head4 Synopsis
5322  
5323 $fromClause = $sql->fromClause(@from);
5324  
5325 =head4 Description
5326  
5327 Wandele die Liste von From-Elementen, @from, in eine FROM-Klausel
5328 und liefere diese zurück.
5329  
5330 Die Elemente werden mit Komma als Trennzeichen konkateniert und
5331 folgendermaßen behandelt:
5332  
5333 =over 4
5334  
5335 =item 'string'
5336  
5337 Eine Zeichenkette wird nicht verändert.
5338  
5339 =item ['AS',$alias,$fromExpr]
5340  
5341 Es wird ein FROM-Alias erzeugt. Dieser hat entweder den Aufbau
5342 "expr AS alias" oder "fromExpr alias", abhängig vom DBMS.
5343 Oracle akzeptiert "fromExpr AS alias" nicht.
5344  
5345 =back
5346  
5347 =cut
5348  
5349 # -----------------------------------------------------------------------------
5350  
5351 89 ▶sub fromClause {
Subroutine fromClause: called CC=5 SCAR=16.2
Pod documented
5352 89 my $self = shift;
5353 89 my @from = @_; # Wir müssen kopieren
5354  
5355 89 for my $expr (@from) {
5356 85 ▶ if (ref $expr) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $expr) 2 83 85
5357 2 ▶ if ($expr->[0] eq 'AS') {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr->[0] eq 'AS') { } 2 0 2
5358 2 ▶ if ($self->isOracle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isOracle) { } 1 1 2
5359 1 $expr = "$expr->[2] $expr->[1]";
5360 }
5361 else {
5362 1 $expr = "$expr->[2] AS $expr->[1]";
5363 }
5364 }
5365 else {
5366 0 $self->throw('Not implemented');
5367 }
5368 }
5369 85 $expr = Quiq::String->removeIndentation($expr);
5370 # $expr =~ s/\n/\n /g;
5371 }
5372  
5373 89 return join "\n, ",@from;
5374 }
5375  
5376 # -----------------------------------------------------------------------------
5377  
5378 =head3 whereClause() - Liefere WHERE-Klausel
5379  
5380 =head4 Synopsis
5381  
5382 $where = $sql->whereClause(@where);
5383  
5384 =head4 Description
5385  
5386 Wenn +null in @where vorkommt, werden alle folgenden
5387 leeren Bedingungen nicht übergangen.
5388  
5389 =cut
5390  
5391 # -----------------------------------------------------------------------------
5392  
5393 95 ▶sub whereClause {
Subroutine whereClause: called CC=10 SCAR=24.1
Pod documented
5394 95 my $self = shift;
5395 # @_: @where
5396  
5397 95 my $plusNull = 0; # Wenn gesetzt, übergehen wir leere Bedingungen nicht
5398  
5399 # FIXME: Logische Operatoren OR und NOT und Klammern
5400  
5401 95 my @where;
5402 95 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 79 95 174
5403 79 ▶ if (defined($_[0]) && $_[0] =~ /[\s=><]/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0] and $_[0] =~ /[\s=><]/) 62 17 79
Condition66%2/3
defined $_[0] and $_[0] =~ /[\s=><]/
!ll&&!rl&&r
01762
MC/DC50%1/2
defined $_[0] and $_[0] =~ /[\s=><]/
defined $_[0] $_[0] =~ /[\s=><]/
Truth table66%2/3
A and B
A= defined $_[0]B= $_[0] =~ /[\s=><]/
ABresult
0X0
100
111
5404 # Enthält das Argument Leerzeichen oder einen der
5405 # Vergleichsoperatoren =, >, <, betrachten wir es als
5406 # vollständige Klausel und übernehmen es in die WHERE-Klausel.
5407  
5408 62 my $clause = Quiq::String->removeIndentation(shift);
5409 62 ▶ if ($clause =~ /\n/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($clause =~ /\n/) 0 62 62
5410 # Einrücken, wenn mehrzeilig (z.B. EXISTS-Klausel)
5411
5412 0 $clause =~ s/^/ /gm;
5413 0 $clause =~ s/^\s+//;
5414 }
5415 62 push @where,$clause;
5416 62 next;
5417 }
5418  
5419 # Wir betrachten das Argument als Kolumnenname und das
5420 # nächste Argument als Vergleichswert mit Operator.
5421  
5422 17 my $key = shift;
5423 17 ▶ if (!defined $key || $key eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $key or $key eq '') { } 0 17 17
elsif ($key eq '+null') { } 1 16 17
Condition33%1/3
not defined $key or $key eq ""
l!l&&r!l&&!r
0017
MC/DC0%0/2
not defined $key or $key eq ""
not defined $key $key eq ""
Truth table33%1/3
not(A) or B
A= not defined $keyB= $key eq ""
ABresult
1X1
011
000
5424 # leere Exists/Not Exists-Klauseln übergehen
5425 0 next;
5426 }
5427 elsif ($key eq '+null') {
5428 1 $plusNull = 1;
5429 1 next;
5430 }
5431  
5432 16 $key = $self->keyExpr($key);
5433 16 my $opVal = $self->whereExpr(shift);
5434 16 ▶ if ($opVal eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($opVal eq "") 5 11 16
5435 5 ▶ unless ($plusNull) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plusNull) 5 0 5
5436 # Wir übergehen die Bedingung
5437 5 next;
5438 }
5439 0 $opVal = 'IS NULL';
5440 }
5441 11 push @where,"$key $opVal";
5442 }
5443  
5444 # return join " AND\n ",@where;
5445 95 return join "\n AND ",@where;
5446 }
5447  
5448 # -----------------------------------------------------------------------------
5449  
5450 =head3 setClause() - Liefere SET-Klausel für UPDATE-Statement
5451  
5452 =head4 Synopsis
5453  
5454 $set = $sql->setClause(@keyVal);
5455  
5456 =cut
5457  
5458 # -----------------------------------------------------------------------------
5459  
5460 10 ▶sub setClause {
Subroutine setClause: called CC=3 SCAR=11.0
Pod documented
5461 10 my $self = shift;
5462 # @_: @keyVal
5463  
5464 10 my @set;
5465 10 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 11 10 21
5466 11 my $key = shift;
5467 11 my $val = $self->valExpr(shift);
5468 11 ▶ if ($val eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($val eq "") 2 9 11
5469 2 $val = 'NULL';
5470 }
5471 11 push @set,"$key = $val";
5472 }
5473  
5474 10 return join ",\n ",@set;
5475 }
5476  
5477 # -----------------------------------------------------------------------------
5478  
5479 =head3 exists() - Liefere EXISTS-Klausel
5480  
5481 =head4 Synopsis
5482  
5483 $str = $sql->exists(@opt,@select);
5484  
5485 =head4 Options
5486  
5487 =over 4
5488  
5489 =item -active => $bool (Default: 1)
5490  
5491 Bedingung, unter der die EXISTS-Klausel gilt. Ist $bool falsch, liefert
5492 die Methode eine leere Liste (Array-Kontext) oder einen Leerstring
5493 (Skalar-Kontext), d.h. die Klausel kann in der Verarbeitung
5494 ignoriert werden.
5495  
5496 =item -not => $bool (Default: 0)
5497  
5498 Liefere NOT EXISTS Klausel.
5499  
5500 =back
5501  
5502 =cut
5503  
5504 # -----------------------------------------------------------------------------
5505  
5506 2 ▶sub exists {
Subroutine exists: called CC=4 SCAR=14.6
Pod documented
5507 2 my $self = shift;
5508 # @_: @opt,@select
5509  
5510 2 my $active = 1;
5511 2 my $not = 0;
5512  
5513 2 Quiq::Option->extract(-mode=>'sloppy',\@_,
5514 -active => \$active,
5515 -not => \$not,
5516 );
5517  
5518 2 ▶ if (!$active) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($active) 0 2 2
5519 0 ▶ return wantarray? (): '';
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
5520 }
5521  
5522 2 my $stmt = $self->select(@_);
5523 2 $stmt =~ s/^/ /gm;
5524  
5525 2 ▶ return ($not? 'NOT ': '')."EXISTS (\n$stmt\n)";
Branch: 1 branch
BranchTrueFalseTotal
$not ? : 1 1 2
5526 }
5527  
5528 # -----------------------------------------------------------------------------
5529  
5530 =head3 notExists() - Liefere NOT EXISTS-Klausel
5531  
5532 =head4 Synopsis
5533  
5534 $str = $sql->notExists(@select);
5535  
5536 =cut
5537  
5538 # -----------------------------------------------------------------------------
5539  
5540 1 ▶sub notExists {
Subroutine notExists: called CC=1 SCAR=0.0
Pod documented
5541 1 return shift->exists(-not=>1,@_);
5542 }
5543  
5544 # -----------------------------------------------------------------------------
5545  
5546 =head3 union() - Verknüpfe Statements mit UNION
5547  
5548 =head4 Synopsis
5549  
5550 $stmt = $sql->union(@stmts);
5551  
5552 =head4 Arguments
5553  
5554 =over 4
5555  
5556 =item @stmts
5557  
5558 Statements, die mit UNION verknpft werden.
5559  
5560 =back
5561  
5562 =head4 Returns
5563  
5564 String
5565  
5566 =head4 Description
5567  
5568 Verknüpfe die (SELECT-)Statements @stmts per UNION und liefere das
5569 resultierende Statement zurück.
5570  
5571 =cut
5572  
5573 # -----------------------------------------------------------------------------
5574  
5575 2 ▶sub union {
Subroutine union: called CC=3 SCAR=11.0
Pod documented
5576 2 my $self = shift;
5577 # @_: @stmts
5578  
5579 2 my $stmt = '';
5580 2 for (@_) {
5581 2 ▶ if ($stmt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt) 1 1 2
5582 1 $stmt .= "\nUNION\n";
5583 }
5584 2 $stmt .= Quiq::Unindent->trim($_);
5585 }
5586  
5587 2 return $stmt;
5588 }
5589  
5590 # -----------------------------------------------------------------------------
5591  
5592 =head2 Spezielle Konstrukte
5593  
5594 =head3 diff() - Liefere SELECT zur Differenzermittlung
5595  
5596 =head4 Synopsis
5597  
5598 $stmt = $sql->diff(
5599 $keyCol,
5600 $fromClause,
5601 [$type,$col1,$col2,$col2Expr],
5602 ...
5603 @where,
5604 @selOpts
5605 );
5606  
5607 =head4 Example
5608  
5609 $tab = $db->diff(
5610 't.id',
5611 "de_ticket t LEFT OUTER JOIN spielgemeinschaftanteil s\n".
5612 'ON t.id = s.spielid*65536+1',
5613 ['N','t.subscription'=>'s.dauerschein'],
5614 ['N','t.product_id'=>'s.spielgemeinschaftid',
5615 \'CASE %C WHEN 9685 THEN 24 WHEN 9684 THEN 26 WHEN 9687 THEN 28 END',
5616 ],
5617 't.product_ticket_type'=>'LOTTERY_CLUB_TICKET',
5618 -limit => 100,
5619 );
5620  
5621 =cut
5622  
5623 # -----------------------------------------------------------------------------
5624  
5625 0 ▶sub diff {
Subroutine diff: not called CC=5 SCAR=34.0
Pod documented
5626 0 my $self = shift;
5627 0 my $keyCol = shift;
5628 0 my $fromClause = shift;
5629 # @_: @colSpecs,@where
5630  
5631 # Schlüssel-Kolumne
5632 0 (my $keyColAlias = $keyCol) =~ s/\./_/;
5633  
5634 # Kolumnenspezifikation auswerten
5635  
5636 0 my @select = (['AS',$keyCol,$keyColAlias]);
5637 0 my @or;
5638 0 ▶ while (ref $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0]) 0 0 0
5639 0 my $colSpec = shift;
5640  
5641 # FIXME: DefaultVal-Typen erweitern
5642  
5643 0 my $type = $colSpec->[0];
5644 0 my $defaultVal;
5645 0 ▶ if ($type eq 'S') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'S') { } 0 0 0
elsif ($type eq 'N') { } 0 0 0
5646 0 $defaultVal = \'(null)';
5647 }
5648 elsif ($type eq 'N') {
5649 0 $defaultVal = '-1';
5650 }
5651 else {
5652 0 $self->throw(
5653 'SQL-00003: Unbekannter Datentyp',
5654 Type => $type,
5655 );
5656 }
5657  
5658 0 my $col1Name = $colSpec->[1];
5659 0 (my $col1Alias = $col1Name) =~ s/\./_/;
5660 0 push @select,['AS',$col1Name,$col1Alias];
5661  
5662 0 my $col2Name = $colSpec->[2];
5663 0 my $col2Expr;
5664 0 ▶ if ($colSpec->[3]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($colSpec->[3]) { } 0 0 0
5665 0 $col2Expr = $self->valExpr($colSpec->[3]);
5666 0 $col2Expr =~ s/%C/$col2Name/g;
5667 }
5668 else {
5669 0 $col2Expr = $col2Name;
5670 }
5671 0 (my $col2Alias = $col2Name) =~ s/\./_/;
5672 0 push @select,['AS',$col2Expr,$col2Alias];
5673 # push @select,['AS',$col2Name,$col2Alias];
5674  
5675 0 push @or,$self->keyExpr(['COALESCE',$col1Name,$defaultVal]).' <> '.
5676 $self->keyExpr(['COALESCE',$col2Expr,$defaultVal]);
5677 }
5678  
5679 # WHERE-Klausel und Statement-Optionen wie -limt (welche
5680 # am Ende stehen müssen)
5681  
5682 0 my @opt = Quiq::Option->extractAll(\@_);
5683 0 my @where = (@_,'('.join(" OR\n ",@or).')');
5684  
5685 0 return $self->select(
5686 -select => @select,
5687 -from => $fromClause,
5688 -where => @where,
5689 @opt,
5690 );
5691 }
5692  
5693 # -----------------------------------------------------------------------------
5694  
5695 =head1 VERSION
5696  
5697 1.240
5698  
5699 =head1 AUTHOR
5700  
5701 Frank Seitz, L<http://fseitz.de/>
5702  
5703 =head1 COPYRIGHT
5704  
5705 Copyright (C) 2026 Frank Seitz
5706  
5707 =head1 LICENSE
5708  
5709 This code is free software; you can redistribute it and/or modify
5710 it under the same terms as Perl itself.
5711  
5712 =cut
5713  
5714 # -----------------------------------------------------------------------------
5715  
5716 6 1;
5717  
5718 # eof
« Quiq/Terminal.pm ↑ Summary Quiq/Http/Client.pm »