lib/oEdtk/DBAdmin.pm

filter: Statementstmt 38.1% 1009 / 2644 Branchbran 26.9% 302 / 1122 Conditioncond 15.5% 134 / 864 MC/DCmcdc 6.9% 33 / 472 Subroutinesub 53.8% 104 / 193 Podpod 70.0% 35 / 50 totaltotal 30.2% 1617 / 5345 CC 962 SCAR 54.1
CC
962
Cov
31%
acheck_db_admin_on_connect
1722.0
__ANON__
1190.0
schema_AdditivePlan
870.0
CRAP 223.7
« blib/lib/oEdtk/Tracking2.pm ↑ Summary blib/lib/oEdtk/logger2.pm »
1 package oEdtk::DBAdmin;
2  
3 32 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 32 ▶use oEdtk::Config qw(config_read);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 32 ▶use oEdtk::logger qw(logger $LOGGERLEVEL $WARN2LOGGER);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 32 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 32 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 32 ▶use Digest::MD5 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 32 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 32 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 32 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 32 ▶use Encode qw(encode decode find_encoding);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 32 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 32 ▶use Data::Dumper qw(Dumper);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 # check sql : https://www.eversql.com
17 # SHOW CREATE DATABASE oEdtk;
18  
19 32 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 32 our $VERSION = 2.1131;
21 32 our $VERSION_TXT = $VERSION =~ s/\./_/gr;
22 32 our @ISA = qw(Exporter);
23 32 our @EXPORT_OK = qw(
24 acheck_db_admin_on_connect
25 acheck_db_admin
26 agrege_idJob
27 copy_table
28 create_SCHEMA
29 schema_Create
30 schema_Upgrade
31 schema_Detect
32 schema_Report
33 schema_Manifest
34 schema_MigrationPlan
35 schema_Historize
36 schema_Revert
37 schema_Additive
38 schema_AdditivePlan
39 schema_StaleWarning
40 create_lot_sequence
41 create_table_TRACKING
42 create_table_OUTMNGR
43 create_table_DISTRIB
44 create_table_ACQUIT
45 create_table_ACQMGENTECH
46 create_table_SCHEMA_HISTORY
47 create_table_ADMIN
48 create_table_AGREGE
49 create_table_DATAGROUPS
50 create_table_FILIERES
51 create_table_ID
52 create_table_INDEX
53 create_table_LOTS
54 create_table_PARA
55 create_table_REFIDDOC
56 create_table_SUPPORTS
57 csv_import
58 db_backup_agent
59 db_backup_available
60 db_backup_pending
61 db_backup_prepare
62 db_reconcile_backup
63 db_on_backup
64 db_check_privileges
65 db_invalidate_meta_cache
66 db_connect
67 db_drop_table
68 get_columns_names
69 historicize_table
70 insert_tData
71 schema_History_add
72 move_table
73 admin_optimize_db
74 @INDEX_COLS
75 @TRACKER_COLS
76 );
77  
78 32 my $_LOCAL_EDTK_WAITRUN = 0;
79 32 my $CONNECT_COUNT = 0;
80  
81 # Re-entrancy guards (package variables so `local` can scope them per call).
82 32 our $IN_ACHECK = 0; # acheck_db_admin_on_connect
83 32 our $IN_RECONCILE = 0; # db_reconcile_backup
84 32 our %_csv_import_type_cache;
85 32 my $_DB_ENGINE_CACHE;
86 32 my $_PG_STG_SEQ = 0; # ELT staging-table sequence (D60)
87  
88 # PostgreSQL bulk-load tuning (used by _load_csv_pg_copy / _pg_load_tx).
89 32 ▶use constant PG_COPY_SYNC_OFF =>
Subroutine BEGIN: called CC=1 SCAR=0.0
90 32 'SET LOCAL synchronous_commit = off'; # relax fsync for this transaction only
91 32 ▶use constant PG_COPY_ANALYZE => 'ANALYZE %s'; # refresh planner stats after a bulk load
Subroutine BEGIN: called CC=1 SCAR=0.0
92 32 ▶use constant PG_COPY_BLOCK_SIZE => 1 << 20; # bytes fed per pg_putcopydata call
Subroutine BEGIN: called CC=1 SCAR=0.0
93  
94 # Index-deferral policy (H4 / O4): dropping and rebuilding the secondary indexes
95 # and unique / foreign-key constraints takes an exclusive lock for the whole COPY,
96 # so it is opt-in and gated on the incoming volume (see _pg_should_defer).
97 32 ▶use constant PG_COPY_LOCK_TIMEOUT => '5s'; # cap the lock wait for the deferral
Subroutine BEGIN: called CC=1 SCAR=0.0
98 32 ▶use constant PG_DEFER_DEFAULT_RATIO => 0.1; # defer if incoming >= 10% of the table
Subroutine BEGIN: called CC=1 SCAR=0.0
99 32 ▶use constant PG_DEFER_DEFAULT_MIN_ROWS => 10_000; # ... and at least this many rows
Subroutine BEGIN: called CC=1 SCAR=0.0
100 32 ▶use constant PG_DEFER_SAMPLE_BYTES => 65_536; # header sample used to size the import
Subroutine BEGIN: called CC=1 SCAR=0.0
101 32 ▶use constant PG_ANALYZE_TABLE_SHARE => 0.1; # ANALYZE only if rows added >= 10% (O5)
Subroutine BEGIN: called CC=1 SCAR=0.0
102  
103 # ELT staging path (D60): above EDTK_DB_BURST_MO megabytes a PostgreSQL insert
104 # loads into an unconstrained TEMP staging table with one raw COPY and moves the
105 # rows with a single INSERT ... SELECT, skipping the per-row Perl parse. The
106 # default threshold is 50 MiB; see _pg_burst_decision.
107 32 ▶use constant PG_BURST_MO_DEFAULT => 50; # default threshold, in MiB; 0 disables ELT
Subroutine BEGIN: called CC=1 SCAR=0.0
108 32 ▶use constant PG_BURST_BYTES_PER_MO => 1_048_576; # bytes per MiB
Subroutine BEGIN: called CC=1 SCAR=0.0
109 32 ▶use constant PG_STG_PREFIX => 'edtk_stg_'; # staging table name prefix
Subroutine BEGIN: called CC=1 SCAR=0.0
110 32 ▶use constant PG_BURST_MAINT_MEM => '256MB'; # maintenance_work_mem during an index rebuild
Subroutine BEGIN: called CC=1 SCAR=0.0
111  
112 # Positions in the acknowledgement (ACQUIT) file, the fork's format (D-S53).
113 # _acquit_table_INDEX and _acquit_API read these fields; together they locate the
114 # indexed items whose mailing-out date and status the acknowledgement stamps.
115 32 ▶use constant ACQ_FIELD_LOT => 2; # mailing batch id (sub-batch)
Subroutine BEGIN: called CC=1 SCAR=0.0
116 32 ▶use constant ACQ_FIELD_PLI => 7; # folded-item file name, "name_number"
Subroutine BEGIN: called CC=1 SCAR=0.0
117 32 ▶use constant ACQ_FIELD_IDDEST => 11; # recipient id in the management system
Subroutine BEGIN: called CC=1 SCAR=0.0
118 32 ▶use constant ACQ_FIELD_DTLOT => 25; # batch reception date (its year prefix)
Subroutine BEGIN: called CC=1 SCAR=0.0
119 32 ▶use constant ACQ_FIELD_EXPED => 26; # mailing-out date (DATEEXPED)
Subroutine BEGIN: called CC=1 SCAR=0.0
120 32 ▶use constant ACQ_FIELD_STATUS => 29; # acknowledgement status
Subroutine BEGIN: called CC=1 SCAR=0.0
121  
122 0 ▶sub move_table {
Subroutine move_table: not called CC=1 SCAR=6.9
Pod documented
123 0 &logger( 4,
124 "method oEdtk::DBAdmin::move_table is deprecated you should use oEdtk::DBAdmin::copy_table"
125 );
126  
127 0 copy_table(@_);
128 0 1;
129 }
130  
131 5 ▶sub copy_table {
Subroutine copy_table: called CC=5 SCAR=16.4
Pod documented
132 5 my ( $dbh, $table_source, $table_cible, $create_option ) = @_;
133 5 ▶ $create_option ||= "";
Condition50%1/2
$create_option ||= ""
l!l
50
MC/DC0%0/1
$create_option ||= ""
$create_option
Truth table50%1/2
A
A= $create_option
Aresult
11
00
134  
135 # check if source is empty
136 5 my $sql_check_source = "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM " . $table_source;
137 5 my $sth = $dbh->prepare($sql_check_source);
138 5 ▶ do { local $sth->{PrintError} = 0; $sth->execute() }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 5 0 5
139 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
140 5 my $result = $sth->fetchrow_array;
141 5 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 1 4 5
142 1 &logger( 4, "Source $table_source is empty, copy aborted" );
143 1 return 1;
144 }
145  
146 # preparing the data copy from source to target
147 4 &logger( 5, "Data from $table_source will be copyed into $table_cible" );
148  
149 4 ▶ if ( $create_option =~ /-create/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($create_option =~ /-create/i) { } 4 0 4
150 4 my $sql_create = "CREATE TABLE " . $table_cible . " AS SELECT * FROM " . $table_source;
151  
152 # on error, DIE so no other operation runs against the databases (db_backup_agent, ...)
153 4 _db_do_log(
154 $dbh,
155 _sql_fixup( $dbh, $sql_create, 'casse' ),
156 "ERROR: can't create $table_cible",
157 fatal => 1
158 );
159  
160 }
161 else {
162 0 my $sql_insert = "INSERT INTO " . $table_cible . " SELECT * FROM " . $table_source;
163  
164 # on error, DIE so no other operation runs against the databases (db_backup_agent, ...)
165 0 _db_do_log(
166 $dbh,
167 _sql_fixup( $dbh, $sql_insert, 'casse' ),
168 "ERROR: can't insert into $table_cible",
169 fatal => 1
170 );
171 }
172  
173 4 &logger( 6, "Insert DONE into $table_cible" );
174 4 1;
175 }
176  
177 0 ▶sub _load_csv_mysql_local_infile {
Subroutine _load_csv_mysql_local_infile: not called CC=9 SCAR=45.0
178 0 my ( $dbh, $tablename, $fi, $params ) = @_;
179  
180 # read the header line: it holds the field names and the insert order
181 0 ▶ open( my $fh, '<', $fi ) or die "ERROR: Cannot open file \"$fi\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fi or die qq[ERROR: Cannot open file "$fi": $!\n] 0 0 0
182 0 my $fields = <$fh>;
183 0 chomp($fields);
184 0 $fields =~ s/\"+//g;
185 0 close($fh);
186  
187 # H9 : validate the header columns before building the LOAD statement.
188 0 my ( $norm_id, $norm_table, @cols ) =
189 _norm_identifiers( $dbh, $tablename, [ split( /,/, $fields ) ] );
190 0 my $col_meta = _get_col_meta( $dbh, $norm_table, $norm_id );
191 0 ▶ my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
Branch: 1 branch
BranchTrueFalseTotal
keys %$col_meta ? : 0 0 0
192 0 ▶ if (@$unknown) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$unknown) 0 0 0
193 return (
194 0 -1,
195 &logger(
196 3,
197 "LOAD DATA: unknown column(s) " . join( ', ', @$unknown ) . " for table $tablename"
198 )
199 );
200 }
201  
202 0 my $sep = $params->{'sep_char'};
203 my $sql =
204 "LOAD DATA LOCAL INFILE ? INTO TABLE $tablename CHARACTER SET latin1 "
205 . " FIELDS TERMINATED BY '"
206 . $sep
207 . "' ENCLOSED BY '"
208 0 . $params->{'quote_char'} . "' "
209 . " LINES TERMINATED BY '" . '\n' . "'"
210 . " IGNORE 1 LINES "
211 . "($fields)";
212 0 &logger( 7, $sql );
213  
214 ## OPTIONALLY ENCLOSED BY '"'
215 ## REPLACE
216  
217 0 &logger( 7, "_load_csv_mysql_local_infile trying : $sql" );
218  
219 0 my $count = _db_do_log( $dbh, $sql, "SQL execute failed", bind => [$fi] );
220  
221 0 ▶ if ( !defined $count || ( $count !~ m/^\d+$/ && $count ne '0E0' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $count or not $count =~ /^\d+$/ and $count ne "0E0") 0 0 0
Condition0%0/6
not defined $count or not $count =~ /^\d+$/ and $count ne "0E0"
l!l&&r!l&&!r
000
not $count =~ /^\d+$/ and $count ne "0E0"
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $count or not $count =~ /^\d+$/ and $count ne "0E0"
not defined $count not $count =~ /^\d+$/ $count ne "0E0"
Truth table0%0/4
not(A) or not(B) and C
A= not defined $countB= not $count =~ /^\d+$/C= $count ne "0E0"
ABCresult
1XX1
0111
00X0
0100
222 0 ▶ return ( -1, &logger( 3, "$count-ERROR LOAD INFILE-$@ $!" . ( $dbh->errstr // '' ) ) );
Condition0%0/2
$dbh->errstr // ""
l!l
00
MC/DC0%0/1
$dbh->errstr // ""
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
223 }
224  
225 # Refresh the planner statistics after the bulk load (parity with the PG COPY path).
226 0 ▶ eval { local $dbh->{PrintError} = 0; $dbh->do("analyze table $tablename"); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do("analyze table $tablename"); 1 } } or &logger(7, "_load_csv_mysql_local_infile: analyze table $tablename failed: $@") 0 0 0
227 or &logger( 7, "_load_csv_mysql_local_infile: analyze table $tablename failed: $@" );
228  
229 0 my $rows = _count_csv_rows( $fi, $params );
230 0 &logger( 5, "bulk insert into $tablename via LOAD DATA LOCAL INFILE: $rows rows" );
231 0 return ( $count, " lines inserted" );
232 }
233  
234 # ============================================================
235 # PRIVATE : serialize one CSV field (RFC4180 style).
236 # undef => unquoted empty field => read as NULL by COPY (NULL '')
237 # '' => force-quoted "" => read as empty string (clean_val parity)
238 # otherwise=> quoted only when needed (sep, quote, CR or LF inside)
239 # ============================================================
240 35031 ▶sub _pg_csv_field {
Subroutine _pg_csv_field: called CC=6 SCAR=17.9
241 35031 my ( $val, $sep, $quo ) = @_;
242 35031 ▶ return '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 7 35024 35031
243 35024 ▶ return $val
Branch: 1 branch
BranchTrueFalseTotal
unless $val eq "" or index($val, $sep) != -1 or index($val, $quo) != -1 or $val =~ /[\r\n]/ 35010 14 35024
Condition100%9/9
$val eq "" or index($val, $sep) != -1 or index($val, $quo) != -1 or $val =~ /[\r\n]/
l!l&&r!l&&!r
13135010
$val eq "" or index($val, $sep) != -1 or index($val, $quo) != -1
l!l&&r!l&&!r
10335011
$val eq "" or index($val, $sep) != -1
l!l&&r!l&&!r
7335014
MC/DC100%4/4
$val eq "" or index($val, $sep) != -1 or index($val, $quo) != -1 or $val =~ /[\r\n]/
$val eq "" index($val, $sep) != -1 index($val, $quo) != -1 $val =~ /[\r\n]/
Truth table100%5/5
A or B or C or D
A= $val eq ""B= index($val, $sep) != -1C= index($val, $quo) != -1D= $val =~ /[\r\n]/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
244 unless $val eq ''
245 || index( $val, $sep ) >= 0
246 || index( $val, $quo ) >= 0
247 || $val =~ /[\r\n]/;
248 14 ( my $esc = $val ) =~ s/\Q$quo\E/$quo$quo/g;
249 14 return $quo . $esc . $quo;
250 }
251  
252 # ============================================================
253 # PRIVATE : clean then serialize one CSV record for COPY. The per-column
254 # cleaning flags are passed positionally ($blank_to_null and $col_size,
255 # precomputed from the column metadata) so no hash lookup or closure runs per
256 # value ; the result matches the _make_clean_val contract (truncation, and
257 # '' => NULL for numeric/date columns). Fields are serialized with
258 # _pg_csv_field. Debug logs are guarded so their message is not built when the
259 # level is disabled.
260 # ============================================================
261 7005 ▶sub _pg_csv_row {
Subroutine _pg_csv_row: called CC=9 SCAR=22.0
262 7005 my ( $data, $cols, $sep, $quo, $blank_to_null, $col_size ) = @_;
263 7005 my @out;
264 7005 for my $i ( 0 .. $#{$cols} ) {
265 35025 my $v = $data->[$i];
266 35025 ▶ if ( defined $v ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $v) 35024 1 35025
267 35024 ▶ if ( $v eq '' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($v eq '') { } 11 35013 35024
elsif ($col_size->[$i] and length $v > $col_size->[$i]) { } 2 70017 70019
268 11 ▶ if ( $blank_to_null->[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($blank_to_null->[$i]) 5 6 11
269 5 ▶ &logger( 7, "clean_val: col '$cols->[$i]' numeric/date, '' => undef" )
Branch: 1 branch
BranchTrueFalseTotal
if $oEdtk::DBAdmin::LOGGERLEVEL >= 7 0 5 5
270 if $LOGGERLEVEL >= 7;
271 5 $v = undef;
272 }
273 }
274 ▶ elsif ( $col_size->[$i] && length($v) > $col_size->[$i] ) {
Condition100%3/3
$col_size->[$i] and length $v > $col_size->[$i]
!ll&&!rl&&r
3500652
MC/DC100%2/2
$col_size->[$i] and length $v > $col_size->[$i]
$col_size->[$i] length $v > $col_size->[$i]
Truth table100%3/3
A and B
A= $col_size->[$i]B= length $v > $col_size->[$i]
ABresult
0X0
100
111
275 2 ▶ &logger( 6,
Branch: 1 branch
BranchTrueFalseTotal
if $oEdtk::DBAdmin::LOGGERLEVEL >= 6 0 2 2
276 "clean_val: col '$cols->[$i]' truncated from "
277 . length($v)
278 . " to $col_size->[$i] chars" )
279 if $LOGGERLEVEL >= 6;
280 2 $v = substr( $v, 0, $col_size->[$i] );
281 }
282 }
283 35025 push @out, _pg_csv_field( $v, $sep, $quo );
284 }
285 7005 return join( $sep, @out );
286 }
287  
288 # ============================================================
289 # PRIVATE : build the COPY ... FROM STDIN byte supplier for one CSV source.
290 # The returned coderef yields up to PG_COPY_BLOCK_SIZE bytes of cleaned,
291 # client_encoding-encoded CSV per call, or undef at end of stream, and dies on
292 # a CSV parse error (the message carries the line number). Rows are cleaned and
293 # serialized by _pg_csv_row; $$count_ref is incremented per data record (the
294 # header is skipped). A fresh supplier is built for each COPY attempt so the
295 # one retry path (a rare deferral failure) re-reads the source. Encode is
296 # concatenative, so encoding whole blocks is equivalent to encoding each row.
297 # ============================================================
298 3 ▶sub _pg_csv_supplier {
Subroutine _pg_csv_supplier: called CC=3 SCAR=11.5
299 3 my ( $fi, $params, $cols, $blank_to_null, $col_size, $count_ref, $enc, $src_enc ) = @_;
300 3 my $sep = $params->{'sep_char'};
301 3 my $quo = $params->{'quote_char'};
302  
303 3 ▶ open( my $fh, '<', $fi ) or die "ERROR: Cannot open file \"$fi\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fi or die qq[ERROR: Cannot open file "$fi": $!\n] 3 0 3
304 3 my $csv = Text::CSV->new(
305 {
306 binary => 1,
307 sep_char => $sep,
308 quote_char => $quo
309 }
310 );
311 3 ▶ unless ( $csv->getline($fh) ) { # skip the header record
Branch: 1 branch
BranchTrueFalseTotal
unless ($csv->getline($fh)) 0 3 3
312 0 close($fh);
313 0 die "ERROR: cannot read header of \"$fi\"\n";
314 }
315  
316 3 my $closed = 0;
317 10 ▶ return sub {
Subroutine __ANON__: called CC=12 SCAR=26.7
318 10 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 3 7 10
319 7 my $eof = 0;
320 7 my $bytes = 0;
321 7 my @rows;
322  
323 # Collect whole rows and join() them once per block. Appending to a scalar
324 # and resetting it every block is quadratic and dominated the load ; join()
325 # allocates the whole block in a single pass.
326 7 ▶ while ( $bytes < PG_COPY_BLOCK_SIZE ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bytes < 1048576) 7006 4 7010
327 7006 my $data = $csv->getline($fh);
328 7006 ▶ if ( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 3 7003 7006
329 3 ▶ unless ( $csv->eof ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($csv->eof) 0 3 3
330 0 ▶ die "CSV parse error near line "
Condition0%0/2
$csv->error_diag // "unknown"
l!l
00
MC/DC0%0/1
$csv->error_diag // "unknown"
$csv->error_diag
Truth table0%0/2
A
A= $csv->error_diag
Aresult
11
00
331 . ( $$count_ref + 1 )
332 . " in \"$fi\": "
333 . ( $csv->error_diag // 'unknown' ) . "\n";
334 }
335 3 $eof = 1;
336 3 last;
337 }
338 7003 my $row = _pg_csv_row( $data, $cols, $sep, $quo, $blank_to_null, $col_size );
339 7003 push @rows, $row;
340 7003 $bytes += length($row) + 1; # +1 for the newline added by join()
341 7003 $$count_ref++;
342 }
343 7 ▶ if ($eof) { $closed = 1; close($fh); }
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 3 4 7
344 7 ▶ return unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 0 7 7
345 7 my $chunk = join( "\n", @rows ) . "\n";
346  
347 7 ▶ if ( defined $src_enc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $src_enc) { } 0 7 7
348  
349 # The bytes on disk are declared to be in $src_enc. Text::CSV may
350 # have upgraded a valid-UTF-8 field to a character string; re-encode
351 # it to recover the true file bytes before decoding them.
352 0 ▶ utf8::encode($chunk) if Encode::is_utf8($chunk);
Branch: 1 branch
BranchTrueFalseTotal
if &Encode::is_utf8($chunk) 0 0 0
353 0 ▶ $chunk = encode( $enc, decode( $src_enc, $chunk ) ) if defined $enc;
Branch: 1 branch
BranchTrueFalseTotal
if defined $enc 0 0 0
354 }
355 else {
356  
357 # No explicit source encoding: keep the historical behaviour, where
358 # Text::CSV's own detection (a valid-UTF-8 field is upgraded) plus
359 # the Latin-1 reading of raw bytes round-trips both file flavours.
360 7 ▶ $chunk = encode( $enc, $chunk ) if defined $enc;
Branch: 1 branch
BranchTrueFalseTotal
if defined $enc 2 5 7
361 }
362 7 return $chunk;
363 3 };
364 }
365  
366 # Map a PostgreSQL client_encoding name to an Encode name.
367 # Text::CSV (binary=>1) returns decoded characters, so values must be
368 # re-encoded to the session client_encoding before COPY reads the bytes.
369 8 ▶sub _pg_encoding_name {
Subroutine _pg_encoding_name: called CC=6 SCAR=18.0
370 8 my ($pg) = @_;
371 8 ▶ my $n = uc( $pg // '' );
Condition100%2/2
$pg // ""
l!l
71
MC/DC100%1/1
$pg // ""
$pg
Truth table100%2/2
A
A= $pg
Aresult
11
00
372 8 $n =~ s/[^A-Z0-9]//g;
373 8 my %map = (
374 UTF8 => 'UTF-8',
375 UNICODE => 'UTF-8',
376 LATIN1 => 'ISO-8859-1',
377 LATIN2 => 'ISO-8859-2',
378 LATIN3 => 'ISO-8859-3',
379 LATIN4 => 'ISO-8859-4',
380 LATIN5 => 'ISO-8859-9',
381 LATIN6 => 'ISO-8859-10',
382 LATIN7 => 'ISO-8859-13',
383 LATIN8 => 'ISO-8859-14',
384 LATIN9 => 'ISO-8859-15',
385 LATIN10 => 'ISO-8859-16',
386 );
387 8 ▶ return $map{$n} if exists $map{$n};
Branch: 1 branch
BranchTrueFalseTotal
if exists $map{$n} 3 5 8
388 5 ▶ return "CP$1" if $n =~ /^WIN(\d+)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $n =~ /^WIN(\d+)$/ 1 4 5
389 4 ▶ return $n if $n ne '' && defined find_encoding($n);
Branch: 1 branch
BranchTrueFalseTotal
if $n ne "" and defined &find_encoding($n) 0 4 4
Condition66%2/3
$n ne "" and defined &find_encoding($n)
!ll&&!rl&&r
220
MC/DC0%0/2
$n ne "" and defined &find_encoding($n)
$n ne "" defined &find_encoding($n)
Truth table66%2/3
A and B
A= $n ne ""B= defined &find_encoding($n)
ABresult
0X0
100
111
390 4 return 'UTF-8';
391 }
392  
393 # True when $pg names an encoding we recognize: a PostgreSQL alias
394 # (UTF8, UNICODE, LATIN1..LATIN10), a WIN<n> code page, or any name Encode
395 # knows. Used to reject a typo in EDTK_DB_COPY_ENCODING instead of silently
396 # reading it as UTF-8.
397 0 ▶sub _pg_encoding_known {
Subroutine _pg_encoding_known: not called CC=8 SCAR=42.8
398 0 my ($pg) = @_;
399 0 ▶ my $n = uc( $pg // '' );
Condition0%0/2
$pg // ""
l!l
00
MC/DC0%0/1
$pg // ""
$pg
Truth table0%0/2
A
A= $pg
Aresult
11
00
400 0 $n =~ s/[^A-Z0-9]//g;
401 0 ▶ return 0 if $n eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $n eq "" 0 0 0
402 0 ▶ return 1 if $n =~ /^(?:UTF8|UNICODE|LATIN(?:10|[1-9]))$/;
Branch: 1 branch
BranchTrueFalseTotal
if $n =~ /^(?:UTF8|UNICODE|LATIN(?:10|[1-9]))$/ 0 0 0
403 0 ▶ return 1 if $n =~ /^WIN\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $n =~ /^WIN\d+$/ 0 0 0
404 0 ▶ return 1 if defined find_encoding($n);
Branch: 1 branch
BranchTrueFalseTotal
if defined &find_encoding($n) 0 0 0
405 0 ▶ return 1 if defined find_encoding( $pg // '' );
Branch: 1 branch
BranchTrueFalseTotal
if defined &find_encoding(scalar($pg // "")) 0 0 0
Condition0%0/2
$pg // ""
l!l
00
MC/DC0%0/1
$pg // ""
$pg
Truth table0%0/2
A
A= $pg
Aresult
11
00
406 0 return 0;
407 }
408  
409 # Resolve the source encoding of the bytes fed to COPY (H8). The caller's
410 # pg_copy_encoding wins, then EDTK_DB_COPY_ENCODING, then LATIN1 (the
411 # historical assumption). EDTK_OUT_ENCODING is deliberately not consulted:
412 # it governs output files, not the COPY input, and honouring it here would
413 # silently re-read Latin-1 acquittal files as UTF-8. Returns
414 # ( $encode_name, $error ); $error is set (and $encode_name undef) on a
415 # name we do not recognize.
416 0 ▶sub _pg_source_encoding {
Subroutine _pg_source_encoding: not called CC=7 SCAR=40.3
417 0 my ( $params, $cfg ) = @_;
418 0 my $raw = $params->{'pg_copy_encoding'};
419 0 ▶ $raw = $cfg->{'EDTK_DB_COPY_ENCODING'} unless defined $raw && $raw ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and $raw ne "" 0 0 0
Condition0%0/3
defined $raw and $raw ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $raw and $raw ne ""
defined $raw $raw ne ""
Truth table0%0/3
A and B
A= defined $rawB= $raw ne ""
ABresult
0X0
100
111
420 0 ▶ $raw = 'LATIN1' unless defined $raw && $raw ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and $raw ne "" 0 0 0
Condition0%0/3
defined $raw and $raw ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $raw and $raw ne ""
defined $raw $raw ne ""
Truth table0%0/3
A and B
A= defined $rawB= $raw ne ""
ABresult
0X0
100
111
421 0 ▶ return ( undef, "unknown copy encoding '$raw'" ) unless _pg_encoding_known($raw);
Branch: 1 branch
BranchTrueFalseTotal
unless _pg_encoding_known($raw) 0 0 0
422 0 ▶ return ( ( defined find_encoding($raw) ? $raw : _pg_encoding_name($raw) ), undef );
Branch: 1 branch
BranchTrueFalseTotal
defined &find_encoding($raw) ? : 0 0 0
423 }
424  
425 # ============================================================
426 # PRIVATE : count the CSV data records (header excluded) so a bulk
427 # load can report how many rows it is about to inject. getline (not
428 # parse) is used so a quoted field may span several physical lines.
429 # Returns the number of data records, or -1 when the file is unreadable.
430 # ============================================================
431 0 ▶sub _count_csv_rows {
Subroutine _count_csv_rows: not called CC=5 SCAR=34.0
432 0 my ( $fi, $params ) = @_;
433 0 ▶ open( my $fh, '<', $fi ) or return -1;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fi or return -1 0 0 0
434 my $csv = Text::CSV->new(
435 {
436 binary => 1,
437 sep_char => $params->{'sep_char'} // ',',
438 0 ▶ quote_char => $params->{'quote_char'} // '"',
Condition0%0/4
$params->{"sep_char"} // ","
l!l
00
$params->{"quote_char"} // "\""
l!l
00
MC/DC0%0/1
$params->{"sep_char"} // ","
$params->{"sep_char"}
MC/DC0%0/1
$params->{"quote_char"} // "\""
$params->{"quote_char"}
Truth table0%0/2
A
A= $params->{"sep_char"}
Aresult
11
00
Truth table0%0/2
A
A= $params->{"quote_char"}
Aresult
11
00
439 }
440 );
441 0 $csv->getline($fh); # skip the header record
442 0 my $rows = 0;
443 0 while (1) {
444 0 my $data = $csv->getline($fh);
445 0 ▶ last if !defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
446 0 $rows++;
447 }
448 0 close($fh);
449 0 return $rows;
450 }
451  
452 # ============================================================
453 # PRIVATE : run a COPY ... FROM STDIN, feeding it from $next_block -- a
454 # coderef that returns the next chunk of serialized bytes (undef at end of
455 # stream) and dies on a producer error (e.g. a CSV parse error). Feeding whole
456 # blocks instead of one line per call keeps the per-record overhead out of the
457 # COPY loop. The COPY is aborted best-effort on failure.
458 # Returns the error message, or undef on success.
459 # ============================================================
460 0 ▶sub _pg_copy_stdin {
Subroutine _pg_copy_stdin: not called CC=9 SCAR=45.0
461 0 my ( $dbh, $sql, $next_block ) = @_;
462 0 my $emsg;
463 0 my $copy_live = 0;
464 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do($sql); $copy_live = 1; while (defined(my $chunk = &$next_block())) { do { defined $dbh->pg_putcopydata($chunk) or die $dbh->errstr || "pg_putcopydata failed" }; } ; $copy_live = 0; $dbh->pg_putcopyend; 1 } } or $emsg = $@ 0 0 0
465 0 local $dbh->{PrintError} = 0;
466 0 $dbh->do($sql);
467 0 $copy_live = 1;
468 0 ▶ while ( defined( my $chunk = $next_block->() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $chunk = &$next_block())) 0 0 0
469 0 ▶ defined $dbh->pg_putcopydata($chunk)
Branch: 1 branch
BranchTrueFalseTotal
defined $dbh->pg_putcopydata($chunk) or die $dbh->errstr || "pg_putcopydata failed" 0 0 0
Condition0%0/2
$dbh->errstr || 'pg_putcopydata failed'
l!l
00
MC/DC0%0/1
$dbh->errstr || 'pg_putcopydata failed'
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
470 or die( $dbh->errstr || "pg_putcopydata failed" );
471 }
472 0 $copy_live = 0; # pg_putcopyend always ends the COPY
473 0 $dbh->pg_putcopyend();
474 0 1;
475 } or $emsg = $@;
476 0 ▶ $emsg ||= ( $dbh->err ? $dbh->errstr : '' );
Branch: 1 branch
BranchTrueFalseTotal
$dbh->err ? : 0 0 0
Condition0%0/3
$emsg ||= $dbh->err ? $dbh->errstr : ""
l!l&&r!l&&!r
000
MC/DC0%0/2
$emsg ||= $dbh->err ? $dbh->errstr : ""
$emsg $dbh->err ? $dbh->errstr : ""
Truth table0%0/3
A ||= B
A= $emsgB= $dbh->err ? $dbh->errstr : ""
ABresult
1X1
011
000
477 0 ▶ if ($emsg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($emsg) 0 0 0
478 0 ▶ eval { $dbh->pg_putcopyend() } if $copy_live; # abort a live COPY
Branch: 1 branch
BranchTrueFalseTotal
if $copy_live 0 0 0
479 0 return $emsg;
480 }
481 0 return;
482 }
483  
484 # ============================================================
485 # PRIVATE : quote a PostgreSQL identifier ("" doubling).
486 # ============================================================
487 0 ▶sub _pg_quote_ident {
Subroutine _pg_quote_ident: not called CC=1 SCAR=6.9
488 0 my ($name) = @_;
489 0 ( my $s = $name ) =~ s/"/""/g;
490 0 return '"' . $s . '"';
491 }
492  
493 # ============================================================
494 # PRIVATE : list the DDL a bulk COPY may drop up-front and rebuild
495 # afterwards, so every inserted row does not have to maintain it.
496 # Standalone secondary indexes and unique / foreign-key constraints are always
497 # returned ; the primary key is returned only when $defer_pk is true. Any index
498 # a foreign key depends on -- including a primary key referenced by an external
499 # foreign key -- is left untouched. Returns { drop => [sql...], create => [sql...] }.
500 # ============================================================
501 0 ▶sub _pg_deferrable_ddl {
Subroutine _pg_deferrable_ddl: not called CC=5 SCAR=34.0
502 0 my ( $dbh, $table, $defer_pk ) = @_;
503 0 my ($oid) = $dbh->selectrow_array( "SELECT to_regclass(?)::oid", undef, $table );
504 0 ▶ return { drop => [], create => [] } unless $oid;
Branch: 1 branch
BranchTrueFalseTotal
unless $oid 0 0 0
505  
506 0 my ( @drop, @create );
507  
508 # Secondary indexes that back no constraint and are referenced by no FK.
509 0 my $idx = $dbh->selectall_arrayref(
510 "SELECT n.nspname, c.relname, pg_get_indexdef(i.indexrelid)"
511 . " FROM pg_index i"
512 . " JOIN pg_class c ON c.oid = i.indexrelid"
513 . " JOIN pg_namespace n ON n.oid = c.relnamespace"
514 . " WHERE i.indrelid = ? AND NOT i.indisprimary"
515 . " AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conindid = i.indexrelid)",
516 undef, $oid
517 );
518 0 foreach my $r (@$idx) {
519 0 my ( $nsp, $name, $def ) = @$r;
520 0 push @drop, "DROP INDEX " . _pg_quote_ident($nsp) . "." . _pg_quote_ident($name);
521 0 push @create, $def;
522 }
523  
524 # Unique and foreign-key constraints on this table -- plus the primary key
525 # when $defer_pk is set -- except any whose index a foreign key depends on.
526 0 ▶ my $cons = $dbh->selectall_arrayref(
Branch: 1 branch
BranchTrueFalseTotal
$defer_pk ? : 0 0 0
527 "SELECT c.conname, pg_get_constraintdef(c.oid) FROM pg_constraint c"
528 . " WHERE c.conrelid = ? AND c.contype IN ('u','f'"
529 . ( $defer_pk ? ",'p'" : "" ) . ")"
530 . " AND NOT (c.contype IN ('u','p') AND EXISTS (SELECT 1 FROM pg_constraint k"
531 . " WHERE k.conindid = c.conindid"
532 . " AND k.contype = 'f'))",
533 undef, $oid
534 );
535 0 foreach my $r (@$cons) {
536 0 my ( $cname, $cdef ) = @$r;
537 0 my $cid = _pg_quote_ident($cname);
538 0 push @drop, "ALTER TABLE $table DROP CONSTRAINT $cid";
539 0 push @create, "ALTER TABLE $table ADD CONSTRAINT $cid $cdef";
540 }
541  
542 0 return { drop => \@drop, create => \@create };
543 }
544  
545 # ============================================================
546 # PRIVATE : estimate the number of data rows a file will insert, from its byte
547 # size and a bounded header sample (the mean record size), without parsing the
548 # whole file. Returns 0 when the file cannot be sampled.
549 # ============================================================
550 0 ▶sub _pg_estimate_rows {
Subroutine _pg_estimate_rows: not called CC=8 SCAR=42.8
551 0 my ($fi) = @_;
552 0 my $size = -s $fi;
553 0 ▶ return 0 unless defined $size && $size > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size and $size > 0 0 0 0
Condition0%0/3
defined $size and $size > 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $size and $size > 0
defined $size $size > 0
Truth table0%0/3
A and B
A= defined $sizeB= $size > 0
ABresult
0X0
100
111
554 0 ▶ open( my $fh, '<', $fi ) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fi or return 0 0 0 0
555 0 binmode($fh);
556 0 my $got = read( $fh, my $buf, PG_DEFER_SAMPLE_BYTES );
557 0 close($fh);
558 0 ▶ return 0 unless $got;
Branch: 1 branch
BranchTrueFalseTotal
unless $got 0 0 0
559 0 my $cut = rindex( $buf, "\n" ); # ignore the truncated last line
560 0 ▶ return 0 if $cut < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cut < 0 0 0 0
561 0 my $sample = substr( $buf, 0, $cut + 1 );
562 0 my $lines = () = $sample =~ /\n/g;
563 0 ▶ return 0 unless $lines;
Branch: 1 branch
BranchTrueFalseTotal
unless $lines 0 0 0
564 0 my $mean = length($sample) / $lines;
565 0 ▶ return 0 unless $mean > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $mean > 0 0 0 0
566 0 return int( $size / $mean );
567 }
568  
569 # ============================================================
570 # PRIVATE : live row estimate of a table from the planner's pg_class.reltuples.
571 # 0 when unknown (empty or never analyzed), which makes any non-trivial import
572 # count as "large relative to the table".
573 # ============================================================
574 0 ▶sub _pg_table_rows {
Subroutine _pg_table_rows: not called CC=3 SCAR=24.8
575 0 my ( $dbh, $table ) = @_;
576 0 my ($n) = eval {
577 0 $dbh->selectrow_array(
578 'SELECT GREATEST(reltuples, 0) FROM pg_class WHERE oid = to_regclass(?)',
579 undef, $table );
580 };
581 0 ▶ return 0 unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 0 0
582 0 ▶ return $n < 0 ? 0 : int($n);
Branch: 1 branch
BranchTrueFalseTotal
$n < 0 ? : 0 0 0
583 }
584  
585 # ============================================================
586 # PRIVATE : H4 / O4 -- is deferring the indexes worth it? The deferral is
587 # OPT-IN: it only happens when a threshold is declared (the caller params
588 # pg_defer_index_ratio / pg_defer_index_min_rows, or the ini keys
589 # EDTK_DB_DEFER_INDEX_RATIO / EDTK_DB_DEFER_INDEX_MIN_ROWS). With none declared
590 # it never defers. The measured benefit is in NOT deferring -- a small file on a
591 # large table loads ~35x faster and takes no exclusive lock -- so the deferral,
592 # which locks the whole table for the COPY, must be asked for explicitly.
593 # ============================================================
594 0 ▶sub _pg_should_defer {
Subroutine _pg_should_defer: not called CC=16 SCAR=56.1
595 0 my ( $params, $cfg, $incoming, $table_rows ) = @_;
596 0 my $ratio = $params->{'pg_defer_index_ratio'};
597 0 ▶ $ratio = $cfg->{'EDTK_DB_DEFER_INDEX_RATIO'} unless defined $ratio && $ratio ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ratio and $ratio ne "" 0 0 0
Condition0%0/3
defined $ratio and $ratio ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ratio and $ratio ne ""
defined $ratio $ratio ne ""
Truth table0%0/3
A and B
A= defined $ratioB= $ratio ne ""
ABresult
0X0
100
111
598 0 my $min = $params->{'pg_defer_index_min_rows'};
599 0 ▶ $min = $cfg->{'EDTK_DB_DEFER_INDEX_MIN_ROWS'} unless defined $min && $min ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min and $min ne "" 0 0 0
Condition0%0/3
defined $min and $min ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $min and $min ne ""
defined $min $min ne ""
Truth table0%0/3
A and B
A= defined $minB= $min ne ""
ABresult
0X0
100
111
600 0 ▶ return 0 unless ( defined $ratio && $ratio ne '' ) || ( defined $min && $min ne '' );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ratio and $ratio ne "" or defined $min and $min ne "" 0 0 0
Condition0%0/9
defined $ratio and $ratio ne "" or defined $min and $min ne ""
l!l&&r!l&&!r
000
defined $ratio and $ratio ne ""
!ll&&!rl&&r
000
defined $min and $min ne ""
!ll&&!rl&&r
000
MC/DC0%0/4
defined $ratio and $ratio ne "" or defined $min and $min ne ""
defined $ratio $ratio ne "" defined $min $min ne ""
Truth table0%0/7
A and B or C and D
A= defined $ratioB= $ratio ne ""C= defined $minD= $min ne ""
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
601 0 ▶ $ratio = PG_DEFER_DEFAULT_RATIO unless defined $ratio && $ratio ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ratio and $ratio ne "" 0 0 0
Condition0%0/3
defined $ratio and $ratio ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ratio and $ratio ne ""
defined $ratio $ratio ne ""
Truth table0%0/3
A and B
A= defined $ratioB= $ratio ne ""
ABresult
0X0
100
111
602 0 ▶ $min = PG_DEFER_DEFAULT_MIN_ROWS unless defined $min && $min ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min and $min ne "" 0 0 0
Condition0%0/3
defined $min and $min ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $min and $min ne ""
defined $min $min ne ""
Truth table0%0/3
A and B
A= defined $minB= $min ne ""
ABresult
0X0
100
111
603 0 ▶ return 0 unless $incoming >= $min;
Branch: 1 branch
BranchTrueFalseTotal
unless $incoming >= $min 0 0 0
604 0 ▶ return 1 if $table_rows <= 0; # empty or unknown table: nothing to weigh against
Branch: 1 branch
BranchTrueFalseTotal
if $table_rows <= 0 0 0 0
605 0 ▶ return $incoming >= $ratio * $table_rows ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$incoming >= $ratio * $table_rows ? : 0 0 0
606 }
607  
608 # ============================================================
609 # PRIVATE : load into $tablename inside one transaction from $make_supplier
610 # (called once per attempt to obtain a fresh COPY byte supplier), optionally
611 # after dropping the deferrable DDL and relaxing synchronous_commit for that
612 # transaction only (SET LOCAL). Rebuilds the DDL and commits ; a failure rolls
613 # the data AND the DDL back. When the caller manages the transaction (AutoCommit
614 # already off) the work runs under a SAVEPOINT so a failure can be undone without
615 # poisoning the caller's transaction (H14). %opt: lock_timeout => 'Ns' bounds the
616 # wait for the exclusive lock the DDL drop needs. Returns ('ok',''), ('defer',$err)
617 # when the DDL could not be dropped, or ('fail',$err) on any other error.
618 # ============================================================
619 0 ▶sub _pg_load_tx {
Subroutine _pg_load_tx: not called CC=19 SCAR=59.4
620 0 my ( $dbh, $tablename, $sql, $make_supplier, $ddl, %opt ) = @_;
621 0 ▶ my $own = $dbh->{AutoCommit} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->{'AutoCommit'} ? : 0 0 0
622 0 my $sp = 'edtk_pg_load'; # savepoint used when the caller owns the transaction
623 0 my $phase = 'begin';
624 0 my $ok = eval {
625 0 ▶ if ($own) { $dbh->begin_work }
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
626 0 else { $dbh->do("SAVEPOINT $sp") }
627  
628 # Bound the wait for the exclusive lock a deferral needs (O4): on timeout
629 # the DROP fails and the caller retries without deferring.
630 0 ▶ if ( $opt{lock_timeout} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"lock_timeout"}) 0 0 0
631 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do(qq[SET LOCAL lock_timeout = '$opt{"lock_timeout"}']); 1 } } or &logger(4, "_pg_load_tx: SET LOCAL lock_timeout failed: $@") 0 0 0
632 0 local $dbh->{PrintError} = 0;
633 0 $dbh->do("SET LOCAL lock_timeout = '$opt{lock_timeout}'");
634 0 1;
635 } or &logger( 4, "_pg_load_tx: SET LOCAL lock_timeout failed: $@" );
636 }
637 0 ▶ eval { local $dbh->{PrintError} = 0; $dbh->do(PG_COPY_SYNC_OFF); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do("SET LOCAL synchronous_commit = off"); 1 } } or &logger(4, "_pg_load_tx: SET LOCAL failed: $@") 0 0 0
638 or &logger( 4, "_pg_load_tx: SET LOCAL failed: $@" );
639 0 $phase = 'defer';
640 0 foreach my $s ( @{ $ddl->{drop} } ) {
641 0 ▶ $dbh->do($s) or die( $dbh->errstr || "drop failed: $s" );
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($s) or die $dbh->errstr || "drop failed: $s" 0 0 0
Condition0%0/2
$dbh->errstr || "drop failed: $s"
l!l
00
MC/DC0%0/1
$dbh->errstr || "drop failed: $s"
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
642 }
643 0 $phase = 'copy';
644 0 my $err = _pg_copy_stdin( $dbh, $sql, $make_supplier->() );
645 0 ▶ die $err if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 0 0 0
646 0 $phase = 'rebuild';
647 0 foreach my $s ( @{ $ddl->{create} } ) {
648 0 ▶ $dbh->do($s) or die( $dbh->errstr || "create failed: $s" );
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($s) or die $dbh->errstr || "create failed: $s" 0 0 0
Condition0%0/2
$dbh->errstr || "create failed: $s"
l!l
00
MC/DC0%0/1
$dbh->errstr || "create failed: $s"
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
649 }
650 0 ▶ if ($own) { $dbh->commit }
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
651 0 else { $dbh->do("RELEASE SAVEPOINT $sp") }
652 0 1;
653 };
654 0 ▶ return ( 'ok', '' ) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
655  
656 0 ▶ my $err = $@ // '';
Condition0%0/2
$@ // ""
l!l
00
MC/DC0%0/1
$@ // ""
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
657 0 ▶ if ($own) {
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
658 0 ▶ eval { $dbh->rollback } if !$dbh->{AutoCommit};
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->{"AutoCommit"} 0 0 0
659 }
660 else {
661 # H14: undo to the savepoint, leaving the caller's transaction usable.
662 0 eval {
663 0 local $dbh->{PrintError} = 0;
664 0 $dbh->do("ROLLBACK TO SAVEPOINT $sp");
665 0 $dbh->do("RELEASE SAVEPOINT $sp");
666 0 1;
667 };
668 }
669 0 $err =~ s/\s+\z//;
670 0 ▶ return ( $phase eq 'defer' ? 'defer' : 'fail', $err );
Branch: 1 branch
BranchTrueFalseTotal
$phase eq 'defer' ? : 0 0 0
671 }
672  
673 # ============================================================
674 # PRIVATE : D60 -- choose between the raw COPY path and the ELT staging path.
675 # The ELT path is used only on PostgreSQL, in insert mode (the caller dispatches
676 # it), when the file reaches the threshold EDTK_DB_BURST_MO megabytes. 0 disables
677 # it; an explicit caller param pg_copy_staging (0 or 1) overrides the threshold,
678 # which is what the tests use to exercise either path on a small fixture.
679 # force_copy (true) forces the COPY path ahead of every other setting.
680 # Returns ($use_elt, $reason).
681 # ============================================================
682 4 ▶sub _pg_burst_decision {
Subroutine _pg_burst_decision: called CC=13 SCAR=45.7
683 4 my ( $params, $cfg, $fi ) = @_;
684  
685 # Operator override: COPY even when ELT would be selected, ahead of
686 # pg_copy_staging / burst_mo / EDTK_DB_BURST_MO.
687 4 ▶ return ( 0, 'force_copy => 1' ) if $params->{'force_copy'};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"force_copy"} 2 2 4
688 2 ▶ if ( defined $params->{'pg_copy_staging'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"pg_copy_staging"}) 2 0 2
689 2 ▶ return $params->{'pg_copy_staging'}
Branch: 1 branch
BranchTrueFalseTotal
$params->{'pg_copy_staging'} ? : 1 1 2
690 ? ( 1, 'pg_copy_staging => 1' )
691 : ( 0, 'pg_copy_staging => 0' );
692 }
693 0 my $mo = $params->{'burst_mo'};
694 0 ▶ $mo = $cfg->{'EDTK_DB_BURST_MO'} unless defined $mo && $mo ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mo and $mo ne "" 0 0 0
Condition0%0/3
defined $mo and $mo ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $mo and $mo ne ""
defined $mo $mo ne ""
Truth table0%0/3
A and B
A= defined $moB= $mo ne ""
ABresult
0X0
100
111
695 0 ▶ if ( !defined $mo || $mo eq '' ) { $mo = PG_BURST_MO_DEFAULT; }
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $mo or $mo eq '') { } 0 0 0
elsif (not $mo =~ /^\s*[0-9]+(?:\.[0-9]+)?\s*$/) { } 0 0 0
Condition0%0/3
not defined $mo or $mo eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $mo or $mo eq ""
not defined $mo $mo eq ""
Truth table0%0/3
not(A) or B
A= not defined $moB= $mo eq ""
ABresult
1X1
011
000
696 elsif ( $mo !~ /^\s*[0-9]+(?:\.[0-9]+)?\s*$/ ) {
697 0 &logger( 3,
698 "_pg_burst_decision: invalid EDTK_DB_BURST_MO '$mo', using default "
699 . PG_BURST_MO_DEFAULT );
700 0 $mo = PG_BURST_MO_DEFAULT;
701 }
702 0 ▶ return ( 0, 'EDTK_DB_BURST_MO=0 (ELT disabled)' ) if $mo == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $mo == 0 0 0 0
703 0 my $size = -s $fi;
704 0 ▶ $size = 0 unless defined $size && $size > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size and $size > 0 0 0 0
Condition0%0/3
defined $size and $size > 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $size and $size > 0
defined $size $size > 0
Truth table0%0/3
A and B
A= defined $sizeB= $size > 0
ABresult
0X0
100
111
705 0 my $limit = $mo * PG_BURST_BYTES_PER_MO;
706 0 ▶ return ( 1, "file ${size}B >= ${mo}Mo threshold" ) if $size >= $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $size >= $limit 0 0 0
707 0 return ( 0, "file ${size}B < ${mo}Mo threshold" );
708 }
709  
710 # ============================================================
711 # PRIVATE : the DDL a bulk load may drop up-front and rebuild afterwards, honouring
712 # the opt-in deferral policy (H4 / O4). Shared by the COPY and ELT paths.
713 # Returns { drop => [sql...], create => [sql...] } (empty when nothing is deferred).
714 # ============================================================
715 0 ▶sub _pg_defer_plan {
Subroutine _pg_defer_plan: not called CC=7 SCAR=40.3
716 0 my ( $dbh, $tablename, $params, $cfg, $fi, $rows_before ) = @_;
717 0 ▶ return { drop => [], create => [] } unless $params->{'pg_copy_optimize'} // 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"pg_copy_optimize"} // 1 0 0 0
Condition0%0/2
$params->{"pg_copy_optimize"} // 1
l!l
00
MC/DC0%0/1
$params->{"pg_copy_optimize"} // 1
$params->{"pg_copy_optimize"}
Truth table0%0/2
A
A= $params->{"pg_copy_optimize"}
Aresult
11
00
718 0 my $incoming = _pg_estimate_rows($fi);
719 0 ▶ unless ( _pg_should_defer( $params, $cfg, $incoming, $rows_before ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_pg_should_defer($params, $cfg, $incoming, $rows_before)) 0 0 0
720 0 &logger( 5, "_pg_defer_plan: not deferring (~$incoming incoming, $rows_before rows)" );
721 0 return { drop => [], create => [] };
722 }
723 0 my $ddl = eval { _pg_deferrable_ddl( $dbh, $tablename, $params->{'pg_copy_defer_pk'} ) };
724 0 ▶ &logger( 4, "_pg_defer_plan: deferral lookup failed: $@" ) unless $ddl;
Branch: 1 branch
BranchTrueFalseTotal
unless $ddl 0 0 0
725 0 ▶ $ddl ||= { drop => [], create => [] };
Condition0%0/2
$ddl ||= {"drop", [], "create", []}
l!l
00
MC/DC0%0/1
$ddl ||= {"drop", [], "create", []}
$ddl
Truth table0%0/2
A
A= $ddl
Aresult
11
00
726 &logger( 5, "_pg_defer_plan: deferring indexes (~$incoming incoming vs $rows_before rows)" )
727 0 ▶ if @{ $ddl->{drop} };
Branch: 1 branch
BranchTrueFalseTotal
if @{$ddl->{"drop"};} 0 0 0
728 0 return $ddl;
729 }
730  
731 # ============================================================
732 # PRIVATE : per-column staging type. A character column (text / varchar / bpchar
733 # / char / name) is staged as text, so an empty field stays an empty string and a
734 # long value is not rejected by the COPY (the target truncation is applied by the
735 # transfer INSERT). Every other column keeps the target's declared type, so a bad
736 # numeric or date still fails with the COPY's line number. Returns undef when the
737 # catalogue cannot be read (the caller then falls back to the COPY path).
738 # ============================================================
739 0 ▶sub _pg_column_types {
Subroutine _pg_column_types: not called CC=5 SCAR=34.0
740 0 my ( $dbh, $table, $cols ) = @_;
741 0 my $rows = eval {
742 0 $dbh->selectall_arrayref(
743 "SELECT a.attname, t.typname, format_type(a.atttypid, a.atttypmod)"
744 . " FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid"
745 . " WHERE a.attrelid = to_regclass(?) AND a.attnum > 0 AND NOT a.attisdropped",
746 undef, $table
747 );
748 };
749 0 ▶ return undef unless $rows; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless $rows 0 0 0
750 0 my %seen = map { lc( $_->[0] ) => { typname => $_->[1], ftype => $_->[2] } } @$rows;
751 0 my %type;
752 0 for my $c (@$cols) {
753 0 ▶ my $t = $seen{ lc $c } or return undef; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
my $t = $seen{lc $c} or return undef 0 0 0
754 0 ▶ $type{$c} = $t->{typname} =~ /^(?:text|varchar|bpchar|char|name)$/ ? 'text' : $t->{ftype};
Branch: 1 branch
BranchTrueFalseTotal
$t->{'typname'} =~ /^(?:text|varchar|bpchar|char|name)$/ ? : 0 0 0
755 }
756 0 return \%type;
757 }
758  
759 # ============================================================
760 # PRIVATE : D60 SQL builders (no side effect, so they are easy to read and test).
761 # _pg_stg_name : a session-unique staging table name.
762 # _pg_stg_ddl : CREATE TEMP TABLE without LIKE, so the staging table
763 # carries no NOT NULL constraint and no default.
764 # _pg_stg_copy_sql : the raw COPY into the staging table (HEADER true,
765 # ENCODING, FORCE_NOT_NULL on the text columns).
766 # _pg_stg_insert_sql: the transfer INSERT ... SELECT with the same substr
767 # truncation as the row-by-row path.
768 # ============================================================
769 0 ▶sub _pg_stg_name {
Subroutine _pg_stg_name: not called CC=1 SCAR=6.9
770 0 return PG_STG_PREFIX . $$ . '_' . ++$_PG_STG_SEQ;
771 }
772  
773 0 ▶sub _pg_stg_ddl {
Subroutine _pg_stg_ddl: not called CC=1 SCAR=6.9
774 0 my ( $stg, $cols, $types ) = @_;
775 0 my $list = join( ', ', map { _pg_quote_ident($_) . ' ' . $types->{$_} } @$cols );
776 0 return 'CREATE TEMP TABLE ' . _pg_quote_ident($stg) . " ( $list ) ON COMMIT DROP";
777 }
778  
779 0 ▶sub _pg_stg_copy_sql {
Subroutine _pg_stg_copy_sql: not called CC=4 SCAR=30.0
780 0 my ( $stg, $cols, $types, $sep, $quo, $src_enc ) = @_;
781 0 my $opts = "FORMAT csv, HEADER true, DELIMITER '$sep', QUOTE '$quo'";
782 0 ▶ $opts .= ", ENCODING '$src_enc'" if defined $src_enc && $src_enc ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $src_enc and $src_enc ne "" 0 0 0
Condition0%0/3
defined $src_enc and $src_enc ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $src_enc and $src_enc ne ""
defined $src_enc $src_enc ne ""
Truth table0%0/3
A and B
A= defined $src_encB= $src_enc ne ""
ABresult
0X0
100
111
783 0 my @text = grep { $types->{$_} eq 'text' } @$cols;
784 0 ▶ $opts .= ', FORCE_NOT_NULL (' . join( ',', map { _pg_quote_ident($_) } @text ) . ')' if @text;
Branch: 1 branch
BranchTrueFalseTotal
if @text 0 0 0
785 return
786 'COPY '
787 . _pg_quote_ident($stg) . ' ('
788 0 . join( ',', map { _pg_quote_ident($_) } @$cols )
789 . ") FROM STDIN WITH ($opts)";
790 }
791  
792 0 ▶sub _pg_stg_insert_sql {
Subroutine _pg_stg_insert_sql: not called CC=4 SCAR=30.0
793 0 my ( $copy_table, $cols, $col_meta, $stg ) = @_;
794 0 my $ins = join( ', ', map { _pg_quote_ident($_) } @$cols );
795 my $sel = join(
796 ', ',
797 map {
798 0 ▶ my $size = ( $col_meta->{$_} // {} )->{size} // 0;
Condition0%0/4
+($col_meta->{$_} // {})->{"size"} // 0
l!l
00
$col_meta->{$_} // {}
l!l
00
MC/DC0%0/1
+($col_meta->{$_} // {})->{"size"} // 0
$col_meta->{$_}
Truth table0%0/2
A
A= $col_meta->{$_}
Aresult
11
00
799 0 ▶ $size > 0 ? 'substr(' . _pg_quote_ident($_) . ", 1, $size)" : _pg_quote_ident($_);
Branch: 1 branch
BranchTrueFalseTotal
$size > 0 ? : 0 0 0
800 } @$cols
801 );
802 0 return "INSERT INTO $copy_table ( $ins ) SELECT $sel FROM " . _pg_quote_ident($stg);
803 }
804  
805 # ============================================================
806 # PRIVATE : a byte supplier that streams the file in 1 MiB blocks, with no Perl
807 # CSV parse (the raw bytes go straight to COPY). Closes the handle at EOF.
808 # ============================================================
809 0 ▶sub _pg_raw_supplier {
Subroutine _pg_raw_supplier: not called CC=1 SCAR=6.9
810 0 my ($fi) = @_;
811 0 ▶ return sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
812 0 ▶ open my $fh, '<:raw', $fi or die "cannot open \"$fi\": $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $fi or die qq[cannot open "$fi": $!] 0 0 0
813 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
814 0 my $r = read( $fh, my $buf, PG_COPY_BLOCK_SIZE );
815 0 ▶ die "read \"$fi\": $!" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 0 0
816 0 ▶ if ( $r == 0 ) { close $fh; return undef; } ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
if ($r == 0) 0 0 0
817 0 return $buf;
818 0 };
819 0 };
820 }
821  
822 # ============================================================
823 # PRIVATE : D60 -- the ELT path. Loads $fi into an unconstrained TEMP staging
824 # table with one raw COPY (no per-row Perl parse), then moves the rows with a
825 # single INSERT ... SELECT that applies the same substr truncation as the
826 # row-by-row path. Everything runs in one transaction (SAVEPOINT when the caller
827 # already owns one), so a failure leaves no row and no staging table. A missing
828 # TEMPORARY right or an unreadable catalogue is reported as 'fallback' so the
829 # caller retries on the COPY path. Returns ( 'ok', $rows ), ( 'defer', $err ),
830 # ( 'fallback', $err ) or ( 'fail', $err ).
831 # ============================================================
832 0 ▶sub _pg_stage_and_insert {
Subroutine _pg_stage_and_insert: not called CC=27 SCAR=66.3
833 0 my (%a) = @_;
834 0 my $dbh = $a{dbh};
835 0 my $cols = $a{cols};
836 0 my $col_meta = $a{col_meta};
837 0 my $ddl = $a{ddl};
838 0 ▶ my $own = $dbh->{AutoCommit} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->{'AutoCommit'} ? : 0 0 0
839 0 my $sp = 'edtk_pg_elt';
840 0 my $phase = 'begin';
841 0 my $rows = 0;
842 0 my $t0 = time;
843 0 my $ok = eval {
844 0 ▶ if ($own) { $dbh->begin_work }
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
845 0 else { $dbh->do("SAVEPOINT $sp") }
846  
847 # Bound the wait for the exclusive lock a deferral needs (O4), and give the
848 # index rebuild a larger maintenance_work_mem (plan 3.2).
849 0 ▶ if ( $a{lock_timeout} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a{"lock_timeout"}) 0 0 0
850 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do(qq[SET LOCAL lock_timeout = '$a{"lock_timeout"}']); 1 } } or &logger(4, "_pg_stage_and_insert: SET LOCAL lock_timeout failed: $@") 0 0 0
851 0 local $dbh->{PrintError} = 0;
852 0 $dbh->do("SET LOCAL lock_timeout = '$a{lock_timeout}'");
853 0 1;
854 } or &logger( 4, "_pg_stage_and_insert: SET LOCAL lock_timeout failed: $@" );
855 }
856 0 ▶ eval { local $dbh->{PrintError} = 0; $dbh->do(PG_COPY_SYNC_OFF); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do("SET LOCAL synchronous_commit = off"); 1 } } or &logger(4, "_pg_stage_and_insert: SET LOCAL failed: $@") 0 0 0
857 or &logger( 4, "_pg_stage_and_insert: SET LOCAL failed: $@" );
858 0 ▶ if ( @{ $ddl->{drop} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ddl->{"drop"};}) 0 0 0
859 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do("SET LOCAL maintenance_work_mem = '256MB'"); 1 } } or &logger(4, "_pg_stage_and_insert: SET LOCAL maintenance_work_mem failed: $@") 0 0 0
860 0 local $dbh->{PrintError} = 0;
861 0 $dbh->do( "SET LOCAL maintenance_work_mem = '" . PG_BURST_MAINT_MEM . "'" );
862 0 1;
863 }
864 or &logger( 4, "_pg_stage_and_insert: SET LOCAL maintenance_work_mem failed: $@" );
865 }
866  
867 0 $phase = 'defer';
868 0 foreach my $s ( @{ $ddl->{drop} } ) {
869 0 ▶ $dbh->do($s) or die( $dbh->errstr || "drop failed: $s" );
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($s) or die $dbh->errstr || "drop failed: $s" 0 0 0
Condition0%0/2
$dbh->errstr || "drop failed: $s"
l!l
00
MC/DC0%0/1
$dbh->errstr || "drop failed: $s"
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
870 }
871  
872 0 $phase = 'stage';
873 0 my $types = _pg_column_types( $dbh, $a{tablename}, $cols );
874 0 ▶ die "ELT_FALLBACK: column types unavailable\n" unless $types;
Branch: 1 branch
BranchTrueFalseTotal
unless $types 0 0 0
875 0 my $stg = _pg_stg_name();
876 my $cre =
877 0 eval { local $dbh->{PrintError} = 0; $dbh->do( _pg_stg_ddl( $stg, $cols, $types ) ); 1 };
878 0 ▶ die 'ELT_FALLBACK: CREATE TEMP TABLE refused: ' . ( $@ || $dbh->errstr ) . "\n" unless $cre;
Branch: 1 branch
BranchTrueFalseTotal
unless $cre 0 0 0
Condition0%0/3
$@ || $dbh->errstr
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $dbh->errstr
$@ $dbh->errstr
Truth table0%0/3
A || B
A= $@B= $dbh->errstr
ABresult
1X1
011
000
879 my $err = _pg_copy_stdin(
880 $dbh,
881 _pg_stg_copy_sql( $stg, $cols, $types, $a{sep}, $a{quo}, $a{src_enc} ),
882 0 _pg_raw_supplier( $a{fi} )->()
883 );
884 0 ▶ die $err if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 0 0 0
885 0 my $t_stage = time;
886  
887 0 $phase = 'insert';
888 0 $rows = $dbh->do( _pg_stg_insert_sql( $a{copy_table}, $cols, $col_meta, $stg ) );
889 0 ▶ defined $rows or die( $dbh->errstr || "insert failed" );
Branch: 1 branch
BranchTrueFalseTotal
defined $rows or die $dbh->errstr || "insert failed" 0 0 0
Condition0%0/2
$dbh->errstr || 'insert failed'
l!l
00
MC/DC0%0/1
$dbh->errstr || 'insert failed'
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
890 0 my $t_ins = time;
891  
892 0 $phase = 'rebuild';
893 0 foreach my $s ( @{ $ddl->{create} } ) {
894 0 ▶ $dbh->do($s) or die( $dbh->errstr || "create failed: $s" );
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($s) or die $dbh->errstr || "create failed: $s" 0 0 0
Condition0%0/2
$dbh->errstr || "create failed: $s"
l!l
00
MC/DC0%0/1
$dbh->errstr || "create failed: $s"
$dbh->errstr
Truth table0%0/2
A
A= $dbh->errstr
Aresult
11
00
895 }
896 0 ▶ if ($own) { $dbh->commit }
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
897 0 else { $dbh->do("RELEASE SAVEPOINT $sp") }
898 0 &logger(
899 4,
900 sprintf(
901 '_pg_stage_and_insert: stage %.3fs insert %.3fs rebuild %.3fs',
902 $t_stage - $t0,
903 $t_ins - $t_stage,
904 time - $t_ins
905 )
906 );
907 0 1;
908 };
909 0 ▶ return ( 'ok', $rows ) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
910  
911 0 ▶ my $err = $@ // '';
Condition0%0/2
$@ // ""
l!l
00
MC/DC0%0/1
$@ // ""
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
912 0 ▶ if ($own) {
Branch: 1 branch
BranchTrueFalseTotal
if ($own) { } 0 0 0
913 0 ▶ eval { $dbh->rollback } if !$dbh->{AutoCommit};
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->{"AutoCommit"} 0 0 0
914 }
915 else {
916  
917 # H14: undo to the savepoint, leaving the caller's transaction usable.
918 0 eval {
919 0 local $dbh->{PrintError} = 0;
920 0 $dbh->do("ROLLBACK TO SAVEPOINT $sp");
921 0 $dbh->do("RELEASE SAVEPOINT $sp");
922 0 1;
923 };
924 }
925 0 $err =~ s/\s+\z//;
926 0 ▶ return ( 'fallback', $err ) if $err =~ /^ELT_FALLBACK:/;
Branch: 1 branch
BranchTrueFalseTotal
if $err =~ /^ELT_FALLBACK:/ 0 0 0
927 0 ▶ return ( $phase eq 'defer' ? 'defer' : 'fail', $err );
Branch: 1 branch
BranchTrueFalseTotal
$phase eq 'defer' ? : 0 0 0
928 }
929  
930 # ============================================================
931 # PRIVATE : D60 -- drive the ELT path: deferral plan, the staging load, the
932 # retry without deferral on lock_timeout, and the conditional ANALYZE (O5).
933 # Returns ( 'ok', $rows ), ( 'fallback', $err ) or ( 'fail', $err ).
934 # ============================================================
935 0 ▶sub _pg_elt_load {
Subroutine _pg_elt_load: not called CC=9 SCAR=45.0
936 my (
937 0 $dbh, $tablename, $fi, $params, $cols, $col_meta,
938 $sep, $quo, $enc, $src_enc, $copy_table, $cfg
939 ) = @_;
940 0 my $rows_before = _pg_table_rows( $dbh, $tablename );
941 0 my $defer_ddl = _pg_defer_plan( $dbh, $tablename, $params, $cfg, $fi, $rows_before );
942 0 ▶ my %lt = ( @{ $defer_ddl->{drop} } ? ( lock_timeout => PG_COPY_LOCK_TIMEOUT ) : () );
Branch: 1 branch
BranchTrueFalseTotal
@{$defer_ddl->{'drop'};} ? : 0 0 0
943  
944 # The ELT COPY declares the file encoding and lets the server convert, with no
945 # per-field Perl re-encode. That is equivalent to the COPY path only when the
946 # source encoding is EXPLICITLY declared (pg_copy_encoding / EDTK_DB_COPY_ENCODING):
947 # the COPY path's default is a per-field heuristic (raw bytes read as Latin-1,
948 # but a field that is valid UTF-8 kept as-is) that no single server-side ENCODING
949 # reproduces -- declaring LATIN1 by default double-encoded a UTF-8 file (TD20).
950 # An undeclared encoding therefore falls back to the COPY path.
951 0 ▶ return ( 'fallback', 'ELT needs an explicit source encoding' )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $src_enc and $src_enc ne "" 0 0 0
Condition0%0/3
defined $src_enc and $src_enc ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $src_enc and $src_enc ne ""
defined $src_enc $src_enc ne ""
Truth table0%0/3
A and B
A= defined $src_encB= $src_enc ne ""
ABresult
0X0
100
111
952 unless defined $src_enc && $src_enc ne '';
953 0 my $decl = $src_enc;
954  
955 0 my %common = (
956 dbh => $dbh,
957 tablename => $tablename,
958 copy_table => $copy_table,
959 fi => $fi,
960 cols => $cols,
961 col_meta => $col_meta,
962 sep => $sep,
963 quo => $quo,
964 src_enc => $decl,
965 );
966 0 my ( $status, $res ) = _pg_stage_and_insert( %common, ddl => $defer_ddl, %lt );
967 0 ▶ if ( $status eq 'defer' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status eq "defer") 0 0 0
968 0 &logger( 4, "_pg_elt_load: deferral unavailable ($res), retrying without it" );
969 0 ( $status, $res ) =
970 _pg_stage_and_insert( %common, ddl => { drop => [], create => [] } );
971 }
972 0 ▶ return ( $status, $res ) unless $status eq 'ok';
Branch: 1 branch
BranchTrueFalseTotal
unless $status eq "ok" 0 0 0
973  
974 # Refresh the planner statistics only when the load is significant (O5).
975 0 ▶ if ( $rows_before <= 0 || $res >= PG_ANALYZE_TABLE_SHARE * $rows_before ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rows_before <= 0 or $res >= 0.1 * $rows_before) { } 0 0 0
Condition0%0/3
$rows_before <= 0 or $res >= "0.1" * $rows_before
l!l&&r!l&&!r
000
MC/DC0%0/2
$rows_before <= 0 or $res >= "0.1" * $rows_before
$rows_before <= 0 $res >= "0.1" * $rows_before
Truth table0%0/3
A or B
A= $rows_before <= 0B= $res >= "0.1" * $rows_before
ABresult
1X1
011
000
976 0 ▶ eval { local $dbh->{PrintError} = 0; $dbh->do( sprintf( PG_COPY_ANALYZE, $tablename ) ); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do(sprintf('ANALYZE %s', $tablename)); 1 } } or &logger(4, "_pg_elt_load: ANALYZE $tablename failed: $@") 0 0 0
977 or &logger( 4, "_pg_elt_load: ANALYZE $tablename failed: $@" );
978 }
979 else {
980 0 &logger( 5, "_pg_elt_load: ANALYZE $tablename skipped ($res rows added to $rows_before)" );
981 }
982 0 return ( 'ok', $res );
983 }
984  
985 # ============================================================
986 # PRIVATE : bulk load a CSV file into a PostgreSQL table with
987 # COPY ... FROM STDIN (native equivalent of LOAD DATA LOCAL INFILE).
988 # Rows are cleaned through the same _get_col_meta / _make_clean_val contract
989 # (truncation, '' => NULL for numeric/date) and streamed straight into COPY, so
990 # no temporary file is written. $norm_id comes from _norm_identifiers
991 # (PostgreSQL identifiers are lowercase).
992 # Returns ($count, " lines inserted") on success, (-1, "...") on failure.
993 # ============================================================
994 0 ▶sub _load_csv_pg_copy {
Subroutine _load_csv_pg_copy: not called CC=28 SCAR=67.0
995 0 my ( $dbh, $tablename, $fi, $params, $norm_id ) = @_;
996  
997 0 my $sep = $params->{'sep_char'};
998 0 my $quo = $params->{'quote_char'};
999  
1000 # COPY reads the bytes in the session client_encoding; encode rows to
1001 # match what the row-by-row DBI path would send.
1002 0 my $enc = _pg_encoding_name( eval { $dbh->selectrow_array('SHOW client_encoding') } );
1003 0 ▶ &logger( 7, "_load_csv_pg_copy: client_encoding=" . ( $enc // 'raw' ) );
Condition0%0/2
$enc // "raw"
l!l
00
MC/DC0%0/1
$enc // "raw"
$enc
Truth table0%0/2
A
A= $enc
Aresult
11
00
1004  
1005 # H8 : source encoding of the file bytes. Only an explicit declaration
1006 # (the caller param or EDTK_DB_COPY_ENCODING) overrides the historical
1007 # default; otherwise $src_enc stays undef and the supplier keeps the
1008 # previous behaviour byte-for-byte.
1009 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
1010 0 my ( $src_enc, $src_err ) = _pg_source_encoding( $params, $cfg );
1011 0 ▶ return ( -1, &logger( 3, "_load_csv_pg_copy: $src_err" ) ) if $src_err;
Branch: 1 branch
BranchTrueFalseTotal
if $src_err 0 0 0
1012 0 my $decl = $params->{'pg_copy_encoding'};
1013 0 ▶ $decl = $cfg->{'EDTK_DB_COPY_ENCODING'} unless defined $decl && $decl ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decl and $decl ne "" 0 0 0
Condition0%0/3
defined $decl and $decl ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $decl and $decl ne ""
defined $decl $decl ne ""
Truth table0%0/3
A and B
A= defined $declB= $decl ne ""
ABresult
0X0
100
111
1014 0 ▶ $src_enc = undef unless defined $decl && $decl ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decl and $decl ne "" 0 0 0
Condition0%0/3
defined $decl and $decl ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $decl and $decl ne ""
defined $decl $decl ne ""
Truth table0%0/3
A and B
A= defined $declB= $decl ne ""
ABresult
0X0
100
111
1015  
1016 # Read the header record for column names and insertion order.
1017 # getline (not parse) so a quoted field may span several physical lines.
1018 0 ▶ open( my $fh, '<', $fi )
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fi or return -1, &logger(3, qq[_load_csv_pg_copy: cannot open "$fi": $!]) 0 0 0
1019 or return ( -1, &logger( 3, "_load_csv_pg_copy: cannot open \"$fi\": $!" ) );
1020 0 my $csv = Text::CSV->new(
1021 {
1022 binary => 1,
1023 sep_char => $sep,
1024 quote_char => $quo
1025 }
1026 );
1027 0 my $hdr = $csv->getline($fh);
1028 0 ▶ unless ($hdr) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hdr) 0 0 0
1029 0 close($fh);
1030 0 return ( -1, &logger( 3, "_load_csv_pg_copy: cannot read header of \"$fi\"" ) );
1031 }
1032 0 close($fh);
1033 0 my @cols = map { $norm_id->($_) } @$hdr;
1034  
1035 # Same column metadata as the row-by-row path, flattened into positional
1036 # arrays so the per-row loop does no hash lookup.
1037 0 my $col_meta = _get_col_meta( $dbh, $tablename, $norm_id );
1038  
1039 # H9 : refuse a header column that is not in the table before building SQL,
1040 # so a third-party header cannot inject an identifier.
1041 0 ▶ my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
Branch: 1 branch
BranchTrueFalseTotal
keys %$col_meta ? : 0 0 0
1042 0 ▶ if (@$unknown) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$unknown) 0 0 0
1043 return (
1044 0 -1,
1045 &logger(
1046 3,
1047 "_load_csv_pg_copy: unknown column(s) "
1048 . join( ', ', @$unknown )
1049 . " for table $tablename"
1050 )
1051 );
1052 }
1053 0 ▶ my @blank_to_null = map { ( $col_meta->{$_} // {} )->{blank_to_null} ? 1 : 0 } @cols;
Branch: 1 branch
BranchTrueFalseTotal
+($col_meta->{$_} // {})->{'blank_to_null'} ? : 0 0 0
Condition0%0/2
$col_meta->{$_} // {}
l!l
00
MC/DC0%0/1
$col_meta->{$_} // {}
$col_meta->{$_}
Truth table0%0/2
A
A= $col_meta->{$_}
Aresult
11
00
1054 0 ▶ my @col_size = map { ( $col_meta->{$_} // {} )->{size} // 0 } @cols;
Condition0%0/4
+($col_meta->{$_} // {})->{"size"} // 0
l!l
00
$col_meta->{$_} // {}
l!l
00
MC/DC0%0/1
+($col_meta->{$_} // {})->{"size"} // 0
$col_meta->{$_}
Truth table0%0/2
A
A= $col_meta->{$_}
Aresult
11
00
1055  
1056 # COPY ... FROM STDIN : NULL '' makes an unquoted empty field a NULL.
1057 0 my $copy_table = join( '.', map { _pg_quote_ident($_) } split( /\./, $tablename, 2 ) );
1058  
1059 # D60 : above the threshold (EDTK_DB_BURST_MO, default 50 MiB) the file
1060 # is loaded through the ELT staging path. A 'fallback' (no TEMPORARY right, an
1061 # unreadable catalogue) silently retries below on the COPY path.
1062 0 my ( $use_elt, $why ) = _pg_burst_decision( $params, $cfg, $fi );
1063 0 ▶ &logger( 5, "_load_csv_pg_copy: path " . ( $use_elt ? 'ELT' : 'COPY' ) . " ($why)" );
Branch: 1 branch
BranchTrueFalseTotal
$use_elt ? : 0 0 0
1064 0 ▶ if ($use_elt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_elt) 0 0 0
1065 0 my ( $status, $res ) = _pg_elt_load(
1066 $dbh, $tablename, $fi, $params, \@cols, $col_meta,
1067 $sep, $quo, $enc, $src_enc, $copy_table, $cfg
1068 );
1069 0 ▶ &logger( 5, "bulk insert into $tablename via ELT staging: $res rows" ) if $status eq 'ok';
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "ok" 0 0 0
1070 0 ▶ return ( $res, " lines inserted" ) if $status eq 'ok';
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "ok" 0 0 0
1071 0 ▶ return ( -1, &logger( 3, "_load_csv_pg_copy: ELT into $tablename failed: $res" ) )
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "fail" 0 0 0
1072 if $status eq 'fail';
1073 0 &logger( 3, "_load_csv_pg_copy: ELT unavailable ($res), using COPY" );
1074 }
1075  
1076 my $sql =
1077 "COPY $copy_table ("
1078 0 . join( ',', map { _pg_quote_ident($_) } @cols ) . ")"
1079 . " FROM STDIN WITH (FORMAT csv, DELIMITER '"
1080 . $sep . "',"
1081 . " QUOTE '"
1082 . $quo
1083 . "', NULL '')";
1084 0 &logger( 7, $sql );
1085  
1086 # $make_supplier returns a fresh byte supplier for each COPY attempt so the
1087 # single retry path re-reads the source ; $count is reset on every attempt.
1088 0 my $count = 0;
1089 0 ▶ my $make_supplier = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1090 0 $count = 0;
1091 0 _pg_csv_supplier( $fi, $params, \@cols, \@blank_to_null, \@col_size, \$count, $enc,
1092 $src_enc );
1093 0 };
1094  
1095 # Default path (pg_copy_optimize unset or true) : load inside one transaction,
1096 # dropping the target table's secondary indexes and unique / foreign-key
1097 # constraints (plus the primary key when pg_copy_defer_pk is set) -- but ONLY
1098 # when the deferral is enabled AND the incoming volume justifies the exclusive
1099 # lock (H4 / O4; the deferral is opt-in, see _pg_should_defer). Otherwise the
1100 # indexes are left in place and the load stays non-blocking. Either way the
1101 # COPY runs inside one transaction (H7), with synchronous_commit relaxed for
1102 # that transaction only, and the planner statistics are refreshed when the
1103 # volume warrants it (O5). pg_copy_optimize => 0 never defers.
1104 0 my $rows_before = _pg_table_rows( $dbh, $tablename );
1105 0 my $defer_ddl = _pg_defer_plan( $dbh, $tablename, $params, $cfg, $fi, $rows_before );
1106  
1107 # lock_timeout only matters when there is DDL to drop (the exclusive lock).
1108 0 ▶ my %lt = ( @{ $defer_ddl->{drop} } ? ( lock_timeout => PG_COPY_LOCK_TIMEOUT ) : () );
Branch: 1 branch
BranchTrueFalseTotal
@{$defer_ddl->{'drop'};} ? : 0 0 0
1109 0 my ( $status, $emsg ) = _pg_load_tx( $dbh, $tablename, $sql, $make_supplier, $defer_ddl, %lt );
1110 0 ▶ if ( $status eq 'defer' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status eq "defer") 0 0 0
1111 0 &logger( 4, "_load_csv_pg_copy: deferral unavailable ($emsg), retrying without it" );
1112 0 ( $status, $emsg ) =
1113 _pg_load_tx( $dbh, $tablename, $sql, $make_supplier, { drop => [], create => [] } );
1114 }
1115  
1116 0 ▶ if ( $status ne 'ok' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status ne "ok") 0 0 0
1117 0 ▶ chomp( $emsg //= '' );
Condition0%0/2
$emsg //= ""
l!l
00
MC/DC0%0/1
$emsg //= ""
$emsg
Truth table0%0/2
A
A= $emsg
Aresult
11
00
1118 0 return ( -1, &logger( 3, "_load_csv_pg_copy: COPY into $tablename failed: $emsg" ) );
1119 }
1120  
1121 # Refresh the planner statistics only when the load is significant for the
1122 # table (O5): a small append to a large table does not move the estimate.
1123 0 ▶ if ( $rows_before <= 0 || $count >= PG_ANALYZE_TABLE_SHARE * $rows_before ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rows_before <= 0 or $count >= 0.1 * $rows_before) { } 0 0 0
Condition0%0/3
$rows_before <= 0 or $count >= "0.1" * $rows_before
l!l&&r!l&&!r
000
MC/DC0%0/2
$rows_before <= 0 or $count >= "0.1" * $rows_before
$rows_before <= 0 $count >= "0.1" * $rows_before
Truth table0%0/3
A or B
A= $rows_before <= 0B= $count >= "0.1" * $rows_before
ABresult
1X1
011
000
1124 0 ▶ eval { local $dbh->{PrintError} = 0; $dbh->do( sprintf( PG_COPY_ANALYZE, $tablename ) ); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $dbh->{"PrintError"} = 0; $dbh->do(sprintf('ANALYZE %s', $tablename)); 1 } } or &logger(4, "_load_csv_pg_copy: ANALYZE $tablename failed: $@") 0 0 0
1125 or &logger( 4, "_load_csv_pg_copy: ANALYZE $tablename failed: $@" );
1126 }
1127 else {
1128 0 &logger( 5,
1129 "_load_csv_pg_copy: ANALYZE $tablename skipped ($count rows added to $rows_before)" );
1130 }
1131  
1132 0 &logger( 5, "bulk insert into $tablename via COPY ... FROM STDIN: $count rows" );
1133 0 return ( $count, " lines inserted" );
1134 }
1135  
1136 # ============================================================
1137 # PRIVATE : header columns that are not in the target table. The caller has
1138 # normalized the columns and holds the table metadata; a column absent from
1139 # the metadata is refused before any SQL is built, so a third-party header
1140 # cannot inject an identifier. Empty list => every column is known.
1141 # ============================================================
1142 1 ▶sub _unknown_csv_columns {
Subroutine _unknown_csv_columns: called CC=1 SCAR=0.0
1143 1 my ( $cols, $col_meta ) = @_;
1144 1 return [ grep { !exists $col_meta->{$_} } @$cols ];
1145 }
1146  
1147 # ============================================================
1148 # PRIVATE: normalize SQL identifiers
1149 # according to the driver case (uc for MySQL/MariaDB, lc otherwise)
1150 # ============================================================
1151 8 ▶sub _norm_identifiers {
Subroutine _norm_identifiers: called CC=5 SCAR=16.1
1152 8 my ( $dbh, $table, $cols_ref ) = @_;
1153  
1154 8 ▶ my $driver = lc( $dbh->{Driver}{Name} // '' );
Condition50%1/2
$dbh->{"Driver"}{"Name"} // ""
l!l
80
MC/DC0%0/1
$dbh->{"Driver"}{"Name"} // ""
$dbh->{"Driver"}{"Name"}
Truth table50%1/2
A
A= $dbh->{"Driver"}{"Name"}
Aresult
11
00
1155 8 ▶ my $is_mysql = ( $driver =~ /mysql|mariadb/ ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$driver =~ /mysql|mariadb/ ? : 1 7 8
1156 my $norm_id =
1157 $is_mysql
1158 4 ▶ ? sub { my $s = $_[0]; $s =~ s/^\s+|\s+$//g; return uc($s) }
Subroutine __ANON__: called CC=1 SCAR=0.0
1159 8 ▶ : sub { my $s = $_[0]; $s =~ s/^\s+|\s+$//g; return lc($s) };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$is_mysql ? : 1 7 8
1160  
1161 # Normalize the table name, keeping the schema when present
1162 8 my $norm_table = join( '.', map { $norm_id->($_) } split( /\./, $table, 2 ) );
1163  
1164 # Normalize the columns (optional)
1165 8 ▶ my @norm_cols = map { $norm_id->($_) } @{ $cols_ref // [] };
Condition100%2/2
$cols_ref // []
l!l
71
MC/DC100%1/1
$cols_ref // []
$cols_ref
Truth table100%2/2
A
A= $cols_ref
Aresult
11
00
1166  
1167 8 return ( $norm_id, $norm_table, @norm_cols );
1168 }
1169  
1170 # ============================================================
1171 # PRIVATE: column metadata read from the statement NAME list.
1172 # Used when column_info is unsupported, or is supported but returns no
1173 # usable column name (DBD::SQLite under FetchHashKeyName=NAME_uc).
1174 # Degraded mode: column names only, without type or size.
1175 # ============================================================
1176  
1177 0 ▶sub _col_meta_from_names {
Subroutine _col_meta_from_names: not called CC=2 SCAR=17.9
1178 0 my ( $dbh, $table, $norm_id ) = @_;
1179  
1180 0 my %meta;
1181 0 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
1182 0 $sth->execute();
1183 0 for my $col ( @{ $sth->{NAME} } ) {
1184 0 my $norm_col = $norm_id->($col);
1185 0 $meta{$norm_col} = { numeric => 0, size => 0 };
1186 0 &logger( 7, "_get_col_meta (fallback): col=$norm_col" );
1187 }
1188 0 return \%meta;
1189 }
1190  
1191 # ============================================================
1192 # PRIVATE: column metadata for one table
1193 # Returns { col_name => { numeric => 1, size => N } }
1194 # The keys are normalized through $norm_id (supplied by _norm_identifiers)
1195 # $table must already be normalized by the caller
1196 # ============================================================
1197  
1198 9 ▶sub _get_col_meta {
Subroutine _get_col_meta: called CC=22 SCAR=33.4
1199 9 my ( $dbh, $table, $norm_id ) = @_;
1200  
1201 # $norm_id is mandatory - always supplied by _norm_identifiers
1202 9 ▶ die "_get_col_meta: norm_id missing" unless defined $norm_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $norm_id 1 8 9
1203  
1204 8 ▶ my $driver = lc( $dbh->{Driver}{Name} // '' );
Condition50%1/2
$dbh->{"Driver"}{"Name"} // ""
l!l
80
MC/DC0%0/1
$dbh->{"Driver"}{"Name"} // ""
$dbh->{"Driver"}{"Name"}
Truth table50%1/2
A
A= $dbh->{"Driver"}{"Name"}
Aresult
11
00
1205 8 my $cache_key = lc($table) . "\0" . $driver;
1206 return $_csv_import_type_cache{$cache_key}
1207 8 ▶ if exists $_csv_import_type_cache{$cache_key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $oEdtk::DBAdmin::_csv_import_type_cache{$cache_key} 3 5 8
1208  
1209 5 my %meta;
1210 5 eval {
1211 # $table is already normalized by the caller: split without re-normalizing
1212 5 ▶ my ( $schema, $table_name ) =
Branch: 1 branch
BranchTrueFalseTotal
$table =~ /^(\w+)\.(\w+)$/ ? : 0 5 5
1213 $table =~ /^(\w+)\.(\w+)$/
1214 ? ( $1, $2 )
1215 : ( undef, $table );
1216  
1217 5 my $sth = $dbh->column_info( undef, $schema, $table_name, undef );
1218  
1219 # Fallback for drivers that do not support column_info (e.g. SQLite)
1220 # Degraded mode: column names without type or size
1221 5 ▶ unless ( defined $sth ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sth) 0 5 5
1222 0 &logger( 5,
1223 "_get_col_meta: column_info unsupported for '$table_name', fallback SELECT" );
1224 0 %meta = %{ _col_meta_from_names( $dbh, $table, $norm_id ) };
1225 0 $_csv_import_type_cache{$cache_key} = \%meta;
1226 0 return;
1227 }
1228  
1229 5 my %num_codes = map { $_ => 1 } ( 2, 3, 4, 5, 6, 7, 8, -5, -6, -7 );
1230 5 my $found = 0;
1231 5 ▶ while ( my $row = $sth->fetchrow_hashref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 55 5 60
1232  
1233 # Some drivers (DBD::SQLite under FetchHashKeyName=NAME_uc) return
1234 # rows whose COLUMN_NAME is empty; skip them so the metadata never
1235 # carries a nameless column.
1236 55 ▶ next unless defined $row->{COLUMN_NAME} && $row->{COLUMN_NAME} ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{"COLUMN_NAME"} and $row->{"COLUMN_NAME"} ne "" 0 55 55
Condition33%1/3
defined $row->{"COLUMN_NAME"} and $row->{"COLUMN_NAME"} ne ""
!ll&&!rl&&r
0055
MC/DC0%0/2
defined $row->{"COLUMN_NAME"} and $row->{"COLUMN_NAME"} ne ""
defined $row->{"COLUMN_NAME"} $row->{"COLUMN_NAME"} ne ""
Truth table33%1/3
A and B
A= defined $row->{"COLUMN_NAME"}B= $row->{"COLUMN_NAME"} ne ""
ABresult
0X0
100
111
1237 55 $found++;
1238 55 my $col = $norm_id->( $row->{COLUMN_NAME} );
1239 55 ▶ my $type = $row->{DATA_TYPE} // 0;
Condition50%1/2
$row->{"DATA_TYPE"} // 0
l!l
055
MC/DC0%0/1
$row->{"DATA_TYPE"} // 0
$row->{"DATA_TYPE"}
Truth table50%1/2
A
A= $row->{"DATA_TYPE"}
Aresult
11
00
1240 55 ▶ my $name = lc( $row->{TYPE_NAME} // '' );
Condition50%1/2
$row->{"TYPE_NAME"} // ""
l!l
550
MC/DC0%0/1
$row->{"TYPE_NAME"} // ""
$row->{"TYPE_NAME"}
Truth table50%1/2
A
A= $row->{"TYPE_NAME"}
Aresult
11
00
1241 55 ▶ my $size = $row->{COLUMN_SIZE} // 0;
Condition100%2/2
$row->{"COLUMN_SIZE"} // 0
l!l
487
MC/DC100%1/1
$row->{"COLUMN_SIZE"} // 0
$row->{"COLUMN_SIZE"}
Truth table100%2/2
A
A= $row->{"COLUMN_SIZE"}
Aresult
11
00
1242  
1243 55 ▶ my $by_name = (
Branch: 1 branch
BranchTrueFalseTotal
$name =~ / ^( int[248]? | integer | smallint | bigint | serial | bigserial | smallserial | numeric | decimal | number | float[48]? | real | double(\s+precision)? | money | tinyint | mediumint )$ /xi ? : 6 49 55
1244 $name =~ m{
1245 ^( int[248]? | integer | smallint | bigint
1246 | serial | bigserial | smallserial
1247 | numeric | decimal | number
1248 | float[48]? | real | double(\s+precision)?
1249 | money | tinyint | mediumint )$
1250 }xi
1251 ) ? 1 : 0;
1252 55 ▶ my $is_num = ( $num_codes{$type} || $by_name ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$num_codes{$type} || $by_name ? : 6 49 55
Condition66%2/3
$num_codes{$type} or $by_name
l!l&&r!l&&!r
0649
MC/DC50%1/2
$num_codes{$type} or $by_name
$num_codes{$type} $by_name
Truth table66%2/3
A or B
A= $num_codes{$type}B= $by_name
ABresult
1X1
011
000
1253  
1254 # COLUMN_SIZE is a usable character length for truncation only
1255 # for text types. For numeric, date, time, etc. types, column_info
1256 # (in particular DBD::Pg) returns the internal storage size (e.g.
1257 # date(4), like an int4), which wrongly truncates values (e.g. a
1258 # date "2026-07-09" cut down to "2026" before the insert).
1259 55 ▶ my $is_text = (
Branch: 1 branch
BranchTrueFalseTotal
$name =~ / ^( varchar | character(\s+varying)? | char | bpchar | text ) /xi ? : 48 7 55
1260 $name =~ m{
1261 ^( varchar | character(\s+varying)? | char | bpchar | text )
1262 }xi
1263 ) ? 1 : 0;
1264  
1265 # Types that need the '' => NULL conversion on insert: the
1266 # numeric ones (already covered by is_num) plus the date/time
1267 # types, for which PostgreSQL rejects an empty string
1268 # ('ERROR: invalid input syntax for type date: ""').
1269 55 ▶ my $is_datetime = (
Branch: 1 branch
BranchTrueFalseTotal
$name =~ / ^( date | time | timestamp(tz)? | datetime ) /xi ? : 1 54 55
1270 $name =~ m{
1271 ^( date | time | timestamp(tz)? | datetime )
1272 }xi
1273 ) ? 1 : 0;
1274 55 ▶ my $blank_to_null = ( $is_num || $is_datetime ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$is_num || $is_datetime ? : 7 48 55
Condition100%3/3
$is_num or $is_datetime
l!l&&r!l&&!r
6148
MC/DC100%2/2
$is_num or $is_datetime
$is_num $is_datetime
Truth table100%3/3
A or B
A= $is_numB= $is_datetime
ABresult
1X1
011
000
1275  
1276 55 ▶ $meta{$col} = {
Branch: 1 branch
BranchTrueFalseTotal
$is_text ? : 48 7 55
1277 numeric => $is_num,
1278 blank_to_null => $blank_to_null,
1279 size => ( $is_text ? $size : 0 ),
1280 };
1281 55 &logger( 7,
1282 "_get_col_meta: col=$col TYPE=$name($size) is_num=$is_num is_text=$is_text blank_to_null=$blank_to_null"
1283 );
1284 }
1285 5 ▶ if ( !$found ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $found) { } 0 5 5
1286  
1287 # column_info is supported but returned no usable column name (e.g.
1288 # DBD::SQLite under FetchHashKeyName=NAME_uc): fall back to the
1289 # statement NAME list so the header check still has names to
1290 # validate against. Types and sizes stay degraded.
1291 0 &logger( 5,
1292 "_get_col_meta: column_info returned no usable column for '$table_name', fallback SELECT"
1293 );
1294 0 %meta = %{ _col_meta_from_names( $dbh, $table, $norm_id ) };
1295 }
1296 else {
1297 5 &logger( 5, "_get_col_meta: $found columns for '$table_name'" );
1298 }
1299 };
1300 5 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5 5
1301 0 &logger( 3, "_get_col_meta: column_info failed for $table: $@" );
1302 }
1303  
1304 5 $_csv_import_type_cache{$cache_key} = \%meta;
1305 5 return \%meta;
1306 }
1307  
1308 # Drops the column-metadata cache used by csv_import (keyed by table + driver).
1309 # Call it after a schema change (schema_Create / schema_Upgrade) so the next import
1310 # re-reads the columns instead of reusing a stale description.
1311 7 ▶sub db_invalidate_meta_cache {
Subroutine db_invalidate_meta_cache: called CC=1 SCAR=0.0
Pod documented
1312 7 %_csv_import_type_cache = ();
1313 7 return 1;
1314 }
1315  
1316 # ============================================================
1317 # PRIVATE: clean one value according to the column metadata
1318 # (numeric type, max size)
1319 # ============================================================
1320 4 ▶sub _make_clean_val {
Subroutine _make_clean_val: called CC=1 SCAR=0.0
1321 4 my ($col_meta) = @_;
1322 86 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
1323 86 my ( $col, $val ) = @_;
1324 86 ▶ return undef unless defined $val; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 42 44 86
1325 44 ▶ my $m = $col_meta->{$col} // {};
Condition100%2/2
$col_meta->{$col} // {}
l!l
404
MC/DC100%1/1
$col_meta->{$col} // {}
$col_meta->{$col}
Truth table100%2/2
A
A= $col_meta->{$col}
Aresult
11
00
1326  
1327 44 ▶ if ( $val eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val eq "") 6 38 44
1328 6 ▶ if ( $m->{blank_to_null} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m->{"blank_to_null"}) 4 2 6
1329 4 &logger( 7, "clean_val: col '$col' numeric/date, '' => undef" );
1330 4 return undef; ## no critic (ProhibitExplicitReturnUndef)
1331 }
1332 2 return $val;
1333 }
1334  
1335 38 ▶ if ( $m->{size} && length($val) > $m->{size} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m->{"size"} and length $val > $m->{"size"}) 3 35 38
Condition100%3/3
$m->{"size"} and length $val > $m->{"size"}
!ll&&!rl&&r
11243
MC/DC100%2/2
$m->{"size"} and length $val > $m->{"size"}
$m->{"size"} length $val > $m->{"size"}
Truth table100%3/3
A and B
A= $m->{"size"}B= length $val > $m->{"size"}
ABresult
0X0
100
111
1336 3 my $truncated = substr( $val, 0, $m->{size} );
1337 3 &logger( 6,
1338 "clean_val: col '$col' truncated from " . length($val) . " to $m->{size} chars" );
1339 3 return $truncated;
1340 }
1341  
1342 35 return $val;
1343 4 };
1344 }
1345  
1346 # ============================================================
1347 # PRIVATE: prepare the per-column cleaning plan once for a row loop.
1348 # Each entry is [ name, max_size (0 = none), blank_to_null ]; _clean_row
1349 # applies it with one test sequence per field and no per-field call (plan O3,
1350 # the row-by-row analogue of _pg_csv_row).
1351 # ============================================================
1352 4 ▶sub _make_clean_plan {
Subroutine _make_clean_plan: called CC=4 SCAR=13.9
1353 4 my ( $col_meta, $cols ) = @_;
1354 return [
1355 map {
1356 4 ▶ my $m = $col_meta->{$_} // {};
Condition100%2/2
$col_meta->{$_} // {}
l!l
121
MC/DC100%1/1
$col_meta->{$_} // {}
$col_meta->{$_}
Truth table100%2/2
A
A= $col_meta->{$_}
Aresult
11
00
1357 13 ▶ [ $_, ( $m->{size} // 0 ), ( $m->{blank_to_null} ? 1 : 0 ) ]
Branch: 1 branch
BranchTrueFalseTotal
$m->{'blank_to_null'} ? : 8 5 13
Condition100%2/2
$m->{"size"} // 0
l!l
112
MC/DC100%1/1
$m->{"size"} // 0
$m->{"size"}
Truth table100%2/2
A
A= $m->{"size"}
Aresult
11
00
1358 } @$cols
1359 ];
1360 }
1361  
1362 # ============================================================
1363 # PRIVATE: clean one CSV row against a plan, positionally. One test sequence
1364 # per field, no closure call and no name-keyed lookup (plan O3). A field past
1365 # the end of $data cleans to NULL, like the _make_clean_val contract; the log
1366 # lines match it too.
1367 # ============================================================
1368 7 ▶sub _clean_row {
Subroutine _clean_row: called CC=9 SCAR=22.0
1369 7 my ( $plan, $data ) = @_;
1370 7 my @out;
1371 7 for my $i ( 0 .. $#$plan ) {
1372 25 my $v = $data->[$i];
1373 25 my $p = $plan->[$i];
1374 25 ▶ if ( !defined $v ) { push @out, undef; next; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 4 21 25
1375 21 ▶ if ( $v eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v eq "") 5 16 21
1376 5 ▶ if ( $p->[2] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->[2]) { } 4 1 5
1377 4 ▶ &logger( 7, "clean_val: col '$p->[0]' numeric/date, '' => undef" )
Branch: 1 branch
BranchTrueFalseTotal
if $oEdtk::DBAdmin::LOGGERLEVEL >= 7 0 4 4
1378 if $LOGGERLEVEL >= 7;
1379 4 push @out, undef;
1380 }
1381 1 else { push @out, $v; }
1382 5 next;
1383 }
1384 16 ▶ if ( $p->[1] && length($v) > $p->[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->[1] and length $v > $p->[1]) 3 13 16
Condition100%3/3
$p->[1] and length $v > $p->[1]
!ll&&!rl&&r
853
MC/DC100%2/2
$p->[1] and length $v > $p->[1]
$p->[1] length $v > $p->[1]
Truth table100%3/3
A and B
A= $p->[1]B= length $v > $p->[1]
ABresult
0X0
100
111
1385 3 ▶ &logger( 6,
Branch: 1 branch
BranchTrueFalseTotal
if $oEdtk::DBAdmin::LOGGERLEVEL >= 6 0 3 3
1386 "clean_val: col '$p->[0]' truncated from " . length($v) . " to $p->[1] chars" )
1387 if $LOGGERLEVEL >= 6;
1388 3 push @out, substr( $v, 0, $p->[1] );
1389 3 next;
1390 }
1391 13 push @out, $v;
1392 }
1393 7 return @out;
1394 }
1395  
1396 # ============================================================
1397 # PRIVATE: the CSV paths go through Text::CSV. Without its XS backend
1398 # (Text::CSV_XS) the per-line parse dominates the load (plan O1), so warn once
1399 # (3-ALERT) and point at the blocking prerequisite. Text::CSV->backend is
1400 # 'Text::CSV_PP' when the XS module is missing.
1401 # ============================================================
1402 32 my $_CSV_BACKEND_WARNED = 0;
1403  
1404 1 ▶sub _check_csv_backend {
Subroutine _check_csv_backend: called CC=5 SCAR=20.9
1405 1 ▶ return if $_CSV_BACKEND_WARNED;
Branch: 1 branch
BranchTrueFalseTotal
if $_CSV_BACKEND_WARNED 0 1 1
1406 1 my $backend = eval { Text::CSV->backend };
1407 1 ▶ unless ( defined $backend && $backend eq 'Text::CSV_XS' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $backend and $backend eq "Text::CSV_XS") 0 1 1
Condition33%1/3
defined $backend and $backend eq "Text::CSV_XS"
!ll&&!rl&&r
001
MC/DC0%0/2
defined $backend and $backend eq "Text::CSV_XS"
defined $backend $backend eq "Text::CSV_XS"
Truth table33%1/3
A and B
A= defined $backendB= $backend eq "Text::CSV_XS"
ABresult
0X0
100
111
1408 0 $_CSV_BACKEND_WARNED = 1;
1409 0 ▶ &logger( 3,
Condition0%0/2
$backend // "unknown"
l!l
00
MC/DC0%0/1
$backend // "unknown"
$backend
Truth table0%0/2
A
A= $backend
Aresult
11
00
1410 "csv_import: Text::CSV backend is '"
1411 . ( $backend // 'unknown' )
1412 . "', not Text::CSV_XS - install Text::CSV_XS (plan O1)" );
1413 }
1414 1 return;
1415 }
1416  
1417 2 ▶sub insert_tData {
Subroutine insert_tData: called CC=2 SCAR=6.9
Pod documented
1418  
1419 # Example call:
1420 # my $ret = insert_tData(
1421 # dbh => $dbh,
1422 # table => $cfg->{'EDTK_DBI_TRACKING'},
1423 # tCols => \@cols,
1424 # tData => \@tData
1425 # );
1426 2 my (%p) = @_;
1427  
1428 my ( $norm_id, $norm_table, @norm_cols ) =
1429 2 _norm_identifiers( $p{'dbh'}, $p{'table'}, $p{'tCols'} );
1430  
1431 2 my $col_meta = _get_col_meta( $p{'dbh'}, $norm_table, $norm_id );
1432 2 my $plan = _make_clean_plan( $col_meta, \@norm_cols );
1433  
1434 2 &logger( 7, "Table : $norm_table" );
1435 2 &logger( 7, "NB Data : " . scalar @{ $p{'tData'} } );
1436 2 &logger( 7, "Data : " . Dumper( $p{'tData'} ) );
1437  
1438 2 my $sql =
1439 "INSERT INTO "
1440 . $norm_table . " ("
1441 . join( ',', @norm_cols ) . ")"
1442 . " VALUES ("
1443 . join( ',', ('?') x @norm_cols ) . ")";
1444 2 &logger( 7, $sql );
1445  
1446 2 my $sth = $p{'dbh'}->prepare_cached($sql);
1447 2 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute(_clean_row($plan, $p{"tData"})) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 2 0 2
1448 2 local $sth->{PrintError} = 0;
1449 2 $sth->execute( _clean_row( $plan, $p{'tData'} ) );
1450 }
1451 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1452 2 1;
1453 }
1454  
1455 # ============================================================
1456 # PUBLIC: import a CSV file into a table
1457 # API unchanged
1458 # ============================================================
1459 1 ▶sub csv_import {
Subroutine csv_import: called CC=38 SCAR=57.4
Pod documented
1460 1 my ( $dbh, $table, $in, $params ) = @_;
1461 1 ▶ $params->{'mode'} = $params->{'mode'} || "insert";
Condition50%1/2
$params->{'mode'} || 'insert'
l!l
01
MC/DC0%0/1
$params->{'mode'} || 'insert'
$params->{'mode'}
Truth table50%1/2
A
A= $params->{'mode'}
Aresult
11
00
1462 1 ▶ $params->{'sep_char'} = $params->{'sep_char'} || ',';
Condition50%1/2
$params->{'sep_char'} || ','
l!l
01
MC/DC0%0/1
$params->{'sep_char'} || ','
$params->{'sep_char'}
Truth table50%1/2
A
A= $params->{'sep_char'}
Aresult
11
00
1463 1 ▶ $params->{'quote_char'} = $params->{'quote_char'} || '"';
Condition50%1/2
$params->{'quote_char'} || '"'
l!l
01
MC/DC0%0/1
$params->{'quote_char'} || '"'
$params->{'quote_char'}
Truth table50%1/2
A
A= $params->{'quote_char'}
Aresult
11
00
1464 1 ▶ $params->{'local_infile'} = $params->{'local_infile'} || "no";
Condition50%1/2
$params->{'local_infile'} || 'no'
l!l
01
MC/DC0%0/1
$params->{'local_infile'} || 'no'
$params->{'local_infile'}
Truth table50%1/2
A
A= $params->{'local_infile'}
Aresult
11
00
1465 1 ▶ $params->{'ref_col'} = $params->{'ref_col'} || 0; # merge match column (D-S53)
Condition50%1/2
$params->{'ref_col'} || 0
l!l
01
MC/DC0%0/1
$params->{'ref_col'} || 0
$params->{'ref_col'}
Truth table50%1/2
A
A= $params->{'ref_col'}
Aresult
11
00
1466  
1467 # O1: the CSV parse paths need the Text::CSV_XS backend; warn once otherwise.
1468 1 _check_csv_backend();
1469  
1470 # Normalize the driver and the table name
1471 # $norm_id is kept to normalize the CSV columns after reading the header
1472 1 my ( $norm_id, $norm_table ) = _norm_identifiers( $dbh, $table );
1473  
1474 1 ▶ if ( $params->{'local_infile'} =~ /try/i
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"local_infile"} =~ /try/i and not $params->{"mode"} =~ /merge/i and $dbh->{"Name"} =~ /mysql_local_infile\=true/i) 0 1 1
Condition33%2/6
$params->{"local_infile"} =~ /try/i and not $params->{"mode"} =~ /merge/i and $dbh->{"Name"} =~ /mysql_local_infile\=true/i
!ll&&!rl&&r
100
$params->{"local_infile"} =~ /try/i and not $params->{"mode"} =~ /merge/i
!ll&&!rl&&r
100
MC/DC0%0/3
$params->{"local_infile"} =~ /try/i and not $params->{"mode"} =~ /merge/i and $dbh->{"Name"} =~ /mysql_local_infile\=true/i
$params->{"local_infile"} =~ /try/i not $params->{"mode"} =~ /merge/i $dbh->{"Name"} =~ /mysql_local_infile\=true/i
Truth table25%1/4
A and not(B) and C
A= $params->{"local_infile"} =~ /try/iB= not $params->{"mode"} =~ /merge/iC= $dbh->{"Name"} =~ /mysql_local_infile\=true/i
ABCresult
0XX0
10X0
1100
1111
1475 && $params->{'mode'} !~ /merge/i
1476 && $dbh->{'Name'} =~ m/mysql_local_infile\=true/i )
1477 {
1478 0 &logger( 7,
1479 "'mysql_local_infile=true' detected in DSN by csv_import, trying local infile" );
1480 0 return _load_csv_mysql_local_infile( $dbh, $norm_table, $in, $params );
1481 }
1482  
1483 # PostgreSQL: COPY ... FROM STDIN is the native equivalent of LOAD DATA LOCAL INFILE.
1484 # Enabled automatically for the Pg driver (merge mode keeps the row-by-row path).
1485 1 ▶ if ( $params->{'mode'} !~ /merge/i
Branch: 1 branch
BranchTrueFalseTotal
if (not $params->{"mode"} =~ /merge/i and _db_check_driver_name($dbh) eq "PostgreSQL") 0 1 1
Condition33%1/3
not $params->{"mode"} =~ /merge/i and _db_check_driver_name($dbh) eq "PostgreSQL"
!ll&&!rl&&r
010
MC/DC0%0/2
not $params->{"mode"} =~ /merge/i and _db_check_driver_name($dbh) eq "PostgreSQL"
not $params->{"mode"} =~ /merge/i _db_check_driver_name($dbh) eq "PostgreSQL"
Truth table33%1/3
not(A) and B
A= not $params->{"mode"} =~ /merge/iB= _db_check_driver_name($dbh) eq "PostgreSQL"
ABresult
0X0
100
111
1486 && _db_check_driver_name($dbh) eq "PostgreSQL" )
1487 {
1488 0 ▶ if ( defined $params->{'header'} || defined $params->{'ignore_first_line'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{'header'} or defined $params->{'ignore_first_line'}) { } 0 0 0
Condition0%0/3
defined $params->{"header"} or defined $params->{"ignore_first_line"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $params->{"header"} or defined $params->{"ignore_first_line"}
defined $params->{"header"} defined $params->{"ignore_first_line"}
Truth table0%0/3
A or B
A= defined $params->{"header"}B= defined $params->{"ignore_first_line"}
ABresult
1X1
011
000
1489 0 &logger( 5,
1490 "csv_import: header/ignore_first_line requested, using the row-by-row path (COPY ignores them)"
1491 );
1492 }
1493 else {
1494 0 &logger( 7, "PostgreSQL driver detected by csv_import, trying COPY FROM STDIN" );
1495 0 return _load_csv_pg_copy( $dbh, $norm_table, $in, $params, $norm_id );
1496 }
1497 }
1498  
1499 1 ▶ open( my $fh, '<', $in ) or die "ERROR: Cannot open index file \"$in\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $in or die qq[ERROR: Cannot open index file "$in": $!\n] 1 0 1
1500 my $csv = Text::CSV->new(
1501 {
1502 binary => 1,
1503 sep_char => $params->{'sep_char'},
1504 1 quote_char => $params->{'quote_char'}
1505 }
1506 );
1507  
1508 1 my ( $line, $lines_inserted, $rv );
1509 1 ▶ if ( defined $params->{'header'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{'header'}) { } 0 1 1
1510 0 $line = $params->{'header'};
1511 }
1512 else {
1513 1 $line = <$fh>;
1514 }
1515 1 $csv->parse($line);
1516  
1517 # The CSV columns are normalized through $norm_id after reading the header,
1518 # since they are only known at that point (unlike insert_tData)
1519 1 my @cols = map { $norm_id->($_) } $csv->fields();
1520  
1521 1 ▶ if ( defined $params->{'ignore_first_line'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"ignore_first_line"}) 0 1 1
1522 0 $line = <$fh>;
1523 }
1524  
1525 # $norm_table and $norm_id are consistent: the %$col_meta keys
1526 # are in the same case as @cols
1527 1 my $col_meta = _get_col_meta( $dbh, $norm_table, $norm_id );
1528  
1529 # H9 : refuse a header column that is not in the table before any SQL.
1530 1 ▶ my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
Branch: 1 branch
BranchTrueFalseTotal
keys %$col_meta ? : 1 0 1
1531 1 ▶ if (@$unknown) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$unknown) 0 1 1
1532 0 close($fh);
1533 return (
1534 0 -1,
1535 &logger(
1536 3,
1537 "csv_import: unknown column(s) "
1538 . join( ', ', @$unknown )
1539 . " for table $norm_table"
1540 )
1541 );
1542 }
1543  
1544 # The column metadata is prepared once into a positional plan (plan O3), so
1545 # each field of every row costs one test sequence, not a closure call.
1546 1 my $plan = _make_clean_plan( $col_meta, \@cols );
1547  
1548 # The merge looks up the existing row on the column named by ref_col (D-S53;
1549 # the fork hard-coded the first column). The default 0 keeps M's behaviour.
1550 1 my $refcol = $params->{'ref_col'};
1551  
1552 1 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 1 1 2
1553 1 $lines_inserted++;
1554 1 $csv->parse($_);
1555 1 my @data = $csv->fields();
1556 1 my @clean = _clean_row( $plan, \@data );
1557 1 my ( $sql, $sth, $seqlot );
1558  
1559 1 ▶ if ( $params->{'mode'} =~ /merge/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"mode"} =~ /merge/i) 0 1 1
1560 0 $sql =
1561 "SELECT "
1562 . $cols[$refcol]
1563 . " FROM "
1564 . $norm_table
1565 . " WHERE "
1566 . $cols[$refcol] . " = ?";
1567 0 &logger( 7, "Select from $norm_table : $sql" );
1568 0 $sth = $dbh->prepare_cached($sql);
1569 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute($clean[$refcol]) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
1570 0 local $sth->{PrintError} = 0;
1571 0 $sth->execute( $clean[$refcol] );
1572 }
1573 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1574 0 $seqlot = $sth->fetchrow_hashref();
1575  
1576 # fetchrow_hashref returns keys in the driver's native case:
1577 # normalize so the comparison with the match column is reliable
1578 0 ▶ if ( defined $seqlot ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $seqlot) 0 0 0
1579 0 $seqlot = { map { $norm_id->($_) => $seqlot->{$_} } keys %$seqlot };
1580 }
1581 }
1582  
1583 1 ▶ if ( defined $seqlot && defined $seqlot->{ $cols[$refcol] } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $seqlot and defined $$seqlot{$cols[$refcol]}) { } 0 1 1
Condition33%1/3
defined $seqlot and defined $$seqlot{$cols[$refcol]}
!ll&&!rl&&r
100
MC/DC0%0/2
defined $seqlot and defined $$seqlot{$cols[$refcol]}
defined $seqlot defined $$seqlot{$cols[$refcol]}
Truth table33%1/3
A and B
A= defined $seqlotB= defined $$seqlot{$cols[$refcol]}
ABresult
0X0
100
111
1584 0 $sql =
1585 "UPDATE "
1586 . $norm_table . " SET "
1587 . join( '=?, ', @cols ) . "=? "
1588 . " WHERE "
1589 . $cols[$refcol] . " = ?";
1590 0 &logger( 7, "Update $norm_table : $sql" );
1591 0 $sth = $dbh->prepare_cached($sql);
1592 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute(@clean, $clean[$refcol]) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
1593 0 local $sth->{PrintError} = 0;
1594 0 $sth->execute( @clean, $clean[$refcol] );
1595 }
1596 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1597 }
1598 else {
1599 1 $sql =
1600 "INSERT INTO "
1601 . $norm_table . " ("
1602 . join( ',', @cols ) . ")"
1603 . " VALUES ("
1604 . join( ',', ('?') x @cols ) . ")";
1605 1 &logger( 7, "Insert into $norm_table : $sql" );
1606 1 $sth = $dbh->prepare_cached($sql);
1607 1 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute(@clean) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 1 0 1
1608 1 local $sth->{PrintError} = 0;
1609 1 $sth->execute(@clean);
1610 }
1611 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1612 }
1613  
1614 # Acquittal (D-S53): the acknowledgement file also stamps the mailing-out
1615 # date on the indexed items and, when configured, hands the document to
1616 # the API callable (EDTK_ACQUIT_API). A malformed date, an absent
1617 # callable or a driver that cannot run the lookup is a log line, never
1618 # fatal (the fork croaked on a malformed date).
1619 1 ▶ if ( $params->{'timestamp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"timestamp"}) 0 1 1
1620 0 my $exped = $data[ACQ_FIELD_EXPED];
1621 0 ▶ if ( defined $exped && $exped ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exped and $exped ne "") 0 0 0
Condition0%0/3
defined $exped and $exped ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $exped and $exped ne ""
defined $exped $exped ne ""
Truth table0%0/3
A and B
A= defined $expedB= $exped ne ""
ABresult
0X0
100
111
1622 0 ▶ if ( $exped !~ /^20[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $exped =~ /^20[0-9]+$/) { } 0 0 0
1623 0 &logger( 3, "csv_import: acknowledgement date '$exped' is not a valid date" );
1624 }
1625 else {
1626 0 my $acfg = eval { config_read( 'EDTK_DB', 'SERVICES' ) };
1627 0 ▶ if ( ref $acfg eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $acfg eq "HASH") 0 0 0
1628 0 my $idx = $acfg->{'EDTK_DBI_OUTMNGR'};
1629 0 ▶ _acquit_table_INDEX( $dbh, \@data, $idx ) if defined $idx && length $idx;
Branch: 1 branch
BranchTrueFalseTotal
if defined $idx and length $idx 0 0 0
Condition0%0/3
defined $idx and length $idx
!ll&&!rl&&r
000
MC/DC0%0/2
defined $idx and length $idx
defined $idx length $idx
Truth table0%0/3
A and B
A= defined $idxB= length $idx
ABresult
0X0
100
111
1630 0 _acquit_API( $dbh, \@data, $acfg );
1631 }
1632 }
1633 }
1634 }
1635  
1636 1 ▶ if ( $sth->err && ( $sth->err > 0 || $sth->err =~ m/0E/ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->err and $sth->err > 0 || $sth->err =~ /0E/) 0 1 1
Condition16%1/6
$sth->err and $sth->err > 0 || $sth->err =~ /0E/
!ll&&!rl&&r
100
$sth->err > 0 or $sth->err =~ /0E/
l!l&&r!l&&!r
000
MC/DC0%0/3
$sth->err and $sth->err > 0 || $sth->err =~ /0E/
$sth->err $sth->err > 0 $sth->err =~ /0E/
Truth table25%1/4
A and B or C
A= $sth->errB= $sth->err > 0C= $sth->err =~ /0E/
ABCresult
0XX0
1000
11X1
1011
1637 0 $rv = $sth->err . "-" . $sth->errstr;
1638 }
1639 }
1640  
1641 1 close($fh);
1642 1 ▶ if ($rv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rv) { } 0 1 1
1643 0 &logger( -1, $rv );
1644 0 return ( -1, " - $rv" );
1645 }
1646 else {
1647 1 ▶ $lines_inserted //= 0;
Condition50%1/2
$lines_inserted //= 0
l!l
10
MC/DC0%0/1
$lines_inserted //= 0
$lines_inserted
Truth table50%1/2
A
A= $lines_inserted
Aresult
11
00
1648 1 &logger( 5, "$lines_inserted lines inserted from $in" );
1649 1 return ( $lines_inserted, " lines inserted" );
1650 }
1651 }
1652  
1653 ###### ORACLE VERSION OF THE MERGE, DIFFERENT FROM THE POSTGRESQL ONE
1654 #MERGE INTO table_name USING table_reference ON (condition)
1655 # WHEN MATCHED THEN
1656 # UPDATE SET column1 = value1 [, column2 = value2 ...]
1657 # WHEN NOT MATCHED THEN
1658 # INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...
1659  
1660 #MERGE INTO Table1 T1
1661 # USING (SELECT Id, Meschamps FROM Table2) T2
1662 # ON ( T1.Id = T2.Id ) -- Join condition
1663 #WHEN MATCHED THEN -- If true
1664 # UPDATE SET T1.Meschamps = T2.Meschamps
1665 #WHEN NOT MATCHED THEN -- If false
1666 # INSERT (T1.ID, T1.MesChamps) VALUES ( T2.ID, T2.MesChamps);
1667  
1668 ###### VERSION POSTGRESQL
1669 #MERGE INTO table [[AS] alias]
1670 #USING [table-ref | query]
1671 #ON join-condition
1672 #[WHEN MATCHED [AND condition] THEN MergeUpdate | DELETE | DO NOTHING | RAISE ERROR]
1673 #[WHEN NOT MATCHED [AND condition] THEN MergeInsert | DO NOTHING | RAISE ERROR]
1674 #MergeUpdate is
1675 #
1676 #UPDATE SET { column = { expression | DEFAULT } |
1677 #( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) }
1678 #[, ...]
1679 #(yes, there is no WHERE clause here)
1680 #MergeInsert is
1681 #INSERT [ ( column [, ...] ) ]
1682 #{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] )
1683 #[, ...]}
1684  
1685 7 ▶sub _db_connect1 {
Subroutine _db_connect1: called CC=13 SCAR=29.6
1686 7 my ( $cfg, $dsnvar, $dbargs ) = @_;
1687 7 my $dbh;
1688 7 my $dsn = $cfg->{$dsnvar};
1689 7 $_LOCAL_EDTK_WAITRUN = $cfg->{EDTK_WAITRUN};
1690  
1691 7 &logger( 5, "Connecting to DSN $dsn, $dsnvar" );
1692  
1693 # TODO review attribute handling for displaying error messages:
1694 # https://docstore.mik.ua/orelly/linux/dbi/ch04_05.htm
1695  
1696 # connection handled in a timed loop: 3 attempts with an increasing pause
1697 7 ▶ for ( my $i = 0 ; $i < 3 ; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 3) 9 7 16
1698 9 sleep( $_LOCAL_EDTK_WAITRUN * $i );
1699 9 $dbh = undef;
1700 9 eval {
1701 9 $dbh = DBI->connect( $dsn, $cfg->{"${dsnvar}_USER"}, $cfg->{"${dsnvar}_PASS"}, $dbargs )
1702 ; ## xxxx
1703 };
1704  
1705 # H5: a driver may fail without raising (RaiseError=0, the reason left in
1706 # $DBI::errstr only). Only a defined handle counts as a success, so a silent
1707 # miss is retried instead of being mistaken for an established connection.
1708 9 ▶ if ( $@ || !defined $dbh ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $dbh) { } 3 6 9
Condition66%2/3
$@ or not defined $dbh
l!l&&r!l&&!r
036
MC/DC50%1/2
$@ or not defined $dbh
$@ not defined $dbh
Truth table66%2/3
A or not(B)
A= $@B= not defined $dbh
ABresult
1X1
011
000
1709  
1710 # on a connection failure, try again
1711 3 &logger( 4, "DBI connection missmatch to $dsnvar, we try 3 times" );
1712 3 ▶ &logger( 4, "Error message was : " . ( $@ || $DBI::errstr || 'no handle returned' ) );
Condition40%2/5
$@ || $DBI::errstr || 'no handle returned'
l!l
30
$@ or $DBI::errstr
l!l&&r!l&&!r
030
MC/DC0%0/2
$@ || $DBI::errstr || 'no handle returned'
$@ $DBI::errstr
Truth table33%1/3
A or B
A= $@B= $DBI::errstr
ABresult
1X1
011
000
1713  
1714 }
1715 else {
1716 # if it looks fine, we are done
1717  
1718 6 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_TRACKED"})) 0 6 6
Condition44%8/18
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_TRACKED"})
!ll&&!rl&&r
600
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"})
!ll&&!rl&&r
600
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"})
!ll&&!rl&&r
600
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i
!ll&&!rl&&r
600
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/
!ll&&!rl&&r
510
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM"
!ll&&!rl&&r
501
MC/DC0%0/7
$CONNECT_COUNT == 1 and $dsnvar ne "EDTK_DBI_PARAM" and not $dsnvar =~ /_BAK\z/ and $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"}) and &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_TRACKED"})
$CONNECT_COUNT == 1 $dsnvar ne "EDTK_DBI_PARAM" not $dsnvar =~ /_BAK\z/ $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/i &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"}) &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"}) &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_TRACKED"})
Truth table25%2/8
A and B and not(C) and D and E and F and G
A= $CONNECT_COUNT == 1B= $dsnvar ne "EDTK_DBI_PARAM"C= not $dsnvar =~ /_BAK\z/D= $cfg->{"EDTK_DB_CHECK_AUTO"} =~ /YES/iE= &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT"})F= &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_KEPT_STATS"})G= &looks_like_number($cfg->{"EDTK_DB_MAX_DAYS_TRACKED"})
ABCDEFGresult
0XXXXXX0
10XXXXX0
110XXXX0
1110XXX0
11110XX0
111110X0
11111100
11111111
1719 $CONNECT_COUNT == 1
1720 and $dsnvar ne "EDTK_DBI_PARAM"
1721  
1722 # H1: never run the automatic check on the backup buffer. Its handle
1723 # is opened while the counter still reads 1 (the check runs on the
1724 # second connection, before the counter is bumped), so without this
1725 # guard every backup handle would re-enter the reconcile.
1726 and $dsnvar !~ /_BAK\z/
1727  
1728 #and ($cfg->{EDTK_DB_CHECK_AUTO}||"YES")!~/NO/i
1729 #and (defined $cfg->{EDTK_DB_CHECK_AUTO} && $cfg->{EDTK_DB_CHECK_AUTO} =~/YES/i)
1730 and ( $cfg->{EDTK_DB_CHECK_AUTO} =~ /YES/i )
1731 and looks_like_number( $cfg->{EDTK_DB_MAX_DAYS_KEPT} )
1732 and looks_like_number( $cfg->{EDTK_DB_MAX_DAYS_KEPT_STATS} )
1733 and looks_like_number( $cfg->{EDTK_DB_MAX_DAYS_TRACKED} )
1734 )
1735 {
1736 0 my ( $level, $return ) = acheck_db_admin_on_connect( $dbh, $cfg );
1737 0 &logger( $level, "$return-$dsn" );
1738 }
1739 6 $CONNECT_COUNT++;
1740  
1741 6 $i = 4;
1742 }
1743 }
1744 7 return $dbh;
1745 }
1746  
1747 2 ▶sub db_connect {
Subroutine db_connect: called CC=13 SCAR=30.8
Pod documented
1748 2 my ( $cfg, $dsnvar, $dbargs ) = @_;
1749  
1750 # $dbargs->{'RaiseError'} = 1;
1751  
1752 # Turning tracking off in a Test environment (D-S53) opens no handle at all:
1753 # callers receive undef and skip their database work. This is the fork's test
1754 # (EDTK_TYPE_ENV = Test and EDTK_TRACK_MODE = NONE).
1755 return
1756 if ( ( $cfg->{'EDTK_TYPE_ENV'} // '' ) eq 'Test'
1757 2 ▶ && ( uc( $cfg->{'EDTK_TRACK_MODE'} // '' ) eq 'NONE' ) );
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"EDTK_TYPE_ENV"} // "") eq "Test" and uc($cfg->{"EDTK_TRACK_MODE"} // "") eq "NONE" 0 2 2
Condition28%2/7
($cfg->{"EDTK_TYPE_ENV"} // "") eq "Test" and uc($cfg->{"EDTK_TRACK_MODE"} // "") eq "NONE"
!ll&&!rl&&r
200
$cfg->{"EDTK_TYPE_ENV"} // ""
l!l
20
$cfg->{"EDTK_TRACK_MODE"} // ""
l!l
00
MC/DC0%0/2
($cfg->{"EDTK_TYPE_ENV"} // "") eq "Test" and uc($cfg->{"EDTK_TRACK_MODE"} // "") eq "NONE"
$cfg->{"EDTK_TYPE_ENV"} $cfg->{"EDTK_TRACK_MODE"}
Truth table0%0/3
A and B
A= $cfg->{"EDTK_TYPE_ENV"}B= $cfg->{"EDTK_TRACK_MODE"}
ABresult
0X0
100
111
1758  
1759 # This avoids problems with PostgreSQL where in some cases, the column
1760 # names are lowercase instead of uppercase, defaukt set as uc.
1761 2 ▶ $dbargs->{'FetchHashKeyName'} = $cfg->{EDTK_DB_FetchHashKeyName} || 'NAME_uc';
Condition50%1/2
$cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc'
l!l
20
MC/DC0%0/1
$cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc'
$cfg->{'EDTK_DB_FetchHashKeyName'}
Truth table50%1/2
A
A= $cfg->{'EDTK_DB_FetchHashKeyName'}
Aresult
11
00
1762  
1763 #$dbh = DBI->connect($dsn, $user, $password,
1764 # { RaiseError => 1, AutoCommit => 0 });
1765  
1766 # Connect to the database.
1767 2 my $dbh = _db_connect1( $cfg, $dsnvar, $dbargs );
1768  
1769 # If we could not connect to the database server, try
1770 # to connect to the backup database server if there is one.
1771 2 ▶ if ( !defined $dbh ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $dbh) 1 1 2
1772 1 ▶ if ( defined $cfg->{"${dsnvar}_BAK"} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$cfg{"${dsnvar}_BAK"}) { } 1 0 1
1773 { # TODO the setting should be added in the backup database (procedure that creates it)
1774 1 ▶ &logger( 4,
Condition50%1/2
$DBI::errstr || 'not defined'
l!l
10
MC/DC0%0/1
$DBI::errstr || 'not defined'
$DBI::errstr
Truth table50%1/2
A
A= $DBI::errstr
Aresult
11
00
1775 "Could not connect to main database server: " . ( $DBI::errstr || "not defined" ) );
1776 1 $dbh = _db_connect1( $cfg, "${dsnvar}_BAK", $dbargs );
1777  
1778 1 ▶ if ( !defined $dbh ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $dbh) 0 1 1
1779 0 ▶ die "ERROR: Could not connect to backup database server : "
Condition0%0/2
$DBI::errstr || 'not defined'
l!l
00
MC/DC0%0/1
$DBI::errstr || 'not defined'
$DBI::errstr
Truth table0%0/2
A
A= $DBI::errstr
Aresult
11
00
1780 . ( $DBI::errstr || "not defined" ) . "\n";
1781 }
1782  
1783 # Store-and-forward: flag that we are writing on the backup buffer and
1784 # make sure it can hold the event tables. db_reconcile_backup will copy
1785 # the accumulated rows back once the main server is reachable again.
1786 1 $dbh->{'private_oEdtk_on_backup'} = 1;
1787 1 &logger( 3,
1788 "Writing to the BACKUP database (main unreachable): data is buffered and will be repatriated."
1789 );
1790 1 eval { db_backup_prepare($dbh); };
1791 }
1792 else {
1793 0 ▶ die "ERROR: Could not connect to database server : "
Condition0%0/2
$DBI::errstr || 'not defined'
l!l
00
MC/DC0%0/1
$DBI::errstr || 'not defined'
$DBI::errstr
Truth table0%0/2
A
A= $DBI::errstr
Aresult
11
00
1794 . ( $DBI::errstr || "not defined" ) . "\n";
1795 }
1796 }
1797  
1798 2 ▶ if ( _table_exists( $dbh, $cfg->{'EDTK_DBI_TRACKING'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_table_exists($dbh, $cfg->{'EDTK_DBI_TRACKING'})) { } 1 1 2
1799  
1800 # silent soft check
1801 }
1802 else {
1803 1 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} );
1804 }
1805  
1806 2 return $dbh;
1807 }
1808  
1809 # Elapsed whole seconds since $since. DBAdmin imports time() from Time::HiRes,
1810 # so a raw difference is fractional; edtk_admin.ed_action_duration is integer.
1811 1 ▶sub _elapsed_seconds {
Subroutine _elapsed_seconds: called CC=1 SCAR=0.0
1812 1 my ($since) = @_;
1813 1 return int( time - $since );
1814 }
1815  
1816 # Run a DML statement, routing any driver error through the logger (see the
1817 # &logger calls below) rather than letting DBI's PrintError dump the raw message
1818 # to STDERR. Returns do()'s result (truthy even for 0 rows, "0E0", as DBI does)
1819 # or undef on failure. Never dies: pass fatal => 1 to log then re-raise (so $@
1820 # carries the message); pass bind => [..] for placeholder arguments.
1821 7 ▶sub _db_do_log {
Subroutine _db_do_log: called CC=6 SCAR=24.1
1822 7 my ( $dbh, $sql, $msg, %opt ) = @_;
1823 7 my $res = do {
1824 7 local $dbh->{PrintError} = 0;
1825 7 local $dbh->{RaiseError} = 0;
1826 7 ▶ eval { $dbh->do( $sql, undef, @{ $opt{bind} // [] } ) };
Condition100%2/2
$opt{"bind"} // []
l!l
34
MC/DC100%1/1
$opt{"bind"} // []
$opt{"bind"}
Truth table100%2/2
A
A= $opt{"bind"}
Aresult
11
00
1827 };
1828 7 ▶ return $res if defined $res;
Branch: 1 branch
BranchTrueFalseTotal
if defined $res 7 0 7
1829 0 ▶ my $full = $msg . ": " . ( $dbh->errstr // $@ // 'unknown error' );
Condition0%0/5
($dbh->errstr // $@) // "unknown error"
l!l
00
$dbh->errstr // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
($dbh->errstr // $@) // "unknown error"
$dbh->errstr $@
Truth table0%0/3
A // B
A= $dbh->errstrB= $@
ABresult
1X1
011
000
1830 0 ▶ die &logger( -1, $full ) if $opt{fatal};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"fatal"} 0 0 0
1831 0 &logger( 3, $full );
1832 0 return;
1833 }
1834  
1835 10 ▶sub _table_exists {
Subroutine _table_exists: called CC=2 SCAR=6.9
1836 10 my ( $dbh, $table_name ) = @_;
1837  
1838 # universal soft and silent check
1839  
1840 # table_info takes 4 arguments: catalog, schema, table, type
1841 # Pass undef for the global filters and target the table name
1842 10 my $sth = $dbh->table_info( undef, undef, $table_name, 'TABLE' );
1843  
1844 # If fetchrow_array returns a row, the table exists
1845 10 my @info = $sth->fetchrow_array();
1846  
1847 10 ▶ return @info ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@info ? : 7 3 10
1848 }
1849  
1850 0 ▶sub acheck_db_admin {
Subroutine acheck_db_admin: not called CC=5 SCAR=34.0
Pod documented
1851  
1852 # EXAMPLE CALL:
1853 # acheck_db_admin (CFG => $cfg);
1854 # in Auto mode, a single daily run is performed
1855 0 my %p = @_;
1856  
1857 # print $p{TEST} . " for TEST\n";
1858 # print $p{maxTime} . " for maxTime\n";
1859 # print $p{tableau} . " for array\n";
1860 # print $p{tableau}[2] . " for array[2]\n";
1861  
1862 # my $time =time;
1863 0 my $date = strftime "%Y-%m-%d", localtime;
1864 0 my ( $sth, $sql );
1865 0 &logger( 6, "ACHECK lookup" );
1866  
1867 # LOOK FOR THE LAST ACTION ON THE ADMIN TABLE
1868 0 $sql =
1869 "select ed_action_date, ed_action_pid, ed_action_status, ed_action_duration, ed_oedtk_release from edtk_admin "
1870 . " where ed_action_date = '"
1871 . $date
1872 . "' "; #order by ed_action_date desc limit 1";
1873 0 &logger( 7, $sql );
1874  
1875 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1876 0 eval { schema_StaleWarning( $p{DBH}, cfg => $p{CFG} ); };
1877 0 ▶ $sth = $p{DBH}->prepare($sql) or return ( 3, $p{DBH}->errstr );
Branch: 1 branch
BranchTrueFalseTotal
$sth = $p{"DBH"}->prepare($sql) or return 3, $p{"DBH"}->errstr 0 0 0
1878 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute() }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
1879 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1880  
1881 # HAS AN ADMINISTRATION ACTION ALREADY BEEN DONE TODAY ?
1882 0 my @tValues = $p{DBH}->selectrow_array( $sql, undef )
1883 ; # or warn ("ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr);
1884 0 my $rc = $sth->finish;
1885 0 $p{DBH}->disconnect;
1886  
1887 0 ▶ if ( $tValues[0] and $date eq $tValues[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tValues[0] and $date eq $tValues[0]) 0 0 0
Condition0%0/3
$tValues[0] and $date eq $tValues[0]
!ll&&!rl&&r
000
MC/DC0%0/2
$tValues[0] and $date eq $tValues[0]
$tValues[0] $date eq $tValues[0]
Truth table0%0/3
A and B
A= $tValues[0]B= $date eq $tValues[0]
ABresult
0X0
100
111
1888 0 &logger(
1889 5,
1890 (
1891 "Previously done, ACHECK Last EDTK_DB_MAX_DAYS check : "
1892 . $tValues[0] . " PID "
1893 . $tValues[1]
1894 )
1895 );
1896 0 return ( 5,
1897 ( "ACHECK Last EDTK_DB_MAX_DAYS check : " . $tValues[0] . " PID " . $tValues[1] ) );
1898 }
1899  
1900 0 return _acheck_request_for_db( CFG => $p{CFG} );
1901 }
1902  
1903 0 ▶sub _acheck_request_for_db {
Subroutine _acheck_request_for_db: not called CC=7 SCAR=40.3
1904  
1905 # example call
1906 # _acheck_request_for_db (CFG => $cfg, DBH => $dbh);
1907 0 my %p = @_;
1908  
1909 0 my $time = time;
1910 0 my $date = strftime "%Y-%m-%d", localtime;
1911 0 my $pid = $$;
1912 0 my ( $rc, $sth, $sql, $insert, $reportActions );
1913  
1914 # REQUEST A TICKET TO CARRY OUT THE ACTIONS
1915 0 $insert =
1916 'insert into edtk_admin (ed_action_date, ed_action_pid, ed_action_status, ed_oedtk_release) '
1917 . ' values (?, ?, ?, ?) ';
1918 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1919 0 $sth = $p{DBH}->prepare_cached($insert);
1920  
1921 0 eval {
1922 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute( $date, $pid, "START", $VERSION ) }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute($date, $pid, "START", $oEdtk::DBAdmin::VERSION) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
1923 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1924 };
1925 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1926 0 &logger( 3, "ERROR: $@ into $insert" );
1927 }
1928  
1929 # CHECK THAT WE HOLD THE LOCK FOR THE ACTION
1930 # LOOK FOR THE LAST ACTION ON THE ADMIN TABLE
1931 $sql =
1932 0 "select ed_action_date, ed_action_pid, ed_action_status, ed_action_duration, ed_oedtk_release from edtk_admin "
1933 . " where ed_action_date = '"
1934 . $date
1935 . "' "; #order by ed_action_date desc limit 1";
1936 0 &logger( 7, $sql );
1937  
1938 0 $sth = $p{DBH}->prepare($sql);
1939 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute() }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
1940 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1941 0 my @tValues = do { local $p{DBH}->{PrintError} = 0; $p{DBH}->selectrow_array( $sql, undef ) }
1942 0 ▶ or &logger( 3, "ERROR: in acheck_db_admin_on_connect, message is " . $p{DBH}->errstr );
Branch: 1 branch
BranchTrueFalseTotal
my(@tValues) = do { local $p{"DBH"}{"PrintError"} = 0; $p{"DBH"}->selectrow_array($sql, undef) } or &logger(3, 'ERROR: in acheck_db_admin_on_connect, message is ' . $p{"DBH"}->errstr) 0 0 0
1943 0 $reportActions = "ACHECK Check 1 : " . $tValues[0] . " PID " . $tValues[1];
1944 0 $rc = $sth->finish;
1945 0 $p{DBH}->disconnect;
1946  
1947 0 ▶ if ( $date eq $tValues[0] and $pid eq $tValues[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date eq $tValues[0] and $pid eq $tValues[1]) { } 0 0 0
Condition0%0/3
$date eq $tValues[0] and $pid eq $tValues[1]
!ll&&!rl&&r
000
MC/DC0%0/2
$date eq $tValues[0] and $pid eq $tValues[1]
$date eq $tValues[0] $pid eq $tValues[1]
Truth table0%0/3
A and B
A= $date eq $tValues[0]B= $pid eq $tValues[1]
ABresult
0X0
100
111
1948 0 &logger( 5, $reportActions );
1949 0 $reportActions .= _acheck_db_rotate( CFG => $p{CFG} );
1950 0 $reportActions .= _acheck_db_purges( CFG => $p{CFG} );
1951  
1952 }
1953 else {
1954 # another process took the action, giving up
1955 0 &logger( 6, "failed, process locked" );
1956 0 return ( 5, $reportActions );
1957 }
1958  
1959 # End of the run
1960 0 $time = _elapsed_seconds($time);
1961 0 $sql =
1962 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?';
1963 0 &logger( 7, $sql );
1964  
1965 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1966 _db_do_log(
1967 0 $p{DBH}, $sql,
1968 "ERROR: can't update ED_ACTION_STATUS",
1969 bind => [ "DONE", $time, $date ]
1970 );
1971  
1972 0 $rc = $sth->finish;
1973 0 $p{DBH}->disconnect;
1974 0 return ( 4, $reportActions );
1975 }
1976  
1977 0 ▶sub _acheck_db_purges {
Subroutine _acheck_db_purges: not called CC=19 SCAR=59.4
1978 0 my %p = @_;
1979  
1980 # my $time =time;
1981 # my $date =strftime "%Y-%m-%d", localtime;
1982 # my $day =strftime "%d", localtime;
1983 0 my ( $sql, $insert, $result, $reportActions );
1984  
1985 # my $DAYS_KEPT_time = time - (86400*$p{CFG}->{EDTK_DB_MAX_DAYS_KEPT});
1986 0 my $DAYS_TRACKED_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} );
1987 0 my $DAYS_KEPT_STATS_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
1988 my $DAYS_AGREGED_time = time -
1989 0 ▶ ( 86400 * ( $p{CFG}->{EDTK_DB_MAX_DAYS_AGREGED} || $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} ) );
Condition0%0/3
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} || $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} || $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
Truth table0%0/3
A || B
A= $p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'}B= $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
ABresult
1X1
011
000
1990  
1991 ### STATS PURGES ###
1992 # PURGE FROM OEDTK_ADMIN
1993 0 $sql = "delete from edtk_admin where ed_action_date < '"
1994 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
1995 0 &logger( 7, $sql );
1996  
1997 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1998 0 ▶ $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update edtk_admin" ) or return;
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, "ERROR: can't update edtk_admin") or return 0 0 0
1999 0 $p{DBH}->disconnect;
2000 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2001 0 ▶ $reportActions = "ACHECK PURGE edtk_admin=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2002  
2003 # PURGE FROM EDTK_DBI_TRACKING
2004 $sql =
2005 "delete from "
2006 0 . $p{CFG}->{'EDTK_DBI_TRACKING'}
2007 . " where ed_tstamp < '"
2008 . ( strftime "%Y%m%d", localtime($DAYS_TRACKED_time) )
2009 . "000000'";
2010 0 &logger( 7, $sql );
2011  
2012 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2013 0 ▶ $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_TRACKING'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, q[ERROR: can't update ] . $p{"CFG"}{"EDTK_DBI_TRACKING"}) or return 0 0 0
2014 or return;
2015 0 $p{DBH}->disconnect;
2016 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2017 0 ▶ $reportActions .= "-PURGE TRACKING=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2018  
2019 # PURGE FROM EDTK_DBI_DISTRIB_STATS
2020 $sql =
2021 "delete from "
2022 0 . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'}
2023 . " where ed_dtlot < '"
2024 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) )
2025 . "'"; # note: NOT REGEXP_LIKE (ED_DTLOT, '\d\d\d\d-\d\d-\d\d') does not work on MySQL...
2026 0 &logger( 7, $sql );
2027  
2028 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2029 $result =
2030 0 ▶ _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, q[ERROR: can't update ] . $p{"CFG"}{"EDTK_DBI_DISTRIB_STATS"}) or return 0 0 0
2031 or return;
2032 0 $p{DBH}->disconnect;
2033 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2034 0 ▶ $reportActions .= "-PURGE DISTRIB_S=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2035  
2036 # PURGE FROM OUTMNGR_STATS
2037 $sql =
2038 "delete from "
2039 0 . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'}
2040 . " where ed_dtlot < '"
2041 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) ) . "'";
2042 0 &logger( 7, $sql );
2043  
2044 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2045 $result =
2046 0 ▶ _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, q[ERROR: can't update ] . $p{"CFG"}{"EDTK_DBI_OUTMNGR_STATS"}) or return 0 0 0
2047 or return;
2048 0 $p{DBH}->disconnect;
2049 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2050 0 ▶ $reportActions .= "-PURGE OUTMNGR_S=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2051  
2052 # PURGE FROM EDTK_AGREGE
2053 0 $sql =
2054 "delete from edtk_agrege "
2055 . " where ed_dtlot < '"
2056 . ( strftime "%Y-%m-%d", localtime($DAYS_AGREGED_time) ) . "'";
2057 0 &logger( 7, $sql );
2058  
2059 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2060 0 ▶ $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update EDTK_AGREGE" ) or return;
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, "ERROR: can't update EDTK_AGREGE") or return 0 0 0
2061 0 $p{DBH}->disconnect;
2062 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2063 0 ▶ $reportActions .= "-PURGE AGREGE=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2064  
2065 ### EDTK_ID ###
2066 # PURGE FROM EDTK_ID
2067 0 $sql =
2068 "delete from edtk_id"
2069 . " where ed_id_date < '"
2070 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2071 0 &logger( 7, $sql );
2072  
2073 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2074 $result =
2075 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2076 0 $p{DBH}->disconnect;
2077 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2078 0 ▶ $reportActions .= "-PURGE EDTK_ID=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2079  
2080 0 return &logger( 6, $reportActions );
2081 }
2082  
2083 0 ▶sub _acheck_db_rotate {
Subroutine _acheck_db_rotate: not called CC=13 SCAR=52.0
2084 0 my %p = @_;
2085  
2086 # my $time =time;
2087 # my $date =strftime "%Y-%m-%d", localtime;
2088 # my $day =strftime "%d", localtime;
2089 # my $pid =$$;
2090 0 my ( $sql, $insert, $result, $reportActions );
2091 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2092  
2093 # Repatriate any pending backup rows before rotating / purging.
2094 0 eval { _db_maybe_reconcile( $p{DBH}, $p{CFG} ); };
2095 0 my $stamp = strftime "%Y%m%d%H%M%S", localtime;
2096  
2097 0 my $DAYS_KEPT_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT} );
2098 0 my $DAYS_KEPT_STATS_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
2099 0 my $DAYS_TRACKED_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} );
2100 my $DAYS_AGREGED_time = time -
2101 0 ▶ ( 86400 * ( $p{CFG}->{EDTK_DB_MAX_DAYS_AGREGED} || $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} ) );
Condition0%0/3
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} || $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} || $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
$p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'} $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
Truth table0%0/3
A || B
A= $p{'CFG'}{'EDTK_DB_MAX_DAYS_AGREGED'}B= $p{'CFG'}{'EDTK_DB_MAX_DAYS_TRACKED'}
ABresult
1X1
011
000
2102  
2103 ### ROTATIONS ###
2104 ### EDTK_AGREGE ###
2105 # MOVE DATA TO EDTK_AGREGE
2106 $sql =
2107 "insert into edtk_agrege "
2108 . "select "
2109 . "i.ed_source, "
2110 . "d.ed_chanel_out, "
2111 . "i.ed_refiddoc, "
2112 . "i.ed_idproduct, "
2113 . "i.ed_dtedtion, "
2114 . "count(distinct d.ed_idldoc) as ed_cntd_idldoc, "
2115 . "count(d.ed_idseqpg) as ed_cnt_idseqpg, "
2116 . "d.ed_dtlot, "
2117 . "d.ed_idlot, "
2118 . "d.ed_idjob, "
2119 . $stamp
2120 . " from "
2121 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2122 . " as i "
2123 . "inner join "
2124 0 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2125 . " as d on d.ed_idldoc = i.ed_idldoc "
2126 . "and d.ed_idseqpg = i.ed_idseqpg "
2127 . "and d.ed_seqdoc = i.ed_seqdoc "
2128 . "and d.ed_idjob = i.ed_idjob "
2129 . "where d.ed_dtlot < '"
2130 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "' "
2131 . "group by "
2132 . "i.ed_source, "
2133 . "d.ed_chanel_out, "
2134 . "i.ed_refiddoc, "
2135 . "i.ed_idproduct,"
2136 . "i.ed_dtedtion, "
2137 . "d.ed_dtlot, "
2138 . "d.ed_idlot, "
2139 . "d.ed_idjob ";
2140 0 &logger( 7, "SQL = $sql" );
2141  
2142 0 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update EDTK_AGREGE", fatal => 1 );
2143 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2144 0 ▶ $reportActions .= "-MV AGREGE=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2145  
2146 ### DISTRIB ###
2147 # MOVE DATA FROM DISTRIB TO DISTRIB_STATS
2148 $sql =
2149 "insert into "
2150 . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'}
2151 . " select * from "
2152 0 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2153 . " where ed_dtlot < '"
2154 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2155 0 &logger( 7, $sql );
2156  
2157 $result =
2158 0 ▶ _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, q[ERROR: can't update ] . $p{"CFG"}{"EDTK_DBI_DISTRIB_STATS"}) or return 0 0 0
2159 or return;
2160 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2161 0 ▶ $reportActions .= "-MV DISTRIB=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2162  
2163 # CLEAN DISTRIB
2164 $sql =
2165 "delete from "
2166 0 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2167 . " where ed_dtlot < '"
2168 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2169 0 &logger( 7, $sql );
2170  
2171 $result =
2172 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} );
2173 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2174 0 ▶ $reportActions .= "/" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2175  
2176 ### OUTMNGR ###
2177 # MOVE DATA FROM OUTMNGR TO OUTMNGR_STATS
2178 $sql =
2179 "insert into "
2180 . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'}
2181 . " select * from "
2182 0 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2183 . " where ed_dtlot < '"
2184 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2185 0 &logger( 7, $sql );
2186  
2187 $result =
2188 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2189 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2190 0 ▶ $reportActions .= "-MV OUTMNGR=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2191  
2192 # CLEAN OUTMNGR
2193 $sql =
2194 "delete from "
2195 0 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2196 . " where ed_dtlot < '"
2197 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2198 0 &logger( 7, $sql );
2199  
2200 $result =
2201 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2202 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2203 0 ▶ $reportActions .= "/" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2204  
2205 0 $p{DBH}->disconnect;
2206 0 return ( 4, $reportActions );
2207 }
2208  
2209 0 ▶sub agrege_idJob {
Subroutine agrege_idJob: not called CC=12 SCAR=50.5
Pod documented
2210  
2211 # EXAMPLE CALL:
2212 # agrege_idJob (CFG => $cfg, IDJOB => 'IdJob');
2213 0 my %p = @_;
2214 0 my $stamp = strftime "%Y%m%d%H%M%S", localtime;
2215 0 &logger( 6, "p{CFG} = " . $p{CFG} . " - p{IDJOB} " . $p{IDJOB} );
2216  
2217 0 my ( $sql, $insert, $result, $reportActions );
2218 0 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2219  
2220 # Repatriate any pending backup rows before aggregating.
2221 0 eval { _db_maybe_reconcile( $p{DBH}, $p{CFG} ); };
2222  
2223 ### ROTATIONS JobID ###
2224 ### EDTK_AGREGE ###
2225 # MOVE DATA TO EDTK_AGREGE
2226  
2227 $sql =
2228 "insert into edtk_agrege "
2229 . "select "
2230 . "i.ed_source, "
2231 . "d.ed_chanel_out, "
2232 . "i.ed_refiddoc, "
2233 . "i.ed_idproduct, "
2234 . "i.ed_dtedtion, "
2235 . "count(distinct d.ed_idldoc) as ed_cntd_idldoc, "
2236 . "count(d.ed_idseqpg) as ed_cnt_idseqpg, "
2237 . "d.ed_dtlot, "
2238 . "d.ed_idlot, "
2239 . "d.ed_idjob, "
2240 . $stamp
2241 . " from "
2242 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2243 . " as i "
2244 . "inner join "
2245 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2246 . " as d on d.ed_idldoc = i.ed_idldoc "
2247 . "and d.ed_idseqpg = i.ed_idseqpg "
2248 . "and d.ed_seqdoc = i.ed_seqdoc "
2249 . "and d.ed_idjob = i.ed_idjob "
2250 . "where d.ed_idjob = '"
2251 0 . $p{IDJOB} . "' "
2252 . "group by "
2253 . "i.ed_source, "
2254 . "d.ed_chanel_out, "
2255 . "i.ed_refiddoc, "
2256 . "i.ed_idproduct,"
2257 . "i.ed_dtedtion, "
2258 . "d.ed_dtlot, "
2259 . "d.ed_idlot, "
2260 . "d.ed_idjob ";
2261 0 &logger( 7, "SQL = $sql" );
2262  
2263 0 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update edtk_agrege", fatal => 1 );
2264 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2265 0 ▶ $reportActions .= "-MV AGREGE=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2266  
2267 ### DISTRIB ###
2268 # MOVE DATA FROM DISTRIB TO DISTRIB_STATS
2269 $sql =
2270 "insert into "
2271 . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'}
2272 . " select * from "
2273 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2274 . " where ed_idjob = '"
2275 0 . $p{IDJOB} . "'";
2276 0 &logger( 7, $sql );
2277  
2278 $result =
2279 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
2280 0 ▶ or do { $p{DBH}->disconnect; return ( 4, $reportActions ); };
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($p{"DBH"}, $sql, q[ERROR: can't update ] . $p{"CFG"}{"EDTK_DBI_DISTRIB_STATS"}) or do { $p{"DBH"}->disconnect; return 4, $reportActions } 0 0 0
2281 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2282 0 ▶ $reportActions .= "-MV DISTRIB=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2283  
2284 # CLEAN DISTRIB
2285 0 $sql = "delete from " . $p{CFG}->{'EDTK_DBI_DISTRIB'} . " where ed_idjob = '" . $p{IDJOB} . "'";
2286 0 &logger( 7, $sql );
2287  
2288 $result =
2289 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} );
2290 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2291 0 ▶ $reportActions .= "/" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2292  
2293 ### OUTMNGR ###
2294 # MOVE DATA FROM OUTMNGR TO OUTMNGR_STATS
2295 $sql =
2296 "insert into "
2297 . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'}
2298 . " select * from "
2299 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2300 . " where ed_idjob = '"
2301 0 . $p{IDJOB} . "'";
2302 0 &logger( 7, $sql );
2303  
2304 $result =
2305 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2306 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2307 0 ▶ $reportActions .= "-MV OUTMNGR=" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2308  
2309 # CLEAN OUTMNGR
2310 0 $sql = "delete from " . $p{CFG}->{'EDTK_DBI_OUTMNGR'} . " where ed_idjob = '" . $p{IDJOB} . "'";
2311 0 &logger( 7, $sql );
2312  
2313 $result =
2314 0 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2315 0 ▶ &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2316 0 ▶ $reportActions .= "/" . ( $result || 0 );
Condition0%0/2
$result || 0
l!l
00
MC/DC0%0/1
$result || 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2317  
2318 0 $p{DBH}->disconnect;
2319 0 return ( 4, $reportActions );
2320 }
2321  
2322 0 ▶sub acheck_db_admin_on_connect {
Subroutine acheck_db_admin_on_connect: not called CC=41 SCAR=74.5
Pod documented
2323  
2324 # https://www.forknerds.com/reduce-the-size-of-mysql/
2325 # my ($level, $return) = acheck_db_admin_on_connect ($dbh, $cfg);
2326 0 my $dbh = shift;
2327 0 my $cfg = shift;
2328  
2329 # H1: this check must not re-enter itself. It reconciles the backup buffer,
2330 # which opens a backup handle through _db_connect1(); did that fire the check
2331 # again the calls would nest without bound. A dedicated guard is used rather
2332 # than moving $CONNECT_COUNT, which would change when the check first fires.
2333 0 ▶ return ( 5, "ACHECK already running in this process" ) if $IN_ACHECK;
Branch: 1 branch
BranchTrueFalseTotal
if $oEdtk::DBAdmin::IN_ACHECK 0 0 0
2334 0 local $IN_ACHECK = 1;
2335  
2336 0 eval { schema_StaleWarning( $dbh, cfg => $cfg ); };
2337  
2338 0 my $time = time;
2339 0 my $date = strftime "%Y-%m-%d", localtime;
2340 0 my $day = strftime "%d", localtime;
2341 0 my $pid = $$;
2342 0 my ( $sth, $sql, $insert, $result, $reportActions );
2343  
2344 0 my $DAYS_KEPT_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_KEPT} );
2345 0 my $DAYS_KEPT_STATS_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
2346 0 my $DAYS_TRACKED_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_TRACKED} );
2347 my $DAYS_AGREGED_time =
2348 0 ▶ time - ( 86400 * ( $cfg->{EDTK_DB_MAX_DAYS_AGREGED} || $cfg->{EDTK_DB_MAX_DAYS_TRACKED} ) );
Condition0%0/3
$cfg->{'EDTK_DB_MAX_DAYS_AGREGED'} || $cfg->{'EDTK_DB_MAX_DAYS_TRACKED'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$cfg->{'EDTK_DB_MAX_DAYS_AGREGED'} || $cfg->{'EDTK_DB_MAX_DAYS_TRACKED'}
$cfg->{'EDTK_DB_MAX_DAYS_AGREGED'} $cfg->{'EDTK_DB_MAX_DAYS_TRACKED'}
Truth table0%0/3
A || B
A= $cfg->{'EDTK_DB_MAX_DAYS_AGREGED'}B= $cfg->{'EDTK_DB_MAX_DAYS_TRACKED'}
ABresult
1X1
011
000
2349  
2350 #my $EDTK_DB_CHECK_MONTH_DAY = $cfg->{EDTK_DB_CHECK_MONTH_DAY} || 0; # to remove
2351  
2352 # Repatriate any pending backup rows before the maintenance check.
2353 0 eval { _db_maybe_reconcile( $dbh, $cfg ); };
2354  
2355 0 &logger( 6, "ACHECK Check START" );
2356  
2357 #LOOK FOR THE LAST ACTION ON THE ADMIN TABLE
2358 0 $sql =
2359 "select ed_action_date, ed_action_pid, ed_action_status, ed_action_duration, ed_oedtk_release from edtk_admin "
2360 . " where ed_action_date = '"
2361 . $date
2362 . "' "; #order by ed_action_date desc limit 1";
2363 0 &logger( 7, $sql );
2364  
2365 0 ▶ $sth = $dbh->prepare($sql) or return ( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
$sth = $dbh->prepare($sql) or return 3, $dbh->errstr 0 0 0
2366  
2367 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute() }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
2368 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2369  
2370 # HAS AN ADMINISTRATION ACTION ALREADY BEEN DONE TODAY ?
2371 0 my @tValues = $dbh->selectrow_array( $sql, undef )
2372 ; # or warn ("ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr);
2373 0 ▶ if ( $tValues[0] and $date eq $tValues[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tValues[0] and $date eq $tValues[0]) 0 0 0
Condition0%0/3
$tValues[0] and $date eq $tValues[0]
!ll&&!rl&&r
000
MC/DC0%0/2
$tValues[0] and $date eq $tValues[0]
$tValues[0] $date eq $tValues[0]
Truth table0%0/3
A and B
A= $tValues[0]B= $date eq $tValues[0]
ABresult
0X0
100
111
2374 0 &logger(
2375 6,
2376 (
2377 "Previously done, ACHECK Last EDTK_DB_MAX_DAYS check : "
2378 . $tValues[0] . " PID "
2379 . $tValues[1]
2380 )
2381 );
2382 0 return ( 5,
2383 ( "ACHECK Last EDTK_DB_MAX_DAYS check : " . $tValues[0] . " PID " . $tValues[1] ) );
2384 }
2385  
2386 # OTHERWISE, REQUEST A TICKET TO CARRY OUT THE ACTION
2387 $insert =
2388 0 'insert into edtk_admin (ed_action_date, ed_action_pid, ed_action_status, ed_oedtk_release) '
2389 . ' values (?, ?, ?, ?) ';
2390 0 $sth = $dbh->prepare_cached($insert);
2391  
2392 0 eval {
2393 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute( $date, $pid, "START", $VERSION ) }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute($date, $pid, "START", $oEdtk::DBAdmin::VERSION) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
2394 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2395 };
2396 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2397 0 &logger( 3, "ERROR: $@ into $insert" );
2398 }
2399  
2400 # CHECK THAT WE HOLD THE LOCK FOR THE ACTION
2401 0 $sth = $dbh->prepare($sql);
2402 0 ▶ do { local $sth->{PrintError} = 0; $sth->execute() }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 0 0 0
2403 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2404 0 ▶ @tValues = do { local $dbh->{PrintError} = 0; $dbh->selectrow_array( $sql, undef ) }
Branch: 1 branch
BranchTrueFalseTotal
@tValues = do { local $dbh->{"PrintError"} = 0; $dbh->selectrow_array($sql, undef) } or &logger(3, 'ERROR: in acheck_db_admin_on_connect, message is ' . $dbh->errstr) 0 0 0
2405 or &logger( 3, "ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr );
2406 0 $reportActions = "ACHECK Check 2 : " . $tValues[0] . " PID " . $tValues[1];
2407  
2408 0 ▶ if ( $date eq $tValues[0] and $pid eq $tValues[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date eq $tValues[0] and $pid eq $tValues[1]) { } 0 0 0
Condition0%0/3
$date eq $tValues[0] and $pid eq $tValues[1]
!ll&&!rl&&r
000
MC/DC0%0/2
$date eq $tValues[0] and $pid eq $tValues[1]
$date eq $tValues[0] $pid eq $tValues[1]
Truth table0%0/3
A and B
A= $date eq $tValues[0]B= $pid eq $tValues[1]
ABresult
0X0
100
111
2409 0 &logger( 5, $reportActions );
2410  
2411 # _db_admin_actions;
2412 }
2413 else {
2414 # another process did the action, giving up
2415 0 return ( 5, $reportActions );
2416 }
2417  
2418 ### PURGES ###
2419 # PURGE FROM OEDTK_ADMIN
2420 0 $sql = "delete from edtk_admin where ed_action_date < '"
2421 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2422 0 &logger( 7, $sql );
2423  
2424 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_ADMIN" ) or return;
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, "ERROR: can't update EDTK_ADMIN") or return 0 0 0
2425 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2426 0 ▶ $reportActions = "ACHECK PURGE edtk_admin=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2427  
2428 # PURGE FROM EDTK_DBI_TRACKING
2429 $sql =
2430 "delete from "
2431 0 . $cfg->{'EDTK_DBI_TRACKING'}
2432 . " where ed_tstamp < '"
2433 . ( strftime "%Y%m%d", localtime($DAYS_TRACKED_time) )
2434 . "000000'";
2435 0 &logger( 7, $sql );
2436  
2437 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_TRACKING'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, q[ERROR: can't update ] . $cfg->{"EDTK_DBI_TRACKING"}) or return 0 0 0
2438 or return;
2439 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2440 0 ▶ $reportActions .= "-PURGE tracking=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2441  
2442 # PURGE FROM EDTK_DBI_DISTRIB_STATS
2443 $sql =
2444 "delete from "
2445 0 . $cfg->{'EDTK_DBI_DISTRIB_STATS'}
2446 . " where ed_dtlot < '"
2447 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) )
2448 . "'"; # note: NOT REGEXP_LIKE (ED_DTLOT, '\d\d\d\d-\d\d-\d\d') does not work on MySQL...
2449 0 &logger( 7, $sql );
2450  
2451 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, q[ERROR: can't update ] . $cfg->{"EDTK_DBI_DISTRIB_STATS"}) or return 0 0 0
2452 or return;
2453 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2454 0 ▶ $reportActions .= "-PURGE distrib_s=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2455  
2456 # PURGE FROM OUTMNGR_STATS
2457 $sql =
2458 "delete from "
2459 0 . $cfg->{'EDTK_DBI_OUTMNGR_STATS'}
2460 . " where ed_dtlot < '"
2461 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) ) . "'";
2462 0 &logger( 7, $sql );
2463  
2464 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, q[ERROR: can't update ] . $cfg->{"EDTK_DBI_OUTMNGR_STATS"}) or return 0 0 0
2465 or return;
2466 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2467 0 ▶ $reportActions .= "-PURGE outmngr_s=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2468  
2469 # PURGE FROM EDTK_AGREGE
2470 0 $sql =
2471 "delete from edtk_agrege "
2472 . " where ed_dtlot < '"
2473 . ( strftime "%Y-%m-%d", localtime($DAYS_AGREGED_time) ) . "'";
2474 0 &logger( 7, $sql );
2475  
2476 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_AGREGE" ) or return;
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, "ERROR: can't update EDTK_AGREGE") or return 0 0 0
2477 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2478 0 ▶ $reportActions .= "-PURGE agrege=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2479 0 my $stamp = strftime "%Y%m%d%H%M%S", localtime;
2480  
2481 ### MOVE / PURGE ###
2482 ### EDTK_AGREGE ###
2483 # MOVE DATA TO EDTK_AGREGE
2484 $sql =
2485 "insert into edtk_agrege "
2486 . "select "
2487 . "i.ed_source, "
2488 . "d.ed_chanel_out, "
2489 . "i.ed_refiddoc, "
2490 . "i.ed_idproduct, "
2491 . "i.ed_dtedtion, "
2492 . "count(distinct d.ed_idldoc) as ed_cntd_idldoc, "
2493 . "count(d.ed_idseqpg) as ed_cnt_idseqpg, "
2494 . "d.ed_dtlot, "
2495 . "d.ed_idlot, "
2496 . "d.ed_idjob, "
2497 . $stamp
2498 . " from "
2499 . $cfg->{'EDTK_DBI_OUTMNGR'}
2500 . " as i "
2501 . "inner join "
2502 0 . $cfg->{'EDTK_DBI_DISTRIB'}
2503 . " as d on d.ed_idldoc = i.ed_idldoc "
2504 . "and d.ed_idseqpg = i.ed_idseqpg "
2505 . "and d.ed_seqdoc = i.ed_seqdoc "
2506 . "and d.ed_idjob = i.ed_idjob "
2507 . " where d.ed_dtlot < '"
2508 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'"
2509 . "group by "
2510 . "i.ed_source, "
2511 . "d.ed_chanel_out, "
2512 . "i.ed_refiddoc, "
2513 . "i.ed_idproduct,"
2514 . "i.ed_dtedtion, "
2515 . "d.ed_dtlot, "
2516 . "d.ed_idlot, "
2517 . "d.ed_idjob ";
2518 0 &logger( 7, "SQL = $sql" );
2519  
2520 0 $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_AGREGE", fatal => 1 );
2521 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2522 0 ▶ $reportActions .= "-MV agrege=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2523  
2524 ### DISTRIB ###
2525 # MOVE DATA FROM DISTRIB TO DISTRIB_STATS
2526 $sql =
2527 "insert into "
2528 . $cfg->{'EDTK_DBI_DISTRIB_STATS'}
2529 . " select * from "
2530 0 . $cfg->{'EDTK_DBI_DISTRIB'}
2531 . " where ed_dtlot < '"
2532 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2533 0 &logger( 7, $sql );
2534  
2535 0 ▶ $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} )
Branch: 1 branch
BranchTrueFalseTotal
$result = _db_do_log($dbh, $sql, q[ERROR: can't update ] . $cfg->{"EDTK_DBI_DISTRIB_STATS"}) or return 0 0 0
2536 or return;
2537 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2538 0 ▶ $reportActions .= "-MV distrib=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2539  
2540 # CLEAN DISTRIB
2541 $sql =
2542 "delete from "
2543 0 . $cfg->{'EDTK_DBI_DISTRIB'}
2544 . " where ed_dtlot < '"
2545 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2546 0 &logger( 7, $sql );
2547  
2548 0 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} );
2549 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2550 0 ▶ $reportActions .= "/" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2551  
2552 ### OUTMNGR ###
2553 # MOVE DATA FROM OUTMNGR TO OUTMNGR_STATS
2554 $sql =
2555 "insert into "
2556 . $cfg->{'EDTK_DBI_OUTMNGR_STATS'}
2557 . " select * from "
2558 0 . $cfg->{'EDTK_DBI_OUTMNGR'}
2559 . " where ed_dtlot < '"
2560 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2561 0 &logger( 7, $sql );
2562  
2563 0 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2564 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2565 0 ▶ $reportActions .= "-MV outmngr=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2566  
2567 # CLEAN OUTMNGR
2568 $sql =
2569 "delete from "
2570 0 . $cfg->{'EDTK_DBI_OUTMNGR'}
2571 . " where ed_dtlot < '"
2572 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2573 0 &logger( 7, $sql );
2574  
2575 0 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2576 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2577 0 ▶ $reportActions .= "/" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2578  
2579 ### EDTK_ID ###
2580 # PURGE FROM EDTK_ID
2581 0 $sql =
2582 "delete from edtk_id"
2583 . " where ed_id_date < '"
2584 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2585 0 &logger( 7, $sql );
2586  
2587 0 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2588 0 ▶ &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2589 0 ▶ $reportActions .= "-PURGE edtk_id=" . ( $result // 0 );
Condition0%0/2
$result // 0
l!l
00
MC/DC0%0/1
$result // 0
$result
Truth table0%0/2
A
A= $result
Aresult
11
00
2590  
2591 # End of the run
2592 0 $time = _elapsed_seconds($time);
2593 0 $sql =
2594 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?';
2595 0 _db_do_log(
2596 $dbh, $sql,
2597 "ERROR: can't update ED_ACTION_STATUS",
2598 bind => [ "DONE", $time, $date ]
2599 );
2600  
2601 0 return ( 4, $reportActions );
2602 }
2603  
2604 32 our @TRACKER_COLS = (
2605 [ 'ed_tstamp', 'varchar2(14) not null' ], # timestamp of event
2606 [ 'ed_sngl_id', 'varchar2(36) not null' ]
2607 , # ed_idldoc single id : 36-char UUID (S70, D1); was the 16-digit YWWWDHHMMSSPPPP.r format
2608 [ 'ed_seq', 'integer not null' ], # sequence
2609 [ 'ed_app', 'varchar2(20) not null' ], #xx ed_refiddoc application name
2610  
2611 [ 'ed_user', 'varchar2(10) not null' ], # user for the job or request
2612 [ 'ed_corp', 'varchar2(8) not null' ], # entity related
2613 [ 'ed_account', 'varchar2(8)' ], # administrative account
2614 [ 'ed_mod_ed', 'char(1)' ], # editing mode (undef, batch, tp, web, mail, probing)
2615 [ 'ed_job_evt', 'char(1)' ]
2616 , # level of the event (job (default), spool, document, line, warning, error, halt (critic), reject)
2617 [ 'ed_obj_typ', 'varchar2(3)' ], # to define the object concerned
2618 [ 'ed_obj_count', 'integer' ], # number of objects attached to the event
2619 [ 'ed_child_typ', 'varchar2(3)' ], # to define the object concerned
2620 [ 'ed_child_id', 'varchar2(36)' ]
2621 , # ed_idldoc single id : 36-char UUID (S70, D1); was the 16-digit YWWWDHHMMSSPPPP.r format
2622 [ 'ed_parent_id', 'varchar2(36)' ]
2623 , # ed_idldoc single id : 36-char UUID (S70, D1); was the 16-digit YWWWDHHMMSSPPPP.r format
2624  
2625 [ 'ed_host', 'varchar2(32)' ]
2626 , # hostname for input stream of this document (max length for smtp is 31, could be 255...)
2627 [ 'ed_source', 'varchar2(128)' ], # input stream of this document
2628 [ 'ed_message', 'varchar2(256)' ] # treatment message
2629  
2630 );
2631  
2632 7 ▶sub create_table_TRACKING {
Subroutine create_table_TRACKING: called CC=6 SCAR=18.9
Pod documented
2633 7 my ( $dbh, $table, $maxkeys ) = @_;
2634  
2635 my $sql = "create table if not exists $table ("
2636 7 . join( ', ', map { "$$_[0] $$_[1]" } @TRACKER_COLS ) . ", ";
2637  
2638 7 foreach my $i ( 0 .. $maxkeys ) {
2639 39 $sql .= " ed_k${i}_NAME VARCHAR2(8),"; # Name of key $i
2640 39 $sql .= " ed_k${i}_VAL VARCHAR2(128)"; # Value of key $i
2641 39 ▶ $sql .= "," unless ( $i == $maxkeys );
Branch: 1 branch
BranchTrueFalseTotal
unless $i == $maxkeys 32 7 39
2642 }
2643 7 $sql .= " )";
2644 7 $sql .= _db_engine_clause($dbh);
2645 7 &logger( 7, $sql );
2646 7 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 7 0 7
2647  
2648 # my $idx = "ix_".$table."_".$VERSION_TXT;
2649 7 my $idx = "ix_" . $table;
2650 7 $sql = "create index if not exists $idx on $table " . " (ed_tstamp);";
2651 7 &logger( 7, $sql );
2652 7 ▶ _db_do_ddl( $dbh, $sql )
Branch: 1 branch
BranchTrueFalseTotal
if _db_check_driver_name($dbh) ne "SQLite" 0 7 7
Condition16%1/6
_db_check_driver_name($dbh) ne 'SQLite' && (_db_do_ddl($dbh, $sql) || &logger(3, $dbh->errstr))
!ll&&!rl&&r
700
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr)
l!l&&r!l&&!r
000
MC/DC0%0/3
_db_check_driver_name($dbh) ne 'SQLite' && (_db_do_ddl($dbh, $sql) || &logger(3, $dbh->errstr))
_db_check_driver_name($dbh) ne 'SQLite' _db_do_ddl($dbh, $sql) &logger(3, $dbh->errstr)
Truth table0%0/4
A && B or C
A= _db_check_driver_name($dbh) ne 'SQLite'B= _db_do_ddl($dbh, $sql)C= &logger(3, $dbh->errstr)
ABCresult
0XX0
1000
11X1
1011
2653 or &logger( 3, $dbh->errstr )
2654 if ( _db_check_driver_name($dbh) ne "SQLite" );
2655  
2656 }
2657  
2658 1 ▶sub db_drop_table {
Subroutine db_drop_table: called CC=2 SCAR=7.1
Pod documented
2659 1 my ( $dbh, $table ) = @_;
2660 1 my $sql = "drop table $table";
2661  
2662 1 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 1 0 1
2663 }
2664  
2665 # ============================================================
2666 # Backup-buffer ("store-and-forward") repatriation.
2667 #
2668 # When the main database server is unreachable, db_connect silently falls back
2669 # to the ${dsnvar}_BAK database (a SQLite buffer) and every write accumulates
2670 # there. The routines below are the missing "return" half: they detect pending
2671 # rows and copy them back into the main database, idempotently.
2672 #
2673 # Design note: no high-water-mark table is kept. Repatriation is made
2674 # idempotent by an "insert if the natural key is absent" test plus a full drain
2675 # of the buffer on success, so a crash or a re-run cannot duplicate nor lose a
2676 # row. The buffer holds only event tables: edtk_agrege is recomputed from its
2677 # sources and edtk_admin is per-database coordination, so both are excluded.
2678 # ============================================================
2679  
2680 # Is a distinct backup database configured?
2681 11 ▶sub db_backup_available {
Subroutine db_backup_available: called CC=7 SCAR=20.5
Pod documented
2682 11 my ($cfg) = @_;
2683 11 ▶ return 0 unless $cfg && defined $cfg->{'EDTK_DBI_DSN_BAK'};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg and defined $cfg->{"EDTK_DBI_DSN_BAK"} 0 11 11
Condition33%1/3
$cfg and defined $cfg->{"EDTK_DBI_DSN_BAK"}
!ll&&!rl&&r
0011
MC/DC0%0/2
$cfg and defined $cfg->{"EDTK_DBI_DSN_BAK"}
$cfg defined $cfg->{"EDTK_DBI_DSN_BAK"}
Truth table33%1/3
A and B
A= $cfgB= defined $cfg->{"EDTK_DBI_DSN_BAK"}
ABresult
0X0
100
111
2684 11 ▶ my $main = $cfg->{'EDTK_DBI_DSN'} // '';
Condition50%1/2
$cfg->{"EDTK_DBI_DSN"} // ""
l!l
110
MC/DC0%0/1
$cfg->{"EDTK_DBI_DSN"} // ""
$cfg->{"EDTK_DBI_DSN"}
Truth table50%1/2
A
A= $cfg->{"EDTK_DBI_DSN"}
Aresult
11
00
2685 11 ▶ my $bak = $cfg->{'EDTK_DBI_DSN_BAK'} // '';
Condition50%1/2
$cfg->{"EDTK_DBI_DSN_BAK"} // ""
l!l
110
MC/DC0%0/1
$cfg->{"EDTK_DBI_DSN_BAK"} // ""
$cfg->{"EDTK_DBI_DSN_BAK"}
Truth table50%1/2
A
A= $cfg->{"EDTK_DBI_DSN_BAK"}
Aresult
11
00
2686 11 ▶ return 0 if $bak eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $bak eq "" 1 10 11
2687 10 ▶ return 0 if $bak eq $main; # anti-loop guard: backup == main
Branch: 1 branch
BranchTrueFalseTotal
if $bak eq $main 1 9 10
2688 9 return 1;
2689 }
2690  
2691 # Does this handle point at the backup buffer?
2692 5 ▶sub db_on_backup {
Subroutine db_on_backup: called CC=3 SCAR=11.1
Pod documented
2693 5 my ($dbh) = @_;
2694 5 ▶ return ( defined $dbh && $dbh->{'private_oEdtk_on_backup'} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $dbh && $dbh->{'private_oEdtk_on_backup'} ? : 1 4 5
Condition66%2/3
defined $dbh and $dbh->{"private_oEdtk_on_backup"}
!ll&&!rl&&r
041
MC/DC50%1/2
defined $dbh and $dbh->{"private_oEdtk_on_backup"}
defined $dbh $dbh->{"private_oEdtk_on_backup"}
Truth table66%2/3
A and B
A= defined $dbhB= $dbh->{"private_oEdtk_on_backup"}
ABresult
0X0
100
111
2695 }
2696  
2697 # Canonical identity of the database behind a handle, so two handles opened from
2698 # different DSN strings that resolve to the SAME database can be told apart from
2699 # genuinely distinct ones. Returns a string key, or undef when the driver cannot
2700 # be interrogated (Oracle, "NC"): the caller then cannot prove sameness.
2701 6 ▶sub _db_identity {
Subroutine _db_identity: called CC=15 SCAR=39.9
2702 6 my ($dbh) = @_;
2703 6 ▶ return unless defined $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbh 0 6 6
2704 6 my $drv = eval { _db_check_driver_name($dbh) };
2705 6 ▶ return unless defined $drv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $drv 0 6 6
2706 6 return do {
2707 6 local $dbh->{PrintError} = 0;
2708 6 local $dbh->{RaiseError} = 0;
2709 6 my @parts;
2710 6 ▶ if ( $drv eq 'SQLite' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($drv eq 'SQLite') { } 6 0 6
elsif ($drv eq 'PostgreSQL') { } 0 0 0
elsif ($drv eq 'mysql') { } 0 0 0
2711  
2712 # PRAGMA database_list canonicalizes the file path, so ".../main.db"
2713 # and "..././main.db" resolve to the same absolute path.
2714 6 my $rows = eval { $dbh->selectall_arrayref('pragma database_list') };
2715 6 ▶ my ($main) = grep { $_->[1] eq 'main' } @{ $rows || [] };
Condition50%1/2
$rows || []
l!l
60
MC/DC0%0/1
$rows || []
$rows
Truth table50%1/2
A
A= $rows
Aresult
11
00
2716 6 ▶ push @parts, 'sqlite', ( $main ? ( $main->[2] // '' ) : '' );
Branch: 1 branch
BranchTrueFalseTotal
$main ? : 6 0 6
Condition50%1/2
$main->[2] // ""
l!l
60
MC/DC0%0/1
$main->[2] // ""
$main->[2]
Truth table50%1/2
A
A= $main->[2]
Aresult
11
00
2717 }
2718 elsif ( $drv eq 'PostgreSQL' ) {
2719 0 my ( $d, $h, $p ) = eval {
2720 0 $dbh->selectrow_array(
2721 'select current_database(), inet_server_addr()::text, inet_server_port()');
2722 };
2723 0 ▶ push @parts, 'pg', ( $d // '' ), ( $h // '' ), ( $p // '' );
Condition0%0/6
$d // ""
l!l
00
$h // ""
l!l
00
$p // ""
l!l
00
MC/DC0%0/1
$d // ""
$d
MC/DC0%0/1
$h // ""
$h
MC/DC0%0/1
$p // ""
$p
Truth table0%0/2
A
A= $d
Aresult
11
00
Truth table0%0/2
A
A= $h
Aresult
11
00
Truth table0%0/2
A
A= $p
Aresult
11
00
2724 }
2725 elsif ( $drv eq 'mysql' ) {
2726 my ( $d, $h, $p ) =
2727 0 eval { $dbh->selectrow_array('select database(), @@hostname, @@port') };
2728 0 ▶ push @parts, 'mysql', ( $d // '' ), ( $h // '' ), ( $p // '' );
Condition0%0/6
$d // ""
l!l
00
$h // ""
l!l
00
$p // ""
l!l
00
MC/DC0%0/1
$d // ""
$d
MC/DC0%0/1
$h // ""
$h
MC/DC0%0/1
$p // ""
$p
Truth table0%0/2
A
A= $d
Aresult
11
00
Truth table0%0/2
A
A= $h
Aresult
11
00
Truth table0%0/2
A
A= $p
Aresult
11
00
2729 }
2730 0 else { return }
2731 6 return join "\0", @parts;
2732 };
2733 }
2734  
2735 # True when the two handles designate the same physical database. Conservative:
2736 # when either identity cannot be established, the answer is "different" so a
2737 # legitimate reconcile is never refused on a mere guess.
2738 3 ▶sub _db_same_database {
Subroutine _db_same_database: called CC=4 SCAR=15.2
2739 3 my ( $a, $b ) = @_;
2740 3 my $ka = _db_identity($a);
2741 3 my $kb = _db_identity($b);
2742 3 ▶ return 0 unless defined $ka && defined $kb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ka and defined $kb 0 3 3
Condition33%1/3
defined $ka and defined $kb
!ll&&!rl&&r
003
MC/DC0%0/2
defined $ka and defined $kb
defined $ka defined $kb
Truth table33%1/3
A and B
A= defined $kaB= defined $kb
ABresult
0X0
100
111
2743 3 ▶ return $ka eq $kb ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ka eq $kb ? : 0 3 3
2744 }
2745  
2746 # Open the backup buffer (never fatal, never blocking).
2747 4 ▶sub _db_backup_connect {
Subroutine _db_backup_connect: called CC=4 SCAR=14.3
2748 4 my ($cfg) = @_;
2749 4 ▶ return unless db_backup_available($cfg);
Branch: 1 branch
BranchTrueFalseTotal
unless db_backup_available($cfg) 0 4 4
2750  
2751 # H1: the probe must not trigger the automatic maintenance check (it would
2752 # reconcile the very buffer we are about to read) and must not pause: no
2753 # retry loop, and the check forced off on this connection.
2754 4 my %bcfg = ( %$cfg, EDTK_WAITRUN => 0, EDTK_DB_CHECK_AUTO => 'NO' );
2755 4 my $bak = eval {
2756 _db_connect1(
2757 \%bcfg,
2758 'EDTK_DBI_DSN_BAK',
2759 {
2760 4 ▶ FetchHashKeyName => $cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc',
Condition50%1/2
$cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc'
l!l
40
MC/DC0%0/1
$cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc'
$cfg->{'EDTK_DB_FetchHashKeyName'}
Truth table50%1/2
A
A= $cfg->{'EDTK_DB_FetchHashKeyName'}
Aresult
11
00
2761 AutoCommit => 1
2762 }
2763 );
2764 };
2765  
2766 # H1/H3: flag the handle the moment it is opened, so db_on_backup() stops a
2767 # reconcile from running against the buffer itself.
2768 4 ▶ $bak->{'private_oEdtk_on_backup'} = 1 if defined $bak;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bak 4 0 4
2769 4 return $bak;
2770 }
2771  
2772 # Tables repatriated from the buffer, in dependency order, with the natural key
2773 # used for the idempotent "insert if absent" test.
2774 4 ▶sub _backup_table_registry {
Subroutine _backup_table_registry: called CC=5 SCAR=16.8
2775 4 my ($cfg) = @_;
2776 4 my @t;
2777 push @t,
2778 { table => $cfg->{'EDTK_DBI_TRACKING'}, keys => [qw(ed_tstamp ed_sngl_id ed_seq ed_app)] }
2779 4 ▶ if $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_TRACKING"} 4 0 4
2780 push @t, { table => $cfg->{'EDTK_DBI_ACQUIT'}, keys => [qw(ed_seqlot ed_lotname ed_dtpost)] }
2781 4 ▶ if $cfg->{'EDTK_DBI_ACQUIT'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_ACQUIT"} 4 0 4
2782 4 push @t, { table => 'edtk_id', keys => [qw(ed_id_value)] };
2783 push @t,
2784 {
2785 table => $cfg->{'EDTK_DBI_OUTMNGR'},
2786 keys => [qw(ed_idldoc ed_seqdoc ed_idseqpg ed_idjob)]
2787 }
2788 4 ▶ if $cfg->{'EDTK_DBI_OUTMNGR'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_OUTMNGR"} 4 0 4
2789 push @t,
2790 {
2791 table => $cfg->{'EDTK_DBI_DISTRIB'},
2792 keys => [qw(ed_idldoc ed_seqdoc ed_idseqpg ed_idjob)]
2793 }
2794 4 ▶ if $cfg->{'EDTK_DBI_DISTRIB'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_DISTRIB"} 4 0 4
2795 4 return @t;
2796 }
2797  
2798 # Guarantee the backup buffer can hold the event tables (resolves TODO in db_connect).
2799 1 ▶sub db_backup_prepare {
Subroutine db_backup_prepare: called CC=5 SCAR=17.1
Pod documented
2800 1 my ($bak_dbh) = @_;
2801 1 ▶ return 0 unless defined $bak_dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bak_dbh 0 1 1
2802 1 my $ok = eval {
2803 1 my $cfg = config_read('EDTK_DB');
2804 1 schema_Create($bak_dbh);
2805  
2806 # schema_Create does not create the tracking table (db_connect does), but
2807 # the buffer must be able to hold tracking rows.
2808 1 ▶ unless ( _table_exists( $bak_dbh, $cfg->{'EDTK_DBI_TRACKING'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_table_exists($bak_dbh, $cfg->{"EDTK_DBI_TRACKING"})) 0 1 1
2809 create_table_TRACKING(
2810 $bak_dbh,
2811 $cfg->{'EDTK_DBI_TRACKING'},
2812 0 $cfg->{'EDTK_MAX_USER_KEY'}
2813 );
2814 }
2815 1 1;
2816 };
2817 1 ▶ &logger( 3, "db_backup_prepare: could not prepare the backup schema: $@" ) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 1 1
2818 1 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1 0 1
2819 }
2820  
2821 # Count pending rows per buffer table (read-only detection).
2822 1 ▶sub db_backup_pending {
Subroutine db_backup_pending: called CC=6 SCAR=18.4
Pod documented
2823 1 my ($cfg) = @_;
2824 1 my %pending;
2825 1 ▶ return \%pending unless db_backup_available($cfg);
Branch: 1 branch
BranchTrueFalseTotal
unless db_backup_available($cfg) 0 1 1
2826 1 my $bak = _db_backup_connect($cfg);
2827 1 ▶ unless ($bak) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bak) 0 1 1
2828 0 &logger( 7, "db_backup_pending: backup database unreachable" );
2829 0 return \%pending;
2830 }
2831 1 for my $t ( _backup_table_registry($cfg) ) {
2832 5 my $n = eval { my ($c) = $bak->selectrow_array("select count(*) from $t->{table}"); $c };
2833 5 ▶ $pending{ $t->{table} } = $n if defined $n && $n > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and $n > 0 3 2 5
Condition66%2/3
defined $n and $n > 0
!ll&&!rl&&r
023
MC/DC50%1/2
defined $n and $n > 0
defined $n $n > 0
Truth table66%2/3
A and B
A= defined $nB= $n > 0
ABresult
0X0
100
111
2834 }
2835 1 eval { $bak->disconnect };
2836 1 return \%pending;
2837 }
2838  
2839 # Copy the pending rows of ONE buffer table into the main database, then drain
2840 # the buffer table when the whole batch succeeded. Idempotent.
2841 15 ▶sub _reconcile_one_table {
Subroutine _reconcile_one_table: called CC=25 SCAR=37.3
2842 15 my ( $main, $bak, $t, %p ) = @_;
2843 15 my $table = $t->{table};
2844 15 my @keys = @{ $t->{keys} };
2845 15 my $out = { read => 0, written => 0, skipped => 0, ok => 1 };
2846  
2847 # The buffer only carries the tables that were actually written, so a table
2848 # missing here is normal, not an error. Check it silently and return: with DBI's
2849 # default PrintError the probe would otherwise print "relation does not exist".
2850 15 my $n = do {
2851 15 local $bak->{PrintError} = 0;
2852 15 local $bak->{RaiseError} = 0;
2853 15 eval { my ($c) = $bak->selectrow_array("select count(*) from $table"); $c };
2854 };
2855 15 ▶ unless ( defined $n ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $n) 0 15 15
2856 0 &logger( 7, "_reconcile_one_table: '$table' absent from the backup" );
2857 0 return $out;
2858 }
2859 15 ▶ return $out if $n == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 9 6 15
2860 6 ▶ if ( $p{dry_run} ) { $out->{read} = $n; return $out; }
Branch: 1 branch
BranchTrueFalseTotal
if ($p{"dry_run"}) 3 3 6
2861  
2862 3 my $sth_rd = $bak->prepare("select * from $table");
2863 3 ▶ unless ( $sth_rd && $sth_rd->execute ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth_rd and $sth_rd->execute) 0 3 3
Condition33%1/3
$sth_rd and $sth_rd->execute
!ll&&!rl&&r
003
MC/DC0%0/2
$sth_rd and $sth_rd->execute
$sth_rd $sth_rd->execute
Truth table33%1/3
A and B
A= $sth_rdB= $sth_rd->execute
ABresult
0X0
100
111
2864 0 ▶ &logger( 3,
Condition0%0/2
$bak->errstr // ""
l!l
00
MC/DC0%0/1
$bak->errstr // ""
$bak->errstr
Truth table0%0/2
A
A= $bak->errstr
Aresult
11
00
2865 "_reconcile_one_table: cannot read '$table' from the backup: "
2866 . ( $bak->errstr // '' ) );
2867 0 $out->{ok} = 0;
2868 0 return $out;
2869 }
2870 3 my $raw_cols = $sth_rd->{NAME}; # buffer column names (raw order)
2871  
2872 3 my ( $norm_id, $norm_table, @norm_cols ) = _norm_identifiers( $main, $table, $raw_cols );
2873 3 my $meta = _get_col_meta( $main, $norm_table, $norm_id );
2874 3 my $clean = _make_clean_val($meta);
2875  
2876 3 my @uk = map { $norm_id->($_) } @keys;
2877 3 my $sql_exists = "select 1 from $norm_table where " . join( ' and ', map { "$_ = ?" } @uk );
2878 3 my $sql_insert =
2879 "insert into $norm_table ("
2880 . join( ',', @norm_cols ) . ")"
2881 . " values ("
2882 . join( ',', ('?') x @norm_cols ) . ")";
2883 3 my $sth_chk = $main->prepare($sql_exists);
2884 3 my $sth_ins = $main->prepare($sql_insert);
2885 3 &logger( 7, "_reconcile_one_table: $table exists=[$sql_exists]" );
2886  
2887 # Buffer-side raw name of each natural-key element, matched by normalized
2888 # name (the buffer and the registry may differ in case). The drain deletes
2889 # ONLY the rows we read, key by key (H3): an unconditional "delete from
2890 # <table>" would also erase a row written by a process still on backup during
2891 # our read, losing it for good.
2892 3 my %norm2raw;
2893 3 for my $i ( 0 .. $#$raw_cols ) { $norm2raw{ $norm_id->( $raw_cols->[$i] ) } = $raw_cols->[$i]; }
2894 3 ▶ my @del_cols = map { $norm2raw{ $norm_id->($_) } // $_ } @keys;
Condition33%1/3
$norm2raw{&$norm_id($_)} // $_
l!l&&r!l&&!r
800
MC/DC0%0/2
$norm2raw{&$norm_id($_)} // $_
$norm2raw{&$norm_id($_)} $_
Truth table33%1/3
A // B
A= $norm2raw{&$norm_id($_)}B= $_
ABresult
1X1
011
000
2895 3 my $sql_del = "delete from $table where " . join( ' and ', map { "$_ = ?" } @del_cols );
2896 3 my @read_keys;
2897  
2898 3 ▶ while ( my $row = $sth_rd->fetchrow_arrayref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth_rd->fetchrow_arrayref) 4 3 7
2899 4 $out->{read}++;
2900  
2901 # Map values by NAME (not position) so that a column-order divergence
2902 # between the buffer and the main schema cannot corrupt the data.
2903 4 my %by_name;
2904 4 for my $i ( 0 .. $#$raw_cols ) { $by_name{ $norm_id->( $raw_cols->[$i] ) } = $row->[$i]; }
2905 4 push @read_keys, [ map { $by_name{ $norm_id->($_) } } @keys ];
2906  
2907 4 my $dup = eval {
2908 4 local $sth_chk->{PrintError} = 0;
2909 4 $sth_chk->execute( map { $clean->( $_, $by_name{$_} ) } @uk );
2910 4 my ($x) = $sth_chk->fetchrow_array;
2911 4 $sth_chk->finish;
2912 4 $x;
2913 };
2914 4 ▶ if ($dup) { $out->{skipped}++; next; }
Branch: 1 branch
BranchTrueFalseTotal
if ($dup) 1 3 4
2915  
2916 3 my $ok = eval {
2917 3 local $sth_ins->{PrintError} = 0;
2918 3 $sth_ins->execute( map { $clean->( $_, $by_name{$_} ) } @norm_cols );
2919 3 1;
2920 };
2921 3 ▶ if ($ok) { $out->{written}++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 3 0 3
2922 else {
2923 0 ▶ &logger( 3,
Condition0%0/3
$main->errstr // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
$main->errstr // $@
$main->errstr $@
Truth table0%0/3
A // B
A= $main->errstrB= $@
ABresult
1X1
011
000
2924 "_reconcile_one_table: insert into '$table' failed: " . ( $main->errstr // $@ ) );
2925 0 $out->{ok} = 0;
2926 0 last;
2927 }
2928 }
2929 3 $sth_rd->finish;
2930  
2931 # Drain the buffer table only when the whole batch was written, and only the
2932 # rows we actually read (H3). The count is checked first: a mismatch aborts the
2933 # drain rather than erasing rows we never copied.
2934 3 ▶ if ( $out->{ok} && !$p{keep_backup} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($out->{"ok"} and not $p{"keep_backup"}) 3 0 3
Condition33%1/3
$out->{"ok"} and not $p{"keep_backup"}
!ll&&!rl&&r
003
MC/DC0%0/2
$out->{"ok"} and not $p{"keep_backup"}
$out->{"ok"} not $p{"keep_backup"}
Truth table33%1/3
A and not(B)
A= $out->{"ok"}B= not $p{"keep_backup"}
ABresult
0X0
100
111
2935 3 ▶ if ( @read_keys != $out->{read} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@read_keys != $out->{'read'}) { } 0 3 3
2936 0 &logger( 3, "_reconcile_one_table: '$table' read/key mismatch, buffer not drained" );
2937 0 $out->{ok} = 0;
2938 }
2939 else {
2940 # Atomic drain when we own the transaction; if the caller manages it,
2941 # the deletes just join that transaction.
2942 3 my $own_tx = eval { $bak->{AutoCommit} };
2943 3 ▶ eval { $bak->begin_work } if $own_tx;
Branch: 1 branch
BranchTrueFalseTotal
if $own_tx 3 0 3
2944 3 my $bad;
2945 3 for my $kv (@read_keys) {
2946 4 my $ok = eval {
2947 4 local $bak->{PrintError} = 0;
2948 4 local $bak->{RaiseError} = 0;
2949 4 $bak->do( $sql_del, undef, @$kv );
2950 4 1;
2951 };
2952 0 ▶ unless ($ok) { $bad = $bak->errstr // $@ // 'unknown error'; last; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 4 4
Condition0%0/5
($bak->errstr // $@) // "unknown error"
l!l
00
$bak->errstr // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
($bak->errstr // $@) // "unknown error"
$bak->errstr $@
Truth table0%0/3
A // B
A= $bak->errstrB= $@
ABresult
1X1
011
000
2953 }
2954 3 ▶ if ( defined $bad ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bad) { } 0 3 3
2955 0 ▶ eval { $bak->rollback } if $own_tx;
Branch: 1 branch
BranchTrueFalseTotal
if $own_tx 0 0 0
2956 0 &logger( 3, "_reconcile_one_table: could not drain '$table': $bad" );
2957 0 $out->{ok} = 0;
2958 }
2959 else {
2960 3 ▶ eval { $bak->commit } if $own_tx;
Branch: 1 branch
BranchTrueFalseTotal
if $own_tx 3 0 3
2961 }
2962 }
2963 }
2964 3 return $out;
2965 }
2966  
2967 # PUBLIC: copy every pending row of the backup buffer back into the main DB.
2968 # Never dies; returns a report hashref.
2969 # %opt: CFG => $cfg, tables => [ {table=>,keys=>[]} ], dry_run => 1, keep_backup => 1
2970 3 ▶sub db_reconcile_backup {
Subroutine db_reconcile_backup: called CC=10 SCAR=30.5
Pod documented
2971 3 my ( $main_dbh, %p ) = @_;
2972 3 ▶ my $cfg = $p{CFG} || config_read('EDTK_DB');
Condition33%1/3
$p{'CFG'} || config_read('EDTK_DB')
l!l&&r!l&&!r
300
MC/DC0%0/2
$p{'CFG'} || config_read('EDTK_DB')
$p{'CFG'} config_read('EDTK_DB')
Truth table33%1/3
A || B
A= $p{'CFG'}B= config_read('EDTK_DB')
ABresult
1X1
011
000
2973 3 my $res = { driver => _db_check_driver_name($main_dbh), tables => {}, written => 0, ok => 1 };
2974  
2975 # H1: never nest a reconcile with itself. This is reached from the on-connect
2976 # check, which may itself be running on a connection an outer reconcile opened.
2977 3 ▶ if ($IN_RECONCILE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oEdtk::DBAdmin::IN_RECONCILE) 0 3 3
2978 0 &logger( 7, "db_reconcile_backup: already running in this process, skipping" );
2979 0 return $res;
2980 }
2981 3 local $IN_RECONCILE = 1;
2982  
2983 3 ▶ unless ( db_backup_available($cfg) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (db_backup_available($cfg)) 0 3 3
2984 0 &logger( 7, "db_reconcile_backup: no distinct backup database configured, nothing to do" );
2985 0 return $res;
2986 }
2987 3 ▶ if ( db_on_backup($main_dbh) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (db_on_backup($main_dbh)) 0 3 3
2988 0 &logger( 7, "db_reconcile_backup: current handle is the backup itself, skipping" );
2989 0 return $res;
2990 }
2991  
2992 3 my $bak = _db_backup_connect($cfg);
2993 3 ▶ unless ($bak) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bak) 0 3 3
2994 0 &logger( 3, "db_reconcile_backup: backup database unreachable, no repatriation" );
2995 0 $res->{ok} = 0;
2996 0 $res->{error} = 'backup unreachable';
2997 0 return $res;
2998 }
2999  
3000 # H3: refuse when both handles designate the SAME database (the anti-loop
3001 # guard only compares the DSN strings, so two spellings of one database slip
3002 # through). Reconciling a database with itself would drain the main table.
3003 3 ▶ if ( _db_same_database( $main_dbh, $bak ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_db_same_database($main_dbh, $bak)) 0 3 3
3004 0 &logger( 3,
3005 "db_reconcile_backup: main and backup handles designate the same database, refusing" );
3006 0 $res->{ok} = 0;
3007 0 $res->{error} = 'main and backup are the same database';
3008 0 eval { $bak->disconnect };
3009 0 return $res;
3010 }
3011  
3012 0 ▶ my @tables = $p{tables} ? @{ $p{tables} } : _backup_table_registry($cfg);
Branch: 1 branch
BranchTrueFalseTotal
$p{'tables'} ? : 0 3 3
3013 3 &logger( 6, "checking if backup data needs reconciliation ..." );
3014  
3015 3 for my $t (@tables) {
3016 15 my $r = _reconcile_one_table( $main_dbh, $bak, $t, %p );
3017 15 $res->{tables}{ $t->{table} } = $r;
3018 15 $res->{written} += $r->{written};
3019 15 ▶ $res->{ok} = 0 unless $r->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"ok"} 0 15 15
3020 }
3021 3 eval { $bak->disconnect };
3022 3 return $res;
3023 }
3024  
3025 # Best-effort hook: repatriate before a maintenance operation. Never fatal.
3026 1 ▶sub _db_maybe_reconcile {
Subroutine _db_maybe_reconcile: called CC=7 SCAR=33.6
3027 1 my ( $dbh, $cfg ) = @_;
3028 1 ▶ return unless defined $dbh && defined $cfg && db_backup_available($cfg);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbh and defined $cfg and db_backup_available($cfg) 1 0 1
Condition33%2/6
defined $dbh and defined $cfg and db_backup_available($cfg)
!ll&&!rl&&r
010
defined $dbh and defined $cfg
!ll&&!rl&&r
001
MC/DC0%0/3
defined $dbh and defined $cfg and db_backup_available($cfg)
defined $dbh defined $cfg db_backup_available($cfg)
Truth table25%1/4
A and B and C
A= defined $dbhB= defined $cfgC= db_backup_available($cfg)
ABCresult
0XX0
10X0
1100
1111
3029 0 eval {
3030 0 my $r = db_reconcile_backup( $dbh, CFG => $cfg );
3031 &logger( 3,
3032 "db_reconcile_backup: " . $r->{written} . " row(s) repatriated from the backup buffer" )
3033 0 ▶ if ( $r->{written} || 0 ) > 0;
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"written"} || 0) > 0 0 0 0
Condition0%0/2
$r->{'written'} || 0
l!l
00
MC/DC0%0/1
$r->{'written'} || 0
$r->{'written'}
Truth table0%0/2
A
A= $r->{'written'}
Aresult
11
00
3034 };
3035 0 ▶ &logger( 3, "db_reconcile_backup failed: $@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
3036 0 return;
3037 }
3038  
3039 0 ▶sub historicize_table {
Subroutine historicize_table: not called CC=2 SCAR=17.9
Pod documented
3040 0 my ( $dbh, $table, $suffixe ) = @_;
3041 0 my $table_cible = $table . "_" . $suffixe;
3042  
3043 0 copy_table( $dbh, $table, $table_cible, '-create' );
3044  
3045 # SQLite has no TRUNCATE statement; DELETE achieves the same move of the data.
3046 0 ▶ my $sql =
Branch: 1 branch
BranchTrueFalseTotal
_db_check_driver_name($dbh) eq 'SQLite' ? : 0 0 0
3047 ( _db_check_driver_name($dbh) eq 'SQLite' )
3048 ? "delete from $table"
3049 : "truncate table $table";
3050 0 &logger( 7, $sql );
3051  
3052 0 _db_do_log( $dbh, _sql_fixup( $dbh, $sql, 'casse' ), "ERROR: can't $sql", fatal => 1 );
3053 }
3054  
3055 7 ▶sub create_table_ADMIN {
Subroutine create_table_ADMIN: called CC=2 SCAR=6.9
Pod undocumented
3056 7 my $dbh = shift;
3057 7 my $table = "edtk_admin";
3058  
3059 7 my $sql = "create table if not exists $table ";
3060 7 $sql .= "( ed_action_date date not null";
3061 7 $sql .= ", ed_action_pid integer not null";
3062 7 $sql .= ", ed_action_status varchar2(16)";
3063 7 $sql .= ", ed_action_duration integer";
3064 7 $sql .= ", ed_oedtk_release varchar2(8) not null";
3065 7 $sql .= ", primary key (ed_action_date)";
3066 7 $sql .= " )";
3067 7 $sql .= _db_engine_clause($dbh);
3068 7 &logger( 7, $sql );
3069  
3070 7 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 7 0 7
3071 }
3072  
3073 6 ▶sub create_table_ID {
Subroutine create_table_ID: called CC=3 SCAR=11.0
Pod undocumented
3074 6 my $dbh = shift;
3075 6 my $table = "edtk_id";
3076  
3077 6 my $sql = "create table if not exists $table ";
3078 6 $sql .= "( ed_id_date date not null"; # 2021-05-19
3079 6 $sql .= ", ed_id_value varchar2(25) unique";
3080 6 $sql .= ", ed_id_chanel_out varchar2(32)";
3081 6 $sql .= ", primary key (ed_id_value)";
3082 6 $sql .= " )";
3083 6 $sql .= _db_engine_clause($dbh);
3084  
3085 6 &logger( 7, $sql );
3086  
3087 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3088  
3089 # my $idx = "ix_".$table."_".$VERSION_TXT;
3090 6 my $idx = "ix_" . $table;
3091 6 $sql = "create index if not exists $idx on $table (ed_id_date);";
3092 6 &logger( 7, $sql );
3093 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3094  
3095 }
3096  
3097 6 ▶sub create_table_FILIERES {
Subroutine create_table_FILIERES: called CC=2 SCAR=6.9
Pod undocumented
3098 6 my $dbh = shift;
3099 6 my $table = "edtk_filieres";
3100  
3101 6 my $sql = "create table if not exists $table ";
3102 6 $sql .= "( ed_idfiliere varchar2(5) unique"; #
3103 6 $sql .= ", ed_priorite integer unique"; #
3104 6 $sql .= ", ed_idmanufact varchar2(16)";
3105 6 $sql .= ", ed_designation varchar2(64)"; #
3106 6 $sql .= ", ed_actif char(1) not null"; # flag: whether that business line (filiere) is active
3107 6 $sql .= ", ed_typed char(1) not null"; #
3108 6 $sql .= ", ed_modedi char(1) not null"; #
3109 6 $sql .= ", ed_idgplot varchar2(16) not null"; #
3110 6 $sql .= ", ed_nbbacprn integer not null"; #
3111 6 $sql .= ", ed_nbencmax integer";
3112 6 $sql .= ", ed_minfeuil_l integer";
3113 6 $sql .= ", ed_maxfeuil_l integer";
3114 6 $sql .= ", ed_feuilpli integer";
3115 6 $sql .= ", ed_minplis integer";
3116 6 $sql .= ", ed_maxplis integer not null";
3117 6 $sql .= ", ed_poids_pli integer"; # maximum weight of the folded item in the line
3118 6 $sql .= ", ed_ref_env varchar2(8) not null";
3119 6 $sql .= ", ed_formflux varchar2(3) not null";
3120 6 $sql .= ", ed_sort varchar2(128) not null";
3121 6 $sql .= ", ed_direction varchar2(4) not null";
3122 6 $sql .= ", ed_postcomp varchar2(8) not null";
3123 6 $sql .= ", primary key (ed_idfiliere, ed_priorite)";
3124 6 $sql .= " )";
3125 6 $sql .= _db_engine_clause($dbh);
3126 6 &logger( 7, $sql );
3127  
3128 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3129 }
3130  
3131 6 ▶sub create_table_LOTS {
Subroutine create_table_LOTS: called CC=2 SCAR=6.9
Pod undocumented
3132 6 my $dbh = shift;
3133 6 my $table = "edtk_lots";
3134  
3135 6 my $sql = "create table if not exists $table ";
3136 6 $sql .= "( ed_idlot varchar2(8) not null"
3137 ; # rendre unique ? -> alter table edtk_lots modify ed_idlot varchar2(8) not null
3138 6 $sql .= ", ed_priorite integer unique"; #
3139 6 $sql .= ", ed_idappdoc varchar2(20)"; #
3140 6 $sql .= ", ed_refiddoc varchar2(20) not null"; #
3141 6 $sql .= ", ed_cpdest varchar2(10)"; #
3142 6 $sql .= ", ed_filter varchar2(64)"; #
3143 6 $sql .= ", ed_refenc varchar2(32)"; #
3144 6 $sql .= ", ed_groupby varchar2(16)";
3145 6 $sql .= ", ed_lotname varchar2(64) not null"; #
3146 6 $sql .= ", ed_idgplot varchar2(16) not null";
3147 6 $sql .= ", ed_idmanufact varchar2(16) not null";
3148 6 $sql .= ", ed_consigne varchar2(250) "; #
3149 6 $sql .= ", primary key (ed_idlot, ed_priorite)";
3150 6 $sql .= " )";
3151 6 $sql .= _db_engine_clause($dbh);
3152 6 &logger( 7, $sql );
3153  
3154 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3155 }
3156  
3157 6 ▶sub create_table_REFIDDOC {
Subroutine create_table_REFIDDOC: called CC=2 SCAR=6.9
Pod undocumented
3158 6 my $dbh = shift;
3159 6 my $table = "edtk_refiddoc";
3160  
3161 6 my $sql = "create table if not exists $table ";
3162 6 $sql .= "( ed_refiddoc varchar2(20) unique";
3163 6 $sql .= ", ed_corp varchar2(8) not null"; # entity related to the document
3164 6 $sql .= ", ed_catdoc char(1) not null";
3165 6 $sql .= ", ed_portadr char(1) not null";
3166 6 $sql .= ", ed_massmail char(1) not null";
3167 6 $sql .= ", ed_edocshare char(1) not null";
3168 6 $sql .= ", ed_typed char(1) not null";
3169 6 $sql .= ", ed_modedi char(1) not null";
3170 6 $sql .= ", ed_pgorien varchar2(2)";
3171 6 $sql .= ", ed_formatp varchar2(2)";
3172 6 $sql .= ", ed_refimp_p1 varchar2(16)";
3173 6 $sql .= ", ed_refimp_ps varchar2(16)";
3174 6 $sql .= ", ed_refimp_refiddoc varchar2(64)";
3175 6 $sql .= ", ed_mail_referent varchar2(300)"; # referent mail for doc validation
3176 6 $sql .= ", primary key (ed_refiddoc, ed_corp, ed_catdoc)";
3177 6 $sql .= " )";
3178 6 $sql .= _db_engine_clause($dbh);
3179 6 &logger( 7, $sql );
3180  
3181 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3182 }
3183  
3184 6 ▶sub create_table_SUPPORTS {
Subroutine create_table_SUPPORTS: called CC=2 SCAR=6.9
Pod undocumented
3185 6 my $dbh = shift;
3186 6 my $table = "edtk_supports";
3187  
3188 6 my $sql = "create table if not exists $table ";
3189 6 $sql .= "( ed_refimp varchar2(16) unique"; #
3190 6 $sql .= ", ed_typimp char(1) not null";
3191 6 $sql .= ", ed_formatp varchar2(2) not null";
3192 6 $sql .= ", ed_poidsunit integer not null";
3193 6 $sql .= ", ed_feuimax integer";
3194 6 $sql .= ", ed_poidsmax integer";
3195 6 $sql .= ", ed_bac_insert integer";
3196 6 $sql .= ", ed_copygroup varchar2(16)";
3197 6 $sql .= ", ed_optctrl varchar2(8)";
3198 6 $sql .= ", ed_debvalid varchar2(8)";
3199 6 $sql .= ", ed_finvalid varchar2(8)";
3200 6 $sql .= ", primary key (ed_refimp)";
3201 6 $sql .= " )";
3202 6 $sql .= _db_engine_clause($dbh);
3203 6 &logger( 7, $sql );
3204  
3205 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3206 }
3207  
3208 32 our @DISTRIB_COLS = (
3209 [ 'ed_idldoc', 'varchar2(36) not null' ]
3210 , # document id within the page-layout batch ed_sngl_id widened to 36
3211 [ 'ed_idseqpg', 'integer not null' ], # page sequence number [doc] within the page-layout batch
3212 [ 'ed_seqdoc', 'integer not null' ], # document sequence number within the batch
3213 [ 'ed_idjob', 'varchar2(25) not null' ], # job id
3214  
3215 [ 'ed_idlot', 'varchar2(8)' ], # batch id
3216 [ 'ed_seqlot', 'varchar2(7)' ], # mailing batch id (sub-batch)
3217 [ 'ed_dtlot', 'varchar2(10)' ], # creation date of the mailing batch
3218 [ 'ed_idfiliere', 'varchar2(5)' ], # production line id
3219 [ 'ed_seqpgdoc', 'integer' ], # page sequence number within the document
3220 [ 'ed_nbpgdoc', 'integer' ], # number of pages (sides) of the document
3221  
3222 # add
3223 [ 'ed_workflow', 'varchar2(32)' ], # workflow on which the metadata was produced ++ new ++
3224 [ 'ed_chanel_out', 'varchar2(32)' ], # distribution/output channel ++ new ++
3225  
3226 [ 'ed_idged', 'varchar2(25)' ]
3227  
3228 );
3229  
3230 12 ▶sub create_table_DISTRIB {
Subroutine create_table_DISTRIB: called CC=5 SCAR=16.2
Pod undocumented
3231 12 my ( $dbh, $table ) = @_;
3232  
3233 my $sql =
3234 12 "create table if not exists $table (" . join( ', ', map { "$$_[0] $$_[1]" } @DISTRIB_COLS )
3235  
3236 # . ", primary key (ed_idldoc, ed_seqdoc, ed_idseqpg, ed_idjob, ed_chanel_out)"
3237 . " )";
3238 12 $sql .= _db_engine_clause($dbh);
3239 12 &logger( 7, $sql );
3240  
3241 12 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 12 0 12
3242  
3243 # my $idx = "ix_".$table."_".$VERSION_TXT;
3244 12 my $idx = "ix_" . $table;
3245  
3246 12 $sql = "create index if not exists $idx on $table "
3247 . " (ed_idldoc, ed_seqdoc, ed_idseqpg, ed_idjob, ed_chanel_out, ed_dtlot);";
3248 12 &logger( 7, $sql );
3249 12 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 12 0 12
3250  
3251 # Rotation / maintenance predicates. Rows are selected and deleted by job
3252 # (agrege_idJob, _acheck_db_rotate) and by batch date (rotation). The composite
3253 # index above leads with ed_idldoc, so neither predicate can use it: dedicated
3254 # indexes are required (verified with EXPLAIN: seq scan -> index scan).
3255 12 for my $spec ( [ 'job', 'ed_idjob' ], [ 'dtlot', 'ed_dtlot' ] ) {
3256 24 my ( $sfx, $col ) = @$spec;
3257 24 $sql = "create index if not exists ${idx}_$sfx on $table ($col);";
3258 24 &logger( 7, $sql );
3259 24 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 24 0 24
3260 }
3261  
3262 }
3263  
3264 32 our @AGREGE_COLS = (
3265 [ 'ed_source', 'varchar2(128)' ], # input stream of this document
3266 [ 'ed_chanel_out', 'varchar2(32)' ], # distribution/output channel
3267 [ 'ed_refiddoc', 'varchar2(25) not null' ], # id in the document repository
3268 [ 'ed_idproduct', 'varchar2(8)' ], # product id
3269 [ 'ed_dtedtion', 'varchar2(8) not null' ], # edition date, the one printed on the document
3270 [ 'ed_cntd_idldoc', 'integer not null' ], # distinct count of document ids
3271 [ 'ed_cnt_idseqpg', 'integer not null' ]
3272 , # count of page sequence [doc] within the page-layout batch
3273 [ 'ed_dtlot', 'varchar2(10)' ], # creation date of the mailing batch
3274 [ 'ed_idlot', 'varchar2(8)' ], # batch id
3275 [ 'ed_idjob', 'varchar2(25) not null' ], # job id
3276 [ 'ed_tstamp', 'varchar2(14) not null'
3277 ] # timestamp of event # TODO see how upgrade handles differing field counts
3278  
3279 );
3280  
3281 6 ▶sub create_table_AGREGE {
Subroutine create_table_AGREGE: called CC=3 SCAR=11.1
Pod undocumented
3282 6 my ($dbh) = @_;
3283 6 my $table = "edtk_agrege";
3284  
3285 my $sql = "create table if not exists $table ("
3286 6 . join( ', ', map { "$$_[0] $$_[1]" } @AGREGE_COLS ) . " )";
3287 6 $sql .= _db_engine_clause($dbh);
3288 6 &logger( 7, $sql );
3289  
3290 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3291  
3292 # my $idx = "ix_".$table."_".$VERSION_TXT;
3293 6 my $idx = "ix_" . $table;
3294 6 $sql = "create index if not exists $idx on $table "
3295 . " (ed_source, ed_chanel_out, ed_refiddoc, ed_idproduct, ed_dtedtion, ed_dtlot, ed_idlot);";
3296 6 &logger( 7, $sql );
3297 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3298  
3299 }
3300  
3301 0 ▶sub create_table_PARA {
Subroutine create_table_PARA: not called CC=2 SCAR=17.9
Pod undocumented
3302 0 my $dbh = shift;
3303 0 my $table = "edtk_test_para";
3304  
3305 0 my $sql = "create table if not exists $table ";
3306 0 $sql .= "( ed_para_refiddoc varchar2(20) not null";
3307 0 $sql .= ", ed_para_corp varchar2(8) not null"; # entity related to the document
3308 0 $sql .= ", ed_id integer unique"; #
3309 0 $sql .= ", ed_tstamp varchar2(14) not null"; # timestamp of event
3310 0 $sql .= ", ed_textbloc varchar2(512)";
3311 0 $sql .= ", primary key (ed_para_refiddoc, ed_para_corp, ed_id)";
3312 0 $sql .= " )";
3313 0 $sql .= _db_engine_clause($dbh);
3314 0 &logger( 7, $sql );
3315  
3316 0 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 0 0 0
3317 }
3318  
3319 0 ▶sub create_table_DATAGROUPS {
Subroutine create_table_DATAGROUPS: not called CC=3 SCAR=24.8
Pod undocumented
3320 0 my $dbh = shift;
3321 0 my $table = "edtk_test_datagroups";
3322  
3323 0 my $sql = "create table if not exists $table ";
3324 0 $sql .= "( ed_dgps_refiddoc varchar2(20) not null";
3325 0 $sql .= ", ed_id integer not null";
3326 0 $sql .= ", ed_data varchar2(64)";
3327 0 $sql .= " )";
3328 0 $sql .= _db_engine_clause($dbh);
3329  
3330 0 &logger( 7, $sql );
3331  
3332 0 ▶ _db_do_ddl( $dbh, $sql ) or die &logger( -1, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or die &logger(-1, $dbh->errstr) 0 0 0
3333  
3334 # my $idx = "ix_".$table."_".$VERSION_TXT;
3335 0 my $idx = "ix_" . $table;
3336 0 $sql = "create index if not exists $idx on $table " . " (ed_dgps_refiddoc, ed_id);";
3337 0 &logger( 7, $sql );
3338 0 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 0 0 0
3339  
3340 }
3341  
3342 6 ▶sub create_table_ACQUIT {
Subroutine create_table_ACQUIT: called CC=2 SCAR=6.9
Pod undocumented
3343 6 my $dbh = shift;
3344 6 my $table = "edtk_acq";
3345  
3346 6 my $sql = "create table if not exists $table ";
3347 6 $sql .= "( ed_seqlot varchar2(7) not null"
3348 ; # mailing batch id (sub-batch) update edtk_acq set ed_seqlot = substr('1'|| ed_seqlot,-7);
3349 6 $sql .= ", ed_lotname varchar2(16) not null"; #
3350 6 $sql .= ", ed_dtpost varchar2(8) not null"; # mailing-out date
3351 6 $sql .= ", ed_dtprint varchar2(8)"; # print date
3352 6 $sql .= ", ed_nbfaces integer not null"
3353 ; # number of sides of the batch (accounting sides, including blank recto/verso sides)
3354 6 $sql .= ", ed_nbplis integer not null"; # number of documents in the folded item
3355 6 $sql .= ", ed_dtpost2 varchar2(8)"; # mailing-out date
3356 6 $sql .= ", ed_dtcheck varchar2(8)"; # check date
3357 6 $sql .= ", ed_status varchar2(4)"; # check status
3358 6 $sql .= ", primary key (ed_seqlot, ed_lotname, ed_dtpost)";
3359 6 $sql .= " )";
3360 6 $sql .= _db_engine_clause($dbh);
3361  
3362 6 &logger( 7, $sql );
3363  
3364 6 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 6 0 6
3365 }
3366  
3367 # Acquittal, step 1 (D-S53): stamp the mailing-out date and the acknowledgement
3368 # status on the indexed items the acknowledgement line refers to. The batch id,
3369 # the folded-item number and the recipient id select the rows; the reception
3370 # year disambiguates batches of the same number across years.
3371 0 ▶sub _acquit_table_INDEX {
Subroutine _acquit_table_INDEX: not called CC=4 SCAR=30.0
3372 0 my ( $dbh, $data, $table ) = @_;
3373 0 ▶ my ($pli) = ( ( $data->[ACQ_FIELD_PLI] // '' ) =~ m/_(\d*)\z/ );
Condition0%0/2
$data->[7] // ""
l!l
00
MC/DC0%0/1
$data->[7] // ""
$data->[7]
Truth table0%0/2
A
A= $data->[7]
Aresult
11
00
3374 0 my $lot = $data->[ACQ_FIELD_LOT];
3375 0 my $annee = substr( $data->[ACQ_FIELD_DTLOT], 0, 4 );
3376 0 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3377 0 my $iddest = $data->[ACQ_FIELD_IDDEST];
3378 0 my $status = $data->[ACQ_FIELD_STATUS];
3379  
3380 0 my $sql = "UPDATE $table SET ED_DTPOSTE=?, ED_STATUS=?"
3381 . " WHERE ED_SEQLOT=? AND ED_IDDEST=? AND SUBSTR(ED_DTLOT,1,4)=? AND ED_IDPLI=?";
3382 0 my $sth = $dbh->prepare($sql);
3383 0 ▶ $sth->execute( $exped, $status, $lot, $iddest, $annee, $pli )
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute($exped, $status, $lot, $iddest, $annee, $pli) or &logger(3, 'acquit_index: update failed: ' . $sth->errstr) 0 0 0
3384 or &logger( 3, "acquit_index: update failed: " . $sth->errstr );
3385 0 ▶ if ( $sth->rows == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->rows == 0) 0 0 0
3386 0 &logger( 3,
3387 "acquit_index: no indexed item for lot $lot, id_dest $iddest, year $annee, item $pli" );
3388 }
3389 0 return 0;
3390 }
3391  
3392 # The document id of the acknowledged batch's first page: "idldoc_seqpg" with the
3393 # page sequence padded to 7 digits. undef when the lookup finds nothing or the
3394 # driver rejects the statement.
3395 0 ▶sub _acquit_docid {
Subroutine _acquit_docid: not called CC=7 SCAR=40.3
3396 0 my ( $dbh, $table, $data ) = @_;
3397 0 ▶ return unless defined $table && length $table;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and length $table 0 0 0
Condition0%0/3
defined $table and length $table
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and length $table
defined $table length $table
Truth table0%0/3
A and B
A= defined $tableB= length $table
ABresult
0X0
100
111
3398 0 my $lot = $data->[ACQ_FIELD_LOT];
3399 0 my $annee = substr( $data->[ACQ_FIELD_DTLOT], 0, 4 );
3400 0 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3401 0 my $iddest = $data->[ACQ_FIELD_IDDEST];
3402 0 my $status = $data->[ACQ_FIELD_STATUS];
3403  
3404 # The fork built the id with a driver-specific concatenation and lpad(); the
3405 # page sequence is padded here in Perl instead (portable across the SGBDs).
3406 0 my $sql =
3407 "SELECT ED_IDLDOC, ED_IDSEQPG FROM $table"
3408 . " WHERE ED_DTPOSTE=? AND ED_STATUS=? AND ED_SEQLOT=? AND ED_IDDEST=? AND SUBSTR(ED_DTLOT,1,4)=?"
3409 . " AND ED_IDSEQPG=(SELECT MIN(ED_IDSEQPG) FROM $table WHERE ED_STATUS=? AND ED_SEQLOT=? AND ED_IDDEST=?)";
3410 0 my $row = eval {
3411 0 my $sth = $dbh->prepare($sql);
3412 0 ▶ $sth->execute( $exped, $status, $lot, $iddest, $annee, $status, $lot, $iddest ) or return;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute($exped, $status, $lot, $iddest, $annee, $status, $lot, $iddest) or return 0 0 0
3413 0 $sth->fetchrow_arrayref();
3414 };
3415 0 ▶ return unless ref $row eq 'ARRAY' && defined $row->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" and defined $row->[0] 0 0 0
Condition0%0/3
ref $row eq "ARRAY" and defined $row->[0]
!ll&&!rl&&r
000
MC/DC0%0/2
ref $row eq "ARRAY" and defined $row->[0]
ref $row eq "ARRAY" defined $row->[0]
Truth table0%0/3
A and B
A= ref $row eq "ARRAY"B= defined $row->[0]
ABresult
0X0
100
111
3416 0 ▶ my $seqpg = defined $row->[1] ? $row->[1] + 0 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $row->[1] ? : 0 0 0
3417 0 return sprintf( '%s_%07d', $row->[0], $seqpg );
3418 }
3419  
3420 # Acquittal, step 2 (D-S53, D24): hand the acknowledged document to the callable
3421 # named in EDTK_ACQUIT_API ("Module::function", validated and loaded by
3422 # oEdtk::Ext). The document id is the batch's first page; when the batch is not
3423 # the weekly one the batch id is passed instead (the fork's fallback). An absent
3424 # or failing callable is a log line, never fatal: the mainline default is no API
3425 # acquittal, and user-specific variants live in oEUser.
3426 0 ▶sub _acquit_API {
Subroutine _acquit_API: not called CC=5 SCAR=34.0
3427 0 my ( $dbh, $data, $cfg ) = @_;
3428 0 my $name = $cfg->{'EDTK_ACQUIT_API'};
3429 0 ▶ unless ( defined $name && length $name ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name and length $name) 0 0 0
Condition0%0/3
defined $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table0%0/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
3430 0 &logger( 5, "acquit_api: EDTK_ACQUIT_API is not set, no API acquittal" );
3431 0 return 0;
3432 }
3433  
3434 0 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3435 0 my $docid = _acquit_docid( $dbh, $cfg->{'EDTK_DBI_OUTMNGR'}, $data );
3436 0 ▶ $docid = $data->[ACQ_FIELD_LOT] unless defined $docid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $docid 0 0 0
3437  
3438 0 require oEdtk::Ext;
3439 0 eval { oEdtk::Ext::call_named_callable( $cfg, 'EDTK_ACQUIT_API', $docid, $exped, $cfg ) };
3440 0 ▶ &logger( 3, "acquit_api: callable '$name' failed: $@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
3441 0 return 0;
3442 }
3443  
3444 32 our @INDEX_COLS = (
3445  
3446 # NB : " primary key (ed_idldoc, ed_seqdoc, ed_idseqpg, ed_idjob)"
3447  
3448 # INDEX COMPOSITION SECTION
3449 [ 'ed_refiddoc', 'varchar2(25) not null' ], # id in the document repository
3450 [ 'ed_idldoc', 'varchar2(36) not null' ]
3451 , # document id within the page-layout batch ed_sngl_id widened to 36
3452 [ 'ed_idseqpg', 'integer not null' ], # page sequence number [doc] within the page-layout batch
3453 [ 'ed_seqdoc', 'integer not null' ], # document sequence number within the batch
3454 [ 'ed_idjob', 'varchar2(25) not null' ], # Job id
3455  
3456 # SECTION DOCUMENT
3457 [ 'ed_dtedtion', 'varchar2(8) not null' ], # edition date, the one printed on the document
3458 [ 'ed_cpdest', 'varchar2(10)' ], # recipient postal code
3459 [ 'ed_villdest', 'varchar2(38)' ], # recipient city
3460 [ 'ed_iddest', 'varchar2(25)' ], # recipient id in the management system
3461 [ 'ed_nomdest', 'varchar2(38)' ], # recipient name
3462 [ 'ed_idemet', 'varchar2(10)' ], # sender id
3463 [ 'ed_typprod', 'varchar(16)' ], # production type associated with the batch
3464 [ 'ed_portadr', 'char(1)' ], # flag: document carries an address
3465 [ 'ed_adrln1', 'varchar2(38)' ], # address line 1
3466 [ 'ed_cleged1', 'varchar2(32)' ], # archiving system key
3467 [ 'ed_adrln2', 'varchar2(38)' ], # address line 2
3468 [ 'ed_cleged2', 'varchar2(20)' ], # archiving system key
3469 [ 'ed_adrln3', 'varchar2(38)' ], # address line 3
3470 [ 'ed_cleged3', 'varchar2(20)' ], # archiving system key
3471 [ 'ed_adrln4', 'varchar2(38)' ], # address line 4
3472 [ 'ed_cleged4', 'varchar2(20)' ], # archiving system key
3473 [ 'ed_adrln5', 'varchar2(38)' ], # address line 5
3474 [ 'ed_corp', 'varchar2(8) not null' ], # issuing entity of the page
3475 [ 'ed_doclib', 'varchar2(32)' ], # merge library associated with the page
3476 [ 'ed_refimp', 'varchar2(16)' ], # pre-printed, printed or insert reference
3477 [ 'ed_adrln6', 'varchar2(38)' ], # address line 6
3478 [ 'ed_source', 'varchar2(8) not null' ], # index source or ed_corp entity
3479 [ 'ed_owner', 'varchar2(10)' ], # document owner (used in document management / archiving)
3480 [ 'ed_host', 'varchar2(32)' ], # hostname of the machine this entry came from
3481 [ 'ed_ididx', 'varchar2(8) ' ], # index id
3482 [ 'ed_catdoc', 'char(1)' ], # document category
3483 [ 'ed_codrupt', 'varchar2(8)' ], # burst forcing code
3484  
3485 # INDEX BATCHING SECTION
3486 [ 'ed_idlot', 'varchar2(8)' ], # batch id
3487 [ 'ed_seqlot', 'varchar2(7)' ], # mailing batch id (sub-batch)
3488 [ 'ed_dtlot', 'varchar2(10)' ], # creation date of the mailing batch
3489 [ 'ed_idfiliere', 'varchar2(5)' ], # production line id
3490 [ 'ed_seqpgdoc', 'integer' ], # page sequence number within the document
3491 [ 'ed_nbpgdoc', 'integer' ], # number of pages (sides) of the document
3492 [ 'ed_poidsunit', 'integer' ], # weight of the print or insert in mg
3493 [ 'ed_nbenc', 'integer' ], # number of inserts in the doc
3494 [ 'ed_encpds', 'integer' ], # weight of the inserts in the doc
3495 [ 'ed_bac_insert', 'integer' ], # Tray or insert call
3496  
3497 # INDEX EDITION SECTION
3498 [ 'ed_typed', 'char(1)' ], # edition type (black / full color)
3499 [ 'ed_modedi', 'char(1)' ], # edition mode (simplex / duplex) => recto / verso
3500 [ 'ed_formatp', 'varchar2(2)' ], # paper format (a4 / a3 ...)
3501 [ 'ed_pgorien', 'varchar2(2)' ]
3502 , # edition orientation (portrait / reverseportrait / landscape / reverse landscape)
3503 [ 'ed_formflux', 'varchar2(3)' ], # edition stream format (afp / pdf / ...)
3504  
3505 # ['ed_formdef', 'varchar2(8)'], # formdef afp
3506 # ['ed_pagedef', 'varchar2(8)'], # pagedef afp
3507 # ['ed_forms', 'varchar2(8)'], # Forms
3508  
3509 # INDEX FOLDING SECTION
3510 [ 'ed_idpli', 'integer' ], # folded-item id
3511 [ 'ed_nbdocpli', 'integer' ], # number of documents in the folded item
3512 [ 'ed_numpgpli', 'integer' ], # page (side) number in the folded item
3513 [ 'ed_nbpgpli', 'integer' ], # number of pages (sides) of the folded item
3514 [ 'ed_nbfpli', 'integer' ], # number of sheets of the folded item
3515 [ 'ed_listerefenc', 'varchar2(64)' ], # list of inserts in the folded item
3516 [ 'ed_pdspli', 'integer' ], # weight of the folded item in mg
3517 [ 'ed_typobj', 'char(1)' ], # object type in the folded item xxxxxx conserver ?
3518 [ 'ed_status', 'varchar2(8)' ]
3519 , # batching status (mailing-out date or status depending on the version)
3520 [ 'ed_dtposte', 'varchar2(8)' ]
3521 , # to remove : batching status (mailing-out date or status depending on the version)
3522  
3523 # ADD
3524 [ 'ed_workflow', 'varchar2(32)' ], # workflow on which the metadata was produced ++ new ++
3525 [ 'ed_chanel_out', 'varchar2(32)' ], # distribution/output channel ++ new ++
3526 [ 'ed_country', 'varchar2(5)' ], # recipient country code ++ new ++
3527 [ 'ed_idcontract', 'varchar2(16)' ], # contract id ++ new ++
3528 [ 'ed_idproduct', 'varchar2(8)' ], # Product id ++ NEW ++
3529 # ECM SECTION (fork F): document-management columns the standard schema lacked.
3530 # Sizes = max(F, M); EDTK_ACQMGENTECH itself is carried by the oEUser extension.
3531 [ 'ed_typdoc', 'varchar2(4)' ], # document type (ECM)
3532 [ 'ed_idcoll', 'varchar2(16)' ], # collection id (ECM)
3533 [ 'ed_idmnt', 'varchar2(10)' ], # archive id from the extension (annexe E)
3534 [ 'ed_cleged5', 'varchar2(20)' ], # archiving system key (ECM)
3535 [ 'ed_idpmsir', 'varchar2(18)' ] # PM/SIR archive id (ECM)
3536  
3537 );
3538  
3539 12 ▶sub create_table_OUTMNGR {
Subroutine create_table_OUTMNGR: called CC=5 SCAR=16.4
Pod undocumented
3540 12 my ( $dbh, $table, %opt ) = @_;
3541  
3542 # The primary key carries ed_idjob in M's default mode (EDTK_DB_PK_IDJOB=yes).
3543 # Option pk_idjob => 0 builds the F-shaped key without it (D16).
3544 12 ▶ my $pk_idjob = exists $opt{pk_idjob} ? $opt{pk_idjob} : _pk_idjob_default();
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'pk_idjob'} ? : 0 12 12
3545 12 my @pk = qw(ed_idldoc ed_seqdoc ed_idseqpg);
3546 12 ▶ push @pk, 'ed_idjob' if $pk_idjob;
Branch: 1 branch
BranchTrueFalseTotal
if $pk_idjob 12 0 12
3547  
3548 my $sql =
3549 "create table if not exists $table ("
3550 12 . join( ', ', map { "$$_[0] $$_[1]" } @INDEX_COLS ) . ", "
3551 . " primary key ("
3552 . join( ', ', @pk ) . ")" . " )";
3553 12 $sql .= _db_engine_clause($dbh);
3554 12 &logger( 7, $sql );
3555  
3556 12 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 12 0 12
3557  
3558 # my $idx = "ix_".$table."_".$VERSION_TXT;
3559 12 my $idx = "ix_" . $table;
3560 12 $sql = "create index if not exists $idx on $table " . " (ed_dtedtion, ed_seqlot, ed_typprod);";
3561 12 &logger( 7, $sql );
3562 12 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 12 0 12
3563 }
3564  
3565 6 ▶sub create_lot_sequence {
Subroutine create_lot_sequence: called CC=5 SCAR=19.7
Pod documented
3566  
3567 # USED FOR BATCH CREATION IN Outmngr.pm
3568 6 my $dbh = shift;
3569  
3570 6 ▶ if ( _db_check_driver_name($dbh) eq "SQLite" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_db_check_driver_name($dbh) eq "SQLite") 6 0 6
3571  
3572 # SQLite has no SEQUENCE object: emulate EDTK_IDLOT with a one-row counter
3573 # table cycling 0..999 (read back by _get_seqlot in Outmngr.pm). MySQL uses
3574 # its own AUTO_INCREMENT emulation and is skipped by the caller.
3575 6 ▶ _db_do_ddl( $dbh, "create table if not exists edtk_idlot_seq (id_val integer not null)" )
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, "create table if not exists edtk_idlot_seq (id_val integer not null)") or &logger(3, $dbh->errstr) 6 0 6
3576 or &logger( 3, $dbh->errstr );
3577 6 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
do { local $dbh->{"PrintError"} = 0; $dbh->do("insert into edtk_idlot_seq (id_val) select 0 where not exists (select 1 from edtk_idlot_seq)") } or &logger(3, $dbh->errstr) 6 0 6
3578 6 local $dbh->{PrintError} = 0;
3579 6 $dbh->do(
3580 "insert into edtk_idlot_seq (id_val) select 0 where not exists (select 1 from edtk_idlot_seq)"
3581 );
3582 }
3583 or &logger( 3, $dbh->errstr );
3584 6 return 1;
3585 }
3586  
3587 # method valid for most DBMS except MySQL
3588 0 my $sql = "create sequence if not exists edtk_idlot minvalue 0 maxvalue 999 cycle";
3589 0 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 0 0 0
3590 0 return 1;
3591 }
3592  
3593 # ============================================================
3594 # Fork-F API delegates. T is a superset of F (PLAN, annexe E): the names F
3595 # exported are kept, wired to T's own implementation.
3596 # ============================================================
3597  
3598 # F: create_SCHEMA( $dbh, $table, $maxkeys ) built the whole F schema.
3599 # T: the canonical schema_Create, plus the TRACKING table F also created.
3600 0 ▶sub create_SCHEMA {
Subroutine create_SCHEMA: not called CC=3 SCAR=24.8
Pod documented
3601 0 my ($dbh) = @_;
3602 0 schema_Create($dbh);
3603 0 my $cfg = eval { config_read('EDTK_DB') };
3604 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
3605 0 ▶ if $cfg && $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg and $cfg->{"EDTK_DBI_TRACKING"} 0 0 0
Condition0%0/3
$cfg and $cfg->{"EDTK_DBI_TRACKING"}
!ll&&!rl&&r
000
MC/DC0%0/2
$cfg and $cfg->{"EDTK_DBI_TRACKING"}
$cfg $cfg->{"EDTK_DBI_TRACKING"}
Truth table0%0/3
A and B
A= $cfgB= $cfg->{"EDTK_DBI_TRACKING"}
ABresult
0X0
100
111
3606 0 return 0;
3607 }
3608  
3609 # F: create_table_INDEX( $dbh, $table ) created the page-layout index table.
3610 # T: that table is create_table_OUTMNGR; its key follows EDTK_DB_PK_IDJOB (D16).
3611 0 ▶sub create_table_INDEX {
Subroutine create_table_INDEX: not called CC=1 SCAR=6.9
Pod undocumented
3612 0 my ( $dbh, $table ) = @_;
3613 0 create_table_OUTMNGR( $dbh, $table );
3614 0 return 0;
3615 }
3616  
3617 # F: get_columns_names( $dbh, $table ) read all_tab_columns (Oracle only).
3618 # T: read the driver-neutral column catalogue; names keep the catalogue's case.
3619 0 ▶sub get_columns_names {
Subroutine get_columns_names: not called CC=9 SCAR=45.0
Pod documented
3620 0 my ( $dbh, $table ) = @_;
3621 0 ▶ return () unless defined $dbh && defined $table;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbh and defined $table 0 0 0
Condition0%0/3
defined $dbh and defined $table
!ll&&!rl&&r
000
MC/DC0%0/2
defined $dbh and defined $table
defined $dbh defined $table
Truth table0%0/3
A and B
A= defined $dbhB= defined $table
ABresult
0X0
100
111
3622  
3623 0 my @cols;
3624 0 my $sth = $dbh->column_info( undef, undef, $table, undef );
3625 0 ▶ if ( defined $sth ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sth) 0 0 0
3626 0 ▶ while ( my $row = $sth->fetchrow_hashref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
3627 0 my $name = $row->{COLUMN_NAME};
3628 0 ▶ push @cols, $name if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 0 0 0
3629 }
3630 }
3631  
3632 # Fallback for drivers without column_info: the statement's NAME list.
3633 0 ▶ unless (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cols) 0 0 0
3634 0 my $sel = eval { $dbh->prepare("select * from $table where 1=0") };
3635 0 ▶ if ($sel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel) 0 0 0
3636 0 $sel->execute();
3637 0 ▶ @cols = @{ $sel->{NAME} // [] };
Condition0%0/2
$sel->{"NAME"} // []
l!l
00
MC/DC0%0/1
$sel->{"NAME"} // []
$sel->{"NAME"}
Truth table0%0/2
A
A= $sel->{"NAME"}
Aresult
11
00
3638 }
3639 }
3640 0 return @cols;
3641 }
3642  
3643 # Default of the primary-key mode, from EDTK_DB_PK_IDJOB (D16): 'yes' gives M's
3644 # shape (ed_idjob in the key) unless the configuration says otherwise.
3645 12 ▶sub _pk_idjob_default {
Subroutine _pk_idjob_default: called CC=7 SCAR=33.6
3646 12 my $cfg = eval { config_read('EDTK_DB') };
3647 12 ▶ return 1 unless $cfg && defined $cfg->{'EDTK_DB_PK_IDJOB'};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg and defined $cfg->{"EDTK_DB_PK_IDJOB"} 12 0 12
Condition33%1/3
$cfg and defined $cfg->{"EDTK_DB_PK_IDJOB"}
!ll&&!rl&&r
0120
MC/DC0%0/2
$cfg and defined $cfg->{"EDTK_DB_PK_IDJOB"}
$cfg defined $cfg->{"EDTK_DB_PK_IDJOB"}
Truth table33%1/3
A and B
A= $cfgB= defined $cfg->{"EDTK_DB_PK_IDJOB"}
ABresult
0X0
100
111
3648 0 my $v = lc( $cfg->{'EDTK_DB_PK_IDJOB'} );
3649 0 ▶ return ( $v eq 'no' || $v eq '0' || $v eq 'false' || $v eq 'n' ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$v eq 'no' || $v eq '0' || $v eq 'false' || $v eq 'n' ? : 0 0 0
Condition0%0/9
$v eq "no" or $v eq 0 or $v eq "false" or $v eq "n"
l!l&&r!l&&!r
000
$v eq "no" or $v eq 0 or $v eq "false"
l!l&&r!l&&!r
000
$v eq "no" or $v eq 0
l!l&&r!l&&!r
000
MC/DC0%0/4
$v eq "no" or $v eq 0 or $v eq "false" or $v eq "n"
$v eq "no" $v eq 0 $v eq "false" $v eq "n"
Truth table0%0/5
A or B or C or D
A= $v eq "no"B= $v eq 0C= $v eq "false"D= $v eq "n"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3650 }
3651  
3652 # ============================================================
3653 # Optional schema extension (oEUser::Schema, D19). The module has a fixed name,
3654 # carries data only, and is absent from the standard distribution; when it is
3655 # not installed only the standard schema is built.
3656 # ============================================================
3657  
3658 # Load and validate oEUser::Schema::extra(); an empty hashref when absent.
3659 6 ▶sub _schema_extra {
Subroutine _schema_extra: called CC=4 SCAR=24.2
3660 6 require oEdtk::Ext;
3661 6 ▶ return {} unless oEdtk::Ext::require_optional('oEUser::Schema');
Branch: 1 branch
BranchTrueFalseTotal
unless oEdtk::Ext::require_optional("oEUser::Schema") 6 0 6
3662 0 my $extra = eval { oEUser::Schema::extra() };
3663 0 ▶ return {} unless ref $extra eq 'HASH' && %$extra;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $extra eq "HASH" and %$extra 0 0 0
Condition0%0/3
ref $extra eq "HASH" and %$extra
!ll&&!rl&&r
000
MC/DC0%0/2
ref $extra eq "HASH" and %$extra
ref $extra eq "HASH" %$extra
Truth table0%0/3
A and B
A= ref $extra eq "HASH"B= %$extra
ABresult
0X0
100
111
3664 0 return _validate_schema_extra($extra);
3665 }
3666  
3667 # Validate the extension structure: identifiers and column types only.
3668 0 ▶sub _validate_schema_extra {
Subroutine _validate_schema_extra: not called CC=14 SCAR=53.5
3669 0 my ($extra) = @_;
3670 0 my %types = map { $_ => 1 } qw( VARCHAR2 VARCHAR CHAR INTEGER NUMBER DATE TIMESTAMP );
3671 0 ▶ my $tables = $extra->{tables} // {};
Condition0%0/2
$extra->{"tables"} // {}
l!l
00
MC/DC0%0/1
$extra->{"tables"} // {}
$extra->{"tables"}
Truth table0%0/2
A
A= $extra->{"tables"}
Aresult
11
00
3672 0 ▶ my $columns = $extra->{columns} // {};
Condition0%0/2
$extra->{"columns"} // {}
l!l
00
MC/DC0%0/1
$extra->{"columns"} // {}
$extra->{"columns"}
Truth table0%0/2
A
A= $extra->{"columns"}
Aresult
11
00
3673  
3674 0 for my $table ( keys %$tables ) {
3675 0 ▶ die "ERROR: oEUser::Schema::extra(): invalid table name '$table'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /\A[A-Z][A-Z0-9_]*\z/ 0 0 0
3676 unless $table =~ /\A[A-Z][A-Z0-9_]*\z/;
3677  
3678 0 my $defs = $columns->{$table};
3679 0 ▶ die "ERROR: oEUser::Schema::extra(): no columns for table '$table'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defs eq "ARRAY" and @$defs 0 0 0
Condition0%0/3
ref $defs eq "ARRAY" and @$defs
!ll&&!rl&&r
000
MC/DC0%0/2
ref $defs eq "ARRAY" and @$defs
ref $defs eq "ARRAY" @$defs
Truth table0%0/3
A and B
A= ref $defs eq "ARRAY"B= @$defs
ABresult
0X0
100
111
3680 unless ref $defs eq 'ARRAY' && @$defs;
3681  
3682 0 for my $col (@$defs) {
3683 0 ▶ my $name = $col->{name} // '';
Condition0%0/2
$col->{"name"} // ""
l!l
00
MC/DC0%0/1
$col->{"name"} // ""
$col->{"name"}
Truth table0%0/2
A
A= $col->{"name"}
Aresult
11
00
3684 0 ▶ die "ERROR: oEUser::Schema::extra(): invalid column name '$name' in '$table'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[A-Z][A-Z0-9_]*\z/ 0 0 0
3685 unless $name =~ /\A[A-Z][A-Z0-9_]*\z/;
3686 0 ▶ my $type = uc( $col->{type} // '' );
Condition0%0/2
$col->{"type"} // ""
l!l
00
MC/DC0%0/1
$col->{"type"} // ""
$col->{"type"}
Truth table0%0/2
A
A= $col->{"type"}
Aresult
11
00
3687 die "ERROR: oEUser::Schema::extra(): invalid type '$type' for $table.$name\n"
3688 0 ▶ unless $types{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $types{$type} 0 0 0
3689 }
3690  
3691 0 ▶ my $pk = $tables->{$table}{primary_key} // [];
Condition0%0/2
$tables->{$table}{"primary_key"} // []
l!l
00
MC/DC0%0/1
$tables->{$table}{"primary_key"} // []
$tables->{$table}{"primary_key"}
Truth table0%0/2
A
A= $tables->{$table}{"primary_key"}
Aresult
11
00
3692 0 ▶ die "ERROR: oEUser::Schema::extra(): primary_key of '$table' must be a list\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pk eq "ARRAY" 0 0 0
3693 unless ref $pk eq 'ARRAY';
3694 }
3695 0 return $extra;
3696 }
3697  
3698 # Build the CREATE TABLE of one extension table from its definition.
3699 0 ▶sub _create_table_extra {
Subroutine _create_table_extra: not called CC=7 SCAR=40.3
3700 0 my ( $dbh, $table, $spec, $defs ) = @_;
3701  
3702 my @cols = map {
3703 0 my $type = uc( $_->{type} );
3704 0 ▶ $type .= "(" . $_->{size} . ")" if defined $_->{size} && $_->{size} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $_->{"size"} and $_->{"size"} ne "" 0 0 0
Condition0%0/3
defined $_->{"size"} and $_->{"size"} ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_->{"size"} and $_->{"size"} ne ""
defined $_->{"size"} $_->{"size"} ne ""
Truth table0%0/3
A and B
A= defined $_->{"size"}B= $_->{"size"} ne ""
ABresult
0X0
100
111
3705 0 ▶ my $null = $_->{nullable} ? '' : ' not null';
Branch: 1 branch
BranchTrueFalseTotal
$_->{'nullable'} ? : 0 0 0
3706 0 "$_->{name} $type$null";
3707 } @$defs;
3708  
3709 0 my $sql = "create table if not exists $table ( " . join( ', ', @cols );
3710 0 my $pk = $spec->{primary_key};
3711 0 ▶ $sql .= ", primary key ( " . join( ', ', @$pk ) . " )" if ref $pk eq 'ARRAY' && @$pk;
Branch: 1 branch
BranchTrueFalseTotal
if ref $pk eq "ARRAY" and @$pk 0 0 0
Condition0%0/3
ref $pk eq "ARRAY" and @$pk
!ll&&!rl&&r
000
MC/DC0%0/2
ref $pk eq "ARRAY" and @$pk
ref $pk eq "ARRAY" @$pk
Truth table0%0/3
A and B
A= ref $pk eq "ARRAY"B= @$pk
ABresult
0X0
100
111
3712 0 $sql .= " )";
3713 0 $sql .= _db_engine_clause($dbh);
3714 0 &logger( 7, $sql );
3715 0 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 0 0 0
3716 0 return 1;
3717 }
3718  
3719 # Apply every table of the extension; returns the number of tables applied.
3720 6 ▶sub _schema_create_extra {
Subroutine _schema_create_extra: called CC=4 SCAR=14.6
3721 6 my ($dbh) = @_;
3722 6 my $extra = _schema_extra();
3723 6 ▶ for my $table ( sort keys %{ $extra->{tables} // {} } ) {
Condition50%1/2
$extra->{"tables"} // {}
l!l
06
MC/DC0%0/1
$extra->{"tables"} // {}
$extra->{"tables"}
Truth table50%1/2
A
A= $extra->{"tables"}
Aresult
11
00
3724 0 _create_table_extra( $dbh, $table, $extra->{tables}{$table}, $extra->{columns}{$table} );
3725 }
3726 6 ▶ return scalar keys %{ $extra->{tables} // {} };
Condition50%1/2
$extra->{"tables"} // {}
l!l
06
MC/DC0%0/1
$extra->{"tables"} // {}
$extra->{"tables"}
Truth table50%1/2
A
A= $extra->{"tables"}
Aresult
11
00
3727 }
3728  
3729 # F: create_table_ACQMGENTECH( $dbh, $table ). The acquisition table belongs to
3730 # the oEUser::Schema extension (D19), which is optional: the extension is loaded
3731 # through an eval (see _schema_extra). When it is not installed -- or does not
3732 # define the table -- there is nothing to create and the call is a silent no-op,
3733 # so oEdtk keeps running standalone without oEUser. Fixed arity: the table name
3734 # defaults to EDTK_ACQMGENTECH.
3735 0 ▶sub create_table_ACQMGENTECH {
Subroutine create_table_ACQMGENTECH: not called CC=4 SCAR=30.0
Pod undocumented
3736 0 my ( $dbh, $table ) = @_;
3737 0 ▶ $table //= 'EDTK_ACQMGENTECH';
Condition0%0/2
$table //= "EDTK_ACQMGENTECH"
l!l
00
MC/DC0%0/1
$table //= "EDTK_ACQMGENTECH"
$table
Truth table0%0/2
A
A= $table
Aresult
11
00
3738  
3739 0 my $extra = _schema_extra();
3740 0 my $spec = $extra->{tables}{$table};
3741 0 my $defs = $extra->{columns}{$table};
3742 0 ▶ return 0 unless $spec && $defs;
Branch: 1 branch
BranchTrueFalseTotal
unless $spec and $defs 0 0 0
Condition0%0/3
$spec and $defs
!ll&&!rl&&r
000
MC/DC0%0/2
$spec and $defs
$spec $defs
Truth table0%0/3
A and B
A= $specB= $defs
ABresult
0X0
100
111
3743  
3744 0 _create_table_extra( $dbh, $table, $spec, $defs );
3745 0 return 0;
3746 }
3747  
3748 # ============================================================
3749 # Schema-level detection and history (S51a, PLAN). schema_Detect inspects a live
3750 # base through the driver-neutral oEdtk::SchemaScan and tells which of the three
3751 # documented shapes it shows -- F (the fork), M (mainline 2.1109) or T (the
3752 # integrated target) -- or 'mixte' when the observed features match no single
3753 # one. It reads the data dictionary only and writes nothing; the report is meant
3754 # to be printed by an operator before any migration (--check-only).
3755 #
3756 # Discriminators, on the index table named EDTK_DBI_OUTMNGR:
3757 # * whether the primary key carries ed_idjob (D16);
3758 # * whether the ECM columns the fork added are present (S50);
3759 # * the declared width of ed_idldoc (F=17, M=25, T=36, D9).
3760 # ============================================================
3761  
3762 # The ECM columns the fork appended to the index table, absent from M.
3763 32 our @SCHEMA_ECM_COLS = qw( ed_typdoc ed_idcoll ed_idmnt ed_cleged5 ed_idpmsir );
3764  
3765 # Document-id widths of the three shapes (D9).
3766 32 ▶use constant SCHEMA_IDLDOC_F => 17;
Subroutine BEGIN: called CC=1 SCAR=0.0
3767 32 ▶use constant SCHEMA_IDLDOC_M => 25;
Subroutine BEGIN: called CC=1 SCAR=0.0
3768 32 ▶use constant SCHEMA_IDLDOC_T => 36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3769  
3770 # The three documented shapes, as the feature set each one shows.
3771 0 ▶sub _schema_level_defs {
Subroutine _schema_level_defs: not called CC=1 SCAR=6.9
3772 return (
3773 0 F => { idjob_in_key => 0, ecm => 0, idldoc_min => 0, idldoc_max => SCHEMA_IDLDOC_M },
3774 M => {
3775 idjob_in_key => 1,
3776 ecm => 0,
3777 idldoc_min => SCHEMA_IDLDOC_M,
3778 idldoc_max => SCHEMA_IDLDOC_M
3779 },
3780 T => {
3781 idjob_in_key => 1,
3782 ecm => scalar @SCHEMA_ECM_COLS,
3783 idldoc_min => SCHEMA_IDLDOC_T,
3784 idldoc_max => 9999
3785 },
3786 );
3787 }
3788  
3789 # Find a table in a SchemaScan result, ignoring identifier case. PostgreSQL
3790 # folds unquoted names to lower case while the shipped configuration keeps the
3791 # historical upper-case names (EDTK_INDEX), so an exact hash lookup misses it.
3792 4 ▶sub _schema_scan_table {
Subroutine _schema_scan_table: called CC=5 SCAR=16.1
3793 4 my ( $scan, $table ) = @_;
3794 4 ▶ my $tables = $scan->{tables} // {};
Condition50%1/2
$scan->{"tables"} // {}
l!l
40
MC/DC0%0/1
$scan->{"tables"} // {}
$scan->{"tables"}
Truth table50%1/2
A
A= $scan->{"tables"}
Aresult
11
00
3795 4 ▶ return $tables->{$table} if exists $tables->{$table};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tables->{$table} 1 3 4
3796 3 my $want = lc $table;
3797 3 for my $name ( keys %$tables ) {
3798 3 ▶ return $tables->{$name} if lc($name) eq $want;
Branch: 1 branch
BranchTrueFalseTotal
if lc $name eq $want 2 1 3
3799 }
3800 1 return;
3801 }
3802  
3803 # The discriminators of one table, read off a SchemaScan result.
3804 1 ▶sub _schema_features {
Subroutine _schema_features: called CC=5 SCAR=16.4
3805 1 my ( $scan, $table ) = @_;
3806 1 my $t = _schema_scan_table( $scan, $table );
3807 1 ▶ return unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 0 1 1
3808  
3809 1 ▶ my @cols = @{ $t->{columns} // [] };
Condition50%1/2
$t->{"columns"} // []
l!l
10
MC/DC0%0/1
$t->{"columns"} // []
$t->{"columns"}
Truth table50%1/2
A
A= $t->{"columns"}
Aresult
11
00
3810 1 my %col = map { lc( $_->{name} ) => $_ } @cols;
3811 1 my @key = map { lc $_->{name} } sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @cols;
3812  
3813 return {
3814 table => $table,
3815 key => \@key,
3816 2 idjob_in_key => ( grep { $_ eq 'ed_idjob' } @key ) ? 1 : 0,
3817 5 ▶ ecm => scalar( grep { exists $col{$_} } @SCHEMA_ECM_COLS ),
Branch: 1 branch
BranchTrueFalseTotal
$col{'ed_idldoc'} ? : 1 0 1
3818 1 ▶ idldoc_size => ( $col{ed_idldoc} ? $col{ed_idldoc}{size} : undef ),
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq 'ed_idjob';} @key) ? : 0 1 1
3819 };
3820 }
3821  
3822 # Diff one table's live columns against a [name, ddl type] reference list.
3823 # Returns ( \@missing, \@shrink ). An absent table makes every reference column
3824 # missing. READ-ONLY: it works off the caller's SchemaScan result, writes nothing.
3825 0 ▶sub _schema_col_diff {
Subroutine _schema_col_diff: not called CC=9 SCAR=45.0
3826 0 my ( $scan, $table, $cols ) = @_;
3827 0 my ( @missing, @shrink );
3828 0 ▶ my $t = $table ? _schema_scan_table( $scan, $table ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$table ? : 0 0 0
3829 0 ▶ my %live = $t ? map { lc( $_->{name} ) => $_ } @{ $t->{columns} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$t ? : 0 0 0
Condition0%0/2
$t->{"columns"} // []
l!l
00
MC/DC0%0/1
$t->{"columns"} // []
$t->{"columns"}
Truth table0%0/2
A
A= $t->{"columns"}
Aresult
11
00
3830 0 for my $c (@$cols) {
3831 0 my ( $name, $type ) = @$c;
3832 0 my $n = lc $name;
3833 0 ▶ unless ( $live{$n} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($live{$n}) 0 0 0
3834 0 push @missing, $name;
3835 0 next;
3836 }
3837 0 my $want = oEdtk::SchemaScan::size_from_type($type);
3838 0 my $have = $live{$n}{size};
3839 0 ▶ push @shrink, "$name ($have < $want)"
Branch: 1 branch
BranchTrueFalseTotal
if defined $want and defined $have and $have < $want 0 0 0
Condition0%0/6
defined $want and defined $have and $have < $want
!ll&&!rl&&r
000
defined $want and defined $have
!ll&&!rl&&r
000
MC/DC0%0/3
defined $want and defined $have and $have < $want
defined $want defined $have $have < $want
Truth table0%0/4
A and B and C
A= defined $wantB= defined $haveC= $have < $want
ABCresult
0XX0
10X0
1100
1111
3840 if defined $want && defined $have && $have < $want;
3841 }
3842 0 return ( \@missing, \@shrink );
3843 }
3844  
3845 # Features, level and the index-table column diff, all from a single scan. An
3846 # absent index table keeps empty missing/shrink, as schema_Detect always did.
3847 0 ▶sub _schema_assess {
Subroutine _schema_assess: not called CC=2 SCAR=17.9
3848 0 my ( $scan, $index_table ) = @_;
3849 0 my $f = _schema_features( $scan, $index_table );
3850 0 my $level = _schema_classify($f);
3851 0 ▶ my ( $missing, $shrink ) =
Branch: 1 branch
BranchTrueFalseTotal
$f ? : 0 0 0
3852 $f ? _schema_col_diff( $scan, $index_table, \@INDEX_COLS ) : ( [], [] );
3853 0 return ( $f, $level, $missing, $shrink );
3854 }
3855  
3856 # Which documented shape a feature set matches; 'mixte' when none does.
3857 0 ▶sub _schema_classify {
Subroutine _schema_classify: not called CC=8 SCAR=42.8
3858 0 my ($f) = @_;
3859 0 ▶ return 'absente' unless $f;
Branch: 1 branch
BranchTrueFalseTotal
unless $f 0 0 0
3860 0 my %def = _schema_level_defs();
3861 0 for my $lvl ( sort keys %def ) {
3862 0 my $d = $def{$lvl};
3863 0 ▶ next unless $f->{idjob_in_key} == $d->{idjob_in_key};
Branch: 1 branch
BranchTrueFalseTotal
unless $f->{"idjob_in_key"} == $d->{"idjob_in_key"} 0 0 0
3864 0 ▶ next unless $f->{ecm} == $d->{ecm};
Branch: 1 branch
BranchTrueFalseTotal
unless $f->{"ecm"} == $d->{"ecm"} 0 0 0
3865 0 ▶ next unless defined $f->{idldoc_size};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $f->{"idldoc_size"} 0 0 0
3866 return $lvl
3867 0 ▶ if $f->{idldoc_size} >= $d->{idldoc_min} && $f->{idldoc_size} <= $d->{idldoc_max};
Branch: 1 branch
BranchTrueFalseTotal
if $f->{"idldoc_size"} >= $d->{"idldoc_min"} and $f->{"idldoc_size"} <= $d->{"idldoc_max"} 0 0 0
Condition0%0/3
$f->{"idldoc_size"} >= $d->{"idldoc_min"} and $f->{"idldoc_size"} <= $d->{"idldoc_max"}
!ll&&!rl&&r
000
MC/DC0%0/2
$f->{"idldoc_size"} >= $d->{"idldoc_min"} and $f->{"idldoc_size"} <= $d->{"idldoc_max"}
$f->{"idldoc_size"} >= $d->{"idldoc_min"} $f->{"idldoc_size"} <= $d->{"idldoc_max"}
Truth table0%0/3
A and B
A= $f->{"idldoc_size"} >= $d->{"idldoc_min"}B= $f->{"idldoc_size"} <= $d->{"idldoc_max"}
ABresult
0X0
100
111
3868 }
3869 0 return 'mixte';
3870 }
3871  
3872 # Build the readable report from a schema_Detect result.
3873 0 ▶sub _schema_report_lines {
Subroutine _schema_report_lines: not called CC=6 SCAR=37.4
3874 0 my (%p) = @_;
3875 0 my @lines;
3876  
3877 #push @lines, "schema level: $p{level}";
3878 0 push @lines, "driver: $p{driver}";
3879 0 push @lines, "index table: $p{table}";
3880 0 ▶ if ( my $f = $p{features} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $f = $p{"features"}) 0 0 0
3881 0 push @lines, " primary key: " . join( ', ', @{ $f->{key} } );
3882 0 push @lines, " ed_idjob in key: $f->{idjob_in_key}";
3883 0 push @lines, " ECM columns present: $f->{ecm}/" . scalar @SCHEMA_ECM_COLS;
3884 push @lines,
3885 0 ▶ " ed_idldoc width: " . ( defined $f->{idldoc_size} ? $f->{idldoc_size} : 'n/a' );
Branch: 1 branch
BranchTrueFalseTotal
defined $f->{'idldoc_size'} ? : 0 0 0
3886 }
3887 0 ▶ push @lines, "missing vs T: " . ( @{ $p{missing} } ? join( ', ', @{ $p{missing} } ) : 'none' );
Branch: 1 branch
BranchTrueFalseTotal
@{$p{'missing'};} ? : 0 0 0
3888 0 ▶ push @lines, "narrowed vs T: " . ( @{ $p{shrink} } ? join( ', ', @{ $p{shrink} } ) : 'none' );
Branch: 1 branch
BranchTrueFalseTotal
@{$p{'shrink'};} ? : 0 0 0
3889 0 ▶ push @lines, "verdict: " . ( $p{ok} ? 'conforms to T' : 'does not conform to T' );
Branch: 1 branch
BranchTrueFalseTotal
$p{'ok'} ? : 0 0 0
3890 0 return \@lines;
3891 }
3892  
3893 # Inspect a live base and report its schema level against the T definitions.
3894 # Options: index_table => 'name' (defaults to EDTK_DBI_OUTMNGR from the config).
3895 # READ-ONLY: every statement is a SELECT / PRAGMA; nothing is written.
3896 0 ▶sub schema_Detect {
Subroutine schema_Detect: not called CC=7 SCAR=40.3
Pod documented
3897 0 my ( $dbh, %opt ) = @_;
3898 0 require oEdtk::SchemaScan;
3899  
3900 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
3901 0 ▶ my $index_table = $opt{index_table} // $cfg->{'EDTK_DBI_OUTMNGR'} // 'edtk_outmngr';
Condition0%0/5
($opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}) // "edtk_outmngr"
l!l
00
$opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}) // "edtk_outmngr"
$opt{"index_table"} $cfg->{"EDTK_DBI_OUTMNGR"}
Truth table0%0/3
A // B
A= $opt{"index_table"}B= $cfg->{"EDTK_DBI_OUTMNGR"}
ABresult
1X1
011
000
3902  
3903 0 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
3904 0 my ( $f, $level, $missing, $shrink ) = _schema_assess( $scan, $index_table );
3905  
3906 0 ▶ my $ok = ( $level eq 'T' && !@$missing && !@$shrink ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$level eq 'T' && !@$missing && !@$shrink ? : 0 0 0
Condition0%0/6
$level eq "T" and not @$missing and not @$shrink
!ll&&!rl&&r
000
$level eq "T" and not @$missing
!ll&&!rl&&r
000
MC/DC0%0/3
$level eq "T" and not @$missing and not @$shrink
$level eq "T" not @$missing not @$shrink
Truth table0%0/4
A and not(B) and not(C)
A= $level eq "T"B= not @$missingC= not @$shrink
ABCresult
0XX0
10X0
1100
1111
3907 my $report = _schema_report_lines(
3908 level => $level,
3909 driver => $scan->{driver},
3910 0 table => $index_table,
3911 features => $f,
3912 missing => $missing,
3913 shrink => $shrink,
3914 ok => $ok,
3915 );
3916  
3917 return {
3918 driver => $scan->{driver},
3919 0 index_table => $index_table,
3920 level => $level,
3921 features => $f,
3922 missing => $missing,
3923 shrink => $shrink,
3924 ok => $ok,
3925 report => $report,
3926 };
3927 }
3928  
3929 # The report of schema_Detect as printable text.
3930 0 ▶sub schema_Report {
Subroutine schema_Report: not called CC=2 SCAR=17.9
Pod documented
3931 0 my ($res) = @_;
3932 0 ▶ return join( "\n", @{ $res->{report} // [] } ) . "\n";
Condition0%0/2
$res->{"report"} // []
l!l
00
MC/DC0%0/1
$res->{"report"} // []
$res->{"report"}
Truth table0%0/2
A
A= $res->{"report"}
Aresult
11
00
3933 }
3934  
3935 # READ-ONLY assessment of the index table AND the tracking table against T.
3936 # Returns a probe hash; stale is set when either table does not conform.
3937 0 ▶sub _schema_stale_probe {
Subroutine _schema_stale_probe: not called CC=10 SCAR=47.0
3938 0 my ( $scan, $cfg, $index_table, $tracking_table ) = @_;
3939  
3940 0 my ( $f, $level, $i_missing, $i_shrink ) = _schema_assess( $scan, $index_table );
3941  
3942 0 my ( $t_missing, $t_shrink ) = ( [], [] );
3943 0 ▶ if ( defined $tracking_table && length $tracking_table ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tracking_table and length $tracking_table) 0 0 0
Condition0%0/3
defined $tracking_table and length $tracking_table
!ll&&!rl&&r
000
MC/DC0%0/2
defined $tracking_table and length $tracking_table
defined $tracking_table length $tracking_table
Truth table0%0/3
A and B
A= defined $tracking_tableB= length $tracking_table
ABresult
0X0
100
111
3944 0 ( $t_missing, $t_shrink ) = _schema_col_diff( $scan, $tracking_table, \@TRACKER_COLS );
3945 }
3946  
3947 0 ▶ my $index_ok = ( $level eq 'T' && !@$i_missing && !@$i_shrink ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$level eq 'T' && !@$i_missing && !@$i_shrink ? : 0 0 0
Condition0%0/6
$level eq "T" and not @$i_missing and not @$i_shrink
!ll&&!rl&&r
000
$level eq "T" and not @$i_missing
!ll&&!rl&&r
000
MC/DC0%0/3
$level eq "T" and not @$i_missing and not @$i_shrink
$level eq "T" not @$i_missing not @$i_shrink
Truth table0%0/4
A and not(B) and not(C)
A= $level eq "T"B= not @$i_missingC= not @$i_shrink
ABCresult
0XX0
10X0
1100
1111
3948 0 ▶ my $track_ok = ( !@$t_missing && !@$t_shrink ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!(@$t_missing || @$t_shrink) ? : 0 0 0
Condition0%0/3
@$t_missing || @$t_shrink
l!l&&r!l&&!r
000
MC/DC0%0/2
@$t_missing || @$t_shrink
@$t_missing @$t_shrink
Truth table0%0/3
A || B
A= @$t_missingB= @$t_shrink
ABresult
1X1
011
000
3949  
3950 return {
3951 0 ▶ stale => ( $index_ok && $track_ok ) ? 0 : 1,
Branch: 1 branch
BranchTrueFalseTotal
$index_ok && $track_ok ? : 0 0 0
Condition0%0/3
$index_ok and $track_ok
!ll&&!rl&&r
000
MC/DC0%0/2
$index_ok and $track_ok
$index_ok $track_ok
Truth table0%0/3
A and B
A= $index_okB= $track_ok
ABresult
0X0
100
111
3952 level => $level,
3953 index_table => $index_table,
3954 tracking_table => $tracking_table,
3955 index_missing => $i_missing,
3956 index_shrink => $i_shrink,
3957 track_missing => $t_missing,
3958 track_shrink => $t_shrink,
3959 cfg => $cfg,
3960 };
3961 }
3962  
3963 # Render a ( missing, narrowed ) pair as "missing=a,b narrowed=x (y<z)".
3964 0 ▶sub _schema_diff_text {
Subroutine _schema_diff_text: not called CC=3 SCAR=24.8
3965 0 my ( $missing, $shrink ) = @_;
3966 return
3967 0 ▶ '(missing='
Branch: 2 branches
BranchTrueFalseTotal
@$missing ? : 0 0 0
@$shrink ? : 0 0 0
3968 . ( @$missing ? join( ',', @$missing ) : 'none' )
3969 . ' narrowed='
3970 . ( @$shrink ? join( ',', @$shrink ) : 'none' ) . ')';
3971 }
3972  
3973 # Quote a value for a copy-paste command line (single quotes, embedded quotes
3974 # escaped). An undefined/empty value is returned unchanged.
3975 0 ▶sub _shell_quote {
Subroutine _shell_quote: not called CC=3 SCAR=24.8
3976 0 my ($s) = @_;
3977 0 ▶ return $s unless defined $s && length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s and length $s 0 0 0
Condition0%0/3
defined $s and length $s
!ll&&!rl&&r
000
MC/DC0%0/2
defined $s and length $s
defined $s length $s
Truth table0%0/3
A and B
A= defined $sB= length $s
ABresult
0X0
100
111
3978 0 $s =~ s/'/'\\''/g;
3979 0 return "'$s'";
3980 }
3981  
3982 # A host program may register a renderer here so the remediation hint names a
3983 # command it can actually run (the packaged tracker has no lib/db_migrate.pl);
3984 # coderef ($cfg) -> $hint_string. Defaults to the shipped lib/db_migrate.pl.
3985 32 our $SCHEMA_FIX_HINT;
3986  
3987 # The remediation hint. The password VALUE is never printed. Values are
3988 # shell-quoted so the hint is copy-pasteable. A failing host hook falls back to
3989 # the default form.
3990 0 ▶sub _schema_fix_command {
Subroutine _schema_fix_command: not called CC=8 SCAR=42.8
3991 0 my ($cfg) = @_;
3992  
3993 0 ▶ if ( ref $SCHEMA_FIX_HINT eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $oEdtk::DBAdmin::SCHEMA_FIX_HINT eq "CODE") 0 0 0
3994 0 my $hint = eval { $SCHEMA_FIX_HINT->($cfg) };
3995 0 ▶ return $hint if defined $hint && length $hint;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hint and length $hint 0 0 0
Condition0%0/3
defined $hint and length $hint
!ll&&!rl&&r
000
MC/DC0%0/2
defined $hint and length $hint
defined $hint length $hint
Truth table0%0/3
A and B
A= defined $hintB= length $hint
ABresult
0X0
100
111
3996 }
3997  
3998 0 ▶ my $dsn = $cfg->{EDTK_DBI_DSN} // '';
Condition0%0/2
$cfg->{"EDTK_DBI_DSN"} // ""
l!l
00
MC/DC0%0/1
$cfg->{"EDTK_DBI_DSN"} // ""
$cfg->{"EDTK_DBI_DSN"}
Truth table0%0/2
A
A= $cfg->{"EDTK_DBI_DSN"}
Aresult
11
00
3999 0 $dsn =~ s/(pass(word)?=)[^;]*/$1***/gi; # mask an inline secret, if any
4000 0 ▶ $dsn = '<dsn>' unless length $dsn;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dsn 0 0 0
4001 0 $dsn = _shell_quote($dsn);
4002 0 my $user = $cfg->{EDTK_DBI_DSN_USER};
4003 0 my $cmd = "perl lib/db_migrate.pl --check-only --dsn $dsn ; then";
4004 0 $cmd .= " perl lib/db_migrate.pl --additive --dsn $dsn";
4005 0 ▶ $cmd .= ' --user ' . _shell_quote($user) if defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
if defined $user and length $user 0 0 0
Condition0%0/3
defined $user and length $user
!ll&&!rl&&r
000
MC/DC0%0/2
defined $user and length $user
defined $user length $user
Truth table0%0/3
A and B
A= defined $userB= length $user
ABresult
0X0
100
111
4006 0 $cmd .= ' --pass <pass>';
4007 0 return $cmd;
4008 }
4009  
4010 # The one-line operator message for a stale schema (see _schema_stale_probe).
4011 0 ▶sub _schema_stale_message {
Subroutine _schema_stale_message: not called CC=7 SCAR=40.3
4012 0 my ($p) = @_;
4013 0 my @parts = ("database schema is STALE vs T (level=$p->{level})");
4014 push @parts, "$p->{index_table} " . _schema_diff_text( $p->{index_missing}, $p->{index_shrink} )
4015 0 ▶ if ( @{ $p->{index_missing} } || @{ $p->{index_shrink} } );
Branch: 1 branch
BranchTrueFalseTotal
if @{$p->{"index_missing"};} or @{$p->{"index_shrink"};} 0 0 0
Condition0%0/3
@{$p->{"index_missing"};} or @{$p->{"index_shrink"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$p->{"index_missing"};} or @{$p->{"index_shrink"};}
@{$p->{"index_missing"};} @{$p->{"index_shrink"};}
Truth table0%0/3
A or B
A= @{$p->{"index_missing"};}B= @{$p->{"index_shrink"};}
ABresult
1X1
011
000
4016 push @parts,
4017 "$p->{tracking_table} " . _schema_diff_text( $p->{track_missing}, $p->{track_shrink} )
4018 if ( ( defined $p->{tracking_table} && length $p->{tracking_table} )
4019 0 ▶ && ( @{ $p->{track_missing} } || @{ $p->{track_shrink} } ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tracking_table"} and length $p->{"tracking_table"} and @{$p->{"track_missing"};} || @{$p->{"track_shrink"};} 0 0 0
Condition0%0/9
defined $p->{"tracking_table"} and length $p->{"tracking_table"} and @{$p->{"track_missing"};} || @{$p->{"track_shrink"};}
!ll&&!rl&&r
000
defined $p->{"tracking_table"} and length $p->{"tracking_table"}
!ll&&!rl&&r
000
@{$p->{"track_missing"};} or @{$p->{"track_shrink"};}
l!l&&r!l&&!r
000
MC/DC0%0/4
defined $p->{"tracking_table"} and length $p->{"tracking_table"} and @{$p->{"track_missing"};} || @{$p->{"track_shrink"};}
defined $p->{"tracking_table"} length $p->{"tracking_table"} @{$p->{"track_missing"};} @{$p->{"track_shrink"};}
Truth table0%0/5
A and B and C or D
A= defined $p->{"tracking_table"}B= length $p->{"tracking_table"}C= @{$p->{"track_missing"};}D= @{$p->{"track_shrink"};}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
4020 0 push @parts, 'to fix: ' . _schema_fix_command( $p->{cfg} );
4021 0 return join( '; ', @parts );
4022 }
4023  
4024 # Report a stale schema ONCE, READ-ONLY, never fatal. Options: cfg, index_table,
4025 # tracking_table (all default to the EDTK_DB configuration). Returns the probe
4026 # when a warning was emitted, undef otherwise. It never writes to the database.
4027 0 ▶sub schema_StaleWarning {
Subroutine schema_StaleWarning: not called CC=8 SCAR=42.8
Pod documented
4028 0 my ( $dbh, %opt ) = @_;
4029 0 ▶ return unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 0 0 0
4030  
4031 0 ▶ my $cfg = $opt{cfg} || ( eval { config_read('EDTK_DB') } || {} );
Condition0%0/5
$opt{'cfg'} || (eval { do { config_read('EDTK_DB') } } || {})
l!l&&r!l&&!r
000
eval { do { config_read("EDTK_DB") } } or {}
l!l
00
MC/DC0%0/2
$opt{'cfg'} || (eval { do { config_read('EDTK_DB') } } || {})
$opt{'cfg'} eval { do { config_read("EDTK_DB") } }
Truth table0%0/3
A || B
A= $opt{'cfg'}B= eval { do { config_read("EDTK_DB") } }
ABresult
1X1
011
000
4032 0 ▶ my $index_table = $opt{index_table} // $cfg->{'EDTK_DBI_OUTMNGR'} // 'edtk_outmngr';
Condition0%0/5
($opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}) // "edtk_outmngr"
l!l
00
$opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($opt{"index_table"} // $cfg->{"EDTK_DBI_OUTMNGR"}) // "edtk_outmngr"
$opt{"index_table"} $cfg->{"EDTK_DBI_OUTMNGR"}
Truth table0%0/3
A // B
A= $opt{"index_table"}B= $cfg->{"EDTK_DBI_OUTMNGR"}
ABresult
1X1
011
000
4033 0 ▶ my $tracking_table = $opt{tracking_table} // $cfg->{'EDTK_DBI_TRACKING'};
Condition0%0/3
$opt{"tracking_table"} // $cfg->{"EDTK_DBI_TRACKING"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt{"tracking_table"} // $cfg->{"EDTK_DBI_TRACKING"}
$opt{"tracking_table"} $cfg->{"EDTK_DBI_TRACKING"}
Truth table0%0/3
A // B
A= $opt{"tracking_table"}B= $cfg->{"EDTK_DBI_TRACKING"}
ABresult
1X1
011
000
4034  
4035 # A warn()/die() below must not re-enter the oEdtk::Tracking __WARN__/__DIE__
4036 # handlers (they would call track() recursively). Neutralize them for this
4037 # call only; they are restored on return, so Halt-tracking still works.
4038 0 return do {
4039 0 local $SIG{__WARN__} = 'DEFAULT';
4040 0 local $SIG{__DIE__} = 'DEFAULT';
4041 0 eval {
4042 0 require oEdtk::SchemaScan;
4043 0 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4044 0 my $p = _schema_stale_probe( $scan, $cfg, $index_table, $tracking_table );
4045 0 ▶ return unless $p->{stale};
Branch: 1 branch
BranchTrueFalseTotal
unless $p->{"stale"} 0 0 0
4046 0 &logger( 3, _schema_stale_message($p) );
4047 0 return $p;
4048 };
4049 };
4050 }
4051  
4052 # Additive detection / migration history (S51a). Kept out of schema_Create on
4053 # purpose: adding it there would change the T golden schema.
4054 0 ▶sub create_table_SCHEMA_HISTORY {
Subroutine create_table_SCHEMA_HISTORY: not called CC=3 SCAR=24.8
Pod undocumented
4055 0 my ( $dbh, $table ) = @_;
4056 0 ▶ $table //= 'edtk_schema_history';
Condition0%0/2
$table //= "edtk_schema_history"
l!l
00
MC/DC0%0/1
$table //= "edtk_schema_history"
$table
Truth table0%0/2
A
A= $table
Aresult
11
00
4057  
4058 0 my $sql = "create table if not exists $table ";
4059 0 $sql .= "( ed_hist_date varchar2(14) not null"; # detection / migration timestamp
4060 0 $sql .= ", ed_hist_from varchar2(8)"; # source level (F, M, T, mixte)
4061 0 $sql .= ", ed_hist_to varchar2(8)"; # target level
4062 0 $sql .= ", ed_hist_mode varchar2(16)"; # check / historize / additive
4063 0 $sql .= ", ed_hist_tool varchar2(32)"; # tool and version
4064 0 $sql .= ", ed_hist_counts varchar2(255)"; # row counts, "k=v;k=v"
4065 0 $sql .= " )";
4066 0 $sql .= _db_engine_clause($dbh);
4067 0 &logger( 7, $sql );
4068  
4069 0 ▶ _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
Branch: 1 branch
BranchTrueFalseTotal
_db_do_ddl($dbh, $sql) or &logger(3, $dbh->errstr) 0 0 0
4070 0 return 0;
4071 }
4072  
4073 # Append one history row. Named parameters: date, from, to, mode, tool and
4074 # counts (a hash ref, stored as a compact "k=v;k=v" string).
4075 0 ▶sub schema_History_add {
Subroutine schema_History_add: not called CC=9 SCAR=45.0
Pod documented
4076 0 my ( $dbh, %p ) = @_;
4077 0 ▶ my $table = $p{table} // 'edtk_schema_history';
Condition0%0/2
$p{"table"} // "edtk_schema_history"
l!l
00
MC/DC0%0/1
$p{"table"} // "edtk_schema_history"
$p{"table"}
Truth table0%0/2
A
A= $p{"table"}
Aresult
11
00
4078 0 create_table_SCHEMA_HISTORY( $dbh, $table );
4079  
4080 0 ▶ my $date = $p{date} // strftime( '%Y%m%d%H%M%S', localtime );
Condition0%0/3
$p{"date"} // strftime("%Y%m%d%H%M%S", localtime)
l!l&&r!l&&!r
000
MC/DC0%0/2
$p{"date"} // strftime("%Y%m%d%H%M%S", localtime)
$p{"date"} strftime("%Y%m%d%H%M%S", localtime)
Truth table0%0/3
A // B
A= $p{"date"}B= strftime("%Y%m%d%H%M%S", localtime)
ABresult
1X1
011
000
4081 0 ▶ my $tool = $p{tool} // __PACKAGE__ . " $VERSION";
Condition0%0/2
$p{"tool"} // 'oEdtk::DBAdmin' . " $oEdtk::DBAdmin::VERSION"
l!l
00
MC/DC0%0/1
$p{"tool"} // 'oEdtk::DBAdmin' . " $oEdtk::DBAdmin::VERSION"
$p{"tool"}
Truth table0%0/2
A
A= $p{"tool"}
Aresult
11
00
4082  
4083 0 my $counts = $p{counts};
4084 0 my $ctext = '';
4085 0 ▶ if ( ref $counts eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $counts eq 'HASH') { } 0 0 0
elsif (defined $counts) { } 0 0 0
4086 $ctext = join( ';',
4087 0 ▶ map { "$_=" . ( defined $counts->{$_} ? $counts->{$_} : '' ) } sort keys %$counts );
Branch: 1 branch
BranchTrueFalseTotal
defined $counts->{$_} ? : 0 0 0
4088 }
4089 elsif ( defined $counts ) {
4090 0 $ctext = "$counts";
4091 }
4092 0 $ctext = substr( $ctext, 0, 255 );
4093  
4094 0 local $dbh->{PrintError} = 0;
4095 my $ok = $dbh->do(
4096 "insert into $table "
4097 . "(ed_hist_date,ed_hist_from,ed_hist_to,ed_hist_mode,ed_hist_tool,ed_hist_counts) "
4098 . "values (?,?,?,?,?,?)",
4099 0 undef, $date, $p{from}, $p{to}, $p{mode}, $tool, $ctext
4100 );
4101 0 ▶ &logger( 3, $dbh->errstr ) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
4102 0 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 0 0
4103 }
4104  
4105 # ============================================================
4106 # Update by historisation (S51b, PLAN annexe D, decision D17). The recommended
4107 # procedure: build a T-shaped target, copy the data by NAMED columns, validate by
4108 # counts and checksums, switch over, and KEEP the old schema as history. The
4109 # service schema is never modified in place; nothing is ever dropped.
4110 #
4111 # Portable algorithm (mirrors schema_Upgrade's timestamped rename):
4112 # 1. rename every live table to <table><HIST_SEP><stamp> (kept, not dropped);
4113 # 2. build the T target under the original names (schema_Create + extension);
4114 # 3. copy the common columns by name, then validate (count + md5 checksum);
4115 # 4. give the kept history its indexes back under non-colliding names;
4116 # 5. keep the stamped tables and append one EDTK_SCHEMA_HISTORY row.
4117 # Atomicity: on a driver with transactional DDL (SQLite, PostgreSQL) the whole
4118 # run is one transaction, so any failure rolls the service schema back. On the
4119 # others (MariaDB, MySQL, Oracle) the captured renames are inverted explicitly.
4120 # Nothing is written by schema_MigrationPlan (--check-only / --dry-run).
4121 # ============================================================
4122  
4123 32 ▶use constant SCHEMA_HIST_SEP => '_hist_';
Subroutine BEGIN: called CC=1 SCAR=0.0
4124  
4125 # The ordered, de-duplicated list of tables the migration covers: the fixed base
4126 # tables, the configuration-driven ones, the tracking table and any extension
4127 # table. This is the same set schema_Create (plus create_table_TRACKING) builds.
4128 0 ▶sub schema_Manifest {
Subroutine schema_Manifest: not called CC=6 SCAR=37.4
Pod documented
4129 0 my ($cfg) = @_;
4130 0 ▶ $cfg //= eval { config_read('EDTK_DB') } || {};
Condition0%0/4
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
l!l
00
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
$cfg
Truth table0%0/2
A
A= $cfg
Aresult
11
00
4131  
4132 0 my @fixed = qw( edtk_acq edtk_admin edtk_agrege edtk_filieres edtk_id edtk_lots
4133 edtk_refiddoc edtk_supports );
4134 0 ▶ my @cfg = grep { defined && length }
Condition0%0/3
defined $_ && length $_
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table0%0/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
4135 0 map { $cfg->{$_} }
4136 qw( EDTK_DBI_OUTMNGR EDTK_DBI_OUTMNGR_STATS EDTK_DBI_DISTRIB EDTK_DBI_DISTRIB_STATS );
4137 0 ▶ my @track = grep { defined && length } ( $cfg->{'EDTK_DBI_TRACKING'} );
Condition0%0/3
defined $_ && length $_
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table0%0/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
4138 0 ▶ my @ext = sort keys %{ _schema_extra()->{tables} // {} };
Condition0%0/2
_schema_extra()->{"tables"} // {}
l!l
00
MC/DC0%0/1
_schema_extra()->{"tables"} // {}
_schema_extra()->{"tables"}
Truth table0%0/2
A
A= _schema_extra()->{"tables"}
Aresult
11
00
4139  
4140 0 my %seen;
4141 0 return grep { !$seen{$_}++ } ( @fixed, @cfg, @track, @ext );
4142 }
4143  
4144 # Drivers whose DDL is transactional: a failure can roll the whole run back.
4145 0 ▶sub _schema_txn_ddl {
Subroutine _schema_txn_ddl: not called CC=3 SCAR=24.8
4146 0 my ($dbh) = @_;
4147 0 my $driver = _db_check_driver_name($dbh);
4148 0 ▶ return ( $driver eq 'SQLite' || $driver eq 'PostgreSQL' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$driver eq 'SQLite' || $driver eq 'PostgreSQL' ? : 0 0 0
Condition0%0/3
$driver eq "SQLite" or $driver eq "PostgreSQL"
l!l&&r!l&&!r
000
MC/DC0%0/2
$driver eq "SQLite" or $driver eq "PostgreSQL"
$driver eq "SQLite" $driver eq "PostgreSQL"
Truth table0%0/3
A or B
A= $driver eq "SQLite"B= $driver eq "PostgreSQL"
ABresult
1X1
011
000
4149 }
4150  
4151 # Rename a table, driver-neutrally (MariaDB/MySQL use RENAME TABLE).
4152 0 ▶sub _schema_rename_table {
Subroutine _schema_rename_table: not called CC=2 SCAR=17.9
4153 0 my ( $dbh, $from, $to ) = @_;
4154 0 my $driver = _db_check_driver_name($dbh);
4155 0 ▶ my $sql =
Branch: 1 branch
BranchTrueFalseTotal
$driver eq 'mysql' ? : 0 0 0
4156 ( $driver eq 'mysql' )
4157 ? "rename table $from to $to"
4158 : "alter table $from rename to $to";
4159 0 &logger( 7, $sql );
4160 0 return _db_do_ddl( $dbh, $sql );
4161 }
4162  
4163 # A history name that is free: <table>_hist_<stamp>[_n] when taken.
4164 0 ▶sub _schema_hist_name {
Subroutine _schema_hist_name: not called CC=2 SCAR=17.9
4165 0 my ( $dbh, $table, $stamp ) = @_;
4166 0 my $base = $table . SCHEMA_HIST_SEP . $stamp;
4167 0 my $name = $base;
4168 0 my $n = 1;
4169 0 ▶ $name = $base . '_' . $n++ while _table_exists( $dbh, $name );
Branch: 1 branch
BranchTrueFalseTotal
_table_exists($dbh, $name) and do { $name = $base . '_' . $n++ } 0 0 0
4170 0 return $name;
4171 }
4172  
4173 # The secondary indexes of a table, as portable specs (name, unique, columns).
4174 # Best effort: an unreadable catalogue (unsupported driver) yields none.
4175 0 ▶sub _schema_index_specs {
Subroutine _schema_index_specs: not called CC=4 SCAR=30.0
4176 0 my ( $dbh, $table ) = @_;
4177 0 require oEdtk::SchemaScan;
4178 0 ▶ my $scan = eval { oEdtk::SchemaScan::scan_schema($dbh) } or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $scan = eval { do { oEdtk::SchemaScan::scan_schema($dbh) } } or return [] 0 0 0
4179 0 ▶ my $t = _schema_scan_table( $scan, $table ) or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $t = _schema_scan_table($scan, $table) or return [] 0 0 0
4180 return [
4181 0 map { { name => $_->{name}, unique => $_->{unique}, columns => $_->{columns} } }
4182 0 ▶ grep { $_->{name} !~ /^sqlite_autoindex_/ } @{ $t->{indexes} // [] }
Condition0%0/2
$t->{"indexes"} // []
l!l
00
MC/DC0%0/1
$t->{"indexes"} // []
$t->{"indexes"}
Truth table0%0/2
A
A= $t->{"indexes"}
Aresult
11
00
4183 ];
4184 }
4185  
4186 # On SQLite/PostgreSQL/Oracle index names are unique per schema, so after the
4187 # rename the history table still owns the original names and the target's
4188 # "CREATE INDEX IF NOT EXISTS" would be skipped. Drop the history's indexes to
4189 # free the names. MariaDB/MySQL index names are table-scoped and never collide,
4190 # so nothing is touched there.
4191 0 ▶sub _schema_release_indexes {
Subroutine _schema_release_indexes: not called CC=3 SCAR=24.8
4192 0 my ( $dbh, $table, $specs ) = @_;
4193 0 ▶ return if _db_check_driver_name($dbh) eq 'mysql';
Branch: 1 branch
BranchTrueFalseTotal
if _db_check_driver_name($dbh) eq "mysql" 0 0 0
4194 0 for my $ix (@$specs) {
4195 0 eval { _db_do_ddl( $dbh, "drop index $ix->{name}" ) };
4196 }
4197 0 return;
4198 }
4199  
4200 # Recreate index specs on a table, appending $suffix to each name (empty to
4201 # restore the original names). Best effort: never throws.
4202 0 ▶sub _schema_restore_indexes {
Subroutine _schema_restore_indexes: not called CC=5 SCAR=34.0
4203 0 my ( $dbh, $table, $specs, $suffix ) = @_;
4204 0 ▶ return if _db_check_driver_name($dbh) eq 'mysql';
Branch: 1 branch
BranchTrueFalseTotal
if _db_check_driver_name($dbh) eq "mysql" 0 0 0
4205 0 for my $ix (@$specs) {
4206 0 ▶ my $u = $ix->{unique} ? 'unique ' : '';
Branch: 1 branch
BranchTrueFalseTotal
$ix->{'unique'} ? : 0 0 0
4207 0 my $cols = join( ', ', @{ $ix->{columns} } );
4208 0 ▶ next unless length $cols;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cols 0 0 0
4209 0 eval {
4210 0 _db_do_ddl( $dbh,
4211 "create ${u}index if not exists $ix->{name}$suffix on $table ( $cols )" );
4212 };
4213 }
4214 0 return;
4215 }
4216  
4217 # The ordered column names of a table (catalogue read).
4218 0 ▶sub _schema_columns {
Subroutine _schema_columns: not called CC=1 SCAR=6.9
4219 0 my ( $dbh, $table ) = @_;
4220 0 return get_columns_names( $dbh, $table );
4221 }
4222  
4223 # The primary-key columns of a table, in key order (lower-cased). Best effort:
4224 # an unreadable catalogue yields none and the caller falls back to all columns.
4225 0 ▶sub _schema_key_columns {
Subroutine _schema_key_columns: not called CC=4 SCAR=30.0
4226 0 my ( $dbh, $table ) = @_;
4227 0 require oEdtk::SchemaScan;
4228 0 ▶ my $scan = eval { oEdtk::SchemaScan::scan_schema($dbh) } or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $scan = eval { do { oEdtk::SchemaScan::scan_schema($dbh) } } or return () 0 0 0
4229 0 ▶ my $t = _schema_scan_table( $scan, $table ) or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $t = _schema_scan_table($scan, $table) or return () 0 0 0
4230 0 return map { lc $_->{name} }
4231 0 ▶ sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @{ $t->{columns} // [] };
Condition0%0/2
$t->{"columns"} // []
l!l
00
MC/DC0%0/1
$t->{"columns"} // []
$t->{"columns"}
Truth table0%0/2
A
A= $t->{"columns"}
Aresult
11
00
4232 }
4233  
4234 # The columns common to a source and a target, in the target's order. Returned
4235 # as the target spelling so the INSERT list and the SELECT list agree.
4236 0 ▶sub _schema_common_columns {
Subroutine _schema_common_columns: not called CC=1 SCAR=6.9
4237 0 my ( $dbh, $source, $target ) = @_;
4238 0 my @src = _schema_columns( $dbh, $source );
4239 0 my %src = map { lc($_) => $_ } @src;
4240 0 return grep { exists $src{ lc($_) } } _schema_columns( $dbh, $target );
4241 }
4242  
4243 # INSERT ... SELECT with NAMED column lists (never positional).
4244 0 ▶sub _schema_copy_named {
Subroutine _schema_copy_named: not called CC=2 SCAR=17.9
4245 0 my ( $dbh, $source, $target, $cols ) = @_;
4246 0 my $list = join( ', ', @$cols );
4247 0 my $sql = "insert into $target ( $list ) select $list from $source";
4248 0 &logger( 7, $sql );
4249 0 local $dbh->{PrintError} = 0;
4250 0 $dbh->do($sql);
4251 0 ▶ return defined $dbh->err ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $dbh->err ? : 0 0 0
4252 }
4253  
4254 # A driver-neutral md5 over a table's rows, projected on $cols and ordered by
4255 # $order. Used to prove the copy preserved every value of the common columns.
4256 0 ▶sub _schema_checksum {
Subroutine _schema_checksum: not called CC=4 SCAR=30.0
4257 0 my ( $dbh, $table, $cols, $order ) = @_;
4258 0 my $list = join( ', ', @$cols );
4259 0 my $sql = "select $list from $table";
4260 0 ▶ $sql .= " order by " . join( ', ', @$order ) if @$order;
Branch: 1 branch
BranchTrueFalseTotal
if @$order 0 0 0
4261 0 my $sth = $dbh->prepare($sql);
4262 0 $sth->execute;
4263 0 my $md5 = Digest::MD5->new;
4264 0 ▶ while ( my @row = $sth->fetchrow_array ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@row) = $sth->fetchrow_array) 0 0 0
4265 0 ▶ $md5->add( join( "\x1f", map { defined $_ ? $_ : "\x00" } @row ), "\n" );
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
4266 }
4267 0 return $md5->hexdigest;
4268 }
4269  
4270 # Build the T target once, in a throwaway in-memory SQLite base, to learn each
4271 # table's columns and the DDL schema_Create emits. Best effort: {} on failure.
4272 0 ▶sub _schema_target_model {
Subroutine _schema_target_model: not called CC=6 SCAR=37.4
4273 0 my ($cfg) = @_;
4274 0 ▶ $cfg //= eval { config_read('EDTK_DB') } || {};
Condition0%0/4
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
l!l
00
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
$cfg
Truth table0%0/2
A
A= $cfg
Aresult
11
00
4275 0 my %model;
4276 0 eval {
4277 0 ▶ my $m =
Branch: 1 branch
BranchTrueFalseTotal
my $m = "DBI"->connect("dbi:SQLite:dbname=:memory:", "", "", {"RaiseError", 1, "PrintError", 0, "AutoCommit", 1}) or return 0 0 0
4278 DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '',
4279 { RaiseError => 1, PrintError => 0, AutoCommit => 1 } )
4280 or return;
4281 {
4282 0 local $m->{PrintError} = 0;
4283 0 eval { create_lot_sequence($m) };
4284 0 eval { schema_Create($m) };
4285 eval {
4286 create_table_TRACKING(
4287 $m,
4288 $cfg->{'EDTK_DBI_TRACKING'},
4289 0 $cfg->{'EDTK_MAX_USER_KEY'}
4290 );
4291 }
4292 0 ▶ if $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_TRACKING"} 0 0 0
4293 }
4294 0 my $rows =
4295 $m->selectall_arrayref(
4296 "select name, sql from sqlite_master where type='table' and name not like 'sqlite_%' order by name"
4297 );
4298 0 for my $r (@$rows) {
4299 0 my ( $name, $ddl ) = @$r;
4300 0 my @cols = map { lc } _schema_columns( $m, $name );
4301 0 $model{ lc $name } = { name => $name, columns => \@cols, ddl => $ddl };
4302 }
4303 0 $m->disconnect;
4304 };
4305 0 return \%model;
4306 }
4307  
4308 # Read-only plan for an update by historisation (--check-only / --dry-run). It
4309 # reports the detected level, the per-table column sets and the copy SQL. It
4310 # writes nothing: every statement it prepares is a SELECT / PRAGMA.
4311 0 ▶sub schema_MigrationPlan {
Subroutine schema_MigrationPlan: not called CC=11 SCAR=48.8
Pod documented
4312 0 my ( $dbh, %opt ) = @_;
4313 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
4314 0 ▶ my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
Condition0%0/2
$opt{"manifest"} // [schema_Manifest($cfg)]
l!l
00
MC/DC0%0/1
$opt{"manifest"} // [schema_Manifest($cfg)]
$opt{"manifest"}
Truth table0%0/2
A
A= $opt{"manifest"}
Aresult
11
00
4315 0 my $model = _schema_target_model($cfg);
4316 0 my $detect = schema_Detect( $dbh, %opt );
4317 0 ▶ my $stamp = $opt{stamp} // '<stamp>';
Condition0%0/2
$opt{"stamp"} // "<stamp>"
l!l
00
MC/DC0%0/1
$opt{"stamp"} // "<stamp>"
$opt{"stamp"}
Truth table0%0/2
A
A= $opt{"stamp"}
Aresult
11
00
4318  
4319 0 my @tables;
4320 my @copy_sql;
4321 0 for my $t (@$manifest) {
4322 0 my $has = _table_exists( $dbh, $t );
4323 0 my $target = $model->{ lc $t };
4324 0 ▶ my @tcols = $target ? @{ $target->{columns} } : ();
Branch: 1 branch
BranchTrueFalseTotal
$target ? : 0 0 0
4325 0 my ( $src, $rows ) = ( [], 0 );
4326 0 ▶ if ($has) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has) 0 0 0
4327 0 $src = [ map { lc } _schema_columns( $dbh, $t ) ];
4328 0 ($rows) = $dbh->selectrow_array("select count(*) from $t");
4329 }
4330 0 my %s = map { $_ => 1 } @$src;
4331 0 my %d = map { $_ => 1 } @tcols;
4332  
4333 # Common columns in the target's order (lower-cased, name-matched).
4334 0 my @common = grep { $s{$_} } @tcols;
4335 0 my @dropped = grep { !$d{$_} } @$src; # present in source, absent in T
4336 0 my @defaulted = grep { !$s{$_} } @tcols; # absent in source, filled by T
4337  
4338 0 ▶ push @tables,
Branch: 1 branch
BranchTrueFalseTotal
$has ? : 0 0 0
4339 {
4340 name => $t,
4341 present => ( $has ? 1 : 0 ),
4342 rows => ( $rows + 0 ),
4343 common => \@common,
4344 dropped => \@dropped,
4345 defaulted => \@defaulted,
4346 };
4347 0 ▶ if ( $has && @common ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has and @common) 0 0 0
Condition0%0/3
$has and @common
!ll&&!rl&&r
000
MC/DC0%0/2
$has and @common
$has @common
Truth table0%0/3
A and B
A= $hasB= @common
ABresult
0X0
100
111
4348 0 my $list = join( ', ', @common );
4349 0 my $hist = $t . SCHEMA_HIST_SEP . $stamp;
4350 0 push @copy_sql, "insert into $t ( $list ) select $list from $hist";
4351 }
4352 }
4353  
4354 0 my @report;
4355  
4356 #push @report, "schema level: $detect->{level}";
4357 0 push @report, "driver: $detect->{driver}";
4358 0 push @report, "target level: T";
4359 0 push @report, "history stamp: $stamp";
4360 0 push @report, sprintf( "tables: %d", scalar @tables );
4361 0 for my $t (@tables) {
4362 push @report,
4363 sprintf(
4364 " %-28s source rows=%-6d common=%-3d dropped=%-3d defaulted=%d",
4365 $t->{name}, $t->{rows},
4366 0 scalar @{ $t->{common} },
4367 0 scalar @{ $t->{dropped} },
4368 0 scalar @{ $t->{defaulted} }
4369 );
4370 }
4371  
4372 return {
4373 level => $detect->{level},
4374 driver => $detect->{driver},
4375 0 stamp => $stamp,
4376 tables => \@tables,
4377 copy_sql => \@copy_sql,
4378 model => $model,
4379 detect => $detect,
4380 report => \@report,
4381 };
4382 }
4383  
4384 # Perform the update by historisation. Options: stamp, manifest, checkpoint (a
4385 # code ref called after each table's copy; a die aborts and rolls back),
4386 # keep_old (default 1 -- the stamped tables are kept) and force (act even when
4387 # the base is already T). An already T base is a no-op (result field noop => 1).
4388 # Returns a result hash.
4389 0 ▶sub schema_Historize {
Subroutine schema_Historize: not called CC=15 SCAR=54.8
Pod documented
4390 0 my ( $dbh, %opt ) = @_;
4391 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
4392 0 ▶ my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
Condition0%0/2
$opt{"manifest"} // [schema_Manifest($cfg)]
l!l
00
MC/DC0%0/1
$opt{"manifest"} // [schema_Manifest($cfg)]
$opt{"manifest"}
Truth table0%0/2
A
A= $opt{"manifest"}
Aresult
11
00
4393 0 ▶ my $stamp = $opt{stamp} // strftime( '%Y%m%d_%H%M%S', localtime );
Condition0%0/3
$opt{"stamp"} // strftime("%Y%m%d_%H%M%S", localtime)
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt{"stamp"} // strftime("%Y%m%d_%H%M%S", localtime)
$opt{"stamp"} strftime("%Y%m%d_%H%M%S", localtime)
Truth table0%0/3
A // B
A= $opt{"stamp"}B= strftime("%Y%m%d_%H%M%S", localtime)
ABresult
1X1
011
000
4394 0 my $detect = schema_Detect( $dbh, %opt );
4395 0 my $txn = _schema_txn_ddl($dbh);
4396 0 ▶ my $own = $dbh->{AutoCommit} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->{'AutoCommit'} ? : 0 0 0
4397  
4398 # Idempotent replay: an already T-conformant base is left untouched (no new
4399 # history snapshot). Detection keys on the index table (EDTK_DBI_OUTMNGR).
4400 0 ▶ if ( !$opt{force} && $detect->{level} eq 'T' && $detect->{ok} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt{"force"} and $detect->{"level"} eq "T" and $detect->{"ok"}) 0 0 0
Condition0%0/6
not $opt{"force"} and $detect->{"level"} eq "T" and $detect->{"ok"}
!ll&&!rl&&r
000
not $opt{"force"} and $detect->{"level"} eq "T"
!ll&&!rl&&r
000
MC/DC0%0/3
not $opt{"force"} and $detect->{"level"} eq "T" and $detect->{"ok"}
not $opt{"force"} $detect->{"level"} eq "T" $detect->{"ok"}
Truth table0%0/4
not(A) and B and C
A= not $opt{"force"}B= $detect->{"level"} eq "T"C= $detect->{"ok"}
ABCresult
0XX0
10X0
1100
1111
4401 return {
4402 0 ok => 1,
4403 noop => 1,
4404 from => 'T',
4405 to => 'T',
4406 stamp => $stamp,
4407 renamed => [],
4408 rows => {},
4409 };
4410 }
4411  
4412 0 my @renamed; # [ table, hist_name, index_specs ]
4413 my %rows; # table => source row count
4414  
4415 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=17 SCAR=57.2
4416 0 ▶ $dbh->begin_work if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4417  
4418 # 1. move every live table aside (kept) and free its index names.
4419 0 for my $t (@$manifest) {
4420 0 ▶ next unless _table_exists( $dbh, $t );
Branch: 1 branch
BranchTrueFalseTotal
unless _table_exists($dbh, $t) 0 0 0
4421 0 my $specs = _schema_index_specs( $dbh, $t );
4422 0 my $hist = _schema_hist_name( $dbh, $t, $stamp );
4423 0 ▶ die "rename failed: $t -> $hist\n"
Branch: 1 branch
BranchTrueFalseTotal
unless _schema_rename_table($dbh, $t, $hist) 0 0 0
4424 unless _schema_rename_table( $dbh, $t, $hist );
4425 0 _schema_release_indexes( $dbh, $hist, $specs );
4426 0 push @renamed, [ $t, $hist, $specs ];
4427 }
4428  
4429 # 2. build the T target under the original names (extension included).
4430 0 schema_Create($dbh);
4431 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
4432 0 ▶ if $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_TRACKING"} 0 0 0
4433  
4434 # 3. copy the common columns by name, then validate.
4435 0 for my $pair (@renamed) {
4436 0 my ( $t, $hist ) = @$pair;
4437 0 my @common = _schema_common_columns( $dbh, $hist, $t );
4438 0 ▶ die "no common column between $hist and $t\n" unless @common;
Branch: 1 branch
BranchTrueFalseTotal
unless @common 0 0 0
4439 0 my @order = _schema_key_columns( $dbh, $t );
4440 0 ▶ @order = @common unless @order;
Branch: 1 branch
BranchTrueFalseTotal
unless @order 0 0 0
4441  
4442 0 ▶ die "copy failed: $hist -> $t\n"
Branch: 1 branch
BranchTrueFalseTotal
unless _schema_copy_named($dbh, $hist, $t, \@common) 0 0 0
4443 unless _schema_copy_named( $dbh, $hist, $t, \@common );
4444  
4445 0 my ($ns) = $dbh->selectrow_array("select count(*) from $hist");
4446 0 my ($nt) = $dbh->selectrow_array("select count(*) from $t");
4447 0 ▶ die "row count differs on $t: source=$ns target=$nt\n" if $ns != $nt;
Branch: 1 branch
BranchTrueFalseTotal
if $ns != $nt 0 0 0
4448 0 $rows{$t} = $ns + 0;
4449  
4450 0 my $cs = _schema_checksum( $dbh, $hist, \@common, \@order );
4451 0 my $ct = _schema_checksum( $dbh, $t, \@common, \@order );
4452 0 ▶ die "checksum differs on $t\n" if $cs ne $ct;
Branch: 1 branch
BranchTrueFalseTotal
if $cs ne $ct 0 0 0
4453  
4454 0 ▶ $opt{checkpoint}->($t) if $opt{checkpoint};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"checkpoint"} 0 0 0
4455 }
4456  
4457 # 4. give the kept history its indexes back, under names that cannot
4458 # collide with the freshly built target's.
4459 0 for my $pair (@renamed) {
4460 0 my ( $t, $hist, $specs ) = @$pair;
4461 0 _schema_restore_indexes( $dbh, $hist, $specs, SCHEMA_HIST_SEP . $stamp );
4462 }
4463  
4464 0 ▶ $dbh->commit if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4465 0 return 1;
4466 0 };
4467  
4468 0 my $ok = eval { $run->(); 1 };
4469 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
4470 0 ▶ my $err = $@ // 'unknown error';
Condition0%0/2
$@ // "unknown error"
l!l
00
MC/DC0%0/1
$@ // "unknown error"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
4471 0 ▶ if ( $own && $txn ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($own and $txn) { } 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4472 0 eval { $dbh->rollback };
4473 }
4474 else {
4475  
4476 # No transactional DDL: invert the captured renames explicitly.
4477 0 for my $pair ( reverse @renamed ) {
4478 0 my ( $t, $hist, $specs ) = @$pair;
4479 0 eval {
4480 0 _db_do_ddl( $dbh, "drop table if exists $t" );
4481 0 _schema_rename_table( $dbh, $hist, $t );
4482 0 _schema_restore_indexes( $dbh, $t, $specs, '' );
4483 };
4484 }
4485 }
4486 0 &logger( 3, "schema_Historize: aborted, service schema untouched: $err" );
4487 return {
4488 ok => 0,
4489 from => $detect->{level},
4490 0 to => 'T',
4491 stamp => $stamp,
4492 renamed => \@renamed,
4493 error => $err,
4494 };
4495 }
4496  
4497 # 5. keep the stamped tables and log one history row (outside the txn).
4498 schema_History_add(
4499 $dbh,
4500 from => $detect->{level},
4501 to => 'T',
4502 0 ▶ mode => ( $opt{keep_old} // 1 ) ? 'historize' : 'historize-drop',
Branch: 1 branch
BranchTrueFalseTotal
$opt{'keep_old'} // 1 ? : 0 0 0
Condition0%0/2
$opt{"keep_old"} // 1
l!l
00
MC/DC0%0/1
$opt{"keep_old"} // 1
$opt{"keep_old"}
Truth table0%0/2
A
A= $opt{"keep_old"}
Aresult
11
00
4503 counts => \%rows,
4504 );
4505 return {
4506 ok => 1,
4507 from => $detect->{level},
4508 0 to => 'T',
4509 stamp => $stamp,
4510 renamed => \@renamed,
4511 rows => \%rows,
4512 };
4513 }
4514  
4515 # Invert a historisation before resuming the service (annexe D step 8): put the
4516 # stamped tables back under their original names, dropping the current target.
4517 # Options: stamp (required, the one the migration used).
4518 0 ▶sub schema_Revert {
Subroutine schema_Revert: not called CC=16 SCAR=56.1
Pod documented
4519 0 my ( $dbh, %opt ) = @_;
4520 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
4521 my $stamp = $opt{stamp}
4522 0 ▶ or die "schema_Revert: a stamp is required\n";
Branch: 1 branch
BranchTrueFalseTotal
my $stamp = $opt{"stamp"} or die "schema_Revert: a stamp is required\n" 0 0 0
4523 0 ▶ my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
Condition0%0/2
$opt{"manifest"} // [schema_Manifest($cfg)]
l!l
00
MC/DC0%0/1
$opt{"manifest"} // [schema_Manifest($cfg)]
$opt{"manifest"}
Truth table0%0/2
A
A= $opt{"manifest"}
Aresult
11
00
4524 0 my $txn = _schema_txn_ddl($dbh);
4525 0 ▶ my $own = $dbh->{AutoCommit} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->{'AutoCommit'} ? : 0 0 0
4526  
4527 0 my @done;
4528 0 my $ok = eval {
4529 0 ▶ $dbh->begin_work if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4530 0 for my $t (@$manifest) {
4531 0 my $hist = $t . SCHEMA_HIST_SEP . $stamp;
4532 0 ▶ next unless _table_exists( $dbh, $hist );
Branch: 1 branch
BranchTrueFalseTotal
unless _table_exists($dbh, $hist) 0 0 0
4533 0 _db_do_ddl( $dbh, "drop table if exists $t" );
4534 0 ▶ die "revert failed: $hist -> $t\n" unless _schema_rename_table( $dbh, $hist, $t );
Branch: 1 branch
BranchTrueFalseTotal
unless _schema_rename_table($dbh, $hist, $t) 0 0 0
4535 0 push @done, $t;
4536 }
4537 0 ▶ $dbh->commit if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4538 0 1;
4539 };
4540 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
4541 0 ▶ my $err = $@ // 'unknown error';
Condition0%0/2
$@ // "unknown error"
l!l
00
MC/DC0%0/1
$@ // "unknown error"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
4542 0 ▶ eval { $dbh->rollback } if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4543 0 &logger( 3, "schema_Revert: aborted: $err" );
4544 0 return { ok => 0, stamp => $stamp, error => $err };
4545 }
4546 schema_History_add(
4547 0 $dbh,
4548 from => 'T',
4549 to => 'T',
4550 mode => 'revert',
4551 counts => { tables => scalar @done },
4552 );
4553 0 return { ok => 1, stamp => $stamp, reverted => \@done };
4554 }
4555  
4556 # ============================================================
4557 # Update by in-place additive delta (S51c, PLAN annexe D "Mode additif"). For the
4558 # cases WITHOUT a key change: ADD COLUMN, column widening and CREATE ... IF NOT
4559 # EXISTS. Strictly monotone: never a DROP, never a narrowing, never a rename. A
4560 # NOT NULL column is only added to a populated table when the target definition
4561 # carries a default. With --with-constraints the primary key may change: a
4562 # duplicate pre-check runs first, then the key is swapped on the drivers that
4563 # allow it. Everything runs in one transaction where DDL is transactional
4564 # (SQLite, PostgreSQL); elsewhere it is applied statement by statement.
4565 # ============================================================
4566  
4567 # The T target's per-table column metadata, read off a throwaway in-memory SQLite
4568 # built with the very schema_Create T ships. Returns the SchemaScan tables hash
4569 # (name => { columns => [...], indexes => [...] }). Best effort: {} on failure.
4570 0 ▶sub _schema_target_scan {
Subroutine _schema_target_scan: not called CC=6 SCAR=37.4
4571 0 my ($cfg) = @_;
4572 0 ▶ $cfg //= eval { config_read('EDTK_DB') } || {};
Condition0%0/4
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
l!l
00
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
$cfg //= eval { do { config_read("EDTK_DB") } } || {}
$cfg
Truth table0%0/2
A
A= $cfg
Aresult
11
00
4573 0 my %tables;
4574 0 eval {
4575 0 ▶ my $m =
Branch: 1 branch
BranchTrueFalseTotal
my $m = "DBI"->connect("dbi:SQLite:dbname=:memory:", "", "", {"RaiseError", 1, "PrintError", 0, "AutoCommit", 1}) or return 0 0 0
4576 DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '',
4577 { RaiseError => 1, PrintError => 0, AutoCommit => 1 } )
4578 or return;
4579 {
4580 0 local $m->{PrintError} = 0;
4581 0 eval { create_lot_sequence($m) };
4582 0 eval { schema_Create($m) };
4583 eval {
4584 create_table_TRACKING(
4585 $m,
4586 $cfg->{'EDTK_DBI_TRACKING'},
4587 0 $cfg->{'EDTK_MAX_USER_KEY'}
4588 );
4589 }
4590 0 ▶ if $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_TRACKING"} 0 0 0
4591 }
4592 0 require oEdtk::SchemaScan;
4593 0 my $scan = oEdtk::SchemaScan::scan_schema($m);
4594 0 ▶ %tables = %{ $scan->{tables} // {} };
Condition0%0/2
$scan->{"tables"} // {}
l!l
00
MC/DC0%0/1
$scan->{"tables"} // {}
$scan->{"tables"}
Truth table0%0/2
A
A= $scan->{"tables"}
Aresult
11
00
4595 0 $m->disconnect;
4596 };
4597 0 return \%tables;
4598 }
4599  
4600 # The primary-key columns of a SchemaScan table hash, in key order (lower-cased).
4601 0 ▶sub _schema_pk_of {
Subroutine _schema_pk_of: not called CC=2 SCAR=17.9
4602 0 my ($tbl) = @_;
4603 0 return map { lc $_->{name} }
4604 0 ▶ sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @{ $tbl->{columns} // [] };
Condition0%0/2
$tbl->{"columns"} // []
l!l
00
MC/DC0%0/1
$tbl->{"columns"} // []
$tbl->{"columns"}
Truth table0%0/2
A
A= $tbl->{"columns"}
Aresult
11
00
4605 }
4606  
4607 # The ADD COLUMN statement for a target column, per driver. The type string comes
4608 # from the T target model (already portable: VARCHAR(n), integer, char(1)).
4609 0 ▶sub _schema_add_column_sql {
Subroutine _schema_add_column_sql: not called CC=6 SCAR=37.4
4610 0 my ( $driver, $table, $col ) = @_;
4611 0 my $name = $col->{name};
4612 0 ▶ my $type = $col->{type} // 'varchar2(255)';
Condition0%0/2
$col->{"type"} // "varchar2(255)"
l!l
00
MC/DC0%0/1
$col->{"type"} // "varchar2(255)"
$col->{"type"}
Truth table0%0/2
A
A= $col->{"type"}
Aresult
11
00
4613 0 ▶ my $nn = ( defined $col->{nullable} && !$col->{nullable} ) ? ' not null' : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'nullable'} && !$col->{'nullable'} ? : 0 0 0
Condition0%0/3
defined $col->{"nullable"} and not $col->{"nullable"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"nullable"} and not $col->{"nullable"}
defined $col->{"nullable"} not $col->{"nullable"}
Truth table0%0/3
A and not(B)
A= defined $col->{"nullable"}B= not $col->{"nullable"}
ABresult
0X0
100
111
4614 0 ▶ my $def = defined $col->{default} ? " default $col->{default}" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'default'} ? : 0 0 0
4615 0 ▶ return "alter table $table add ( $name $type$def$nn )" if $driver eq 'Oracle';
Branch: 1 branch
BranchTrueFalseTotal
if $driver eq "Oracle" 0 0 0
4616 0 return "alter table $table add column $name $type$nn$def";
4617 }
4618  
4619 # Widen a character column to $size, per driver. Returns undef when the driver
4620 # cannot alter a column type in place (SQLite has no such statement).
4621 0 ▶sub _schema_widen_sql {
Subroutine _schema_widen_sql: not called CC=7 SCAR=40.3
4622 0 my ( $driver, $table, $col, $size ) = @_;
4623 0 ▶ return if $driver eq 'SQLite';
Branch: 1 branch
BranchTrueFalseTotal
if $driver eq "SQLite" 0 0 0
4624 0 my $name = $col->{name};
4625 0 my $type = "varchar2($size)";
4626 0 ▶ if ( $driver eq 'mysql' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "mysql") 0 0 0
4627 0 ▶ my $nn = ( defined $col->{nullable} && !$col->{nullable} ) ? ' not null' : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'nullable'} && !$col->{'nullable'} ? : 0 0 0
Condition0%0/3
defined $col->{"nullable"} and not $col->{"nullable"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"nullable"} and not $col->{"nullable"}
defined $col->{"nullable"} not $col->{"nullable"}
Truth table0%0/3
A and not(B)
A= defined $col->{"nullable"}B= not $col->{"nullable"}
ABresult
0X0
100
111
4628 0 ▶ my $def = defined $col->{default} ? " default $col->{default}" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'default'} ? : 0 0 0
4629 0 return "alter table $table modify $name $type$nn$def";
4630 }
4631 0 ▶ return "alter table $table alter column $name type $type" if $driver eq 'PostgreSQL';
Branch: 1 branch
BranchTrueFalseTotal
if $driver eq "PostgreSQL" 0 0 0
4632 0 return "alter table $table modify $name $type"; # Oracle
4633 }
4634  
4635 # How many duplicate groups a column combination has (0 = the combination is a
4636 # valid key). Run before any new unique constraint (S51c pre-check).
4637 0 ▶sub _schema_has_duplicates {
Subroutine _schema_has_duplicates: not called CC=1 SCAR=6.9
4638 0 my ( $dbh, $table, $cols ) = @_;
4639 0 my $list = join( ', ', @$cols );
4640 0 my ($n) = $dbh->selectrow_array(
4641 "select count(*) from ( select $list from $table group by $list having count(*) > 1 ) d");
4642 0 return $n + 0;
4643 }
4644  
4645 # The name of a table's current primary-key constraint, or undef. Best effort.
4646 0 ▶sub _schema_pk_constraint_name {
Subroutine _schema_pk_constraint_name: not called CC=3 SCAR=24.8
4647 0 my ( $dbh, $table ) = @_;
4648 0 my $driver = _db_check_driver_name($dbh);
4649 0 ▶ if ( $driver eq 'PostgreSQL' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($driver eq 'PostgreSQL') { } 0 0 0
elsif ($driver eq 'Oracle') { } 0 0 0
4650 0 my ($n) = $dbh->selectrow_array(
4651 "select conname from pg_constraint where conrelid = ?::regclass and contype = 'p'",
4652 undef, $table );
4653 0 return $n;
4654 }
4655 elsif ( $driver eq 'Oracle' ) {
4656 0 my ($n) = $dbh->selectrow_array(
4657 "select constraint_name from user_constraints where table_name = upper(?) and constraint_type = 'P'",
4658 undef, $table
4659 );
4660 0 return $n;
4661 }
4662 0 return;
4663 }
4664  
4665 # The DDL that swaps a table's primary key for $cols, per driver, as a list of
4666 # statements. Returns ($statements, $error): $statements is an arrayref and
4667 # $error is undef on success. SQLite and NC cannot change a key in place.
4668 # PostgreSQL and Oracle build a separate unique index and attach it, so the
4669 # constraint and the index never compete for the same name.
4670 5 ▶sub _schema_change_key_sql {
Subroutine _schema_change_key_sql: called CC=6 SCAR=17.9
4671 5 my ( $driver, $table, $cols, $pkname ) = @_;
4672 5 my $list = join( ', ', @$cols );
4673 5 ▶ return ( [], "changing the key in place is not supported on $driver" )
Branch: 1 branch
BranchTrueFalseTotal
if $driver eq "SQLite" or $driver eq "NC" 1 4 5
Condition66%2/3
$driver eq "SQLite" or $driver eq "NC"
l!l&&r!l&&!r
104
MC/DC50%1/2
$driver eq "SQLite" or $driver eq "NC"
$driver eq "SQLite" $driver eq "NC"
Truth table66%2/3
A or B
A= $driver eq "SQLite"B= $driver eq "NC"
ABresult
1X1
011
000
4674 if $driver eq 'SQLite' || $driver eq 'NC';
4675  
4676 4 ▶ if ( $driver eq 'mysql' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "mysql") 1 3 4
4677 return (
4678 [
4679 1 "alter table $table drop primary key",
4680 "alter table $table add primary key ( $list )"
4681 ],
4682 undef
4683 );
4684 }
4685  
4686 3 ▶ return ( [], "cannot find the primary-key constraint of $table" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pkname 1 2 3
4687 unless defined $pkname;
4688  
4689 2 my $ix = "ux_" . $table;
4690 2 my @sql = (
4691 "alter table $table drop constraint $pkname",
4692 "create unique index if not exists $ix on $table ( $list )",
4693 );
4694 2 ▶ push @sql,
Branch: 1 branch
BranchTrueFalseTotal
$driver eq 'PostgreSQL' ? : 1 1 2
4695 ( $driver eq 'PostgreSQL' )
4696 ? "alter table $table add constraint pk_$table primary key using index $ix"
4697 : "alter table $table add constraint pk_$table primary key ( $list ) using index $ix";
4698 2 return ( \@sql, undef );
4699 }
4700  
4701 # Swap a table's primary key for a duplicate-free column set, per driver. On
4702 # SQLite a key cannot be changed without rebuilding the table, which is out of
4703 # scope for an additive delta. Returns an (ok, error) pair.
4704 0 ▶sub _schema_change_key {
Subroutine _schema_change_key: not called CC=7 SCAR=40.3
4705 0 my ( $dbh, $table, $cols ) = @_;
4706 0 my $driver = _db_check_driver_name($dbh);
4707 0 ▶ my $pkname =
Branch: 1 branch
BranchTrueFalseTotal
$driver eq 'PostgreSQL' || $driver eq 'Oracle' ? : 0 0 0
Condition0%0/3
$driver eq "PostgreSQL" or $driver eq "Oracle"
l!l&&r!l&&!r
000
MC/DC0%0/2
$driver eq "PostgreSQL" or $driver eq "Oracle"
$driver eq "PostgreSQL" $driver eq "Oracle"
Truth table0%0/3
A or B
A= $driver eq "PostgreSQL"B= $driver eq "Oracle"
ABresult
1X1
011
000
4708 ( $driver eq 'PostgreSQL' || $driver eq 'Oracle' )
4709 ? _schema_pk_constraint_name( $dbh, $table )
4710 : undef;
4711 0 my ( $statements, $err ) = _schema_change_key_sql( $driver, $table, $cols, $pkname );
4712 0 ▶ return ( 0, $err ) if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 0 0 0
4713  
4714 0 for my $sql (@$statements) {
4715 0 my $ok = eval { _db_do_ddl( $dbh, $sql ) };
4716 0 ▶ unless ( defined $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ok) 0 0 0
4717 0 ▶ my $why = $@ || 'the driver refused the statement';
Condition0%0/2
$@ || 'the driver refused the statement'
l!l
00
MC/DC0%0/1
$@ || 'the driver refused the statement'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
4718 0 return ( 0, "$sql: $why" );
4719 }
4720 }
4721 0 return ( 1, undef );
4722 }
4723  
4724 # READ-ONLY preview of the in-place additive update: exactly what schema_Additive
4725 # would add, widen, create or change, without writing anything (every statement is
4726 # a SELECT / PRAGMA). Options: manifest, with_constraints (0|1). Returns a plan
4727 # hash: ok, level, driver, detect, create (list), add (table => [cols]), widen
4728 # (table => [ {col,from,to} ]), key (list), add_sql (list), widen_sql (list),
4729 # key_sql (list), violations (list) and report (list of lines). A key change
4730 # requested on a driver that cannot perform it in place is a violation, so the
4731 # preview never promises more than schema_Additive can deliver.
4732 0 ▶sub schema_AdditivePlan {
Subroutine schema_AdditivePlan: not called CC=29 SCAR=67.7
Pod documented
4733 0 my ( $dbh, %opt ) = @_;
4734 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
4735 0 ▶ my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
Condition0%0/2
$opt{"manifest"} // [schema_Manifest($cfg)]
l!l
00
MC/DC0%0/1
$opt{"manifest"} // [schema_Manifest($cfg)]
$opt{"manifest"}
Truth table0%0/2
A
A= $opt{"manifest"}
Aresult
11
00
4736 0 my $detect = schema_Detect( $dbh, %opt );
4737 0 my $driver = _db_check_driver_name($dbh);
4738  
4739 0 my $target = _schema_target_scan($cfg);
4740  
4741 0 require oEdtk::SchemaScan;
4742 0 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4743  
4744 0 my @create;
4745 my %add;
4746 0 my %widen;
4747 0 my @key;
4748 0 my @violations;
4749 0 my @add_sql;
4750 0 my @widen_sql;
4751 0 my @key_sql;
4752  
4753 0 for my $t (@$manifest) {
4754 0 ▶ my $tbl = $target->{$t} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $tbl = $target->{$t} or next 0 0 0
4755  
4756 # A table absent from the base is created, not altered.
4757 0 my $live = _schema_scan_table( $scan, $t );
4758 0 ▶ if ( !$live ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($live) 0 0 0
4759 0 push @create, $t;
4760 0 next;
4761 }
4762  
4763 0 ▶ my %sc = map { lc( $_->{name} ) => $_ } @{ $live->{columns} // [] };
Condition0%0/2
$live->{"columns"} // []
l!l
00
MC/DC0%0/1
$live->{"columns"} // []
$live->{"columns"}
Truth table0%0/2
A
A= $live->{"columns"}
Aresult
11
00
4764 0 my ($nrows) = $dbh->selectrow_array("select count(*) from $t");
4765 0 $nrows += 0;
4766  
4767 0 ▶ for my $col ( @{ $tbl->{columns} // [] } ) {
Condition0%0/2
$tbl->{"columns"} // []
l!l
00
MC/DC0%0/1
$tbl->{"columns"} // []
$tbl->{"columns"}
Truth table0%0/2
A
A= $tbl->{"columns"}
Aresult
11
00
4768 0 my $key = lc $col->{name};
4769 0 ▶ if ( !exists $sc{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $sc{$key}) 0 0 0
4770 0 ▶ my $notnull = ( defined $col->{nullable} && !$col->{nullable} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'nullable'} && !$col->{'nullable'} ? : 0 0 0
Condition0%0/3
defined $col->{"nullable"} and not $col->{"nullable"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"nullable"} and not $col->{"nullable"}
defined $col->{"nullable"} not $col->{"nullable"}
Truth table0%0/3
A and not(B)
A= defined $col->{"nullable"}B= not $col->{"nullable"}
ABresult
0X0
100
111
4771 0 ▶ if ( $notnull && !defined $col->{default} && $nrows > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($notnull and not defined $col->{"default"} and $nrows > 0) 0 0 0
Condition0%0/6
$notnull and not defined $col->{"default"} and $nrows > 0
!ll&&!rl&&r
000
$notnull and not defined $col->{"default"}
!ll&&!rl&&r
000
MC/DC0%0/3
$notnull and not defined $col->{"default"} and $nrows > 0
$notnull not defined $col->{"default"} $nrows > 0
Truth table0%0/4
A and not(B) and C
A= $notnullB= not defined $col->{"default"}C= $nrows > 0
ABCresult
0XX0
10X0
1100
1111
4772 0 push @violations,
4773 "$t.$col->{name}: NOT NULL without a default on a populated table";
4774 0 next;
4775 }
4776 0 push @{ $add{$t} }, $col->{name};
4777 0 push @add_sql, _schema_add_column_sql( $driver, $t, $col );
4778 0 next;
4779 }
4780 0 my $s = $sc{$key};
4781 0 ▶ next unless defined $col->{size} && defined $s->{size};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col->{"size"} and defined $s->{"size"} 0 0 0
Condition0%0/3
defined $col->{"size"} and defined $s->{"size"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"size"} and defined $s->{"size"}
defined $col->{"size"} defined $s->{"size"}
Truth table0%0/3
A and B
A= defined $col->{"size"}B= defined $s->{"size"}
ABresult
0X0
100
111
4782 0 ▶ if ( $col->{size} > $s->{size} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($col->{'size'} > $s->{'size'}) { } 0 0 0
elsif ($col->{'size'} < $s->{'size'}) { } 0 0 0
4783 0 push @{ $widen{$t} },
4784 0 { col => $col->{name}, from => $s->{size}, to => $col->{size} };
4785 0 my $sql = _schema_widen_sql( $driver, $t, $col, $col->{size} );
4786 0 ▶ if ( defined $sql ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sql) { } 0 0 0
4787 0 push @widen_sql, $sql;
4788 }
4789 else {
4790 0 push @violations,
4791 "$t.$col->{name}: widening $s->{size}->$col->{size} not supported on $driver";
4792 }
4793 }
4794 elsif ( $col->{size} < $s->{size} ) {
4795 0 push @violations, "narrowing refused: $t.$col->{name} $s->{size}->$col->{size}";
4796 }
4797 }
4798  
4799 0 my @spk = _schema_pk_of($live);
4800 0 my @tpk = _schema_pk_of($tbl);
4801 0 ▶ if ( @tpk && join( ',', @spk ) ne join( ',', @tpk ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tpk and join(",", @spk) ne join(",", @tpk)) 0 0 0
Condition0%0/3
@tpk and join(",", @spk) ne join(",", @tpk)
!ll&&!rl&&r
000
MC/DC0%0/2
@tpk and join(",", @spk) ne join(",", @tpk)
@tpk join(",", @spk) ne join(",", @tpk)
Truth table0%0/3
A and B
A= @tpkB= join(",", @spk) ne join(",", @tpk)
ABresult
0X0
100
111
4802 0 push @key, { table => $t, from => join( ',', @spk ), to => join( ',', @tpk ) };
4803 0 ▶ if ( !$opt{with_constraints} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt{'with_constraints'}) { } 0 0 0
4804 0 push @violations,
4805 "$t: key differs ( "
4806 . join( ',', @spk ) . " -> "
4807 . join( ',', @tpk )
4808 . " ); use --with-constraints";
4809 }
4810 else {
4811 0 my $pkname = _schema_pk_constraint_name( $dbh, $t );
4812 0 my ( $sql, $err ) = _schema_change_key_sql( $driver, $t, \@tpk, $pkname );
4813 0 ▶ if ( defined $err ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) { } 0 0 0
4814 0 push @violations, "$t: $err";
4815 }
4816 else {
4817 0 push @key_sql, @$sql;
4818 }
4819 }
4820 }
4821 }
4822  
4823 0 my @report;
4824  
4825 #push @report, "schema level: $detect->{level}";
4826 0 push @report, "driver: $driver";
4827 0 push @report, "target level: T";
4828 0 push @report, "mode: additive (in place, read-only preview)";
4829 0 push @report, sprintf( "tables to create: %d", scalar @create );
4830 0 push @report, sprintf( "columns to add: %d", scalar( map { @$_ } values %add ) );
4831 0 push @report, sprintf( "columns to widen: %d", scalar( map { @$_ } values %widen ) );
4832 0 push @report, sprintf( "key changes: %d", scalar @key );
4833 0 push @report, sprintf( "violations: %d", scalar @violations );
4834 0 push @report, sprintf( " create %s", $_ ) for @create;
4835  
4836 0 for my $t ( sort keys %add ) {
4837 0 push @report, sprintf( " add %-28s %s", $t, join( ',', @{ $add{$t} } ) );
4838 }
4839 0 for my $t ( sort keys %widen ) {
4840 push @report,
4841 sprintf(
4842 " widen %-28s %s",
4843 $t,
4844 join( ',',
4845 0 map { sprintf( '%s %s->%s', $_->{col}, $_->{from}, $_->{to} ) } @{ $widen{$t} } )
4846 );
4847 }
4848 0 push @report, sprintf( " key %s ( %s -> %s )", $_->{table}, $_->{from}, $_->{to} ) for @key;
4849 0 push @report, " violation: $_" for @violations;
4850  
4851 return {
4852 ok => 1,
4853 level => $detect->{level},
4854 0 driver => $driver,
4855 detect => $detect,
4856 create => \@create,
4857 add => \%add,
4858 widen => \%widen,
4859 key => \@key,
4860 add_sql => \@add_sql,
4861 widen_sql => \@widen_sql,
4862 key_sql => \@key_sql,
4863 violations => \@violations,
4864 report => \@report,
4865 };
4866 }
4867  
4868 # Perform the in-place additive update. Options: manifest, with_constraints (0|1),
4869 # checkpoint (a code ref called after each table) and force. A base that already
4870 # conforms to T with nothing to add or widen is a no-op (result field noop => 1).
4871 # Returns a result hash: created (list), added (table => [cols]), widened
4872 # (table => [ {col,from,to} ]), key_changed (list), violations (list) and error.
4873 0 ▶sub schema_Additive {
Subroutine schema_Additive: not called CC=12 SCAR=50.5
Pod documented
4874 0 my ( $dbh, %opt ) = @_;
4875 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
4876 0 ▶ my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
Condition0%0/2
$opt{"manifest"} // [schema_Manifest($cfg)]
l!l
00
MC/DC0%0/1
$opt{"manifest"} // [schema_Manifest($cfg)]
$opt{"manifest"}
Truth table0%0/2
A
A= $opt{"manifest"}
Aresult
11
00
4877 0 my $detect = schema_Detect( $dbh, %opt );
4878 0 my $driver = _db_check_driver_name($dbh);
4879 0 my $txn = _schema_txn_ddl($dbh);
4880 0 ▶ my $own = $dbh->{AutoCommit} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->{'AutoCommit'} ? : 0 0 0
4881  
4882 0 my $target = _schema_target_scan($cfg);
4883  
4884 0 my @created;
4885 my %added;
4886 0 my %widened;
4887 0 my @key_changed;
4888 0 my @violations;
4889  
4890 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=34 SCAR=70.8
4891 0 ▶ $dbh->begin_work if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4892  
4893 0 require oEdtk::SchemaScan;
4894 0 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4895  
4896 # 1. add the missing columns, widen the narrower ones and, when asked,
4897 # change the key -- on the tables that already exist.
4898 0 for my $t (@$manifest) {
4899 0 ▶ my $tbl = $target->{$t} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $tbl = $target->{$t} or next 0 0 0
4900 0 ▶ my $live = _schema_scan_table( $scan, $t ) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $live = _schema_scan_table($scan, $t) or next 0 0 0
4901 0 ▶ my %sc = map { lc( $_->{name} ) => $_ } @{ $live->{columns} // [] };
Condition0%0/2
$live->{"columns"} // []
l!l
00
MC/DC0%0/1
$live->{"columns"} // []
$live->{"columns"}
Truth table0%0/2
A
A= $live->{"columns"}
Aresult
11
00
4902 0 my ($nrows) = $dbh->selectrow_array("select count(*) from $t");
4903 0 $nrows += 0;
4904  
4905 0 ▶ for my $col ( @{ $tbl->{columns} // [] } ) {
Condition0%0/2
$tbl->{"columns"} // []
l!l
00
MC/DC0%0/1
$tbl->{"columns"} // []
$tbl->{"columns"}
Truth table0%0/2
A
A= $tbl->{"columns"}
Aresult
11
00
4906 0 my $key = lc $col->{name};
4907 0 ▶ if ( !exists $sc{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $sc{$key}) 0 0 0
4908 0 ▶ my $notnull = ( defined $col->{nullable} && !$col->{nullable} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'nullable'} && !$col->{'nullable'} ? : 0 0 0
Condition0%0/3
defined $col->{"nullable"} and not $col->{"nullable"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"nullable"} and not $col->{"nullable"}
defined $col->{"nullable"} not $col->{"nullable"}
Truth table0%0/3
A and not(B)
A= defined $col->{"nullable"}B= not $col->{"nullable"}
ABresult
0X0
100
111
4909 0 ▶ if ( $notnull && !defined $col->{default} && $nrows > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($notnull and not defined $col->{"default"} and $nrows > 0) 0 0 0
Condition0%0/6
$notnull and not defined $col->{"default"} and $nrows > 0
!ll&&!rl&&r
000
$notnull and not defined $col->{"default"}
!ll&&!rl&&r
000
MC/DC0%0/3
$notnull and not defined $col->{"default"} and $nrows > 0
$notnull not defined $col->{"default"} $nrows > 0
Truth table0%0/4
A and not(B) and C
A= $notnullB= not defined $col->{"default"}C= $nrows > 0
ABCresult
0XX0
10X0
1100
1111
4910 0 push @violations,
4911 "$t.$col->{name}: NOT NULL without a default on a populated table";
4912 0 next;
4913 }
4914 0 my $sql = _schema_add_column_sql( $driver, $t, $col );
4915 0 ▶ die "add column failed on $t.$col->{name}\n" unless _db_do_ddl( $dbh, $sql );
Branch: 1 branch
BranchTrueFalseTotal
unless _db_do_ddl($dbh, $sql) 0 0 0
4916 0 push @{ $added{$t} }, $col->{name};
4917 0 next;
4918 }
4919 0 my $s = $sc{$key};
4920 0 ▶ next unless defined $col->{size} && defined $s->{size};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col->{"size"} and defined $s->{"size"} 0 0 0
Condition0%0/3
defined $col->{"size"} and defined $s->{"size"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $col->{"size"} and defined $s->{"size"}
defined $col->{"size"} defined $s->{"size"}
Truth table0%0/3
A and B
A= defined $col->{"size"}B= defined $s->{"size"}
ABresult
0X0
100
111
4921 0 ▶ if ( $col->{size} > $s->{size} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($col->{'size'} > $s->{'size'}) { } 0 0 0
elsif ($col->{'size'} < $s->{'size'}) { } 0 0 0
4922 0 my $sql = _schema_widen_sql( $driver, $t, $col, $col->{size} );
4923 0 ▶ next unless defined $sql;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sql 0 0 0
4924 0 ▶ die "widen failed on $t.$col->{name}\n" unless _db_do_ddl( $dbh, $sql );
Branch: 1 branch
BranchTrueFalseTotal
unless _db_do_ddl($dbh, $sql) 0 0 0
4925 0 push @{ $widened{$t} },
4926 0 { col => $col->{name}, from => $s->{size}, to => $col->{size} };
4927 }
4928 elsif ( $col->{size} < $s->{size} ) {
4929 0 push @violations, "narrowing refused: $t.$col->{name} $s->{size}->$col->{size}";
4930 }
4931 }
4932  
4933 # Change the key only when explicitly asked to.
4934 0 my @spk = _schema_pk_of($live);
4935 0 my @tpk = _schema_pk_of($tbl);
4936 0 ▶ if ( @tpk && join( ',', @spk ) ne join( ',', @tpk ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tpk and join(",", @spk) ne join(",", @tpk)) 0 0 0
Condition0%0/3
@tpk and join(",", @spk) ne join(",", @tpk)
!ll&&!rl&&r
000
MC/DC0%0/2
@tpk and join(",", @spk) ne join(",", @tpk)
@tpk join(",", @spk) ne join(",", @tpk)
Truth table0%0/3
A and B
A= @tpkB= join(",", @spk) ne join(",", @tpk)
ABresult
0X0
100
111
4937 0 ▶ if ( !$opt{with_constraints} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt{'with_constraints'}) { } 0 0 0
4938 0 push @violations,
4939 "$t: key differs ( "
4940 . join( ',', @spk ) . " -> "
4941 . join( ',', @tpk )
4942 . " ); use --with-constraints";
4943 }
4944 else {
4945 0 my $dup = _schema_has_duplicates( $dbh, $t, \@tpk );
4946 0 ▶ die "duplicate rows on $t ( " . join( ',', @tpk ) . " ): $dup\n" if $dup;
Branch: 1 branch
BranchTrueFalseTotal
if $dup 0 0 0
4947 0 my ( $kok, $kerr ) = _schema_change_key( $dbh, $t, \@tpk );
4948 0 ▶ die "key change failed on $t: $kerr\n" unless $kok;
Branch: 1 branch
BranchTrueFalseTotal
unless $kok 0 0 0
4949 0 push @key_changed, $t;
4950 }
4951 }
4952  
4953 0 ▶ $opt{checkpoint}->($t) if $opt{checkpoint};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"checkpoint"} 0 0 0
4954 }
4955  
4956 # 2. create the still-missing tables last, once the existing ones carry
4957 # every column their indexes reference (schema_Create is "IF NOT EXISTS").
4958 0 for my $t (@$manifest) {
4959 0 ▶ push @created, $t unless _schema_scan_table( $scan, $t );
Branch: 1 branch
BranchTrueFalseTotal
unless _schema_scan_table($scan, $t) 0 0 0
4960 }
4961 0 ▶ if (@created) {
Branch: 1 branch
BranchTrueFalseTotal
if (@created) 0 0 0
4962 0 schema_Create($dbh);
4963 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
4964 0 ▶ if $cfg->{'EDTK_DBI_TRACKING'};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"EDTK_DBI_TRACKING"} 0 0 0
4965 }
4966  
4967 0 ▶ $dbh->commit if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4968 0 return 1;
4969 0 };
4970  
4971 0 my $ok = eval { $run->(); 1 };
4972 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
4973 0 ▶ my $err = $@ // 'unknown error';
Condition0%0/2
$@ // "unknown error"
l!l
00
MC/DC0%0/1
$@ // "unknown error"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
4974 0 ▶ eval { $dbh->rollback } if $own && $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $own and $txn 0 0 0
Condition0%0/3
$own and $txn
!ll&&!rl&&r
000
MC/DC0%0/2
$own and $txn
$own $txn
Truth table0%0/3
A and B
A= $ownB= $txn
ABresult
0X0
100
111
4975 0 &logger( 3, "schema_Additive: aborted: $err" );
4976 return {
4977 ok => 0,
4978 from => $detect->{level},
4979 0 to => 'T',
4980 created => \@created,
4981 added => \%added,
4982 widened => \%widened,
4983 key_changed => \@key_changed,
4984 violations => \@violations,
4985 error => $err,
4986 };
4987 }
4988  
4989 # 3. nothing changed at all -> no-op, and no history row.
4990 0 ▶ unless ( @created || %added || %widened || @key_changed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@created or %added or %widened or @key_changed) 0 0 0
Condition0%0/9
@created or %added or %widened or @key_changed
l!l&&r!l&&!r
000
@created or %added or %widened
l!l&&r!l&&!r
000
@created or %added
l!l&&r!l&&!r
000
MC/DC0%0/4
@created or %added or %widened or @key_changed
@created %added %widened @key_changed
Truth table0%0/5
A or B or C or D
A= @createdB= %addedC= %widenedD= @key_changed
ABCDresult
1XXX1
01XX1
001X1
00011
00000
4991 return {
4992 ok => 1,
4993 noop => 1,
4994 from => $detect->{level},
4995 0 to => 'T',
4996 created => [],
4997 added => {},
4998 widened => {},
4999 key_changed => [],
5000 violations => \@violations,
5001 };
5002 }
5003  
5004 schema_History_add(
5005 $dbh,
5006 from => $detect->{level},
5007 to => 'T',
5008 mode => 'additive',
5009 counts => {
5010 created => scalar @created,
5011 0 added => scalar( map { @$_ } values %added ),
5012 },
5013 );
5014 return {
5015 ok => 1,
5016 from => $detect->{level},
5017 0 to => 'T',
5018 created => \@created,
5019 added => \%added,
5020 widened => \%widened,
5021 key_changed => \@key_changed,
5022 violations => \@violations,
5023 };
5024 }
5025  
5026 # ============================================================
5027 # PUBLIC : probe whether the connected DB user may run the DDL that schema_Create
5028 # and schema_Upgrade issue, so a missing right is reported early instead of failing
5029 # later on a CREATE TABLE / INDEX / SEQUENCE or an ALTER TABLE. Best effort: it only
5030 # reads the data dictionary and never dies.
5031 #
5032 # Returns { driver => 'SQLite'|'Oracle'|'PostgreSQL'|'mysql'|'NC',
5033 # checked => 0|1, # 0 when the driver has no privilege model
5034 # create => 0|1, # undef when left unknown
5035 # drop => 0|1,
5036 # index => 0|1,
5037 # alter => 0|1,
5038 # sequence=> 0|1,
5039 # missing => [ 'CREATE', ... ],
5040 # error => '...' } # set when the probe itself failed
5041 # Options: table => 'name' targets a specific table for the ownership checks
5042 # (PostgreSQL); ignored by the other backends.
5043 # ============================================================
5044 19 ▶sub db_check_privileges {
Subroutine db_check_privileges: called CC=13 SCAR=25.7
Pod documented
5045 19 my ( $dbh, %opt ) = @_;
5046  
5047 # Rights probed, in the order they are reported in 'missing'.
5048 19 my @RIGHTS = qw(CREATE DROP INDEX ALTER SEQUENCE);
5049  
5050 19 my %res = ( driver => 'NC', checked => 0, missing => [] );
5051 19 ▶ return \%res unless defined $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbh 1 18 19
5052  
5053 18 my $driver = _db_check_driver_name($dbh);
5054 18 $res{driver} = $driver;
5055  
5056 # SQLite has no GRANT/privilege model: the file owner may do everything.
5057 18 ▶ if ( $driver eq 'SQLite' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "SQLite") 7 11 18
5058 7 $res{ lc $_ } = 1 for @RIGHTS;
5059 7 $res{checked} = 1;
5060 7 &logger( 7,
5061 "db_check_privileges: SQLite has no privilege model, "
5062 . "assuming every right is allowed" );
5063 7 return \%res;
5064 }
5065  
5066 # No privilege model we can query: report nothing rather than guess.
5067 11 ▶ if ( $driver eq 'NC' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "NC") 1 10 11
5068 1 &logger( 7, "db_check_privileges: unknown driver, " . "cannot check privileges" );
5069 1 return \%res;
5070 }
5071  
5072 10 my %rights;
5073 10 my $ok = eval {
5074 10 ▶ %rights =
Branch: 3 branches
BranchTrueFalseTotal
$driver eq 'PostgreSQL' ? : 5 5 10
$driver eq 'mysql' ? : 3 2 5
$driver eq 'Oracle' ? : 2 0 2
5075 $driver eq 'PostgreSQL' ? _db_priv_pg( $dbh, %opt )
5076 : $driver eq 'mysql' ? _db_priv_mysql( $dbh, %opt )
5077 : $driver eq 'Oracle' ? _db_priv_oracle( $dbh, %opt )
5078 : ();
5079 9 1;
5080 };
5081 10 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 9 10
5082 1 ▶ $res{error} = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
5083 1 &logger( 3, "db_check_privileges: privilege probe failed: $res{error}" );
5084 1 return \%res;
5085 }
5086  
5087 9 $res{checked} = 1;
5088 9 for my $right (@RIGHTS) {
5089 45 my $have = $rights{ lc $right };
5090 45 $res{ lc $right } = $have;
5091 45 ▶ next if !defined $have || $have;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $have or $have 31 14 45
Condition66%2/3
not defined $have or $have
l!l&&r!l&&!r
03114
MC/DC50%1/2
not defined $have or $have
not defined $have $have
Truth table66%2/3
not(A) or B
A= not defined $haveB= $have
ABresult
1X1
011
000
5092 14 push @{ $res{missing} }, $right;
5093 14 &logger( 3,
5094 "db_check_privileges: DB user lacks the $right privilege on the "
5095 . "current database/schema ; schema_Create and schema_Upgrade may fail" );
5096 }
5097 9 return \%res;
5098 }
5099  
5100 # PostgreSQL: CREATE is a database/schema privilege; owning the table grants DROP,
5101 # INDEX and ALTER. Ownership is tested on the target table (option 'table') or on
5102 # any table of the current schema, and a superuser always passes; an empty schema
5103 # does not raise a false alarm. Returns a hash of rights.
5104 5 ▶sub _db_priv_pg {
Subroutine _db_priv_pg: called CC=8 SCAR=20.8
5105 5 my ( $dbh, %opt ) = @_;
5106  
5107 5 my ($super) =
5108 $dbh->selectrow_array("SELECT rolsuper FROM pg_roles WHERE rolname = current_user");
5109 4 ▶ return map { $_ => 1 } qw(create drop index alter sequence) if $super;
Branch: 1 branch
BranchTrueFalseTotal
if $super 1 3 4
5110  
5111 3 my ($create) = $dbh->selectrow_array(
5112 "SELECT has_database_privilege(current_user, current_database(), 'CREATE') "
5113 . "AND has_schema_privilege(current_user, current_schema(), 'CREATE')" );
5114  
5115 3 my $owns;
5116 3 ▶ if ( defined $opt{table} && length $opt{table} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{'table'} and length $opt{'table'}) { } 1 2 3
Condition66%2/3
defined $opt{"table"} and length $opt{"table"}
!ll&&!rl&&r
201
MC/DC50%1/2
defined $opt{"table"} and length $opt{"table"}
defined $opt{"table"} length $opt{"table"}
Truth table66%2/3
A and B
A= defined $opt{"table"}B= length $opt{"table"}
ABresult
0X0
100
111
5117 ($owns) = $dbh->selectrow_array(
5118 "SELECT pg_get_userbyid(c.relowner) = current_user "
5119 . "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
5120 . "WHERE c.relname = ? AND n.nspname = current_schema()",
5121 undef, $opt{table}
5122 1 );
5123 }
5124 else {
5125 2 ($owns) =
5126 $dbh->selectrow_array( "SELECT bool_or(pg_get_userbyid(c.relowner) = current_user) "
5127 . "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
5128 . "WHERE n.nspname = current_schema() AND c.relkind = 'r'" );
5129 }
5130 3 ▶ my $owning = defined $owns ? ( $owns ? 1 : 0 ) : 1;
Branch: 2 branches
BranchTrueFalseTotal
defined $owns ? : 3 0 3
$owns ? : 2 1 3
5131  
5132 return (
5133 3 ▶ create => $create ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
$create ? : 2 1 3
$create ? : 2 1 3
5134 drop => $owning,
5135 index => $owning, # CREATE INDEX needs table ownership
5136 alter => $owning, # ALTER TABLE needs table ownership
5137 sequence => $create ? 1 : 0, # CREATE SEQUENCE needs CREATE on the schema
5138 );
5139 }
5140  
5141 # MySQL / MariaDB: SHOW GRANTS lists the effective grants. A statement that grants
5142 # ALL PRIVILEGES, or the specific right, on '*.*' or on the current database gives
5143 # the right. CREATE INDEX needs INDEX or ALTER; CREATE SEQUENCE (MariaDB) needs
5144 # CREATE. Returns a hash of rights.
5145 3 ▶sub _db_priv_mysql {
Subroutine _db_priv_mysql: called CC=18 SCAR=29.2
5146 3 my ( $dbh, %opt ) = @_;
5147  
5148 3 my ($db) = $dbh->selectrow_array("SELECT DATABASE()");
5149 3 ▶ $db = '' unless defined $db;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $db 0 3 3
5150  
5151 3 my $rows = $dbh->selectall_arrayref("SHOW GRANTS FOR CURRENT_USER()");
5152 3 my %have;
5153 3 ▶ for my $r ( @{ $rows || [] } ) {
Condition50%1/2
$rows || []
l!l
30
MC/DC0%0/1
$rows || []
$rows
Truth table50%1/2
A
A= $rows
Aresult
11
00
5154 4 ▶ my $grant = $r->[0] // '';
Condition50%1/2
$r->[0] // ""
l!l
40
MC/DC0%0/1
$r->[0] // ""
$r->[0]
Truth table50%1/2
A
A= $r->[0]
Aresult
11
00
5155 4 ▶ next unless $grant =~ /^\s*GRANT\s+(.+?)\s+ON\s+(\S.*?)\s+TO\s/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $grant =~ /^\s*GRANT\s+(.+?)\s+ON\s+(\S.*?)\s+TO\s/i 0 4 4
5156 4 my ( $privs, $scope ) = ( uc $1, $2 );
5157 4 $scope =~ s/`//g;
5158 4 my $global = ( $scope eq '*.*' );
5159 4 ▶ my $local = ( $db ne '' && lc($scope) eq lc("$db.*") );
Condition66%2/3
$db ne '' && lc $scope eq lc "$db.*"
!ll&&!rl&&r
031
MC/DC50%1/2
$db ne '' && lc $scope eq lc "$db.*"
$db ne '' lc $scope eq lc "$db.*"
Truth table66%2/3
A && B
A= $db ne ''B= lc $scope eq lc "$db.*"
ABresult
0X0
100
111
5160 4 ▶ next unless $global || $local;
Branch: 1 branch
BranchTrueFalseTotal
unless $global or $local 1 3 4
Condition100%3/3
$global or $local
l!l&&r!l&&!r
211
MC/DC100%2/2
$global or $local
$global $local
Truth table100%3/3
A or B
A= $globalB= $local
ABresult
1X1
011
000
5161 3 ▶ if ( $privs =~ /ALL PRIVILEGES/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($privs =~ /ALL PRIVILEGES/) { } 1 2 3
5162 1 $have{$_} = 1 for qw(CREATE DROP INDEX ALTER);
5163 }
5164 else {
5165 2 $have{$_} = 1 for grep { $privs =~ /\b$_\b/ } qw(CREATE DROP INDEX ALTER);
5166 }
5167 }
5168 return (
5169 create => $have{CREATE} ? 1 : 0,
5170 drop => $have{DROP} ? 1 : 0,
5171 index => ( $have{INDEX} || $have{ALTER} ) ? 1 : 0,
5172 alter => $have{ALTER} ? 1 : 0,
5173 3 ▶ sequence => $have{CREATE} ? 1 : 0,
Branch: 5 branches
BranchTrueFalseTotal
$have{'CREATE'} ? : 2 1 3
$have{'DROP'} ? : 2 1 3
$have{'INDEX'} || $have{'ALTER'} ? : 1 2 3
$have{'ALTER'} ? : 1 2 3
$have{'CREATE'} ? : 2 1 3
Condition66%2/3
$have{"INDEX"} or $have{"ALTER"}
l!l&&r!l&&!r
102
MC/DC50%1/2
$have{"INDEX"} or $have{"ALTER"}
$have{"INDEX"} $have{"ALTER"}
Truth table66%2/3
A or B
A= $have{"INDEX"}B= $have{"ALTER"}
ABresult
1X1
011
000
5174 );
5175 }
5176  
5177 # Oracle: system privileges; those held directly sit in USER_SYS_PRIVS, those held
5178 # through an enabled role in ROLE_SYS_PRIVS. Creating the tables (CREATE TABLE) makes
5179 # us their owner, so we may then INDEX and ALTER them. Returns a hash of rights.
5180 2 ▶sub _db_priv_oracle {
Subroutine _db_priv_oracle: called CC=12 SCAR=33.0
5181 2 my ( $dbh, %opt ) = @_;
5182  
5183 2 my $ref = $dbh->selectcol_arrayref(
5184 "SELECT PRIVILEGE FROM USER_SYS_PRIVS " . "UNION SELECT PRIVILEGE FROM ROLE_SYS_PRIVS" );
5185 2 ▶ my %priv = map { uc($_) => 1 } @{ $ref || [] };
Condition50%1/2
$ref || []
l!l
20
MC/DC0%0/1
$ref || []
$ref
Truth table50%1/2
A
A= $ref
Aresult
11
00
5186  
5187 2 ▶ my $create_table = ( $priv{'CREATE TABLE'} || $priv{'CREATE ANY TABLE'} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$priv{'CREATE TABLE'} || $priv{'CREATE ANY TABLE'} ? : 2 0 2
Condition33%1/3
$priv{"CREATE TABLE"} or $priv{"CREATE ANY TABLE"}
l!l&&r!l&&!r
200
MC/DC0%0/2
$priv{"CREATE TABLE"} or $priv{"CREATE ANY TABLE"}
$priv{"CREATE TABLE"} $priv{"CREATE ANY TABLE"}
Truth table33%1/3
A or B
A= $priv{"CREATE TABLE"}B= $priv{"CREATE ANY TABLE"}
ABresult
1X1
011
000
5188 return (
5189 create => $create_table,
5190 drop => ( $create_table || $priv{'DROP ANY TABLE'} ) ? 1 : 0,
5191 index => ( $create_table || $priv{'CREATE ANY INDEX'} ) ? 1 : 0,
5192 alter => ( $create_table || $priv{'ALTER ANY TABLE'} ) ? 1 : 0,
5193 2 ▶ sequence => ( $priv{'CREATE SEQUENCE'} || $priv{'CREATE ANY SEQUENCE'} ) ? 1 : 0,
Branch: 4 branches
BranchTrueFalseTotal
$create_table || $priv{'DROP ANY TABLE'} ? : 2 0 2
$create_table || $priv{'CREATE ANY INDEX'} ? : 2 0 2
$create_table || $priv{'ALTER ANY TABLE'} ? : 2 0 2
$priv{'CREATE SEQUENCE'} || $priv{'CREATE ANY SEQUENCE'} ? : 0 2 2
Condition33%4/12
$create_table or $priv{"DROP ANY TABLE"}
l!l&&r!l&&!r
200
$create_table or $priv{"CREATE ANY INDEX"}
l!l&&r!l&&!r
200
$create_table or $priv{"ALTER ANY TABLE"}
l!l&&r!l&&!r
200
$priv{"CREATE SEQUENCE"} or $priv{"CREATE ANY SEQUENCE"}
l!l&&r!l&&!r
002
MC/DC0%0/2
$create_table or $priv{"DROP ANY TABLE"}
$create_table $priv{"DROP ANY TABLE"}
MC/DC0%0/2
$create_table or $priv{"CREATE ANY INDEX"}
$create_table $priv{"CREATE ANY INDEX"}
MC/DC0%0/2
$create_table or $priv{"ALTER ANY TABLE"}
$create_table $priv{"ALTER ANY TABLE"}
MC/DC0%0/2
$priv{"CREATE SEQUENCE"} or $priv{"CREATE ANY SEQUENCE"}
$priv{"CREATE SEQUENCE"} $priv{"CREATE ANY SEQUENCE"}
Truth table33%1/3
A or B
A= $create_tableB= $priv{"DROP ANY TABLE"}
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= $create_tableB= $priv{"CREATE ANY INDEX"}
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= $create_tableB= $priv{"ALTER ANY TABLE"}
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= $priv{"CREATE SEQUENCE"}B= $priv{"CREATE ANY SEQUENCE"}
ABresult
1X1
011
000
5194 );
5195 }
5196  
5197 0 ▶sub schema_Upgrade {
Subroutine schema_Upgrade: not called CC=3 SCAR=24.8
Pod documented
5198  
5199 # EXAMPLE CALL:
5200 # schema_Upgrade (CFG => $cfg);
5201 0 my %p = @_;
5202  
5203 # D50 (H2): schema_Upgrade is now an envelope of schema_Historize, which
5204 # frees the index names before schema_Create (so the ix_* indexes are really
5205 # rebuilt on the new table instead of being silently skipped while the
5206 # renamed table still holds their names), copies the rows by NAMED columns
5207 # (never positionally) and inverts the renames if a step fails. The call form
5208 # schema_Upgrade(CFG => $cfg) is unchanged.
5209 #
5210 # PREREQUISITES FOR THIS OPERATION:
5211 #- DISK SPACE (the previous schema is kept as history, see below)
5212 #- HISTORIZATION
5213 0 my $dbh = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5214  
5215 # Repatriate any pending backup rows before renaming / copying the schema.
5216 0 eval { _db_maybe_reconcile( $dbh, $p{CFG} ); };
5217  
5218 # Best effort: alert (never block) when the DB user cannot CREATE/DROP.
5219 0 eval { db_check_privileges($dbh) };
5220  
5221 # force => the upgrade always rebuilds (as before), even on an already
5222 # conformant base; the current schema is set aside as <table>_hist_<stamp>.
5223 0 &logger( 3,
5224 "schema_Upgrade: the previous schema is kept as history "
5225 . "(<table>_hist_<stamp>) and consumes disk space" );
5226  
5227 my $result = schema_Historize(
5228 $dbh,
5229 0 manifest => [ schema_Manifest( $p{CFG} ) ],
5230 keep_old => 1,
5231 force => 1,
5232 );
5233  
5234 die "schema_Upgrade: " . ( $result->{error} // 'unknown error' ) . "\n"
5235 0 ▶ unless $result->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $result->{"ok"} 0 0 0
Condition0%0/2
$result->{"error"} // "unknown error"
l!l
00
MC/DC0%0/1
$result->{"error"} // "unknown error"
$result->{"error"}
Truth table0%0/2
A
A= $result->{"error"}
Aresult
11
00
5236 0 db_invalidate_meta_cache();
5237 0 return $result;
5238 }
5239  
5240 6 ▶sub schema_Create {
Subroutine schema_Create: called CC=2 SCAR=6.9
Pod documented
5241  
5242 # my ($dbh, $table, $maxkeys) = @_;
5243 6 my $dbh = shift;
5244 6 my $cfg = config_read('EDTK_DB');
5245  
5246 # Best effort: alert (never block) when the DB user cannot CREATE/DROP.
5247 6 eval { db_check_privileges($dbh) };
5248  
5249 #if ( $cfg->{'EDTK_DBI_DSN'} =~ m/SQLite/i) {
5250 6 ▶ if ( $dbh->{'Driver'}->{'Name'} =~ m/mysql/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->{'Driver'}{'Name'} =~ /mysql/i) { } 0 6 6
5251  
5252 # MySQL uses its own AUTO_INCREMENT emulation, nothing to create here.
5253 0 &logger( 5, "MySQL uses its own sequence emulation, ignoring." );
5254 }
5255 else {
5256 # Oracle/PostgreSQL create a SEQUENCE; SQLite creates a counter table.
5257 6 create_lot_sequence($dbh);
5258 }
5259  
5260 6 create_table_ADMIN($dbh);
5261 6 create_table_ACQUIT($dbh);
5262 6 create_table_AGREGE($dbh);
5263 6 create_table_FILIERES($dbh);
5264 6 create_table_ID($dbh);
5265 6 create_table_LOTS($dbh);
5266 6 create_table_REFIDDOC($dbh);
5267 6 create_table_SUPPORTS($dbh);
5268  
5269 #create_table_DATAGROUPS($dbh);
5270 #create_table_PARA($dbh);
5271  
5272 # CHECK THE PRIMARY KEY AND INDEX PROPOSALS (BE CAREFUL NOT TO DO ANYTHING DAFT)
5273 6 create_table_OUTMNGR( $dbh, $cfg->{'EDTK_DBI_OUTMNGR'} );
5274 6 create_table_OUTMNGR( $dbh, $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
5275 6 create_table_DISTRIB( $dbh, $cfg->{'EDTK_DBI_DISTRIB'} );
5276 6 create_table_DISTRIB( $dbh, $cfg->{'EDTK_DBI_DISTRIB_STATS'} );
5277  
5278 # Optional extension schema (oEUser::Schema, D19): absent -> nothing extra.
5279 6 _schema_create_extra($dbh);
5280  
5281 6 db_invalidate_meta_cache();
5282 }
5283  
5284 0 ▶sub _db_with_lock {
Subroutine _db_with_lock: not called CC=4 SCAR=30.0
5285 0 my (%p) = @_; # CFG, CODE-REF
5286 0 my $dbh = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5287 0 my $date = strftime( "%Y-%m-%d", localtime );
5288 0 my $pid = $$;
5289  
5290 # Try to insert the lock
5291 0 eval {
5292 0 local $dbh->{PrintError} = 0;
5293 0 $dbh->do(
5294 'insert into edtk_admin (ed_action_date,ed_action_pid,ed_action_status,ed_oedtk_release) values (?,?,?,?)',
5295 undef, $date, $pid, 'START', $VERSION
5296 );
5297 };
5298 0 ▶ if ($@) { # conflict, another process already holds it
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
5299 0 $dbh->disconnect;
5300 0 return 0;
5301 }
5302  
5303 # Check that it is really us
5304 0 my ($got_pid) =
5305 $dbh->selectrow_array( 'select ed_action_pid from edtk_admin where ed_action_date = ?',
5306 undef, $date );
5307 0 ▶ unless ( $got_pid == $pid ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($got_pid == $pid) 0 0 0
5308 0 $dbh->disconnect;
5309 0 return 0;
5310 }
5311  
5312 # Run the body
5313 0 eval { $p{code}->($dbh) };
5314 0 my $err = $@;
5315  
5316 # Mark the end
5317 0 my $duration = _elapsed_seconds($^T);
5318 0 $dbh->do(
5319 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?',
5320 undef, 'DONE', $duration, $date
5321 );
5322 0 $dbh->disconnect;
5323  
5324 0 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
5325 0 return 1;
5326 }
5327  
5328 468 ▶sub _db_check_driver_name {
Subroutine _db_check_driver_name: called CC=7 SCAR=19.5
5329 468 my ($dbh) = shift;
5330  
5331 # Guard against an invalid or disconnected $dbh
5332 468 ▶ return "NC" unless defined $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbh 1 467 468
5333 467 my $driver_name = eval { $dbh->{'Driver'}->{'Name'} };
5334 467 ▶ return "NC" unless defined $driver_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $driver_name 0 467 467
5335  
5336 467 ▶ if ( $driver_name =~ m/SQLite/i ) { return "SQLite"; }
Branch: 4 branches
BranchTrueFalseTotal
if ($driver_name =~ /SQLite/i) { } 446 21 467
elsif ($driver_name =~ /Oracle/i) { } 4 17 21
elsif ($driver_name =~ /Pg/i) { } 8 9 17
elsif ($driver_name =~ /(?:mysql|maria)/i) { } 7 2 9
5337 4 elsif ( $driver_name =~ m/Oracle/i ) { return "Oracle"; }
5338 8 elsif ( $driver_name =~ m/Pg/i ) { return "PostgreSQL"; }
5339 7 elsif ( $driver_name =~ m/(?:mysql|maria)/i ) { return "mysql"; }
5340 2 else { return "NC"; }
5341 }
5342  
5343 # Returns the MySQL storage-engine clause appended to CREATE TABLE statements.
5344 # The engine is configurable through EDTK_DB_STORAGE_ENGINE (default: MyISAM,
5345 # kept for its bulk-load performance). Empty string for non-MySQL drivers.
5346 80 ▶sub _db_engine_clause {
Subroutine _db_engine_clause: called CC=5 SCAR=28.8
5347 80 my ($dbh) = @_;
5348 80 ▶ return '' unless _db_check_driver_name($dbh) eq 'mysql';
Branch: 1 branch
BranchTrueFalseTotal
unless _db_check_driver_name($dbh) eq "mysql" 80 0 80
5349 0 ▶ unless ( defined $_DB_ENGINE_CACHE ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $_DB_ENGINE_CACHE) 0 0 0
5350 0 ▶ my $cfg = eval { config_read('EDTK_DB') } || {};
Condition0%0/2
eval { do { config_read('EDTK_DB') } } || {}
l!l
00
MC/DC0%0/1
eval { do { config_read('EDTK_DB') } } || {}
eval { do { config_read('EDTK_DB') } }
Truth table0%0/2
A
A= eval { do { config_read('EDTK_DB') } }
Aresult
11
00
5351 0 ▶ $_DB_ENGINE_CACHE = $cfg->{'EDTK_DB_STORAGE_ENGINE'} || 'MyISAM';
Condition0%0/2
$cfg->{'EDTK_DB_STORAGE_ENGINE'} || 'MyISAM'
l!l
00
MC/DC0%0/1
$cfg->{'EDTK_DB_STORAGE_ENGINE'} || 'MyISAM'
$cfg->{'EDTK_DB_STORAGE_ENGINE'}
Truth table0%0/2
A
A= $cfg->{'EDTK_DB_STORAGE_ENGINE'}
Aresult
11
00
5352 }
5353 0 return ' engine=' . $_DB_ENGINE_CACHE . ' ';
5354 }
5355  
5356 # Does an object (table, index or sequence) already exist in the current schema?
5357 # Queries each driver's data dictionary; returns 1/0 (0 for an unknown driver,
5358 # so that the CREATE attempt is still allowed to run).
5359 9 ▶sub _db_object_exists {
Subroutine _db_object_exists: called CC=12 SCAR=42.4
5360 9 my ( $dbh, $kind, $name ) = @_;
5361 9 my $driver = _db_check_driver_name($dbh);
5362 9 ▶ my ( $schema, $obj ) = ( $name =~ /^(\w+)\.(\w+)$/ ) ? ( $1, $2 ) : ( undef, $name );
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /^(\w+)\.(\w+)$/ ? : 0 9 9
5363  
5364 9 ▶ if ( $driver eq 'SQLite' ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($driver eq 'SQLite') { } 9 0 9
elsif ($driver eq 'PostgreSQL') { } 0 0 0
elsif ($driver eq 'mysql') { } 0 0 0
elsif ($driver eq 'Oracle') { } 0 0 0
5365 9 my ($n) = $dbh->selectrow_array( 'select 1 from sqlite_master where type = ? and name = ?',
5366 undef, $kind, $obj );
5367 9 ▶ return $n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 3 6 9
5368 }
5369 elsif ( $driver eq 'PostgreSQL' ) {
5370  
5371 # PostgreSQL folds unquoted identifiers to lower case (EDTK_ACQMGENTECH is
5372 # stored as edtk_acqmgentech), so compare case-insensitively, as the Oracle
5373 # branch does with upper().
5374 0 my ($n) = $dbh->selectrow_array(
5375 'select 1 from pg_class c join pg_namespace n on n.oid = c.relnamespace '
5376 . 'where lower(c.relname) = lower(?) and n.nspname = current_schema()',
5377 undef, $obj
5378 );
5379 0 ▶ return $n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 0 0 0
5380 }
5381 elsif ( $driver eq 'mysql' ) {
5382 0 ▶ if ( $kind eq 'index' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "index") 0 0 0
5383 0 my ($n) = $dbh->selectrow_array(
5384 'select 1 from information_schema.statistics '
5385 . 'where table_schema = database() and index_name = ?',
5386 undef, $obj
5387 );
5388 0 ▶ return $n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 0 0 0
5389 }
5390 0 my ($n) = $dbh->selectrow_array( 'show tables like ?', undef, $obj );
5391 0 ▶ return $n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 0 0 0
5392 }
5393 elsif ( $driver eq 'Oracle' ) {
5394 0 my ($n) = $dbh->selectrow_array( 'select 1 from user_objects where object_name = upper(?)',
5395 undef, $obj );
5396 0 ▶ return $n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 0 0 0
5397 }
5398 0 return 0;
5399 }
5400  
5401 # Extracts the kind ('table'|'index'|'sequence') and name from a CREATE statement.
5402 0 ▶sub _db_parse_create {
Subroutine _db_parse_create: not called CC=4 SCAR=30.0
5403 0 my ($sql) = @_;
5404 0 ▶ return ( 'index', $1 )
Branch: 1 branch
BranchTrueFalseTotal
if $sql =~ /\bcreate\s+(?:unique\s+)?index\s+(?:if\s+not\s+exists\s+)?(\S+)/i 0 0 0
5405 if $sql =~ /\bcreate\s+(?:unique\s+)?index\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
5406 0 ▶ return ( 'table', $1 ) if $sql =~ /\bcreate\s+table\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $sql =~ /\bcreate\s+table\s+(?:if\s+not\s+exists\s+)?(\S+)/i 0 0 0
5407 0 ▶ return ( 'sequence', $1 ) if $sql =~ /\bcreate\s+sequence\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $sql =~ /\bcreate\s+sequence\s+(?:if\s+not\s+exists\s+)?(\S+)/i 0 0 0
5408 0 return;
5409 }
5410  
5411 # Runs a DDL statement through the driver-specific fixup. On drivers that lack
5412 # "CREATE ... IF NOT EXISTS" (Oracle, MySQL) the clause is emulated by checking
5413 # existence first and stripping it. PostgreSQL supports the clause natively, but
5414 # the server then emits a "relation ... already exists, skipping" NOTICE straight
5415 # to STDERR; pre-checking it too turns that notice into a regular Information log
5416 # line and skips the redundant DDL. Returns the underlying do() result.
5417 147 ▶sub _db_do_ddl {
Subroutine _db_do_ddl: called CC=9 SCAR=35.0
5418 147 my ( $dbh, $sql ) = @_;
5419 147 my $driver = _db_check_driver_name($dbh);
5420 147 $sql = _sql_fixup( $dbh, $sql, 'casse' );
5421  
5422 147 ▶ if ( ( $driver eq 'Oracle' || $driver eq 'mysql' || $driver eq 'PostgreSQL' )
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "Oracle" || $driver eq "mysql" || $driver eq "PostgreSQL" and $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is) 0 147 147
Condition33%3/9
$driver eq "Oracle" || $driver eq "mysql" || $driver eq "PostgreSQL" and $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is
!ll&&!rl&&r
14700
$driver eq "Oracle" or $driver eq "mysql" or $driver eq "PostgreSQL"
l!l&&r!l&&!r
00147
$driver eq "Oracle" or $driver eq "mysql"
l!l&&r!l&&!r
00147
MC/DC0%0/4
$driver eq "Oracle" || $driver eq "mysql" || $driver eq "PostgreSQL" and $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is
$driver eq "Oracle" $driver eq "mysql" $driver eq "PostgreSQL" $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is
Truth table14%1/7
A or B or C and D
A= $driver eq "Oracle"B= $driver eq "mysql"C= $driver eq "PostgreSQL"D= $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
5423 && $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is )
5424 {
5425 0 my ( $kind, $name ) = _db_parse_create($sql);
5426 0 ▶ if ( defined $name && _db_object_exists( $dbh, $kind, $name ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name and _db_object_exists($dbh, $kind, $name)) 0 0 0
Condition0%0/3
defined $name and _db_object_exists($dbh, $kind, $name)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and _db_object_exists($dbh, $kind, $name)
defined $name _db_object_exists($dbh, $kind, $name)
Truth table0%0/3
A and B
A= defined $nameB= _db_object_exists($dbh, $kind, $name)
ABresult
0X0
100
111
5427 0 &logger( 6, "INFO: relation \"$name\" already exists, skipping\n" );
5428 0 return 1;
5429 }
5430 0 ▶ $sql =~ s/\s+if\s+not\s+exists\b//ig
Branch: 1 branch
BranchTrueFalseTotal
if $driver eq "Oracle" or $driver eq "mysql" 0 0 0
Condition0%0/3
$driver eq "Oracle" or $driver eq "mysql"
l!l&&r!l&&!r
000
MC/DC0%0/2
$driver eq "Oracle" or $driver eq "mysql"
$driver eq "Oracle" $driver eq "mysql"
Truth table0%0/3
A or B
A= $driver eq "Oracle"B= $driver eq "mysql"
ABresult
1X1
011
000
5431 if $driver eq 'Oracle' || $driver eq 'mysql';
5432 }
5433 147 return do { local $dbh->{PrintError} = 0; $dbh->do($sql) };
5434 }
5435  
5436 # Per-engine table-maintenance command templates, as (repair, optimize) hash refs
5437 # keyed by _db_check_driver_name() class. A template without %s is a portable no-op
5438 # ("select 1"), so an engine that has no such command still runs harmlessly. Kept in
5439 # one place so every engine's coverage is declared and unit-testable.
5440 9 ▶sub _db_maintenance_commands {
Subroutine _db_maintenance_commands: called CC=1 SCAR=0.0
5441 9 my ($driver) = @_;
5442 9 my %repair = (
5443 NC => "select 1",
5444 mysql => "repair table %s",
5445 Oracle => "select 1 from dual",
5446 PostgreSQL => "select 1",
5447 SQLite => "select 1",
5448 );
5449 9 my %optm = (
5450 NC => "select 1",
5451 mysql => "optimize table %s",
5452 Oracle => "select 1 from dual",
5453  
5454 # VACUUM FULL takes an exclusive lock and rewrites the whole table: it does
5455 # not belong in the routine maintenance path. Plain VACUUM ANALYZE reclaims
5456 # space without blocking writers and refreshes the planner statistics.
5457 PostgreSQL => "vacuum analyze %s",
5458  
5459 # SQLite has no per-table VACUUM; ANALYZE %s refreshes the statistics it uses.
5460 SQLite => "analyze %s",
5461 );
5462 9 return ( \%repair, \%optm );
5463 }
5464  
5465 1 ▶sub admin_optimize_db {
Subroutine admin_optimize_db: called CC=10 SCAR=24.9
Pod documented
5466  
5467 # EXAMPLE CALL:
5468 # admin_optimize_db (CFG => $cfg);
5469  
5470 1 my %p = @_;
5471  
5472 # Single connection for the whole operation (it used to open two per table).
5473 1 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5474  
5475 # Repatriate any pending backup rows before optimizing / repairing.
5476 1 eval { _db_maybe_reconcile( $p{DBH}, $p{CFG} ); };
5477 1 ▶ &logger( 3, "admin_optimize_db: reconciliation failed: $@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
5478  
5479 13 ▶ my @tListeTables = grep { defined $_ && $_ ne '' } (
Condition33%1/3
defined $_ && $_ ne ''
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table33%1/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
5480 "edtk_acq",
5481 "edtk_admin",
5482 "edtk_agrege",
5483 "edtk_filieres",
5484 "edtk_id",
5485 "edtk_lots",
5486 "edtk_refiddoc",
5487 "edtk_supports",
5488  
5489 # "edtk_datagroups",
5490 # "edtk_para",
5491 $p{CFG}->{EDTK_DBI_DISTRIB},
5492 $p{CFG}->{EDTK_DBI_DISTRIB_STATS},
5493 $p{CFG}->{EDTK_DBI_OUTMNGR},
5494 $p{CFG}->{EDTK_DBI_OUTMNGR_STATS},
5495 1 "edtk_tracking"
5496 );
5497  
5498 # Detect the driver once, on the live handle.
5499 1 my $dbName = _db_check_driver_name( $p{DBH} );
5500 1 &logger( 7, "admin_optimize_db: driver=$dbName, " . scalar(@tListeTables) . " tables" );
5501  
5502 # PostgreSQL maintenance can spawn parallel workers that allocate dynamic shared
5503 # memory in /dev/shm; on a small /dev/shm the segment resize aborts with
5504 # "could not resize shared memory segment ... No space left on device". Routine
5505 # per-table maintenance gains nothing from parallelism, so force it serial.
5506 1 ▶ if ( $dbName eq 'PostgreSQL' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbName eq "PostgreSQL") 0 1 1
5507 0 eval { local $p{DBH}->{PrintError} = 0; $p{DBH}->do($_) }
5508 0 for (
5509 'set max_parallel_maintenance_workers = 0',
5510 'set max_parallel_workers_per_gather = 0'
5511 );
5512 }
5513  
5514 1 my ( $hCdeRepair, $hCdeOptm ) = _db_maintenance_commands($dbName);
5515  
5516 1 foreach my $table (@tListeTables) {
5517  
5518 # Repair
5519 13 ▶ my $tpl_repair = $hCdeRepair->{$dbName} // "select 1";
Condition50%1/2
$hCdeRepair->{$dbName} // "select 1"
l!l
130
MC/DC0%0/1
$hCdeRepair->{$dbName} // "select 1"
$hCdeRepair->{$dbName}
Truth table50%1/2
A
A= $hCdeRepair->{$dbName}
Aresult
11
00
5520  
5521 # sprintf only when the template contains %s
5522 13 ▶ my $sql_repair = ( $tpl_repair =~ /\%s/ ) ? sprintf( $tpl_repair, $table ) : $tpl_repair;
Branch: 1 branch
BranchTrueFalseTotal
$tpl_repair =~ /\%s/ ? : 0 13 13
5523 13 &logger( 7, "repair: $sql_repair" );
5524 13 _db_maintenance_run( $p{DBH}, _sql_fixup( $p{DBH}, $sql_repair, 'casse' ),
5525 "repair $table" );
5526  
5527 # Optimize
5528 13 ▶ my $tpl_optm = $hCdeOptm->{$dbName} // "select 1";
Condition50%1/2
$hCdeOptm->{$dbName} // "select 1"
l!l
130
MC/DC0%0/1
$hCdeOptm->{$dbName} // "select 1"
$hCdeOptm->{$dbName}
Truth table50%1/2
A
A= $hCdeOptm->{$dbName}
Aresult
11
00
5529 13 ▶ my $sql_optm = ( $tpl_optm =~ /\%s/ ) ? sprintf( $tpl_optm, $table ) : $tpl_optm;
Branch: 1 branch
BranchTrueFalseTotal
$tpl_optm =~ /\%s/ ? : 13 0 13
5530 13 &logger( 7, "optimize: $sql_optm" );
5531 13 _db_maintenance_run( $p{DBH}, _sql_fixup( $p{DBH}, $sql_optm, 'casse' ),
5532 "optimize $table" );
5533 }
5534 1 $p{DBH}->disconnect;
5535 1 return 1;
5536 }
5537  
5538 # Run one maintenance statement. Catches driver errors so a single table cannot
5539 # abort the whole pass, and reports them as one concise logger line instead of the
5540 # raw DBI/PrintError dump (e.g. a PostgreSQL shared-memory exhaustion). Never dies.
5541 26 ▶sub _db_maintenance_run {
Subroutine _db_maintenance_run: called CC=4 SCAR=17.9
5542 26 my ( $dbh, $sql, $what ) = @_;
5543 26 my $res = do {
5544 26 local $dbh->{PrintError} = 0;
5545 26 local $dbh->{RaiseError} = 0;
5546 26 eval { $dbh->do($sql) };
5547 };
5548 26 ▶ return 1 if defined $res;
Branch: 1 branch
BranchTrueFalseTotal
if defined $res 26 0 26
5549 0 ▶ &logger( 3, "can't $what: " . ( $dbh->errstr // $@ // 'unknown error' ) );
Condition0%0/5
($dbh->errstr // $@) // "unknown error"
l!l
00
$dbh->errstr // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
($dbh->errstr // $@) // "unknown error"
$dbh->errstr $@
Truth table0%0/3
A // B
A= $dbh->errstrB= $@
ABresult
1X1
011
000
5550 0 return 0;
5551 }
5552  
5553 184 ▶sub _sql_fixup {
Subroutine _sql_fixup: called CC=7 SCAR=19.5
5554 184 my ( $dbh, $sql, $mysqlCasse ) = @_;
5555 184 my $driver = $dbh->{'Driver'}->{'Name'};
5556  
5557 # Driver class, so that MariaDB (Driver.Name 'MariaDB') is handled like MySQL.
5558 184 my $class = _db_check_driver_name($dbh);
5559  
5560 # POSTGRESQL specifics
5561 184 ▶ if ( $class eq 'PostgreSQL' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq "PostgreSQL") 2 182 184
5562  
5563 # --- Empty strings '' for non-string types ---
5564 2 ▶ if ( $sql =~ /VALUES\s*\((.*)\)/si ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /VALUES\s*\((.*)\)/is) 1 1 2
5565 1 my $values_part = $1;
5566  
5567 # Replace standalone '' with NULL
5568 1 $values_part =~ s/''(?=\s*,|\s*\))/NULL/g;
5569 1 $sql =~ s/VALUES\s*\(.*\)/VALUES ($values_part)/si;
5570 }
5571  
5572 # Handle the update form "SET column = ''"
5573 2 $sql =~ s/=\s*''(\s*,|\s+WHERE|=)/ = NULL$1/gi;
5574 }
5575  
5576 # Generic logic / other drivers: Oracle keeps VARCHAR2, everyone else gets VARCHAR.
5577 184 ▶ if ( $class ne 'Oracle' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class ne "Oracle") 183 1 184
5578 183 $sql =~ s/VARCHAR2 *(\(\d+\))/VARCHAR$1/gi;
5579 }
5580  
5581 # MySQL forced case (keyed on the real MySQL driver only; MariaDB is left untouched).
5582 184 ▶ if ( $driver eq 'mysql' and $mysqlCasse and $sql !~ /\b(INSERT|REPLACE)\b/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver eq "mysql" and $mysqlCasse and not $sql =~ /\b(INSERT|REPLACE)\b/i) 1 183 184
Condition83%5/6
$driver eq "mysql" and $mysqlCasse and not $sql =~ /\b(INSERT|REPLACE)\b/i
!ll&&!rl&&r
18211
$driver eq "mysql" and $mysqlCasse
!ll&&!rl&&r
18202
MC/DC66%2/3
$driver eq "mysql" and $mysqlCasse and not $sql =~ /\b(INSERT|REPLACE)\b/i
$driver eq "mysql" $mysqlCasse not $sql =~ /\b(INSERT|REPLACE)\b/i
Truth table75%3/4
A and B and not(C)
A= $driver eq "mysql"B= $mysqlCasseC= not $sql =~ /\b(INSERT|REPLACE)\b/i
ABCresult
0XX0
10X0
1100
1111
5583 1 $sql = uc($sql);
5584 }
5585  
5586 184 return $sql;
5587 }
5588  
5589 3 ▶sub db_backup_agent {
Subroutine db_backup_agent: called CC=12 SCAR=27.1
Pod documented
5590  
5591 # Archives the 3 production tables (EDTK_DBI_TRACKING / OUTMNGR / ACQUIT) into a
5592 # date-stamped snapshot, then purges the rows older than EDTK_ENTIRE_YEARS_KEPT.
5593 # The snapshot copies the whole table (not just the old rows), so a re-run on the
5594 # same day must not overwrite it with the now-smaller source: the existing archive
5595 # is kept as is. Called from Outmngr::omgr_purge_fs.
5596 3 my ( $dbh, $cfg ) = @_;
5597 3 ▶ $cfg ||= config_read('EDTK_DB');
Condition33%1/3
$cfg ||= config_read("EDTK_DB")
l!l&&r!l&&!r
300
MC/DC0%0/2
$cfg ||= config_read("EDTK_DB")
$cfg config_read("EDTK_DB")
Truth table33%1/3
A ||= B
A= $cfgB= config_read("EDTK_DB")
ABresult
1X1
011
000
5598 3 ▶ unless ( defined( $cfg->{'EDTK_ENTIRE_YEARS_KEPT'} ) && $cfg->{'EDTK_ENTIRE_YEARS_KEPT'} > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} and $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} > 0) 1 2 3
Condition66%2/3
defined $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} and $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} > 0
!ll&&!rl&&r
102
MC/DC50%1/2
defined $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} and $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} > 0
defined $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} > 0
Truth table66%2/3
A and B
A= defined $cfg->{"EDTK_ENTIRE_YEARS_KEPT"}B= $cfg->{"EDTK_ENTIRE_YEARS_KEPT"} > 0
ABresult
0X0
100
111
5599 1 &logger( 6,
5600 "EDTK_ENTIRE_YEARS_KEPT not defined for optimization purge. db_backup_agent not needed."
5601 );
5602 1 return 1;
5603 }
5604  
5605 2 my $suffixe = strftime( "%Y%m%d", localtime ) . "_BAK";
5606 2 my $cur_year = strftime( "%Y", localtime );
5607 2 my $kept_year = $cur_year - $cfg->{'EDTK_ENTIRE_YEARS_KEPT'};
5608  
5609 # (table, date column, purge threshold) of the tables to archive and purge.
5610 my @plan = (
5611 [ $cfg->{'EDTK_DBI_TRACKING'}, 'ed_tstamp', $kept_year . "0101000000" ],
5612 [ $cfg->{'EDTK_DBI_OUTMNGR'}, 'ed_dtedtion', $kept_year . "0101" ],
5613 2 [ $cfg->{'EDTK_DBI_ACQUIT'}, 'ed_dtpost', $kept_year . "0101" ],
5614 );
5615  
5616 2 foreach my $spec (@plan) {
5617 6 my ( $table, $datecol, $check ) = @$spec;
5618 6 ▶ next unless defined $table && $table ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and $table ne "" 0 6 6
Condition33%1/3
defined $table and $table ne ""
!ll&&!rl&&r
006
MC/DC0%0/2
defined $table and $table ne ""
defined $table $table ne ""
Truth table33%1/3
A and B
A= defined $tableB= $table ne ""
ABresult
0X0
100
111
5619  
5620 6 my $sql_check = "select count($datecol) from $table where $datecol < ? ";
5621 6 my $sth = $dbh->prepare($sql_check);
5622 6 ▶ do { local $sth->{PrintError} = 0; $sth->execute($check) }
Branch: 1 branch
BranchTrueFalseTotal
do { local $sth->{"PrintError"} = 0; $sth->execute($check) } or &logger(3, 'SQL execute failed ' . $sth->err . '-' . $sth->errstr) 6 0 6
5623 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
5624 6 my ($result) = $sth->fetchrow_array;
5625 6 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 3 3 6
5626 3 &logger( 5, "db_backup_agent has nothing to do with $table" );
5627 3 next;
5628 }
5629  
5630 3 my $cible = $table . "_" . $suffixe;
5631  
5632 # MySQL stores the archive under its uppercase name (copy_table DDL is uppercased).
5633 3 ▶ my $exists = _db_object_exists( $dbh, 'table', $cible )
Condition33%1/3
_db_object_exists($dbh, 'table', $cible) || _db_object_exists($dbh, 'table', uc $cible)
l!l&&r!l&&!r
003
MC/DC0%0/2
_db_object_exists($dbh, 'table', $cible) || _db_object_exists($dbh, 'table', uc $cible)
_db_object_exists($dbh, 'table', $cible) _db_object_exists($dbh, 'table', uc $cible)
Truth table33%1/3
A || B
A= _db_object_exists($dbh, 'table', $cible)B= _db_object_exists($dbh, 'table', uc $cible)
ABresult
1X1
011
000
5634 || _db_object_exists( $dbh, 'table', uc $cible );
5635 3 ▶ if ($exists) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exists) { } 0 3 3
5636 0 &logger( 6, "db_backup_agent: archive $cible already exists for today, keeping it" );
5637  
5638 # H13: a row older than the threshold may have arrived since the archive was
5639 # made. Archive the rows we are about to purge, so none is deleted without
5640 # first being saved (the same-day re-run used to purge them unarchived).
5641 0 ▶ my $arch = ( _db_check_driver_name($dbh) eq 'mysql' ) ? uc $cible : $cible;
Branch: 1 branch
BranchTrueFalseTotal
_db_check_driver_name($dbh) eq 'mysql' ? : 0 0 0
5642 0 my $sql_a = "insert into $arch select * from $table where $datecol < ?";
5643 0 _db_do_log(
5644 $dbh, _sql_fixup( $dbh, $sql_a, 'casse' ),
5645 "ERROR: can't archive into $cible",
5646 bind => [$check],
5647 fatal => 1
5648 );
5649 }
5650 else {
5651 3 copy_table( $dbh, $table, $cible, '-create' );
5652 3 &logger( 5, "db_backup_agent archived $table into $cible" );
5653 }
5654  
5655 3 my $sql_clean = "delete from $table where $datecol < ? ";
5656 3 _db_do_log(
5657 $dbh, $sql_clean, "ERROR: can't delete from $table",
5658 bind => [$check],
5659 fatal => 1
5660 );
5661  
5662 3 &logger( 6, "db_backup_agent DONE with $table for data older than $check." );
5663 }
5664  
5665 2 return 1;
5666 }
5667  
5668 32 1;
5669  
5670 =head1 NAME
5671  
5672 oEdtk::DBAdmin - oEdtk database administration, schema upkeep and bulk CSV loading
5673  
5674 =head1 SYNOPSIS
5675  
5676 use oEdtk::DBAdmin qw(db_connect schema_Create csv_import);
5677  
5678 my $dbh = db_connect( $cfg, 'EDTK_DBI_DSN' );
5679 schema_Create($dbh); # build the whole schema
5680 csv_import( $dbh, $table, $file, ref_col => 'id' );
5681  
5682 =head1 DESCRIPTION
5683  
5684 oEdtk::DBAdmin creates, detects, upgrades and maintains the oEdtk database and
5685 loads CSV data into it, across PostgreSQL, MySQL / MariaDB, Oracle and SQLite.
5686 The hardening work of the DBAdmin chantier (see F<docs/dbadmin/>) added the
5687 tuning keys and the schema-detection / staleness helpers documented below. The
5688 public entry points are grouped by area; the private helpers are not listed.
5689  
5690 =head1 CONNECTION
5691  
5692 =head2 db_connect( $cfg, $key )
5693  
5694 Connect to the database named by the configuration key I<$key> (for example
5695 C<EDTK_DBI_DSN>), applying the per-driver normalisation the module expects.
5696  
5697 =head2 db_check_privileges( $dbh, %opt )
5698  
5699 Read-only probe of the privileges the account holds (CREATE, DROP, INDEX, ALTER,
5700 SEQUENCE); never blocking. Returns a hash with the granted set, the missing one
5701 and an optional error. Option C<table> targets the ownership checks (PostgreSQL).
5702  
5703 =head2 db_invalidate_meta_cache
5704  
5705 Drop the column-metadata cache used by C<csv_import>. Call it after a schema
5706 change (C<schema_Create> / C<schema_Upgrade>) so the next import re-reads the
5707 columns instead of reusing a stale description.
5708  
5709 =head1 SCHEMA
5710  
5711 =head2 schema_Create( $dbh )
5712  
5713 Create the whole T schema: the base tables, the configuration-driven tables and
5714 the tracking table.
5715  
5716 =head2 schema_Upgrade( $dbh, %opt )
5717  
5718 Bring an existing base up to the current schema (delegates to the historisation
5719 path, see C<schema_Historize>).
5720  
5721 =head2 schema_Detect( $dbh, %opt )
5722  
5723 Inspect a live base and report its detected level against the T definitions.
5724 Option C<index_table> names the index table (defaults to C<EDTK_DBI_OUTMNGR>).
5725 READ-ONLY: every statement is a SELECT / PRAGMA; nothing is written.
5726  
5727 =head2 schema_Report( $dbh, %opt )
5728  
5729 The C<schema_Detect> result as printable text.
5730  
5731 =head2 schema_Manifest( ... )
5732  
5733 The ordered, de-duplicated list of tables the migration covers: the fixed base
5734 tables, the configuration-driven ones, the tracking table and any extension
5735 table.
5736  
5737 =head2 schema_MigrationPlan( $dbh, %opt )
5738  
5739 Read-only plan of an update by historisation (C<--check-only> / C<--dry-run>):
5740 the detected level, the per-table column sets and the copy SQL. Writes nothing.
5741  
5742 =head2 schema_Historize( $dbh, %opt )
5743  
5744 Perform the update by historisation. Options: C<stamp>, C<manifest>,
5745 C<checkpoint> (a code ref called after each table's copy; a die aborts and rolls
5746 back), C<keep_old> (default 1, the stamped tables are kept) and C<force>. An
5747 already-T base is a no-op (result field C<noop>). Returns a result hash.
5748  
5749 =head2 schema_Revert( $dbh, %opt )
5750  
5751 Invert a historisation before resuming the service: put the stamped tables back
5752 under their original names, dropping the current target. Option C<stamp>
5753 (required) is the one the migration used.
5754  
5755 =head2 schema_AdditivePlan( $dbh, %opt )
5756  
5757 Read-only preview of the in-place additive update: what C<schema_Additive> would
5758 add, widen, create or change. Option C<with_constraints> (0|1). Writes nothing
5759 (every statement is a SELECT / PRAGMA). Returns a plan hash: C<ok>, C<level>,
5760 C<driver>, C<detect>, C<create>, C<add>, C<widen>, C<key>, C<add_sql>, C<widen_sql>,
5761 C<key_sql>, C<violations> and C<report>. When C<with_constraints> asks for a key
5762 change on a driver that cannot perform it in place (SQLite, NC), the plan reports
5763 it as a violation instead of rendering DDL that the update would refuse.
5764  
5765 =head2 schema_Additive( $dbh, %opt )
5766  
5767 Perform the in-place additive update. Options: C<manifest>, C<with_constraints>
5768 (0|1), C<checkpoint> and C<force>. A base that already conforms to T with
5769 nothing to add or widen is a no-op (result field C<noop>). Returns a result hash:
5770 C<created>, C<added>, C<widened>, C<key_changed>, C<violations> and C<error>.
5771  
5772 =head2 schema_StaleWarning( $dbh, %opt )
5773  
5774 Report a stale schema ONCE, READ-ONLY, never fatal. Options: C<cfg>,
5775 C<index_table>, C<tracking_table> (all default to the EDTK_DB configuration).
5776 Returns the probe when a warning was emitted, undef otherwise. It never writes.
5777  
5778 =head2 schema_History_add( $dbh, %named )
5779  
5780 Append one history row: C<date>, C<from>, C<to>, C<mode>, C<tool> and C<counts>
5781 (a hash ref, stored as a compact "k=v;k=v" string).
5782  
5783 =head2 historicize_table( $dbh, %opt )
5784  
5785 Historise one table (used by the migration).
5786  
5787 =head2 create_SCHEMA( $dbh, $table, $maxkeys )
5788  
5789 Legacy entry point kept for the fork: it creates the whole schema (the canonical
5790 C<schema_Create>) plus the TRACKING table the fork also created.
5791  
5792 =head2 create_lot_sequence( $dbh )
5793  
5794 Create the lot-sequence counter table (needed by SQLite, which has no SEQUENCE).
5795  
5796 =head2 create_table_TRACKING / OUTMNGR / DISTRIB / ACQUIT / ACQMGENTECH / ... ( $dbh, ... )
5797  
5798 Create one table of the schema: TRACKING, OUTMNGR, DISTRIB, ACQUIT, ACQMGENTECH,
5799 SCHEMA_HISTORY, ADMIN, AGREGE, DATAGROUPS, FILIERES, ID, INDEX, LOTS, PARA,
5800 REFIDDOC, SUPPORTS. C<create_table_INDEX> is a fork alias of
5801 C<create_table_OUTMNGR>; C<create_table_ACQMGENTECH> targets the optional oEUser
5802 extension and is a silent no-op when it is not installed.
5803  
5804 =head1 LOADING DATA
5805  
5806 =head2 csv_import( $dbh, $table, $file, %opt )
5807  
5808 Import a CSV file into a table (the historic row-by-row API, unchanged). The
5809 keys and parameters that tune the PostgreSQL bulk path are below.
5810  
5811 =head2 insert_tData( $dbh, %opt )
5812  
5813 Insert one row (used by the C<csv_import> row-by-row path).
5814  
5815 =head1 BULK LOAD TUNING (PostgreSQL)
5816  
5817 =head2 EDTK_DB_BURST_MO
5818  
5819 Above this size, in MiB, a PostgreSQL insert switches to the ELT staging path:
5820 the file is copied raw into an unconstrained TEMP table and moved with a single
5821 INSERT ... SELECT, skipping the per-row Perl parse. 0 disables the path; the
5822 shipped default is 50 MiB. The caller parameter C<burst_mo> overrides it,
5823 C<pg_copy_staging> (0 or 1) forces either path regardless of size, and
5824 C<force_copy> (true) forces the parsed COPY path ahead of every other setting
5825 (the packaged tracker exposes it as C<--forceCopy>).
5826  
5827 The ELT path additionally requires an explicit source encoding
5828 (C<pg_copy_encoding> or C<EDTK_DB_COPY_ENCODING>). Without it the load logs
5829 C<_load_csv_pg_copy: ELT unavailable (ELT needs an explicit source encoding)>
5830 and falls back to the parsed COPY path.
5831  
5832 =head2 EDTK_DB_COPY_ENCODING
5833  
5834 Source encoding of the CSV bytes, declared to the PostgreSQL COPY. It is
5835 required to enable the ELT path: an explicit value (the caller parameter
5836 C<pg_copy_encoding>, else this key) makes the ELT declare C<ENCODING '<name>'>.
5837 When unset, the parsed COPY path keeps its historical per-field heuristic and
5838 the ELT is unavailable (it falls back to parsed COPY as described above). The
5839 name must match the file's real encoding; an unknown value is rejected with a
5840 message instead of being passed silently.
5841  
5842 =head2 EDTK_DB_DEFER_INDEX_RATIO, EDTK_DB_DEFER_INDEX_MIN_ROWS
5843  
5844 A PostgreSQL bulk insert drops the secondary indexes up-front and rebuilds them
5845 afterwards only when the incoming row count is at least
5846 C<EDTK_DB_DEFER_INDEX_RATIO> times the table's estimated row count (default
5847 0.1) and at least C<EDTK_DB_DEFER_INDEX_MIN_ROWS> rows (default 10000). The
5848 caller parameters C<pg_defer_index_ratio> and C<pg_defer_index_min_rows> take
5849 precedence.
5850  
5851 =head1 MAINTENANCE
5852  
5853 =head2 acheck_db_admin( %opt )
5854  
5855 The daily "first process of the day" maintenance, driven by the edtk_admin day
5856 row.
5857  
5858 =head2 acheck_db_admin_on_connect( $dbh, $cfg )
5859  
5860 Claim the day lock on connect and run the maintenance once per day.
5861  
5862 =head2 admin_optimize_db( $dbh, %opt )
5863  
5864 Dispatch a per-engine REPAIR / OPTIMIZE (VACUUM ANALYZE on PostgreSQL) over the
5865 maintenance tables, on a single connection.
5866  
5867 =head2 agrege_idJob( %opt )
5868  
5869 Aggregate one job's distribution rows.
5870  
5871 =head2 copy_table / move_table / db_drop_table ( $dbh, $table, $target, %opt )
5872  
5873 Copy a table, move it (copy then drop) or drop it.
5874  
5875 =head2 get_columns_names( $dbh, $table )
5876  
5877 Read the driver-neutral column catalogue; the names keep the catalogue's case.
5878  
5879 =head1 BACKUP BUFFER
5880  
5881 =head2 db_backup_available( $dbh ) / db_on_backup( $dbh )
5882  
5883 Whether a distinct backup database is configured, and whether this handle points
5884 at the backup buffer.
5885  
5886 =head2 db_backup_pending( $dbh )
5887  
5888 Count the pending rows per buffer table (read-only).
5889  
5890 =head2 db_backup_prepare( $dbh )
5891  
5892 Guarantee the backup buffer can hold the event tables.
5893  
5894 =head2 db_backup_agent( %opt )
5895  
5896 Archive the event tables into the buffer, then purge them (the daily backup job).
5897 It is not deprecated: it archives three tables and then purges.
5898  
5899 =head2 db_reconcile_backup( %opt )
5900  
5901 Copy every pending row of the backup buffer back into the main database. Never
5902 dies; returns a report hashref. Options: C<CFG>, C<tables>, C<dry_run>,
5903 C<keep_backup>.
5904  
5905 =head1 EXPORTED VARIABLES
5906  
5907 =head2 @INDEX_COLS / @TRACKER_COLS
5908  
5909 The ordered C<[ name, ddl-type ]> lists of the index table's and the tracking
5910 table's columns.
5911  
5912 =head1 SEE ALSO
5913  
5914 F<docs/dbadmin/>, F<dbadmin_optim.md>,
5915 F<PLAN-DBAdmin-optimisation-durcissement.md>.
5916  
5917 =head1 AUTHOR
5918  
5919 The oEdtk team.
5920  
5921 =cut
« blib/lib/oEdtk/Tracking2.pm ↑ Summary blib/lib/oEdtk/logger2.pm »